repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
196
func_name
stringlengths
7
107
whole_func_string
stringlengths
76
3.82k
language
stringclasses
1 value
func_code_string
stringlengths
76
3.82k
func_code_tokens
listlengths
22
717
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
508
split_name
stringclasses
1 value
func_code_url
stringlengths
111
310
javalite/activejdbc
javalite-common/src/main/java/org/javalite/common/JsonHelper.java
JsonHelper.toJsonString
public static String toJsonString(Object val, boolean pretty) { try { return pretty ? mapper.writerWithDefaultPrettyPrinter().with(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS).writeValueAsString(val) : mapper.writeValueAsString(val); } catch (Exception e) { throw new RuntimeException(e); } }
java
public static String toJsonString(Object val, boolean pretty) { try { return pretty ? mapper.writerWithDefaultPrettyPrinter().with(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS).writeValueAsString(val) : mapper.writeValueAsString(val); } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "static", "String", "toJsonString", "(", "Object", "val", ",", "boolean", "pretty", ")", "{", "try", "{", "return", "pretty", "?", "mapper", ".", "writerWithDefaultPrettyPrinter", "(", ")", ".", "with", "(", "SerializationFeature", ".", "ORDER_MAP_ENTR...
Convert Java object to a JSON string. @param val Java object @param pretty enable/disable pretty print @return JSON string.
[ "Convert", "Java", "object", "to", "a", "JSON", "string", "." ]
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/javalite-common/src/main/java/org/javalite/common/JsonHelper.java#L88-L94
actorapp/actor-platform
actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/util/images/ops/ImageLoading.java
ImageLoading.loadBitmapOptimized
private static Bitmap loadBitmapOptimized(ImageSource source, int limit) throws ImageLoadException { int scale = getScaleFactor(source.getImageMetadata(), limit); return loadBitmap(source, scale); }
java
private static Bitmap loadBitmapOptimized(ImageSource source, int limit) throws ImageLoadException { int scale = getScaleFactor(source.getImageMetadata(), limit); return loadBitmap(source, scale); }
[ "private", "static", "Bitmap", "loadBitmapOptimized", "(", "ImageSource", "source", ",", "int", "limit", ")", "throws", "ImageLoadException", "{", "int", "scale", "=", "getScaleFactor", "(", "source", ".", "getImageMetadata", "(", ")", ",", "limit", ")", ";", ...
Loading bitmap from ImageSource with limit of amout of pixels @param source image source @param limit maximum pixels size @return loaded bitmap @throws ImageLoadException if it is unable to load image
[ "Loading", "bitmap", "from", "ImageSource", "with", "limit", "of", "amout", "of", "pixels" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/util/images/ops/ImageLoading.java#L384-L387
vanilladb/vanillacore
src/main/java/org/vanilladb/core/storage/buffer/Buffer.java
Buffer.setVal
public void setVal(int offset, Constant val, long txNum, LogSeqNum lsn) { internalLock.writeLock().lock(); try { modifiedBy.add(txNum); if (lsn != null && lsn.compareTo(lastLsn) > 0) lastLsn = lsn; // Put the last LSN in front of the data lastLsn.writeToPage(contents, LAST_LSN_OFFSET); contents.setVal(DATA_START_OFFSET + offset, val); } finally { internalLock.writeLock().unlock(); } }
java
public void setVal(int offset, Constant val, long txNum, LogSeqNum lsn) { internalLock.writeLock().lock(); try { modifiedBy.add(txNum); if (lsn != null && lsn.compareTo(lastLsn) > 0) lastLsn = lsn; // Put the last LSN in front of the data lastLsn.writeToPage(contents, LAST_LSN_OFFSET); contents.setVal(DATA_START_OFFSET + offset, val); } finally { internalLock.writeLock().unlock(); } }
[ "public", "void", "setVal", "(", "int", "offset", ",", "Constant", "val", ",", "long", "txNum", ",", "LogSeqNum", "lsn", ")", "{", "internalLock", ".", "writeLock", "(", ")", ".", "lock", "(", ")", ";", "try", "{", "modifiedBy", ".", "add", "(", "txN...
Writes a value to the specified offset of this buffer's page. This method assumes that the transaction has already written an appropriate log record. The buffer saves the id of the transaction and the LSN of the log record. A negative lsn value indicates that a log record was not necessary. @param offset the byte offset within the page @param val the new value to be written @param txNum the id of the transaction performing the modification @param lsn the LSN of the corresponding log record
[ "Writes", "a", "value", "to", "the", "specified", "offset", "of", "this", "buffer", "s", "page", ".", "This", "method", "assumes", "that", "the", "transaction", "has", "already", "written", "an", "appropriate", "log", "record", ".", "The", "buffer", "saves",...
train
https://github.com/vanilladb/vanillacore/blob/d9a34e876b1b83226036d1fa982a614bbef59bd1/src/main/java/org/vanilladb/core/storage/buffer/Buffer.java#L121-L134
attribyte/wpdb
src/main/java/org/attribyte/wp/db/DB.java
DB.selectPostMetaValue
public Meta selectPostMetaValue(final long postId, final String metaKey) throws SQLException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; Timer.Context ctx = metrics.selectPostMetaTimer.time(); try { conn = connectionSupplier.getConnection(); stmt = conn.prepareStatement(selectPostMetaValueSQL); stmt.setLong(1, postId); stmt.setString(2, metaKey); rs = stmt.executeQuery(); return rs.next() ? new Meta(rs.getLong(1), rs.getString(2), rs.getString(3)) : null; } finally { ctx.stop(); SQLUtil.closeQuietly(conn, stmt, rs); } }
java
public Meta selectPostMetaValue(final long postId, final String metaKey) throws SQLException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; Timer.Context ctx = metrics.selectPostMetaTimer.time(); try { conn = connectionSupplier.getConnection(); stmt = conn.prepareStatement(selectPostMetaValueSQL); stmt.setLong(1, postId); stmt.setString(2, metaKey); rs = stmt.executeQuery(); return rs.next() ? new Meta(rs.getLong(1), rs.getString(2), rs.getString(3)) : null; } finally { ctx.stop(); SQLUtil.closeQuietly(conn, stmt, rs); } }
[ "public", "Meta", "selectPostMetaValue", "(", "final", "long", "postId", ",", "final", "String", "metaKey", ")", "throws", "SQLException", "{", "Connection", "conn", "=", "null", ";", "PreparedStatement", "stmt", "=", "null", ";", "ResultSet", "rs", "=", "null...
Selects a single post meta value. @param postId The post id. @param metaKey The key. @return The meta value or {@code null} if none. @throws SQLException on database error.
[ "Selects", "a", "single", "post", "meta", "value", "." ]
train
https://github.com/attribyte/wpdb/blob/b9adf6131dfb67899ebff770c9bfeb001cc42f30/src/main/java/org/attribyte/wp/db/DB.java#L1918-L1935
jbundle/jbundle
base/db/jdbc/src/main/java/org/jbundle/base/db/jdbc/JdbcTable.java
JdbcTable.checkNullableKey
public void checkNullableKey(BaseField field, boolean bFirstFieldOnly) { for (int iKeySeq = 0; iKeySeq < this.getRecord().getKeyAreaCount(); iKeySeq++) { KeyArea keyArea = this.getRecord().getKeyArea(iKeySeq); for (int iKeyFieldSeq = 0; iKeyFieldSeq < keyArea.getKeyFields(); iKeyFieldSeq++) { if (keyArea.getField(iKeyFieldSeq) == field) { if (field.isNullable() == true) { // Don't allow this key to be null field.setNullable(false); return; } } if (bFirstFieldOnly) break; } } }
java
public void checkNullableKey(BaseField field, boolean bFirstFieldOnly) { for (int iKeySeq = 0; iKeySeq < this.getRecord().getKeyAreaCount(); iKeySeq++) { KeyArea keyArea = this.getRecord().getKeyArea(iKeySeq); for (int iKeyFieldSeq = 0; iKeyFieldSeq < keyArea.getKeyFields(); iKeyFieldSeq++) { if (keyArea.getField(iKeyFieldSeq) == field) { if (field.isNullable() == true) { // Don't allow this key to be null field.setNullable(false); return; } } if (bFirstFieldOnly) break; } } }
[ "public", "void", "checkNullableKey", "(", "BaseField", "field", ",", "boolean", "bFirstFieldOnly", ")", "{", "for", "(", "int", "iKeySeq", "=", "0", ";", "iKeySeq", "<", "this", ".", "getRecord", "(", ")", ".", "getKeyAreaCount", "(", ")", ";", "iKeySeq",...
This is a special method - If the db doesn't allow null keys, you must make sure they are not nullable. <br />This is used on create. @param field Field to check, if it is in a key and is nullable, set to not nullable.
[ "This", "is", "a", "special", "method", "-", "If", "the", "db", "doesn", "t", "allow", "null", "keys", "you", "must", "make", "sure", "they", "are", "not", "nullable", ".", "<br", "/", ">", "This", "is", "used", "on", "create", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/db/jdbc/src/main/java/org/jbundle/base/db/jdbc/JdbcTable.java#L1349-L1368
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/Factory.java
Factory.addFeatures
private static void addFeatures(Featurable featurable, Services services, Setup setup) { final List<Feature> rawFeatures = FeaturableConfig.getFeatures(services, setup); final int length = rawFeatures.size(); for (int i = 0; i < length; i++) { final Feature feature = rawFeatures.get(i); featurable.addFeature(feature); } featurable.addAfter(services, setup); }
java
private static void addFeatures(Featurable featurable, Services services, Setup setup) { final List<Feature> rawFeatures = FeaturableConfig.getFeatures(services, setup); final int length = rawFeatures.size(); for (int i = 0; i < length; i++) { final Feature feature = rawFeatures.get(i); featurable.addFeature(feature); } featurable.addAfter(services, setup); }
[ "private", "static", "void", "addFeatures", "(", "Featurable", "featurable", ",", "Services", "services", ",", "Setup", "setup", ")", "{", "final", "List", "<", "Feature", ">", "rawFeatures", "=", "FeaturableConfig", ".", "getFeatures", "(", "services", ",", "...
Add all features declared in configuration. @param featurable The featurable to handle. @param services The services reference. @param setup The setup reference.
[ "Add", "all", "features", "declared", "in", "configuration", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/Factory.java#L72-L82
dain/leveldb
leveldb/src/main/java/org/iq80/leveldb/util/Slice.java
Slice.setBytes
public void setBytes(int index, ByteBuffer source) { checkPositionIndexes(index, index + source.remaining(), this.length); index += offset; source.get(data, index, source.remaining()); }
java
public void setBytes(int index, ByteBuffer source) { checkPositionIndexes(index, index + source.remaining(), this.length); index += offset; source.get(data, index, source.remaining()); }
[ "public", "void", "setBytes", "(", "int", "index", ",", "ByteBuffer", "source", ")", "{", "checkPositionIndexes", "(", "index", ",", "index", "+", "source", ".", "remaining", "(", ")", ",", "this", ".", "length", ")", ";", "index", "+=", "offset", ";", ...
Transfers the specified source buffer's data to this buffer starting at the specified absolute {@code index} until the source buffer's position reaches its limit. @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or if {@code index + src.remaining()} is greater than {@code this.capacity}
[ "Transfers", "the", "specified", "source", "buffer", "s", "data", "to", "this", "buffer", "starting", "at", "the", "specified", "absolute", "{", "@code", "index", "}", "until", "the", "source", "buffer", "s", "position", "reaches", "its", "limit", "." ]
train
https://github.com/dain/leveldb/blob/7994065b48eada2ef29e7fefd172c2ad1e0110eb/leveldb/src/main/java/org/iq80/leveldb/util/Slice.java#L399-L404
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java
CPMeasurementUnitPersistenceImpl.findByG_K_T
@Override public CPMeasurementUnit findByG_K_T(long groupId, String key, int type) throws NoSuchCPMeasurementUnitException { CPMeasurementUnit cpMeasurementUnit = fetchByG_K_T(groupId, key, type); if (cpMeasurementUnit == null) { StringBundler msg = new StringBundler(8); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("groupId="); msg.append(groupId); msg.append(", key="); msg.append(key); msg.append(", type="); msg.append(type); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchCPMeasurementUnitException(msg.toString()); } return cpMeasurementUnit; }
java
@Override public CPMeasurementUnit findByG_K_T(long groupId, String key, int type) throws NoSuchCPMeasurementUnitException { CPMeasurementUnit cpMeasurementUnit = fetchByG_K_T(groupId, key, type); if (cpMeasurementUnit == null) { StringBundler msg = new StringBundler(8); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("groupId="); msg.append(groupId); msg.append(", key="); msg.append(key); msg.append(", type="); msg.append(type); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchCPMeasurementUnitException(msg.toString()); } return cpMeasurementUnit; }
[ "@", "Override", "public", "CPMeasurementUnit", "findByG_K_T", "(", "long", "groupId", ",", "String", "key", ",", "int", "type", ")", "throws", "NoSuchCPMeasurementUnitException", "{", "CPMeasurementUnit", "cpMeasurementUnit", "=", "fetchByG_K_T", "(", "groupId", ",",...
Returns the cp measurement unit where groupId = &#63; and key = &#63; and type = &#63; or throws a {@link NoSuchCPMeasurementUnitException} if it could not be found. @param groupId the group ID @param key the key @param type the type @return the matching cp measurement unit @throws NoSuchCPMeasurementUnitException if a matching cp measurement unit could not be found
[ "Returns", "the", "cp", "measurement", "unit", "where", "groupId", "=", "&#63", ";", "and", "key", "=", "&#63", ";", "and", "type", "=", "&#63", ";", "or", "throws", "a", "{", "@link", "NoSuchCPMeasurementUnitException", "}", "if", "it", "could", "not", ...
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java#L2567-L2596
apiman/apiman
common/net/src/main/java/io/apiman/common/net/hawkular/beans/MetricLongBean.java
MetricLongBean.addDataPoint
public DataPointLongBean addDataPoint(Date timestamp, long value, Map<String, String> tags) { DataPointLongBean point = new DataPointLongBean(timestamp, value); for (Entry<String, String> entry : tags.entrySet()) { point.addTag(entry.getKey(), entry.getValue()); } dataPoints.add(point); return point; }
java
public DataPointLongBean addDataPoint(Date timestamp, long value, Map<String, String> tags) { DataPointLongBean point = new DataPointLongBean(timestamp, value); for (Entry<String, String> entry : tags.entrySet()) { point.addTag(entry.getKey(), entry.getValue()); } dataPoints.add(point); return point; }
[ "public", "DataPointLongBean", "addDataPoint", "(", "Date", "timestamp", ",", "long", "value", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "DataPointLongBean", "point", "=", "new", "DataPointLongBean", "(", "timestamp", ",", "value", ")", ...
Adds a single data point to the metric. @param timestamp @param value @param tags
[ "Adds", "a", "single", "data", "point", "to", "the", "metric", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/net/src/main/java/io/apiman/common/net/hawkular/beans/MetricLongBean.java#L101-L108
joniles/mpxj
src/main/java/net/sf/mpxj/mpx/LocaleData.java
LocaleData.getMap
@SuppressWarnings("rawtypes") public static final Map getMap(Locale locale, String key) { ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale); return ((Map) bundle.getObject(key)); }
java
@SuppressWarnings("rawtypes") public static final Map getMap(Locale locale, String key) { ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale); return ((Map) bundle.getObject(key)); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "public", "static", "final", "Map", "getMap", "(", "Locale", "locale", ",", "String", "key", ")", "{", "ResourceBundle", "bundle", "=", "ResourceBundle", ".", "getBundle", "(", "LocaleData", ".", "class", ".",...
Convenience method for retrieving a Map resource. @param locale locale identifier @param key resource key @return resource value
[ "Convenience", "method", "for", "retrieving", "a", "Map", "resource", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/LocaleData.java#L112-L116
jamesdbloom/mockserver
mockserver-core/src/main/java/org/mockserver/model/HttpRequest.java
HttpRequest.withHeader
public HttpRequest withHeader(String name, String... values) { this.headers.withEntry(header(name, values)); return this; }
java
public HttpRequest withHeader(String name, String... values) { this.headers.withEntry(header(name, values)); return this; }
[ "public", "HttpRequest", "withHeader", "(", "String", "name", ",", "String", "...", "values", ")", "{", "this", ".", "headers", ".", "withEntry", "(", "header", "(", "name", ",", "values", ")", ")", ";", "return", "this", ";", "}" ]
Adds one header to match which can specified using plain strings or regular expressions (for more details of the supported regex syntax see http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html) @param name the header name @param values the header values which can be a varags of strings or regular expressions
[ "Adds", "one", "header", "to", "match", "which", "can", "specified", "using", "plain", "strings", "or", "regular", "expressions", "(", "for", "more", "details", "of", "the", "supported", "regex", "syntax", "see", "http", ":", "//", "docs", ".", "oracle", "...
train
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/model/HttpRequest.java#L411-L414
aoindustries/aocode-public
src/main/java/com/aoindustries/servlet/http/ServletUtil.java
ServletUtil.getResource
@Deprecated public static URL getResource(ServletContext servletContext, String path) throws MalformedURLException { return servletContext.getResource(path); }
java
@Deprecated public static URL getResource(ServletContext servletContext, String path) throws MalformedURLException { return servletContext.getResource(path); }
[ "@", "Deprecated", "public", "static", "URL", "getResource", "(", "ServletContext", "servletContext", ",", "String", "path", ")", "throws", "MalformedURLException", "{", "return", "servletContext", ".", "getResource", "(", "path", ")", ";", "}" ]
Gets the URL for the provided absolute path or <code>null</code> if no resource is mapped to the path. @deprecated Use regular methods directly @see ServletContext#getResource(java.lang.String) @see ServletContextCache#getResource(java.lang.String) @see ServletContextCache#getResource(javax.servlet.ServletContext, java.lang.String)
[ "Gets", "the", "URL", "for", "the", "provided", "absolute", "path", "or", "<code", ">", "null<", "/", "code", ">", "if", "no", "resource", "is", "mapped", "to", "the", "path", "." ]
train
https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/servlet/http/ServletUtil.java#L159-L162
RestComm/sipunit
src/main/java/org/cafesip/sipunit/SipSession.java
SipSession.setPublicAddress
public boolean setPublicAddress(String host, int port) { try { // set 'sentBy' in the listening point for outbound messages parent.getSipProvider().getListeningPoints()[0].setSentBy(host + ":" + port); // update my contact info SipURI my_uri = (SipURI) contactInfo.getContactHeader().getAddress().getURI(); my_uri.setHost(host); my_uri.setPort(port); // update my via header ViaHeader my_via = (ViaHeader) viaHeaders.get(0); my_via.setHost(host); my_via.setPort(port); // update my host myhost = host; } catch (Exception ex) { setException(ex); setErrorMessage("Exception: " + ex.getClass().getName() + ": " + ex.getMessage()); setReturnCode(EXCEPTION_ENCOUNTERED); return false; } // LOG.info("my public IP {}", host); // LOG.info("my public port = {}", port); // LOG.info("my sentby = {}", // parent.getSipProvider().getListeningPoints()[0].getSentBy()); return true; }
java
public boolean setPublicAddress(String host, int port) { try { // set 'sentBy' in the listening point for outbound messages parent.getSipProvider().getListeningPoints()[0].setSentBy(host + ":" + port); // update my contact info SipURI my_uri = (SipURI) contactInfo.getContactHeader().getAddress().getURI(); my_uri.setHost(host); my_uri.setPort(port); // update my via header ViaHeader my_via = (ViaHeader) viaHeaders.get(0); my_via.setHost(host); my_via.setPort(port); // update my host myhost = host; } catch (Exception ex) { setException(ex); setErrorMessage("Exception: " + ex.getClass().getName() + ": " + ex.getMessage()); setReturnCode(EXCEPTION_ENCOUNTERED); return false; } // LOG.info("my public IP {}", host); // LOG.info("my public port = {}", port); // LOG.info("my sentby = {}", // parent.getSipProvider().getListeningPoints()[0].getSentBy()); return true; }
[ "public", "boolean", "setPublicAddress", "(", "String", "host", ",", "int", "port", ")", "{", "try", "{", "// set 'sentBy' in the listening point for outbound messages", "parent", ".", "getSipProvider", "(", ")", ".", "getListeningPoints", "(", ")", "[", "0", "]", ...
This method replaces the host/port values currently being used in this Sip agent's contact address, via, and listening point 'sentby' components with the given host and port parameters. <p> Call this method when you are running a SipUnit testcase behind a NAT and need to register with a proxy on the public internet. Before creating the SipStack and SipPhone, you'll need to first obtain the public IP address/port using a mechanism such as the Stun4j API. See the TestWithStun.java file in the sipunit test/examples directory for an example of how to do it. @param host The publicly accessible IP address for this Sip client (ex: 66.32.44.112). @param port The port to be used with the publicly accessible IP address. @return true if the parameters are successfully parsed and this client's information is updated, false otherwise.
[ "This", "method", "replaces", "the", "host", "/", "port", "values", "currently", "being", "used", "in", "this", "Sip", "agent", "s", "contact", "address", "via", "and", "listening", "point", "sentby", "components", "with", "the", "given", "host", "and", "por...
train
https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/SipSession.java#L404-L434
ThreeTen/threetenbp
src/main/java/org/threeten/bp/Duration.java
Duration.ofSeconds
public static Duration ofSeconds(long seconds, long nanoAdjustment) { long secs = Jdk8Methods.safeAdd(seconds, Jdk8Methods.floorDiv(nanoAdjustment, NANOS_PER_SECOND)); int nos = Jdk8Methods.floorMod(nanoAdjustment, NANOS_PER_SECOND); return create(secs, nos); }
java
public static Duration ofSeconds(long seconds, long nanoAdjustment) { long secs = Jdk8Methods.safeAdd(seconds, Jdk8Methods.floorDiv(nanoAdjustment, NANOS_PER_SECOND)); int nos = Jdk8Methods.floorMod(nanoAdjustment, NANOS_PER_SECOND); return create(secs, nos); }
[ "public", "static", "Duration", "ofSeconds", "(", "long", "seconds", ",", "long", "nanoAdjustment", ")", "{", "long", "secs", "=", "Jdk8Methods", ".", "safeAdd", "(", "seconds", ",", "Jdk8Methods", ".", "floorDiv", "(", "nanoAdjustment", ",", "NANOS_PER_SECOND",...
Obtains an instance of {@code Duration} from a number of seconds and an adjustment in nanoseconds. <p> This method allows an arbitrary number of nanoseconds to be passed in. The factory will alter the values of the second and nanosecond in order to ensure that the stored nanosecond is in the range 0 to 999,999,999. For example, the following will result in the exactly the same duration: <pre> Duration.ofSeconds(3, 1); Duration.ofSeconds(4, -999_999_999); Duration.ofSeconds(2, 1000_000_001); </pre> @param seconds the number of seconds, positive or negative @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative @return a {@code Duration}, not null @throws ArithmeticException if the adjustment causes the seconds to exceed the capacity of {@code Duration}
[ "Obtains", "an", "instance", "of", "{", "@code", "Duration", "}", "from", "a", "number", "of", "seconds", "and", "an", "adjustment", "in", "nanoseconds", ".", "<p", ">", "This", "method", "allows", "an", "arbitrary", "number", "of", "nanoseconds", "to", "b...
train
https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/Duration.java#L212-L216
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WTableRenderer.java
WTableRenderer.paintRows
private void paintRows(final WTable table, final WebXmlRenderContext renderContext) { XmlStringBuilder xml = renderContext.getWriter(); TableModel model = table.getTableModel(); xml.appendTagOpen("ui:tbody"); xml.appendAttribute("id", table.getId() + ".body"); xml.appendClose(); if (model.getRowCount() == 0) { xml.appendTag("ui:nodata"); xml.appendEscaped(table.getNoDataMessage()); xml.appendEndTag("ui:nodata"); } else { // If has at least one visible col, paint the rows. final int columnCount = table.getColumnCount(); for (int i = 0; i < columnCount; i++) { if (table.getColumn(i).isVisible()) { doPaintRows(table, renderContext); break; } } } xml.appendEndTag("ui:tbody"); }
java
private void paintRows(final WTable table, final WebXmlRenderContext renderContext) { XmlStringBuilder xml = renderContext.getWriter(); TableModel model = table.getTableModel(); xml.appendTagOpen("ui:tbody"); xml.appendAttribute("id", table.getId() + ".body"); xml.appendClose(); if (model.getRowCount() == 0) { xml.appendTag("ui:nodata"); xml.appendEscaped(table.getNoDataMessage()); xml.appendEndTag("ui:nodata"); } else { // If has at least one visible col, paint the rows. final int columnCount = table.getColumnCount(); for (int i = 0; i < columnCount; i++) { if (table.getColumn(i).isVisible()) { doPaintRows(table, renderContext); break; } } } xml.appendEndTag("ui:tbody"); }
[ "private", "void", "paintRows", "(", "final", "WTable", "table", ",", "final", "WebXmlRenderContext", "renderContext", ")", "{", "XmlStringBuilder", "xml", "=", "renderContext", ".", "getWriter", "(", ")", ";", "TableModel", "model", "=", "table", ".", "getTable...
Paints the rows of the table. @param table the table to paint the rows for. @param renderContext the RenderContext to paint to.
[ "Paints", "the", "rows", "of", "the", "table", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WTableRenderer.java#L338-L363
eurekaclinical/javautil
src/main/java/org/arp/javautil/collections/Collections.java
Collections.putSet
public static <K, V> void putSet(Map<K, Set<V>> map, K key, V valueElt) { if (map.containsKey(key)) { Set<V> l = map.get(key); l.add(valueElt); } else { Set<V> l = new HashSet<>(); l.add(valueElt); map.put(key, l); } }
java
public static <K, V> void putSet(Map<K, Set<V>> map, K key, V valueElt) { if (map.containsKey(key)) { Set<V> l = map.get(key); l.add(valueElt); } else { Set<V> l = new HashSet<>(); l.add(valueElt); map.put(key, l); } }
[ "public", "static", "<", "K", ",", "V", ">", "void", "putSet", "(", "Map", "<", "K", ",", "Set", "<", "V", ">", ">", "map", ",", "K", "key", ",", "V", "valueElt", ")", "{", "if", "(", "map", ".", "containsKey", "(", "key", ")", ")", "{", "S...
Puts a value into a map of key -> set of values. If the specified key is new, it creates a {@link HashSet} as its value. @param map a {@link Map}. @param key a key. @param valueElt a value.
[ "Puts", "a", "value", "into", "a", "map", "of", "key", "-", ">", "set", "of", "values", ".", "If", "the", "specified", "key", "is", "new", "it", "creates", "a", "{" ]
train
https://github.com/eurekaclinical/javautil/blob/779bbc5bf096c75f8eed4f99ca45b99c1d44df43/src/main/java/org/arp/javautil/collections/Collections.java#L82-L91
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVisionManager.java
ComputerVisionManager.authenticate
public static ComputerVisionClient authenticate(ServiceClientCredentials credentials, String endpoint) { return authenticate("https://{endpoint}/vision/v2.0/", credentials) .withEndpoint(endpoint); }
java
public static ComputerVisionClient authenticate(ServiceClientCredentials credentials, String endpoint) { return authenticate("https://{endpoint}/vision/v2.0/", credentials) .withEndpoint(endpoint); }
[ "public", "static", "ComputerVisionClient", "authenticate", "(", "ServiceClientCredentials", "credentials", ",", "String", "endpoint", ")", "{", "return", "authenticate", "(", "\"https://{endpoint}/vision/v2.0/\"", ",", "credentials", ")", ".", "withEndpoint", "(", "endpo...
Initializes an instance of Computer Vision API client. @param credentials the management credentials for Azure @param endpoint Supported Cognitive Services endpoints. @return the Computer Vision API client
[ "Initializes", "an", "instance", "of", "Computer", "Vision", "API", "client", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVisionManager.java#L69-L72
ironjacamar/ironjacamar
common/src/main/java/org/ironjacamar/common/metadata/common/AbstractParser.java
AbstractParser.elementAsString
protected String elementAsString(XMLStreamReader reader, String key, Map<String, String> expressions) throws XMLStreamException { String elementtext = rawElementText(reader); if (key != null && expressions != null && elementtext != null && elementtext.indexOf("${") != -1) expressions.put(key, elementtext); return getSubstitutionValue(elementtext); }
java
protected String elementAsString(XMLStreamReader reader, String key, Map<String, String> expressions) throws XMLStreamException { String elementtext = rawElementText(reader); if (key != null && expressions != null && elementtext != null && elementtext.indexOf("${") != -1) expressions.put(key, elementtext); return getSubstitutionValue(elementtext); }
[ "protected", "String", "elementAsString", "(", "XMLStreamReader", "reader", ",", "String", "key", ",", "Map", "<", "String", ",", "String", ">", "expressions", ")", "throws", "XMLStreamException", "{", "String", "elementtext", "=", "rawElementText", "(", "reader",...
convert an xml element in String value @param reader the StAX reader @param key The key @param expressions The expressions @return the string representing element @throws XMLStreamException StAX exception
[ "convert", "an", "xml", "element", "in", "String", "value" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/common/src/main/java/org/ironjacamar/common/metadata/common/AbstractParser.java#L159-L168
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-crypto/xwiki-commons-crypto-pkix/src/main/java/org/xwiki/crypto/signer/internal/cms/BcStoreUtils.java
BcStoreUtils.newCertificateProvider
private static CertificateProvider newCertificateProvider(ComponentManager manager, Store store) throws GeneralSecurityException { try { CertificateProvider provider = manager.getInstance(CertificateProvider.class, "BCStoreX509"); ((BcStoreX509CertificateProvider) provider).setStore(store); return provider; } catch (ComponentLookupException e) { throw new GeneralSecurityException("Unable to initialize the certificates store", e); } }
java
private static CertificateProvider newCertificateProvider(ComponentManager manager, Store store) throws GeneralSecurityException { try { CertificateProvider provider = manager.getInstance(CertificateProvider.class, "BCStoreX509"); ((BcStoreX509CertificateProvider) provider).setStore(store); return provider; } catch (ComponentLookupException e) { throw new GeneralSecurityException("Unable to initialize the certificates store", e); } }
[ "private", "static", "CertificateProvider", "newCertificateProvider", "(", "ComponentManager", "manager", ",", "Store", "store", ")", "throws", "GeneralSecurityException", "{", "try", "{", "CertificateProvider", "provider", "=", "manager", ".", "getInstance", "(", "Cert...
Wrap a bouncy castle store into an adapter for the CertificateProvider interface. @param manager the component manager. @param store the store. @return a certificate provider wrapping the store. @throws GeneralSecurityException if unable to initialize the provider.
[ "Wrap", "a", "bouncy", "castle", "store", "into", "an", "adapter", "for", "the", "CertificateProvider", "interface", "." ]
train
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-crypto/xwiki-commons-crypto-pkix/src/main/java/org/xwiki/crypto/signer/internal/cms/BcStoreUtils.java#L126-L137
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/PropertyBuilder.java
PropertyBuilder.buildDeprecationInfo
public void buildDeprecationInfo(XMLNode node, Content propertyDocTree) { writer.addDeprecated( (MethodDoc) properties.get(currentPropertyIndex), propertyDocTree); }
java
public void buildDeprecationInfo(XMLNode node, Content propertyDocTree) { writer.addDeprecated( (MethodDoc) properties.get(currentPropertyIndex), propertyDocTree); }
[ "public", "void", "buildDeprecationInfo", "(", "XMLNode", "node", ",", "Content", "propertyDocTree", ")", "{", "writer", ".", "addDeprecated", "(", "(", "MethodDoc", ")", "properties", ".", "get", "(", "currentPropertyIndex", ")", ",", "propertyDocTree", ")", ";...
Build the deprecation information. @param node the XML element that specifies which components to document @param propertyDocTree the content tree to which the documentation will be added
[ "Build", "the", "deprecation", "information", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/PropertyBuilder.java#L193-L196
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/apple/XcodeProjectWriter.java
XcodeProjectWriter.addSources
private List<PBXObjectRef> addSources(final Map objects, final String sourceTree, final String basePath, final Map<String, TargetInfo> targets) { final List<PBXObjectRef> sourceGroupChildren = new ArrayList<>(); final List<File> sourceList = new ArrayList<>(targets.size()); for (final TargetInfo info : targets.values()) { final File[] targetsources = info.getSources(); Collections.addAll(sourceList, targetsources); } final File[] sortedSources = sourceList.toArray(new File[sourceList.size()]); Arrays.sort(sortedSources, new Comparator<File>() { @Override public int compare(final File o1, final File o2) { return o1.getName().compareTo(o2.getName()); } }); for (final File sortedSource : sortedSources) { final PBXObjectRef fileRef = createPBXFileReference(sourceTree, basePath, sortedSource); sourceGroupChildren.add(fileRef); objects.put(fileRef.getID(), fileRef.getProperties()); } return sourceGroupChildren; }
java
private List<PBXObjectRef> addSources(final Map objects, final String sourceTree, final String basePath, final Map<String, TargetInfo> targets) { final List<PBXObjectRef> sourceGroupChildren = new ArrayList<>(); final List<File> sourceList = new ArrayList<>(targets.size()); for (final TargetInfo info : targets.values()) { final File[] targetsources = info.getSources(); Collections.addAll(sourceList, targetsources); } final File[] sortedSources = sourceList.toArray(new File[sourceList.size()]); Arrays.sort(sortedSources, new Comparator<File>() { @Override public int compare(final File o1, final File o2) { return o1.getName().compareTo(o2.getName()); } }); for (final File sortedSource : sortedSources) { final PBXObjectRef fileRef = createPBXFileReference(sourceTree, basePath, sortedSource); sourceGroupChildren.add(fileRef); objects.put(fileRef.getID(), fileRef.getProperties()); } return sourceGroupChildren; }
[ "private", "List", "<", "PBXObjectRef", ">", "addSources", "(", "final", "Map", "objects", ",", "final", "String", "sourceTree", ",", "final", "String", "basePath", ",", "final", "Map", "<", "String", ",", "TargetInfo", ">", "targets", ")", "{", "final", "...
Add file references for all source files to map of objects. @param objects map of objects. @param sourceTree source tree. @param basePath parent of XCode project dir @param targets build targets. @return list containing file references of source files.
[ "Add", "file", "references", "for", "all", "source", "files", "to", "map", "of", "objects", "." ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/apple/XcodeProjectWriter.java#L759-L782
di2e/Argo
clui/src/main/java/net/dharwin/common/tools/cli/api/CLIContext.java
CLIContext.getInteger
public int getInteger(String key, int defaultValue) { Object o = getObject(key); if (o == null) { return defaultValue; } int val = defaultValue; try { val = Integer.parseInt(o.toString()); } catch (Exception e) { throw new IllegalArgumentException("Object ["+o+"] associated with key ["+key+"] is not of type Integer."); } return val; }
java
public int getInteger(String key, int defaultValue) { Object o = getObject(key); if (o == null) { return defaultValue; } int val = defaultValue; try { val = Integer.parseInt(o.toString()); } catch (Exception e) { throw new IllegalArgumentException("Object ["+o+"] associated with key ["+key+"] is not of type Integer."); } return val; }
[ "public", "int", "getInteger", "(", "String", "key", ",", "int", "defaultValue", ")", "{", "Object", "o", "=", "getObject", "(", "key", ")", ";", "if", "(", "o", "==", "null", ")", "{", "return", "defaultValue", ";", "}", "int", "val", "=", "defaultV...
Get the integer value, or the defaultValue if not found. @param key The key to search for. @param defaultValue the default value @return The value, or defaultValue if not found.
[ "Get", "the", "integer", "value", "or", "the", "defaultValue", "if", "not", "found", "." ]
train
https://github.com/di2e/Argo/blob/f537a03d2d25fdfecda7999ec10e1da67dc3b8f3/clui/src/main/java/net/dharwin/common/tools/cli/api/CLIContext.java#L212-L225
aoindustries/aocode-public
src/main/java/com/aoindustries/io/ParallelDelete.java
ParallelDelete.getRelativePath
private static String getRelativePath(File file, FilesystemIterator iterator) throws IOException { String path = file.getPath(); String prefix = iterator.getStartPath(); if(!path.startsWith(prefix)) throw new IOException("path doesn't start with prefix: path=\""+path+"\", prefix=\""+prefix+"\""); return path.substring(prefix.length()); }
java
private static String getRelativePath(File file, FilesystemIterator iterator) throws IOException { String path = file.getPath(); String prefix = iterator.getStartPath(); if(!path.startsWith(prefix)) throw new IOException("path doesn't start with prefix: path=\""+path+"\", prefix=\""+prefix+"\""); return path.substring(prefix.length()); }
[ "private", "static", "String", "getRelativePath", "(", "File", "file", ",", "FilesystemIterator", "iterator", ")", "throws", "IOException", "{", "String", "path", "=", "file", ".", "getPath", "(", ")", ";", "String", "prefix", "=", "iterator", ".", "getStartPa...
Gets the relative path for the provided file from the provided iterator.
[ "Gets", "the", "relative", "path", "for", "the", "provided", "file", "from", "the", "provided", "iterator", "." ]
train
https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/ParallelDelete.java#L328-L333
intendia-oss/rxjava-gwt
src/main/modified/io/reactivex/super/io/reactivex/Flowable.java
Flowable.concatMapSingleDelayError
@CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> concatMapSingleDelayError(Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean tillTheEnd, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); return RxJavaPlugins.onAssembly(new FlowableConcatMapSingle<T, R>(this, mapper, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY, prefetch)); }
java
@CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> concatMapSingleDelayError(Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean tillTheEnd, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); return RxJavaPlugins.onAssembly(new FlowableConcatMapSingle<T, R>(this, mapper, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY, prefetch)); }
[ "@", "CheckReturnValue", "@", "BackpressureSupport", "(", "BackpressureKind", ".", "FULL", ")", "@", "SchedulerSupport", "(", "SchedulerSupport", ".", "NONE", ")", "public", "final", "<", "R", ">", "Flowable", "<", "R", ">", "concatMapSingleDelayError", "(", "Fu...
Maps the upstream items into {@link SingleSource}s and subscribes to them one after the other succeeds or fails, emits their success values and optionally delays errors till both this {@code Flowable} and all inner {@code SingleSource}s terminate. <p> <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt=""> <dl> <dt><b>Backpressure:</b></dt> <dd>The operator expects the upstream to support backpressure and honors the backpressure from downstream. If this {@code Flowable} violates the rule, the operator will signal a {@code MissingBackpressureException}.</dd> <dt><b>Scheduler:</b></dt> <dd>{@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.</dd> </dl> <p>History: 2.1.11 - experimental @param <R> the result type of the inner {@code SingleSource}s @param mapper the function called with the upstream item and should return a {@code SingleSource} to become the next source to be subscribed to @param tillTheEnd If {@code true}, errors from this {@code Flowable} or any of the inner {@code SingleSource}s are delayed until all of them terminate. If {@code false}, an error from this {@code Flowable} is delayed until the current inner {@code SingleSource} terminates and only then is it emitted to the downstream. @param prefetch The number of upstream items to prefetch so that fresh items are ready to be mapped when a previous {@code SingleSource} terminates. The operator replenishes after half of the prefetch amount has been consumed and turned into {@code SingleSource}s. @return a new Flowable instance @see #concatMapSingle(Function, int) @since 2.2
[ "Maps", "the", "upstream", "items", "into", "{" ]
train
https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Flowable.java#L7903-L7910
apache/incubator-zipkin
zipkin-server/src/main/java/zipkin2/server/internal/elasticsearch/ZipkinElasticsearchStorageAutoConfiguration.java
ZipkinElasticsearchStorageAutoConfiguration.makeContextAware
static ExecutorService makeContextAware(ExecutorService delegate, CurrentTraceContext traceCtx) { class TracingCurrentRequestContextExecutorService extends WrappingExecutorService { @Override protected ExecutorService delegate() { return delegate; } @Override protected <C> Callable<C> wrap(Callable<C> task) { return RequestContext.current().makeContextAware(traceCtx.wrap(task)); } @Override protected Runnable wrap(Runnable task) { return RequestContext.current().makeContextAware(traceCtx.wrap(task)); } } return new TracingCurrentRequestContextExecutorService(); }
java
static ExecutorService makeContextAware(ExecutorService delegate, CurrentTraceContext traceCtx) { class TracingCurrentRequestContextExecutorService extends WrappingExecutorService { @Override protected ExecutorService delegate() { return delegate; } @Override protected <C> Callable<C> wrap(Callable<C> task) { return RequestContext.current().makeContextAware(traceCtx.wrap(task)); } @Override protected Runnable wrap(Runnable task) { return RequestContext.current().makeContextAware(traceCtx.wrap(task)); } } return new TracingCurrentRequestContextExecutorService(); }
[ "static", "ExecutorService", "makeContextAware", "(", "ExecutorService", "delegate", ",", "CurrentTraceContext", "traceCtx", ")", "{", "class", "TracingCurrentRequestContextExecutorService", "extends", "WrappingExecutorService", "{", "@", "Override", "protected", "ExecutorServi...
Decorates the input such that the {@link RequestContext#current() current request context} and the and the {@link CurrentTraceContext#get() current trace context} at assembly time is made current when task is executed.
[ "Decorates", "the", "input", "such", "that", "the", "{" ]
train
https://github.com/apache/incubator-zipkin/blob/89b2fab983fc626b3be32ce9d7cf64b3f01f1a87/zipkin-server/src/main/java/zipkin2/server/internal/elasticsearch/ZipkinElasticsearchStorageAutoConfiguration.java#L169-L185
opengeospatial/teamengine
teamengine-web/src/main/java/com/occamlab/te/web/CoverageMonitor.java
CoverageMonitor.writeDocument
void writeDocument(OutputStream outStream, Document doc) { DOMImplementationRegistry domRegistry = null; try { domRegistry = DOMImplementationRegistry.newInstance(); // Fortify Mod: Broaden try block to capture all potential exceptions // } catch (Exception e) { // LOGR.warning(e.getMessage()); // } DOMImplementationLS impl = (DOMImplementationLS) domRegistry .getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("xml-declaration", false); writer.getDomConfig().setParameter("format-pretty-print", true); LSOutput output = impl.createLSOutput(); output.setEncoding("UTF-8"); output.setByteStream(outStream); writer.write(doc, output); } catch (Exception e) { LOGR.warning(e.getMessage()); } }
java
void writeDocument(OutputStream outStream, Document doc) { DOMImplementationRegistry domRegistry = null; try { domRegistry = DOMImplementationRegistry.newInstance(); // Fortify Mod: Broaden try block to capture all potential exceptions // } catch (Exception e) { // LOGR.warning(e.getMessage()); // } DOMImplementationLS impl = (DOMImplementationLS) domRegistry .getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("xml-declaration", false); writer.getDomConfig().setParameter("format-pretty-print", true); LSOutput output = impl.createLSOutput(); output.setEncoding("UTF-8"); output.setByteStream(outStream); writer.write(doc, output); } catch (Exception e) { LOGR.warning(e.getMessage()); } }
[ "void", "writeDocument", "(", "OutputStream", "outStream", ",", "Document", "doc", ")", "{", "DOMImplementationRegistry", "domRegistry", "=", "null", ";", "try", "{", "domRegistry", "=", "DOMImplementationRegistry", ".", "newInstance", "(", ")", ";", "// Fortify Mod...
Writes a DOM Document to the given OutputStream using the "UTF-8" encoding. The XML declaration is omitted. @param outStream The destination OutputStream object. @param doc A Document node.
[ "Writes", "a", "DOM", "Document", "to", "the", "given", "OutputStream", "using", "the", "UTF", "-", "8", "encoding", ".", "The", "XML", "declaration", "is", "omitted", "." ]
train
https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-web/src/main/java/com/occamlab/te/web/CoverageMonitor.java#L237-L257
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java
IoUtil.readUtf8Lines
public static <T extends Collection<String>> T readUtf8Lines(InputStream in, T collection) throws IORuntimeException { return readLines(in, CharsetUtil.CHARSET_UTF_8, collection); }
java
public static <T extends Collection<String>> T readUtf8Lines(InputStream in, T collection) throws IORuntimeException { return readLines(in, CharsetUtil.CHARSET_UTF_8, collection); }
[ "public", "static", "<", "T", "extends", "Collection", "<", "String", ">", ">", "T", "readUtf8Lines", "(", "InputStream", "in", ",", "T", "collection", ")", "throws", "IORuntimeException", "{", "return", "readLines", "(", "in", ",", "CharsetUtil", ".", "CHAR...
从流中读取内容,使用UTF-8编码 @param <T> 集合类型 @param in 输入流 @param collection 返回集合 @return 内容 @throws IORuntimeException IO异常
[ "从流中读取内容,使用UTF", "-", "8编码" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java#L630-L632
xqbase/tuna
core/src/main/java/com/xqbase/tuna/ConnectionWrapper.java
ConnectionWrapper.onRecv
@Override public void onRecv(byte[] b, int off, int len) { connection.onRecv(b, off, len); }
java
@Override public void onRecv(byte[] b, int off, int len) { connection.onRecv(b, off, len); }
[ "@", "Override", "public", "void", "onRecv", "(", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "{", "connection", ".", "onRecv", "(", "b", ",", "off", ",", "len", ")", ";", "}" ]
Wraps received data, from the network side to the application side
[ "Wraps", "received", "data", "from", "the", "network", "side", "to", "the", "application", "side" ]
train
https://github.com/xqbase/tuna/blob/60d05a9e03877a3daafe9de83dc4427c6cbb9995/core/src/main/java/com/xqbase/tuna/ConnectionWrapper.java#L16-L19
jayantk/jklol
src/com/jayantkrish/jklol/ccg/chart/CcgExactChart.java
CcgExactChart.decodeBestParseForSpan
public CcgParse decodeBestParseForSpan(int spanStart, int spanEnd, CcgParser parser) { double maxProb = -1; int maxEntryIndex = -1; double[] probs = getChartEntryProbsForSpan(spanStart, spanEnd); for (int i = 0; i < chartSizes[spanStart][spanEnd]; i++) { if (probs[i] > maxProb) { maxProb = probs[i]; maxEntryIndex = i; } } if (maxEntryIndex == -1) { // No parses. return null; } else { return decodeParseFromSpan(spanStart, spanEnd, maxEntryIndex, parser); } }
java
public CcgParse decodeBestParseForSpan(int spanStart, int spanEnd, CcgParser parser) { double maxProb = -1; int maxEntryIndex = -1; double[] probs = getChartEntryProbsForSpan(spanStart, spanEnd); for (int i = 0; i < chartSizes[spanStart][spanEnd]; i++) { if (probs[i] > maxProb) { maxProb = probs[i]; maxEntryIndex = i; } } if (maxEntryIndex == -1) { // No parses. return null; } else { return decodeParseFromSpan(spanStart, spanEnd, maxEntryIndex, parser); } }
[ "public", "CcgParse", "decodeBestParseForSpan", "(", "int", "spanStart", ",", "int", "spanEnd", ",", "CcgParser", "parser", ")", "{", "double", "maxProb", "=", "-", "1", ";", "int", "maxEntryIndex", "=", "-", "1", ";", "double", "[", "]", "probs", "=", "...
Gets the best CCG parse for the given span. Returns {@code null} if no parse was found. @param spanStart @param spanEnd @param parser @return
[ "Gets", "the", "best", "CCG", "parse", "for", "the", "given", "span", ".", "Returns", "{", "@code", "null", "}", "if", "no", "parse", "was", "found", "." ]
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/chart/CcgExactChart.java#L55-L72
apache/groovy
subprojects/groovy-swing/src/main/java/org/codehaus/groovy/runtime/SwingGroovyMethods.java
SwingGroovyMethods.leftShift
public static JMenu leftShift(JMenu self, String str) { self.add(str); return self; }
java
public static JMenu leftShift(JMenu self, String str) { self.add(str); return self; }
[ "public", "static", "JMenu", "leftShift", "(", "JMenu", "self", ",", "String", "str", ")", "{", "self", ".", "add", "(", "str", ")", ";", "return", "self", ";", "}" ]
Overloads the left shift operator to provide an easy way to add components to a menu.<p> @param self a JMenu @param str a String to be added to the menu. @return same menu, after the value was added to it. @since 1.6.4
[ "Overloads", "the", "left", "shift", "operator", "to", "provide", "an", "easy", "way", "to", "add", "components", "to", "a", "menu", ".", "<p", ">" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/runtime/SwingGroovyMethods.java#L809-L812
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/CustomFieldValueReader.java
CustomFieldValueReader.getTypedValue
protected Object getTypedValue(int type, byte[] value) { Object result; switch (type) { case 4: // Date { result = MPPUtility.getTimestamp(value, 0); break; } case 6: // Duration { TimeUnit units = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(value, 4), m_properties.getDefaultDurationUnits()); result = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(value, 0), units); break; } case 9: // Cost { result = Double.valueOf(MPPUtility.getDouble(value, 0) / 100); break; } case 15: // Number { result = Double.valueOf(MPPUtility.getDouble(value, 0)); break; } case 36058: case 21: // Text { result = MPPUtility.getUnicodeString(value, 0); break; } default: { result = value; break; } } return result; }
java
protected Object getTypedValue(int type, byte[] value) { Object result; switch (type) { case 4: // Date { result = MPPUtility.getTimestamp(value, 0); break; } case 6: // Duration { TimeUnit units = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(value, 4), m_properties.getDefaultDurationUnits()); result = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(value, 0), units); break; } case 9: // Cost { result = Double.valueOf(MPPUtility.getDouble(value, 0) / 100); break; } case 15: // Number { result = Double.valueOf(MPPUtility.getDouble(value, 0)); break; } case 36058: case 21: // Text { result = MPPUtility.getUnicodeString(value, 0); break; } default: { result = value; break; } } return result; }
[ "protected", "Object", "getTypedValue", "(", "int", "type", ",", "byte", "[", "]", "value", ")", "{", "Object", "result", ";", "switch", "(", "type", ")", "{", "case", "4", ":", "// Date", "{", "result", "=", "MPPUtility", ".", "getTimestamp", "(", "va...
Convert raw value as read from the MPP file into a Java type. @param type MPP value type @param value raw value data @return Java object
[ "Convert", "raw", "value", "as", "read", "from", "the", "MPP", "file", "into", "a", "Java", "type", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/CustomFieldValueReader.java#L71-L117
Azure/azure-sdk-for-java
iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java
IotHubResourcesInner.beginUpdateAsync
public Observable<IotHubDescriptionInner> beginUpdateAsync(String resourceGroupName, String resourceName) { return beginUpdateWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<IotHubDescriptionInner>, IotHubDescriptionInner>() { @Override public IotHubDescriptionInner call(ServiceResponse<IotHubDescriptionInner> response) { return response.body(); } }); }
java
public Observable<IotHubDescriptionInner> beginUpdateAsync(String resourceGroupName, String resourceName) { return beginUpdateWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<IotHubDescriptionInner>, IotHubDescriptionInner>() { @Override public IotHubDescriptionInner call(ServiceResponse<IotHubDescriptionInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "IotHubDescriptionInner", ">", "beginUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "resourceName", ")", "{", "return", "beginUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ")", ".", "map", ...
Update an existing IoT Hubs tags. Update an existing IoT Hub tags. to update other fields use the CreateOrUpdate method. @param resourceGroupName Resource group identifier. @param resourceName Name of iot hub to update. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the IotHubDescriptionInner object
[ "Update", "an", "existing", "IoT", "Hubs", "tags", ".", "Update", "an", "existing", "IoT", "Hub", "tags", ".", "to", "update", "other", "fields", "use", "the", "CreateOrUpdate", "method", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java#L860-L867
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java
IoUtil.toStream
public static ByteArrayInputStream toStream(String content, String charsetName) { return toStream(content, CharsetUtil.charset(charsetName)); }
java
public static ByteArrayInputStream toStream(String content, String charsetName) { return toStream(content, CharsetUtil.charset(charsetName)); }
[ "public", "static", "ByteArrayInputStream", "toStream", "(", "String", "content", ",", "String", "charsetName", ")", "{", "return", "toStream", "(", "content", ",", "CharsetUtil", ".", "charset", "(", "charsetName", ")", ")", ";", "}" ]
String 转为流 @param content 内容 @param charsetName 编码 @return 字节流
[ "String", "转为流" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java#L739-L741
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/Type1Font.java
Type1Font.getFontDescriptor
public float getFontDescriptor(int key, float fontSize) { switch (key) { case AWT_ASCENT: case ASCENT: return Ascender * fontSize / 1000; case CAPHEIGHT: return CapHeight * fontSize / 1000; case AWT_DESCENT: case DESCENT: return Descender * fontSize / 1000; case ITALICANGLE: return ItalicAngle; case BBOXLLX: return llx * fontSize / 1000; case BBOXLLY: return lly * fontSize / 1000; case BBOXURX: return urx * fontSize / 1000; case BBOXURY: return ury * fontSize / 1000; case AWT_LEADING: return 0; case AWT_MAXADVANCE: return (urx - llx) * fontSize / 1000; case UNDERLINE_POSITION: return UnderlinePosition * fontSize / 1000; case UNDERLINE_THICKNESS: return UnderlineThickness * fontSize / 1000; } return 0; }
java
public float getFontDescriptor(int key, float fontSize) { switch (key) { case AWT_ASCENT: case ASCENT: return Ascender * fontSize / 1000; case CAPHEIGHT: return CapHeight * fontSize / 1000; case AWT_DESCENT: case DESCENT: return Descender * fontSize / 1000; case ITALICANGLE: return ItalicAngle; case BBOXLLX: return llx * fontSize / 1000; case BBOXLLY: return lly * fontSize / 1000; case BBOXURX: return urx * fontSize / 1000; case BBOXURY: return ury * fontSize / 1000; case AWT_LEADING: return 0; case AWT_MAXADVANCE: return (urx - llx) * fontSize / 1000; case UNDERLINE_POSITION: return UnderlinePosition * fontSize / 1000; case UNDERLINE_THICKNESS: return UnderlineThickness * fontSize / 1000; } return 0; }
[ "public", "float", "getFontDescriptor", "(", "int", "key", ",", "float", "fontSize", ")", "{", "switch", "(", "key", ")", "{", "case", "AWT_ASCENT", ":", "case", "ASCENT", ":", "return", "Ascender", "*", "fontSize", "/", "1000", ";", "case", "CAPHEIGHT", ...
Gets the font parameter identified by <CODE>key</CODE>. Valid values for <CODE>key</CODE> are <CODE>ASCENT</CODE>, <CODE>CAPHEIGHT</CODE>, <CODE>DESCENT</CODE>, <CODE>ITALICANGLE</CODE>, <CODE>BBOXLLX</CODE>, <CODE>BBOXLLY</CODE>, <CODE>BBOXURX</CODE> and <CODE>BBOXURY</CODE>. @param key the parameter to be extracted @param fontSize the font size in points @return the parameter in points
[ "Gets", "the", "font", "parameter", "identified", "by", "<CODE", ">", "key<", "/", "CODE", ">", ".", "Valid", "values", "for", "<CODE", ">", "key<", "/", "CODE", ">", "are", "<CODE", ">", "ASCENT<", "/", "CODE", ">", "<CODE", ">", "CAPHEIGHT<", "/", ...
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/Type1Font.java#L689-L719
camunda/camunda-commons
typed-values/src/main/java/org/camunda/bpm/engine/variable/Variables.java
Variables.fromMap
public static VariableMap fromMap(Map<String, Object> map) { if(map instanceof VariableMap) { return (VariableMap) map; } else { return new VariableMapImpl(map); } }
java
public static VariableMap fromMap(Map<String, Object> map) { if(map instanceof VariableMap) { return (VariableMap) map; } else { return new VariableMapImpl(map); } }
[ "public", "static", "VariableMap", "fromMap", "(", "Map", "<", "String", ",", "Object", ">", "map", ")", "{", "if", "(", "map", "instanceof", "VariableMap", ")", "{", "return", "(", "VariableMap", ")", "map", ";", "}", "else", "{", "return", "new", "Va...
If the given map is not a variable map, adds all its entries as untyped values to a new {@link VariableMap}. If the given map is a {@link VariableMap}, it is returned as is.
[ "If", "the", "given", "map", "is", "not", "a", "variable", "map", "adds", "all", "its", "entries", "as", "untyped", "values", "to", "a", "new", "{" ]
train
https://github.com/camunda/camunda-commons/blob/bd3195db47c92c25717288fe9e6735f8e882f247/typed-values/src/main/java/org/camunda/bpm/engine/variable/Variables.java#L148-L155
JodaOrg/joda-beans
src/main/java/org/joda/beans/ser/SerIteratorFactory.java
SerIteratorFactory.sortedSet
public static final SerIterable sortedSet(final Class<?> valueType, final List<Class<?>> valueTypeTypes) { final SortedSet<Object> coll = new TreeSet<>(); return set(valueType, valueTypeTypes, coll); }
java
public static final SerIterable sortedSet(final Class<?> valueType, final List<Class<?>> valueTypeTypes) { final SortedSet<Object> coll = new TreeSet<>(); return set(valueType, valueTypeTypes, coll); }
[ "public", "static", "final", "SerIterable", "sortedSet", "(", "final", "Class", "<", "?", ">", "valueType", ",", "final", "List", "<", "Class", "<", "?", ">", ">", "valueTypeTypes", ")", "{", "final", "SortedSet", "<", "Object", ">", "coll", "=", "new", ...
Gets an iterable wrapper for {@code SortedSet}. @param valueType the value type, not null @param valueTypeTypes the generic parameters of the value type @return the iterable, not null
[ "Gets", "an", "iterable", "wrapper", "for", "{", "@code", "SortedSet", "}", "." ]
train
https://github.com/JodaOrg/joda-beans/blob/f07dbe42947150b23a173f35984c6ab33c5529bf/src/main/java/org/joda/beans/ser/SerIteratorFactory.java#L416-L419
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java
InodeTree.deleteInode
public void deleteInode(RpcContext rpcContext, LockedInodePath inodePath, long opTimeMs) throws FileDoesNotExistException { Preconditions.checkState(inodePath.getLockPattern() == LockPattern.WRITE_EDGE); Inode inode = inodePath.getInode(); mState.applyAndJournal(rpcContext, DeleteFileEntry.newBuilder() .setId(inode.getId()) .setRecursive(false) .setOpTimeMs(opTimeMs) .build()); if (inode.isFile()) { rpcContext.getBlockDeletionContext().registerBlocksForDeletion(inode.asFile().getBlockIds()); } }
java
public void deleteInode(RpcContext rpcContext, LockedInodePath inodePath, long opTimeMs) throws FileDoesNotExistException { Preconditions.checkState(inodePath.getLockPattern() == LockPattern.WRITE_EDGE); Inode inode = inodePath.getInode(); mState.applyAndJournal(rpcContext, DeleteFileEntry.newBuilder() .setId(inode.getId()) .setRecursive(false) .setOpTimeMs(opTimeMs) .build()); if (inode.isFile()) { rpcContext.getBlockDeletionContext().registerBlocksForDeletion(inode.asFile().getBlockIds()); } }
[ "public", "void", "deleteInode", "(", "RpcContext", "rpcContext", ",", "LockedInodePath", "inodePath", ",", "long", "opTimeMs", ")", "throws", "FileDoesNotExistException", "{", "Preconditions", ".", "checkState", "(", "inodePath", ".", "getLockPattern", "(", ")", "=...
Deletes a single inode from the inode tree by removing it from the parent inode. @param rpcContext the rpc context @param inodePath the {@link LockedInodePath} to delete @param opTimeMs the operation time @throws FileDoesNotExistException if the Inode cannot be retrieved
[ "Deletes", "a", "single", "inode", "from", "the", "inode", "tree", "by", "removing", "it", "from", "the", "parent", "inode", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java#L852-L866
j256/ormlite-android
src/main/java/com/j256/ormlite/android/apptools/OrmLiteSqliteOpenHelper.java
OrmLiteSqliteOpenHelper.getRuntimeExceptionDao
public <D extends RuntimeExceptionDao<T, ?>, T> D getRuntimeExceptionDao(Class<T> clazz) { try { Dao<T, ?> dao = getDao(clazz); @SuppressWarnings({ "unchecked", "rawtypes" }) D castDao = (D) new RuntimeExceptionDao(dao); return castDao; } catch (SQLException e) { throw new RuntimeException("Could not create RuntimeExcepitionDao for class " + clazz, e); } }
java
public <D extends RuntimeExceptionDao<T, ?>, T> D getRuntimeExceptionDao(Class<T> clazz) { try { Dao<T, ?> dao = getDao(clazz); @SuppressWarnings({ "unchecked", "rawtypes" }) D castDao = (D) new RuntimeExceptionDao(dao); return castDao; } catch (SQLException e) { throw new RuntimeException("Could not create RuntimeExcepitionDao for class " + clazz, e); } }
[ "public", "<", "D", "extends", "RuntimeExceptionDao", "<", "T", ",", "?", ">", ",", "T", ">", "D", "getRuntimeExceptionDao", "(", "Class", "<", "T", ">", "clazz", ")", "{", "try", "{", "Dao", "<", "T", ",", "?", ">", "dao", "=", "getDao", "(", "c...
Get a RuntimeExceptionDao for our class. This uses the {@link DaoManager} to cache the DAO for future gets. <p> NOTE: This routing does not return RuntimeExceptionDao&lt;T, ID&gt; because of casting issues if we are assigning it to a custom DAO. Grumble. </p>
[ "Get", "a", "RuntimeExceptionDao", "for", "our", "class", ".", "This", "uses", "the", "{", "@link", "DaoManager", "}", "to", "cache", "the", "DAO", "for", "future", "gets", "." ]
train
https://github.com/j256/ormlite-android/blob/e82327a868ae242f994730fe2389f79684d7bcab/src/main/java/com/j256/ormlite/android/apptools/OrmLiteSqliteOpenHelper.java#L291-L300
tvbarthel/Cheerleader
sample/src/main/java/fr/tvbarthel/cheerleader/sampleapp/ArtistActivity.java
ArtistActivity.startActivity
public static void startActivity(Context context, String artistName) { Intent i = new Intent(context, ArtistActivity.class); i.putExtra(BUNDLE_KEY_ARTIST_NAME, artistName); context.startActivity(i); }
java
public static void startActivity(Context context, String artistName) { Intent i = new Intent(context, ArtistActivity.class); i.putExtra(BUNDLE_KEY_ARTIST_NAME, artistName); context.startActivity(i); }
[ "public", "static", "void", "startActivity", "(", "Context", "context", ",", "String", "artistName", ")", "{", "Intent", "i", "=", "new", "Intent", "(", "context", ",", "ArtistActivity", ".", "class", ")", ";", "i", ".", "putExtra", "(", "BUNDLE_KEY_ARTIST_N...
Start an ArtistActivity for a given artist name. Start activity pattern. @param context context used to start the activity. @param artistName name of the artist.
[ "Start", "an", "ArtistActivity", "for", "a", "given", "artist", "name", ".", "Start", "activity", "pattern", "." ]
train
https://github.com/tvbarthel/Cheerleader/blob/f61527e4cc44fcd0ed2e1e98aca285f8c236f24e/sample/src/main/java/fr/tvbarthel/cheerleader/sampleapp/ArtistActivity.java#L85-L89
astrapi69/jaulp-wicket
jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/WicketComponentExtensions.java
WicketComponentExtensions.getParameter
@Deprecated public static String getParameter(final Request request, final String parameterName) { return PageParametersExtensions.getParameter(request, parameterName); }
java
@Deprecated public static String getParameter(final Request request, final String parameterName) { return PageParametersExtensions.getParameter(request, parameterName); }
[ "@", "Deprecated", "public", "static", "String", "getParameter", "(", "final", "Request", "request", ",", "final", "String", "parameterName", ")", "{", "return", "PageParametersExtensions", ".", "getParameter", "(", "request", ",", "parameterName", ")", ";", "}" ]
Gets the parameter value from given parameter name. Looks in the query and post parameters. @param request the request @param parameterName the parameter name @return the parameter value @deprecated use instead {@link PageParametersExtensions#getParameter(Request, String)}
[ "Gets", "the", "parameter", "value", "from", "given", "parameter", "name", ".", "Looks", "in", "the", "query", "and", "post", "parameters", "." ]
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/WicketComponentExtensions.java#L187-L191
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/msvc/VisualStudioNETProjectWriter.java
VisualStudioNETProjectWriter.getRuntimeLibrary
private String getRuntimeLibrary(final CommandLineCompilerConfiguration compilerConfig, final boolean isDebug) { String rtl = null; final String[] args = compilerConfig.getPreArguments(); for (final String arg : args) { if (arg.startsWith("/MT")) { if (isDebug) { rtl = "1"; } else { rtl = "0"; } } else if (arg.startsWith("/MD")) { if (isDebug) { rtl = "3"; } else { rtl = "2"; } } } return rtl; }
java
private String getRuntimeLibrary(final CommandLineCompilerConfiguration compilerConfig, final boolean isDebug) { String rtl = null; final String[] args = compilerConfig.getPreArguments(); for (final String arg : args) { if (arg.startsWith("/MT")) { if (isDebug) { rtl = "1"; } else { rtl = "0"; } } else if (arg.startsWith("/MD")) { if (isDebug) { rtl = "3"; } else { rtl = "2"; } } } return rtl; }
[ "private", "String", "getRuntimeLibrary", "(", "final", "CommandLineCompilerConfiguration", "compilerConfig", ",", "final", "boolean", "isDebug", ")", "{", "String", "rtl", "=", "null", ";", "final", "String", "[", "]", "args", "=", "compilerConfig", ".", "getPreA...
Get value of RuntimeLibrary property. @param compilerConfig compiler configuration. @param isDebug true if generating debug configuration. @return value of RuntimeLibrary property.
[ "Get", "value", "of", "RuntimeLibrary", "property", "." ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/msvc/VisualStudioNETProjectWriter.java#L460-L479
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_line_serviceName_phone_PUT
public void billingAccount_line_serviceName_phone_PUT(String billingAccount, String serviceName, OvhPhone body) throws IOException { String qPath = "/telephony/{billingAccount}/line/{serviceName}/phone"; StringBuilder sb = path(qPath, billingAccount, serviceName); exec(qPath, "PUT", sb.toString(), body); }
java
public void billingAccount_line_serviceName_phone_PUT(String billingAccount, String serviceName, OvhPhone body) throws IOException { String qPath = "/telephony/{billingAccount}/line/{serviceName}/phone"; StringBuilder sb = path(qPath, billingAccount, serviceName); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "billingAccount_line_serviceName_phone_PUT", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "OvhPhone", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/line/{serviceName}/phone\"", ";", ...
Alter this object properties REST: PUT /telephony/{billingAccount}/line/{serviceName}/phone @param body [required] New object properties @param billingAccount [required] The name of your billingAccount @param serviceName [required]
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L982-L986
googleapis/google-oauth-java-client
google-oauth-client/src/main/java/com/google/api/client/auth/oauth2/AuthorizationCodeFlow.java
AuthorizationCodeFlow.newCredential
@SuppressWarnings("deprecation") private Credential newCredential(String userId) { Credential.Builder builder = new Credential.Builder(method).setTransport(transport) .setJsonFactory(jsonFactory) .setTokenServerEncodedUrl(tokenServerEncodedUrl) .setClientAuthentication(clientAuthentication) .setRequestInitializer(requestInitializer) .setClock(clock); if (credentialDataStore != null) { builder.addRefreshListener( new DataStoreCredentialRefreshListener(userId, credentialDataStore)); } else if (credentialStore != null) { builder.addRefreshListener(new CredentialStoreRefreshListener(userId, credentialStore)); } builder.getRefreshListeners().addAll(refreshListeners); return builder.build(); }
java
@SuppressWarnings("deprecation") private Credential newCredential(String userId) { Credential.Builder builder = new Credential.Builder(method).setTransport(transport) .setJsonFactory(jsonFactory) .setTokenServerEncodedUrl(tokenServerEncodedUrl) .setClientAuthentication(clientAuthentication) .setRequestInitializer(requestInitializer) .setClock(clock); if (credentialDataStore != null) { builder.addRefreshListener( new DataStoreCredentialRefreshListener(userId, credentialDataStore)); } else if (credentialStore != null) { builder.addRefreshListener(new CredentialStoreRefreshListener(userId, credentialStore)); } builder.getRefreshListeners().addAll(refreshListeners); return builder.build(); }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "private", "Credential", "newCredential", "(", "String", "userId", ")", "{", "Credential", ".", "Builder", "builder", "=", "new", "Credential", ".", "Builder", "(", "method", ")", ".", "setTransport", "(", ...
Returns a new credential instance based on the given user ID. @param userId user ID or {@code null} if not using a persisted credential store
[ "Returns", "a", "new", "credential", "instance", "based", "on", "the", "given", "user", "ID", "." ]
train
https://github.com/googleapis/google-oauth-java-client/blob/7a829f8fd4d216c7d5882a82b9b58930fb375592/google-oauth-client/src/main/java/com/google/api/client/auth/oauth2/AuthorizationCodeFlow.java#L276-L292
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/common/Similarity.java
Similarity.getSimilarity
public static <T extends Vector> double getSimilarity( SimType similarityType, T a, T b) { switch (similarityType) { case COSINE: return cosineSimilarity(a, b); case PEARSON_CORRELATION: return correlation(a, b); case EUCLIDEAN: return euclideanSimilarity(a, b); case SPEARMAN_RANK_CORRELATION: return spearmanRankCorrelationCoefficient(a, b); case JACCARD_INDEX: return jaccardIndex(a, b); case AVERAGE_COMMON_FEATURE_RANK: return averageCommonFeatureRank(a, b); case LIN: return linSimilarity(a, b); case KL_DIVERGENCE: return klDivergence(a, b); case KENDALLS_TAU: return kendallsTau(a, b); case TANIMOTO_COEFFICIENT: return tanimotoCoefficient(a, b); } return 0; }
java
public static <T extends Vector> double getSimilarity( SimType similarityType, T a, T b) { switch (similarityType) { case COSINE: return cosineSimilarity(a, b); case PEARSON_CORRELATION: return correlation(a, b); case EUCLIDEAN: return euclideanSimilarity(a, b); case SPEARMAN_RANK_CORRELATION: return spearmanRankCorrelationCoefficient(a, b); case JACCARD_INDEX: return jaccardIndex(a, b); case AVERAGE_COMMON_FEATURE_RANK: return averageCommonFeatureRank(a, b); case LIN: return linSimilarity(a, b); case KL_DIVERGENCE: return klDivergence(a, b); case KENDALLS_TAU: return kendallsTau(a, b); case TANIMOTO_COEFFICIENT: return tanimotoCoefficient(a, b); } return 0; }
[ "public", "static", "<", "T", "extends", "Vector", ">", "double", "getSimilarity", "(", "SimType", "similarityType", ",", "T", "a", ",", "T", "b", ")", "{", "switch", "(", "similarityType", ")", "{", "case", "COSINE", ":", "return", "cosineSimilarity", "("...
Calculates the similarity of the two vectors using the provided similarity measure. @param similarityType the similarity evaluation to use when comparing {@code a} and {@code b} @param a a {@code Vector} @param b a {@code Vector} @return the similarity according to the specified measure
[ "Calculates", "the", "similarity", "of", "the", "two", "vectors", "using", "the", "provided", "similarity", "measure", "." ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/common/Similarity.java#L260-L285
knowm/Yank
src/main/java/org/knowm/yank/Yank.java
Yank.insertSQLKey
public static Long insertSQLKey(String sqlKey, Object[] params) throws SQLStatementNotFoundException, YankSQLException { return insertSQLKey(YankPoolManager.DEFAULT_POOL_NAME, sqlKey, params); }
java
public static Long insertSQLKey(String sqlKey, Object[] params) throws SQLStatementNotFoundException, YankSQLException { return insertSQLKey(YankPoolManager.DEFAULT_POOL_NAME, sqlKey, params); }
[ "public", "static", "Long", "insertSQLKey", "(", "String", "sqlKey", ",", "Object", "[", "]", "params", ")", "throws", "SQLStatementNotFoundException", ",", "YankSQLException", "{", "return", "insertSQLKey", "(", "YankPoolManager", ".", "DEFAULT_POOL_NAME", ",", "sq...
Executes a given INSERT SQL prepared statement matching the sqlKey String in a properties file loaded via Yank.addSQLStatements(...) using the default connection pool. Returns the auto-increment id of the inserted row. @param sqlKey The SQL Key found in a properties file corresponding to the desired SQL statement value @param params The replacement parameters @return the auto-increment id of the inserted row, or null if no id is available @throws SQLStatementNotFoundException if an SQL statement could not be found for the given sqlKey String
[ "Executes", "a", "given", "INSERT", "SQL", "prepared", "statement", "matching", "the", "sqlKey", "String", "in", "a", "properties", "file", "loaded", "via", "Yank", ".", "addSQLStatements", "(", "...", ")", "using", "the", "default", "connection", "pool", ".",...
train
https://github.com/knowm/Yank/blob/b2071dcd94da99db6904355f9557456b8b292a6b/src/main/java/org/knowm/yank/Yank.java#L66-L70
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/context/VmlGraphicsContext.java
VmlGraphicsContext.drawImage
public void drawImage(Object parent, String name, String href, Bbox bounds, PictureStyle style) { if (isAttached()) { Element image = helper.createOrUpdateElement(parent, name, "image", style); applyAbsolutePosition(image, bounds.getOrigin()); applyElementSize(image, (int) bounds.getWidth(), (int) bounds.getHeight(), true); Dom.setElementAttribute(image, "src", Dom.makeUrlAbsolute(href)); } }
java
public void drawImage(Object parent, String name, String href, Bbox bounds, PictureStyle style) { if (isAttached()) { Element image = helper.createOrUpdateElement(parent, name, "image", style); applyAbsolutePosition(image, bounds.getOrigin()); applyElementSize(image, (int) bounds.getWidth(), (int) bounds.getHeight(), true); Dom.setElementAttribute(image, "src", Dom.makeUrlAbsolute(href)); } }
[ "public", "void", "drawImage", "(", "Object", "parent", ",", "String", "name", ",", "String", "href", ",", "Bbox", "bounds", ",", "PictureStyle", "style", ")", "{", "if", "(", "isAttached", "(", ")", ")", "{", "Element", "image", "=", "helper", ".", "c...
Draw an image onto the the <code>GraphicsContext</code>. @param parent parent group object @param name The image's name. @param href The image's location (URL). @param bounds The bounding box that sets the image's origin (x and y), it's width and it's height. @param style A styling object to be passed along with the image. Can be null.
[ "Draw", "an", "image", "onto", "the", "the", "<code", ">", "GraphicsContext<", "/", "code", ">", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/context/VmlGraphicsContext.java#L266-L273
Samsung/GearVRf
GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/Widget.java
Widget.addChild
protected boolean addChild(final Widget child, final GVRSceneObject childRootSceneObject, final int index) { return addChild(child, childRootSceneObject, index, false); }
java
protected boolean addChild(final Widget child, final GVRSceneObject childRootSceneObject, final int index) { return addChild(child, childRootSceneObject, index, false); }
[ "protected", "boolean", "addChild", "(", "final", "Widget", "child", ",", "final", "GVRSceneObject", "childRootSceneObject", ",", "final", "int", "index", ")", "{", "return", "addChild", "(", "child", ",", "childRootSceneObject", ",", "index", ",", "false", ")",...
Add another {@link Widget} as a child of this one. Convenience method for {@link #addChild(Widget, GVRSceneObject, int, boolean) addChild(child, childRootSceneObject, index, false)}. @param child The {@code Widget} to add as a child. @param childRootSceneObject The root {@link GVRSceneObject} of the child. @param index Position at which to add the child. Pass -1 to add at end. @return {@code True} if {@code child} was added; {@code false} if {@code child} was previously added to this instance.
[ "Add", "another", "{", "@link", "Widget", "}", "as", "a", "child", "of", "this", "one", ".", "Convenience", "method", "for", "{", "@link", "#addChild", "(", "Widget", "GVRSceneObject", "int", "boolean", ")", "addChild", "(", "child", "childRootSceneObject", ...
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/Widget.java#L2954-L2957
netty/netty
buffer/src/main/java/io/netty/buffer/Unpooled.java
Unpooled.wrappedBuffer
public static ByteBuf wrappedBuffer(byte[] array) { if (array.length == 0) { return EMPTY_BUFFER; } return new UnpooledHeapByteBuf(ALLOC, array, array.length); }
java
public static ByteBuf wrappedBuffer(byte[] array) { if (array.length == 0) { return EMPTY_BUFFER; } return new UnpooledHeapByteBuf(ALLOC, array, array.length); }
[ "public", "static", "ByteBuf", "wrappedBuffer", "(", "byte", "[", "]", "array", ")", "{", "if", "(", "array", ".", "length", "==", "0", ")", "{", "return", "EMPTY_BUFFER", ";", "}", "return", "new", "UnpooledHeapByteBuf", "(", "ALLOC", ",", "array", ",",...
Creates a new big-endian buffer which wraps the specified {@code array}. A modification on the specified array's content will be visible to the returned buffer.
[ "Creates", "a", "new", "big", "-", "endian", "buffer", "which", "wraps", "the", "specified", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/buffer/src/main/java/io/netty/buffer/Unpooled.java#L153-L158
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkManager.java
BookmarkManager.addBookmarkedURL
public void addBookmarkedURL(String URL, String name, boolean isRSS) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { retrieveBookmarks(); BookmarkedURL bookmark = new BookmarkedURL(URL, name, isRSS); List<BookmarkedURL> urls = bookmarks.getBookmarkedURLS(); if (urls.contains(bookmark)) { BookmarkedURL oldURL = urls.get(urls.indexOf(bookmark)); if (oldURL.isShared()) { throw new IllegalArgumentException("Cannot modify shared bookmarks"); } oldURL.setName(name); oldURL.setRss(isRSS); } else { bookmarks.addBookmarkedURL(bookmark); } privateDataManager.setPrivateData(bookmarks); }
java
public void addBookmarkedURL(String URL, String name, boolean isRSS) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { retrieveBookmarks(); BookmarkedURL bookmark = new BookmarkedURL(URL, name, isRSS); List<BookmarkedURL> urls = bookmarks.getBookmarkedURLS(); if (urls.contains(bookmark)) { BookmarkedURL oldURL = urls.get(urls.indexOf(bookmark)); if (oldURL.isShared()) { throw new IllegalArgumentException("Cannot modify shared bookmarks"); } oldURL.setName(name); oldURL.setRss(isRSS); } else { bookmarks.addBookmarkedURL(bookmark); } privateDataManager.setPrivateData(bookmarks); }
[ "public", "void", "addBookmarkedURL", "(", "String", "URL", ",", "String", "name", ",", "boolean", "isRSS", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "retrieveBookmarks", "(", ")", ...
Adds a new url or updates an already existing url in the bookmarks. @param URL the url of the bookmark @param name the name of the bookmark @param isRSS whether or not the url is an rss feed @throws XMPPErrorException thrown when there is an error retriving or saving bookmarks from or to the server @throws NoResponseException if there was no response from the server. @throws NotConnectedException @throws InterruptedException
[ "Adds", "a", "new", "url", "or", "updates", "an", "already", "existing", "url", "in", "the", "bookmarks", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkManager.java#L191-L207
ttddyy/datasource-proxy
src/main/java/net/ttddyy/dsproxy/listener/logging/DefaultQueryLogEntryCreator.java
DefaultQueryLogEntryCreator.writeConnectionIdEntry
protected void writeConnectionIdEntry(StringBuilder sb, ExecutionInfo execInfo, List<QueryInfo> queryInfoList) { sb.append("Connection:"); sb.append(execInfo.getConnectionId()); sb.append(", "); }
java
protected void writeConnectionIdEntry(StringBuilder sb, ExecutionInfo execInfo, List<QueryInfo> queryInfoList) { sb.append("Connection:"); sb.append(execInfo.getConnectionId()); sb.append(", "); }
[ "protected", "void", "writeConnectionIdEntry", "(", "StringBuilder", "sb", ",", "ExecutionInfo", "execInfo", ",", "List", "<", "QueryInfo", ">", "queryInfoList", ")", "{", "sb", ".", "append", "(", "\"Connection:\"", ")", ";", "sb", ".", "append", "(", "execIn...
Write connection ID when enabled. <p>default: Connection: 1, @param sb StringBuilder to write @param execInfo execution info @param queryInfoList query info list @since 1.4.2
[ "Write", "connection", "ID", "when", "enabled", "." ]
train
https://github.com/ttddyy/datasource-proxy/blob/62163ccf9a569a99aa3ad9f9151a32567447a62e/src/main/java/net/ttddyy/dsproxy/listener/logging/DefaultQueryLogEntryCreator.java#L107-L111
apache/flink
flink-core/src/main/java/org/apache/flink/util/FileUtils.java
FileUtils.deletePathIfEmpty
public static boolean deletePathIfEmpty(FileSystem fileSystem, Path path) throws IOException { final FileStatus[] fileStatuses; try { fileStatuses = fileSystem.listStatus(path); } catch (FileNotFoundException e) { // path already deleted return true; } catch (Exception e) { // could not access directory, cannot delete return false; } // if there are no more files or if we couldn't list the file status try to delete the path if (fileStatuses == null) { // another indicator of "file not found" return true; } else if (fileStatuses.length == 0) { // attempt to delete the path (will fail and be ignored if the path now contains // some files (possibly added concurrently)) return fileSystem.delete(path, false); } else { return false; } }
java
public static boolean deletePathIfEmpty(FileSystem fileSystem, Path path) throws IOException { final FileStatus[] fileStatuses; try { fileStatuses = fileSystem.listStatus(path); } catch (FileNotFoundException e) { // path already deleted return true; } catch (Exception e) { // could not access directory, cannot delete return false; } // if there are no more files or if we couldn't list the file status try to delete the path if (fileStatuses == null) { // another indicator of "file not found" return true; } else if (fileStatuses.length == 0) { // attempt to delete the path (will fail and be ignored if the path now contains // some files (possibly added concurrently)) return fileSystem.delete(path, false); } else { return false; } }
[ "public", "static", "boolean", "deletePathIfEmpty", "(", "FileSystem", "fileSystem", ",", "Path", "path", ")", "throws", "IOException", "{", "final", "FileStatus", "[", "]", "fileStatuses", ";", "try", "{", "fileStatuses", "=", "fileSystem", ".", "listStatus", "...
Deletes the path if it is empty. A path can only be empty if it is a directory which does not contain any other directories/files. @param fileSystem to use @param path to be deleted if empty @return true if the path could be deleted; otherwise false @throws IOException if the delete operation fails
[ "Deletes", "the", "path", "if", "it", "is", "empty", ".", "A", "path", "can", "only", "be", "empty", "if", "it", "is", "a", "directory", "which", "does", "not", "contain", "any", "other", "directories", "/", "files", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/FileUtils.java#L399-L427
Abnaxos/markdown-doclet
doclet/jdk8/src/main/java/ch/raffael/mddoclet/mdtaglet/argval/PredefinedArgumentValidators.java
PredefinedArgumentValidators.anyOf
public static ArgumentValidator anyOf(String description, ArgumentValidator... argumentValidators) { return new AnyOf(Arrays.asList(argumentValidators), description); }
java
public static ArgumentValidator anyOf(String description, ArgumentValidator... argumentValidators) { return new AnyOf(Arrays.asList(argumentValidators), description); }
[ "public", "static", "ArgumentValidator", "anyOf", "(", "String", "description", ",", "ArgumentValidator", "...", "argumentValidators", ")", "{", "return", "new", "AnyOf", "(", "Arrays", ".", "asList", "(", "argumentValidators", ")", ",", "description", ")", ";", ...
# Creates a {@link ArgumentValidator} which iterates over all `argumentValidators` until the first {@link Type#VALID} has been found. This is of course a logical OR. - If all are `VALID` then the result is also `VALID`. - If at least one is `VALID`, then the entire expression is VALID. - If all are *NOT VALID*, the result is the first invalid result, but the error message will be replaced with `description`. @param argumentValidators 1 or more argument validators @param description any description @return a AnyOf validator
[ "#", "Creates", "a", "{", "@link", "ArgumentValidator", "}", "which", "iterates", "over", "all", "argumentValidators", "until", "the", "first", "{", "@link", "Type#VALID", "}", "has", "been", "found", "." ]
train
https://github.com/Abnaxos/markdown-doclet/blob/e98a9630206fc9c8d813cf2349ff594be8630054/doclet/jdk8/src/main/java/ch/raffael/mddoclet/mdtaglet/argval/PredefinedArgumentValidators.java#L289-L291
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/LocalityStats.java
LocalityStats.record
public void record( TaskInProgress tip, String host, long inputBytes) { synchronized (localityRecords) { localityRecords.add(new Record(tip, host, inputBytes)); localityRecords.notify(); } }
java
public void record( TaskInProgress tip, String host, long inputBytes) { synchronized (localityRecords) { localityRecords.add(new Record(tip, host, inputBytes)); localityRecords.notify(); } }
[ "public", "void", "record", "(", "TaskInProgress", "tip", ",", "String", "host", ",", "long", "inputBytes", ")", "{", "synchronized", "(", "localityRecords", ")", "{", "localityRecords", ".", "add", "(", "new", "Record", "(", "tip", ",", "host", ",", "inpu...
Asynchronous update of locality. @param tip The task. @param host The task tracker host. @param inputBytes The number of bytes processed.
[ "Asynchronous", "update", "of", "locality", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/LocalityStats.java#L105-L111
apereo/cas
support/cas-server-support-service-registry-stream/src/main/java/org/apereo/cas/services/publisher/BaseCasRegisteredServiceStreamPublisher.java
BaseCasRegisteredServiceStreamPublisher.publishInternal
protected void publishInternal(final RegisteredService service, final ApplicationEvent event) { if (event instanceof CasRegisteredServiceDeletedEvent) { handleCasRegisteredServiceDeletedEvent(service, event); return; } if (event instanceof CasRegisteredServiceSavedEvent || event instanceof CasRegisteredServiceLoadedEvent) { handleCasRegisteredServiceUpdateEvents(service, event); return; } LOGGER.warn("Unsupported event [{}} for service replication", event); }
java
protected void publishInternal(final RegisteredService service, final ApplicationEvent event) { if (event instanceof CasRegisteredServiceDeletedEvent) { handleCasRegisteredServiceDeletedEvent(service, event); return; } if (event instanceof CasRegisteredServiceSavedEvent || event instanceof CasRegisteredServiceLoadedEvent) { handleCasRegisteredServiceUpdateEvents(service, event); return; } LOGGER.warn("Unsupported event [{}} for service replication", event); }
[ "protected", "void", "publishInternal", "(", "final", "RegisteredService", "service", ",", "final", "ApplicationEvent", "event", ")", "{", "if", "(", "event", "instanceof", "CasRegisteredServiceDeletedEvent", ")", "{", "handleCasRegisteredServiceDeletedEvent", "(", "servi...
Publish internal. @param service the service @param event the event
[ "Publish", "internal", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-service-registry-stream/src/main/java/org/apereo/cas/services/publisher/BaseCasRegisteredServiceStreamPublisher.java#L44-L55
openengsb/openengsb
components/ekb/modelregistry-tracker/src/main/java/org/openengsb/core/ekb/modelregistry/tracker/internal/ModelRegistryService.java
ModelRegistryService.loadModelsOfBundle
private Set<ModelDescription> loadModelsOfBundle(Bundle bundle) { Enumeration<URL> classEntries = bundle.findEntries("/", "*.class", true); Set<ModelDescription> models = new HashSet<ModelDescription>(); if (classEntries == null) { LOGGER.debug("Found no classes in the bundle {}", bundle); return models; } while (classEntries.hasMoreElements()) { URL classURL = classEntries.nextElement(); String classname = extractClassName(classURL); if (isModelClass(classname, bundle)) { models.add(new ModelDescription(classname, bundle.getVersion().toString())); } } return models; }
java
private Set<ModelDescription> loadModelsOfBundle(Bundle bundle) { Enumeration<URL> classEntries = bundle.findEntries("/", "*.class", true); Set<ModelDescription> models = new HashSet<ModelDescription>(); if (classEntries == null) { LOGGER.debug("Found no classes in the bundle {}", bundle); return models; } while (classEntries.hasMoreElements()) { URL classURL = classEntries.nextElement(); String classname = extractClassName(classURL); if (isModelClass(classname, bundle)) { models.add(new ModelDescription(classname, bundle.getVersion().toString())); } } return models; }
[ "private", "Set", "<", "ModelDescription", ">", "loadModelsOfBundle", "(", "Bundle", "bundle", ")", "{", "Enumeration", "<", "URL", ">", "classEntries", "=", "bundle", ".", "findEntries", "(", "\"/\"", ",", "\"*.class\"", ",", "true", ")", ";", "Set", "<", ...
Searches the bundle for model classes and return a set of them.
[ "Searches", "the", "bundle", "for", "model", "classes", "and", "return", "a", "set", "of", "them", "." ]
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/modelregistry-tracker/src/main/java/org/openengsb/core/ekb/modelregistry/tracker/internal/ModelRegistryService.java#L95-L110
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/mapreduce/aggregation/Aggregations.java
Aggregations.bigIntegerMax
public static <Key, Value> Aggregation<Key, BigInteger, BigInteger> bigIntegerMax() { return new AggregationAdapter(new BigIntegerMaxAggregation<Key, Value>()); }
java
public static <Key, Value> Aggregation<Key, BigInteger, BigInteger> bigIntegerMax() { return new AggregationAdapter(new BigIntegerMaxAggregation<Key, Value>()); }
[ "public", "static", "<", "Key", ",", "Value", ">", "Aggregation", "<", "Key", ",", "BigInteger", ",", "BigInteger", ">", "bigIntegerMax", "(", ")", "{", "return", "new", "AggregationAdapter", "(", "new", "BigIntegerMaxAggregation", "<", "Key", ",", "Value", ...
Returns an aggregation to find the {@link java.math.BigInteger} maximum of all supplied values.<br/> This aggregation is similar to: <pre>SELECT MAX(value) FROM x</pre> @param <Key> the input key type @param <Value> the supplied value type @return the maximum value over all supplied values
[ "Returns", "an", "aggregation", "to", "find", "the", "{", "@link", "java", ".", "math", ".", "BigInteger", "}", "maximum", "of", "all", "supplied", "values", ".", "<br", "/", ">", "This", "aggregation", "is", "similar", "to", ":", "<pre", ">", "SELECT", ...
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/mapreduce/aggregation/Aggregations.java#L338-L340
teatrove/teatrove
trove/src/main/java/org/teatrove/trove/classfile/ClassFile.java
ClassFile.setVersion
public void setVersion(int major, int minor) throws IllegalArgumentException { if (major != JDK1_1_MAJOR_VERSION || minor != JDK1_1_MINOR_VERSION) { throw new IllegalArgumentException("Version " + major + ", " + minor + " is not supported"); } mMajorVersion = major; mMinorVersion = minor; }
java
public void setVersion(int major, int minor) throws IllegalArgumentException { if (major != JDK1_1_MAJOR_VERSION || minor != JDK1_1_MINOR_VERSION) { throw new IllegalArgumentException("Version " + major + ", " + minor + " is not supported"); } mMajorVersion = major; mMinorVersion = minor; }
[ "public", "void", "setVersion", "(", "int", "major", ",", "int", "minor", ")", "throws", "IllegalArgumentException", "{", "if", "(", "major", "!=", "JDK1_1_MAJOR_VERSION", "||", "minor", "!=", "JDK1_1_MINOR_VERSION", ")", "{", "throw", "new", "IllegalArgumentExcep...
Sets the version to use when writing the generated ClassFile. Currently, only version 45, 3 is supported, and is set by default. @exception IllegalArgumentException when the version isn't supported
[ "Sets", "the", "version", "to", "use", "when", "writing", "the", "generated", "ClassFile", ".", "Currently", "only", "version", "45", "3", "is", "supported", "and", "is", "set", "by", "default", "." ]
train
https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/ClassFile.java#L806-L818
jcuda/jcuda
JCudaJava/src/main/java/jcuda/runtime/JCuda.java
JCuda.cudaDeviceGetPCIBusId
public static int cudaDeviceGetPCIBusId(String pciBusId[], int len, int device) { return checkResult(cudaDeviceGetPCIBusIdNative(pciBusId, len, device)); }
java
public static int cudaDeviceGetPCIBusId(String pciBusId[], int len, int device) { return checkResult(cudaDeviceGetPCIBusIdNative(pciBusId, len, device)); }
[ "public", "static", "int", "cudaDeviceGetPCIBusId", "(", "String", "pciBusId", "[", "]", ",", "int", "len", ",", "int", "device", ")", "{", "return", "checkResult", "(", "cudaDeviceGetPCIBusIdNative", "(", "pciBusId", ",", "len", ",", "device", ")", ")", ";"...
Returns a PCI Bus Id string for the device. <pre> cudaError_t cudaDeviceGetPCIBusId ( char* pciBusId, int len, int device ) </pre> <div> <p>Returns a PCI Bus Id string for the device. Returns an ASCII string identifying the device <tt>dev</tt> in the NULL-terminated string pointed to by <tt>pciBusId</tt>. <tt>len</tt> specifies the maximum length of the string that may be returned. </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param pciBusId Returned identifier string for the device in the following format [domain]:[bus]:[device].[function] where domain, bus, device, and function are all hexadecimal values. pciBusId should be large enough to store 13 characters including the NULL-terminator. @param len Maximum length of string to store in name @param device Device to get identifier string for @return cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidDevice @see JCuda#cudaDeviceGetByPCIBusId
[ "Returns", "a", "PCI", "Bus", "Id", "string", "for", "the", "device", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/runtime/JCuda.java#L7957-L7960
samskivert/pythagoras
src/main/java/pythagoras/d/Rectangles.java
Rectangles.closestInteriorPoint
public static Point closestInteriorPoint (IRectangle r, IPoint p) { return closestInteriorPoint(r, p, new Point()); }
java
public static Point closestInteriorPoint (IRectangle r, IPoint p) { return closestInteriorPoint(r, p, new Point()); }
[ "public", "static", "Point", "closestInteriorPoint", "(", "IRectangle", "r", ",", "IPoint", "p", ")", "{", "return", "closestInteriorPoint", "(", "r", ",", "p", ",", "new", "Point", "(", ")", ")", ";", "}" ]
Computes and returns the point inside the bounds of the rectangle that's closest to the given point.
[ "Computes", "and", "returns", "the", "point", "inside", "the", "bounds", "of", "the", "rectangle", "that", "s", "closest", "to", "the", "given", "point", "." ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/d/Rectangles.java#L49-L51
sculptor/sculptor
sculptor-framework/sculptor-framework-main/src/main/java/org/sculptor/framework/accessimpl/jpa/JpaHelper.java
JpaHelper.findProperty
public static Method findProperty(Class<?> clazz, String name) { assert clazz != null; assert name != null; Class<?> entityClass = clazz; while (entityClass != null) { Method[] methods = (entityClass.isInterface() ? entityClass.getMethods() : entityClass.getDeclaredMethods()); for (Method method : methods) { if (method.getName().equals("get"+ StringUtils.capitalize(name)) || method.getName().equals("is"+ StringUtils.capitalize(name))) { return method; } } entityClass = entityClass.getSuperclass(); } return null; }
java
public static Method findProperty(Class<?> clazz, String name) { assert clazz != null; assert name != null; Class<?> entityClass = clazz; while (entityClass != null) { Method[] methods = (entityClass.isInterface() ? entityClass.getMethods() : entityClass.getDeclaredMethods()); for (Method method : methods) { if (method.getName().equals("get"+ StringUtils.capitalize(name)) || method.getName().equals("is"+ StringUtils.capitalize(name))) { return method; } } entityClass = entityClass.getSuperclass(); } return null; }
[ "public", "static", "Method", "findProperty", "(", "Class", "<", "?", ">", "clazz", ",", "String", "name", ")", "{", "assert", "clazz", "!=", "null", ";", "assert", "name", "!=", "null", ";", "Class", "<", "?", ">", "entityClass", "=", "clazz", ";", ...
tries to find a property method by name @param clazz type @param name name of the property @return
[ "tries", "to", "find", "a", "property", "method", "by", "name" ]
train
https://github.com/sculptor/sculptor/blob/38df06ceb7e40f5f52dbd53b1cd1d07ee11aade5/sculptor-framework/sculptor-framework-main/src/main/java/org/sculptor/framework/accessimpl/jpa/JpaHelper.java#L135-L150
citrusframework/citrus
modules/citrus-core/src/main/java/com/consol/citrus/variable/dictionary/AbstractDataDictionary.java
AbstractDataDictionary.convertIfNecessary
protected <T> T convertIfNecessary(String value, T originalValue) { if (originalValue == null) { return (T) value; } return TypeConversionUtils.convertIfNecessary(value, (Class<T>) originalValue.getClass()); }
java
protected <T> T convertIfNecessary(String value, T originalValue) { if (originalValue == null) { return (T) value; } return TypeConversionUtils.convertIfNecessary(value, (Class<T>) originalValue.getClass()); }
[ "protected", "<", "T", ">", "T", "convertIfNecessary", "(", "String", "value", ",", "T", "originalValue", ")", "{", "if", "(", "originalValue", "==", "null", ")", "{", "return", "(", "T", ")", "value", ";", "}", "return", "TypeConversionUtils", ".", "con...
Convert to original value type if necessary. @param value @param originalValue @param <T> @return
[ "Convert", "to", "original", "value", "type", "if", "necessary", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/variable/dictionary/AbstractDataDictionary.java#L62-L68
mygreen/excel-cellformatter
src/main/java/com/github/mygreen/cellformatter/ConditionFormatterFactory.java
ConditionFormatterFactory.setupConditionOperator
protected ConditionOperator setupConditionOperator(final ConditionFormatter formatter, final Token.Condition token) { final Matcher matcher = PATTERN_CONDITION_OPERATOR.matcher(token.getValue()); if(!matcher.matches()) { throw new IllegalArgumentException("not match condition:" + token.getValue()); } final String operator = matcher.group(1); final String number = matcher.group(2); final double condition = Double.valueOf(number); final ConditionOperator conditionOperator; switch(operator) { case "=": conditionOperator = new ConditionOperator.Equal(condition); break; case "<>": conditionOperator = new ConditionOperator.NotEqual(condition); break; case ">": conditionOperator = new ConditionOperator.GreaterThan(condition); break; case "<": conditionOperator = new ConditionOperator.LessThan(condition); break; case ">=": conditionOperator = new ConditionOperator.GreaterEqual(condition); break; case "<=": conditionOperator = new ConditionOperator.LessEqual(condition); break; default: logger.warn("unknown operator : {}", operator); conditionOperator = ConditionOperator.ALL; break; } formatter.setOperator(conditionOperator); return conditionOperator; }
java
protected ConditionOperator setupConditionOperator(final ConditionFormatter formatter, final Token.Condition token) { final Matcher matcher = PATTERN_CONDITION_OPERATOR.matcher(token.getValue()); if(!matcher.matches()) { throw new IllegalArgumentException("not match condition:" + token.getValue()); } final String operator = matcher.group(1); final String number = matcher.group(2); final double condition = Double.valueOf(number); final ConditionOperator conditionOperator; switch(operator) { case "=": conditionOperator = new ConditionOperator.Equal(condition); break; case "<>": conditionOperator = new ConditionOperator.NotEqual(condition); break; case ">": conditionOperator = new ConditionOperator.GreaterThan(condition); break; case "<": conditionOperator = new ConditionOperator.LessThan(condition); break; case ">=": conditionOperator = new ConditionOperator.GreaterEqual(condition); break; case "<=": conditionOperator = new ConditionOperator.LessEqual(condition); break; default: logger.warn("unknown operator : {}", operator); conditionOperator = ConditionOperator.ALL; break; } formatter.setOperator(conditionOperator); return conditionOperator; }
[ "protected", "ConditionOperator", "setupConditionOperator", "(", "final", "ConditionFormatter", "formatter", ",", "final", "Token", ".", "Condition", "token", ")", "{", "final", "Matcher", "matcher", "=", "PATTERN_CONDITION_OPERATOR", ".", "matcher", "(", "token", "."...
{@literal '[<=1000]'}などの数値の条件を組み立てる @param formatter 現在の組み立て中のフォーマッタのインスタンス。 @param token 条件式のトークン。 @return 演算子の条件式。 @throws IllegalArgumentException 処理対象の条件として一致しない場合
[ "{" ]
train
https://github.com/mygreen/excel-cellformatter/blob/e802af273d49889500591e03799c9262cbf29185/src/main/java/com/github/mygreen/cellformatter/ConditionFormatterFactory.java#L122-L162
oaqa/uima-ecd
src/main/java/edu/cmu/lti/oaqa/ecd/driver/SimplePipelineRev803.java
SimplePipelineRev803.runPipeline
public static void runPipeline(final CollectionReaderDescription readerDesc, final AnalysisEngineDescription... descs) throws UIMAException, IOException { // Create the components final CollectionReader reader = createCollectionReader(readerDesc); try { // Run the pipeline runPipeline(reader, descs); } finally { close(reader); destroy(reader); } }
java
public static void runPipeline(final CollectionReaderDescription readerDesc, final AnalysisEngineDescription... descs) throws UIMAException, IOException { // Create the components final CollectionReader reader = createCollectionReader(readerDesc); try { // Run the pipeline runPipeline(reader, descs); } finally { close(reader); destroy(reader); } }
[ "public", "static", "void", "runPipeline", "(", "final", "CollectionReaderDescription", "readerDesc", ",", "final", "AnalysisEngineDescription", "...", "descs", ")", "throws", "UIMAException", ",", "IOException", "{", "// Create the components", "final", "CollectionReader",...
Run the CollectionReader and AnalysisEngines as a pipeline. After processing all CASes provided by the reader, the method calls {@link AnalysisEngine#collectionProcessComplete() collectionProcessComplete()} on the engines, {@link CollectionReader#close() close()} on the reader and {@link Resource#destroy() destroy()} on the reader and all engines. @param readerDesc The CollectionReader that loads the documents into the CAS. @param descs Primitive AnalysisEngineDescriptions that process the CAS, in order. If you have a mix of primitive and aggregate engines, then please create the AnalysisEngines yourself and call the other runPipeline method. @throws UIMAException @throws IOException
[ "Run", "the", "CollectionReader", "and", "AnalysisEngines", "as", "a", "pipeline", ".", "After", "processing", "all", "CASes", "provided", "by", "the", "reader", "the", "method", "calls", "{", "@link", "AnalysisEngine#collectionProcessComplete", "()", "collectionProce...
train
https://github.com/oaqa/uima-ecd/blob/09a0ae26647490b43affc36ab3a01100702b989f/src/main/java/edu/cmu/lti/oaqa/ecd/driver/SimplePipelineRev803.java#L117-L130
Azure/azure-sdk-for-java
batchai/resource-manager/v2018_05_01/src/main/java/com/microsoft/azure/management/batchai/v2018_05_01/implementation/WorkspacesInner.java
WorkspacesInner.beginCreate
public WorkspaceInner beginCreate(String resourceGroupName, String workspaceName, WorkspaceCreateParameters parameters) { return beginCreateWithServiceResponseAsync(resourceGroupName, workspaceName, parameters).toBlocking().single().body(); }
java
public WorkspaceInner beginCreate(String resourceGroupName, String workspaceName, WorkspaceCreateParameters parameters) { return beginCreateWithServiceResponseAsync(resourceGroupName, workspaceName, parameters).toBlocking().single().body(); }
[ "public", "WorkspaceInner", "beginCreate", "(", "String", "resourceGroupName", ",", "String", "workspaceName", ",", "WorkspaceCreateParameters", "parameters", ")", "{", "return", "beginCreateWithServiceResponseAsync", "(", "resourceGroupName", ",", "workspaceName", ",", "pa...
Creates a Workspace. @param resourceGroupName Name of the resource group to which the resource belongs. @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @param parameters Workspace creation parameters. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the WorkspaceInner object if successful.
[ "Creates", "a", "Workspace", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batchai/resource-manager/v2018_05_01/src/main/java/com/microsoft/azure/management/batchai/v2018_05_01/implementation/WorkspacesInner.java#L650-L652
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java
InternalService.updateConversation
public void updateConversation(@NonNull final String conversationId, @NonNull final ConversationUpdate request, @NonNull final String eTag, @Nullable Callback<ComapiResult<ConversationDetails>> callback) { adapter.adapt(updateConversation(conversationId, request, eTag), callback); }
java
public void updateConversation(@NonNull final String conversationId, @NonNull final ConversationUpdate request, @NonNull final String eTag, @Nullable Callback<ComapiResult<ConversationDetails>> callback) { adapter.adapt(updateConversation(conversationId, request, eTag), callback); }
[ "public", "void", "updateConversation", "(", "@", "NonNull", "final", "String", "conversationId", ",", "@", "NonNull", "final", "ConversationUpdate", "request", ",", "@", "NonNull", "final", "String", "eTag", ",", "@", "Nullable", "Callback", "<", "ComapiResult", ...
Returns observable to update a conversation. @param conversationId ID of a conversation to update. @param request Request with conversation details to update. @param eTag ETag for server to check if local version of the data is the same as the one the server side. @param callback Callback to deliver new session instance.
[ "Returns", "observable", "to", "update", "a", "conversation", "." ]
train
https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java#L595-L597
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/util/pathfinding/AStarPathFinder.java
AStarPathFinder.getHeuristicCost
public float getHeuristicCost(Mover mover, int x, int y, int tx, int ty) { return heuristic.getCost(map, mover, x, y, tx, ty); }
java
public float getHeuristicCost(Mover mover, int x, int y, int tx, int ty) { return heuristic.getCost(map, mover, x, y, tx, ty); }
[ "public", "float", "getHeuristicCost", "(", "Mover", "mover", ",", "int", "x", ",", "int", "y", ",", "int", "tx", ",", "int", "ty", ")", "{", "return", "heuristic", ".", "getCost", "(", "map", ",", "mover", ",", "x", ",", "y", ",", "tx", ",", "ty...
Get the heuristic cost for the given location. This determines in which order the locations are processed. @param mover The entity that is being moved @param x The x coordinate of the tile whose cost is being determined @param y The y coordiante of the tile whose cost is being determined @param tx The x coordinate of the target location @param ty The y coordinate of the target location @return The heuristic cost assigned to the tile
[ "Get", "the", "heuristic", "cost", "for", "the", "given", "location", ".", "This", "determines", "in", "which", "order", "the", "locations", "are", "processed", "." ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/util/pathfinding/AStarPathFinder.java#L359-L361
beanshell/beanshell
src/main/java/bsh/NameSpace.java
NameSpace.createVariable
protected Variable createVariable(final String name, final Class<?> type, final LHS lhs) throws UtilEvalError { return new Variable(name, type, lhs); }
java
protected Variable createVariable(final String name, final Class<?> type, final LHS lhs) throws UtilEvalError { return new Variable(name, type, lhs); }
[ "protected", "Variable", "createVariable", "(", "final", "String", "name", ",", "final", "Class", "<", "?", ">", "type", ",", "final", "LHS", "lhs", ")", "throws", "UtilEvalError", "{", "return", "new", "Variable", "(", "name", ",", "type", ",", "lhs", "...
Creates the variable. @param name the name @param type the type @param lhs the lhs @return the variable @throws UtilEvalError the util eval error
[ "Creates", "the", "variable", "." ]
train
https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/NameSpace.java#L427-L430
JDBDT/jdbdt
src/main/java/org/jdbdt/JDBDT.java
JDBDT.deleteAllWhere
@SafeVarargs public static int deleteAllWhere(Table table, String where, Object... args) { return DBSetup.deleteAll(CallInfo.create(), table, where, args); }
java
@SafeVarargs public static int deleteAllWhere(Table table, String where, Object... args) { return DBSetup.deleteAll(CallInfo.create(), table, where, args); }
[ "@", "SafeVarargs", "public", "static", "int", "deleteAllWhere", "(", "Table", "table", ",", "String", "where", ",", "Object", "...", "args", ")", "{", "return", "DBSetup", ".", "deleteAll", "(", "CallInfo", ".", "create", "(", ")", ",", "table", ",", "w...
Delete all data from a table, subject to a <code>WHERE</code> clause. @param table Table. @param where <code>WHERE</code> clause @param args <code>WHERE</code> clause arguments, if any. @return Number of deleted entries. @see #deleteAll(Table) @see #truncate(Table)
[ "Delete", "all", "data", "from", "a", "table", "subject", "to", "a", "<code", ">", "WHERE<", "/", "code", ">", "clause", "." ]
train
https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/JDBDT.java#L1145-L1148
jenkinsci/java-client-api
jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java
JenkinsServer.updateJob
public JenkinsServer updateJob(String jobName, String jobXml) throws IOException { return this.updateJob(jobName, jobXml, true); }
java
public JenkinsServer updateJob(String jobName, String jobXml) throws IOException { return this.updateJob(jobName, jobXml, true); }
[ "public", "JenkinsServer", "updateJob", "(", "String", "jobName", ",", "String", "jobXml", ")", "throws", "IOException", "{", "return", "this", ".", "updateJob", "(", "jobName", ",", "jobXml", ",", "true", ")", ";", "}" ]
Update the xml description of an existing job @param jobName name of the job to be updated. @param jobXml the configuration to be used for updating. @throws IOException in case of an error.
[ "Update", "the", "xml", "description", "of", "an", "existing", "job" ]
train
https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java#L608-L610
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/ArrayBackedSortedColumns.java
ArrayBackedSortedColumns.maybeAppendColumn
public void maybeAppendColumn(Cell cell, DeletionInfo.InOrderTester tester, int gcBefore) { if (cell.getLocalDeletionTime() >= gcBefore && !tester.isDeleted(cell)) { internalAdd(cell); sortedSize++; } }
java
public void maybeAppendColumn(Cell cell, DeletionInfo.InOrderTester tester, int gcBefore) { if (cell.getLocalDeletionTime() >= gcBefore && !tester.isDeleted(cell)) { internalAdd(cell); sortedSize++; } }
[ "public", "void", "maybeAppendColumn", "(", "Cell", "cell", ",", "DeletionInfo", ".", "InOrderTester", "tester", ",", "int", "gcBefore", ")", "{", "if", "(", "cell", ".", "getLocalDeletionTime", "(", ")", ">=", "gcBefore", "&&", "!", "tester", ".", "isDelete...
Adds a cell, assuming that: - it's non-gc-able (if a tombstone) or not a tombstone - it has a more recent timestamp than any partition/range tombstone shadowing it - it sorts *strictly after* the current-last cell in the array.
[ "Adds", "a", "cell", "assuming", "that", ":", "-", "it", "s", "non", "-", "gc", "-", "able", "(", "if", "a", "tombstone", ")", "or", "not", "a", "tombstone", "-", "it", "has", "a", "more", "recent", "timestamp", "than", "any", "partition", "/", "ra...
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/ArrayBackedSortedColumns.java#L282-L289
ACINQ/bitcoin-lib
src/main/java/fr/acinq/Secp256k1Loader.java
Secp256k1Loader.cleanup
static void cleanup() { String tempFolder = getTempDir().getAbsolutePath(); File dir = new File(tempFolder); File[] nativeLibFiles = dir.listFiles(new FilenameFilter() { private final String searchPattern = "secp256k1-"; public boolean accept(File dir, String name) { return name.startsWith(searchPattern) && !name.endsWith(".lck"); } }); if(nativeLibFiles != null) { for(File nativeLibFile : nativeLibFiles) { File lckFile = new File(nativeLibFile.getAbsolutePath() + ".lck"); if(!lckFile.exists()) { try { nativeLibFile.delete(); } catch(SecurityException e) { System.err.println("Failed to delete old native lib" + e.getMessage()); } } } } }
java
static void cleanup() { String tempFolder = getTempDir().getAbsolutePath(); File dir = new File(tempFolder); File[] nativeLibFiles = dir.listFiles(new FilenameFilter() { private final String searchPattern = "secp256k1-"; public boolean accept(File dir, String name) { return name.startsWith(searchPattern) && !name.endsWith(".lck"); } }); if(nativeLibFiles != null) { for(File nativeLibFile : nativeLibFiles) { File lckFile = new File(nativeLibFile.getAbsolutePath() + ".lck"); if(!lckFile.exists()) { try { nativeLibFile.delete(); } catch(SecurityException e) { System.err.println("Failed to delete old native lib" + e.getMessage()); } } } } }
[ "static", "void", "cleanup", "(", ")", "{", "String", "tempFolder", "=", "getTempDir", "(", ")", ".", "getAbsolutePath", "(", ")", ";", "File", "dir", "=", "new", "File", "(", "tempFolder", ")", ";", "File", "[", "]", "nativeLibFiles", "=", "dir", ".",...
Deleted old native libraries e.g. on Windows the DLL file is not removed on VM-Exit (bug #80)
[ "Deleted", "old", "native", "libraries", "e", ".", "g", ".", "on", "Windows", "the", "DLL", "file", "is", "not", "removed", "on", "VM", "-", "Exit", "(", "bug", "#80", ")" ]
train
https://github.com/ACINQ/bitcoin-lib/blob/74a30b28b1001672359b19890ffa3d3951362d65/src/main/java/fr/acinq/Secp256k1Loader.java#L72-L95
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/rules/spelling/suggestions/SuggestionsOrdererFeatureExtractor.java
SuggestionsOrdererFeatureExtractor.computeFeatures
public Pair<List<SuggestedReplacement>, SortedMap<String, Float>> computeFeatures(List<String> suggestions, String word, AnalyzedSentence sentence, int startPos) { if (suggestions.isEmpty()) { return Pair.of(Collections.emptyList(), Collections.emptySortedMap()); } if (topN <= 0) { topN = suggestions.size(); } List<String> topSuggestions = suggestions.subList(0, Math.min(suggestions.size(), topN)); //EditDistance<Integer> levenshteinDistance = new LevenshteinDistance(4); EditDistance levenstheinDistance = new EditDistance(word, EditDistance.DistanceAlgorithm.Damerau); SimilarityScore<Double> jaroWrinklerDistance = new JaroWinklerDistance(); List<Feature> features = new ArrayList<>(topSuggestions.size()); for (String candidate : topSuggestions) { double prob1 = languageModel.getPseudoProbability(Collections.singletonList(candidate)).getProb(); double prob3 = LanguageModelUtils.get3gramProbabilityFor(language, languageModel, startPos, sentence, candidate); //double prob4 = LanguageModelUtils.get4gramProbabilityFor(language, languageModel, startPos, sentence, candidate); long wordCount = ((BaseLanguageModel) languageModel).getCount(candidate); int levenstheinDist = levenstheinDistance.compare(candidate, 3); double jaroWrinklerDist = jaroWrinklerDistance.apply(word, candidate); DetailedDamerauLevenstheinDistance.Distance detailedDistance = DetailedDamerauLevenstheinDistance.compare(word, candidate); features.add(new Feature(prob1, prob3, wordCount, levenstheinDist, detailedDistance, jaroWrinklerDist, candidate)); } if (!"noop".equals(score)) { features.sort(Feature::compareTo); } //logger.trace("Features for '%s' in '%s': %n", word, sentence.getText()); //features.stream().map(Feature::toString).forEach(logger::trace); List<String> words = features.stream().map(Feature::getWord).collect(Collectors.toList()); // compute general features, not tied to candidates SortedMap<String, Float> matchData = new TreeMap<>(); matchData.put("candidateCount", (float) words.size()); List<SuggestedReplacement> suggestionsData = features.stream().map(f -> { SuggestedReplacement s = new SuggestedReplacement(f.getWord()); s.setFeatures(f.getData()); return s; }).collect(Collectors.toList()); return Pair.of(suggestionsData, matchData); }
java
public Pair<List<SuggestedReplacement>, SortedMap<String, Float>> computeFeatures(List<String> suggestions, String word, AnalyzedSentence sentence, int startPos) { if (suggestions.isEmpty()) { return Pair.of(Collections.emptyList(), Collections.emptySortedMap()); } if (topN <= 0) { topN = suggestions.size(); } List<String> topSuggestions = suggestions.subList(0, Math.min(suggestions.size(), topN)); //EditDistance<Integer> levenshteinDistance = new LevenshteinDistance(4); EditDistance levenstheinDistance = new EditDistance(word, EditDistance.DistanceAlgorithm.Damerau); SimilarityScore<Double> jaroWrinklerDistance = new JaroWinklerDistance(); List<Feature> features = new ArrayList<>(topSuggestions.size()); for (String candidate : topSuggestions) { double prob1 = languageModel.getPseudoProbability(Collections.singletonList(candidate)).getProb(); double prob3 = LanguageModelUtils.get3gramProbabilityFor(language, languageModel, startPos, sentence, candidate); //double prob4 = LanguageModelUtils.get4gramProbabilityFor(language, languageModel, startPos, sentence, candidate); long wordCount = ((BaseLanguageModel) languageModel).getCount(candidate); int levenstheinDist = levenstheinDistance.compare(candidate, 3); double jaroWrinklerDist = jaroWrinklerDistance.apply(word, candidate); DetailedDamerauLevenstheinDistance.Distance detailedDistance = DetailedDamerauLevenstheinDistance.compare(word, candidate); features.add(new Feature(prob1, prob3, wordCount, levenstheinDist, detailedDistance, jaroWrinklerDist, candidate)); } if (!"noop".equals(score)) { features.sort(Feature::compareTo); } //logger.trace("Features for '%s' in '%s': %n", word, sentence.getText()); //features.stream().map(Feature::toString).forEach(logger::trace); List<String> words = features.stream().map(Feature::getWord).collect(Collectors.toList()); // compute general features, not tied to candidates SortedMap<String, Float> matchData = new TreeMap<>(); matchData.put("candidateCount", (float) words.size()); List<SuggestedReplacement> suggestionsData = features.stream().map(f -> { SuggestedReplacement s = new SuggestedReplacement(f.getWord()); s.setFeatures(f.getData()); return s; }).collect(Collectors.toList()); return Pair.of(suggestionsData, matchData); }
[ "public", "Pair", "<", "List", "<", "SuggestedReplacement", ">", ",", "SortedMap", "<", "String", ",", "Float", ">", ">", "computeFeatures", "(", "List", "<", "String", ">", "suggestions", ",", "String", "word", ",", "AnalyzedSentence", "sentence", ",", "int...
compute features for training or prediction of a ranking model for suggestions @param suggestions @param word @param sentence @param startPos @return correction candidates, features for the match in general, features specific to candidates
[ "compute", "features", "for", "training", "or", "prediction", "of", "a", "ranking", "model", "for", "suggestions" ]
train
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/spelling/suggestions/SuggestionsOrdererFeatureExtractor.java#L92-L133
couchbase/CouchbaseMock
src/main/java/com/couchbase/mock/DocumentLoader.java
DocumentLoader.main
public static void main(String[] args) throws Exception { String input = args[0]; File outputFile = new File(input.replace(".zip", "") + ".serialized.xz"); // Get the base name FileOutputStream fos = new FileOutputStream(outputFile); LZMA2Options options = new LZMA2Options(9); XZOutputStream xzo = new XZOutputStream(fos, options); ObjectOutputStream oos = new ObjectOutputStream(xzo); BundleSerializer ml = new BundleSerializer(); ml.loadDocuments(input); oos.writeObject(ml.toStore); oos.flush(); oos.close(); }
java
public static void main(String[] args) throws Exception { String input = args[0]; File outputFile = new File(input.replace(".zip", "") + ".serialized.xz"); // Get the base name FileOutputStream fos = new FileOutputStream(outputFile); LZMA2Options options = new LZMA2Options(9); XZOutputStream xzo = new XZOutputStream(fos, options); ObjectOutputStream oos = new ObjectOutputStream(xzo); BundleSerializer ml = new BundleSerializer(); ml.loadDocuments(input); oos.writeObject(ml.toStore); oos.flush(); oos.close(); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "String", "input", "=", "args", "[", "0", "]", ";", "File", "outputFile", "=", "new", "File", "(", "input", ".", "replace", "(", "\".zip\"", ",", "\...
Converts a zip file into a serialized compress resource. @param args The ZIP file @throws Exception if an error occurs
[ "Converts", "a", "zip", "file", "into", "a", "serialized", "compress", "resource", "." ]
train
https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/DocumentLoader.java#L186-L202
kiegroup/drools
kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/assembler/DMNResourceDependenciesSorter.java
DMNResourceDependenciesSorter.dfVisit
private static void dfVisit(DMNResource node, List<DMNResource> allNodes, Collection<DMNResource> visited, List<DMNResource> dfv) { if (visited.contains(node)) { throw new RuntimeException("Circular dependency detected: " + visited + " , and again to: " + node); } visited.add(node); List<DMNResource> neighbours = node.getDependencies().stream() .flatMap(dep -> allNodes.stream().filter(r -> r.getModelID().equals(dep))) .collect(Collectors.toList()); for (DMNResource n : neighbours) { if (!visited.contains(n)) { dfVisit(n, allNodes, visited, dfv); } } dfv.add(node); }
java
private static void dfVisit(DMNResource node, List<DMNResource> allNodes, Collection<DMNResource> visited, List<DMNResource> dfv) { if (visited.contains(node)) { throw new RuntimeException("Circular dependency detected: " + visited + " , and again to: " + node); } visited.add(node); List<DMNResource> neighbours = node.getDependencies().stream() .flatMap(dep -> allNodes.stream().filter(r -> r.getModelID().equals(dep))) .collect(Collectors.toList()); for (DMNResource n : neighbours) { if (!visited.contains(n)) { dfVisit(n, allNodes, visited, dfv); } } dfv.add(node); }
[ "private", "static", "void", "dfVisit", "(", "DMNResource", "node", ",", "List", "<", "DMNResource", ">", "allNodes", ",", "Collection", "<", "DMNResource", ">", "visited", ",", "List", "<", "DMNResource", ">", "dfv", ")", "{", "if", "(", "visited", ".", ...
Performs a depth first visit, but keeping a separate reference of visited/visiting nodes, _also_ to avoid potential issues of circularities.
[ "Performs", "a", "depth", "first", "visit", "but", "keeping", "a", "separate", "reference", "of", "visited", "/", "visiting", "nodes", "_also_", "to", "avoid", "potential", "issues", "of", "circularities", "." ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/assembler/DMNResourceDependenciesSorter.java#L32-L48
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/layout/Layout.java
Layout.getGeneration
public Layout getGeneration(int generation) throws FetchNoneException, FetchException { try { Storage<StoredLayoutEquivalence> equivStorage = mLayoutFactory.mRepository.storageFor(StoredLayoutEquivalence.class); StoredLayoutEquivalence equiv = equivStorage.prepare(); equiv.setStorableTypeName(getStorableTypeName()); equiv.setGeneration(generation); if (equiv.tryLoad()) { generation = equiv.getMatchedGeneration(); } } catch (RepositoryException e) { throw e.toFetchException(); } return new Layout(mLayoutFactory, getStoredLayoutByGeneration(generation)); }
java
public Layout getGeneration(int generation) throws FetchNoneException, FetchException { try { Storage<StoredLayoutEquivalence> equivStorage = mLayoutFactory.mRepository.storageFor(StoredLayoutEquivalence.class); StoredLayoutEquivalence equiv = equivStorage.prepare(); equiv.setStorableTypeName(getStorableTypeName()); equiv.setGeneration(generation); if (equiv.tryLoad()) { generation = equiv.getMatchedGeneration(); } } catch (RepositoryException e) { throw e.toFetchException(); } return new Layout(mLayoutFactory, getStoredLayoutByGeneration(generation)); }
[ "public", "Layout", "getGeneration", "(", "int", "generation", ")", "throws", "FetchNoneException", ",", "FetchException", "{", "try", "{", "Storage", "<", "StoredLayoutEquivalence", ">", "equivStorage", "=", "mLayoutFactory", ".", "mRepository", ".", "storageFor", ...
Returns the layout for a particular generation of this layout's type. @throws FetchNoneException if generation not found
[ "Returns", "the", "layout", "for", "a", "particular", "generation", "of", "this", "layout", "s", "type", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/layout/Layout.java#L325-L340
Alluxio/alluxio
core/common/src/main/java/alluxio/extensions/ExtensionFactoryRegistry.java
ExtensionFactoryRegistry.scan
private void scan(List<File> files, List<T> factories) { for (File jar : files) { try { URL extensionURL = jar.toURI().toURL(); String jarPath = extensionURL.toString(); ClassLoader extensionsClassLoader = new ExtensionsClassLoader(new URL[] {extensionURL}, ClassLoader.getSystemClassLoader()); ServiceLoader<T> extensionServiceLoader = ServiceLoader.load(mFactoryClass, extensionsClassLoader); for (T factory : extensionServiceLoader) { LOG.debug("Discovered a factory implementation {} - {} in jar {}", factory.getClass(), factory, jarPath); register(factory, factories); } } catch (Throwable t) { LOG.warn("Failed to load jar {}: {}", jar, t.toString()); } } }
java
private void scan(List<File> files, List<T> factories) { for (File jar : files) { try { URL extensionURL = jar.toURI().toURL(); String jarPath = extensionURL.toString(); ClassLoader extensionsClassLoader = new ExtensionsClassLoader(new URL[] {extensionURL}, ClassLoader.getSystemClassLoader()); ServiceLoader<T> extensionServiceLoader = ServiceLoader.load(mFactoryClass, extensionsClassLoader); for (T factory : extensionServiceLoader) { LOG.debug("Discovered a factory implementation {} - {} in jar {}", factory.getClass(), factory, jarPath); register(factory, factories); } } catch (Throwable t) { LOG.warn("Failed to load jar {}: {}", jar, t.toString()); } } }
[ "private", "void", "scan", "(", "List", "<", "File", ">", "files", ",", "List", "<", "T", ">", "factories", ")", "{", "for", "(", "File", "jar", ":", "files", ")", "{", "try", "{", "URL", "extensionURL", "=", "jar", ".", "toURI", "(", ")", ".", ...
Class-loads jar files that have not been loaded. @param files jar files to class-load @param factories list of factories to add to
[ "Class", "-", "loads", "jar", "files", "that", "have", "not", "been", "loaded", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/extensions/ExtensionFactoryRegistry.java#L191-L210
Red5/red5-server-common
src/main/java/org/red5/server/so/SharedObjectScope.java
SharedObjectScope.isWriteAllowed
protected boolean isWriteAllowed(String key, Object value) { // check internal handlers first for (ISharedObjectSecurity handler : securityHandlers) { if (!handler.isWriteAllowed(this, key, value)) { return false; } } // check global SO handlers next final Set<ISharedObjectSecurity> handlers = getSecurityHandlers(); if (handlers == null) { return true; } for (ISharedObjectSecurity handler : handlers) { if (!handler.isWriteAllowed(this, key, value)) { return false; } } return true; }
java
protected boolean isWriteAllowed(String key, Object value) { // check internal handlers first for (ISharedObjectSecurity handler : securityHandlers) { if (!handler.isWriteAllowed(this, key, value)) { return false; } } // check global SO handlers next final Set<ISharedObjectSecurity> handlers = getSecurityHandlers(); if (handlers == null) { return true; } for (ISharedObjectSecurity handler : handlers) { if (!handler.isWriteAllowed(this, key, value)) { return false; } } return true; }
[ "protected", "boolean", "isWriteAllowed", "(", "String", "key", ",", "Object", "value", ")", "{", "// check internal handlers first\r", "for", "(", "ISharedObjectSecurity", "handler", ":", "securityHandlers", ")", "{", "if", "(", "!", "handler", ".", "isWriteAllowed...
Call handlers and check if writing to the SO is allowed. @param key key @param value value @return is write allowed
[ "Call", "handlers", "and", "check", "if", "writing", "to", "the", "SO", "is", "allowed", "." ]
train
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/so/SharedObjectScope.java#L529-L547
rythmengine/rythmengine
src/main/java/org/rythmengine/template/TemplateBase.java
TemplateBase.__getAs
protected final <T> T __getAs(String name, Class<T> c) { Object o = __getRenderArg(name); if (null == o) return null; return (T) o; }
java
protected final <T> T __getAs(String name, Class<T> c) { Object o = __getRenderArg(name); if (null == o) return null; return (T) o; }
[ "protected", "final", "<", "T", ">", "T", "__getAs", "(", "String", "name", ",", "Class", "<", "T", ">", "c", ")", "{", "Object", "o", "=", "__getRenderArg", "(", "name", ")", ";", "if", "(", "null", "==", "o", ")", "return", "null", ";", "return...
Get render arg and do type cast to the class specified @param name @param c @param <T> @return a render argument
[ "Get", "render", "arg", "and", "do", "type", "cast", "to", "the", "class", "specified" ]
train
https://github.com/rythmengine/rythmengine/blob/064b565f08d9da07378bf77a9dd856ea5831cc92/src/main/java/org/rythmengine/template/TemplateBase.java#L1065-L1069
webjars/webjars-locator
src/main/java/org/webjars/RequireJS.java
RequireJS.getSetupJavaScript
public synchronized static String getSetupJavaScript(String cdnPrefix, String urlPrefix) { if (requireConfigJavaScriptCdn == null) { List<String> prefixes = new ArrayList<>(); prefixes.add(cdnPrefix); prefixes.add(urlPrefix); requireConfigJavaScriptCdn = generateSetupJavaScript(prefixes); } return requireConfigJavaScriptCdn; }
java
public synchronized static String getSetupJavaScript(String cdnPrefix, String urlPrefix) { if (requireConfigJavaScriptCdn == null) { List<String> prefixes = new ArrayList<>(); prefixes.add(cdnPrefix); prefixes.add(urlPrefix); requireConfigJavaScriptCdn = generateSetupJavaScript(prefixes); } return requireConfigJavaScriptCdn; }
[ "public", "synchronized", "static", "String", "getSetupJavaScript", "(", "String", "cdnPrefix", ",", "String", "urlPrefix", ")", "{", "if", "(", "requireConfigJavaScriptCdn", "==", "null", ")", "{", "List", "<", "String", ">", "prefixes", "=", "new", "ArrayList"...
Returns the JavaScript that is used to setup the RequireJS config. This value is cached in memory so that all of the processing to get the String only has to happen once. @param urlPrefix The URL prefix where the WebJars can be downloaded from with a trailing slash, e.g. /webJars/ @param cdnPrefix The optional CDN prefix where the WebJars can be downloaded from @return The JavaScript block that can be embedded or loaded in a &lt;script&gt; tag
[ "Returns", "the", "JavaScript", "that", "is", "used", "to", "setup", "the", "RequireJS", "config", ".", "This", "value", "is", "cached", "in", "memory", "so", "that", "all", "of", "the", "processing", "to", "get", "the", "String", "only", "has", "to", "h...
train
https://github.com/webjars/webjars-locator/blob/8796fb3ff1b9ad5c0d433ecf63a60520c715e3a0/src/main/java/org/webjars/RequireJS.java#L63-L72
gallandarakhneorg/afc
core/text/src/main/java/org/arakhne/afc/text/TextUtil.java
TextUtil.getLevenshteinDistance
public static int getLevenshteinDistance(String firstString, String secondString) { final String s0 = firstString == null ? "" : firstString; //$NON-NLS-1$ final String s1 = secondString == null ? "" : secondString; //$NON-NLS-1$ final int len0 = s0.length() + 1; final int len1 = s1.length() + 1; // the array of distances int[] cost = new int[len0]; int[] newcost = new int[len0]; // initial cost of skipping prefix in String s0 for (int i = 0; i < len0; ++i) { cost[i] = i; } // dynamically computing the array of distances // transformation cost for each letter in s1 for (int j = 1; j < len1; ++j) { // initial cost of skipping prefix in String s1 newcost[0] = j; // transformation cost for each letter in s0 for (int i = 1; i < len0; ++i) { // matching current letters in both strings final int match = (s0.charAt(i - 1) == s1.charAt(j - 1)) ? 0 : 1; // computing cost for each transformation final int costReplace = cost[i - 1] + match; final int costInsert = cost[i] + 1; final int costDelete = newcost[i - 1] + 1; // keep minimum cost newcost[i] = Math.min(Math.min(costInsert, costDelete), costReplace); } // swap cost/newcost arrays final int[] swap = cost; cost = newcost; newcost = swap; } // the distance is the cost for transforming all letters in both strings return cost[len0 - 1]; }
java
public static int getLevenshteinDistance(String firstString, String secondString) { final String s0 = firstString == null ? "" : firstString; //$NON-NLS-1$ final String s1 = secondString == null ? "" : secondString; //$NON-NLS-1$ final int len0 = s0.length() + 1; final int len1 = s1.length() + 1; // the array of distances int[] cost = new int[len0]; int[] newcost = new int[len0]; // initial cost of skipping prefix in String s0 for (int i = 0; i < len0; ++i) { cost[i] = i; } // dynamically computing the array of distances // transformation cost for each letter in s1 for (int j = 1; j < len1; ++j) { // initial cost of skipping prefix in String s1 newcost[0] = j; // transformation cost for each letter in s0 for (int i = 1; i < len0; ++i) { // matching current letters in both strings final int match = (s0.charAt(i - 1) == s1.charAt(j - 1)) ? 0 : 1; // computing cost for each transformation final int costReplace = cost[i - 1] + match; final int costInsert = cost[i] + 1; final int costDelete = newcost[i - 1] + 1; // keep minimum cost newcost[i] = Math.min(Math.min(costInsert, costDelete), costReplace); } // swap cost/newcost arrays final int[] swap = cost; cost = newcost; newcost = swap; } // the distance is the cost for transforming all letters in both strings return cost[len0 - 1]; }
[ "public", "static", "int", "getLevenshteinDistance", "(", "String", "firstString", ",", "String", "secondString", ")", "{", "final", "String", "s0", "=", "firstString", "==", "null", "?", "\"\"", ":", "firstString", ";", "//$NON-NLS-1$", "final", "String", "s1",...
Compute the Levenshstein distance between two strings. <p>Null string is assimilated to the empty string. @param firstString first string. @param secondString second string. @return the Levenshstein distance. @see "https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance"
[ "Compute", "the", "Levenshstein", "distance", "between", "two", "strings", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/text/src/main/java/org/arakhne/afc/text/TextUtil.java#L1688-L1733
jtablesaw/tablesaw
core/src/main/java/tech/tablesaw/api/Table.java
Table.xTabCounts
public Table xTabCounts(String column1Name, String column2Name) { return CrossTab.counts(this, categoricalColumn(column1Name), categoricalColumn(column2Name)); }
java
public Table xTabCounts(String column1Name, String column2Name) { return CrossTab.counts(this, categoricalColumn(column1Name), categoricalColumn(column2Name)); }
[ "public", "Table", "xTabCounts", "(", "String", "column1Name", ",", "String", "column2Name", ")", "{", "return", "CrossTab", ".", "counts", "(", "this", ",", "categoricalColumn", "(", "column1Name", ")", ",", "categoricalColumn", "(", "column2Name", ")", ")", ...
Returns a table with n by m + 1 cells. The first column contains labels, the other cells contains the counts for every unique combination of values from the two specified columns in this table
[ "Returns", "a", "table", "with", "n", "by", "m", "+", "1", "cells", ".", "The", "first", "column", "contains", "labels", "the", "other", "cells", "contains", "the", "counts", "for", "every", "unique", "combination", "of", "values", "from", "the", "two", ...
train
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/api/Table.java#L923-L925
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPOptionValuePersistenceImpl.java
CPOptionValuePersistenceImpl.findByCPOptionId
@Override public List<CPOptionValue> findByCPOptionId(long CPOptionId, int start, int end, OrderByComparator<CPOptionValue> orderByComparator) { return findByCPOptionId(CPOptionId, start, end, orderByComparator, true); }
java
@Override public List<CPOptionValue> findByCPOptionId(long CPOptionId, int start, int end, OrderByComparator<CPOptionValue> orderByComparator) { return findByCPOptionId(CPOptionId, start, end, orderByComparator, true); }
[ "@", "Override", "public", "List", "<", "CPOptionValue", ">", "findByCPOptionId", "(", "long", "CPOptionId", ",", "int", "start", ",", "int", "end", ",", "OrderByComparator", "<", "CPOptionValue", ">", "orderByComparator", ")", "{", "return", "findByCPOptionId", ...
Returns an ordered range of all the cp option values where CPOptionId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPOptionValueModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param CPOptionId the cp option ID @param start the lower bound of the range of cp option values @param end the upper bound of the range of cp option values (not inclusive) @param orderByComparator the comparator to order the results by (optionally <code>null</code>) @return the ordered range of matching cp option values
[ "Returns", "an", "ordered", "range", "of", "all", "the", "cp", "option", "values", "where", "CPOptionId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPOptionValuePersistenceImpl.java#L2564-L2568
looly/hutool
hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java
BeanUtil.copyProperties
public static void copyProperties(Object source, Object target, String... ignoreProperties) { copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties)); }
java
public static void copyProperties(Object source, Object target, String... ignoreProperties) { copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties)); }
[ "public", "static", "void", "copyProperties", "(", "Object", "source", ",", "Object", "target", ",", "String", "...", "ignoreProperties", ")", "{", "copyProperties", "(", "source", ",", "target", ",", "CopyOptions", ".", "create", "(", ")", ".", "setIgnoreProp...
复制Bean对象属性<br> 限制类用于限制拷贝的属性,例如一个类我只想复制其父类的一些属性,就可以将editable设置为父类 @param source 源Bean对象 @param target 目标Bean对象 @param ignoreProperties 不拷贝的的属性列表
[ "复制Bean对象属性<br", ">", "限制类用于限制拷贝的属性,例如一个类我只想复制其父类的一些属性,就可以将editable设置为父类" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java#L594-L596
softindex/datakernel
core-http/src/main/java/io/datakernel/http/HttpServerConnection.java
HttpServerConnection.onHeader
@Override protected void onHeader(HttpHeader header, byte[] array, int off, int len) throws ParseException { if (header == HttpHeaders.EXPECT) { if (equalsLowerCaseAscii(EXPECT_100_CONTINUE, array, off, len)) { socket.write(ByteBuf.wrapForReading(EXPECT_RESPONSE_CONTINUE)); } } if (request.headers.size() >= MAX_HEADERS) { throw TOO_MANY_HEADERS; } request.addParsedHeader(header, array, off, len); }
java
@Override protected void onHeader(HttpHeader header, byte[] array, int off, int len) throws ParseException { if (header == HttpHeaders.EXPECT) { if (equalsLowerCaseAscii(EXPECT_100_CONTINUE, array, off, len)) { socket.write(ByteBuf.wrapForReading(EXPECT_RESPONSE_CONTINUE)); } } if (request.headers.size() >= MAX_HEADERS) { throw TOO_MANY_HEADERS; } request.addParsedHeader(header, array, off, len); }
[ "@", "Override", "protected", "void", "onHeader", "(", "HttpHeader", "header", ",", "byte", "[", "]", "array", ",", "int", "off", ",", "int", "len", ")", "throws", "ParseException", "{", "if", "(", "header", "==", "HttpHeaders", ".", "EXPECT", ")", "{", ...
This method is called after receiving header. It sets its value to request. @param header received header
[ "This", "method", "is", "called", "after", "receiving", "header", ".", "It", "sets", "its", "value", "to", "request", "." ]
train
https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/core-http/src/main/java/io/datakernel/http/HttpServerConnection.java#L201-L212
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/FileOperations.java
FileOperations.getFilePropertiesFromComputeNode
public FileProperties getFilePropertiesFromComputeNode(String poolId, String nodeId, String fileName) throws BatchErrorException, IOException { return getFilePropertiesFromComputeNode(poolId, nodeId, fileName, null); }
java
public FileProperties getFilePropertiesFromComputeNode(String poolId, String nodeId, String fileName) throws BatchErrorException, IOException { return getFilePropertiesFromComputeNode(poolId, nodeId, fileName, null); }
[ "public", "FileProperties", "getFilePropertiesFromComputeNode", "(", "String", "poolId", ",", "String", "nodeId", ",", "String", "fileName", ")", "throws", "BatchErrorException", ",", "IOException", "{", "return", "getFilePropertiesFromComputeNode", "(", "poolId", ",", ...
Gets information about a file on a compute node. @param poolId The ID of the pool that contains the compute node. @param nodeId the ID of the compute node. @param fileName The name of the file to retrieve. @return A {@link FileProperties} instance containing information about the file. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Gets", "information", "about", "a", "file", "on", "a", "compute", "node", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/FileOperations.java#L371-L373
relayrides/pushy
pushy/src/main/java/com/turo/pushy/apns/ApnsClientBuilder.java
ApnsClientBuilder.setApnsServer
public ApnsClientBuilder setApnsServer(final String hostname, final int port) { this.apnsServerAddress = InetSocketAddress.createUnresolved(hostname, port); return this; }
java
public ApnsClientBuilder setApnsServer(final String hostname, final int port) { this.apnsServerAddress = InetSocketAddress.createUnresolved(hostname, port); return this; }
[ "public", "ApnsClientBuilder", "setApnsServer", "(", "final", "String", "hostname", ",", "final", "int", "port", ")", "{", "this", ".", "apnsServerAddress", "=", "InetSocketAddress", ".", "createUnresolved", "(", "hostname", ",", "port", ")", ";", "return", "thi...
Sets the hostname and port of the server to which the client under construction will connect. Apple provides a production and development environment, both of which listen for traffic on the default HTTPS port ({@value DEFAULT_APNS_PORT}) and an alternate port ({@value ALTERNATE_APNS_PORT}), which callers may use to work around firewall or proxy restrictions. @param hostname the hostname of the server to which the client under construction should connect @param port the port to which the client under contruction should connect @return a reference to this builder @see ApnsClientBuilder#DEVELOPMENT_APNS_HOST @see ApnsClientBuilder#PRODUCTION_APNS_HOST @see ApnsClientBuilder#DEFAULT_APNS_PORT @see ApnsClientBuilder#ALTERNATE_APNS_PORT @see <a href="https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns">Sending Notification Requests to APNs</a> @since 0.11
[ "Sets", "the", "hostname", "and", "port", "of", "the", "server", "to", "which", "the", "client", "under", "construction", "will", "connect", ".", "Apple", "provides", "a", "production", "and", "development", "environment", "both", "of", "which", "listen", "for...
train
https://github.com/relayrides/pushy/blob/1f6f9a0e07d785c815d74c2320a8d87c80231d36/pushy/src/main/java/com/turo/pushy/apns/ApnsClientBuilder.java#L164-L167
indeedeng/util
io/src/main/java/com/indeed/util/io/Files.java
Files.isChanged
private static boolean isChanged(byte[] bytes, String filepath) throws IOException { return isChanged(bytes, bytes.length, filepath); }
java
private static boolean isChanged(byte[] bytes, String filepath) throws IOException { return isChanged(bytes, bytes.length, filepath); }
[ "private", "static", "boolean", "isChanged", "(", "byte", "[", "]", "bytes", ",", "String", "filepath", ")", "throws", "IOException", "{", "return", "isChanged", "(", "bytes", ",", "bytes", ".", "length", ",", "filepath", ")", ";", "}" ]
Returns true iff the bytes in an array are different from the bytes contained in the given file, or if the file does not exist.
[ "Returns", "true", "iff", "the", "bytes", "in", "an", "array", "are", "different", "from", "the", "bytes", "contained", "in", "the", "given", "file", "or", "if", "the", "file", "does", "not", "exist", "." ]
train
https://github.com/indeedeng/util/blob/332008426cf14b57e7fc3e817d9423e3f84fb922/io/src/main/java/com/indeed/util/io/Files.java#L368-L370
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPAttachmentFileEntryPersistenceImpl.java
CPAttachmentFileEntryPersistenceImpl.removeByLtD_S
@Override public void removeByLtD_S(Date displayDate, int status) { for (CPAttachmentFileEntry cpAttachmentFileEntry : findByLtD_S( displayDate, status, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpAttachmentFileEntry); } }
java
@Override public void removeByLtD_S(Date displayDate, int status) { for (CPAttachmentFileEntry cpAttachmentFileEntry : findByLtD_S( displayDate, status, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpAttachmentFileEntry); } }
[ "@", "Override", "public", "void", "removeByLtD_S", "(", "Date", "displayDate", ",", "int", "status", ")", "{", "for", "(", "CPAttachmentFileEntry", "cpAttachmentFileEntry", ":", "findByLtD_S", "(", "displayDate", ",", "status", ",", "QueryUtil", ".", "ALL_POS", ...
Removes all the cp attachment file entries where displayDate &lt; &#63; and status = &#63; from the database. @param displayDate the display date @param status the status
[ "Removes", "all", "the", "cp", "attachment", "file", "entries", "where", "displayDate", "&lt", ";", "&#63", ";", "and", "status", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPAttachmentFileEntryPersistenceImpl.java#L2536-L2542
Azure/azure-sdk-for-java
cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideosImpl.java
BingVideosImpl.searchWithServiceResponseAsync
public Observable<ServiceResponse<VideosModel>> searchWithServiceResponseAsync(String query, SearchOptionalParameter searchOptionalParameter) { if (query == null) { throw new IllegalArgumentException("Parameter query is required and cannot be null."); } final String acceptLanguage = searchOptionalParameter != null ? searchOptionalParameter.acceptLanguage() : null; final String userAgent = searchOptionalParameter != null ? searchOptionalParameter.userAgent() : this.client.userAgent(); final String clientId = searchOptionalParameter != null ? searchOptionalParameter.clientId() : null; final String clientIp = searchOptionalParameter != null ? searchOptionalParameter.clientIp() : null; final String location = searchOptionalParameter != null ? searchOptionalParameter.location() : null; final String countryCode = searchOptionalParameter != null ? searchOptionalParameter.countryCode() : null; final Integer count = searchOptionalParameter != null ? searchOptionalParameter.count() : null; final Freshness freshness = searchOptionalParameter != null ? searchOptionalParameter.freshness() : null; final String id = searchOptionalParameter != null ? searchOptionalParameter.id() : null; final VideoLength length = searchOptionalParameter != null ? searchOptionalParameter.length() : null; final String market = searchOptionalParameter != null ? searchOptionalParameter.market() : null; final Integer offset = searchOptionalParameter != null ? searchOptionalParameter.offset() : null; final VideoPricing pricing = searchOptionalParameter != null ? searchOptionalParameter.pricing() : null; final VideoResolution resolution = searchOptionalParameter != null ? searchOptionalParameter.resolution() : null; final SafeSearch safeSearch = searchOptionalParameter != null ? searchOptionalParameter.safeSearch() : null; final String setLang = searchOptionalParameter != null ? searchOptionalParameter.setLang() : null; final Boolean textDecorations = searchOptionalParameter != null ? searchOptionalParameter.textDecorations() : null; final TextFormat textFormat = searchOptionalParameter != null ? searchOptionalParameter.textFormat() : null; return searchWithServiceResponseAsync(query, acceptLanguage, userAgent, clientId, clientIp, location, countryCode, count, freshness, id, length, market, offset, pricing, resolution, safeSearch, setLang, textDecorations, textFormat); }
java
public Observable<ServiceResponse<VideosModel>> searchWithServiceResponseAsync(String query, SearchOptionalParameter searchOptionalParameter) { if (query == null) { throw new IllegalArgumentException("Parameter query is required and cannot be null."); } final String acceptLanguage = searchOptionalParameter != null ? searchOptionalParameter.acceptLanguage() : null; final String userAgent = searchOptionalParameter != null ? searchOptionalParameter.userAgent() : this.client.userAgent(); final String clientId = searchOptionalParameter != null ? searchOptionalParameter.clientId() : null; final String clientIp = searchOptionalParameter != null ? searchOptionalParameter.clientIp() : null; final String location = searchOptionalParameter != null ? searchOptionalParameter.location() : null; final String countryCode = searchOptionalParameter != null ? searchOptionalParameter.countryCode() : null; final Integer count = searchOptionalParameter != null ? searchOptionalParameter.count() : null; final Freshness freshness = searchOptionalParameter != null ? searchOptionalParameter.freshness() : null; final String id = searchOptionalParameter != null ? searchOptionalParameter.id() : null; final VideoLength length = searchOptionalParameter != null ? searchOptionalParameter.length() : null; final String market = searchOptionalParameter != null ? searchOptionalParameter.market() : null; final Integer offset = searchOptionalParameter != null ? searchOptionalParameter.offset() : null; final VideoPricing pricing = searchOptionalParameter != null ? searchOptionalParameter.pricing() : null; final VideoResolution resolution = searchOptionalParameter != null ? searchOptionalParameter.resolution() : null; final SafeSearch safeSearch = searchOptionalParameter != null ? searchOptionalParameter.safeSearch() : null; final String setLang = searchOptionalParameter != null ? searchOptionalParameter.setLang() : null; final Boolean textDecorations = searchOptionalParameter != null ? searchOptionalParameter.textDecorations() : null; final TextFormat textFormat = searchOptionalParameter != null ? searchOptionalParameter.textFormat() : null; return searchWithServiceResponseAsync(query, acceptLanguage, userAgent, clientId, clientIp, location, countryCode, count, freshness, id, length, market, offset, pricing, resolution, safeSearch, setLang, textDecorations, textFormat); }
[ "public", "Observable", "<", "ServiceResponse", "<", "VideosModel", ">", ">", "searchWithServiceResponseAsync", "(", "String", "query", ",", "SearchOptionalParameter", "searchOptionalParameter", ")", "{", "if", "(", "query", "==", "null", ")", "{", "throw", "new", ...
The Video Search API lets you send a search query to Bing and get back a list of videos that are relevant to the search query. This section provides technical details about the query parameters and headers that you use to request videos and the JSON response objects that contain them. For examples that show how to make requests, see [Searching the Web for Videos](https://docs.microsoft.com/azure/cognitive-services/bing-video-search/search-the-web). @param query The user's search query string. The query string cannot be empty. The query string may contain [Bing Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit videos to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator. Use this parameter only with the Video Search API. Do not specify this parameter when calling the Trending Videos API. @param searchOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the VideosModel object
[ "The", "Video", "Search", "API", "lets", "you", "send", "a", "search", "query", "to", "Bing", "and", "get", "back", "a", "list", "of", "videos", "that", "are", "relevant", "to", "the", "search", "query", ".", "This", "section", "provides", "technical", "...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideosImpl.java#L137-L161
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.getMetaPropertyValues
public static List<PropertyValue> getMetaPropertyValues(Object self) { MetaClass metaClass = InvokerHelper.getMetaClass(self); List<MetaProperty> mps = metaClass.getProperties(); List<PropertyValue> props = new ArrayList<PropertyValue>(mps.size()); for (MetaProperty mp : mps) { props.add(new PropertyValue(self, mp)); } return props; }
java
public static List<PropertyValue> getMetaPropertyValues(Object self) { MetaClass metaClass = InvokerHelper.getMetaClass(self); List<MetaProperty> mps = metaClass.getProperties(); List<PropertyValue> props = new ArrayList<PropertyValue>(mps.size()); for (MetaProperty mp : mps) { props.add(new PropertyValue(self, mp)); } return props; }
[ "public", "static", "List", "<", "PropertyValue", ">", "getMetaPropertyValues", "(", "Object", "self", ")", "{", "MetaClass", "metaClass", "=", "InvokerHelper", ".", "getMetaClass", "(", "self", ")", ";", "List", "<", "MetaProperty", ">", "mps", "=", "metaClas...
Retrieves the list of {@link groovy.lang.MetaProperty} objects for 'self' and wraps it in a list of {@link groovy.lang.PropertyValue} objects that additionally provide the value for each property of 'self'. @param self the receiver object @return list of {@link groovy.lang.PropertyValue} objects @see groovy.util.Expando#getMetaPropertyValues() @since 1.0
[ "Retrieves", "the", "list", "of", "{", "@link", "groovy", ".", "lang", ".", "MetaProperty", "}", "objects", "for", "self", "and", "wraps", "it", "in", "a", "list", "of", "{", "@link", "groovy", ".", "lang", ".", "PropertyValue", "}", "objects", "that", ...
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L512-L520
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/NodeIndexer.java
NodeIndexer.addPathValue
protected void addPathValue(Document doc, String fieldName, Object pathString) { doc.add(createFieldWithoutNorms(fieldName, pathString.toString(), PropertyType.PATH)); }
java
protected void addPathValue(Document doc, String fieldName, Object pathString) { doc.add(createFieldWithoutNorms(fieldName, pathString.toString(), PropertyType.PATH)); }
[ "protected", "void", "addPathValue", "(", "Document", "doc", ",", "String", "fieldName", ",", "Object", "pathString", ")", "{", "doc", ".", "add", "(", "createFieldWithoutNorms", "(", "fieldName", ",", "pathString", ".", "toString", "(", ")", ",", "PropertyTyp...
Adds the path value to the document as the named field. The path value is converted to an indexable string value using the name space mappings with which this class has been created. @param doc The document to which to add the field @param fieldName The name of the field to add @param pathString The value for the field to add to the document.
[ "Adds", "the", "path", "value", "to", "the", "document", "as", "the", "named", "field", ".", "The", "path", "value", "is", "converted", "to", "an", "indexable", "string", "value", "using", "the", "name", "space", "mappings", "with", "which", "this", "class...
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/NodeIndexer.java#L807-L811
ModeShape/modeshape
modeshape-common/src/main/java/org/modeshape/common/util/SecureHash.java
SecureHash.createHashingReader
public static HashingReader createHashingReader( String digestName, Reader reader, Charset charset ) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance(digestName); return new HashingReader(digest, reader, charset); }
java
public static HashingReader createHashingReader( String digestName, Reader reader, Charset charset ) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance(digestName); return new HashingReader(digest, reader, charset); }
[ "public", "static", "HashingReader", "createHashingReader", "(", "String", "digestName", ",", "Reader", "reader", ",", "Charset", "charset", ")", "throws", "NoSuchAlgorithmException", "{", "MessageDigest", "digest", "=", "MessageDigest", ".", "getInstance", "(", "dige...
Create an Reader instance that wraps another reader and that computes the secure hash (using the algorithm with the supplied name) as the returned Reader is used. This can be used to compute the hash while the content is being processed, and saves from having to process the same content twice. @param digestName the name of the hashing function (or {@link MessageDigest message digest}) that should be used @param reader the reader containing the content that is to be hashed @param charset the character set used within the supplied reader; may not be null @return the hash of the contents as a byte array @throws NoSuchAlgorithmException
[ "Create", "an", "Reader", "instance", "that", "wraps", "another", "reader", "and", "that", "computes", "the", "secure", "hash", "(", "using", "the", "algorithm", "with", "the", "supplied", "name", ")", "as", "the", "returned", "Reader", "is", "used", ".", ...
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/SecureHash.java#L314-L319
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPUtils.java
JBBPUtils.double2str
public static String double2str(final double doubleValue, final int radix) { if (radix != 10 && radix != 16) { throw new IllegalArgumentException("Illegal radix [" + radix + ']'); } final String result; if (radix == 16) { String converted = Double.toHexString(doubleValue); boolean minus = converted.startsWith("-"); if (minus) { converted = converted.substring(1); } if (converted.startsWith("0x")) { converted = converted.substring(2); } result = (minus ? '-' + converted : converted).toUpperCase(Locale.ENGLISH); } else { result = Double.toString(doubleValue); } return result; }
java
public static String double2str(final double doubleValue, final int radix) { if (radix != 10 && radix != 16) { throw new IllegalArgumentException("Illegal radix [" + radix + ']'); } final String result; if (radix == 16) { String converted = Double.toHexString(doubleValue); boolean minus = converted.startsWith("-"); if (minus) { converted = converted.substring(1); } if (converted.startsWith("0x")) { converted = converted.substring(2); } result = (minus ? '-' + converted : converted).toUpperCase(Locale.ENGLISH); } else { result = Double.toString(doubleValue); } return result; }
[ "public", "static", "String", "double2str", "(", "final", "double", "doubleValue", ",", "final", "int", "radix", ")", "{", "if", "(", "radix", "!=", "10", "&&", "radix", "!=", "16", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Illegal radix ...
Convert double value into string representation with defined radix base. @param doubleValue value to be converted in string @param radix radix base to be used for conversion, must be 10 or 16 @return converted value as upper case string @throws IllegalArgumentException for wrong radix base @since 1.4.0
[ "Convert", "double", "value", "into", "string", "representation", "with", "defined", "radix", "base", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPUtils.java#L706-L726
astrapi69/jaulp-wicket
jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/url/WicketUrlExtensions.java
WicketUrlExtensions.getCanonicalPageUrl
public static Url getCanonicalPageUrl(final Class<? extends Page> pageClass, final PageParameters parameters) { return getPageUrl(pageClass, parameters).canonical(); }
java
public static Url getCanonicalPageUrl(final Class<? extends Page> pageClass, final PageParameters parameters) { return getPageUrl(pageClass, parameters).canonical(); }
[ "public", "static", "Url", "getCanonicalPageUrl", "(", "final", "Class", "<", "?", "extends", "Page", ">", "pageClass", ",", "final", "PageParameters", "parameters", ")", "{", "return", "getPageUrl", "(", "pageClass", ",", "parameters", ")", ".", "canonical", ...
Gets the canonical page url. Try to reduce url by eliminating '..' and '.' from the path where appropriate (this is somehow similar to {@link java.io.File#getCanonicalPath()}). @param pageClass the page class @param parameters the parameters @return the page url @see Url#canonical()
[ "Gets", "the", "canonical", "page", "url", ".", "Try", "to", "reduce", "url", "by", "eliminating", "..", "and", ".", "from", "the", "path", "where", "appropriate", "(", "this", "is", "somehow", "similar", "to", "{", "@link", "java", ".", "io", ".", "Fi...
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/url/WicketUrlExtensions.java#L160-L164
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/github/lgooddatepicker/components/DatePicker.java
DatePicker.getBaseline
@Override public int getBaseline(int width, int height) { if (dateTextField.isVisible()) { return dateTextField.getBaseline(width, height); } return super.getBaseline(width, height); }
java
@Override public int getBaseline(int width, int height) { if (dateTextField.isVisible()) { return dateTextField.getBaseline(width, height); } return super.getBaseline(width, height); }
[ "@", "Override", "public", "int", "getBaseline", "(", "int", "width", ",", "int", "height", ")", "{", "if", "(", "dateTextField", ".", "isVisible", "(", ")", ")", "{", "return", "dateTextField", ".", "getBaseline", "(", "width", ",", "height", ")", ";", ...
getBaseline, This returns the baseline value of the dateTextField.
[ "getBaseline", "This", "returns", "the", "baseline", "value", "of", "the", "dateTextField", "." ]
train
https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/github/lgooddatepicker/components/DatePicker.java#L261-L267
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/io/file/PathHelper.java
PathHelper.isFileNewer
public static boolean isFileNewer (@Nonnull final Path aFile1, @Nonnull final Path aFile2) { ValueEnforcer.notNull (aFile1, "File1"); ValueEnforcer.notNull (aFile2, "aFile2"); // The Files API seem to be slow return FileHelper.isFileNewer (aFile1.toFile (), aFile2.toFile ()); // // Compare with the same file? // if (aFile1.equals (aFile2)) // return false; // // // if the first file does not exists, always false // if (!Files.exists (aFile1)) // return false; // // // first file exists, but second file does not // if (!Files.exists (aFile2)) // return true; // // try // { // // both exist, compare file times // return Files.getLastModifiedTime (aFile1).compareTo // (Files.getLastModifiedTime (aFile2)) > 0; // } // catch (final IOException ex) // { // throw new UncheckedIOException (ex); // } }
java
public static boolean isFileNewer (@Nonnull final Path aFile1, @Nonnull final Path aFile2) { ValueEnforcer.notNull (aFile1, "File1"); ValueEnforcer.notNull (aFile2, "aFile2"); // The Files API seem to be slow return FileHelper.isFileNewer (aFile1.toFile (), aFile2.toFile ()); // // Compare with the same file? // if (aFile1.equals (aFile2)) // return false; // // // if the first file does not exists, always false // if (!Files.exists (aFile1)) // return false; // // // first file exists, but second file does not // if (!Files.exists (aFile2)) // return true; // // try // { // // both exist, compare file times // return Files.getLastModifiedTime (aFile1).compareTo // (Files.getLastModifiedTime (aFile2)) > 0; // } // catch (final IOException ex) // { // throw new UncheckedIOException (ex); // } }
[ "public", "static", "boolean", "isFileNewer", "(", "@", "Nonnull", "final", "Path", "aFile1", ",", "@", "Nonnull", "final", "Path", "aFile2", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aFile1", ",", "\"File1\"", ")", ";", "ValueEnforcer", ".", "notNull...
Returns <code>true</code> if the first file is newer than the second file. Returns <code>true</code> if the first file exists and the second file does not exist. Returns <code>false</code> if the first file is older than the second file. Returns <code>false</code> if the first file does not exists but the second does. Returns <code>false</code> if none of the files exist. @param aFile1 First file. May not be <code>null</code>. @param aFile2 Second file. May not be <code>null</code>. @return <code>true</code> if the first file is newer than the second file, <code>false</code> otherwise.
[ "Returns", "<code", ">", "true<", "/", "code", ">", "if", "the", "first", "file", "is", "newer", "than", "the", "second", "file", ".", "Returns", "<code", ">", "true<", "/", "code", ">", "if", "the", "first", "file", "exists", "and", "the", "second", ...
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/io/file/PathHelper.java#L421-L451
Azure/azure-sdk-for-java
sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ReplicationLinksInner.java
ReplicationLinksInner.failover
public void failover(String resourceGroupName, String serverName, String databaseName, String linkId) { failoverWithServiceResponseAsync(resourceGroupName, serverName, databaseName, linkId).toBlocking().last().body(); }
java
public void failover(String resourceGroupName, String serverName, String databaseName, String linkId) { failoverWithServiceResponseAsync(resourceGroupName, serverName, databaseName, linkId).toBlocking().last().body(); }
[ "public", "void", "failover", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "databaseName", ",", "String", "linkId", ")", "{", "failoverWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "databaseName", ",", ...
Sets which replica database is primary by failing over from the current primary replica database. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param databaseName The name of the database that has the replication link to be failed over. @param linkId The ID of the replication link to be failed over. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Sets", "which", "replica", "database", "is", "primary", "by", "failing", "over", "from", "the", "current", "primary", "replica", "database", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ReplicationLinksInner.java#L298-L300
aws/aws-sdk-java
aws-java-sdk-elastictranscoder/src/main/java/com/amazonaws/services/elastictranscoder/model/CreateJobRequest.java
CreateJobRequest.withUserMetadata
public CreateJobRequest withUserMetadata(java.util.Map<String, String> userMetadata) { setUserMetadata(userMetadata); return this; }
java
public CreateJobRequest withUserMetadata(java.util.Map<String, String> userMetadata) { setUserMetadata(userMetadata); return this; }
[ "public", "CreateJobRequest", "withUserMetadata", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "userMetadata", ")", "{", "setUserMetadata", "(", "userMetadata", ")", ";", "return", "this", ";", "}" ]
<p> User-defined metadata that you want to associate with an Elastic Transcoder job. You specify metadata in <code>key/value</code> pairs, and you can add up to 10 <code>key/value</code> pairs per job. Elastic Transcoder does not guarantee that <code>key/value</code> pairs are returned in the same order in which you specify them. </p> @param userMetadata User-defined metadata that you want to associate with an Elastic Transcoder job. You specify metadata in <code>key/value</code> pairs, and you can add up to 10 <code>key/value</code> pairs per job. Elastic Transcoder does not guarantee that <code>key/value</code> pairs are returned in the same order in which you specify them. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "User", "-", "defined", "metadata", "that", "you", "want", "to", "associate", "with", "an", "Elastic", "Transcoder", "job", ".", "You", "specify", "metadata", "in", "<code", ">", "key", "/", "value<", "/", "code", ">", "pairs", "and", "you", ...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-elastictranscoder/src/main/java/com/amazonaws/services/elastictranscoder/model/CreateJobRequest.java#L589-L592
mygreen/super-csv-annotation
src/main/java/com/github/mygreen/supercsv/builder/BeanMappingFactory.java
BeanMappingFactory.createColumnMapping
@SuppressWarnings({"rawtypes", "unchecked"}) protected ColumnMapping createColumnMapping(final Field field, final CsvColumn columnAnno, final Class<?>[] groups) { final FieldAccessor fieldAccessor = new FieldAccessor(field, configuration.getAnnoationComparator()); final ColumnMapping columnMapping = new ColumnMapping(); columnMapping.setField(fieldAccessor); columnMapping.setNumber(columnAnno.number()); if(columnAnno.label().isEmpty()) { columnMapping.setLabel(field.getName()); } else { columnMapping.setLabel(columnAnno.label()); } // ProcessorBuilderの取得 ProcessorBuilder builder; if(columnAnno.builder().length == 0) { builder = configuration.getBuilderResolver().resolve(fieldAccessor.getType()); if(builder == null) { // 不明なタイプの場合 builder = new GeneralProcessorBuilder(); } } else { // 直接Builderクラスが指定されている場合 try { builder = (ProcessorBuilder) configuration.getBeanFactory().create(columnAnno.builder()[0]); } catch(Throwable e) { throw new SuperCsvReflectionException( String.format("Fail create instance of %s with attribute 'builderClass' of @CsvColumn", columnAnno.builder()[0].getCanonicalName()), e); } } // CellProcessorの作成 columnMapping.setCellProcessorForReading( (CellProcessor)builder.buildForReading(field.getType(), fieldAccessor, configuration, groups).orElse(null)); columnMapping.setCellProcessorForWriting( (CellProcessor)builder.buildForWriting(field.getType(), fieldAccessor, configuration, groups).orElse(null)); if(builder instanceof AbstractProcessorBuilder) { columnMapping.setFormatter(((AbstractProcessorBuilder)builder).getFormatter(fieldAccessor, configuration)); } return columnMapping; }
java
@SuppressWarnings({"rawtypes", "unchecked"}) protected ColumnMapping createColumnMapping(final Field field, final CsvColumn columnAnno, final Class<?>[] groups) { final FieldAccessor fieldAccessor = new FieldAccessor(field, configuration.getAnnoationComparator()); final ColumnMapping columnMapping = new ColumnMapping(); columnMapping.setField(fieldAccessor); columnMapping.setNumber(columnAnno.number()); if(columnAnno.label().isEmpty()) { columnMapping.setLabel(field.getName()); } else { columnMapping.setLabel(columnAnno.label()); } // ProcessorBuilderの取得 ProcessorBuilder builder; if(columnAnno.builder().length == 0) { builder = configuration.getBuilderResolver().resolve(fieldAccessor.getType()); if(builder == null) { // 不明なタイプの場合 builder = new GeneralProcessorBuilder(); } } else { // 直接Builderクラスが指定されている場合 try { builder = (ProcessorBuilder) configuration.getBeanFactory().create(columnAnno.builder()[0]); } catch(Throwable e) { throw new SuperCsvReflectionException( String.format("Fail create instance of %s with attribute 'builderClass' of @CsvColumn", columnAnno.builder()[0].getCanonicalName()), e); } } // CellProcessorの作成 columnMapping.setCellProcessorForReading( (CellProcessor)builder.buildForReading(field.getType(), fieldAccessor, configuration, groups).orElse(null)); columnMapping.setCellProcessorForWriting( (CellProcessor)builder.buildForWriting(field.getType(), fieldAccessor, configuration, groups).orElse(null)); if(builder instanceof AbstractProcessorBuilder) { columnMapping.setFormatter(((AbstractProcessorBuilder)builder).getFormatter(fieldAccessor, configuration)); } return columnMapping; }
[ "@", "SuppressWarnings", "(", "{", "\"rawtypes\"", ",", "\"unchecked\"", "}", ")", "protected", "ColumnMapping", "createColumnMapping", "(", "final", "Field", "field", ",", "final", "CsvColumn", "columnAnno", ",", "final", "Class", "<", "?", ">", "[", "]", "gr...
カラム情報を組み立てる @param field フィールド情報 @param columnAnno 設定されているカラムのアノテーション @param groups グループ情報 @return 組み立てたカラム
[ "カラム情報を組み立てる" ]
train
https://github.com/mygreen/super-csv-annotation/blob/9910320cb6dc143be972c7d10d9ab5ffb09c3b84/src/main/java/com/github/mygreen/supercsv/builder/BeanMappingFactory.java#L162-L212
infinispan/infinispan
lucene/directory-provider/src/main/java/org/infinispan/hibernate/search/impl/InfinispanConfigurationParser.java
InfinispanConfigurationParser.patchTransportConfiguration
private void patchTransportConfiguration(ConfigurationBuilderHolder builderHolder, String transportOverrideResource) throws IOException { if (transportOverrideResource != null) { try (InputStream xml = FileLookupFactory.newInstance().lookupFileStrict(transportOverrideResource, ispnClassLoadr)) { Properties p = new Properties(); FileJGroupsChannelConfigurator configurator = new FileJGroupsChannelConfigurator("override", transportOverrideResource, xml, System.getProperties()); p.put(JGroupsTransport.CHANNEL_CONFIGURATOR, configurator); builderHolder.getGlobalConfigurationBuilder().transport().withProperties(p); } } }
java
private void patchTransportConfiguration(ConfigurationBuilderHolder builderHolder, String transportOverrideResource) throws IOException { if (transportOverrideResource != null) { try (InputStream xml = FileLookupFactory.newInstance().lookupFileStrict(transportOverrideResource, ispnClassLoadr)) { Properties p = new Properties(); FileJGroupsChannelConfigurator configurator = new FileJGroupsChannelConfigurator("override", transportOverrideResource, xml, System.getProperties()); p.put(JGroupsTransport.CHANNEL_CONFIGURATOR, configurator); builderHolder.getGlobalConfigurationBuilder().transport().withProperties(p); } } }
[ "private", "void", "patchTransportConfiguration", "(", "ConfigurationBuilderHolder", "builderHolder", ",", "String", "transportOverrideResource", ")", "throws", "IOException", "{", "if", "(", "transportOverrideResource", "!=", "null", ")", "{", "try", "(", "InputStream", ...
After having parsed the Infinispan configuration file, we might want to override the specified JGroups configuration file. @param builderHolder @param transportOverrideResource The alternative JGroups configuration file to be used, or null
[ "After", "having", "parsed", "the", "Infinispan", "configuration", "file", "we", "might", "want", "to", "override", "the", "specified", "JGroups", "configuration", "file", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/lucene/directory-provider/src/main/java/org/infinispan/hibernate/search/impl/InfinispanConfigurationParser.java#L87-L96