repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
188
func_name
stringlengths
7
127
whole_func_string
stringlengths
77
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
77
3.91k
func_code_tokens
listlengths
20
745
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
477
split_name
stringclasses
1 value
func_code_url
stringlengths
111
288
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/utility/StringIterate.java
StringIterate.occurrencesOf
public static int occurrencesOf(String string, String singleCharacter) { if (singleCharacter.length() != 1) { throw new IllegalArgumentException("Argument should be a single character: " + singleCharacter); } return StringIterate.occurrencesOfChar(string, singleCharacter.charAt(0)); }
java
public static int occurrencesOf(String string, String singleCharacter) { if (singleCharacter.length() != 1) { throw new IllegalArgumentException("Argument should be a single character: " + singleCharacter); } return StringIterate.occurrencesOfChar(string, singleCharacter.charAt(0)); }
[ "public", "static", "int", "occurrencesOf", "(", "String", "string", ",", "String", "singleCharacter", ")", "{", "if", "(", "singleCharacter", ".", "length", "(", ")", "!=", "1", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Argument should be a ...
Count the number of occurrences of the specified {@code string}.
[ "Count", "the", "number", "of", "occurrences", "of", "the", "specified", "{" ]
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/StringIterate.java#L777-L784
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendPongBlocking
public static void sendPongBlocking(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel) throws IOException { sendBlockingInternal(pooledData, WebSocketFrameType.PONG, wsChannel); }
java
public static void sendPongBlocking(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel) throws IOException { sendBlockingInternal(pooledData, WebSocketFrameType.PONG, wsChannel); }
[ "public", "static", "void", "sendPongBlocking", "(", "final", "PooledByteBuffer", "pooledData", ",", "final", "WebSocketChannel", "wsChannel", ")", "throws", "IOException", "{", "sendBlockingInternal", "(", "pooledData", ",", "WebSocketFrameType", ".", "PONG", ",", "w...
Sends a complete pong message using blocking IO Automatically frees the pooled byte buffer when done. @param pooledData The data to send, it will be freed when done @param wsChannel The web socket channel
[ "Sends", "a", "complete", "pong", "message", "using", "blocking", "IO", "Automatically", "frees", "the", "pooled", "byte", "buffer", "when", "done", "." ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L578-L580
netplex/json-smart-v2
json-smart/src/main/java/net/minidev/json/JSONArray.java
JSONArray.writeJSONString
public static void writeJSONString(Iterable<? extends Object> list, Appendable out, JSONStyle compression) throws IOException { if (list == null) { out.append("null"); return; } JsonWriter.JSONIterableWriter.writeJSONString(list, out, compression); }
java
public static void writeJSONString(Iterable<? extends Object> list, Appendable out, JSONStyle compression) throws IOException { if (list == null) { out.append("null"); return; } JsonWriter.JSONIterableWriter.writeJSONString(list, out, compression); }
[ "public", "static", "void", "writeJSONString", "(", "Iterable", "<", "?", "extends", "Object", ">", "list", ",", "Appendable", "out", ",", "JSONStyle", "compression", ")", "throws", "IOException", "{", "if", "(", "list", "==", "null", ")", "{", "out", ".",...
Encode a list into JSON text and write it to out. If this list is also a JSONStreamAware or a JSONAware, JSONStreamAware and JSONAware specific behaviours will be ignored at this top level. @see JSONValue#writeJSONString(Object, Appendable) @param list @param out
[ "Encode", "a", "list", "into", "JSON", "text", "and", "write", "it", "to", "out", ".", "If", "this", "list", "is", "also", "a", "JSONStreamAware", "or", "a", "JSONAware", "JSONStreamAware", "and", "JSONAware", "specific", "behaviours", "will", "be", "ignored...
train
https://github.com/netplex/json-smart-v2/blob/bfb3daef039e22a7bbff5f76bf14ea23330cd70e/json-smart/src/main/java/net/minidev/json/JSONArray.java#L69-L76
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/Monitor.java
Monitor.waitToStartCluster
public void waitToStartCluster(final String clusterName, int nodesCount, int timeout) { log.debug(String.format( "Waiting up to %ds for the Elasticsearch cluster to start ...", timeout)); Awaitility.await() .atMost(timeout, TimeUnit.SECONDS) .pollDelay(1, TimeUnit.SECONDS) .pollInterval(1, TimeUnit.SECONDS) .until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return isClusterRunning(clusterName, nodesCount, client); } } ); log.info("The Elasticsearch cluster has started"); }
java
public void waitToStartCluster(final String clusterName, int nodesCount, int timeout) { log.debug(String.format( "Waiting up to %ds for the Elasticsearch cluster to start ...", timeout)); Awaitility.await() .atMost(timeout, TimeUnit.SECONDS) .pollDelay(1, TimeUnit.SECONDS) .pollInterval(1, TimeUnit.SECONDS) .until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return isClusterRunning(clusterName, nodesCount, client); } } ); log.info("The Elasticsearch cluster has started"); }
[ "public", "void", "waitToStartCluster", "(", "final", "String", "clusterName", ",", "int", "nodesCount", ",", "int", "timeout", ")", "{", "log", ".", "debug", "(", "String", ".", "format", "(", "\"Waiting up to %ds for the Elasticsearch cluster to start ...\"", ",", ...
Wait until the cluster has fully started (ie. all nodes have joined). @param clusterName the ES cluster name @param nodesCount the number of nodes in the cluster @param timeout how many seconds to wait
[ "Wait", "until", "the", "cluster", "has", "fully", "started", "(", "ie", ".", "all", "nodes", "have", "joined", ")", "." ]
train
https://github.com/alexcojocaru/elasticsearch-maven-plugin/blob/c283053cf99dc6b6d411b58629364b6aae62b7f8/src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/Monitor.java#L115-L134
aNNiMON/Lightweight-Stream-API
stream/src/main/java/com/annimon/stream/Collectors.java
Collectors.groupingBy
@NotNull public static <T, K, D, A, M extends Map<K, D>> Collector<T, ?, M> groupingBy( @NotNull final Function<? super T, ? extends K> classifier, @NotNull final Supplier<M> mapFactory, @NotNull final Collector<? super T, A, D> downstream) { @SuppressWarnings("unchecked") final Function<A, A> downstreamFinisher = (Function<A, A>) downstream.finisher(); Function<Map<K, A>, M> finisher = new Function<Map<K, A>, M>() { @NotNull @Override public M apply(@NotNull Map<K, A> map) { // Update values of a map by a finisher function for (Map.Entry<K, A> entry : map.entrySet()) { A value = entry.getValue(); value = downstreamFinisher.apply(value); entry.setValue(value); } @SuppressWarnings("unchecked") M castedMap = (M) map; return castedMap; } }; @SuppressWarnings("unchecked") Supplier<Map<K, A>> castedMapFactory = (Supplier<Map<K, A>>) mapFactory; return new CollectorsImpl<T, Map<K, A>, M>( castedMapFactory, new BiConsumer<Map<K, A>, T>() { @Override public void accept(@NotNull Map<K, A> map, T t) { K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key"); // Get container with currently grouped elements A container = map.get(key); if (container == null) { // Put new container (list, map, set, etc) container = downstream.supplier().get(); map.put(key, container); } // Add element to container downstream.accumulator().accept(container, t); } }, finisher ); }
java
@NotNull public static <T, K, D, A, M extends Map<K, D>> Collector<T, ?, M> groupingBy( @NotNull final Function<? super T, ? extends K> classifier, @NotNull final Supplier<M> mapFactory, @NotNull final Collector<? super T, A, D> downstream) { @SuppressWarnings("unchecked") final Function<A, A> downstreamFinisher = (Function<A, A>) downstream.finisher(); Function<Map<K, A>, M> finisher = new Function<Map<K, A>, M>() { @NotNull @Override public M apply(@NotNull Map<K, A> map) { // Update values of a map by a finisher function for (Map.Entry<K, A> entry : map.entrySet()) { A value = entry.getValue(); value = downstreamFinisher.apply(value); entry.setValue(value); } @SuppressWarnings("unchecked") M castedMap = (M) map; return castedMap; } }; @SuppressWarnings("unchecked") Supplier<Map<K, A>> castedMapFactory = (Supplier<Map<K, A>>) mapFactory; return new CollectorsImpl<T, Map<K, A>, M>( castedMapFactory, new BiConsumer<Map<K, A>, T>() { @Override public void accept(@NotNull Map<K, A> map, T t) { K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key"); // Get container with currently grouped elements A container = map.get(key); if (container == null) { // Put new container (list, map, set, etc) container = downstream.supplier().get(); map.put(key, container); } // Add element to container downstream.accumulator().accept(container, t); } }, finisher ); }
[ "@", "NotNull", "public", "static", "<", "T", ",", "K", ",", "D", ",", "A", ",", "M", "extends", "Map", "<", "K", ",", "D", ">", ">", "Collector", "<", "T", ",", "?", ",", "M", ">", "groupingBy", "(", "@", "NotNull", "final", "Function", "<", ...
Returns a {@code Collector} that performs grouping operation by given classifier. @param <T> the type of the input elements @param <K> the type of the keys @param <A> the accumulation type @param <D> the result type of downstream reduction @param <M> the type of the resulting {@code Map} @param classifier the classifier function @param mapFactory a supplier function that provides new {@code Map} @param downstream the collector of mapped elements @return a {@code Collector} @see #groupingBy(com.annimon.stream.function.Function) @see #groupingBy(com.annimon.stream.function.Function, com.annimon.stream.Collector)
[ "Returns", "a", "{", "@code", "Collector", "}", "that", "performs", "grouping", "operation", "by", "given", "classifier", "." ]
train
https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Collectors.java#L939-L986
joniles/mpxj
src/main/java/net/sf/mpxj/mpx/LocaleUtility.java
LocaleUtility.setLocale
public static void setLocale(ProjectProperties properties, Locale locale) { properties.setMpxDelimiter(LocaleData.getChar(locale, LocaleData.FILE_DELIMITER)); properties.setMpxProgramName(LocaleData.getString(locale, LocaleData.PROGRAM_NAME)); properties.setMpxCodePage((CodePage) LocaleData.getObject(locale, LocaleData.CODE_PAGE)); properties.setCurrencySymbol(LocaleData.getString(locale, LocaleData.CURRENCY_SYMBOL)); properties.setSymbolPosition((CurrencySymbolPosition) LocaleData.getObject(locale, LocaleData.CURRENCY_SYMBOL_POSITION)); properties.setCurrencyDigits(LocaleData.getInteger(locale, LocaleData.CURRENCY_DIGITS)); properties.setThousandsSeparator(LocaleData.getChar(locale, LocaleData.CURRENCY_THOUSANDS_SEPARATOR)); properties.setDecimalSeparator(LocaleData.getChar(locale, LocaleData.CURRENCY_DECIMAL_SEPARATOR)); properties.setDateOrder((DateOrder) LocaleData.getObject(locale, LocaleData.DATE_ORDER)); properties.setTimeFormat((ProjectTimeFormat) LocaleData.getObject(locale, LocaleData.TIME_FORMAT)); properties.setDefaultStartTime(DateHelper.getTimeFromMinutesPastMidnight(LocaleData.getInteger(locale, LocaleData.DEFAULT_START_TIME))); properties.setDateSeparator(LocaleData.getChar(locale, LocaleData.DATE_SEPARATOR)); properties.setTimeSeparator(LocaleData.getChar(locale, LocaleData.TIME_SEPARATOR)); properties.setAMText(LocaleData.getString(locale, LocaleData.AM_TEXT)); properties.setPMText(LocaleData.getString(locale, LocaleData.PM_TEXT)); properties.setDateFormat((ProjectDateFormat) LocaleData.getObject(locale, LocaleData.DATE_FORMAT)); properties.setBarTextDateFormat((ProjectDateFormat) LocaleData.getObject(locale, LocaleData.DATE_FORMAT)); }
java
public static void setLocale(ProjectProperties properties, Locale locale) { properties.setMpxDelimiter(LocaleData.getChar(locale, LocaleData.FILE_DELIMITER)); properties.setMpxProgramName(LocaleData.getString(locale, LocaleData.PROGRAM_NAME)); properties.setMpxCodePage((CodePage) LocaleData.getObject(locale, LocaleData.CODE_PAGE)); properties.setCurrencySymbol(LocaleData.getString(locale, LocaleData.CURRENCY_SYMBOL)); properties.setSymbolPosition((CurrencySymbolPosition) LocaleData.getObject(locale, LocaleData.CURRENCY_SYMBOL_POSITION)); properties.setCurrencyDigits(LocaleData.getInteger(locale, LocaleData.CURRENCY_DIGITS)); properties.setThousandsSeparator(LocaleData.getChar(locale, LocaleData.CURRENCY_THOUSANDS_SEPARATOR)); properties.setDecimalSeparator(LocaleData.getChar(locale, LocaleData.CURRENCY_DECIMAL_SEPARATOR)); properties.setDateOrder((DateOrder) LocaleData.getObject(locale, LocaleData.DATE_ORDER)); properties.setTimeFormat((ProjectTimeFormat) LocaleData.getObject(locale, LocaleData.TIME_FORMAT)); properties.setDefaultStartTime(DateHelper.getTimeFromMinutesPastMidnight(LocaleData.getInteger(locale, LocaleData.DEFAULT_START_TIME))); properties.setDateSeparator(LocaleData.getChar(locale, LocaleData.DATE_SEPARATOR)); properties.setTimeSeparator(LocaleData.getChar(locale, LocaleData.TIME_SEPARATOR)); properties.setAMText(LocaleData.getString(locale, LocaleData.AM_TEXT)); properties.setPMText(LocaleData.getString(locale, LocaleData.PM_TEXT)); properties.setDateFormat((ProjectDateFormat) LocaleData.getObject(locale, LocaleData.DATE_FORMAT)); properties.setBarTextDateFormat((ProjectDateFormat) LocaleData.getObject(locale, LocaleData.DATE_FORMAT)); }
[ "public", "static", "void", "setLocale", "(", "ProjectProperties", "properties", ",", "Locale", "locale", ")", "{", "properties", ".", "setMpxDelimiter", "(", "LocaleData", ".", "getChar", "(", "locale", ",", "LocaleData", ".", "FILE_DELIMITER", ")", ")", ";", ...
This method is called when the locale of the parent file is updated. It resets the locale specific currency attributes to the default values for the new locale. @param properties project properties @param locale new locale
[ "This", "method", "is", "called", "when", "the", "locale", "of", "the", "parent", "file", "is", "updated", ".", "It", "resets", "the", "locale", "specific", "currency", "attributes", "to", "the", "default", "values", "for", "the", "new", "locale", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/LocaleUtility.java#L58-L79
EdwardRaff/JSAT
JSAT/src/jsat/classifiers/linear/NHERD.java
NHERD.setC
public void setC(double C) { if(Double.isNaN(C) || Double.isInfinite(C) || C <= 0) throw new IllegalArgumentException("C must be a postive constant, not " + C); this.C = C; }
java
public void setC(double C) { if(Double.isNaN(C) || Double.isInfinite(C) || C <= 0) throw new IllegalArgumentException("C must be a postive constant, not " + C); this.C = C; }
[ "public", "void", "setC", "(", "double", "C", ")", "{", "if", "(", "Double", ".", "isNaN", "(", "C", ")", "||", "Double", ".", "isInfinite", "(", "C", ")", "||", "C", "<=", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"C must be a posti...
Set the aggressiveness parameter. Increasing the value of this parameter increases the aggressiveness of the algorithm. It must be a positive value. This parameter essentially performs a type of regularization on the updates @param C the positive aggressiveness parameter
[ "Set", "the", "aggressiveness", "parameter", ".", "Increasing", "the", "value", "of", "this", "parameter", "increases", "the", "aggressiveness", "of", "the", "algorithm", ".", "It", "must", "be", "a", "positive", "value", ".", "This", "parameter", "essentially",...
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/linear/NHERD.java#L130-L135
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java
MultiViewOps.createEssential
public static DMatrixRMaj createEssential(DMatrixRMaj R, Vector3D_F64 T, @Nullable DMatrixRMaj E) { if( E == null ) E = new DMatrixRMaj(3,3); DMatrixRMaj T_hat = GeometryMath_F64.crossMatrix(T, null); CommonOps_DDRM.mult(T_hat, R, E); return E; }
java
public static DMatrixRMaj createEssential(DMatrixRMaj R, Vector3D_F64 T, @Nullable DMatrixRMaj E) { if( E == null ) E = new DMatrixRMaj(3,3); DMatrixRMaj T_hat = GeometryMath_F64.crossMatrix(T, null); CommonOps_DDRM.mult(T_hat, R, E); return E; }
[ "public", "static", "DMatrixRMaj", "createEssential", "(", "DMatrixRMaj", "R", ",", "Vector3D_F64", "T", ",", "@", "Nullable", "DMatrixRMaj", "E", ")", "{", "if", "(", "E", "==", "null", ")", "E", "=", "new", "DMatrixRMaj", "(", "3", ",", "3", ")", ";"...
<p> Computes an essential matrix from a rotation and translation. This motion is the motion from the first camera frame into the second camera frame. The essential matrix 'E' is defined as:<br> E = hat(T)*R<br> where hat(T) is the skew symmetric cross product matrix for vector T. </p> @param R Rotation matrix. @param T Translation vector. @param E (Output) Storage for essential matrix. 3x3 matrix @return Essential matrix
[ "<p", ">", "Computes", "an", "essential", "matrix", "from", "a", "rotation", "and", "translation", ".", "This", "motion", "is", "the", "motion", "from", "the", "first", "camera", "frame", "into", "the", "second", "camera", "frame", ".", "The", "essential", ...
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java#L667-L676
j256/simplecsv
src/main/java/com/j256/simplecsv/processor/CsvProcessor.java
CsvProcessor.validateHeader
public boolean validateHeader(String line, ParseError parseError) throws ParseException { checkEntityConfig(); String[] columns = processHeader(line, parseError); return validateHeaderColumns(columns, parseError, 1); }
java
public boolean validateHeader(String line, ParseError parseError) throws ParseException { checkEntityConfig(); String[] columns = processHeader(line, parseError); return validateHeaderColumns(columns, parseError, 1); }
[ "public", "boolean", "validateHeader", "(", "String", "line", ",", "ParseError", "parseError", ")", "throws", "ParseException", "{", "checkEntityConfig", "(", ")", ";", "String", "[", "]", "columns", "=", "processHeader", "(", "line", ",", "parseError", ")", "...
Validate the header row against the configured header columns. @param line Line to process to get our validate our header. @param parseError If not null, this will be set with the first parse error and it will return null. If this is null then a ParseException will be thrown instead. @return true if the header matched the column names configured here otherwise false. @throws ParseException Thrown on any parsing problems. If parseError is not null then the error will be added there and an exception should not be thrown.
[ "Validate", "the", "header", "row", "against", "the", "configured", "header", "columns", "." ]
train
https://github.com/j256/simplecsv/blob/964fe53073c43e2a311341e3f8fd2c94372f60cb/src/main/java/com/j256/simplecsv/processor/CsvProcessor.java#L327-L331
playn/playn
core/src/playn/core/json/JsonObject.java
JsonObject.getDouble
public double getDouble(String key, double default_) { Object o = get(key); return o instanceof Number ? ((Number) o).doubleValue() : default_; }
java
public double getDouble(String key, double default_) { Object o = get(key); return o instanceof Number ? ((Number) o).doubleValue() : default_; }
[ "public", "double", "getDouble", "(", "String", "key", ",", "double", "default_", ")", "{", "Object", "o", "=", "get", "(", "key", ")", ";", "return", "o", "instanceof", "Number", "?", "(", "(", "Number", ")", "o", ")", ".", "doubleValue", "(", ")", ...
Returns the {@link Double} at the given key, or the default if it does not exist or is the wrong type.
[ "Returns", "the", "{" ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/json/JsonObject.java#L91-L94
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Validate.java
Validate.notNull
public static <T> T notNull(final T object, final String message, final Object... values) { if (object == null) { throw new NullPointerException(StringUtils.simpleFormat(message, values)); } return object; }
java
public static <T> T notNull(final T object, final String message, final Object... values) { if (object == null) { throw new NullPointerException(StringUtils.simpleFormat(message, values)); } return object; }
[ "public", "static", "<", "T", ">", "T", "notNull", "(", "final", "T", "object", ",", "final", "String", "message", ",", "final", "Object", "...", "values", ")", "{", "if", "(", "object", "==", "null", ")", "{", "throw", "new", "NullPointerException", "...
<p>Validate that the specified argument is not {@code null}; otherwise throwing an exception with the specified message. <pre>Validate.notNull(myObject, "The object must not be null");</pre> @param <T> the object type @param object the object to check @param message the {@link String#format(String, Object...)} exception message if invalid, not null @param values the optional values for the formatted exception message @return the validated object (never {@code null} for method chaining) @throws NullPointerException if the object is {@code null} @see #notNull(Object)
[ "<p", ">", "Validate", "that", "the", "specified", "argument", "is", "not", "{", "@code", "null", "}", ";", "otherwise", "throwing", "an", "exception", "with", "the", "specified", "message", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L225-L230
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/i2c/I2CFactory.java
I2CFactory.getInstance
public static I2CBus getInstance(int busNumber, long lockAquireTimeout, TimeUnit lockAquireTimeoutUnit) throws UnsupportedBusNumberException, IOException { return provider.getBus(busNumber, lockAquireTimeout, lockAquireTimeoutUnit); }
java
public static I2CBus getInstance(int busNumber, long lockAquireTimeout, TimeUnit lockAquireTimeoutUnit) throws UnsupportedBusNumberException, IOException { return provider.getBus(busNumber, lockAquireTimeout, lockAquireTimeoutUnit); }
[ "public", "static", "I2CBus", "getInstance", "(", "int", "busNumber", ",", "long", "lockAquireTimeout", ",", "TimeUnit", "lockAquireTimeoutUnit", ")", "throws", "UnsupportedBusNumberException", ",", "IOException", "{", "return", "provider", ".", "getBus", "(", "busNum...
Create new I2CBus instance. @param busNumber The bus number @param lockAquireTimeout The timeout for locking the bus for exclusive communication @param lockAquireTimeoutUnit The units of lockAquireTimeout @return Return a new I2CBus instance @throws UnsupportedBusNumberException If the given bus-number is not supported by the underlying system @throws IOException If communication to i2c-bus fails
[ "Create", "new", "I2CBus", "instance", "." ]
train
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/i2c/I2CFactory.java#L94-L96
hypercube1024/firefly
firefly-common/src/main/java/com/firefly/utils/lang/QuotedStringTokenizer.java
QuotedStringTokenizer.quoteOnly
public static void quoteOnly(Appendable buffer, String input) { if (input == null) return; try { buffer.append('"'); for (int i = 0; i < input.length(); ++i) { char c = input.charAt(i); if (c == '"' || c == '\\') buffer.append('\\'); buffer.append(c); } buffer.append('"'); } catch (IOException x) { throw new RuntimeException(x); } }
java
public static void quoteOnly(Appendable buffer, String input) { if (input == null) return; try { buffer.append('"'); for (int i = 0; i < input.length(); ++i) { char c = input.charAt(i); if (c == '"' || c == '\\') buffer.append('\\'); buffer.append(c); } buffer.append('"'); } catch (IOException x) { throw new RuntimeException(x); } }
[ "public", "static", "void", "quoteOnly", "(", "Appendable", "buffer", ",", "String", "input", ")", "{", "if", "(", "input", "==", "null", ")", "return", ";", "try", "{", "buffer", ".", "append", "(", "'", "'", ")", ";", "for", "(", "int", "i", "=",...
Quote a string into an Appendable. Only quotes and backslash are escaped. @param buffer The Appendable @param input The String to quote.
[ "Quote", "a", "string", "into", "an", "Appendable", ".", "Only", "quotes", "and", "backslash", "are", "escaped", "." ]
train
https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly-common/src/main/java/com/firefly/utils/lang/QuotedStringTokenizer.java#L251-L267
Netflix/servo
servo-core/src/main/java/com/netflix/servo/jmx/ObjectNameBuilder.java
ObjectNameBuilder.addProperty
public ObjectNameBuilder addProperty(String key, String value) { nameStrBuilder.append(sanitizeValue(key)) .append('=') .append(sanitizeValue(value)).append(","); return this; }
java
public ObjectNameBuilder addProperty(String key, String value) { nameStrBuilder.append(sanitizeValue(key)) .append('=') .append(sanitizeValue(value)).append(","); return this; }
[ "public", "ObjectNameBuilder", "addProperty", "(", "String", "key", ",", "String", "value", ")", "{", "nameStrBuilder", ".", "append", "(", "sanitizeValue", "(", "key", ")", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "sanitizeValue", "(", ...
Adds the key/value as a {@link ObjectName} property. @param key the key to add @param value the value to add @return This builder
[ "Adds", "the", "key", "/", "value", "as", "a", "{", "@link", "ObjectName", "}", "property", "." ]
train
https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/jmx/ObjectNameBuilder.java#L100-L105
pac4j/pac4j
pac4j-saml/src/main/java/org/pac4j/saml/config/SAML2Configuration.java
SAML2Configuration.createSelfSignedCert
private X509Certificate createSelfSignedCert(X500Name dn, String sigName, AlgorithmIdentifier sigAlgID, KeyPair keyPair) throws Exception { final V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1))); certGen.setIssuer(dn); certGen.setSubject(dn); certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L))); final Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.YEAR, 1); certGen.setEndDate(new Time(c.getTime())); certGen.setSignature(sigAlgID); certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); Signature sig = Signature.getInstance(sigName); sig.initSign(keyPair.getPrivate()); sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER)); TBSCertificate tbsCert = certGen.generateTBSCertificate(); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgID); v.add(new DERBitString(sig.sign())); final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER))); // check the certificate - this will confirm the encoded sig algorithm ID is correct. cert.verify(keyPair.getPublic()); return cert; }
java
private X509Certificate createSelfSignedCert(X500Name dn, String sigName, AlgorithmIdentifier sigAlgID, KeyPair keyPair) throws Exception { final V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1))); certGen.setIssuer(dn); certGen.setSubject(dn); certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L))); final Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.YEAR, 1); certGen.setEndDate(new Time(c.getTime())); certGen.setSignature(sigAlgID); certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); Signature sig = Signature.getInstance(sigName); sig.initSign(keyPair.getPrivate()); sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER)); TBSCertificate tbsCert = certGen.generateTBSCertificate(); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgID); v.add(new DERBitString(sig.sign())); final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER))); // check the certificate - this will confirm the encoded sig algorithm ID is correct. cert.verify(keyPair.getPublic()); return cert; }
[ "private", "X509Certificate", "createSelfSignedCert", "(", "X500Name", "dn", ",", "String", "sigName", ",", "AlgorithmIdentifier", "sigAlgID", ",", "KeyPair", "keyPair", ")", "throws", "Exception", "{", "final", "V3TBSCertificateGenerator", "certGen", "=", "new", "V3T...
Generate a self-signed certificate for dn using the provided signature algorithm and key pair. @param dn X.500 name to associate with certificate issuer/subject. @param sigName name of the signature algorithm to use. @param sigAlgID algorithm ID associated with the signature algorithm name. @param keyPair the key pair to associate with the certificate. @return an X509Certificate containing the public key in keyPair. @throws Exception
[ "Generate", "a", "self", "-", "signed", "certificate", "for", "dn", "using", "the", "provided", "signature", "algorithm", "and", "key", "pair", "." ]
train
https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-saml/src/main/java/org/pac4j/saml/config/SAML2Configuration.java#L621-L660
Stratio/stratio-cassandra
src/java/org/apache/cassandra/cql3/statements/SelectStatement.java
SelectStatement.addEOC
private static Composite addEOC(Composite composite, Bound eocBound) { return eocBound == Bound.END ? composite.end() : composite.start(); }
java
private static Composite addEOC(Composite composite, Bound eocBound) { return eocBound == Bound.END ? composite.end() : composite.start(); }
[ "private", "static", "Composite", "addEOC", "(", "Composite", "composite", ",", "Bound", "eocBound", ")", "{", "return", "eocBound", "==", "Bound", ".", "END", "?", "composite", ".", "end", "(", ")", ":", "composite", ".", "start", "(", ")", ";", "}" ]
Adds an EOC to the specified Composite. @param composite the composite @param eocBound the EOC bound @return a new <code>Composite</code> with the EOC corresponding to the eocBound
[ "Adds", "an", "EOC", "to", "the", "specified", "Composite", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/statements/SelectStatement.java#L979-L982
awslabs/amazon-sqs-java-messaging-lib
src/main/java/com/amazon/sqs/javamessaging/message/SQSMessage.java
SQSMessage.getPrimitiveProperty
<T> T getPrimitiveProperty(String property, Class<T> type) throws JMSException { if (property == null) { throw new NullPointerException("Property name is null"); } Object value = getObjectProperty(property); if (value == null) { return handleNullPropertyValue(property, type); } T convertedValue = TypeConversionSupport.convert(value, type); if (convertedValue == null) { throw new MessageFormatException("Property " + property + " was " + value.getClass().getName() + " and cannot be read as " + type.getName()); } return convertedValue; }
java
<T> T getPrimitiveProperty(String property, Class<T> type) throws JMSException { if (property == null) { throw new NullPointerException("Property name is null"); } Object value = getObjectProperty(property); if (value == null) { return handleNullPropertyValue(property, type); } T convertedValue = TypeConversionSupport.convert(value, type); if (convertedValue == null) { throw new MessageFormatException("Property " + property + " was " + value.getClass().getName() + " and cannot be read as " + type.getName()); } return convertedValue; }
[ "<", "T", ">", "T", "getPrimitiveProperty", "(", "String", "property", ",", "Class", "<", "T", ">", "type", ")", "throws", "JMSException", "{", "if", "(", "property", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Property name is nu...
Get the value for a property that represents a java primitive(e.g. int or long). @param property The name of the property to get. @param type The type of the property. @return the converted value for the property. @throws JMSException On internal error. @throws MessageFormatException If the property cannot be converted to the specified type. @throws NullPointerException and NumberFormatException when property name or value is null. Method throws same exception as primitives corresponding valueOf(String) method.
[ "Get", "the", "value", "for", "a", "property", "that", "represents", "a", "java", "primitive", "(", "e", ".", "g", ".", "int", "or", "long", ")", "." ]
train
https://github.com/awslabs/amazon-sqs-java-messaging-lib/blob/efa716d34d51ef1c5572790626cdb795419cb342/src/main/java/com/amazon/sqs/javamessaging/message/SQSMessage.java#L457-L471
zxing/zxing
core/src/main/java/com/google/zxing/pdf417/decoder/DecodedBitStreamParser.java
DecodedBitStreamParser.decodeBase900toBase10
private static String decodeBase900toBase10(int[] codewords, int count) throws FormatException { BigInteger result = BigInteger.ZERO; for (int i = 0; i < count; i++) { result = result.add(EXP900[count - i - 1].multiply(BigInteger.valueOf(codewords[i]))); } String resultString = result.toString(); if (resultString.charAt(0) != '1') { throw FormatException.getFormatInstance(); } return resultString.substring(1); }
java
private static String decodeBase900toBase10(int[] codewords, int count) throws FormatException { BigInteger result = BigInteger.ZERO; for (int i = 0; i < count; i++) { result = result.add(EXP900[count - i - 1].multiply(BigInteger.valueOf(codewords[i]))); } String resultString = result.toString(); if (resultString.charAt(0) != '1') { throw FormatException.getFormatInstance(); } return resultString.substring(1); }
[ "private", "static", "String", "decodeBase900toBase10", "(", "int", "[", "]", "codewords", ",", "int", "count", ")", "throws", "FormatException", "{", "BigInteger", "result", "=", "BigInteger", ".", "ZERO", ";", "for", "(", "int", "i", "=", "0", ";", "i", ...
/* EXAMPLE Encode the fifteen digit numeric string 000213298174000 Prefix the numeric string with a 1 and set the initial value of t = 1 000 213 298 174 000 Calculate codeword 0 d0 = 1 000 213 298 174 000 mod 900 = 200 t = 1 000 213 298 174 000 div 900 = 1 111 348 109 082 Calculate codeword 1 d1 = 1 111 348 109 082 mod 900 = 282 t = 1 111 348 109 082 div 900 = 1 234 831 232 Calculate codeword 2 d2 = 1 234 831 232 mod 900 = 632 t = 1 234 831 232 div 900 = 1 372 034 Calculate codeword 3 d3 = 1 372 034 mod 900 = 434 t = 1 372 034 div 900 = 1 524 Calculate codeword 4 d4 = 1 524 mod 900 = 624 t = 1 524 div 900 = 1 Calculate codeword 5 d5 = 1 mod 900 = 1 t = 1 div 900 = 0 Codeword sequence is: 1, 624, 434, 632, 282, 200 Decode the above codewords involves 1 x 900 power of 5 + 624 x 900 power of 4 + 434 x 900 power of 3 + 632 x 900 power of 2 + 282 x 900 power of 1 + 200 x 900 power of 0 = 1000213298174000 Remove leading 1 => Result is 000213298174000
[ "/", "*", "EXAMPLE", "Encode", "the", "fifteen", "digit", "numeric", "string", "000213298174000", "Prefix", "the", "numeric", "string", "with", "a", "1", "and", "set", "the", "initial", "value", "of", "t", "=", "1", "000", "213", "298", "174", "000", "Ca...
train
https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/pdf417/decoder/DecodedBitStreamParser.java#L705-L715
alkacon/opencms-core
src/org/opencms/site/xmlsitemap/CmsXmlSitemapCache.java
CmsXmlSitemapCache.put
public void put(String key, String value) { LOG.info("Caching sitemap for key " + key + ", size = " + value.length()); m_cache.put(key, value); }
java
public void put(String key, String value) { LOG.info("Caching sitemap for key " + key + ", size = " + value.length()); m_cache.put(key, value); }
[ "public", "void", "put", "(", "String", "key", ",", "String", "value", ")", "{", "LOG", ".", "info", "(", "\"Caching sitemap for key \"", "+", "key", "+", "\", size = \"", "+", "value", ".", "length", "(", ")", ")", ";", "m_cache", ".", "put", "(", "ke...
Stores an XML sitemap in the cache.<p> @param key the XML sitemap key (usually the root path of the sitemap.xml) @param value the XML sitemap content
[ "Stores", "an", "XML", "sitemap", "in", "the", "cache", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/site/xmlsitemap/CmsXmlSitemapCache.java#L75-L79
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLinkPersistenceImpl.java
CPDefinitionLinkPersistenceImpl.removeByCPD_T
@Override public void removeByCPD_T(long CPDefinitionId, String type) { for (CPDefinitionLink cpDefinitionLink : findByCPD_T(CPDefinitionId, type, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpDefinitionLink); } }
java
@Override public void removeByCPD_T(long CPDefinitionId, String type) { for (CPDefinitionLink cpDefinitionLink : findByCPD_T(CPDefinitionId, type, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpDefinitionLink); } }
[ "@", "Override", "public", "void", "removeByCPD_T", "(", "long", "CPDefinitionId", ",", "String", "type", ")", "{", "for", "(", "CPDefinitionLink", "cpDefinitionLink", ":", "findByCPD_T", "(", "CPDefinitionId", ",", "type", ",", "QueryUtil", ".", "ALL_POS", ",",...
Removes all the cp definition links where CPDefinitionId = &#63; and type = &#63; from the database. @param CPDefinitionId the cp definition ID @param type the type
[ "Removes", "all", "the", "cp", "definition", "links", "where", "CPDefinitionId", "=", "&#63", ";", "and", "type", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLinkPersistenceImpl.java#L3022-L3028
JOML-CI/JOML
src/org/joml/Matrix3d.java
Matrix3d.rotateYXZ
public Matrix3d rotateYXZ(Vector3d angles) { return rotateYXZ(angles.y, angles.x, angles.z); }
java
public Matrix3d rotateYXZ(Vector3d angles) { return rotateYXZ(angles.y, angles.x, angles.z); }
[ "public", "Matrix3d", "rotateYXZ", "(", "Vector3d", "angles", ")", "{", "return", "rotateYXZ", "(", "angles", ".", "y", ",", "angles", ".", "x", ",", "angles", ".", "z", ")", ";", "}" ]
Apply rotation of <code>angles.y</code> radians about the Y axis, followed by a rotation of <code>angles.x</code> radians about the X axis and followed by a rotation of <code>angles.z</code> radians about the Z axis. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, then the new matrix will be <code>M * R</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the rotation will be applied first! <p> This method is equivalent to calling: <code>rotateY(angles.y).rotateX(angles.x).rotateZ(angles.z)</code> @param angles the Euler angles @return this
[ "Apply", "rotation", "of", "<code", ">", "angles", ".", "y<", "/", "code", ">", "radians", "about", "the", "Y", "axis", "followed", "by", "a", "rotation", "of", "<code", ">", "angles", ".", "x<", "/", "code", ">", "radians", "about", "the", "X", "axi...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3d.java#L2404-L2406
lightblueseas/wicket-js-addons
wicket-js-addons-core/src/main/java/de/alpharogroup/wicket/js/addon/core/JavascriptGenerator.java
JavascriptGenerator.generateJs
public String generateJs(final Settings settings, final String methodName) { // 1. Create an empty map... final Map<String, Object> variables = initializeVariables(settings.asSet()); // 4. Generate the js template with the map and the method name... final String stringTemplateContent = generateJavascriptTemplateContent(variables, methodName); // 5. Create the StringTextTemplate with the generated template... final StringTextTemplate stringTextTemplate = new StringTextTemplate(stringTemplateContent); // 6. Interpolate the template with the values of the map... stringTextTemplate.interpolate(variables); try { // 7. return it as String... return stringTextTemplate.asString(); } finally { try { stringTextTemplate.close(); } catch (final IOException e) { LOGGER.error(e.getMessage(), e); } } }
java
public String generateJs(final Settings settings, final String methodName) { // 1. Create an empty map... final Map<String, Object> variables = initializeVariables(settings.asSet()); // 4. Generate the js template with the map and the method name... final String stringTemplateContent = generateJavascriptTemplateContent(variables, methodName); // 5. Create the StringTextTemplate with the generated template... final StringTextTemplate stringTextTemplate = new StringTextTemplate(stringTemplateContent); // 6. Interpolate the template with the values of the map... stringTextTemplate.interpolate(variables); try { // 7. return it as String... return stringTextTemplate.asString(); } finally { try { stringTextTemplate.close(); } catch (final IOException e) { LOGGER.error(e.getMessage(), e); } } }
[ "public", "String", "generateJs", "(", "final", "Settings", "settings", ",", "final", "String", "methodName", ")", "{", "// 1. Create an empty map...\r", "final", "Map", "<", "String", ",", "Object", ">", "variables", "=", "initializeVariables", "(", "settings", "...
Generate the javascript code. @param settings the settings @param methodName the method name @return the string
[ "Generate", "the", "javascript", "code", "." ]
train
https://github.com/lightblueseas/wicket-js-addons/blob/b1c88c1abafd1e965f2e32ef13d66be0b28d76f6/wicket-js-addons-core/src/main/java/de/alpharogroup/wicket/js/addon/core/JavascriptGenerator.java#L163-L190
Azure/azure-sdk-for-java
containerinstance/resource-manager/v2018_02_01_preview/src/main/java/com/microsoft/azure/management/containerinstance/v2018_02_01_preview/implementation/ContainerGroupsInner.java
ContainerGroupsInner.deleteAsync
public Observable<ContainerGroupInner> deleteAsync(String resourceGroupName, String containerGroupName) { return deleteWithServiceResponseAsync(resourceGroupName, containerGroupName).map(new Func1<ServiceResponse<ContainerGroupInner>, ContainerGroupInner>() { @Override public ContainerGroupInner call(ServiceResponse<ContainerGroupInner> response) { return response.body(); } }); }
java
public Observable<ContainerGroupInner> deleteAsync(String resourceGroupName, String containerGroupName) { return deleteWithServiceResponseAsync(resourceGroupName, containerGroupName).map(new Func1<ServiceResponse<ContainerGroupInner>, ContainerGroupInner>() { @Override public ContainerGroupInner call(ServiceResponse<ContainerGroupInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ContainerGroupInner", ">", "deleteAsync", "(", "String", "resourceGroupName", ",", "String", "containerGroupName", ")", "{", "return", "deleteWithServiceResponseAsync", "(", "resourceGroupName", ",", "containerGroupName", ")", ".", "map", "...
Delete the specified container group. Delete the specified container group in the specified subscription and resource group. The operation does not delete other resources provided by the user, such as volumes. @param resourceGroupName The name of the resource group. @param containerGroupName The name of the container group. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ContainerGroupInner object
[ "Delete", "the", "specified", "container", "group", ".", "Delete", "the", "specified", "container", "group", "in", "the", "specified", "subscription", "and", "resource", "group", ".", "The", "operation", "does", "not", "delete", "other", "resources", "provided", ...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerinstance/resource-manager/v2018_02_01_preview/src/main/java/com/microsoft/azure/management/containerinstance/v2018_02_01_preview/implementation/ContainerGroupsInner.java#L745-L752
twitter/hraven
hraven-core/src/main/java/com/twitter/hraven/datasource/JobHistoryService.java
JobHistoryService.getHbasePuts
public static List<Put> getHbasePuts(JobDesc jobDesc, Configuration jobConf) { List<Put> puts = new LinkedList<Put>(); JobKey jobKey = new JobKey(jobDesc); byte[] jobKeyBytes = new JobKeyConverter().toBytes(jobKey); // Add all columns to one put Put jobPut = new Put(jobKeyBytes); jobPut.addColumn(Constants.INFO_FAM_BYTES, Constants.VERSION_COLUMN_BYTES, Bytes.toBytes(jobDesc.getVersion())); jobPut.addColumn(Constants.INFO_FAM_BYTES, Constants.FRAMEWORK_COLUMN_BYTES, Bytes.toBytes(jobDesc.getFramework().toString())); // Avoid doing string to byte conversion inside loop. byte[] jobConfColumnPrefix = Bytes.toBytes(Constants.JOB_CONF_COLUMN_PREFIX + Constants.SEP); // Create puts for all the parameters in the job configuration Iterator<Entry<String, String>> jobConfIterator = jobConf.iterator(); while (jobConfIterator.hasNext()) { Entry<String, String> entry = jobConfIterator.next(); // Prefix the job conf entry column with an indicator to byte[] column = Bytes.add(jobConfColumnPrefix, Bytes.toBytes(entry.getKey())); jobPut.addColumn(Constants.INFO_FAM_BYTES, column, Bytes.toBytes(entry.getValue())); } // ensure pool/queuename is set correctly setHravenQueueNamePut(jobConf, jobPut, jobKey, jobConfColumnPrefix); puts.add(jobPut); return puts; }
java
public static List<Put> getHbasePuts(JobDesc jobDesc, Configuration jobConf) { List<Put> puts = new LinkedList<Put>(); JobKey jobKey = new JobKey(jobDesc); byte[] jobKeyBytes = new JobKeyConverter().toBytes(jobKey); // Add all columns to one put Put jobPut = new Put(jobKeyBytes); jobPut.addColumn(Constants.INFO_FAM_BYTES, Constants.VERSION_COLUMN_BYTES, Bytes.toBytes(jobDesc.getVersion())); jobPut.addColumn(Constants.INFO_FAM_BYTES, Constants.FRAMEWORK_COLUMN_BYTES, Bytes.toBytes(jobDesc.getFramework().toString())); // Avoid doing string to byte conversion inside loop. byte[] jobConfColumnPrefix = Bytes.toBytes(Constants.JOB_CONF_COLUMN_PREFIX + Constants.SEP); // Create puts for all the parameters in the job configuration Iterator<Entry<String, String>> jobConfIterator = jobConf.iterator(); while (jobConfIterator.hasNext()) { Entry<String, String> entry = jobConfIterator.next(); // Prefix the job conf entry column with an indicator to byte[] column = Bytes.add(jobConfColumnPrefix, Bytes.toBytes(entry.getKey())); jobPut.addColumn(Constants.INFO_FAM_BYTES, column, Bytes.toBytes(entry.getValue())); } // ensure pool/queuename is set correctly setHravenQueueNamePut(jobConf, jobPut, jobKey, jobConfColumnPrefix); puts.add(jobPut); return puts; }
[ "public", "static", "List", "<", "Put", ">", "getHbasePuts", "(", "JobDesc", "jobDesc", ",", "Configuration", "jobConf", ")", "{", "List", "<", "Put", ">", "puts", "=", "new", "LinkedList", "<", "Put", ">", "(", ")", ";", "JobKey", "jobKey", "=", "new"...
Returns the HBase {@code Put} instances to store for the given {@code Configuration} data. Each configuration property will be stored as a separate key value. @param jobDesc the {@link JobDesc} generated for the job @param jobConf the job configuration @return puts for the given job configuration
[ "Returns", "the", "HBase", "{", "@code", "Put", "}", "instances", "to", "store", "for", "the", "given", "{", "@code", "Configuration", "}", "data", ".", "Each", "configuration", "property", "will", "be", "stored", "as", "a", "separate", "key", "value", "."...
train
https://github.com/twitter/hraven/blob/e35996b6e2f016bcd18db0bad320be7c93d95208/hraven-core/src/main/java/com/twitter/hraven/datasource/JobHistoryService.java#L740-L774
playn/playn
core/src/playn/core/Texture.java
Texture.tile
public Tile tile (float x, float y, float width, float height) { final float tileX = x, tileY = y, tileWidth = width, tileHeight = height; return new Tile() { @Override public Texture texture () { return Texture.this; } @Override public float width () { return tileWidth; } @Override public float height () { return tileHeight; } @Override public float sx () { return tileX/displayWidth; } @Override public float sy () { return tileY/displayHeight; } @Override public float tx () { return (tileX+tileWidth)/displayHeight; } @Override public float ty () { return (tileY+tileWidth)/displayHeight; } @Override public void addToBatch (QuadBatch batch, int tint, AffineTransform tx, float x, float y, float width, float height) { batch.addQuad(texture(), tint, tx, x, y, width, height, tileX, tileY, tileWidth, tileHeight); } @Override public void addToBatch (QuadBatch batch, int tint, AffineTransform tx, float dx, float dy, float dw, float dh, float sx, float sy, float sw, float sh) { batch.addQuad(texture(), tint, tx, dx, dy, dw, dh, tileX+sx, tileY+sy, sw, sh); } }; }
java
public Tile tile (float x, float y, float width, float height) { final float tileX = x, tileY = y, tileWidth = width, tileHeight = height; return new Tile() { @Override public Texture texture () { return Texture.this; } @Override public float width () { return tileWidth; } @Override public float height () { return tileHeight; } @Override public float sx () { return tileX/displayWidth; } @Override public float sy () { return tileY/displayHeight; } @Override public float tx () { return (tileX+tileWidth)/displayHeight; } @Override public float ty () { return (tileY+tileWidth)/displayHeight; } @Override public void addToBatch (QuadBatch batch, int tint, AffineTransform tx, float x, float y, float width, float height) { batch.addQuad(texture(), tint, tx, x, y, width, height, tileX, tileY, tileWidth, tileHeight); } @Override public void addToBatch (QuadBatch batch, int tint, AffineTransform tx, float dx, float dy, float dw, float dh, float sx, float sy, float sw, float sh) { batch.addQuad(texture(), tint, tx, dx, dy, dw, dh, tileX+sx, tileY+sy, sw, sh); } }; }
[ "public", "Tile", "tile", "(", "float", "x", ",", "float", "y", ",", "float", "width", ",", "float", "height", ")", "{", "final", "float", "tileX", "=", "x", ",", "tileY", "=", "y", ",", "tileWidth", "=", "width", ",", "tileHeight", "=", "height", ...
Returns an instance that can be used to render a sub-region of this texture.
[ "Returns", "an", "instance", "that", "can", "be", "used", "to", "render", "a", "sub", "-", "region", "of", "this", "texture", "." ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/Texture.java#L182-L202
Alluxio/alluxio
job/server/src/main/java/alluxio/worker/job/task/TaskExecutorManager.java
TaskExecutorManager.executeTask
public synchronized void executeTask(long jobId, int taskId, JobConfig jobConfig, Serializable taskArgs, RunTaskContext context) { Future<?> future = mTaskExecutionService .submit(new TaskExecutor(jobId, taskId, jobConfig, taskArgs, context, this)); Pair<Long, Integer> id = new Pair<>(jobId, taskId); mTaskFutures.put(id, future); TaskInfo.Builder taskInfo = TaskInfo.newBuilder(); taskInfo.setJobId(jobId); taskInfo.setTaskId(taskId); taskInfo.setStatus(Status.RUNNING); mUnfinishedTasks.put(id, taskInfo); mTaskUpdates.put(id, taskInfo.build()); LOG.info("Task {} for job {} started", taskId, jobId); }
java
public synchronized void executeTask(long jobId, int taskId, JobConfig jobConfig, Serializable taskArgs, RunTaskContext context) { Future<?> future = mTaskExecutionService .submit(new TaskExecutor(jobId, taskId, jobConfig, taskArgs, context, this)); Pair<Long, Integer> id = new Pair<>(jobId, taskId); mTaskFutures.put(id, future); TaskInfo.Builder taskInfo = TaskInfo.newBuilder(); taskInfo.setJobId(jobId); taskInfo.setTaskId(taskId); taskInfo.setStatus(Status.RUNNING); mUnfinishedTasks.put(id, taskInfo); mTaskUpdates.put(id, taskInfo.build()); LOG.info("Task {} for job {} started", taskId, jobId); }
[ "public", "synchronized", "void", "executeTask", "(", "long", "jobId", ",", "int", "taskId", ",", "JobConfig", "jobConfig", ",", "Serializable", "taskArgs", ",", "RunTaskContext", "context", ")", "{", "Future", "<", "?", ">", "future", "=", "mTaskExecutionServic...
Executes the given task. @param jobId the job id @param taskId the task id @param jobConfig the job configuration @param taskArgs the arguments @param context the context of the worker
[ "Executes", "the", "given", "task", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/job/server/src/main/java/alluxio/worker/job/task/TaskExecutorManager.java#L128-L141
Netflix/astyanax
astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/Host.java
Host.parsePortFromHostAndPort
public static int parsePortFromHostAndPort(String urlPort, int defaultPort) { return urlPort.lastIndexOf(':') > 0 ? Integer.valueOf(urlPort.substring(urlPort.lastIndexOf(':') + 1, urlPort.length())) : defaultPort; }
java
public static int parsePortFromHostAndPort(String urlPort, int defaultPort) { return urlPort.lastIndexOf(':') > 0 ? Integer.valueOf(urlPort.substring(urlPort.lastIndexOf(':') + 1, urlPort.length())) : defaultPort; }
[ "public", "static", "int", "parsePortFromHostAndPort", "(", "String", "urlPort", ",", "int", "defaultPort", ")", "{", "return", "urlPort", ".", "lastIndexOf", "(", "'", "'", ")", ">", "0", "?", "Integer", ".", "valueOf", "(", "urlPort", ".", "substring", "...
Parse the port from a "hostname:port" formatted string @param urlPort @param defaultPort @return
[ "Parse", "the", "port", "from", "a", "hostname", ":", "port", "formatted", "string" ]
train
https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/Host.java#L118-L121
lessthanoptimal/ejml
main/ejml-zdense/src/org/ejml/dense/row/MatrixFeatures_ZDRM.java
MatrixFeatures_ZDRM.isEquals
public static boolean isEquals(ZMatrixD1 a , ZMatrixD1 b , double tol ) { if( a.numRows != b.numRows || a.numCols != b.numCols ) { return false; } if( tol == 0.0 ) return isEquals(a,b); final int length = a.getDataLength(); for( int i = 0; i < length; i++ ) { if( !(tol >= Math.abs(a.data[i] - b.data[i])) ) { return false; } } return true; }
java
public static boolean isEquals(ZMatrixD1 a , ZMatrixD1 b , double tol ) { if( a.numRows != b.numRows || a.numCols != b.numCols ) { return false; } if( tol == 0.0 ) return isEquals(a,b); final int length = a.getDataLength(); for( int i = 0; i < length; i++ ) { if( !(tol >= Math.abs(a.data[i] - b.data[i])) ) { return false; } } return true; }
[ "public", "static", "boolean", "isEquals", "(", "ZMatrixD1", "a", ",", "ZMatrixD1", "b", ",", "double", "tol", ")", "{", "if", "(", "a", ".", "numRows", "!=", "b", ".", "numRows", "||", "a", ".", "numCols", "!=", "b", ".", "numCols", ")", "{", "ret...
<p> Checks to see if each element in the two matrices are within tolerance of each other: tol &ge; |a<sub>ij</sub> - b<sub>ij</sub>|. <p> <p> NOTE: If any of the elements are not countable then false is returned.<br> NOTE: If a tolerance of zero is passed in this is equivalent to calling {@link #isEquals(ZMatrixD1, ZMatrixD1)} </p> @param a A matrix. Not modified. @param b A matrix. Not modified. @param tol How close to being identical each element needs to be. @return true if equals and false otherwise.
[ "<p", ">", "Checks", "to", "see", "if", "each", "element", "in", "the", "two", "matrices", "are", "within", "tolerance", "of", "each", "other", ":", "tol", "&ge", ";", "|a<sub", ">", "ij<", "/", "sub", ">", "-", "b<sub", ">", "ij<", "/", "sub", ">"...
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-zdense/src/org/ejml/dense/row/MatrixFeatures_ZDRM.java#L154-L171
sculptor/sculptor
sculptor-generator/sculptor-generator-core/src/main/java/org/sculptor/generator/util/HelperBase.java
HelperBase.substringBetween
public String substringBetween(String string, String begin, String end) { return substringBetween(string, begin, end, false); }
java
public String substringBetween(String string, String begin, String end) { return substringBetween(string, begin, end, false); }
[ "public", "String", "substringBetween", "(", "String", "string", ",", "String", "begin", ",", "String", "end", ")", "{", "return", "substringBetween", "(", "string", ",", "begin", ",", "end", ",", "false", ")", ";", "}" ]
Gets a substring between the begin and end boundaries @param string original string @param begin start boundary @param end end boundary @return substring between boundaries
[ "Gets", "a", "substring", "between", "the", "begin", "and", "end", "boundaries" ]
train
https://github.com/sculptor/sculptor/blob/38df06ceb7e40f5f52dbd53b1cd1d07ee11aade5/sculptor-generator/sculptor-generator-core/src/main/java/org/sculptor/generator/util/HelperBase.java#L523-L525
dhemery/hartley
src/main/java/com/dhemery/expressing/Expressive.java
Expressive.waitUntil
public <V> void waitUntil(Sampler<V> variable, Matcher<? super V> criteria) { waitUntil(variable, eventually(), criteria); }
java
public <V> void waitUntil(Sampler<V> variable, Matcher<? super V> criteria) { waitUntil(variable, eventually(), criteria); }
[ "public", "<", "V", ">", "void", "waitUntil", "(", "Sampler", "<", "V", ">", "variable", ",", "Matcher", "<", "?", "super", "V", ">", "criteria", ")", "{", "waitUntil", "(", "variable", ",", "eventually", "(", ")", ",", "criteria", ")", ";", "}" ]
Wait until a polled sample of the variable satisfies the criteria. Uses a default ticker.
[ "Wait", "until", "a", "polled", "sample", "of", "the", "variable", "satisfies", "the", "criteria", ".", "Uses", "a", "default", "ticker", "." ]
train
https://github.com/dhemery/hartley/blob/7754bd6bc12695f2249601b8890da530a61fcf33/src/main/java/com/dhemery/expressing/Expressive.java#L192-L194
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/jetty/jetty/Server.java
Server.addWebApplication
public WebApplicationContext addWebApplication(String contextPathSpec, String webApp) throws IOException { return addWebApplication(null,contextPathSpec,webApp); }
java
public WebApplicationContext addWebApplication(String contextPathSpec, String webApp) throws IOException { return addWebApplication(null,contextPathSpec,webApp); }
[ "public", "WebApplicationContext", "addWebApplication", "(", "String", "contextPathSpec", ",", "String", "webApp", ")", "throws", "IOException", "{", "return", "addWebApplication", "(", "null", ",", "contextPathSpec", ",", "webApp", ")", ";", "}" ]
Add Web Application. @param contextPathSpec The context path spec. Which must be of the form / or /path/* @param webApp The Web application directory or WAR file. @return The WebApplicationContext @exception IOException
[ "Add", "Web", "Application", "." ]
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/jetty/Server.java#L237-L242
prestodb/presto
presto-spi/src/main/java/com/facebook/presto/spi/HostAddress.java
HostAddress.fromParts
public static HostAddress fromParts(String host, int port) { if (!isValidPort(port)) { throw new IllegalArgumentException("Port is invalid: " + port); } HostAddress parsedHost = fromString(host); if (parsedHost.hasPort()) { throw new IllegalArgumentException("host contains a port declaration: " + host); } return new HostAddress(parsedHost.host, port); }
java
public static HostAddress fromParts(String host, int port) { if (!isValidPort(port)) { throw new IllegalArgumentException("Port is invalid: " + port); } HostAddress parsedHost = fromString(host); if (parsedHost.hasPort()) { throw new IllegalArgumentException("host contains a port declaration: " + host); } return new HostAddress(parsedHost.host, port); }
[ "public", "static", "HostAddress", "fromParts", "(", "String", "host", ",", "int", "port", ")", "{", "if", "(", "!", "isValidPort", "(", "port", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Port is invalid: \"", "+", "port", ")", ";", ...
Build a HostAddress instance from separate host and port values. <p> <p>Note: Non-bracketed IPv6 literals are allowed. @param host the host string to parse. Must not contain a port number. @param port a port number from [0..65535] @return if parsing was successful, a populated HostAddress object. @throws IllegalArgumentException if {@code host} contains a port number, or {@code port} is out of range.
[ "Build", "a", "HostAddress", "instance", "from", "separate", "host", "and", "port", "values", ".", "<p", ">", "<p", ">", "Note", ":", "Non", "-", "bracketed", "IPv6", "literals", "are", "allowed", "." ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-spi/src/main/java/com/facebook/presto/spi/HostAddress.java#L136-L146
apache/reef
lang/java/reef-wake/wake/src/main/java/org/apache/reef/wake/avro/ProtocolSerializer.java
ProtocolSerializer.write
public byte[] write(final SpecificRecord message, final long sequence) { final String classId = getClassId(message.getClass()); try (final ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { LOG.log(Level.FINEST, "Serializing message: {0}", classId); final IMessageSerializer serializer = this.nameToSerializerMap.get(classId); if (serializer != null) { serializer.serialize(outputStream, message, sequence); } return outputStream.toByteArray(); } catch (final IOException e) { throw new RuntimeException("Failure writing message: " + classId, e); } }
java
public byte[] write(final SpecificRecord message, final long sequence) { final String classId = getClassId(message.getClass()); try (final ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { LOG.log(Level.FINEST, "Serializing message: {0}", classId); final IMessageSerializer serializer = this.nameToSerializerMap.get(classId); if (serializer != null) { serializer.serialize(outputStream, message, sequence); } return outputStream.toByteArray(); } catch (final IOException e) { throw new RuntimeException("Failure writing message: " + classId, e); } }
[ "public", "byte", "[", "]", "write", "(", "final", "SpecificRecord", "message", ",", "final", "long", "sequence", ")", "{", "final", "String", "classId", "=", "getClassId", "(", "message", ".", "getClass", "(", ")", ")", ";", "try", "(", "final", "ByteAr...
Marshall the input message to a byte array. @param message The message to be marshaled into a byte array. @param sequence The unique sequence number of the message.
[ "Marshall", "the", "input", "message", "to", "a", "byte", "array", "." ]
train
https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-wake/wake/src/main/java/org/apache/reef/wake/avro/ProtocolSerializer.java#L111-L128
strator-dev/greenpepper
greenpepper-maven-plugin/src/main/java/com/greenpepper/maven/AbstractJarMojo.java
AbstractJarMojo.getJarFile
protected static File getJarFile( File basedir, String finalName, String classifier ) { if ( classifier == null ) { classifier = ""; } else if ( classifier.trim().length() > 0 && !classifier.startsWith( "-" ) ) { classifier = "-" + classifier; } return new File( basedir, finalName + classifier + ".jar" ); }
java
protected static File getJarFile( File basedir, String finalName, String classifier ) { if ( classifier == null ) { classifier = ""; } else if ( classifier.trim().length() > 0 && !classifier.startsWith( "-" ) ) { classifier = "-" + classifier; } return new File( basedir, finalName + classifier + ".jar" ); }
[ "protected", "static", "File", "getJarFile", "(", "File", "basedir", ",", "String", "finalName", ",", "String", "classifier", ")", "{", "if", "(", "classifier", "==", "null", ")", "{", "classifier", "=", "\"\"", ";", "}", "else", "if", "(", "classifier", ...
<p>getJarFile.</p> @param basedir a {@link java.io.File} object. @param finalName a {@link java.lang.String} object. @param classifier a {@link java.lang.String} object. @return a {@link java.io.File} object.
[ "<p", ">", "getJarFile", ".", "<", "/", "p", ">" ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper-maven-plugin/src/main/java/com/greenpepper/maven/AbstractJarMojo.java#L138-L150
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/CircuitsConfig.java
CircuitsConfig.exports
public static void exports(Media media, Collection<Media> levels, Media sheetsConfig, Media groupsConfig) { Check.notNull(media); Check.notNull(levels); Check.notNull(sheetsConfig); Check.notNull(groupsConfig); final CircuitsExtractor extractor = new CircuitsExtractorImpl(); final Map<Circuit, Collection<TileRef>> circuits = extractor.getCircuits(levels, sheetsConfig, groupsConfig); exports(media, circuits); }
java
public static void exports(Media media, Collection<Media> levels, Media sheetsConfig, Media groupsConfig) { Check.notNull(media); Check.notNull(levels); Check.notNull(sheetsConfig); Check.notNull(groupsConfig); final CircuitsExtractor extractor = new CircuitsExtractorImpl(); final Map<Circuit, Collection<TileRef>> circuits = extractor.getCircuits(levels, sheetsConfig, groupsConfig); exports(media, circuits); }
[ "public", "static", "void", "exports", "(", "Media", "media", ",", "Collection", "<", "Media", ">", "levels", ",", "Media", "sheetsConfig", ",", "Media", "groupsConfig", ")", "{", "Check", ".", "notNull", "(", "media", ")", ";", "Check", ".", "notNull", ...
Export all circuits to an XML file. @param media The export output (must not be <code>null</code>). @param levels The level rips used (must not be <code>null</code>). @param sheetsConfig The sheets media (must not be <code>null</code>). @param groupsConfig The groups media (must not be <code>null</code>). @throws LionEngineException If error on export.
[ "Export", "all", "circuits", "to", "an", "XML", "file", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/CircuitsConfig.java#L100-L110
ops4j/org.ops4j.pax.logging
pax-logging-service/src/main/java/org/apache/log4j/receivers/rewrite/PropertyRewritePolicy.java
PropertyRewritePolicy.setProperties
public void setProperties(String props) { Map hashTable = new HashMap(); StringTokenizer pairs = new StringTokenizer(props, ","); while (pairs.hasMoreTokens()) { StringTokenizer entry = new StringTokenizer(pairs.nextToken(), "="); hashTable.put(entry.nextElement().toString().trim(), entry.nextElement().toString().trim()); } synchronized(this) { properties = hashTable; } }
java
public void setProperties(String props) { Map hashTable = new HashMap(); StringTokenizer pairs = new StringTokenizer(props, ","); while (pairs.hasMoreTokens()) { StringTokenizer entry = new StringTokenizer(pairs.nextToken(), "="); hashTable.put(entry.nextElement().toString().trim(), entry.nextElement().toString().trim()); } synchronized(this) { properties = hashTable; } }
[ "public", "void", "setProperties", "(", "String", "props", ")", "{", "Map", "hashTable", "=", "new", "HashMap", "(", ")", ";", "StringTokenizer", "pairs", "=", "new", "StringTokenizer", "(", "props", ",", "\",\"", ")", ";", "while", "(", "pairs", ".", "h...
Set a string representing the property name/value pairs. Form: propname1=propvalue1,propname2=propvalue2 @param props
[ "Set", "a", "string", "representing", "the", "property", "name", "/", "value", "pairs", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-service/src/main/java/org/apache/log4j/receivers/rewrite/PropertyRewritePolicy.java#L45-L55
wcm-io-caravan/caravan-hal
docs-maven-plugin/src/main/java/io/wcm/caravan/maven/plugins/haldocs/GenerateHalDocsJsonMojo.java
GenerateHalDocsJsonMojo.getAnnotation
private <T extends Annotation> T getAnnotation(JavaClass javaClazz, JavaField javaField, ClassLoader compileClassLoader, Class<T> annotationType) { try { Class<?> clazz = compileClassLoader.loadClass(javaClazz.getFullyQualifiedName()); Field field = clazz.getField(javaField.getName()); return field.getAnnotation(annotationType); } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException ex) { throw new RuntimeException("Unable to get contanst value of field '" + javaClazz.getName() + "#" + javaField.getName() + ":\n" + ex.getMessage(), ex); } }
java
private <T extends Annotation> T getAnnotation(JavaClass javaClazz, JavaField javaField, ClassLoader compileClassLoader, Class<T> annotationType) { try { Class<?> clazz = compileClassLoader.loadClass(javaClazz.getFullyQualifiedName()); Field field = clazz.getField(javaField.getName()); return field.getAnnotation(annotationType); } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException ex) { throw new RuntimeException("Unable to get contanst value of field '" + javaClazz.getName() + "#" + javaField.getName() + ":\n" + ex.getMessage(), ex); } }
[ "private", "<", "T", "extends", "Annotation", ">", "T", "getAnnotation", "(", "JavaClass", "javaClazz", ",", "JavaField", "javaField", ",", "ClassLoader", "compileClassLoader", ",", "Class", "<", "T", ">", "annotationType", ")", "{", "try", "{", "Class", "<", ...
Get annotation for field. @param javaClazz QDox class @param javaField QDox field @param compileClassLoader Classloader for compile dependencies @param annotationType Annotation type @return Annotation of null if not present
[ "Get", "annotation", "for", "field", "." ]
train
https://github.com/wcm-io-caravan/caravan-hal/blob/25d58756b58c70c8c48a17fe781e673dd93d5085/docs-maven-plugin/src/main/java/io/wcm/caravan/maven/plugins/haldocs/GenerateHalDocsJsonMojo.java#L349-L358
ribot/easy-adapter
demo/src/main/java/uk/co/ribot/easyadapterdemo/PersonViewHolder.java
PersonViewHolder.onSetValues
@Override public void onSetValues(Person person, PositionInfo positionInfo) { imageViewPerson.setImageResource(person.getResDrawableId()); textViewName.setText(person.getName()); textViewPhone.setText(person.getPhoneNumber()); }
java
@Override public void onSetValues(Person person, PositionInfo positionInfo) { imageViewPerson.setImageResource(person.getResDrawableId()); textViewName.setText(person.getName()); textViewPhone.setText(person.getPhoneNumber()); }
[ "@", "Override", "public", "void", "onSetValues", "(", "Person", "person", ",", "PositionInfo", "positionInfo", ")", "{", "imageViewPerson", ".", "setImageResource", "(", "person", ".", "getResDrawableId", "(", ")", ")", ";", "textViewName", ".", "setText", "(",...
Override onSetValues() to set the values of the items in the views.
[ "Override", "onSetValues", "()", "to", "set", "the", "values", "of", "the", "items", "in", "the", "views", "." ]
train
https://github.com/ribot/easy-adapter/blob/8cf85023a79c781aa2013e9dc39fd66734fb2019/demo/src/main/java/uk/co/ribot/easyadapterdemo/PersonViewHolder.java#L52-L57
kaazing/gateway
mina.core/core/src/main/java/org/apache/mina/core/session/AbstractIoSession.java
AbstractIoSession.notifyIdleness
public static void notifyIdleness(Iterator<? extends IoSession> sessions, long currentTime) { IoSession s; while (sessions.hasNext()) { s = sessions.next(); notifyIdleSession(s, currentTime); } }
java
public static void notifyIdleness(Iterator<? extends IoSession> sessions, long currentTime) { IoSession s; while (sessions.hasNext()) { s = sessions.next(); notifyIdleSession(s, currentTime); } }
[ "public", "static", "void", "notifyIdleness", "(", "Iterator", "<", "?", "extends", "IoSession", ">", "sessions", ",", "long", "currentTime", ")", "{", "IoSession", "s", ";", "while", "(", "sessions", ".", "hasNext", "(", ")", ")", "{", "s", "=", "sessio...
Fires a {@link IoEventType#SESSION_IDLE} event to any applicable sessions in the specified collection. @param currentTime the current time (i.e. {@link System#currentTimeMillis()})
[ "Fires", "a", "{", "@link", "IoEventType#SESSION_IDLE", "}", "event", "to", "any", "applicable", "sessions", "in", "the", "specified", "collection", "." ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.core/core/src/main/java/org/apache/mina/core/session/AbstractIoSession.java#L1199-L1205
mercadopago/dx-java
src/main/java/com/mercadopago/core/MPCache.java
MPCache.addToCache
static void addToCache(String key, MPApiResponse response) { HashMap<String, MPApiResponse> mapCache = getMapCache(); mapCache.put(key, response); }
java
static void addToCache(String key, MPApiResponse response) { HashMap<String, MPApiResponse> mapCache = getMapCache(); mapCache.put(key, response); }
[ "static", "void", "addToCache", "(", "String", "key", ",", "MPApiResponse", "response", ")", "{", "HashMap", "<", "String", ",", "MPApiResponse", ">", "mapCache", "=", "getMapCache", "(", ")", ";", "mapCache", ".", "put", "(", "key", ",", "response", ")", ...
Inserts an entry to the cache. @param key String with cache entry key @param response MPApiResponse object to be cached
[ "Inserts", "an", "entry", "to", "the", "cache", "." ]
train
https://github.com/mercadopago/dx-java/blob/9df65a6bfb4db0c1fddd7699a5b109643961b03f/src/main/java/com/mercadopago/core/MPCache.java#L35-L38
jcuda/jcudnn
JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java
JCudnn.cudnnLRNCrossChannelForward
public static int cudnnLRNCrossChannelForward( cudnnHandle handle, cudnnLRNDescriptor normDesc, int lrnMode, Pointer alpha, cudnnTensorDescriptor xDesc, Pointer x, Pointer beta, cudnnTensorDescriptor yDesc, Pointer y) { return checkResult(cudnnLRNCrossChannelForwardNative(handle, normDesc, lrnMode, alpha, xDesc, x, beta, yDesc, y)); }
java
public static int cudnnLRNCrossChannelForward( cudnnHandle handle, cudnnLRNDescriptor normDesc, int lrnMode, Pointer alpha, cudnnTensorDescriptor xDesc, Pointer x, Pointer beta, cudnnTensorDescriptor yDesc, Pointer y) { return checkResult(cudnnLRNCrossChannelForwardNative(handle, normDesc, lrnMode, alpha, xDesc, x, beta, yDesc, y)); }
[ "public", "static", "int", "cudnnLRNCrossChannelForward", "(", "cudnnHandle", "handle", ",", "cudnnLRNDescriptor", "normDesc", ",", "int", "lrnMode", ",", "Pointer", "alpha", ",", "cudnnTensorDescriptor", "xDesc", ",", "Pointer", "x", ",", "Pointer", "beta", ",", ...
LRN cross-channel forward computation. Double parameters cast to tensor data type
[ "LRN", "cross", "-", "channel", "forward", "computation", ".", "Double", "parameters", "cast", "to", "tensor", "data", "type" ]
train
https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L2054-L2066
sporniket/core
sporniket-core-io/src/main/java/com/sporniket/libre/io/TextLoader.java
TextLoader.append
public StringBuffer append(InputStream source, StringBuffer buffer) throws IOException { Reader _reader = FileTools.createReaderForInputStream(source, getEncoding()); return append(_reader, buffer); }
java
public StringBuffer append(InputStream source, StringBuffer buffer) throws IOException { Reader _reader = FileTools.createReaderForInputStream(source, getEncoding()); return append(_reader, buffer); }
[ "public", "StringBuffer", "append", "(", "InputStream", "source", ",", "StringBuffer", "buffer", ")", "throws", "IOException", "{", "Reader", "_reader", "=", "FileTools", ".", "createReaderForInputStream", "(", "source", ",", "getEncoding", "(", ")", ")", ";", "...
Load a text from the specified file and put it in the provided StringBuffer. @param source source stream. @param buffer buffer to load text into. @return the buffer @throws IOException if there is a problem to deal with.
[ "Load", "a", "text", "from", "the", "specified", "file", "and", "put", "it", "in", "the", "provided", "StringBuffer", "." ]
train
https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-io/src/main/java/com/sporniket/libre/io/TextLoader.java#L174-L178
openbase/jul
visual/javafx/src/main/java/org/openbase/jul/visual/javafx/geometry/svg/SVGIcon.java
SVGIcon.setBackgroundIconColorAnimated
public void setBackgroundIconColorAnimated(final Color color, final int cycleCount) { if (backgroundIcon == null) { LOGGER.warn("Background modification skipped because background icon not set!"); return; } stopBackgroundIconColorFadeAnimation(); backgroundFadeIcon.setFill(color); backgroundIconColorFadeAnimation = Animations.createFadeTransition(backgroundFadeIcon, JFXConstants.TRANSPARENCY_FULLY, JFXConstants.TRANSPARENCY_NONE, cycleCount, JFXConstants.ANIMATION_DURATION_FADE_DEFAULT); backgroundIconColorFadeAnimation.setOnFinished(event -> { backgroundFadeIcon.setFill(color); backgroundFadeIcon.setOpacity(JFXConstants.TRANSPARENCY_FULLY); }); backgroundIconColorFadeAnimation.play(); }
java
public void setBackgroundIconColorAnimated(final Color color, final int cycleCount) { if (backgroundIcon == null) { LOGGER.warn("Background modification skipped because background icon not set!"); return; } stopBackgroundIconColorFadeAnimation(); backgroundFadeIcon.setFill(color); backgroundIconColorFadeAnimation = Animations.createFadeTransition(backgroundFadeIcon, JFXConstants.TRANSPARENCY_FULLY, JFXConstants.TRANSPARENCY_NONE, cycleCount, JFXConstants.ANIMATION_DURATION_FADE_DEFAULT); backgroundIconColorFadeAnimation.setOnFinished(event -> { backgroundFadeIcon.setFill(color); backgroundFadeIcon.setOpacity(JFXConstants.TRANSPARENCY_FULLY); }); backgroundIconColorFadeAnimation.play(); }
[ "public", "void", "setBackgroundIconColorAnimated", "(", "final", "Color", "color", ",", "final", "int", "cycleCount", ")", "{", "if", "(", "backgroundIcon", "==", "null", ")", "{", "LOGGER", ".", "warn", "(", "\"Background modification skipped because background icon...
Allows to set a new color to the backgroundIcon icon and setAnimation its change (by a FadeTransition). @param color the color for the backgroundIcon icon to be setfeature-rights-and-access-management @param cycleCount the number of times the animation should be played (use Animation.INDEFINITE for endless)
[ "Allows", "to", "set", "a", "new", "color", "to", "the", "backgroundIcon", "icon", "and", "setAnimation", "its", "change", "(", "by", "a", "FadeTransition", ")", "." ]
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/visual/javafx/src/main/java/org/openbase/jul/visual/javafx/geometry/svg/SVGIcon.java#L334-L347
dustin/java-memcached-client
src/main/java/net/spy/memcached/MemcachedClient.java
MemcachedClient.asyncDecr
@Override public OperationFuture<Long> asyncDecr(String key, int by, long def, int exp) { return asyncMutate(Mutator.decr, key, by, def, exp); }
java
@Override public OperationFuture<Long> asyncDecr(String key, int by, long def, int exp) { return asyncMutate(Mutator.decr, key, by, def, exp); }
[ "@", "Override", "public", "OperationFuture", "<", "Long", ">", "asyncDecr", "(", "String", "key", ",", "int", "by", ",", "long", "def", ",", "int", "exp", ")", "{", "return", "asyncMutate", "(", "Mutator", ".", "decr", ",", "key", ",", "by", ",", "d...
Asynchronous decrement. @param key key to decrement @param by the amount to decrement the value by @param def the default value (if the counter does not exist) @param exp the expiration of this object @return a future with the decremented value, or -1 if the decrement failed. @throws IllegalStateException in the rare circumstance where queue is too full to accept any more requests
[ "Asynchronous", "decrement", "." ]
train
https://github.com/dustin/java-memcached-client/blob/c232307ad8e0c7ccc926e495dd7d5aad2d713318/src/main/java/net/spy/memcached/MemcachedClient.java#L2127-L2131
h2oai/h2o-3
h2o-core/src/main/java/water/rapids/Session.java
Session.addRefCnt
private int addRefCnt(Key<Vec> vec, int i) { return _addRefCnt(vec, i) + (GLOBALS.contains(vec) ? 1 : 0); }
java
private int addRefCnt(Key<Vec> vec, int i) { return _addRefCnt(vec, i) + (GLOBALS.contains(vec) ? 1 : 0); }
[ "private", "int", "addRefCnt", "(", "Key", "<", "Vec", ">", "vec", ",", "int", "i", ")", "{", "return", "_addRefCnt", "(", "vec", ",", "i", ")", "+", "(", "GLOBALS", ".", "contains", "(", "vec", ")", "?", "1", ":", "0", ")", ";", "}" ]
RefCnt +i this Vec; Global Refs can be alive with zero internal counts
[ "RefCnt", "+", "i", "this", "Vec", ";", "Global", "Refs", "can", "be", "alive", "with", "zero", "internal", "counts" ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/rapids/Session.java#L187-L189
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Solo.java
Solo.getView
public View getView(int id, int index){ if(config.commandLogging){ Log.d(config.commandLoggingTag, "getView("+id+", "+index+")"); } View viewToReturn = getter.getView(id, index); if(viewToReturn == null) { String resourceName = ""; try { resourceName = instrumentation.getTargetContext().getResources().getResourceEntryName(id); } catch (Exception e) { Log.d(config.commandLoggingTag, "unable to get resource entry name for ("+id+")"); } int match = index + 1; if(match > 1){ Assert.fail(match + " Views with id: '" + id + "', resource name: '" + resourceName + "' are not found!"); } else { Assert.fail("View with id: '" + id + "', resource name: '" + resourceName + "' is not found!"); } } return viewToReturn; }
java
public View getView(int id, int index){ if(config.commandLogging){ Log.d(config.commandLoggingTag, "getView("+id+", "+index+")"); } View viewToReturn = getter.getView(id, index); if(viewToReturn == null) { String resourceName = ""; try { resourceName = instrumentation.getTargetContext().getResources().getResourceEntryName(id); } catch (Exception e) { Log.d(config.commandLoggingTag, "unable to get resource entry name for ("+id+")"); } int match = index + 1; if(match > 1){ Assert.fail(match + " Views with id: '" + id + "', resource name: '" + resourceName + "' are not found!"); } else { Assert.fail("View with id: '" + id + "', resource name: '" + resourceName + "' is not found!"); } } return viewToReturn; }
[ "public", "View", "getView", "(", "int", "id", ",", "int", "index", ")", "{", "if", "(", "config", ".", "commandLogging", ")", "{", "Log", ".", "d", "(", "config", ".", "commandLoggingTag", ",", "\"getView(\"", "+", "id", "+", "\", \"", "+", "index", ...
Returns a View matching the specified resource id and index. @param id the R.id of the {@link View} to return @param index the index of the {@link View}. {@code 0} if only one is available @return a {@link View} matching the specified id and index
[ "Returns", "a", "View", "matching", "the", "specified", "resource", "id", "and", "index", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L3041-L3064
d-sauer/JCalcAPI
src/main/java/org/jdice/calc/Num.java
Num.cleanNumber
private static String cleanNumber(String value, char decimalSeparator) { String regex = "[^0-9-" + decimalSeparator + "]"; if (decimalSeparator == '.') regex = regex.replace(".", "\\."); String strip = value.replaceAll(regex, ""); strip = strip.replace(decimalSeparator + "", Properties.DEFAULT_DECIMAL_SEPARATOR + ""); return strip; }
java
private static String cleanNumber(String value, char decimalSeparator) { String regex = "[^0-9-" + decimalSeparator + "]"; if (decimalSeparator == '.') regex = regex.replace(".", "\\."); String strip = value.replaceAll(regex, ""); strip = strip.replace(decimalSeparator + "", Properties.DEFAULT_DECIMAL_SEPARATOR + ""); return strip; }
[ "private", "static", "String", "cleanNumber", "(", "String", "value", ",", "char", "decimalSeparator", ")", "{", "String", "regex", "=", "\"[^0-9-\"", "+", "decimalSeparator", "+", "\"]\"", ";", "if", "(", "decimalSeparator", "==", "'", "'", ")", "regex", "=...
Remove from string number representation all character except numbers and decimal point. <br> And replace given decimalSeparator with '.' <pre> ("44,551.06", '.') => 44551.06 ("1 255 844,551.06", '.') => 1255844551.06 ("44,551..06", '.') => 44551.06 </pre> @param decimalSeparator @param value
[ "Remove", "from", "string", "number", "representation", "all", "character", "except", "numbers", "and", "decimal", "point", ".", "<br", ">", "And", "replace", "given", "decimalSeparator", "with", "." ]
train
https://github.com/d-sauer/JCalcAPI/blob/36ae1f9adfe611a6f1bd8ef87cf1dc0ec88ac035/src/main/java/org/jdice/calc/Num.java#L915-L923
carewebframework/carewebframework-core
org.carewebframework.help-parent/org.carewebframework.help.core/src/main/java/org/carewebframework/help/HelpModule.java
HelpModule.getLocalizedId
public static String getLocalizedId(String id, Locale locale) { String locstr = locale == null ? "" : ("_" + locale.toString()); return id + locstr; }
java
public static String getLocalizedId(String id, Locale locale) { String locstr = locale == null ? "" : ("_" + locale.toString()); return id + locstr; }
[ "public", "static", "String", "getLocalizedId", "(", "String", "id", ",", "Locale", "locale", ")", "{", "String", "locstr", "=", "locale", "==", "null", "?", "\"\"", ":", "(", "\"_\"", "+", "locale", ".", "toString", "(", ")", ")", ";", "return", "id",...
Adds locale information to a help module id. @param id Help module id. @param locale Locale (may be null). @return The id with locale information appended.
[ "Adds", "locale", "information", "to", "a", "help", "module", "id", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.help-parent/org.carewebframework.help.core/src/main/java/org/carewebframework/help/HelpModule.java#L68-L71
knowm/Yank
src/main/java/org/knowm/yank/Yank.java
Yank.queryBeanListSQLKey
public static <T> List<T> queryBeanListSQLKey(String sqlKey, Class<T> beanType, Object[] params) throws SQLStatementNotFoundException, YankSQLException { return queryBeanListSQLKey(YankPoolManager.DEFAULT_POOL_NAME, sqlKey, beanType, params); }
java
public static <T> List<T> queryBeanListSQLKey(String sqlKey, Class<T> beanType, Object[] params) throws SQLStatementNotFoundException, YankSQLException { return queryBeanListSQLKey(YankPoolManager.DEFAULT_POOL_NAME, sqlKey, beanType, params); }
[ "public", "static", "<", "T", ">", "List", "<", "T", ">", "queryBeanListSQLKey", "(", "String", "sqlKey", ",", "Class", "<", "T", ">", "beanType", ",", "Object", "[", "]", "params", ")", "throws", "SQLStatementNotFoundException", ",", "YankSQLException", "{"...
Return a List of Beans given a SQL Key using an SQL statement matching the sqlKey String in a properties file loaded via Yank.addSQLStatements(...) using the default connection pool. @param sqlKey The SQL Key found in a properties file corresponding to the desired SQL statement value @param beanType The Class of the desired return Objects matching the table @param params The replacement parameters @return The List of Objects @throws SQLStatementNotFoundException if an SQL statement could not be found for the given sqlKey String
[ "Return", "a", "List", "of", "Beans", "given", "a", "SQL", "Key", "using", "an", "SQL", "statement", "matching", "the", "sqlKey", "String", "in", "a", "properties", "file", "loaded", "via", "Yank", ".", "addSQLStatements", "(", "...", ")", "using", "the", ...
train
https://github.com/knowm/Yank/blob/b2071dcd94da99db6904355f9557456b8b292a6b/src/main/java/org/knowm/yank/Yank.java#L431-L435
alkacon/opencms-core
src/org/opencms/ui/dialogs/CmsDeleteDialog.java
CmsDeleteDialog.getBrokenLinks
public static Multimap<CmsResource, CmsResource> getBrokenLinks( CmsObject cms, List<CmsResource> selectedResources, boolean includeSiblings) throws CmsException { return getBrokenLinks(cms, selectedResources, includeSiblings, false); }
java
public static Multimap<CmsResource, CmsResource> getBrokenLinks( CmsObject cms, List<CmsResource> selectedResources, boolean includeSiblings) throws CmsException { return getBrokenLinks(cms, selectedResources, includeSiblings, false); }
[ "public", "static", "Multimap", "<", "CmsResource", ",", "CmsResource", ">", "getBrokenLinks", "(", "CmsObject", "cms", ",", "List", "<", "CmsResource", ">", "selectedResources", ",", "boolean", "includeSiblings", ")", "throws", "CmsException", "{", "return", "get...
Gets the broken links.<p> @param cms the CMS context @param selectedResources the selected resources @param includeSiblings <code>true</code> if siblings would be deleted too @return multimap of broken links, with sources as keys and targets as values @throws CmsException if something goes wrong
[ "Gets", "the", "broken", "links", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/dialogs/CmsDeleteDialog.java#L191-L199
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/cert/X509CertSelector.java
X509CertSelector.setIssuer
public void setIssuer(byte[] issuerDN) throws IOException { try { issuer = (issuerDN == null ? null : new X500Principal(issuerDN)); } catch (IllegalArgumentException e) { throw new IOException("Invalid name", e); } }
java
public void setIssuer(byte[] issuerDN) throws IOException { try { issuer = (issuerDN == null ? null : new X500Principal(issuerDN)); } catch (IllegalArgumentException e) { throw new IOException("Invalid name", e); } }
[ "public", "void", "setIssuer", "(", "byte", "[", "]", "issuerDN", ")", "throws", "IOException", "{", "try", "{", "issuer", "=", "(", "issuerDN", "==", "null", "?", "null", ":", "new", "X500Principal", "(", "issuerDN", ")", ")", ";", "}", "catch", "(", ...
Sets the issuer criterion. The specified distinguished name must match the issuer distinguished name in the {@code X509Certificate}. If {@code null} is specified, the issuer criterion is disabled and any issuer distinguished name will do. <p> If {@code issuerDN} is not {@code null}, it should contain a single DER encoded distinguished name, as defined in X.501. The ASN.1 notation for this structure is as follows. <pre>{@code Name ::= CHOICE { RDNSequence } RDNSequence ::= SEQUENCE OF RelativeDistinguishedName RelativeDistinguishedName ::= SET SIZE (1 .. MAX) OF AttributeTypeAndValue AttributeTypeAndValue ::= SEQUENCE { type AttributeType, value AttributeValue } AttributeType ::= OBJECT IDENTIFIER AttributeValue ::= ANY DEFINED BY AttributeType .... DirectoryString ::= CHOICE { teletexString TeletexString (SIZE (1..MAX)), printableString PrintableString (SIZE (1..MAX)), universalString UniversalString (SIZE (1..MAX)), utf8String UTF8String (SIZE (1.. MAX)), bmpString BMPString (SIZE (1..MAX)) } }</pre> <p> Note that the byte array specified here is cloned to protect against subsequent modifications. @param issuerDN a byte array containing the distinguished name in ASN.1 DER encoded form (or {@code null}) @throws IOException if an encoding error occurs (incorrect form for DN)
[ "Sets", "the", "issuer", "criterion", ".", "The", "specified", "distinguished", "name", "must", "match", "the", "issuer", "distinguished", "name", "in", "the", "{", "@code", "X509Certificate", "}", ".", "If", "{", "@code", "null", "}", "is", "specified", "th...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/cert/X509CertSelector.java#L277-L283
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSImage.java
FSImage.loadFSImage
protected void loadFSImage(ImageInputStream iis, File imageFile) throws IOException { MD5Hash expectedMD5 = MD5FileUtils.readStoredMd5ForFile(imageFile); if (expectedMD5 == null) { throw new IOException("No MD5 file found corresponding to image file " + imageFile); } iis.setImageDigest(expectedMD5); loadFSImage(iis); }
java
protected void loadFSImage(ImageInputStream iis, File imageFile) throws IOException { MD5Hash expectedMD5 = MD5FileUtils.readStoredMd5ForFile(imageFile); if (expectedMD5 == null) { throw new IOException("No MD5 file found corresponding to image file " + imageFile); } iis.setImageDigest(expectedMD5); loadFSImage(iis); }
[ "protected", "void", "loadFSImage", "(", "ImageInputStream", "iis", ",", "File", "imageFile", ")", "throws", "IOException", "{", "MD5Hash", "expectedMD5", "=", "MD5FileUtils", ".", "readStoredMd5ForFile", "(", "imageFile", ")", ";", "if", "(", "expectedMD5", "==",...
Load the image namespace from the given image file, verifying it against the MD5 sum stored in its associated .md5 file.
[ "Load", "the", "image", "namespace", "from", "the", "given", "image", "file", "verifying", "it", "against", "the", "MD5", "sum", "stored", "in", "its", "associated", ".", "md5", "file", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSImage.java#L825-L833
jbundle/jbundle
thin/base/db/misc/src/main/java/org/jbundle/thin/base/db/client/SyncRemoteTable.java
SyncRemoteTable.doRemoteAction
public Object doRemoteAction(String strCommand, Map<String, Object> properties) throws DBException, RemoteException { synchronized(m_objSync) { return m_tableRemote.doRemoteAction(strCommand, properties); } }
java
public Object doRemoteAction(String strCommand, Map<String, Object> properties) throws DBException, RemoteException { synchronized(m_objSync) { return m_tableRemote.doRemoteAction(strCommand, properties); } }
[ "public", "Object", "doRemoteAction", "(", "String", "strCommand", ",", "Map", "<", "String", ",", "Object", ">", "properties", ")", "throws", "DBException", ",", "RemoteException", "{", "synchronized", "(", "m_objSync", ")", "{", "return", "m_tableRemote", ".",...
Do a remote action. @param strCommand Command to perform remotely. @param properties Properties for this command (optional). @return boolean success.
[ "Do", "a", "remote", "action", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/db/misc/src/main/java/org/jbundle/thin/base/db/client/SyncRemoteTable.java#L251-L257
apache/incubator-shardingsphere
sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/old/parser/sql/dml/delete/DeleteParserFactory.java
DeleteParserFactory.newInstance
public static AbstractDeleteParser newInstance(final DatabaseType dbType, final ShardingRule shardingRule, final LexerEngine lexerEngine) { switch (dbType) { case H2: case MySQL: return new MySQLDeleteParser(shardingRule, lexerEngine); case Oracle: return new OracleDeleteParser(shardingRule, lexerEngine); case SQLServer: return new SQLServerDeleteParser(shardingRule, lexerEngine); case PostgreSQL: return new PostgreSQLDeleteParser(shardingRule, lexerEngine); default: throw new UnsupportedOperationException(String.format("Cannot support database [%s].", dbType)); } }
java
public static AbstractDeleteParser newInstance(final DatabaseType dbType, final ShardingRule shardingRule, final LexerEngine lexerEngine) { switch (dbType) { case H2: case MySQL: return new MySQLDeleteParser(shardingRule, lexerEngine); case Oracle: return new OracleDeleteParser(shardingRule, lexerEngine); case SQLServer: return new SQLServerDeleteParser(shardingRule, lexerEngine); case PostgreSQL: return new PostgreSQLDeleteParser(shardingRule, lexerEngine); default: throw new UnsupportedOperationException(String.format("Cannot support database [%s].", dbType)); } }
[ "public", "static", "AbstractDeleteParser", "newInstance", "(", "final", "DatabaseType", "dbType", ",", "final", "ShardingRule", "shardingRule", ",", "final", "LexerEngine", "lexerEngine", ")", "{", "switch", "(", "dbType", ")", "{", "case", "H2", ":", "case", "...
Create delete parser instance. @param dbType database type @param shardingRule databases and tables sharding rule @param lexerEngine lexical analysis engine. @return delete parser instance
[ "Create", "delete", "parser", "instance", "." ]
train
https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/old/parser/sql/dml/delete/DeleteParserFactory.java#L46-L60
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/utils/SdkUtils.java
SdkUtils.copyStream
public static void copyStream(final InputStream inputStream, final OutputStream outputStream) throws IOException, InterruptedException { copyStream(inputStream, outputStream, null); }
java
public static void copyStream(final InputStream inputStream, final OutputStream outputStream) throws IOException, InterruptedException { copyStream(inputStream, outputStream, null); }
[ "public", "static", "void", "copyStream", "(", "final", "InputStream", "inputStream", ",", "final", "OutputStream", "outputStream", ")", "throws", "IOException", ",", "InterruptedException", "{", "copyStream", "(", "inputStream", ",", "outputStream", ",", "null", ")...
Utility method to write given inputStream to given outputStream. @param inputStream the inputStream to copy from. @param outputStream the outputStream to write to. @throws IOException thrown if there was a problem reading from inputStream or writing to outputStream. @throws InterruptedException thrown if the thread is interrupted which indicates cancelling.
[ "Utility", "method", "to", "write", "given", "inputStream", "to", "given", "outputStream", "." ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/utils/SdkUtils.java#L74-L77
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/filter/stat/ImageLocalNormalization.java
ImageLocalNormalization.zeroMeanStdOne
public void zeroMeanStdOne( int radius , T input , double maxPixelValue , double delta , T output ) { // check preconditions and initialize data structures initialize(input, output); // avoid overflow issues by ensuring that the max pixel value is 1 T adjusted = ensureMaxValueOfOne(input, maxPixelValue); // take advantage of 2D gaussian kernels being separable if( border == null ) { WorkArrays work = GeneralizedImageOps.createWorkArray(input.getImageType()); GBlurImageOps.mean(adjusted, localMean, radius, output, work); GPixelMath.pow2(adjusted, pow2); GBlurImageOps.mean(pow2, localPow2, radius, output, work); } else { throw new IllegalArgumentException("Only renormalize border supported here so far. This can be changed..."); } // Compute the final output if( imageType == GrayF32.class ) computeOutput((GrayF32)input, (float)delta, (GrayF32)output, (GrayF32)adjusted); else computeOutput((GrayF64)input, delta, (GrayF64)output, (GrayF64)adjusted); }
java
public void zeroMeanStdOne( int radius , T input , double maxPixelValue , double delta , T output ) { // check preconditions and initialize data structures initialize(input, output); // avoid overflow issues by ensuring that the max pixel value is 1 T adjusted = ensureMaxValueOfOne(input, maxPixelValue); // take advantage of 2D gaussian kernels being separable if( border == null ) { WorkArrays work = GeneralizedImageOps.createWorkArray(input.getImageType()); GBlurImageOps.mean(adjusted, localMean, radius, output, work); GPixelMath.pow2(adjusted, pow2); GBlurImageOps.mean(pow2, localPow2, radius, output, work); } else { throw new IllegalArgumentException("Only renormalize border supported here so far. This can be changed..."); } // Compute the final output if( imageType == GrayF32.class ) computeOutput((GrayF32)input, (float)delta, (GrayF32)output, (GrayF32)adjusted); else computeOutput((GrayF64)input, delta, (GrayF64)output, (GrayF64)adjusted); }
[ "public", "void", "zeroMeanStdOne", "(", "int", "radius", ",", "T", "input", ",", "double", "maxPixelValue", ",", "double", "delta", ",", "T", "output", ")", "{", "// check preconditions and initialize data structures", "initialize", "(", "input", ",", "output", "...
/* <p>Normalizes the input image such that local statics are a zero mean and with standard deviation of 1. The image border is handled by truncating the kernel and renormalizing it so that it's sum is still one.</p> <p>output[x,y] = (input[x,y]-mean[x,y])/(stdev[x,y] + delta)</p> @param input Input image @param maxPixelValue maximum value of a pixel element in the input image. -1 = compute max value. Typically this is 255 or 1. @param delta A small value used to avoid divide by zero errors. Typical 1e-4f for 32 bit and 1e-8 for 64bit @param output Storage for output
[ "/", "*", "<p", ">", "Normalizes", "the", "input", "image", "such", "that", "local", "statics", "are", "a", "zero", "mean", "and", "with", "standard", "deviation", "of", "1", ".", "The", "image", "border", "is", "handled", "by", "truncating", "the", "ker...
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/filter/stat/ImageLocalNormalization.java#L132-L154
cdk/cdk
tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java
MolecularFormulaManipulator.containsElement
public static boolean containsElement(IMolecularFormula formula, IElement element) { for (IIsotope isotope : formula.isotopes()) { if (element.getSymbol().equals(isotope.getSymbol())) return true; } return false; }
java
public static boolean containsElement(IMolecularFormula formula, IElement element) { for (IIsotope isotope : formula.isotopes()) { if (element.getSymbol().equals(isotope.getSymbol())) return true; } return false; }
[ "public", "static", "boolean", "containsElement", "(", "IMolecularFormula", "formula", ",", "IElement", "element", ")", "{", "for", "(", "IIsotope", "isotope", ":", "formula", ".", "isotopes", "(", ")", ")", "{", "if", "(", "element", ".", "getSymbol", "(", ...
True, if the MolecularFormula contains the given element as IIsotope object. @param formula IMolecularFormula molecularFormula @param element The element this MolecularFormula is searched for @return True, if the MolecularFormula contains the given element object
[ "True", "if", "the", "MolecularFormula", "contains", "the", "given", "element", "as", "IIsotope", "object", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java#L206-L213
alkacon/opencms-core
src/org/opencms/gwt/CmsIconUtil.java
CmsIconUtil.getFileTypeIconClass
private static String getFileTypeIconClass(String resourceTypeName, String fileName, boolean small) { if ((fileName != null) && fileName.contains(".")) { int last = fileName.lastIndexOf("."); if (fileName.length() > (last + 1)) { String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); return getResourceSubTypeIconClass(resourceTypeName, suffix, small); } } return ""; }
java
private static String getFileTypeIconClass(String resourceTypeName, String fileName, boolean small) { if ((fileName != null) && fileName.contains(".")) { int last = fileName.lastIndexOf("."); if (fileName.length() > (last + 1)) { String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); return getResourceSubTypeIconClass(resourceTypeName, suffix, small); } } return ""; }
[ "private", "static", "String", "getFileTypeIconClass", "(", "String", "resourceTypeName", ",", "String", "fileName", ",", "boolean", "small", ")", "{", "if", "(", "(", "fileName", "!=", "null", ")", "&&", "fileName", ".", "contains", "(", "\".\"", ")", ")", ...
Returns the CSS class for the given filename.<p> @param resourceTypeName the resource type name @param fileName the filename @param small if true, get the CSS class for the small icon, else for the biggest one available @return the CSS class
[ "Returns", "the", "CSS", "class", "for", "the", "given", "filename", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/gwt/CmsIconUtil.java#L470-L481
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/xml/importing/BaseXmlImporter.java
BaseXmlImporter.isParent
private boolean isParent(ItemData data, ItemData parent) { String id1 = data.getParentIdentifier(); String id2 = parent.getIdentifier(); if (id1 == id2) // NOSONAR return true; if (id1 == null && id2 != null) return false; return id1 != null && id1.equals(id2); }
java
private boolean isParent(ItemData data, ItemData parent) { String id1 = data.getParentIdentifier(); String id2 = parent.getIdentifier(); if (id1 == id2) // NOSONAR return true; if (id1 == null && id2 != null) return false; return id1 != null && id1.equals(id2); }
[ "private", "boolean", "isParent", "(", "ItemData", "data", ",", "ItemData", "parent", ")", "{", "String", "id1", "=", "data", ".", "getParentIdentifier", "(", ")", ";", "String", "id2", "=", "parent", ".", "getIdentifier", "(", ")", ";", "if", "(", "id1"...
Check if item <b>parent</b> is parent item of item <b>data</b>. @param data - Possible child ItemData. @param parent - Possible parent ItemData. @return True if parent of both ItemData the same.
[ "Check", "if", "item", "<b", ">", "parent<", "/", "b", ">", "is", "parent", "item", "of", "item", "<b", ">", "data<", "/", "b", ">", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/xml/importing/BaseXmlImporter.java#L667-L676
structr/structr
structr-core/src/main/java/org/structr/core/graph/GraphObjectModificationState.java
GraphObjectModificationState.doInnerCallback
public boolean doInnerCallback(ModificationQueue modificationQueue, SecurityContext securityContext, ErrorBuffer errorBuffer) throws FrameworkException { // check for modification propagation along the relationships if ((status & STATE_PROPAGATING_MODIFICATION) == STATE_PROPAGATING_MODIFICATION && object instanceof AbstractNode) { Set<AbstractNode> nodes = ((AbstractNode)object).getNodesForModificationPropagation(); if (nodes != null) { for (AbstractNode node : nodes) { modificationQueue.propagatedModification(node); } } } // examine only the last 4 bits here switch (status & 0x000f) { case 15: case 14: case 13: case 12: case 11: case 10: case 9: case 8: // since all values >= 8 mean that the object was passively deleted, no action has to be taken // (no callback for passive deletion!) break; case 7: // created, modified, deleted, poor guy => no callback break; case 6: // created, modified => only creation callback will be called object.onCreation(securityContext, errorBuffer); break; case 5: // created, deleted => no callback break; case 4: // created => creation callback object.onCreation(securityContext, errorBuffer); break; case 3: // modified, deleted => deletion callback object.onDeletion(securityContext, errorBuffer, removedProperties); break; case 2: // modified => modification callback object.onModification(securityContext, errorBuffer, modificationQueue); break; case 1: // deleted => deletion callback object.onDeletion(securityContext, errorBuffer, removedProperties); break; case 0: // no action, no callback break; default: break; } // mark as finished modified = false; return !errorBuffer.hasError(); }
java
public boolean doInnerCallback(ModificationQueue modificationQueue, SecurityContext securityContext, ErrorBuffer errorBuffer) throws FrameworkException { // check for modification propagation along the relationships if ((status & STATE_PROPAGATING_MODIFICATION) == STATE_PROPAGATING_MODIFICATION && object instanceof AbstractNode) { Set<AbstractNode> nodes = ((AbstractNode)object).getNodesForModificationPropagation(); if (nodes != null) { for (AbstractNode node : nodes) { modificationQueue.propagatedModification(node); } } } // examine only the last 4 bits here switch (status & 0x000f) { case 15: case 14: case 13: case 12: case 11: case 10: case 9: case 8: // since all values >= 8 mean that the object was passively deleted, no action has to be taken // (no callback for passive deletion!) break; case 7: // created, modified, deleted, poor guy => no callback break; case 6: // created, modified => only creation callback will be called object.onCreation(securityContext, errorBuffer); break; case 5: // created, deleted => no callback break; case 4: // created => creation callback object.onCreation(securityContext, errorBuffer); break; case 3: // modified, deleted => deletion callback object.onDeletion(securityContext, errorBuffer, removedProperties); break; case 2: // modified => modification callback object.onModification(securityContext, errorBuffer, modificationQueue); break; case 1: // deleted => deletion callback object.onDeletion(securityContext, errorBuffer, removedProperties); break; case 0: // no action, no callback break; default: break; } // mark as finished modified = false; return !errorBuffer.hasError(); }
[ "public", "boolean", "doInnerCallback", "(", "ModificationQueue", "modificationQueue", ",", "SecurityContext", "securityContext", ",", "ErrorBuffer", "errorBuffer", ")", "throws", "FrameworkException", "{", "// check for modification propagation along the relationships", "if", "(...
Call beforeModification/Creation/Deletion methods. @param modificationQueue @param securityContext @param errorBuffer @return valid @throws FrameworkException
[ "Call", "beforeModification", "/", "Creation", "/", "Deletion", "methods", "." ]
train
https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-core/src/main/java/org/structr/core/graph/GraphObjectModificationState.java#L284-L351
apache/groovy
src/main/java/org/codehaus/groovy/runtime/IOGroovyMethods.java
IOGroovyMethods.withPrintWriter
public static <T> T withPrintWriter(Writer writer, @ClosureParams(value=SimpleType.class, options="java.io.PrintWriter") Closure<T> closure) throws IOException { return withWriter(newPrintWriter(writer), closure); }
java
public static <T> T withPrintWriter(Writer writer, @ClosureParams(value=SimpleType.class, options="java.io.PrintWriter") Closure<T> closure) throws IOException { return withWriter(newPrintWriter(writer), closure); }
[ "public", "static", "<", "T", ">", "T", "withPrintWriter", "(", "Writer", "writer", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "\"java.io.PrintWriter\"", ")", "Closure", "<", "T", ">", "closure", ")", "th...
Create a new PrintWriter for this Writer. The writer is passed to the closure, and will be closed before this method returns. @param writer a writer @param closure the closure to invoke with the PrintWriter @return the value returned by the closure @throws IOException if an IOException occurs. @since 1.6.0
[ "Create", "a", "new", "PrintWriter", "for", "this", "Writer", ".", "The", "writer", "is", "passed", "to", "the", "closure", "and", "will", "be", "closed", "before", "this", "method", "returns", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/IOGroovyMethods.java#L1103-L1105
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/DBTransaction.java
DBTransaction.addColumn
public void addColumn(String storeName, String rowKey, String columnName) { addColumn(storeName, rowKey, columnName, EMPTY); }
java
public void addColumn(String storeName, String rowKey, String columnName) { addColumn(storeName, rowKey, columnName, EMPTY); }
[ "public", "void", "addColumn", "(", "String", "storeName", ",", "String", "rowKey", ",", "String", "columnName", ")", "{", "addColumn", "(", "storeName", ",", "rowKey", ",", "columnName", ",", "EMPTY", ")", ";", "}" ]
Add a column with empty value. The value will be empty byte array/empty string, not null @param storeName Name of store that owns row. @param rowKey Key of row that owns column. @param columnName Name of column.
[ "Add", "a", "column", "with", "empty", "value", ".", "The", "value", "will", "be", "empty", "byte", "array", "/", "empty", "string", "not", "null" ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/DBTransaction.java#L193-L195
threerings/nenya
core/src/main/java/com/threerings/openal/SoundGroup.java
SoundGroup.getSound
public Sound getSound (String path) { ClipBuffer buffer = null; if (_manager.isInitialized()) { buffer = _manager.getClip(_provider, path); } return (buffer == null) ? new BlankSound() : new Sound(this, buffer); }
java
public Sound getSound (String path) { ClipBuffer buffer = null; if (_manager.isInitialized()) { buffer = _manager.getClip(_provider, path); } return (buffer == null) ? new BlankSound() : new Sound(this, buffer); }
[ "public", "Sound", "getSound", "(", "String", "path", ")", "{", "ClipBuffer", "buffer", "=", "null", ";", "if", "(", "_manager", ".", "isInitialized", "(", ")", ")", "{", "buffer", "=", "_manager", ".", "getClip", "(", "_provider", ",", "path", ")", ";...
Obtains an "instance" of the specified sound which can be positioned, played, looped and otherwise used to make noise.
[ "Obtains", "an", "instance", "of", "the", "specified", "sound", "which", "can", "be", "positioned", "played", "looped", "and", "otherwise", "used", "to", "make", "noise", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/openal/SoundGroup.java#L69-L76
carewebframework/carewebframework-core
org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/context/ContextItems.java
ContextItems.setItem
public void setItem(String itemName, String value) { itemName = lookupItemName(itemName, value != null); if (value == null) { items.remove(itemName); index.remove(itemName.toLowerCase()); } else { items.put(itemName, value); } }
java
public void setItem(String itemName, String value) { itemName = lookupItemName(itemName, value != null); if (value == null) { items.remove(itemName); index.remove(itemName.toLowerCase()); } else { items.put(itemName, value); } }
[ "public", "void", "setItem", "(", "String", "itemName", ",", "String", "value", ")", "{", "itemName", "=", "lookupItemName", "(", "itemName", ",", "value", "!=", "null", ")", ";", "if", "(", "value", "==", "null", ")", "{", "items", ".", "remove", "(",...
Sets a context item value. @param itemName Item name @param value Item value
[ "Sets", "a", "context", "item", "value", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/context/ContextItems.java#L232-L241
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUData.java
ICUData.getStream
static InputStream getStream(final ClassLoader loader, final String resourceName, boolean required) { InputStream i = null; if (System.getSecurityManager() != null) { i = AccessController.doPrivileged(new PrivilegedAction<InputStream>() { @Override public InputStream run() { return loader.getResourceAsStream(resourceName); } }); } else { i = loader.getResourceAsStream(resourceName); } if (i == null && required) { throw new MissingResourceException("could not locate data", loader.toString(), resourceName); } checkStreamForBinaryData(i, resourceName); return i; }
java
static InputStream getStream(final ClassLoader loader, final String resourceName, boolean required) { InputStream i = null; if (System.getSecurityManager() != null) { i = AccessController.doPrivileged(new PrivilegedAction<InputStream>() { @Override public InputStream run() { return loader.getResourceAsStream(resourceName); } }); } else { i = loader.getResourceAsStream(resourceName); } if (i == null && required) { throw new MissingResourceException("could not locate data", loader.toString(), resourceName); } checkStreamForBinaryData(i, resourceName); return i; }
[ "static", "InputStream", "getStream", "(", "final", "ClassLoader", "loader", ",", "final", "String", "resourceName", ",", "boolean", "required", ")", "{", "InputStream", "i", "=", "null", ";", "if", "(", "System", ".", "getSecurityManager", "(", ")", "!=", "...
Should be called only from ICUBinary.getData() or from convenience overloads here.
[ "Should", "be", "called", "only", "from", "ICUBinary", ".", "getData", "()", "or", "from", "convenience", "overloads", "here", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUData.java#L144-L161
fcrepo3/fcrepo
fcrepo-common/src/main/java/org/fcrepo/utilities/DateUtility.java
DateUtility.convertDateToString
public static String convertDateToString(Date date, boolean millis) { if (date == null) { return null; } else { DateTimeFormatter df; if (millis) { // df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); df = FORMATTER_MILLISECONDS_T_Z; } else { // df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df = FORMATTER_SECONDS_T_Z; } return df.print(date.getTime()); } }
java
public static String convertDateToString(Date date, boolean millis) { if (date == null) { return null; } else { DateTimeFormatter df; if (millis) { // df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); df = FORMATTER_MILLISECONDS_T_Z; } else { // df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df = FORMATTER_SECONDS_T_Z; } return df.print(date.getTime()); } }
[ "public", "static", "String", "convertDateToString", "(", "Date", "date", ",", "boolean", "millis", ")", "{", "if", "(", "date", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "DateTimeFormatter", "df", ";", "if", "(", "millis", ")", ...
Converts an instance of java.util.Date into an ISO 8601 String representation. Uses the date format yyyy-MM-ddTHH:mm:ss.SSSZ or yyyy-MM-ddTHH:mm:ssZ, depending on whether millisecond precision is desired. @param date Instance of java.util.Date. @param millis Whether or not the return value should include milliseconds. @return ISO 8601 String representation of the Date argument or null if the Date argument is null.
[ "Converts", "an", "instance", "of", "java", ".", "util", ".", "Date", "into", "an", "ISO", "8601", "String", "representation", ".", "Uses", "the", "date", "format", "yyyy", "-", "MM", "-", "ddTHH", ":", "mm", ":", "ss", ".", "SSSZ", "or", "yyyy", "-"...
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-common/src/main/java/org/fcrepo/utilities/DateUtility.java#L87-L102
trellis-ldp/trellis
core/http/src/main/java/org/trellisldp/http/impl/HttpUtils.java
HttpUtils.buildEtagHash
public static String buildEtagHash(final String identifier, final Instant modified, final Prefer prefer) { final String sep = "."; final String hash = prefer != null ? prefer.getInclude().hashCode() + sep + prefer.getOmit().hashCode() : ""; return md5Hex(modified.toEpochMilli() + sep + modified.getNano() + sep + hash + sep + identifier); }
java
public static String buildEtagHash(final String identifier, final Instant modified, final Prefer prefer) { final String sep = "."; final String hash = prefer != null ? prefer.getInclude().hashCode() + sep + prefer.getOmit().hashCode() : ""; return md5Hex(modified.toEpochMilli() + sep + modified.getNano() + sep + hash + sep + identifier); }
[ "public", "static", "String", "buildEtagHash", "(", "final", "String", "identifier", ",", "final", "Instant", "modified", ",", "final", "Prefer", "prefer", ")", "{", "final", "String", "sep", "=", "\".\"", ";", "final", "String", "hash", "=", "prefer", "!=",...
Build a hash value suitable for generating an ETag. @param identifier the resource identifier @param modified the last modified value @param prefer a prefer header, may be null @return a corresponding hash value
[ "Build", "a", "hash", "value", "suitable", "for", "generating", "an", "ETag", "." ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/core/http/src/main/java/org/trellisldp/http/impl/HttpUtils.java#L113-L117
UrielCh/ovh-java-sdk
ovh-java-sdk-caasregistry/src/main/java/net/minidev/ovh/api/ApiOvhCaasregistry.java
ApiOvhCaasregistry.serviceName_namespaces_namespaceId_GET
public OvhNamespace serviceName_namespaces_namespaceId_GET(String serviceName, String namespaceId) throws IOException { String qPath = "/caas/registry/{serviceName}/namespaces/{namespaceId}"; StringBuilder sb = path(qPath, serviceName, namespaceId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhNamespace.class); }
java
public OvhNamespace serviceName_namespaces_namespaceId_GET(String serviceName, String namespaceId) throws IOException { String qPath = "/caas/registry/{serviceName}/namespaces/{namespaceId}"; StringBuilder sb = path(qPath, serviceName, namespaceId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhNamespace.class); }
[ "public", "OvhNamespace", "serviceName_namespaces_namespaceId_GET", "(", "String", "serviceName", ",", "String", "namespaceId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/caas/registry/{serviceName}/namespaces/{namespaceId}\"", ";", "StringBuilder", "sb", ...
Inspect namespace REST: GET /caas/registry/{serviceName}/namespaces/{namespaceId} @param namespaceId [required] Namespace id @param serviceName [required] Service name API beta
[ "Inspect", "namespace" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-caasregistry/src/main/java/net/minidev/ovh/api/ApiOvhCaasregistry.java#L387-L392
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/vectorwriter/OmsVectorWriter.java
OmsVectorWriter.writeVector
public static void writeVector( String path, SimpleFeatureCollection featureCollection ) throws IOException { OmsVectorWriter writer = new OmsVectorWriter(); writer.file = path; writer.inVector = featureCollection; writer.process(); }
java
public static void writeVector( String path, SimpleFeatureCollection featureCollection ) throws IOException { OmsVectorWriter writer = new OmsVectorWriter(); writer.file = path; writer.inVector = featureCollection; writer.process(); }
[ "public", "static", "void", "writeVector", "(", "String", "path", ",", "SimpleFeatureCollection", "featureCollection", ")", "throws", "IOException", "{", "OmsVectorWriter", "writer", "=", "new", "OmsVectorWriter", "(", ")", ";", "writer", ".", "file", "=", "path",...
Fast write access mode. @param path the vector file path. @param featureCollection the {@link FeatureCollection} to write. @throws IOException
[ "Fast", "write", "access", "mode", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/vectorwriter/OmsVectorWriter.java#L102-L107
wildfly/wildfly-core
protocol/src/main/java/org/jboss/as/protocol/mgmt/AbstractMessageHandler.java
AbstractMessageHandler.getActiveOperation
protected <T, A> ActiveOperation<T, A> getActiveOperation(final Integer id) { //noinspection unchecked return (ActiveOperation<T, A>) activeRequests.get(id); }
java
protected <T, A> ActiveOperation<T, A> getActiveOperation(final Integer id) { //noinspection unchecked return (ActiveOperation<T, A>) activeRequests.get(id); }
[ "protected", "<", "T", ",", "A", ">", "ActiveOperation", "<", "T", ",", "A", ">", "getActiveOperation", "(", "final", "Integer", "id", ")", "{", "//noinspection unchecked", "return", "(", "ActiveOperation", "<", "T", ",", "A", ">", ")", "activeRequests", "...
Get the active operation. @param id the active operation id @return the active operation, {@code null} if if there is no registered operation
[ "Get", "the", "active", "operation", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/protocol/src/main/java/org/jboss/as/protocol/mgmt/AbstractMessageHandler.java#L428-L431
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/db/Record.java
Record.setupRecordListener
public BaseMessageFilter setupRecordListener(JMessageListener listener, boolean bTrackMultipleRecords, boolean bAllowEchos) { boolean bReceiveAllAdds = false; if (((this.getDatabaseType() & DBConstants.TABLE_MASK) == DBConstants.TABLE) || ((this.getDatabaseType() & DBConstants.TABLE_MASK) == DBConstants.LOCAL) || ((this.getDatabaseType() & DBConstants.TABLE_MASK) == DBConstants.REMOTE_MEMORY)) bReceiveAllAdds = true; // The volume of changes is negligable and there is rarely a secondary, so listen for all changes return this.setupRecordListener(listener, bTrackMultipleRecords, bAllowEchos, bReceiveAllAdds); }
java
public BaseMessageFilter setupRecordListener(JMessageListener listener, boolean bTrackMultipleRecords, boolean bAllowEchos) { boolean bReceiveAllAdds = false; if (((this.getDatabaseType() & DBConstants.TABLE_MASK) == DBConstants.TABLE) || ((this.getDatabaseType() & DBConstants.TABLE_MASK) == DBConstants.LOCAL) || ((this.getDatabaseType() & DBConstants.TABLE_MASK) == DBConstants.REMOTE_MEMORY)) bReceiveAllAdds = true; // The volume of changes is negligable and there is rarely a secondary, so listen for all changes return this.setupRecordListener(listener, bTrackMultipleRecords, bAllowEchos, bReceiveAllAdds); }
[ "public", "BaseMessageFilter", "setupRecordListener", "(", "JMessageListener", "listener", ",", "boolean", "bTrackMultipleRecords", ",", "boolean", "bAllowEchos", ")", "{", "boolean", "bReceiveAllAdds", "=", "false", ";", "if", "(", "(", "(", "this", ".", "getDataba...
Set up a listener to notify when an external change is made to the current record. @param listener The listener to set to the new filter. If null, use the record's recordowner. @param bTrackMultipleRecord Use a GridRecordMessageFilter to watch for multiple records. @param bAllowEchos Allow this record to be notified of changes (usually for remotes hooked to grid tables). @param bReceiveAllAdds If true, receive all add notifications, otherwise just receive the adds on secondary reads. @return The new filter.
[ "Set", "up", "a", "listener", "to", "notify", "when", "an", "external", "change", "is", "made", "to", "the", "current", "record", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/Record.java#L2782-L2790
landawn/AbacusUtil
src/com/landawn/abacus/dataSource/PoolablePreparedStatement.java
PoolablePreparedStatement.setDate
@Override public void setDate(int parameterIndex, Date x) throws SQLException { internalStmt.setDate(parameterIndex, x); }
java
@Override public void setDate(int parameterIndex, Date x) throws SQLException { internalStmt.setDate(parameterIndex, x); }
[ "@", "Override", "public", "void", "setDate", "(", "int", "parameterIndex", ",", "Date", "x", ")", "throws", "SQLException", "{", "internalStmt", ".", "setDate", "(", "parameterIndex", ",", "x", ")", ";", "}" ]
Method setDate. @param parameterIndex @param x @throws SQLException @see java.sql.PreparedStatement#setDate(int, Date)
[ "Method", "setDate", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/dataSource/PoolablePreparedStatement.java#L711-L714
prometheus/client_java
simpleclient_common/src/main/java/io/prometheus/client/exporter/common/TextFormat.java
TextFormat.write004
public static void write004(Writer writer, Enumeration<Collector.MetricFamilySamples> mfs) throws IOException { /* See http://prometheus.io/docs/instrumenting/exposition_formats/ * for the output format specification. */ while(mfs.hasMoreElements()) { Collector.MetricFamilySamples metricFamilySamples = mfs.nextElement(); writer.write("# HELP "); writer.write(metricFamilySamples.name); writer.write(' '); writeEscapedHelp(writer, metricFamilySamples.help); writer.write('\n'); writer.write("# TYPE "); writer.write(metricFamilySamples.name); writer.write(' '); writer.write(typeString(metricFamilySamples.type)); writer.write('\n'); for (Collector.MetricFamilySamples.Sample sample: metricFamilySamples.samples) { writer.write(sample.name); if (sample.labelNames.size() > 0) { writer.write('{'); for (int i = 0; i < sample.labelNames.size(); ++i) { writer.write(sample.labelNames.get(i)); writer.write("=\""); writeEscapedLabelValue(writer, sample.labelValues.get(i)); writer.write("\","); } writer.write('}'); } writer.write(' '); writer.write(Collector.doubleToGoString(sample.value)); if (sample.timestampMs != null){ writer.write(' '); writer.write(sample.timestampMs.toString()); } writer.write('\n'); } } }
java
public static void write004(Writer writer, Enumeration<Collector.MetricFamilySamples> mfs) throws IOException { /* See http://prometheus.io/docs/instrumenting/exposition_formats/ * for the output format specification. */ while(mfs.hasMoreElements()) { Collector.MetricFamilySamples metricFamilySamples = mfs.nextElement(); writer.write("# HELP "); writer.write(metricFamilySamples.name); writer.write(' '); writeEscapedHelp(writer, metricFamilySamples.help); writer.write('\n'); writer.write("# TYPE "); writer.write(metricFamilySamples.name); writer.write(' '); writer.write(typeString(metricFamilySamples.type)); writer.write('\n'); for (Collector.MetricFamilySamples.Sample sample: metricFamilySamples.samples) { writer.write(sample.name); if (sample.labelNames.size() > 0) { writer.write('{'); for (int i = 0; i < sample.labelNames.size(); ++i) { writer.write(sample.labelNames.get(i)); writer.write("=\""); writeEscapedLabelValue(writer, sample.labelValues.get(i)); writer.write("\","); } writer.write('}'); } writer.write(' '); writer.write(Collector.doubleToGoString(sample.value)); if (sample.timestampMs != null){ writer.write(' '); writer.write(sample.timestampMs.toString()); } writer.write('\n'); } } }
[ "public", "static", "void", "write004", "(", "Writer", "writer", ",", "Enumeration", "<", "Collector", ".", "MetricFamilySamples", ">", "mfs", ")", "throws", "IOException", "{", "/* See http://prometheus.io/docs/instrumenting/exposition_formats/\n * for the output format sp...
Write out the text version 0.0.4 of the given MetricFamilySamples.
[ "Write", "out", "the", "text", "version", "0", ".", "0", ".", "4", "of", "the", "given", "MetricFamilySamples", "." ]
train
https://github.com/prometheus/client_java/blob/4e0e7527b048f1ffd0382dcb74c0b9dab23b4d9f/simpleclient_common/src/main/java/io/prometheus/client/exporter/common/TextFormat.java#L18-L56
sarl/sarl
sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/util/AbstractMapView.java
AbstractMapView.fireEntryAdded
@SuppressWarnings("unchecked") protected void fireEntryAdded(K key, V value) { if (this.listeners != null) { for (final DMapListener<? super K, ? super V> listener : this.listeners.getListeners(DMapListener.class)) { listener.entryAdded(key, value); } } }
java
@SuppressWarnings("unchecked") protected void fireEntryAdded(K key, V value) { if (this.listeners != null) { for (final DMapListener<? super K, ? super V> listener : this.listeners.getListeners(DMapListener.class)) { listener.entryAdded(key, value); } } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "void", "fireEntryAdded", "(", "K", "key", ",", "V", "value", ")", "{", "if", "(", "this", ".", "listeners", "!=", "null", ")", "{", "for", "(", "final", "DMapListener", "<", "?", "super", ...
Fire the addition event. @param key the added key. @param value the added value.
[ "Fire", "the", "addition", "event", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/util/AbstractMapView.java#L58-L65
meertensinstituut/mtas
src/main/java/mtas/codec/util/CodecInfo.java
CodecInfo.getDoc
public IndexDoc getDoc(String field, int docId) { if (fieldReferences.containsKey(field)) { FieldReferences fr = fieldReferences.get(field); try { IndexInput inIndexDocId = indexInputList.get("indexDocId"); ArrayList<MtasTreeHit<?>> list = CodecSearchTree.searchMtasTree(docId, inIndexDocId, fr.refIndexDocId, fr.refIndexDoc); if (list.size() == 1) { return new IndexDoc(list.get(0).ref); } } catch (IOException e) { log.debug(e); return null; } } return null; }
java
public IndexDoc getDoc(String field, int docId) { if (fieldReferences.containsKey(field)) { FieldReferences fr = fieldReferences.get(field); try { IndexInput inIndexDocId = indexInputList.get("indexDocId"); ArrayList<MtasTreeHit<?>> list = CodecSearchTree.searchMtasTree(docId, inIndexDocId, fr.refIndexDocId, fr.refIndexDoc); if (list.size() == 1) { return new IndexDoc(list.get(0).ref); } } catch (IOException e) { log.debug(e); return null; } } return null; }
[ "public", "IndexDoc", "getDoc", "(", "String", "field", ",", "int", "docId", ")", "{", "if", "(", "fieldReferences", ".", "containsKey", "(", "field", ")", ")", "{", "FieldReferences", "fr", "=", "fieldReferences", ".", "get", "(", "field", ")", ";", "tr...
Gets the doc. @param field the field @param docId the doc id @return the doc
[ "Gets", "the", "doc", "." ]
train
https://github.com/meertensinstituut/mtas/blob/f02ae730848616bd88b553efa7f9eddc32818e64/src/main/java/mtas/codec/util/CodecInfo.java#L566-L582
lotaris/jee-validation
src/main/java/com/lotaris/jee/validation/AbstractPatchTransferObject.java
AbstractPatchTransferObject.markPropertyAsSet
public <T> T markPropertyAsSet(String property, T value) { setProperties.add(property); return value; }
java
public <T> T markPropertyAsSet(String property, T value) { setProperties.add(property); return value; }
[ "public", "<", "T", ">", "T", "markPropertyAsSet", "(", "String", "property", ",", "T", "value", ")", "{", "setProperties", ".", "add", "(", "property", ")", ";", "return", "value", ";", "}" ]
Marks the specified property as set and returns the value given as the second argument. This is meant to be used as a one-liner. <p><pre> public void setFirstName(String firstName) { this.firstName = markPropertyAsSet(FIRST_NAME, firstName); } </pre></p> @param <T> the type of value @param property the property to mark as set @param value the value to return @return the value
[ "Marks", "the", "specified", "property", "as", "set", "and", "returns", "the", "value", "given", "as", "the", "second", "argument", ".", "This", "is", "meant", "to", "be", "used", "as", "a", "one", "-", "liner", "." ]
train
https://github.com/lotaris/jee-validation/blob/feefff820b5a67c7471a13e08fdaf2d60bb3ad16/src/main/java/com/lotaris/jee/validation/AbstractPatchTransferObject.java#L71-L74
vakinge/jeesuite-libs
jeesuite-mybatis/src/main/java/com/jeesuite/mybatis/plugin/cache/EntityCacheHelper.java
EntityCacheHelper.queryTryCache
public static <T> T queryTryCache(Class<? extends BaseEntity> entityClass,String key,long expireSeconds,Callable<T> dataCaller){ if(CacheHandler.cacheProvider == null){ try { return dataCaller.call(); } catch (Exception e) { throw new RuntimeException(e); } } String entityClassName = entityClass.getSimpleName(); key = entityClassName + CacheHandler.SPLIT_PONIT + key; T result = CacheHandler.cacheProvider.get(key); if(result == null){ try { result = dataCaller.call(); if(result != null){ CacheHandler.cacheProvider.set(key, result, expireSeconds); String cacheGroupKey = entityClassName + CacheHandler.GROUPKEY_SUFFIX; CacheHandler.cacheProvider.putGroup(cacheGroupKey, key, expireSeconds); } } catch (Exception e) { throw new RuntimeException(e); } } return result; }
java
public static <T> T queryTryCache(Class<? extends BaseEntity> entityClass,String key,long expireSeconds,Callable<T> dataCaller){ if(CacheHandler.cacheProvider == null){ try { return dataCaller.call(); } catch (Exception e) { throw new RuntimeException(e); } } String entityClassName = entityClass.getSimpleName(); key = entityClassName + CacheHandler.SPLIT_PONIT + key; T result = CacheHandler.cacheProvider.get(key); if(result == null){ try { result = dataCaller.call(); if(result != null){ CacheHandler.cacheProvider.set(key, result, expireSeconds); String cacheGroupKey = entityClassName + CacheHandler.GROUPKEY_SUFFIX; CacheHandler.cacheProvider.putGroup(cacheGroupKey, key, expireSeconds); } } catch (Exception e) { throw new RuntimeException(e); } } return result; }
[ "public", "static", "<", "T", ">", "T", "queryTryCache", "(", "Class", "<", "?", "extends", "BaseEntity", ">", "entityClass", ",", "String", "key", ",", "long", "expireSeconds", ",", "Callable", "<", "T", ">", "dataCaller", ")", "{", "if", "(", "CacheHan...
查询并缓存结果 @param entityClass 实体类class (用户组装实际的缓存key) @param key 缓存的key(和entityClass一起组成真实的缓存key。<br>如entityClass=UserEntity.class,key=findlist,实际的key为:UserEntity.findlist) @param expireSeconds 过期时间,单位:秒 @param dataCaller 缓存不存在数据加载源 @return
[ "查询并缓存结果" ]
train
https://github.com/vakinge/jeesuite-libs/blob/c48fe2c7fbd294892cf4030dbec96e744dd3e386/jeesuite-mybatis/src/main/java/com/jeesuite/mybatis/plugin/cache/EntityCacheHelper.java#L45-L71
CleverTap/clevertap-android-sdk
clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/CleverTapAPI.java
CleverTapAPI.addMultiValuesForKey
@SuppressWarnings({"unused", "WeakerAccess"}) public void addMultiValuesForKey(final String key, final ArrayList<String> values) { postAsyncSafely("addMultiValuesForKey", new Runnable() { @Override public void run() { final String command = (getLocalDataStore().getProfileValueForKey(key) != null) ? Constants.COMMAND_ADD : Constants.COMMAND_SET; _handleMultiValues(values, key, command); } }); }
java
@SuppressWarnings({"unused", "WeakerAccess"}) public void addMultiValuesForKey(final String key, final ArrayList<String> values) { postAsyncSafely("addMultiValuesForKey", new Runnable() { @Override public void run() { final String command = (getLocalDataStore().getProfileValueForKey(key) != null) ? Constants.COMMAND_ADD : Constants.COMMAND_SET; _handleMultiValues(values, key, command); } }); }
[ "@", "SuppressWarnings", "(", "{", "\"unused\"", ",", "\"WeakerAccess\"", "}", ")", "public", "void", "addMultiValuesForKey", "(", "final", "String", "key", ",", "final", "ArrayList", "<", "String", ">", "values", ")", "{", "postAsyncSafely", "(", "\"addMultiVal...
Add a collection of unique values to a multi-value user profile property If the property does not exist it will be created <p/> Max 100 values, on reaching 100 cap, oldest value(s) will be removed. Values must be Strings and are limited to 512 characters. <p/> If the key currently contains a scalar value, the key will be promoted to a multi-value property with the current value cast to a string and the new value(s) added @param key String @param values {@link ArrayList} with String values
[ "Add", "a", "collection", "of", "unique", "values", "to", "a", "multi", "-", "value", "user", "profile", "property", "If", "the", "property", "does", "not", "exist", "it", "will", "be", "created", "<p", "/", ">", "Max", "100", "values", "on", "reaching",...
train
https://github.com/CleverTap/clevertap-android-sdk/blob/be134c06a4f07494c398335ad9ff4976633743e1/clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/CleverTapAPI.java#L3419-L3428
apptik/jus
android/jus-android/src/main/java/io/apptik/comm/jus/ui/NetworkImageView.java
NetworkImageView.setImageUrl
public void setImageUrl(String url, ImageLoader imageLoader) { this.url = url; this.imageLoader = imageLoader; if (this.imageLoader.getDefaultImageId() != 0) { defaultImageId = this.imageLoader.getDefaultImageId(); } if (this.imageLoader.getErrorImageId() != 0) { errorImageId = this.imageLoader.getErrorImageId(); } // The URL has potentially changed. See if we need to load it. loadImageIfNecessary(false); }
java
public void setImageUrl(String url, ImageLoader imageLoader) { this.url = url; this.imageLoader = imageLoader; if (this.imageLoader.getDefaultImageId() != 0) { defaultImageId = this.imageLoader.getDefaultImageId(); } if (this.imageLoader.getErrorImageId() != 0) { errorImageId = this.imageLoader.getErrorImageId(); } // The URL has potentially changed. See if we need to load it. loadImageIfNecessary(false); }
[ "public", "void", "setImageUrl", "(", "String", "url", ",", "ImageLoader", "imageLoader", ")", "{", "this", ".", "url", "=", "url", ";", "this", ".", "imageLoader", "=", "imageLoader", ";", "if", "(", "this", ".", "imageLoader", ".", "getDefaultImageId", "...
Sets URL of the image that should be loaded into this view. Note that calling this will immediately either set the cached image (if available) or the default image specified by {@link NetworkImageView#setDefaultImageResId(int)} on the view. <p/> NOTE: If applicable, {@link NetworkImageView#setDefaultImageResId(int)} and {@link NetworkImageView#setErrorImageResId(int)} should be called prior to calling this function. @param url The URL that should be loaded into this ImageView. @param imageLoader ImageLoader that will be used to make the request.
[ "Sets", "URL", "of", "the", "image", "that", "should", "be", "loaded", "into", "this", "view", ".", "Note", "that", "calling", "this", "will", "immediately", "either", "set", "the", "cached", "image", "(", "if", "available", ")", "or", "the", "default", ...
train
https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/android/jus-android/src/main/java/io/apptik/comm/jus/ui/NetworkImageView.java#L111-L122
Javacord/Javacord
javacord-api/src/main/java/org/javacord/api/util/logging/ExceptionLogger.java
ExceptionLogger.getConsumer
@SafeVarargs public static Consumer<Throwable> getConsumer(Class<? extends Throwable>... ignoredThrowableTypes) { return getConsumer(null, ignoredThrowableTypes); }
java
@SafeVarargs public static Consumer<Throwable> getConsumer(Class<? extends Throwable>... ignoredThrowableTypes) { return getConsumer(null, ignoredThrowableTypes); }
[ "@", "SafeVarargs", "public", "static", "Consumer", "<", "Throwable", ">", "getConsumer", "(", "Class", "<", "?", "extends", "Throwable", ">", "...", "ignoredThrowableTypes", ")", "{", "return", "getConsumer", "(", "null", ",", "ignoredThrowableTypes", ")", ";",...
Returns a consumer that can for example be used in the {@link TextChannel#typeContinuously(Consumer)} method. It unwraps {@link CompletionException CompletionExceptions}, {@link InvocationTargetException InvocationTargetExceptions} and {@link ExecutionException ExecutionExceptions} first, and then adds a fresh {@code CompletionException} as wrapper with the stacktrace of the caller of this method and logs it afterwards. The rewrapped exception is only logged if it is not in the {@code ignoredThrowableTypes}. @param ignoredThrowableTypes The throwable types that should never be logged. @return A consumer which logs the given throwable.
[ "Returns", "a", "consumer", "that", "can", "for", "example", "be", "used", "in", "the", "{", "@link", "TextChannel#typeContinuously", "(", "Consumer", ")", "}", "method", ".", "It", "unwraps", "{", "@link", "CompletionException", "CompletionExceptions", "}", "{"...
train
https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-api/src/main/java/org/javacord/api/util/logging/ExceptionLogger.java#L62-L65
atomix/catalyst
serializer/src/main/java/io/atomix/catalyst/serializer/util/CatalystSerializableSerializer.java
CatalystSerializableSerializer.readReference
@SuppressWarnings("unchecked") private T readReference(Class<T> type, BufferInput<?> buffer, Serializer serializer) { ReferencePool<?> pool = pools.get(type); if (pool == null) { Constructor<?> constructor = constructorMap.get(type); if (constructor == null) { try { constructor = type.getDeclaredConstructor(ReferenceManager.class); constructor.setAccessible(true); constructorMap.put(type, constructor); } catch (NoSuchMethodException e) { throw new SerializationException("failed to instantiate reference: must provide a single argument constructor", e); } } pool = new ReferencePool<>(createFactory(constructor)); pools.put(type, pool); } T object = (T) pool.acquire(); object.readObject(buffer, serializer); return object; }
java
@SuppressWarnings("unchecked") private T readReference(Class<T> type, BufferInput<?> buffer, Serializer serializer) { ReferencePool<?> pool = pools.get(type); if (pool == null) { Constructor<?> constructor = constructorMap.get(type); if (constructor == null) { try { constructor = type.getDeclaredConstructor(ReferenceManager.class); constructor.setAccessible(true); constructorMap.put(type, constructor); } catch (NoSuchMethodException e) { throw new SerializationException("failed to instantiate reference: must provide a single argument constructor", e); } } pool = new ReferencePool<>(createFactory(constructor)); pools.put(type, pool); } T object = (T) pool.acquire(); object.readObject(buffer, serializer); return object; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "T", "readReference", "(", "Class", "<", "T", ">", "type", ",", "BufferInput", "<", "?", ">", "buffer", ",", "Serializer", "serializer", ")", "{", "ReferencePool", "<", "?", ">", "pool", "=", ...
Reads an object reference. @param type The reference type. @param buffer The reference buffer. @param serializer The serializer with which the object is being read. @return The reference to read.
[ "Reads", "an", "object", "reference", "." ]
train
https://github.com/atomix/catalyst/blob/140e762cb975cd8ee1fd85119043c5b8bf917c5c/serializer/src/main/java/io/atomix/catalyst/serializer/util/CatalystSerializableSerializer.java#L71-L92
messenger4j/messenger4j
src/main/java/com/github/messenger4j/webhook/SignatureUtil.java
SignatureUtil.isSignatureValid
public static boolean isSignatureValid(String payload, String signature, String appSecret) { try { final Mac mac = Mac.getInstance(HMAC_SHA1); mac.init(new SecretKeySpec(appSecret.getBytes(), HMAC_SHA1)); final byte[] rawHmac = mac.doFinal(payload.getBytes()); final String expected = signature.substring(5); final String actual = bytesToHexString(rawHmac); return expected.equals(actual); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException(e); } }
java
public static boolean isSignatureValid(String payload, String signature, String appSecret) { try { final Mac mac = Mac.getInstance(HMAC_SHA1); mac.init(new SecretKeySpec(appSecret.getBytes(), HMAC_SHA1)); final byte[] rawHmac = mac.doFinal(payload.getBytes()); final String expected = signature.substring(5); final String actual = bytesToHexString(rawHmac); return expected.equals(actual); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException(e); } }
[ "public", "static", "boolean", "isSignatureValid", "(", "String", "payload", ",", "String", "signature", ",", "String", "appSecret", ")", "{", "try", "{", "final", "Mac", "mac", "=", "Mac", ".", "getInstance", "(", "HMAC_SHA1", ")", ";", "mac", ".", "init"...
Verifies the provided signature of the payload. @param payload the request body {@code JSON payload} @param signature the SHA1 signature of the request payload @param appSecret the {@code Application Secret} of the Facebook App @return {@code true} if the verification was successful, otherwise {@code false}
[ "Verifies", "the", "provided", "signature", "of", "the", "payload", "." ]
train
https://github.com/messenger4j/messenger4j/blob/b45d3dad035e683fcec749c463b645e5567fcf72/src/main/java/com/github/messenger4j/webhook/SignatureUtil.java#L28-L41
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java
BigDecimal.needIncrement
private static boolean needIncrement(long ldivisor, int roundingMode, int qsign, long q, long r) { assert r != 0L; int cmpFracHalf; if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) { cmpFracHalf = 1; // 2 * r can't fit into long } else { cmpFracHalf = longCompareMagnitude(2 * r, ldivisor); } return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, (q & 1L) != 0L); }
java
private static boolean needIncrement(long ldivisor, int roundingMode, int qsign, long q, long r) { assert r != 0L; int cmpFracHalf; if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) { cmpFracHalf = 1; // 2 * r can't fit into long } else { cmpFracHalf = longCompareMagnitude(2 * r, ldivisor); } return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, (q & 1L) != 0L); }
[ "private", "static", "boolean", "needIncrement", "(", "long", "ldivisor", ",", "int", "roundingMode", ",", "int", "qsign", ",", "long", "q", ",", "long", "r", ")", "{", "assert", "r", "!=", "0L", ";", "int", "cmpFracHalf", ";", "if", "(", "r", "<=", ...
Tests if quotient has to be incremented according the roundingMode
[ "Tests", "if", "quotient", "has", "to", "be", "incremented", "according", "the", "roundingMode" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java#L4195-L4207
netarchivesuite/heritrix3-wrapper
src/main/java/org/netarchivesuite/heritrix3wrapper/unzip/UnzipUtility.java
UnzipUtility.unzip
public void unzip(String zipFilePath, String destDirectory) throws IOException { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry entry = zipIn.getNextEntry(); while (entry != null) { File destFile = new File(destDir, entry.getName()); long lastModified = entry.getTime(); if (!entry.isDirectory()) { extractFile(zipIn, destFile); if (lastModified != -1) { destFile.setLastModified(entry.getTime()); } } else { destFile.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } zipIn.close(); }
java
public void unzip(String zipFilePath, String destDirectory) throws IOException { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry entry = zipIn.getNextEntry(); while (entry != null) { File destFile = new File(destDir, entry.getName()); long lastModified = entry.getTime(); if (!entry.isDirectory()) { extractFile(zipIn, destFile); if (lastModified != -1) { destFile.setLastModified(entry.getTime()); } } else { destFile.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } zipIn.close(); }
[ "public", "void", "unzip", "(", "String", "zipFilePath", ",", "String", "destDirectory", ")", "throws", "IOException", "{", "File", "destDir", "=", "new", "File", "(", "destDirectory", ")", ";", "if", "(", "!", "destDir", ".", "exists", "(", ")", ")", "{...
Extracts a zip file specified by the zipFilePath to a directory specified by destDirectory (will be created if does not exists) @param zipFilePath @param destDirectory @throws IOException
[ "Extracts", "a", "zip", "file", "specified", "by", "the", "zipFilePath", "to", "a", "directory", "specified", "by", "destDirectory", "(", "will", "be", "created", "if", "does", "not", "exists", ")" ]
train
https://github.com/netarchivesuite/heritrix3-wrapper/blob/e53ec5736cbac0bdd3925b5331737dc905871629/src/main/java/org/netarchivesuite/heritrix3wrapper/unzip/UnzipUtility.java#L29-L51
liyiorg/weixin-popular
src/main/java/weixin/popular/util/SignatureUtil.java
SignatureUtil.generateSign
public static String generateSign(Map<String, String> map,String sign_type,String paternerKey){ Map<String, String> tmap = MapUtil.order(map); if(tmap.containsKey("sign")){ tmap.remove("sign"); } String str = MapUtil.mapJoin(tmap, false, false); if(sign_type == null){ sign_type = tmap.get("sign_type"); } if("HMAC-SHA256".equalsIgnoreCase(sign_type)){ try { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(paternerKey.getBytes("UTF-8"), "HmacSHA256"); sha256_HMAC.init(secret_key); return Hex.encodeHexString(sha256_HMAC.doFinal((str+"&key="+paternerKey).getBytes("UTF-8"))).toUpperCase(); } catch (Exception e) { logger.error("", e); } return null; }else{//default MD5 return DigestUtils.md5Hex(str+"&key="+paternerKey).toUpperCase(); } }
java
public static String generateSign(Map<String, String> map,String sign_type,String paternerKey){ Map<String, String> tmap = MapUtil.order(map); if(tmap.containsKey("sign")){ tmap.remove("sign"); } String str = MapUtil.mapJoin(tmap, false, false); if(sign_type == null){ sign_type = tmap.get("sign_type"); } if("HMAC-SHA256".equalsIgnoreCase(sign_type)){ try { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(paternerKey.getBytes("UTF-8"), "HmacSHA256"); sha256_HMAC.init(secret_key); return Hex.encodeHexString(sha256_HMAC.doFinal((str+"&key="+paternerKey).getBytes("UTF-8"))).toUpperCase(); } catch (Exception e) { logger.error("", e); } return null; }else{//default MD5 return DigestUtils.md5Hex(str+"&key="+paternerKey).toUpperCase(); } }
[ "public", "static", "String", "generateSign", "(", "Map", "<", "String", ",", "String", ">", "map", ",", "String", "sign_type", ",", "String", "paternerKey", ")", "{", "Map", "<", "String", ",", "String", ">", "tmap", "=", "MapUtil", ".", "order", "(", ...
生成sign HMAC-SHA256 或 MD5 签名 @param map map @param sign_type HMAC-SHA256 或 MD5 @param paternerKey paternerKey @return sign
[ "生成sign", "HMAC", "-", "SHA256", "或", "MD5", "签名" ]
train
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/util/SignatureUtil.java#L35-L57
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/workspace/VoiceApi.java
VoiceApi.setAgentReady
public void setAgentReady(KeyValueCollection reasons, KeyValueCollection extensions) throws WorkspaceApiException { try { VoicereadyData readyData = new VoicereadyData(); readyData.setReasons(Util.toKVList(reasons)); readyData.setExtensions(Util.toKVList(extensions)); ReadyData data = new ReadyData(); data.data(readyData); ApiSuccessResponse response = this.voiceApi.setAgentStateReady(data); throwIfNotOk("setAgentReady", response); } catch (ApiException e) { throw new WorkspaceApiException("setAgentReady failed.", e); } }
java
public void setAgentReady(KeyValueCollection reasons, KeyValueCollection extensions) throws WorkspaceApiException { try { VoicereadyData readyData = new VoicereadyData(); readyData.setReasons(Util.toKVList(reasons)); readyData.setExtensions(Util.toKVList(extensions)); ReadyData data = new ReadyData(); data.data(readyData); ApiSuccessResponse response = this.voiceApi.setAgentStateReady(data); throwIfNotOk("setAgentReady", response); } catch (ApiException e) { throw new WorkspaceApiException("setAgentReady failed.", e); } }
[ "public", "void", "setAgentReady", "(", "KeyValueCollection", "reasons", ",", "KeyValueCollection", "extensions", ")", "throws", "WorkspaceApiException", "{", "try", "{", "VoicereadyData", "readyData", "=", "new", "VoicereadyData", "(", ")", ";", "readyData", ".", "...
Set the current agent's state to Ready on the voice channel. @param reasons Information on causes for, and results of, actions taken by the user of the current DN. For details about reasons, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Reasons). @param extensions Media device/hardware reason codes and similar information. For details about extensions, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Extensions). (optional)
[ "Set", "the", "current", "agent", "s", "state", "to", "Ready", "on", "the", "voice", "channel", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/workspace/VoiceApi.java#L321-L334
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/utils/SdkUtils.java
SdkUtils.setCollabNumberThumb
public static void setCollabNumberThumb(Context context, TextView initialsView, int collabNumber) { String collabNumberDisplay = (collabNumber >= 100) ? "+99" : "+" + Integer.toString(collabNumber); setColorForCollabNumberThumb(initialsView); initialsView.setTextColor(COLLAB_NUMBER_THUMB_COLOR); initialsView.setText(collabNumberDisplay); }
java
public static void setCollabNumberThumb(Context context, TextView initialsView, int collabNumber) { String collabNumberDisplay = (collabNumber >= 100) ? "+99" : "+" + Integer.toString(collabNumber); setColorForCollabNumberThumb(initialsView); initialsView.setTextColor(COLLAB_NUMBER_THUMB_COLOR); initialsView.setText(collabNumberDisplay); }
[ "public", "static", "void", "setCollabNumberThumb", "(", "Context", "context", ",", "TextView", "initialsView", ",", "int", "collabNumber", ")", "{", "String", "collabNumberDisplay", "=", "(", "collabNumber", ">=", "100", ")", "?", "\"+99\"", ":", "\"+\"", "+", ...
Helper method to display number of collaborators. If there are more than 99 collaborators it would show "99+" due to the width constraint in the view. @param context current context @param initialsView TextView used to display number of collaborators @param collabNumber Number of collaborators
[ "Helper", "method", "to", "display", "number", "of", "collaborators", ".", "If", "there", "are", "more", "than", "99", "collaborators", "it", "would", "show", "99", "+", "due", "to", "the", "width", "constraint", "in", "the", "view", "." ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/utils/SdkUtils.java#L576-L581
TheHortonMachine/hortonmachine
hmachine/src/main/java/org/hortonmachine/hmachine/modules/networktools/epanet/core/EpanetWrapper.java
EpanetWrapper.ENgetnodevalue
public float ENgetnodevalue( int index, NodeParameters code ) throws EpanetException { float[] nodeValue = new float[1]; int error = epanet.ENgetnodevalue(index, code.getCode(), nodeValue); checkError(error); return nodeValue[0]; }
java
public float ENgetnodevalue( int index, NodeParameters code ) throws EpanetException { float[] nodeValue = new float[1]; int error = epanet.ENgetnodevalue(index, code.getCode(), nodeValue); checkError(error); return nodeValue[0]; }
[ "public", "float", "ENgetnodevalue", "(", "int", "index", ",", "NodeParameters", "code", ")", "throws", "EpanetException", "{", "float", "[", "]", "nodeValue", "=", "new", "float", "[", "1", "]", ";", "int", "error", "=", "epanet", ".", "ENgetnodevalue", "...
Retrieves the value of a specific link (node?) parameter. @param index the node index. @param code the parameter code. @return the value at the node. @throws EpanetException
[ "Retrieves", "the", "value", "of", "a", "specific", "link", "(", "node?", ")", "parameter", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/networktools/epanet/core/EpanetWrapper.java#L491-L496
mgm-tp/jfunk
jfunk-data-generator/src/main/java/com/mgmtp/jfunk/data/generator/field/FieldFactory.java
FieldFactory.createField
public Field createField(final MathRandom random, final Element element, final String characterSetId) { Field field = null; Element fieldElement = null; Element fieldRefElement = element.getChild(XMLTags.FIELD_REF); if (fieldRefElement != null) { fieldElement = getElementFinder(element).findElementById(fieldRefElement); } else { fieldElement = element.getChild(XMLTags.FIELD); } checkState(fieldElement != null, "Could not find a Field tag or FieldRef tag"); Class<? extends Field> classObject = null; try { classObject = getClassObject(fieldElement); Constructor<? extends Field> constructor = classObject.getConstructor(new Class[] { MathRandom.class, Element.class, String.class }); field = constructor.newInstance(new Object[] { random, fieldElement, characterSetId }); } catch (Exception e) { throw new IllegalStateException("Could not initialise object of class " + classObject, e); } return field; }
java
public Field createField(final MathRandom random, final Element element, final String characterSetId) { Field field = null; Element fieldElement = null; Element fieldRefElement = element.getChild(XMLTags.FIELD_REF); if (fieldRefElement != null) { fieldElement = getElementFinder(element).findElementById(fieldRefElement); } else { fieldElement = element.getChild(XMLTags.FIELD); } checkState(fieldElement != null, "Could not find a Field tag or FieldRef tag"); Class<? extends Field> classObject = null; try { classObject = getClassObject(fieldElement); Constructor<? extends Field> constructor = classObject.getConstructor(new Class[] { MathRandom.class, Element.class, String.class }); field = constructor.newInstance(new Object[] { random, fieldElement, characterSetId }); } catch (Exception e) { throw new IllegalStateException("Could not initialise object of class " + classObject, e); } return field; }
[ "public", "Field", "createField", "(", "final", "MathRandom", "random", ",", "final", "Element", "element", ",", "final", "String", "characterSetId", ")", "{", "Field", "field", "=", "null", ";", "Element", "fieldElement", "=", "null", ";", "Element", "fieldRe...
Searches for the Field Child tag in the specified element or takes the Field_Ref Tag and generates a new field instance based on the tag data. So this method has to be called with an element as parameter that contains a field or a field_ref element, respectively.
[ "Searches", "for", "the", "Field", "Child", "tag", "in", "the", "specified", "element", "or", "takes", "the", "Field_Ref", "Tag", "and", "generates", "a", "new", "field", "instance", "based", "on", "the", "tag", "data", ".", "So", "this", "method", "has", ...
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-data-generator/src/main/java/com/mgmtp/jfunk/data/generator/field/FieldFactory.java#L53-L74
lucee/Lucee
core/src/main/java/lucee/transformer/bytecode/Page.java
Page.registerString
public Range registerString(BytecodeContext bc, String str) throws IOException { boolean append = true; if (staticTextLocation == null) { if (bc.getPageSource() == null) return null; PageSource ps = bc.getPageSource(); Mapping m = ps.getMapping(); staticTextLocation = m.getClassRootDirectory(); staticTextLocation.mkdirs(); staticTextLocation = staticTextLocation.getRealResource(ps.getClassName().replace('.', '/') + ".txt"); if (staticTextLocation.exists()) append = false; else staticTextLocation.createFile(true); off = 0; } IOUtil.write(staticTextLocation, str, CharsetUtil.UTF8, append); Range r = new Range(off, str.length()); off += str.length(); return r; }
java
public Range registerString(BytecodeContext bc, String str) throws IOException { boolean append = true; if (staticTextLocation == null) { if (bc.getPageSource() == null) return null; PageSource ps = bc.getPageSource(); Mapping m = ps.getMapping(); staticTextLocation = m.getClassRootDirectory(); staticTextLocation.mkdirs(); staticTextLocation = staticTextLocation.getRealResource(ps.getClassName().replace('.', '/') + ".txt"); if (staticTextLocation.exists()) append = false; else staticTextLocation.createFile(true); off = 0; } IOUtil.write(staticTextLocation, str, CharsetUtil.UTF8, append); Range r = new Range(off, str.length()); off += str.length(); return r; }
[ "public", "Range", "registerString", "(", "BytecodeContext", "bc", ",", "String", "str", ")", "throws", "IOException", "{", "boolean", "append", "=", "true", ";", "if", "(", "staticTextLocation", "==", "null", ")", "{", "if", "(", "bc", ".", "getPageSource",...
return null if not possible to register @param bc @param str @return @throws IOException
[ "return", "null", "if", "not", "possible", "to", "register" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/transformer/bytecode/Page.java#L1612-L1634
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.setStorageAccountAsync
public Observable<StorageBundle> setStorageAccountAsync(String vaultBaseUrl, String storageAccountName, String resourceId, String activeKeyName, boolean autoRegenerateKey) { return setStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName, resourceId, activeKeyName, autoRegenerateKey).map(new Func1<ServiceResponse<StorageBundle>, StorageBundle>() { @Override public StorageBundle call(ServiceResponse<StorageBundle> response) { return response.body(); } }); }
java
public Observable<StorageBundle> setStorageAccountAsync(String vaultBaseUrl, String storageAccountName, String resourceId, String activeKeyName, boolean autoRegenerateKey) { return setStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName, resourceId, activeKeyName, autoRegenerateKey).map(new Func1<ServiceResponse<StorageBundle>, StorageBundle>() { @Override public StorageBundle call(ServiceResponse<StorageBundle> response) { return response.body(); } }); }
[ "public", "Observable", "<", "StorageBundle", ">", "setStorageAccountAsync", "(", "String", "vaultBaseUrl", ",", "String", "storageAccountName", ",", "String", "resourceId", ",", "String", "activeKeyName", ",", "boolean", "autoRegenerateKey", ")", "{", "return", "setS...
Creates or updates a new storage account. This operation requires the storage/set permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageAccountName The name of the storage account. @param resourceId Storage account resource id. @param activeKeyName Current active storage account key name. @param autoRegenerateKey whether keyvault should manage the storage account for the user. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the StorageBundle object
[ "Creates", "or", "updates", "a", "new", "storage", "account", ".", "This", "operation", "requires", "the", "storage", "/", "set", "permission", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L9899-L9906
Azure/azure-sdk-for-java
network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworkPeeringsInner.java
VirtualNetworkPeeringsInner.getAsync
public Observable<VirtualNetworkPeeringInner> getAsync(String resourceGroupName, String virtualNetworkName, String virtualNetworkPeeringName) { return getWithServiceResponseAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName).map(new Func1<ServiceResponse<VirtualNetworkPeeringInner>, VirtualNetworkPeeringInner>() { @Override public VirtualNetworkPeeringInner call(ServiceResponse<VirtualNetworkPeeringInner> response) { return response.body(); } }); }
java
public Observable<VirtualNetworkPeeringInner> getAsync(String resourceGroupName, String virtualNetworkName, String virtualNetworkPeeringName) { return getWithServiceResponseAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName).map(new Func1<ServiceResponse<VirtualNetworkPeeringInner>, VirtualNetworkPeeringInner>() { @Override public VirtualNetworkPeeringInner call(ServiceResponse<VirtualNetworkPeeringInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "VirtualNetworkPeeringInner", ">", "getAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkName", ",", "String", "virtualNetworkPeeringName", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",",...
Gets the specified virtual network peering. @param resourceGroupName The name of the resource group. @param virtualNetworkName The name of the virtual network. @param virtualNetworkPeeringName The name of the virtual network peering. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the VirtualNetworkPeeringInner object
[ "Gets", "the", "specified", "virtual", "network", "peering", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworkPeeringsInner.java#L297-L304
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/parsing/ParseUtils.java
ParseUtils.readBooleanAttributeElement
public static boolean readBooleanAttributeElement(final XMLExtendedStreamReader reader, final String attributeName) throws XMLStreamException { requireSingleAttribute(reader, attributeName); final boolean value = Boolean.parseBoolean(reader.getAttributeValue(0)); requireNoContent(reader); return value; }
java
public static boolean readBooleanAttributeElement(final XMLExtendedStreamReader reader, final String attributeName) throws XMLStreamException { requireSingleAttribute(reader, attributeName); final boolean value = Boolean.parseBoolean(reader.getAttributeValue(0)); requireNoContent(reader); return value; }
[ "public", "static", "boolean", "readBooleanAttributeElement", "(", "final", "XMLExtendedStreamReader", "reader", ",", "final", "String", "attributeName", ")", "throws", "XMLStreamException", "{", "requireSingleAttribute", "(", "reader", ",", "attributeName", ")", ";", "...
Read an element which contains only a single boolean attribute. @param reader the reader @param attributeName the attribute name, usually "value" @return the boolean value @throws javax.xml.stream.XMLStreamException if an error occurs or if the element does not contain the specified attribute, contains other attributes, or contains child elements.
[ "Read", "an", "element", "which", "contains", "only", "a", "single", "boolean", "attribute", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/parsing/ParseUtils.java#L384-L390
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.writeResource
public void writeResource(CmsDbContext dbc, CmsResource resource) throws CmsException { // access was granted - write the resource resource.setUserLastModified(dbc.currentUser().getId()); CmsUUID projectId = ((dbc.getProjectId() == null) || dbc.getProjectId().isNullUUID()) ? dbc.currentProject().getUuid() : dbc.getProjectId(); getVfsDriver(dbc).writeResource(dbc, projectId, resource, UPDATE_RESOURCE_STATE); // make sure the written resource has the state correctly set if (resource.getState().isUnchanged()) { resource.setState(CmsResource.STATE_CHANGED); } // delete in content relations if the new type is not parseable if (!(OpenCms.getResourceManager().getResourceType(resource.getTypeId()) instanceof I_CmsLinkParseable)) { deleteRelationsWithSiblings(dbc, resource); } // update the cache m_monitor.clearResourceCache(); Map<String, Object> data = new HashMap<String, Object>(2); data.put(I_CmsEventListener.KEY_RESOURCE, resource); data.put(I_CmsEventListener.KEY_CHANGE, new Integer(CHANGED_RESOURCE)); OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_RESOURCE_MODIFIED, data)); }
java
public void writeResource(CmsDbContext dbc, CmsResource resource) throws CmsException { // access was granted - write the resource resource.setUserLastModified(dbc.currentUser().getId()); CmsUUID projectId = ((dbc.getProjectId() == null) || dbc.getProjectId().isNullUUID()) ? dbc.currentProject().getUuid() : dbc.getProjectId(); getVfsDriver(dbc).writeResource(dbc, projectId, resource, UPDATE_RESOURCE_STATE); // make sure the written resource has the state correctly set if (resource.getState().isUnchanged()) { resource.setState(CmsResource.STATE_CHANGED); } // delete in content relations if the new type is not parseable if (!(OpenCms.getResourceManager().getResourceType(resource.getTypeId()) instanceof I_CmsLinkParseable)) { deleteRelationsWithSiblings(dbc, resource); } // update the cache m_monitor.clearResourceCache(); Map<String, Object> data = new HashMap<String, Object>(2); data.put(I_CmsEventListener.KEY_RESOURCE, resource); data.put(I_CmsEventListener.KEY_CHANGE, new Integer(CHANGED_RESOURCE)); OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_RESOURCE_MODIFIED, data)); }
[ "public", "void", "writeResource", "(", "CmsDbContext", "dbc", ",", "CmsResource", "resource", ")", "throws", "CmsException", "{", "// access was granted - write the resource", "resource", ".", "setUserLastModified", "(", "dbc", ".", "currentUser", "(", ")", ".", "get...
Writes a resource to the OpenCms VFS.<p> @param dbc the current database context @param resource the resource to write @throws CmsException if something goes wrong
[ "Writes", "a", "resource", "to", "the", "OpenCms", "VFS", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L10142-L10168
OpenBEL/openbel-framework
org.openbel.framework.api/src/main/java/org/openbel/framework/api/Namespaces.java
Namespaces.findNamespaceHeader
public NamespaceHeader findNamespaceHeader(final String rloc) { if (noLength(rloc)) { throw new InvalidArgument("rloc", rloc); } return headers.get(rloc); }
java
public NamespaceHeader findNamespaceHeader(final String rloc) { if (noLength(rloc)) { throw new InvalidArgument("rloc", rloc); } return headers.get(rloc); }
[ "public", "NamespaceHeader", "findNamespaceHeader", "(", "final", "String", "rloc", ")", "{", "if", "(", "noLength", "(", "rloc", ")", ")", "{", "throw", "new", "InvalidArgument", "(", "\"rloc\"", ",", "rloc", ")", ";", "}", "return", "headers", ".", "get"...
Finds the {@link NamespaceHeader namespace header} for the namespace's {@link String resource location}. @param rloc namespace {@link String resource location}, which cannot be {@code null} @return {@link NamespaceHeader namespace header} or {@code null} if one is not found @throws InvalidArgument Thrown if {@code rloc} is {@code null} or empty
[ "Finds", "the", "{", "@link", "NamespaceHeader", "namespace", "header", "}", "for", "the", "namespace", "s", "{", "@link", "String", "resource", "location", "}", "." ]
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.api/src/main/java/org/openbel/framework/api/Namespaces.java#L114-L120
bmwcarit/joynr
java/messaging/bounceproxy/controlled-bounceproxy/src/main/java/io/joynr/messaging/bounceproxy/monitoring/BounceProxyPerformanceReporter.java
BounceProxyPerformanceReporter.sendPerformanceReportAsHttpRequest
private void sendPerformanceReportAsHttpRequest() throws IOException { final String url = bounceProxyControllerUrl.buildReportPerformanceUrl(); logger.debug("Using monitoring service URL: {}", url); Map<String, Integer> performanceMap = bounceProxyPerformanceMonitor.getAsKeyValuePairs(); String serializedMessage = objectMapper.writeValueAsString(performanceMap); HttpPost postReportPerformance = new HttpPost(url.trim()); // using http apache constants here because JOYNr constants are in // libjoynr which should not be included here postReportPerformance.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); postReportPerformance.setEntity(new StringEntity(serializedMessage, "UTF-8")); CloseableHttpResponse response = null; try { response = httpclient.execute(postReportPerformance); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != HttpURLConnection.HTTP_NO_CONTENT) { logger.error("Failed to send performance report: {}", response); throw new JoynrHttpException(statusCode, "Failed to send performance report."); } } finally { if (response != null) { response.close(); } } }
java
private void sendPerformanceReportAsHttpRequest() throws IOException { final String url = bounceProxyControllerUrl.buildReportPerformanceUrl(); logger.debug("Using monitoring service URL: {}", url); Map<String, Integer> performanceMap = bounceProxyPerformanceMonitor.getAsKeyValuePairs(); String serializedMessage = objectMapper.writeValueAsString(performanceMap); HttpPost postReportPerformance = new HttpPost(url.trim()); // using http apache constants here because JOYNr constants are in // libjoynr which should not be included here postReportPerformance.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); postReportPerformance.setEntity(new StringEntity(serializedMessage, "UTF-8")); CloseableHttpResponse response = null; try { response = httpclient.execute(postReportPerformance); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != HttpURLConnection.HTTP_NO_CONTENT) { logger.error("Failed to send performance report: {}", response); throw new JoynrHttpException(statusCode, "Failed to send performance report."); } } finally { if (response != null) { response.close(); } } }
[ "private", "void", "sendPerformanceReportAsHttpRequest", "(", ")", "throws", "IOException", "{", "final", "String", "url", "=", "bounceProxyControllerUrl", ".", "buildReportPerformanceUrl", "(", ")", ";", "logger", ".", "debug", "(", "\"Using monitoring service URL: {}\""...
Sends an HTTP request to the monitoring service to report performance measures of a bounce proxy instance. @throws IOException
[ "Sends", "an", "HTTP", "request", "to", "the", "monitoring", "service", "to", "report", "performance", "measures", "of", "a", "bounce", "proxy", "instance", "." ]
train
https://github.com/bmwcarit/joynr/blob/b7a92bad1cf2f093de080facd2c803560f4c6c26/java/messaging/bounceproxy/controlled-bounceproxy/src/main/java/io/joynr/messaging/bounceproxy/monitoring/BounceProxyPerformanceReporter.java#L135-L165
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/store/ServiceBuilder.java
ServiceBuilder.createTableStoreService
public TableStore createTableStoreService() { return getSingleton(this.tableStoreService, setup -> new TableService(setup.getContainerRegistry(), setup.getSegmentToContainerMapper())); }
java
public TableStore createTableStoreService() { return getSingleton(this.tableStoreService, setup -> new TableService(setup.getContainerRegistry(), setup.getSegmentToContainerMapper())); }
[ "public", "TableStore", "createTableStoreService", "(", ")", "{", "return", "getSingleton", "(", "this", ".", "tableStoreService", ",", "setup", "->", "new", "TableService", "(", "setup", ".", "getContainerRegistry", "(", ")", ",", "setup", ".", "getSegmentToConta...
Creates a new instance of TableStore using the components generated by this class. @return The new instance of TableStore using the components generated by this class.
[ "Creates", "a", "new", "instance", "of", "TableStore", "using", "the", "components", "generated", "by", "this", "class", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/store/ServiceBuilder.java#L244-L246
cucumber/cucumber-jvm
java/src/main/java/cucumber/runtime/java/ObjectFactoryLoader.java
ObjectFactoryLoader.loadObjectFactory
public static ObjectFactory loadObjectFactory(ClassFinder classFinder, String objectFactoryClassName) { ObjectFactory objectFactory; try { Reflections reflections = new Reflections(classFinder); if (objectFactoryClassName != null) { Class<ObjectFactory> objectFactoryClass = (Class<ObjectFactory>) classFinder.loadClass(objectFactoryClassName); objectFactory = reflections.newInstance(new Class[0], new Object[0], objectFactoryClass); } else { List<URI> packages = asList(URI.create("classpath:cucumber/runtime")); objectFactory = reflections.instantiateExactlyOneSubclass(ObjectFactory.class, packages, new Class[0], new Object[0], null); } } catch (TooManyInstancesException e) { log.warn(e.getMessage()); log.warn(getMultipleObjectFactoryLogMessage()); objectFactory = new DefaultJavaObjectFactory(); } catch (NoInstancesException e) { objectFactory = new DefaultJavaObjectFactory(); } catch (ClassNotFoundException e) { throw new CucumberException("Couldn't instantiate custom ObjectFactory", e); } return objectFactory; }
java
public static ObjectFactory loadObjectFactory(ClassFinder classFinder, String objectFactoryClassName) { ObjectFactory objectFactory; try { Reflections reflections = new Reflections(classFinder); if (objectFactoryClassName != null) { Class<ObjectFactory> objectFactoryClass = (Class<ObjectFactory>) classFinder.loadClass(objectFactoryClassName); objectFactory = reflections.newInstance(new Class[0], new Object[0], objectFactoryClass); } else { List<URI> packages = asList(URI.create("classpath:cucumber/runtime")); objectFactory = reflections.instantiateExactlyOneSubclass(ObjectFactory.class, packages, new Class[0], new Object[0], null); } } catch (TooManyInstancesException e) { log.warn(e.getMessage()); log.warn(getMultipleObjectFactoryLogMessage()); objectFactory = new DefaultJavaObjectFactory(); } catch (NoInstancesException e) { objectFactory = new DefaultJavaObjectFactory(); } catch (ClassNotFoundException e) { throw new CucumberException("Couldn't instantiate custom ObjectFactory", e); } return objectFactory; }
[ "public", "static", "ObjectFactory", "loadObjectFactory", "(", "ClassFinder", "classFinder", ",", "String", "objectFactoryClassName", ")", "{", "ObjectFactory", "objectFactory", ";", "try", "{", "Reflections", "reflections", "=", "new", "Reflections", "(", "classFinder"...
Loads an instance of {@link ObjectFactory}. The class name can be explicit, or it can be null. When it's null, the implementation is searched for in the <pre>cucumber.runtime</pre> packahe. @param classFinder where to load classes from @param objectFactoryClassName specific class name of {@link ObjectFactory} implementation. May be null. @return an instance of {@link ObjectFactory}
[ "Loads", "an", "instance", "of", "{", "@link", "ObjectFactory", "}", ".", "The", "class", "name", "can", "be", "explicit", "or", "it", "can", "be", "null", ".", "When", "it", "s", "null", "the", "implementation", "is", "searched", "for", "in", "the", "...
train
https://github.com/cucumber/cucumber-jvm/blob/437bb3a1f1d91b56f44059c835765b395eefc777/java/src/main/java/cucumber/runtime/java/ObjectFactoryLoader.java#L32-L54
j-easy/easy-random
easy-random-core/src/main/java/org/jeasy/random/randomizers/range/OffsetTimeRangeRandomizer.java
OffsetTimeRangeRandomizer.aNewOffsetTimeRangeRandomizer
public static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed) { return new OffsetTimeRangeRandomizer(min, max, seed); }
java
public static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed) { return new OffsetTimeRangeRandomizer(min, max, seed); }
[ "public", "static", "OffsetTimeRangeRandomizer", "aNewOffsetTimeRangeRandomizer", "(", "final", "OffsetTime", "min", ",", "final", "OffsetTime", "max", ",", "final", "long", "seed", ")", "{", "return", "new", "OffsetTimeRangeRandomizer", "(", "min", ",", "max", ",",...
Create a new {@link OffsetTimeRangeRandomizer}. @param min min value @param max max value @param seed initial seed @return a new {@link OffsetTimeRangeRandomizer}.
[ "Create", "a", "new", "{", "@link", "OffsetTimeRangeRandomizer", "}", "." ]
train
https://github.com/j-easy/easy-random/blob/816b0d6a74c7288af111e70ae1b0b57d7fe3b59d/easy-random-core/src/main/java/org/jeasy/random/randomizers/range/OffsetTimeRangeRandomizer.java#L77-L79
offbynull/coroutines
maven-plugin/src/main/java/com/offbynull/coroutines/mavenplugin/AbstractInstrumentMojo.java
AbstractInstrumentMojo.instrumentPath
protected final void instrumentPath(Log log, List<String> classpath, File path) throws MojoExecutionException { try { Instrumenter instrumenter = getInstrumenter(log, classpath); InstrumentationSettings settings = new InstrumentationSettings(markerType, debugMode, autoSerializable); PluginHelper.instrument(instrumenter, settings, path, path, log::info); } catch (Exception ex) { throw new MojoExecutionException("Unable to get compile classpath elements", ex); } }
java
protected final void instrumentPath(Log log, List<String> classpath, File path) throws MojoExecutionException { try { Instrumenter instrumenter = getInstrumenter(log, classpath); InstrumentationSettings settings = new InstrumentationSettings(markerType, debugMode, autoSerializable); PluginHelper.instrument(instrumenter, settings, path, path, log::info); } catch (Exception ex) { throw new MojoExecutionException("Unable to get compile classpath elements", ex); } }
[ "protected", "final", "void", "instrumentPath", "(", "Log", "log", ",", "List", "<", "String", ">", "classpath", ",", "File", "path", ")", "throws", "MojoExecutionException", "{", "try", "{", "Instrumenter", "instrumenter", "=", "getInstrumenter", "(", "log", ...
Instruments all classes in a path recursively. @param log maven logger @param classpath classpath for classes being instrumented @param path directory containing files to instrument @throws MojoExecutionException if any exception occurs
[ "Instruments", "all", "classes", "in", "a", "path", "recursively", "." ]
train
https://github.com/offbynull/coroutines/blob/b1b83c293945f53a2f63fca8f15a53e88b796bf5/maven-plugin/src/main/java/com/offbynull/coroutines/mavenplugin/AbstractInstrumentMojo.java#L57-L67