repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
194
func_name
stringlengths
6
111
whole_func_string
stringlengths
80
3.8k
language
stringclasses
1 value
func_code_string
stringlengths
80
3.8k
func_code_tokens
listlengths
20
697
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
434
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
bazaarvoice/emodb
table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTable.java
AstyanaxTable.createUnknown
public static AstyanaxTable createUnknown(long uuid, Placement placement, @Nullable String name) { AstyanaxStorage storage = new AstyanaxStorage( uuid, RowKeyUtils.NUM_SHARDS_UNKNOWN, false/*reads-not-allowed*/, placement.getName(), Suppliers.ofInstance(placement)); return new AstyanaxTable( name != null ? name : "__unknown:" + TableUuidFormat.encode(uuid), new TableOptionsBuilder().setPlacement(placement.getName()).build(), ImmutableMap.<String, Object>of("~unknown", true, "uuid", uuid), null/*availability*/, storage, ImmutableList.of(storage), Suppliers.<Collection<DataCenter>>ofInstance(ImmutableList.<DataCenter>of())); }
java
public static AstyanaxTable createUnknown(long uuid, Placement placement, @Nullable String name) { AstyanaxStorage storage = new AstyanaxStorage( uuid, RowKeyUtils.NUM_SHARDS_UNKNOWN, false/*reads-not-allowed*/, placement.getName(), Suppliers.ofInstance(placement)); return new AstyanaxTable( name != null ? name : "__unknown:" + TableUuidFormat.encode(uuid), new TableOptionsBuilder().setPlacement(placement.getName()).build(), ImmutableMap.<String, Object>of("~unknown", true, "uuid", uuid), null/*availability*/, storage, ImmutableList.of(storage), Suppliers.<Collection<DataCenter>>ofInstance(ImmutableList.<DataCenter>of())); }
[ "public", "static", "AstyanaxTable", "createUnknown", "(", "long", "uuid", ",", "Placement", "placement", ",", "@", "Nullable", "String", "name", ")", "{", "AstyanaxStorage", "storage", "=", "new", "AstyanaxStorage", "(", "uuid", ",", "RowKeyUtils", ".", "NUM_SH...
Creates a placeholder for unknown tables. A table may be unknown for one of two reasons: 1) the table used to exist but has been deleted, or 2) the table never existed. In the former case the table will have a name, but in the latter case the table will be unnamed and the "name" parameter will be null.
[ "Creates", "a", "placeholder", "for", "unknown", "tables", ".", "A", "table", "may", "be", "unknown", "for", "one", "of", "two", "reasons", ":", "1", ")", "the", "table", "used", "to", "exist", "but", "has", "been", "deleted", "or", "2", ")", "the", ...
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTable.java#L110-L120
kuali/ojb-1.0.4
src/java/org/apache/ojb/odmg/locking/RemoteLockMapImpl.java
RemoteLockMapImpl.removeReader
public void removeReader(TransactionImpl tx, Object obj) { try { LockEntry lock = new LockEntry(new Identity(obj,getBroker()).toString(), tx.getGUID()); removeReaderRemote(lock); } catch (Throwable t) { log.error("Cannot remove LockEntry for object " + obj + " in transaction " + tx); } }
java
public void removeReader(TransactionImpl tx, Object obj) { try { LockEntry lock = new LockEntry(new Identity(obj,getBroker()).toString(), tx.getGUID()); removeReaderRemote(lock); } catch (Throwable t) { log.error("Cannot remove LockEntry for object " + obj + " in transaction " + tx); } }
[ "public", "void", "removeReader", "(", "TransactionImpl", "tx", ",", "Object", "obj", ")", "{", "try", "{", "LockEntry", "lock", "=", "new", "LockEntry", "(", "new", "Identity", "(", "obj", ",", "getBroker", "(", ")", ")", ".", "toString", "(", ")", ",...
remove a reader lock entry for transaction tx on object obj from the persistent storage.
[ "remove", "a", "reader", "lock", "entry", "for", "transaction", "tx", "on", "object", "obj", "from", "the", "persistent", "storage", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/odmg/locking/RemoteLockMapImpl.java#L245-L256
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.patchClosedListAsync
public Observable<OperationStatus> patchClosedListAsync(UUID appId, String versionId, UUID clEntityId, PatchClosedListOptionalParameter patchClosedListOptionalParameter) { return patchClosedListWithServiceResponseAsync(appId, versionId, clEntityId, patchClosedListOptionalParameter).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() { @Override public OperationStatus call(ServiceResponse<OperationStatus> response) { return response.body(); } }); }
java
public Observable<OperationStatus> patchClosedListAsync(UUID appId, String versionId, UUID clEntityId, PatchClosedListOptionalParameter patchClosedListOptionalParameter) { return patchClosedListWithServiceResponseAsync(appId, versionId, clEntityId, patchClosedListOptionalParameter).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() { @Override public OperationStatus call(ServiceResponse<OperationStatus> response) { return response.body(); } }); }
[ "public", "Observable", "<", "OperationStatus", ">", "patchClosedListAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "clEntityId", ",", "PatchClosedListOptionalParameter", "patchClosedListOptionalParameter", ")", "{", "return", "patchClosedListWithSer...
Adds a batch of sublists to an existing closedlist. @param appId The application ID. @param versionId The version ID. @param clEntityId The closed list model ID. @param patchClosedListOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatus object
[ "Adds", "a", "batch", "of", "sublists", "to", "an", "existing", "closedlist", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L4439-L4446
google/closure-compiler
src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java
DevirtualizePrototypeMethods.rewriteCall
private void rewriteCall(Node getprop, String newMethodName) { checkArgument(getprop.isGetProp(), getprop); Node call = getprop.getParent(); checkArgument(call.isCall(), call); Node receiver = getprop.getFirstChild(); // This rewriting does not exactly preserve order of operations; the newly inserted static // method name will be resolved before `receiver` is evaluated. This is known to be safe due // to the eligibility checks earlier in the pass. // // We choose not to do a full-fidelity rewriting (e.g. using `ExpressionDecomposer`) because // doing so means extracting `receiver` into a new variable at each call-site. This has a // significant code-size impact (circa 2018-11-19). getprop.removeChild(receiver); call.replaceChild(getprop, receiver); call.addChildToFront(IR.name(newMethodName).srcref(getprop)); if (receiver.isSuper()) { // Case: `super.foo(a, b)` => `foo(this, a, b)` receiver.setToken(Token.THIS); } call.putBooleanProp(Node.FREE_CALL, true); compiler.reportChangeToEnclosingScope(call); }
java
private void rewriteCall(Node getprop, String newMethodName) { checkArgument(getprop.isGetProp(), getprop); Node call = getprop.getParent(); checkArgument(call.isCall(), call); Node receiver = getprop.getFirstChild(); // This rewriting does not exactly preserve order of operations; the newly inserted static // method name will be resolved before `receiver` is evaluated. This is known to be safe due // to the eligibility checks earlier in the pass. // // We choose not to do a full-fidelity rewriting (e.g. using `ExpressionDecomposer`) because // doing so means extracting `receiver` into a new variable at each call-site. This has a // significant code-size impact (circa 2018-11-19). getprop.removeChild(receiver); call.replaceChild(getprop, receiver); call.addChildToFront(IR.name(newMethodName).srcref(getprop)); if (receiver.isSuper()) { // Case: `super.foo(a, b)` => `foo(this, a, b)` receiver.setToken(Token.THIS); } call.putBooleanProp(Node.FREE_CALL, true); compiler.reportChangeToEnclosingScope(call); }
[ "private", "void", "rewriteCall", "(", "Node", "getprop", ",", "String", "newMethodName", ")", "{", "checkArgument", "(", "getprop", ".", "isGetProp", "(", ")", ",", "getprop", ")", ";", "Node", "call", "=", "getprop", ".", "getParent", "(", ")", ";", "c...
Rewrites object method call sites as calls to global functions that take "this" as their first argument. <p>Before: o.foo(a, b, c) <p>After: foo(o, a, b, c)
[ "Rewrites", "object", "method", "call", "sites", "as", "calls", "to", "global", "functions", "that", "take", "this", "as", "their", "first", "argument", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java#L363-L388
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WText.java
WText.setText
public void setText(final String text, final Serializable... args) { setData(I18nUtilities.asMessage(text, args)); }
java
public void setText(final String text, final Serializable... args) { setData(I18nUtilities.asMessage(text, args)); }
[ "public", "void", "setText", "(", "final", "String", "text", ",", "final", "Serializable", "...", "args", ")", "{", "setData", "(", "I18nUtilities", ".", "asMessage", "(", "text", ",", "args", ")", ")", ";", "}" ]
<p> Sets the text.</p> <p> NOTE: If the text is dynamically generated, it may be preferable to override {@link #getText()} instead. This will reduce the amount of data which is stored in the user session. </p> @param text the text to set, using {@link MessageFormat} syntax. @param args optional arguments for the message format string. <pre> // Changes the text to "Hello world" myText.setText("Hello world"); </pre> <pre> // Changes the text to "Secret agent James Bond, 007" new WText("Secret agent {0}, {1,number,000}", "James Bond", 7); </pre>
[ "<p", ">", "Sets", "the", "text", ".", "<", "/", "p", ">" ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WText.java#L89-L91
Jasig/uPortal
uPortal-utils/uPortal-utils-jmx/src/main/java/org/apereo/portal/jmx/JavaManagementServerBean.java
JavaManagementServerBean.getServiceUrl
protected JMXServiceURL getServiceUrl(final int portOne, int portTwo) { final String jmxHost; if (this.host == null) { final InetAddress inetHost; try { inetHost = InetAddress.getLocalHost(); } catch (UnknownHostException uhe) { throw new IllegalStateException("Cannot resolve localhost InetAddress.", uhe); } jmxHost = inetHost.getHostName(); } else { jmxHost = this.host; } final String jmxUrl = "service:jmx:rmi://" + jmxHost + ":" + portTwo + "/jndi/rmi://" + jmxHost + ":" + portOne + "/server"; final JMXServiceURL jmxServiceUrl; try { jmxServiceUrl = new JMXServiceURL(jmxUrl); } catch (MalformedURLException mue) { throw new IllegalStateException( "Failed to create JMXServiceURL for url String '" + jmxUrl + "'", mue); } if (this.logger.isDebugEnabled()) { this.logger.debug( "Generated JMXServiceURL='" + jmxServiceUrl + "' from String " + jmxUrl + "'."); } return jmxServiceUrl; }
java
protected JMXServiceURL getServiceUrl(final int portOne, int portTwo) { final String jmxHost; if (this.host == null) { final InetAddress inetHost; try { inetHost = InetAddress.getLocalHost(); } catch (UnknownHostException uhe) { throw new IllegalStateException("Cannot resolve localhost InetAddress.", uhe); } jmxHost = inetHost.getHostName(); } else { jmxHost = this.host; } final String jmxUrl = "service:jmx:rmi://" + jmxHost + ":" + portTwo + "/jndi/rmi://" + jmxHost + ":" + portOne + "/server"; final JMXServiceURL jmxServiceUrl; try { jmxServiceUrl = new JMXServiceURL(jmxUrl); } catch (MalformedURLException mue) { throw new IllegalStateException( "Failed to create JMXServiceURL for url String '" + jmxUrl + "'", mue); } if (this.logger.isDebugEnabled()) { this.logger.debug( "Generated JMXServiceURL='" + jmxServiceUrl + "' from String " + jmxUrl + "'."); } return jmxServiceUrl; }
[ "protected", "JMXServiceURL", "getServiceUrl", "(", "final", "int", "portOne", ",", "int", "portTwo", ")", "{", "final", "String", "jmxHost", ";", "if", "(", "this", ".", "host", "==", "null", ")", "{", "final", "InetAddress", "inetHost", ";", "try", "{", ...
Generates the JMXServiceURL for the two specified ports. @return A JMXServiceURL for this host using the two specified ports. @throws IllegalStateException If localhost cannot be resolved or if the JMXServiceURL is malformed.
[ "Generates", "the", "JMXServiceURL", "for", "the", "two", "specified", "ports", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-jmx/src/main/java/org/apereo/portal/jmx/JavaManagementServerBean.java#L269-L309
jbundle/jbundle
thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/print/PaperPrint.java
PaperPrint.surveyPage
public void surveyPage(PageFormat pageFormat, Graphics2D g2d, boolean bPrintHeader) { pageRect = new Rectangle((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY(), (int)pageFormat.getImageableWidth(), (int)pageFormat.getImageableHeight()); FontMetrics fm = g2d.getFontMetrics(); int textHeight = fm.getHeight(); if (bPrintHeader) { headerHeight = textHeight + HEADER_MARGIN + BORDER; footerHeight = textHeight + HEADER_MARGIN + BORDER; } }
java
public void surveyPage(PageFormat pageFormat, Graphics2D g2d, boolean bPrintHeader) { pageRect = new Rectangle((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY(), (int)pageFormat.getImageableWidth(), (int)pageFormat.getImageableHeight()); FontMetrics fm = g2d.getFontMetrics(); int textHeight = fm.getHeight(); if (bPrintHeader) { headerHeight = textHeight + HEADER_MARGIN + BORDER; footerHeight = textHeight + HEADER_MARGIN + BORDER; } }
[ "public", "void", "surveyPage", "(", "PageFormat", "pageFormat", ",", "Graphics2D", "g2d", ",", "boolean", "bPrintHeader", ")", "{", "pageRect", "=", "new", "Rectangle", "(", "(", "int", ")", "pageFormat", ".", "getImageableX", "(", ")", ",", "(", "int", "...
Save basic page information. @param pageFormat The pageformat from the print call. @param g2d The graphics environment from the print call.
[ "Save", "basic", "page", "information", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/print/PaperPrint.java#L57-L68
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.columnIndex
public static int columnIndex(CSTable table, String name) { for (int i = 1; i <= table.getColumnCount(); i++) { if (table.getColumnName(i).equals(name)) { return i; } } return -1; }
java
public static int columnIndex(CSTable table, String name) { for (int i = 1; i <= table.getColumnCount(); i++) { if (table.getColumnName(i).equals(name)) { return i; } } return -1; }
[ "public", "static", "int", "columnIndex", "(", "CSTable", "table", ",", "String", "name", ")", "{", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "table", ".", "getColumnCount", "(", ")", ";", "i", "++", ")", "{", "if", "(", "table", ".", "ge...
Gets a column index by name @param table The table to check @param name the column name @return the index of the column
[ "Gets", "a", "column", "index", "by", "name" ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L1252-L1259
mlhartme/mork
src/main/java/net/oneandone/mork/semantics/AgBuffer.java
AgBuffer.cloneAttributes
public Attribute cloneAttributes(AgBuffer orig, Type type, Attribute seed) { Map<Attribute, Attribute> map; // old attributes to new attributes Attribute attr; State newState; map = new HashMap<Attribute, Attribute>(); for (State state : orig.states) { attr = state.getAttribute(); map.put(attr, new Attribute(attr.symbol, null, type)); } for (State state : orig.states) { newState = state.cloneAttributeTransport(map); states.add(newState); } attr = map.get(seed); if (attr == null) { throw new IllegalArgumentException(); } return attr; }
java
public Attribute cloneAttributes(AgBuffer orig, Type type, Attribute seed) { Map<Attribute, Attribute> map; // old attributes to new attributes Attribute attr; State newState; map = new HashMap<Attribute, Attribute>(); for (State state : orig.states) { attr = state.getAttribute(); map.put(attr, new Attribute(attr.symbol, null, type)); } for (State state : orig.states) { newState = state.cloneAttributeTransport(map); states.add(newState); } attr = map.get(seed); if (attr == null) { throw new IllegalArgumentException(); } return attr; }
[ "public", "Attribute", "cloneAttributes", "(", "AgBuffer", "orig", ",", "Type", "type", ",", "Attribute", "seed", ")", "{", "Map", "<", "Attribute", ",", "Attribute", ">", "map", ";", "// old attributes to new attributes", "Attribute", "attr", ";", "State", "new...
Clones this buffer but replaces all transport attributes with new attributes of the specified type. @param type for new attributes @return cloned seed
[ "Clones", "this", "buffer", "but", "replaces", "all", "transport", "attributes", "with", "new", "attributes", "of", "the", "specified", "type", "." ]
train
https://github.com/mlhartme/mork/blob/a069b087750c4133bfeebaf1f599c3bc96762113/src/main/java/net/oneandone/mork/semantics/AgBuffer.java#L315-L334
Tourenathan-G5organisation/SiliCompressor
silicompressor/src/main/java/com/iceteck/silicompressorr/FileUtils.java
FileUtils.getThumbnail
public static Bitmap getThumbnail(Context context, Uri uri) { return getThumbnail(context, uri, getMimeType(context, uri)); }
java
public static Bitmap getThumbnail(Context context, Uri uri) { return getThumbnail(context, uri, getMimeType(context, uri)); }
[ "public", "static", "Bitmap", "getThumbnail", "(", "Context", "context", ",", "Uri", "uri", ")", "{", "return", "getThumbnail", "(", "context", ",", "uri", ",", "getMimeType", "(", "context", ",", "uri", ")", ")", ";", "}" ]
Attempt to retrieve the thumbnail of given Uri from the MediaStore. This should not be called on the UI thread. @param context @param uri @return @author paulburke
[ "Attempt", "to", "retrieve", "the", "thumbnail", "of", "given", "Uri", "from", "the", "MediaStore", ".", "This", "should", "not", "be", "called", "on", "the", "UI", "thread", "." ]
train
https://github.com/Tourenathan-G5organisation/SiliCompressor/blob/546f6cd7b2a7a783e1122df46c1e237f8938fe72/silicompressor/src/main/java/com/iceteck/silicompressorr/FileUtils.java#L405-L407
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TimeZoneFormat.java
TimeZoneFormat.formatSpecific
private String formatSpecific(TimeZone tz, NameType stdType, NameType dstType, long date, Output<TimeType> timeType) { assert(stdType == NameType.LONG_STANDARD || stdType == NameType.SHORT_STANDARD); assert(dstType == NameType.LONG_DAYLIGHT || dstType == NameType.SHORT_DAYLIGHT); boolean isDaylight = tz.inDaylightTime(new Date(date)); String name = isDaylight? getTimeZoneNames().getDisplayName(ZoneMeta.getCanonicalCLDRID(tz), dstType, date) : getTimeZoneNames().getDisplayName(ZoneMeta.getCanonicalCLDRID(tz), stdType, date); if (name != null && timeType != null) { timeType.value = isDaylight ? TimeType.DAYLIGHT : TimeType.STANDARD; } return name; }
java
private String formatSpecific(TimeZone tz, NameType stdType, NameType dstType, long date, Output<TimeType> timeType) { assert(stdType == NameType.LONG_STANDARD || stdType == NameType.SHORT_STANDARD); assert(dstType == NameType.LONG_DAYLIGHT || dstType == NameType.SHORT_DAYLIGHT); boolean isDaylight = tz.inDaylightTime(new Date(date)); String name = isDaylight? getTimeZoneNames().getDisplayName(ZoneMeta.getCanonicalCLDRID(tz), dstType, date) : getTimeZoneNames().getDisplayName(ZoneMeta.getCanonicalCLDRID(tz), stdType, date); if (name != null && timeType != null) { timeType.value = isDaylight ? TimeType.DAYLIGHT : TimeType.STANDARD; } return name; }
[ "private", "String", "formatSpecific", "(", "TimeZone", "tz", ",", "NameType", "stdType", ",", "NameType", "dstType", ",", "long", "date", ",", "Output", "<", "TimeType", ">", "timeType", ")", "{", "assert", "(", "stdType", "==", "NameType", ".", "LONG_STAND...
Private method returning the time zone's specific format string. @param tz the time zone @param stdType the name type used for standard time @param dstType the name type used for daylight time @param date the date @param timeType when null, actual time type is set @return the time zone's specific format name string
[ "Private", "method", "returning", "the", "time", "zone", "s", "specific", "format", "string", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TimeZoneFormat.java#L1710-L1723
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/error/ErrorTextProvider.java
ErrorTextProvider.addItem
@Nonnull public ErrorTextProvider addItem (@Nonnull final EField eField, @Nonnull @Nonempty final String sText) { return addItem (new FormattableItem (eField, sText)); }
java
@Nonnull public ErrorTextProvider addItem (@Nonnull final EField eField, @Nonnull @Nonempty final String sText) { return addItem (new FormattableItem (eField, sText)); }
[ "@", "Nonnull", "public", "ErrorTextProvider", "addItem", "(", "@", "Nonnull", "final", "EField", "eField", ",", "@", "Nonnull", "@", "Nonempty", "final", "String", "sText", ")", "{", "return", "addItem", "(", "new", "FormattableItem", "(", "eField", ",", "s...
Add an error item to be disabled. @param eField The field to be used. May not be <code>null</code>. @param sText The text that should contain the placeholder ({@value #PLACEHOLDER}) that will be replaced @return this for chaining
[ "Add", "an", "error", "item", "to", "be", "disabled", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/error/ErrorTextProvider.java#L205-L209
apereo/cas
core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/JsonUtils.java
JsonUtils.renderException
public static void renderException(final Exception ex, final HttpServletResponse response) { val map = new HashMap<String, String>(); map.put("error", ex.getMessage()); map.put("stacktrace", Arrays.deepToString(ex.getStackTrace())); renderException(map, response); }
java
public static void renderException(final Exception ex, final HttpServletResponse response) { val map = new HashMap<String, String>(); map.put("error", ex.getMessage()); map.put("stacktrace", Arrays.deepToString(ex.getStackTrace())); renderException(map, response); }
[ "public", "static", "void", "renderException", "(", "final", "Exception", "ex", ",", "final", "HttpServletResponse", "response", ")", "{", "val", "map", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "map", ".", "put", "(", "\"e...
Render exceptions. Adds error messages and the stack trace to the json model and sets the response status accordingly to note bad requests. @param ex the ex @param response the response
[ "Render", "exceptions", ".", "Adds", "error", "messages", "and", "the", "stack", "trace", "to", "the", "json", "model", "and", "sets", "the", "response", "status", "accordingly", "to", "note", "bad", "requests", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/JsonUtils.java#L54-L59
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/SourceToHTMLConverter.java
SourceToHTMLConverter.convertPackage
public void convertPackage(PackageDoc pd, DocPath outputdir) { if (pd == null) { return; } for (ClassDoc cd : pd.allClasses()) { // If -nodeprecated option is set and the class is marked as deprecated, // do not convert the package files to HTML. We do not check for // containing package deprecation since it is already check in // the calling method above. if (!(configuration.nodeprecated && utils.isDeprecated(cd))) convertClass(cd, outputdir); } }
java
public void convertPackage(PackageDoc pd, DocPath outputdir) { if (pd == null) { return; } for (ClassDoc cd : pd.allClasses()) { // If -nodeprecated option is set and the class is marked as deprecated, // do not convert the package files to HTML. We do not check for // containing package deprecation since it is already check in // the calling method above. if (!(configuration.nodeprecated && utils.isDeprecated(cd))) convertClass(cd, outputdir); } }
[ "public", "void", "convertPackage", "(", "PackageDoc", "pd", ",", "DocPath", "outputdir", ")", "{", "if", "(", "pd", "==", "null", ")", "{", "return", ";", "}", "for", "(", "ClassDoc", "cd", ":", "pd", ".", "allClasses", "(", ")", ")", "{", "// If -n...
Convert the Classes in the given Package to an HTML. @param pd the Package to convert. @param outputdir the name of the directory to output to.
[ "Convert", "the", "Classes", "in", "the", "given", "Package", "to", "an", "HTML", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/SourceToHTMLConverter.java#L124-L136
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CECalendar.java
CECalendar.ceToJD
public static int ceToJD(long year, int month, int day, int jdEpochOffset) { // Julian<->Ethiopic algorithms from: // "Calendars in Ethiopia", Berhanu Beyene, Manfred Kudlek, International Conference // of Ethiopian Studies XV, Hamburg, 2003 // handle month > 12, < 0 (e.g. from add/set) if ( month >= 0 ) { year += month/13; month %= 13; } else { ++month; year += month/13 - 1; month = month%13 + 12; } return (int) ( jdEpochOffset // difference from Julian epoch to 1,1,1 + 365 * year // number of days from years + floorDivide(year, 4) // extra day of leap year + 30 * month // number of days from months (months are 0-based) + day - 1 // number of days for present month (1 based) ); }
java
public static int ceToJD(long year, int month, int day, int jdEpochOffset) { // Julian<->Ethiopic algorithms from: // "Calendars in Ethiopia", Berhanu Beyene, Manfred Kudlek, International Conference // of Ethiopian Studies XV, Hamburg, 2003 // handle month > 12, < 0 (e.g. from add/set) if ( month >= 0 ) { year += month/13; month %= 13; } else { ++month; year += month/13 - 1; month = month%13 + 12; } return (int) ( jdEpochOffset // difference from Julian epoch to 1,1,1 + 365 * year // number of days from years + floorDivide(year, 4) // extra day of leap year + 30 * month // number of days from months (months are 0-based) + day - 1 // number of days for present month (1 based) ); }
[ "public", "static", "int", "ceToJD", "(", "long", "year", ",", "int", "month", ",", "int", "day", ",", "int", "jdEpochOffset", ")", "{", "// Julian<->Ethiopic algorithms from:", "// \"Calendars in Ethiopia\", Berhanu Beyene, Manfred Kudlek, International Conference", "// of E...
Convert an Coptic/Ethiopic year, month and day to a Julian day @param year the extended year @param month the month @param day the day @return Julian day @hide unsupported on Android
[ "Convert", "an", "Coptic", "/", "Ethiopic", "year", "month", "and", "day", "to", "a", "Julian", "day" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CECalendar.java#L236-L258
Red5/red5-client
src/main/java/org/red5/client/net/rtmp/RTMPClient.java
RTMPClient.setProtocol
@Override public void setProtocol(String protocol) throws Exception { this.protocol = protocol; if ("rtmps".equals(protocol) || "rtmpt".equals(protocol) || "rtmpte".equals(protocol) || "rtmfp".equals(protocol)) { throw new Exception("Unsupported protocol specified, please use the correct client for the intended protocol."); } }
java
@Override public void setProtocol(String protocol) throws Exception { this.protocol = protocol; if ("rtmps".equals(protocol) || "rtmpt".equals(protocol) || "rtmpte".equals(protocol) || "rtmfp".equals(protocol)) { throw new Exception("Unsupported protocol specified, please use the correct client for the intended protocol."); } }
[ "@", "Override", "public", "void", "setProtocol", "(", "String", "protocol", ")", "throws", "Exception", "{", "this", ".", "protocol", "=", "protocol", ";", "if", "(", "\"rtmps\"", ".", "equals", "(", "protocol", ")", "||", "\"rtmpt\"", ".", "equals", "(",...
Sets the RTMP protocol, the default is "rtmp". If "rtmps" or "rtmpt" are required, the appropriate client type should be selected. @param protocol the protocol to set @throws Exception
[ "Sets", "the", "RTMP", "protocol", "the", "default", "is", "rtmp", ".", "If", "rtmps", "or", "rtmpt", "are", "required", "the", "appropriate", "client", "type", "should", "be", "selected", "." ]
train
https://github.com/Red5/red5-client/blob/f894495b60e59d7cfba647abd9b934237cac9d45/src/main/java/org/red5/client/net/rtmp/RTMPClient.java#L140-L146
apache/incubator-gobblin
gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/filesystem/MetricsFileSystemInstrumentation.java
MetricsFileSystemInstrumentation.setTimes
public void setTimes (Path f, long t, long a) throws IOException { try (Closeable context = new TimerContextWithLog(this.setTimesTimer.time(), "setTimes", f, t, a)) { super.setTimes(f, t, a); } }
java
public void setTimes (Path f, long t, long a) throws IOException { try (Closeable context = new TimerContextWithLog(this.setTimesTimer.time(), "setTimes", f, t, a)) { super.setTimes(f, t, a); } }
[ "public", "void", "setTimes", "(", "Path", "f", ",", "long", "t", ",", "long", "a", ")", "throws", "IOException", "{", "try", "(", "Closeable", "context", "=", "new", "TimerContextWithLog", "(", "this", ".", "setTimesTimer", ".", "time", "(", ")", ",", ...
Add timer metrics to {@link DistributedFileSystem#setTimes(Path, long, long)}
[ "Add", "timer", "metrics", "to", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/filesystem/MetricsFileSystemInstrumentation.java#L316-L320
rimerosolutions/ant-git-tasks
src/main/java/com/rimerosolutions/ant/git/tasks/BranchListTask.java
BranchListTask.setListMode
public void setListMode(String listMode) { if (!GitTaskUtils.isNullOrBlankString(listMode)) { try { this.listMode = ListBranchCommand.ListMode.valueOf(listMode); } catch (IllegalArgumentException e) { ListBranchCommand.ListMode[] listModes = ListBranchCommand.ListMode.values(); List<String> listModeValidValues = new ArrayList<String>(listModes.length); for (ListBranchCommand.ListMode aListMode : listModes) { listModeValidValues.add(aListMode.name()); } String validModes = listModeValidValues.toString(); throw new BuildException(String.format("Valid listMode options are: %s.", validModes)); } } }
java
public void setListMode(String listMode) { if (!GitTaskUtils.isNullOrBlankString(listMode)) { try { this.listMode = ListBranchCommand.ListMode.valueOf(listMode); } catch (IllegalArgumentException e) { ListBranchCommand.ListMode[] listModes = ListBranchCommand.ListMode.values(); List<String> listModeValidValues = new ArrayList<String>(listModes.length); for (ListBranchCommand.ListMode aListMode : listModes) { listModeValidValues.add(aListMode.name()); } String validModes = listModeValidValues.toString(); throw new BuildException(String.format("Valid listMode options are: %s.", validModes)); } } }
[ "public", "void", "setListMode", "(", "String", "listMode", ")", "{", "if", "(", "!", "GitTaskUtils", ".", "isNullOrBlankString", "(", "listMode", ")", ")", "{", "try", "{", "this", ".", "listMode", "=", "ListBranchCommand", ".", "ListMode", ".", "valueOf", ...
Sets the listing mode @antdoc.notrequired @param listMode - optional: corresponds to the -r/-a options; by default, only local branches will be listed
[ "Sets", "the", "listing", "mode" ]
train
https://github.com/rimerosolutions/ant-git-tasks/blob/bfb32fe68afe6b9dcfd0a5194497d748ef3e8a6f/src/main/java/com/rimerosolutions/ant/git/tasks/BranchListTask.java#L59-L78
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Validate.java
Validate.exclusiveBetween
@SuppressWarnings("boxing") public static void exclusiveBetween(final long start, final long end, final long value) { // TODO when breaking BC, consider returning value if (value <= start || value >= end) { throw new IllegalArgumentException(StringUtils.simpleFormat(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } }
java
@SuppressWarnings("boxing") public static void exclusiveBetween(final long start, final long end, final long value) { // TODO when breaking BC, consider returning value if (value <= start || value >= end) { throw new IllegalArgumentException(StringUtils.simpleFormat(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } }
[ "@", "SuppressWarnings", "(", "\"boxing\"", ")", "public", "static", "void", "exclusiveBetween", "(", "final", "long", "start", ",", "final", "long", "end", ",", "final", "long", "value", ")", "{", "// TODO when breaking BC, consider returning value", "if", "(", "...
Validate that the specified primitive value falls between the two exclusive values specified; otherwise, throws an exception. <pre>Validate.exclusiveBetween(0, 2, 1);</pre> @param start the exclusive start value @param end the exclusive end value @param value the value to validate @throws IllegalArgumentException if the value falls out of the boundaries @since 3.3
[ "Validate", "that", "the", "specified", "primitive", "value", "falls", "between", "the", "two", "exclusive", "values", "specified", ";", "otherwise", "throws", "an", "exception", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L1172-L1178
alkacon/opencms-core
src/org/opencms/ade/sitemap/CmsVfsSitemapService.java
CmsVfsSitemapService.getNewResourceInfos
private List<CmsNewResourceInfo> getNewResourceInfos(CmsObject cms, CmsADEConfigData configData, Locale locale) { List<CmsNewResourceInfo> result = new ArrayList<CmsNewResourceInfo>(); for (CmsModelPageConfig modelConfig : configData.getModelPages()) { try { CmsNewResourceInfo info = createNewResourceInfo(cms, modelConfig.getResource(), locale); info.setDefault(modelConfig.isDefault()); result.add(info); } catch (CmsException e) { LOG.debug(e.getLocalizedMessage(), e); } } Collections.sort(result, new Comparator<CmsNewResourceInfo>() { public int compare(CmsNewResourceInfo a, CmsNewResourceInfo b) { return ComparisonChain.start().compareTrueFirst(a.isDefault(), b.isDefault()).compare( a.getNavPos(), b.getNavPos(), Ordering.natural().nullsLast()).result(); } }); return result; }
java
private List<CmsNewResourceInfo> getNewResourceInfos(CmsObject cms, CmsADEConfigData configData, Locale locale) { List<CmsNewResourceInfo> result = new ArrayList<CmsNewResourceInfo>(); for (CmsModelPageConfig modelConfig : configData.getModelPages()) { try { CmsNewResourceInfo info = createNewResourceInfo(cms, modelConfig.getResource(), locale); info.setDefault(modelConfig.isDefault()); result.add(info); } catch (CmsException e) { LOG.debug(e.getLocalizedMessage(), e); } } Collections.sort(result, new Comparator<CmsNewResourceInfo>() { public int compare(CmsNewResourceInfo a, CmsNewResourceInfo b) { return ComparisonChain.start().compareTrueFirst(a.isDefault(), b.isDefault()).compare( a.getNavPos(), b.getNavPos(), Ordering.natural().nullsLast()).result(); } }); return result; }
[ "private", "List", "<", "CmsNewResourceInfo", ">", "getNewResourceInfos", "(", "CmsObject", "cms", ",", "CmsADEConfigData", "configData", ",", "Locale", "locale", ")", "{", "List", "<", "CmsNewResourceInfo", ">", "result", "=", "new", "ArrayList", "<", "CmsNewReso...
Returns the new resource infos.<p> @param cms the current CMS context @param configData the configuration data from which the new resource infos should be read @param locale locale used for retrieving descriptions/titles @return the new resource infos
[ "Returns", "the", "new", "resource", "infos", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsVfsSitemapService.java#L2441-L2464
prestodb/presto
presto-orc/src/main/java/com/facebook/presto/orc/writer/DictionaryBuilder.java
DictionaryBuilder.getHashPositionOfElement
private long getHashPositionOfElement(Block block, int position) { checkArgument(!block.isNull(position), "position is null"); int length = block.getSliceLength(position); long hashPosition = getMaskedHash(block.hash(position, 0, length)); while (true) { int blockPosition = blockPositionByHash.get(hashPosition); if (blockPosition == EMPTY_SLOT) { // Doesn't have this element return hashPosition; } else if (elementBlock.getSliceLength(blockPosition) == length && block.equals(position, 0, elementBlock, blockPosition, 0, length)) { // Already has this element return hashPosition; } hashPosition = getMaskedHash(hashPosition + 1); } }
java
private long getHashPositionOfElement(Block block, int position) { checkArgument(!block.isNull(position), "position is null"); int length = block.getSliceLength(position); long hashPosition = getMaskedHash(block.hash(position, 0, length)); while (true) { int blockPosition = blockPositionByHash.get(hashPosition); if (blockPosition == EMPTY_SLOT) { // Doesn't have this element return hashPosition; } else if (elementBlock.getSliceLength(blockPosition) == length && block.equals(position, 0, elementBlock, blockPosition, 0, length)) { // Already has this element return hashPosition; } hashPosition = getMaskedHash(hashPosition + 1); } }
[ "private", "long", "getHashPositionOfElement", "(", "Block", "block", ",", "int", "position", ")", "{", "checkArgument", "(", "!", "block", ".", "isNull", "(", "position", ")", ",", "\"position is null\"", ")", ";", "int", "length", "=", "block", ".", "getSl...
Get slot position of element at {@code position} of {@code block}
[ "Get", "slot", "position", "of", "element", "at", "{" ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-orc/src/main/java/com/facebook/presto/orc/writer/DictionaryBuilder.java#L140-L158
marklogic/marklogic-sesame
marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/MarkLogicRepositoryConnection.java
MarkLogicRepositoryConnection.prepareUpdate
@Override public MarkLogicUpdateQuery prepareUpdate(String queryString,String baseURI) throws RepositoryException, MalformedQueryException { return prepareUpdate(QueryLanguage.SPARQL, queryString, baseURI); }
java
@Override public MarkLogicUpdateQuery prepareUpdate(String queryString,String baseURI) throws RepositoryException, MalformedQueryException { return prepareUpdate(QueryLanguage.SPARQL, queryString, baseURI); }
[ "@", "Override", "public", "MarkLogicUpdateQuery", "prepareUpdate", "(", "String", "queryString", ",", "String", "baseURI", ")", "throws", "RepositoryException", ",", "MalformedQueryException", "{", "return", "prepareUpdate", "(", "QueryLanguage", ".", "SPARQL", ",", ...
overload for prepareUpdate @param queryString @param baseURI @return MarkLogicUpdateQuery @throws RepositoryException @throws MalformedQueryException
[ "overload", "for", "prepareUpdate" ]
train
https://github.com/marklogic/marklogic-sesame/blob/d5b668ed2b3d5e90c9f1d5096012813c272062a2/marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/MarkLogicRepositoryConnection.java#L416-L419
DiUS/pact-jvm
pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java
PactDslJsonArray.matchUrl
public PactDslJsonArray matchUrl(String basePath, Object... pathFragments) { UrlMatcherSupport urlMatcher = new UrlMatcherSupport(basePath, Arrays.asList(pathFragments)); body.put(urlMatcher.getExampleValue()); matchers.addRule(rootPath + appendArrayIndex(0), regexp(urlMatcher.getRegexExpression())); return this; }
java
public PactDslJsonArray matchUrl(String basePath, Object... pathFragments) { UrlMatcherSupport urlMatcher = new UrlMatcherSupport(basePath, Arrays.asList(pathFragments)); body.put(urlMatcher.getExampleValue()); matchers.addRule(rootPath + appendArrayIndex(0), regexp(urlMatcher.getRegexExpression())); return this; }
[ "public", "PactDslJsonArray", "matchUrl", "(", "String", "basePath", ",", "Object", "...", "pathFragments", ")", "{", "UrlMatcherSupport", "urlMatcher", "=", "new", "UrlMatcherSupport", "(", "basePath", ",", "Arrays", ".", "asList", "(", "pathFragments", ")", ")",...
Matches a URL that is composed of a base path and a sequence of path expressions @param basePath The base path for the URL (like "http://localhost:8080/") which will be excluded from the matching @param pathFragments Series of path fragments to match on. These can be strings or regular expressions.
[ "Matches", "a", "URL", "that", "is", "composed", "of", "a", "base", "path", "and", "a", "sequence", "of", "path", "expressions" ]
train
https://github.com/DiUS/pact-jvm/blob/2f447e9dd4ac152a6a36b7fcf8962d07de9ef3ef/pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java#L1156-L1161
DiUS/pact-jvm
pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslRequestWithPath.java
PactDslRequestWithPath.matchQuery
public PactDslRequestWithPath matchQuery(String parameter, String regex) { return matchQuery(parameter, regex, new Generex(regex).random()); }
java
public PactDslRequestWithPath matchQuery(String parameter, String regex) { return matchQuery(parameter, regex, new Generex(regex).random()); }
[ "public", "PactDslRequestWithPath", "matchQuery", "(", "String", "parameter", ",", "String", "regex", ")", "{", "return", "matchQuery", "(", "parameter", ",", "regex", ",", "new", "Generex", "(", "regex", ")", ".", "random", "(", ")", ")", ";", "}" ]
Match a query parameter with a regex. A random query parameter value will be generated from the regex. @param parameter Query parameter @param regex Regular expression to match with
[ "Match", "a", "query", "parameter", "with", "a", "regex", ".", "A", "random", "query", "parameter", "value", "will", "be", "generated", "from", "the", "regex", "." ]
train
https://github.com/DiUS/pact-jvm/blob/2f447e9dd4ac152a6a36b7fcf8962d07de9ef3ef/pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslRequestWithPath.java#L365-L367
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/support/BasePool.java
BasePool.unknownStackTrace
static <T extends Throwable> T unknownStackTrace(T cause, Class<?> clazz, String method) { cause.setStackTrace(new StackTraceElement[] { new StackTraceElement(clazz.getName(), method, null, -1) }); return cause; }
java
static <T extends Throwable> T unknownStackTrace(T cause, Class<?> clazz, String method) { cause.setStackTrace(new StackTraceElement[] { new StackTraceElement(clazz.getName(), method, null, -1) }); return cause; }
[ "static", "<", "T", "extends", "Throwable", ">", "T", "unknownStackTrace", "(", "T", "cause", ",", "Class", "<", "?", ">", "clazz", ",", "String", "method", ")", "{", "cause", ".", "setStackTrace", "(", "new", "StackTraceElement", "[", "]", "{", "new", ...
Set the {@link StackTraceElement} for the given {@link Throwable}, using the {@link Class} and method name.
[ "Set", "the", "{" ]
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/support/BasePool.java#L83-L86
google/closure-compiler
src/com/google/javascript/jscomp/PassConfig.java
PassConfig.regenerateGlobalTypedScope
void regenerateGlobalTypedScope(AbstractCompiler compiler, Node root) { typedScopeCreator = new TypedScopeCreator(compiler); topScope = typedScopeCreator.createScope(root, null); }
java
void regenerateGlobalTypedScope(AbstractCompiler compiler, Node root) { typedScopeCreator = new TypedScopeCreator(compiler); topScope = typedScopeCreator.createScope(root, null); }
[ "void", "regenerateGlobalTypedScope", "(", "AbstractCompiler", "compiler", ",", "Node", "root", ")", "{", "typedScopeCreator", "=", "new", "TypedScopeCreator", "(", "compiler", ")", ";", "topScope", "=", "typedScopeCreator", ".", "createScope", "(", "root", ",", "...
Regenerates the top scope from scratch. @param compiler The compiler for which the global scope is regenerated. @param root The root of the AST.
[ "Regenerates", "the", "top", "scope", "from", "scratch", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PassConfig.java#L53-L56
JOML-CI/JOML
src/org/joml/Quaterniond.java
Quaterniond.fromAxisAngleRad
public Quaterniond fromAxisAngleRad(Vector3dc axis, double angle) { return fromAxisAngleRad(axis.x(), axis.y(), axis.z(), angle); }
java
public Quaterniond fromAxisAngleRad(Vector3dc axis, double angle) { return fromAxisAngleRad(axis.x(), axis.y(), axis.z(), angle); }
[ "public", "Quaterniond", "fromAxisAngleRad", "(", "Vector3dc", "axis", ",", "double", "angle", ")", "{", "return", "fromAxisAngleRad", "(", "axis", ".", "x", "(", ")", ",", "axis", ".", "y", "(", ")", ",", "axis", ".", "z", "(", ")", ",", "angle", ")...
Set this quaternion to be a representation of the supplied axis and angle (in radians). @param axis the rotation axis @param angle the angle in radians @return this
[ "Set", "this", "quaternion", "to", "be", "a", "representation", "of", "the", "supplied", "axis", "and", "angle", "(", "in", "radians", ")", "." ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaterniond.java#L647-L649
apache/flink
flink-core/src/main/java/org/apache/flink/util/ExceptionUtils.java
ExceptionUtils.tryDeserializeAndThrow
public static void tryDeserializeAndThrow(Throwable throwable, ClassLoader classLoader) throws Throwable { Throwable current = throwable; while (!(current instanceof SerializedThrowable) && current.getCause() != null) { current = current.getCause(); } if (current instanceof SerializedThrowable) { throw ((SerializedThrowable) current).deserializeError(classLoader); } else { throw throwable; } }
java
public static void tryDeserializeAndThrow(Throwable throwable, ClassLoader classLoader) throws Throwable { Throwable current = throwable; while (!(current instanceof SerializedThrowable) && current.getCause() != null) { current = current.getCause(); } if (current instanceof SerializedThrowable) { throw ((SerializedThrowable) current).deserializeError(classLoader); } else { throw throwable; } }
[ "public", "static", "void", "tryDeserializeAndThrow", "(", "Throwable", "throwable", ",", "ClassLoader", "classLoader", ")", "throws", "Throwable", "{", "Throwable", "current", "=", "throwable", ";", "while", "(", "!", "(", "current", "instanceof", "SerializedThrowa...
Tries to find a {@link SerializedThrowable} as the cause of the given throwable and throws its deserialized value. If there is no such throwable, then the original throwable is thrown. @param throwable to check for a SerializedThrowable @param classLoader to be used for the deserialization of the SerializedThrowable @throws Throwable either the deserialized throwable or the given throwable
[ "Tries", "to", "find", "a", "{", "@link", "SerializedThrowable", "}", "as", "the", "cause", "of", "the", "given", "throwable", "and", "throws", "its", "deserialized", "value", ".", "If", "there", "is", "no", "such", "throwable", "then", "the", "original", ...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/ExceptionUtils.java#L435-L447
openskynetwork/java-adsb
src/main/java/org/opensky/libadsb/msgs/AltitudeReply.java
AltitudeReply.grayToBin
private static int grayToBin(int gray, int bitlength) { int result = 0; for (int i = bitlength-1; i >= 0; --i) result = result|((((0x1<<(i+1))&result)>>>1)^((1<<i)&gray)); return result; }
java
private static int grayToBin(int gray, int bitlength) { int result = 0; for (int i = bitlength-1; i >= 0; --i) result = result|((((0x1<<(i+1))&result)>>>1)^((1<<i)&gray)); return result; }
[ "private", "static", "int", "grayToBin", "(", "int", "gray", ",", "int", "bitlength", ")", "{", "int", "result", "=", "0", ";", "for", "(", "int", "i", "=", "bitlength", "-", "1", ";", "i", ">=", "0", ";", "--", "i", ")", "result", "=", "result",...
This method converts a gray code encoded int to a standard decimal int @param gray gray code encoded int of length bitlength bitlength bitlength of gray code @return radix 2 encoded integer
[ "This", "method", "converts", "a", "gray", "code", "encoded", "int", "to", "a", "standard", "decimal", "int" ]
train
https://github.com/openskynetwork/java-adsb/blob/01d497d3e74ad10063ab443ab583e9c8653a8b8d/src/main/java/org/opensky/libadsb/msgs/AltitudeReply.java#L187-L192
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/RolesInner.java
RolesInner.listByDataBoxEdgeDeviceAsync
public Observable<Page<RoleInner>> listByDataBoxEdgeDeviceAsync(final String deviceName, final String resourceGroupName) { return listByDataBoxEdgeDeviceWithServiceResponseAsync(deviceName, resourceGroupName) .map(new Func1<ServiceResponse<Page<RoleInner>>, Page<RoleInner>>() { @Override public Page<RoleInner> call(ServiceResponse<Page<RoleInner>> response) { return response.body(); } }); }
java
public Observable<Page<RoleInner>> listByDataBoxEdgeDeviceAsync(final String deviceName, final String resourceGroupName) { return listByDataBoxEdgeDeviceWithServiceResponseAsync(deviceName, resourceGroupName) .map(new Func1<ServiceResponse<Page<RoleInner>>, Page<RoleInner>>() { @Override public Page<RoleInner> call(ServiceResponse<Page<RoleInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "RoleInner", ">", ">", "listByDataBoxEdgeDeviceAsync", "(", "final", "String", "deviceName", ",", "final", "String", "resourceGroupName", ")", "{", "return", "listByDataBoxEdgeDeviceWithServiceResponseAsync", "(", "deviceName", ...
Lists all the roles configured in a data box edge/gateway device. @param deviceName The device name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;RoleInner&gt; object
[ "Lists", "all", "the", "roles", "configured", "in", "a", "data", "box", "edge", "/", "gateway", "device", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/RolesInner.java#L143-L151
m-m-m/util
lang/src/main/java/net/sf/mmm/util/lang/api/ComparatorHelper.java
ComparatorHelper.evalComparable
@SuppressWarnings({ "rawtypes", "unchecked" }) static boolean evalComparable(CompareOperator comparator, Comparable arg1, Comparable arg2) { Class<?> type1 = arg1.getClass(); Class<?> type2 = arg2.getClass(); int delta; if (type1.equals(type2) || type1.isAssignableFrom(type2)) { delta = signum(arg1.compareTo(arg2)); } else if (type2.isAssignableFrom(type1)) { delta = -signum(arg2.compareTo(arg1)); } else { // incompatible comparables return (arg1.equals(arg2) == comparator.isTrueIfEquals()); } return comparator.eval(delta); }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) static boolean evalComparable(CompareOperator comparator, Comparable arg1, Comparable arg2) { Class<?> type1 = arg1.getClass(); Class<?> type2 = arg2.getClass(); int delta; if (type1.equals(type2) || type1.isAssignableFrom(type2)) { delta = signum(arg1.compareTo(arg2)); } else if (type2.isAssignableFrom(type1)) { delta = -signum(arg2.compareTo(arg1)); } else { // incompatible comparables return (arg1.equals(arg2) == comparator.isTrueIfEquals()); } return comparator.eval(delta); }
[ "@", "SuppressWarnings", "(", "{", "\"rawtypes\"", ",", "\"unchecked\"", "}", ")", "static", "boolean", "evalComparable", "(", "CompareOperator", "comparator", ",", "Comparable", "arg1", ",", "Comparable", "arg2", ")", "{", "Class", "<", "?", ">", "type1", "="...
Logic for {@link CompareOperator#eval(Object, Object)} with {@link Comparable} arguments. @param comparator is the {@link CompareOperator}. @param arg1 is the first argument. @param arg2 is the second argument. @return the result of the {@link CompareOperator} applied to the given arguments.
[ "Logic", "for", "{", "@link", "CompareOperator#eval", "(", "Object", "Object", ")", "}", "with", "{", "@link", "Comparable", "}", "arguments", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/lang/src/main/java/net/sf/mmm/util/lang/api/ComparatorHelper.java#L68-L83
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/classify/LinearClassifierFactory.java
LinearClassifierFactory.crossValidateSetSigma
public void crossValidateSetSigma(GeneralDataset<L, F> dataset,int kfold) { System.err.println("##you are here."); crossValidateSetSigma(dataset, kfold, new MultiClassAccuracyStats<L>(MultiClassAccuracyStats.USE_LOGLIKELIHOOD), new GoldenSectionLineSearch(true, 1e-2, min, max)); }
java
public void crossValidateSetSigma(GeneralDataset<L, F> dataset,int kfold) { System.err.println("##you are here."); crossValidateSetSigma(dataset, kfold, new MultiClassAccuracyStats<L>(MultiClassAccuracyStats.USE_LOGLIKELIHOOD), new GoldenSectionLineSearch(true, 1e-2, min, max)); }
[ "public", "void", "crossValidateSetSigma", "(", "GeneralDataset", "<", "L", ",", "F", ">", "dataset", ",", "int", "kfold", ")", "{", "System", ".", "err", ".", "println", "(", "\"##you are here.\"", ")", ";", "crossValidateSetSigma", "(", "dataset", ",", "kf...
callls the method {@link #crossValidateSetSigma(GeneralDataset, int, Scorer, LineSearcher)} with multi-class log-likelihood scoring (see {@link MultiClassAccuracyStats}) and golden-section line search (see {@link GoldenSectionLineSearch}). @param dataset the data set to optimize sigma on.
[ "callls", "the", "method", "{" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/classify/LinearClassifierFactory.java#L546-L549
drewwills/cernunnos
cernunnos-core/src/main/java/org/danann/cernunnos/runtime/ScriptRunner.java
ScriptRunner.run
public TaskResponse run(String location, TaskRequest req) { // Assertions. if (location == null) { String msg = "Argument 'location' cannot be null."; throw new IllegalArgumentException(msg); } return run(compileTask(location), req); }
java
public TaskResponse run(String location, TaskRequest req) { // Assertions. if (location == null) { String msg = "Argument 'location' cannot be null."; throw new IllegalArgumentException(msg); } return run(compileTask(location), req); }
[ "public", "TaskResponse", "run", "(", "String", "location", ",", "TaskRequest", "req", ")", "{", "// Assertions.", "if", "(", "location", "==", "null", ")", "{", "String", "msg", "=", "\"Argument 'location' cannot be null.\"", ";", "throw", "new", "IllegalArgument...
Invokes the script found at the specified location (file system or URL). @param location A file on the file system or a URL. @param req A <code>TaskRequest</code> prepared externally. @return The <code>TaskResponse</code> that results from invoking the specified script.
[ "Invokes", "the", "script", "found", "at", "the", "specified", "location", "(", "file", "system", "or", "URL", ")", "." ]
train
https://github.com/drewwills/cernunnos/blob/dc6848e0253775e22b6c869fd06506d4ddb6d728/cernunnos-core/src/main/java/org/danann/cernunnos/runtime/ScriptRunner.java#L150-L160
mnlipp/jgrapes
org.jgrapes.http/src/org/jgrapes/http/HttpConnector.java
HttpConnector.onOutput
@Handler public void onOutput(Output<?> event, WebAppMsgChannel appChannel) throws InterruptedException { appChannel.handleAppOutput(event); }
java
@Handler public void onOutput(Output<?> event, WebAppMsgChannel appChannel) throws InterruptedException { appChannel.handleAppOutput(event); }
[ "@", "Handler", "public", "void", "onOutput", "(", "Output", "<", "?", ">", "event", ",", "WebAppMsgChannel", "appChannel", ")", "throws", "InterruptedException", "{", "appChannel", ".", "handleAppOutput", "(", "event", ")", ";", "}" ]
Handles output from the application. This may be the payload of e.g. a POST or data to be transferes on a websocket connection. @param event the event @param appChannel the application layer channel @throws InterruptedException the interrupted exception
[ "Handles", "output", "from", "the", "application", ".", "This", "may", "be", "the", "payload", "of", "e", ".", "g", ".", "a", "POST", "or", "data", "to", "be", "transferes", "on", "a", "websocket", "connection", "." ]
train
https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/HttpConnector.java#L155-L159
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/tools/HttpTools.java
HttpTools.deleteRequest
public String deleteRequest(final URL url) throws MovieDbException { try { HttpDelete httpDel = new HttpDelete(url.toURI()); return validateResponse(DigestedResponseReader.deleteContent(httpClient, httpDel, CHARSET), url); } catch (URISyntaxException | IOException ex) { throw new MovieDbException(ApiExceptionType.CONNECTION_ERROR, null, url, ex); } }
java
public String deleteRequest(final URL url) throws MovieDbException { try { HttpDelete httpDel = new HttpDelete(url.toURI()); return validateResponse(DigestedResponseReader.deleteContent(httpClient, httpDel, CHARSET), url); } catch (URISyntaxException | IOException ex) { throw new MovieDbException(ApiExceptionType.CONNECTION_ERROR, null, url, ex); } }
[ "public", "String", "deleteRequest", "(", "final", "URL", "url", ")", "throws", "MovieDbException", "{", "try", "{", "HttpDelete", "httpDel", "=", "new", "HttpDelete", "(", "url", ".", "toURI", "(", ")", ")", ";", "return", "validateResponse", "(", "Digested...
Execute a DELETE on the URL @param url URL to use in the request @return String content @throws MovieDbException exception
[ "Execute", "a", "DELETE", "on", "the", "URL" ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/tools/HttpTools.java#L110-L117
Drivemode/TypefaceHelper
TypefaceHelper/src/main/java/com/drivemode/android/typeface/TypefaceHelper.java
TypefaceHelper.setTypeface
public void setTypeface(Paint paint, @StringRes int strResId) { setTypeface(paint, mApplication.getString(strResId)); }
java
public void setTypeface(Paint paint, @StringRes int strResId) { setTypeface(paint, mApplication.getString(strResId)); }
[ "public", "void", "setTypeface", "(", "Paint", "paint", ",", "@", "StringRes", "int", "strResId", ")", "{", "setTypeface", "(", "paint", ",", "mApplication", ".", "getString", "(", "strResId", ")", ")", ";", "}" ]
Set the typeface to the target paint. @param paint the set typeface. @param strResId string resource containing typeface name.
[ "Set", "the", "typeface", "to", "the", "target", "paint", "." ]
train
https://github.com/Drivemode/TypefaceHelper/blob/86bef9ce16b9626b7076559e846db1b9f043c008/TypefaceHelper/src/main/java/com/drivemode/android/typeface/TypefaceHelper.java#L205-L207
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.moveResource
public void moveResource(CmsRequestContext context, CmsResource source, String destination) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); // checking if the destination folder exists and is not marked as deleted readResource(context, CmsResource.getParentFolder(destination), CmsResourceFilter.IGNORE_EXPIRATION); checkPermissions(dbc, source, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); checkPermissions(dbc, source, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); checkSystemLocks(dbc, source); // check write permissions for subresources in case of moving a folder if (source.isFolder()) { dbc.getRequestContext().setAttribute(I_CmsVfsDriver.REQ_ATTR_CHECK_PERMISSIONS, Boolean.TRUE); try { m_driverManager.getVfsDriver( dbc).moveResource(dbc, dbc.currentProject().getUuid(), source, destination); } catch (CmsDataAccessException e) { // unwrap the permission violation exception if (e.getCause() instanceof CmsPermissionViolationException) { throw (CmsPermissionViolationException)e.getCause(); } else { throw e; } } dbc.getRequestContext().removeAttribute(I_CmsVfsDriver.REQ_ATTR_CHECK_PERMISSIONS); } moveResource(dbc, source, destination); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_MOVE_RESOURCE_2, dbc.removeSiteRoot(source.getRootPath()), dbc.removeSiteRoot(destination)), e); } finally { dbc.clear(); } }
java
public void moveResource(CmsRequestContext context, CmsResource source, String destination) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); // checking if the destination folder exists and is not marked as deleted readResource(context, CmsResource.getParentFolder(destination), CmsResourceFilter.IGNORE_EXPIRATION); checkPermissions(dbc, source, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); checkPermissions(dbc, source, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); checkSystemLocks(dbc, source); // check write permissions for subresources in case of moving a folder if (source.isFolder()) { dbc.getRequestContext().setAttribute(I_CmsVfsDriver.REQ_ATTR_CHECK_PERMISSIONS, Boolean.TRUE); try { m_driverManager.getVfsDriver( dbc).moveResource(dbc, dbc.currentProject().getUuid(), source, destination); } catch (CmsDataAccessException e) { // unwrap the permission violation exception if (e.getCause() instanceof CmsPermissionViolationException) { throw (CmsPermissionViolationException)e.getCause(); } else { throw e; } } dbc.getRequestContext().removeAttribute(I_CmsVfsDriver.REQ_ATTR_CHECK_PERMISSIONS); } moveResource(dbc, source, destination); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_MOVE_RESOURCE_2, dbc.removeSiteRoot(source.getRootPath()), dbc.removeSiteRoot(destination)), e); } finally { dbc.clear(); } }
[ "public", "void", "moveResource", "(", "CmsRequestContext", "context", ",", "CmsResource", "source", ",", "String", "destination", ")", "throws", "CmsException", ",", "CmsSecurityException", "{", "CmsDbContext", "dbc", "=", "m_dbContextFactory", ".", "getDbContext", "...
Moves a resource.<p> You must ensure that the destination path is an absolute, valid and existing VFS path. Relative paths from the source are currently not supported.<p> The moved resource will always be locked to the current user after the move operation.<p> In case the target resource already exists, it is overwritten with the source resource.<p> @param context the current request context @param source the resource to copy @param destination the name of the copy destination with complete path @throws CmsException if something goes wrong @throws CmsSecurityException if resource could not be copied @see CmsObject#moveResource(String, String) @see org.opencms.file.types.I_CmsResourceType#moveResource(CmsObject, CmsSecurityManager, CmsResource, String)
[ "Moves", "a", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L3749-L3790
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java
ApiOvhHostingweb.serviceName_cdn_serviceInfosUpdate_POST
public void serviceName_cdn_serviceInfosUpdate_POST(String serviceName, OvhRenewType renew) throws IOException { String qPath = "/hosting/web/{serviceName}/cdn/serviceInfosUpdate"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "renew", renew); exec(qPath, "POST", sb.toString(), o); }
java
public void serviceName_cdn_serviceInfosUpdate_POST(String serviceName, OvhRenewType renew) throws IOException { String qPath = "/hosting/web/{serviceName}/cdn/serviceInfosUpdate"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "renew", renew); exec(qPath, "POST", sb.toString(), o); }
[ "public", "void", "serviceName_cdn_serviceInfosUpdate_POST", "(", "String", "serviceName", ",", "OvhRenewType", "renew", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/hosting/web/{serviceName}/cdn/serviceInfosUpdate\"", ";", "StringBuilder", "sb", "=", "pat...
Alter this object properties REST: POST /hosting/web/{serviceName}/cdn/serviceInfosUpdate @param renew [required] Renew type @param serviceName [required] The internal name of your hosting
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java#L1494-L1500
mapsforge/mapsforge
sqlite-android/src/main/java/org/sqlite/database/sqlite/SQLiteProgram.java
SQLiteProgram.bindBlob
public void bindBlob(int index, byte[] value) { if (value == null) { throw new IllegalArgumentException("the bind value at index " + index + " is null"); } bind(index, value); }
java
public void bindBlob(int index, byte[] value) { if (value == null) { throw new IllegalArgumentException("the bind value at index " + index + " is null"); } bind(index, value); }
[ "public", "void", "bindBlob", "(", "int", "index", ",", "byte", "[", "]", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"the bind value at index \"", "+", "index", "+", "\" is null\"", ")", ...
Bind a byte array value to this statement. The value remains bound until {@link #clearBindings} is called. @param index The 1-based index to the parameter to bind @param value The value to bind, must not be null
[ "Bind", "a", "byte", "array", "value", "to", "this", "statement", ".", "The", "value", "remains", "bound", "until", "{", "@link", "#clearBindings", "}", "is", "called", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/sqlite-android/src/main/java/org/sqlite/database/sqlite/SQLiteProgram.java#L180-L185
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/sampling/SimpleRandomSampling.java
SimpleRandomSampling.pbarVariance
public static double pbarVariance(double pbar, int sampleN, int populationN) { if(populationN<=0 || sampleN<=0 || sampleN>populationN) { throw new IllegalArgumentException("All the parameters must be positive and sampleN smaller than populationN."); } double f = (double)sampleN/populationN; double pbarVariance=((1.0 - f)*pbar*(1.0 - pbar))/(sampleN-1.0); return pbarVariance; }
java
public static double pbarVariance(double pbar, int sampleN, int populationN) { if(populationN<=0 || sampleN<=0 || sampleN>populationN) { throw new IllegalArgumentException("All the parameters must be positive and sampleN smaller than populationN."); } double f = (double)sampleN/populationN; double pbarVariance=((1.0 - f)*pbar*(1.0 - pbar))/(sampleN-1.0); return pbarVariance; }
[ "public", "static", "double", "pbarVariance", "(", "double", "pbar", ",", "int", "sampleN", ",", "int", "populationN", ")", "{", "if", "(", "populationN", "<=", "0", "||", "sampleN", "<=", "0", "||", "sampleN", ">", "populationN", ")", "{", "throw", "new...
Calculates Variance for Pbar for a finite population size @param pbar @param sampleN @param populationN @return
[ "Calculates", "Variance", "for", "Pbar", "for", "a", "finite", "population", "size" ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/sampling/SimpleRandomSampling.java#L213-L221
FXMisc/RichTextFX
richtextfx/src/main/java/org/fxmisc/richtext/util/UndoUtils.java
UndoUtils.plainTextUndoManager
public static <PS, SEG, S> UndoManager<List<PlainTextChange>> plainTextUndoManager( GenericStyledArea<PS, SEG, S> area) { return plainTextUndoManager(area, DEFAULT_PREVENT_MERGE_DELAY); }
java
public static <PS, SEG, S> UndoManager<List<PlainTextChange>> plainTextUndoManager( GenericStyledArea<PS, SEG, S> area) { return plainTextUndoManager(area, DEFAULT_PREVENT_MERGE_DELAY); }
[ "public", "static", "<", "PS", ",", "SEG", ",", "S", ">", "UndoManager", "<", "List", "<", "PlainTextChange", ">", ">", "plainTextUndoManager", "(", "GenericStyledArea", "<", "PS", ",", "SEG", ",", "S", ">", "area", ")", "{", "return", "plainTextUndoManage...
Returns an UndoManager with an unlimited history that can undo/redo {@link PlainTextChange}s. New changes emitted from the stream will not be merged with the previous change after {@link #DEFAULT_PREVENT_MERGE_DELAY}
[ "Returns", "an", "UndoManager", "with", "an", "unlimited", "history", "that", "can", "undo", "/", "redo", "{" ]
train
https://github.com/FXMisc/RichTextFX/blob/bc7cab6a637855e0f37d9b9c12a9172c31545f0b/richtextfx/src/main/java/org/fxmisc/richtext/util/UndoUtils.java#L96-L99
ThreeTen/threeten-extra
src/main/java/org/threeten/extra/chrono/AccountingDate.java
AccountingDate.now
public static AccountingDate now(AccountingChronology chronology, Clock clock) { LocalDate now = LocalDate.now(clock); return ofEpochDay(chronology, now.toEpochDay()); }
java
public static AccountingDate now(AccountingChronology chronology, Clock clock) { LocalDate now = LocalDate.now(clock); return ofEpochDay(chronology, now.toEpochDay()); }
[ "public", "static", "AccountingDate", "now", "(", "AccountingChronology", "chronology", ",", "Clock", "clock", ")", "{", "LocalDate", "now", "=", "LocalDate", ".", "now", "(", "clock", ")", ";", "return", "ofEpochDay", "(", "chronology", ",", "now", ".", "to...
Obtains the current {@code AccountingDate} from the specified clock, translated with the given AccountingChronology. <p> This will query the specified clock to obtain the current date - today. Using this method allows the use of an alternate clock for testing. The alternate clock may be introduced using {@linkplain Clock dependency injection}. @param chronology the Accounting chronology to base the date on, not null @param clock the clock to use, not null @return the current date, not null @throws DateTimeException if the current date cannot be obtained, NullPointerException if an AccountingChronology was not provided
[ "Obtains", "the", "current", "{", "@code", "AccountingDate", "}", "from", "the", "specified", "clock", "translated", "with", "the", "given", "AccountingChronology", ".", "<p", ">", "This", "will", "query", "the", "specified", "clock", "to", "obtain", "the", "c...
train
https://github.com/ThreeTen/threeten-extra/blob/e94ecd3592ef70e54d6eea21095239ea9ffbab78/src/main/java/org/threeten/extra/chrono/AccountingDate.java#L164-L167
Impetus/Kundera
src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/ethereum/EtherObjectConverterUtil.java
EtherObjectConverterUtil.convertEtherBlockToKunderaBlock
public static Block convertEtherBlockToKunderaBlock(EthBlock block, boolean includeTransactions) { Block kunderaBlk = new Block(); org.web3j.protocol.core.methods.response.EthBlock.Block blk = block.getBlock(); kunderaBlk.setAuthor(blk.getAuthor()); kunderaBlk.setDifficulty(blk.getDifficultyRaw()); kunderaBlk.setExtraData(blk.getExtraData()); kunderaBlk.setGasLimit(blk.getGasLimitRaw()); kunderaBlk.setGasUsed(blk.getGasUsedRaw()); kunderaBlk.setHash(blk.getHash()); kunderaBlk.setLogsBloom(blk.getLogsBloom()); kunderaBlk.setMiner(blk.getMiner()); kunderaBlk.setMixHash(blk.getMixHash()); kunderaBlk.setNonce(blk.getNonceRaw()); kunderaBlk.setNumber(blk.getNumberRaw()); kunderaBlk.setParentHash(blk.getParentHash()); kunderaBlk.setReceiptsRoot(blk.getReceiptsRoot()); kunderaBlk.setSealFields(blk.getSealFields()); kunderaBlk.setSha3Uncles(blk.getSha3Uncles()); kunderaBlk.setSize(blk.getSizeRaw()); kunderaBlk.setStateRoot(blk.getStateRoot()); kunderaBlk.setTimestamp(blk.getTimestampRaw()); kunderaBlk.setTotalDifficulty(blk.getTotalDifficultyRaw()); kunderaBlk.setTransactionsRoot(blk.getTransactionsRoot()); kunderaBlk.setUncles(blk.getUncles()); if (includeTransactions) { List<Transaction> kunderaTxs = new ArrayList<>(); List<TransactionResult> txResults = block.getBlock().getTransactions(); if (txResults != null && !txResults.isEmpty()) { for (TransactionResult transactionResult : txResults) { kunderaTxs.add(convertEtherTxToKunderaTx(transactionResult)); } kunderaBlk.setTransactions(kunderaTxs); } } return kunderaBlk; }
java
public static Block convertEtherBlockToKunderaBlock(EthBlock block, boolean includeTransactions) { Block kunderaBlk = new Block(); org.web3j.protocol.core.methods.response.EthBlock.Block blk = block.getBlock(); kunderaBlk.setAuthor(blk.getAuthor()); kunderaBlk.setDifficulty(blk.getDifficultyRaw()); kunderaBlk.setExtraData(blk.getExtraData()); kunderaBlk.setGasLimit(blk.getGasLimitRaw()); kunderaBlk.setGasUsed(blk.getGasUsedRaw()); kunderaBlk.setHash(blk.getHash()); kunderaBlk.setLogsBloom(blk.getLogsBloom()); kunderaBlk.setMiner(blk.getMiner()); kunderaBlk.setMixHash(blk.getMixHash()); kunderaBlk.setNonce(blk.getNonceRaw()); kunderaBlk.setNumber(blk.getNumberRaw()); kunderaBlk.setParentHash(blk.getParentHash()); kunderaBlk.setReceiptsRoot(blk.getReceiptsRoot()); kunderaBlk.setSealFields(blk.getSealFields()); kunderaBlk.setSha3Uncles(blk.getSha3Uncles()); kunderaBlk.setSize(blk.getSizeRaw()); kunderaBlk.setStateRoot(blk.getStateRoot()); kunderaBlk.setTimestamp(blk.getTimestampRaw()); kunderaBlk.setTotalDifficulty(blk.getTotalDifficultyRaw()); kunderaBlk.setTransactionsRoot(blk.getTransactionsRoot()); kunderaBlk.setUncles(blk.getUncles()); if (includeTransactions) { List<Transaction> kunderaTxs = new ArrayList<>(); List<TransactionResult> txResults = block.getBlock().getTransactions(); if (txResults != null && !txResults.isEmpty()) { for (TransactionResult transactionResult : txResults) { kunderaTxs.add(convertEtherTxToKunderaTx(transactionResult)); } kunderaBlk.setTransactions(kunderaTxs); } } return kunderaBlk; }
[ "public", "static", "Block", "convertEtherBlockToKunderaBlock", "(", "EthBlock", "block", ",", "boolean", "includeTransactions", ")", "{", "Block", "kunderaBlk", "=", "new", "Block", "(", ")", ";", "org", ".", "web3j", ".", "protocol", ".", "core", ".", "metho...
Convert ether block to kundera block. @param block the block @param includeTransactions the include transactions @return the block
[ "Convert", "ether", "block", "to", "kundera", "block", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/ethereum/EtherObjectConverterUtil.java#L64-L108
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/ProxiedFileSystemCache.java
ProxiedFileSystemCache.getProxiedFileSystem
@Builder(builderClassName = "ProxiedFileSystemFromProperties", builderMethodName = "fromProperties") private static FileSystem getProxiedFileSystem(@NonNull String userNameToProxyAs, Properties properties, URI fsURI, Configuration configuration, FileSystem referenceFS) throws IOException { Preconditions.checkNotNull(userNameToProxyAs, "Must provide a user name to proxy as."); Preconditions.checkNotNull(properties, "Properties is a mandatory field for proxiedFileSystem generation."); URI actualURI = resolveUri(fsURI, configuration, referenceFS); Configuration actualConfiguration = resolveConfiguration(configuration, referenceFS); try { return USER_NAME_TO_FILESYSTEM_CACHE.get(getFileSystemKey(actualURI, userNameToProxyAs, referenceFS), new CreateProxiedFileSystemFromProperties(userNameToProxyAs, properties, actualURI, actualConfiguration, referenceFS)); } catch (ExecutionException ee) { throw new IOException("Failed to get proxied file system for user " + userNameToProxyAs, ee); } }
java
@Builder(builderClassName = "ProxiedFileSystemFromProperties", builderMethodName = "fromProperties") private static FileSystem getProxiedFileSystem(@NonNull String userNameToProxyAs, Properties properties, URI fsURI, Configuration configuration, FileSystem referenceFS) throws IOException { Preconditions.checkNotNull(userNameToProxyAs, "Must provide a user name to proxy as."); Preconditions.checkNotNull(properties, "Properties is a mandatory field for proxiedFileSystem generation."); URI actualURI = resolveUri(fsURI, configuration, referenceFS); Configuration actualConfiguration = resolveConfiguration(configuration, referenceFS); try { return USER_NAME_TO_FILESYSTEM_CACHE.get(getFileSystemKey(actualURI, userNameToProxyAs, referenceFS), new CreateProxiedFileSystemFromProperties(userNameToProxyAs, properties, actualURI, actualConfiguration, referenceFS)); } catch (ExecutionException ee) { throw new IOException("Failed to get proxied file system for user " + userNameToProxyAs, ee); } }
[ "@", "Builder", "(", "builderClassName", "=", "\"ProxiedFileSystemFromProperties\"", ",", "builderMethodName", "=", "\"fromProperties\"", ")", "private", "static", "FileSystem", "getProxiedFileSystem", "(", "@", "NonNull", "String", "userNameToProxyAs", ",", "Properties", ...
Gets a {@link FileSystem} that can perform any operations allowed by the specified userNameToProxyAs. @param userNameToProxyAs The name of the user the super user should proxy as @param properties {@link java.util.Properties} containing initialization properties. @param fsURI The {@link URI} for the {@link FileSystem} that should be created. @param configuration The {@link Configuration} for the {@link FileSystem} that should be created. @param referenceFS reference {@link FileSystem}. Used to replicate certain decorators of the reference FS: {@link RateControlledFileSystem}. @return a {@link FileSystem} that can execute commands on behalf of the specified userNameToProxyAs @throws IOException
[ "Gets", "a", "{", "@link", "FileSystem", "}", "that", "can", "perform", "any", "operations", "allowed", "by", "the", "specified", "userNameToProxyAs", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ProxiedFileSystemCache.java#L125-L140
NordicSemiconductor/Android-DFU-Library
dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java
SecureDfuImpl.writeExecute
private void writeExecute() throws DfuException, DeviceDisconnectedException, UploadAbortedException, UnknownResponseException, RemoteDfuException { if (!mConnected) throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected"); writeOpCode(mControlPointCharacteristic, OP_CODE_EXECUTE); final byte[] response = readNotificationResponse(); final int status = getStatusCode(response, OP_CODE_EXECUTE_KEY); if (status == SecureDfuError.EXTENDED_ERROR) throw new RemoteDfuExtendedErrorException("Executing object failed", response[3]); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Executing object failed", status); }
java
private void writeExecute() throws DfuException, DeviceDisconnectedException, UploadAbortedException, UnknownResponseException, RemoteDfuException { if (!mConnected) throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected"); writeOpCode(mControlPointCharacteristic, OP_CODE_EXECUTE); final byte[] response = readNotificationResponse(); final int status = getStatusCode(response, OP_CODE_EXECUTE_KEY); if (status == SecureDfuError.EXTENDED_ERROR) throw new RemoteDfuExtendedErrorException("Executing object failed", response[3]); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Executing object failed", status); }
[ "private", "void", "writeExecute", "(", ")", "throws", "DfuException", ",", "DeviceDisconnectedException", ",", "UploadAbortedException", ",", "UnknownResponseException", ",", "RemoteDfuException", "{", "if", "(", "!", "mConnected", ")", "throw", "new", "DeviceDisconnec...
Sends the Execute operation code and awaits for a return notification containing status code. The Execute command will confirm the last chunk of data or the last command that was sent. Creating the same object again, instead of executing it allows to retransmitting it in case of a CRC error. @throws DfuException @throws DeviceDisconnectedException @throws UploadAbortedException @throws UnknownResponseException @throws RemoteDfuException thrown when the returned status code is not equal to {@link #DFU_STATUS_SUCCESS}.
[ "Sends", "the", "Execute", "operation", "code", "and", "awaits", "for", "a", "return", "notification", "containing", "status", "code", ".", "The", "Execute", "command", "will", "confirm", "the", "last", "chunk", "of", "data", "or", "the", "last", "command", ...
train
https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java#L903-L916
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/ObjectUtils.java
ObjectUtils.returnValueOrDefaultIfNull
public static <T> T returnValueOrDefaultIfNull(T value, Supplier<T> supplier) { return Optional.ofNullable(value).orElseGet(supplier); }
java
public static <T> T returnValueOrDefaultIfNull(T value, Supplier<T> supplier) { return Optional.ofNullable(value).orElseGet(supplier); }
[ "public", "static", "<", "T", ">", "T", "returnValueOrDefaultIfNull", "(", "T", "value", ",", "Supplier", "<", "T", ">", "supplier", ")", "{", "return", "Optional", ".", "ofNullable", "(", "value", ")", ".", "orElseGet", "(", "supplier", ")", ";", "}" ]
Returns the given {@code value} if not {@literal null} or call the given {@link Supplier} to supply a value. @param <T> {@link Class} type of the {@code value}. @param value {@link Object} to evaluate for {@literal null}. @param supplier {@link Supplier} used to supply a value if {@code value} is {@literal null}. @return the given {@code value} if not {@literal null} or call the given {@link Supplier} to supply a value. @see java.util.function.Supplier
[ "Returns", "the", "given", "{", "@code", "value", "}", "if", "not", "{", "@literal", "null", "}", "or", "call", "the", "given", "{", "@link", "Supplier", "}", "to", "supply", "a", "value", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ObjectUtils.java#L203-L205
infinispan/infinispan
commons/src/main/java/org/infinispan/commons/jmx/JmxUtil.java
JmxUtil.registerMBean
public static void registerMBean(Object mbean, ObjectName objectName, MBeanServer mBeanServer) throws Exception { if (!mBeanServer.isRegistered(objectName)) { try { SecurityActions.registerMBean(mbean, objectName, mBeanServer); log.tracef("Registered %s under %s", mbean, objectName); } catch (InstanceAlreadyExistsException e) { //this might happen if multiple instances are trying to concurrently register same objectName log.couldNotRegisterObjectName(objectName, e); } } else { log.debugf("Object name %s already registered", objectName); } }
java
public static void registerMBean(Object mbean, ObjectName objectName, MBeanServer mBeanServer) throws Exception { if (!mBeanServer.isRegistered(objectName)) { try { SecurityActions.registerMBean(mbean, objectName, mBeanServer); log.tracef("Registered %s under %s", mbean, objectName); } catch (InstanceAlreadyExistsException e) { //this might happen if multiple instances are trying to concurrently register same objectName log.couldNotRegisterObjectName(objectName, e); } } else { log.debugf("Object name %s already registered", objectName); } }
[ "public", "static", "void", "registerMBean", "(", "Object", "mbean", ",", "ObjectName", "objectName", ",", "MBeanServer", "mBeanServer", ")", "throws", "Exception", "{", "if", "(", "!", "mBeanServer", ".", "isRegistered", "(", "objectName", ")", ")", "{", "try...
Register the given dynamic JMX MBean. @param mbean Dynamic MBean to register @param objectName {@link ObjectName} under which to register the MBean. @param mBeanServer {@link MBeanServer} where to store the MBean. @throws Exception If registration could not be completed.
[ "Register", "the", "given", "dynamic", "JMX", "MBean", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/commons/src/main/java/org/infinispan/commons/jmx/JmxUtil.java#L59-L71
mapbox/mapbox-plugins-android
plugin-localization/src/main/java/com/mapbox/mapboxsdk/plugins/localization/LocalizationPlugin.java
LocalizationPlugin.setCameraToLocaleCountry
public void setCameraToLocaleCountry(MapLocale mapLocale, int padding) { LatLngBounds bounds = mapLocale.getCountryBounds(); if (bounds == null) { throw new NullPointerException("Expected a LatLngBounds object but received null instead. Mak" + "e sure your MapLocale instance also has a country bounding box defined."); } mapboxMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, padding)); }
java
public void setCameraToLocaleCountry(MapLocale mapLocale, int padding) { LatLngBounds bounds = mapLocale.getCountryBounds(); if (bounds == null) { throw new NullPointerException("Expected a LatLngBounds object but received null instead. Mak" + "e sure your MapLocale instance also has a country bounding box defined."); } mapboxMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, padding)); }
[ "public", "void", "setCameraToLocaleCountry", "(", "MapLocale", "mapLocale", ",", "int", "padding", ")", "{", "LatLngBounds", "bounds", "=", "mapLocale", ".", "getCountryBounds", "(", ")", ";", "if", "(", "bounds", "==", "null", ")", "{", "throw", "new", "Nu...
You can pass in a {@link MapLocale} directly into this method which uses the country bounds defined in it to represent the language found on the map. @param mapLocale the {@link MapLocale} object which contains the desired map bounds @param padding camera padding @since 0.1.0
[ "You", "can", "pass", "in", "a", "{", "@link", "MapLocale", "}", "directly", "into", "this", "method", "which", "uses", "the", "country", "bounds", "defined", "in", "it", "to", "represent", "the", "language", "found", "on", "the", "map", "." ]
train
https://github.com/mapbox/mapbox-plugins-android/blob/c683cad4d8306945d71838d96fae73b8cbe2e6c9/plugin-localization/src/main/java/com/mapbox/mapboxsdk/plugins/localization/LocalizationPlugin.java#L344-L351
threerings/gwt-utils
src/main/java/com/threerings/gwt/ui/SmartTable.java
SmartTable.removeStyleNames
public void removeStyleNames (int row, int column, String... styles) { for (String style : styles) { getFlexCellFormatter().removeStyleName(row, column, style); } }
java
public void removeStyleNames (int row, int column, String... styles) { for (String style : styles) { getFlexCellFormatter().removeStyleName(row, column, style); } }
[ "public", "void", "removeStyleNames", "(", "int", "row", ",", "int", "column", ",", "String", "...", "styles", ")", "{", "for", "(", "String", "style", ":", "styles", ")", "{", "getFlexCellFormatter", "(", ")", ".", "removeStyleName", "(", "row", ",", "c...
Removes the specified style names on the specified row and column.
[ "Removes", "the", "specified", "style", "names", "on", "the", "specified", "row", "and", "column", "." ]
train
https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/SmartTable.java#L362-L367
kirgor/enklib
rest/src/main/java/com/kirgor/enklib/rest/RESTClient.java
RESTClient.postWithListResult
public <T> EntityResponse<List<T>> postWithListResult(Class<T> entityClass, String path, Object payload, Map<String, String> headers) throws IOException, RESTException { return postWithListResultInternal(entityClass, payload, new HttpPost(baseUrl + path), headers); }
java
public <T> EntityResponse<List<T>> postWithListResult(Class<T> entityClass, String path, Object payload, Map<String, String> headers) throws IOException, RESTException { return postWithListResultInternal(entityClass, payload, new HttpPost(baseUrl + path), headers); }
[ "public", "<", "T", ">", "EntityResponse", "<", "List", "<", "T", ">", ">", "postWithListResult", "(", "Class", "<", "T", ">", "entityClass", ",", "String", "path", ",", "Object", "payload", ",", "Map", "<", "String", ",", "String", ">", "headers", ")"...
Performs POST request, while expected response entity is a list of specified type. @param entityClass Class, which contains expected response entity fields. @param path Request path. @param payload Entity, which will be used as request payload. @param headers Map of HTTP request headers. @param <T> Type of class, which contains expected response entity fields. @throws IOException If error during HTTP connection or entity parsing occurs. @throws RESTException If HTTP response code is non OK.
[ "Performs", "POST", "request", "while", "expected", "response", "entity", "is", "a", "list", "of", "specified", "type", "." ]
train
https://github.com/kirgor/enklib/blob/8a24db296dc43db5d8fe509cf64ace0a0c7be8f2/rest/src/main/java/com/kirgor/enklib/rest/RESTClient.java#L262-L264
aws/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/AWSS3V4Signer.java
AWSS3V4Signer.getContentLength
static long getContentLength(SignableRequest<?> request) throws IOException { final InputStream content = request.getContent(); if (!content.markSupported()) throw new IllegalStateException("Bug: request input stream must have been made mark-and-resettable at this point"); ReadLimitInfo info = request.getReadLimitInfo(); final int readLimit = info.getReadLimit(); long contentLength = 0; byte[] tmp = new byte[4096]; int read; content.mark(readLimit); while ((read = content.read(tmp)) != -1) { contentLength += read; } try { content.reset(); } catch(IOException ex) { throw new ResetException("Failed to reset the input stream", ex); } return contentLength; }
java
static long getContentLength(SignableRequest<?> request) throws IOException { final InputStream content = request.getContent(); if (!content.markSupported()) throw new IllegalStateException("Bug: request input stream must have been made mark-and-resettable at this point"); ReadLimitInfo info = request.getReadLimitInfo(); final int readLimit = info.getReadLimit(); long contentLength = 0; byte[] tmp = new byte[4096]; int read; content.mark(readLimit); while ((read = content.read(tmp)) != -1) { contentLength += read; } try { content.reset(); } catch(IOException ex) { throw new ResetException("Failed to reset the input stream", ex); } return contentLength; }
[ "static", "long", "getContentLength", "(", "SignableRequest", "<", "?", ">", "request", ")", "throws", "IOException", "{", "final", "InputStream", "content", "=", "request", ".", "getContent", "(", ")", ";", "if", "(", "!", "content", ".", "markSupported", "...
Read the content of the request to get the length of the stream. This method will wrap the stream by SdkBufferedInputStream if it is not mark-supported.
[ "Read", "the", "content", "of", "the", "request", "to", "get", "the", "length", "of", "the", "stream", ".", "This", "method", "will", "wrap", "the", "stream", "by", "SdkBufferedInputStream", "if", "it", "is", "not", "mark", "-", "supported", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/AWSS3V4Signer.java#L180-L199
Red5/red5-io
src/main/java/org/red5/compatibility/flex/messaging/io/ObjectProxy.java
ObjectProxy.put
@Override public V put(T name, V value) { return item.put(name, value); }
java
@Override public V put(T name, V value) { return item.put(name, value); }
[ "@", "Override", "public", "V", "put", "(", "T", "name", ",", "V", "value", ")", "{", "return", "item", ".", "put", "(", "name", ",", "value", ")", ";", "}" ]
Change a property of the proxied object. @param name name @param value value @return old value
[ "Change", "a", "property", "of", "the", "proxied", "object", "." ]
train
https://github.com/Red5/red5-io/blob/9bbbc506423c5a8f18169d46d400df56c0072a33/src/main/java/org/red5/compatibility/flex/messaging/io/ObjectProxy.java#L147-L150
noties/Handle
handle-library/src/main/java/ru/noties/handle/Handle.java
Handle.postDelayed
public static void postDelayed(Object what, long delay) { Handle.getInstance().mHandler.postDelayed(what, delay); }
java
public static void postDelayed(Object what, long delay) { Handle.getInstance().mHandler.postDelayed(what, delay); }
[ "public", "static", "void", "postDelayed", "(", "Object", "what", ",", "long", "delay", ")", "{", "Handle", ".", "getInstance", "(", ")", ".", "mHandler", ".", "postDelayed", "(", "what", ",", "delay", ")", ";", "}" ]
The same as {@link #post(Object)} but with a delay before delivering an event @see #post(Object) @param what an Object to be queued @param delay in milliseconds before delivery
[ "The", "same", "as", "{" ]
train
https://github.com/noties/Handle/blob/257c5e71334ce442b5c55b50bae6d5ae3a667ab9/handle-library/src/main/java/ru/noties/handle/Handle.java#L124-L126
taimos/dvalin
mongodb/src/main/java/de/taimos/dvalin/mongo/AbstractMongoDAO.java
AbstractMongoDAO.findFirstByQuery
protected final T findFirstByQuery(String query, String sort, Object... params) { return this.dataAccess.findFirstByQuery(query, sort, params).orElse(null); }
java
protected final T findFirstByQuery(String query, String sort, Object... params) { return this.dataAccess.findFirstByQuery(query, sort, params).orElse(null); }
[ "protected", "final", "T", "findFirstByQuery", "(", "String", "query", ",", "String", "sort", ",", "Object", "...", "params", ")", "{", "return", "this", ".", "dataAccess", ".", "findFirstByQuery", "(", "query", ",", "sort", ",", "params", ")", ".", "orEls...
queries with the given string, sorts the result and returns the first element. <code>null</code> is returned if no element is found. @param query the query string @param sort the sort string @param params the parameters to replace # symbols @return the first element found or <code>null</code> if none is found
[ "queries", "with", "the", "given", "string", "sorts", "the", "result", "and", "returns", "the", "first", "element", ".", "<code", ">", "null<", "/", "code", ">", "is", "returned", "if", "no", "element", "is", "found", "." ]
train
https://github.com/taimos/dvalin/blob/ff8f1bf594e43d7e8ca8de0b4da9f923b66a1a47/mongodb/src/main/java/de/taimos/dvalin/mongo/AbstractMongoDAO.java#L243-L245
wcm-io-caravan/caravan-commons
httpclient/src/main/java/io/wcm/caravan/commons/httpclient/impl/helpers/CertificateLoader.java
CertificateLoader.getKeyManagerFactory
private static KeyManagerFactory getKeyManagerFactory(InputStream keyStoreStream, StoreProperties storeProperties) throws IOException, GeneralSecurityException { // use provider if given, otherwise use the first matching security provider final KeyStore ks; if (StringUtils.isNotBlank(storeProperties.getProvider())) { ks = KeyStore.getInstance(storeProperties.getType(), storeProperties.getProvider()); } else { ks = KeyStore.getInstance(storeProperties.getType()); } ks.load(keyStoreStream, storeProperties.getPassword().toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(storeProperties.getManagerType()); kmf.init(ks, storeProperties.getPassword().toCharArray()); return kmf; }
java
private static KeyManagerFactory getKeyManagerFactory(InputStream keyStoreStream, StoreProperties storeProperties) throws IOException, GeneralSecurityException { // use provider if given, otherwise use the first matching security provider final KeyStore ks; if (StringUtils.isNotBlank(storeProperties.getProvider())) { ks = KeyStore.getInstance(storeProperties.getType(), storeProperties.getProvider()); } else { ks = KeyStore.getInstance(storeProperties.getType()); } ks.load(keyStoreStream, storeProperties.getPassword().toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(storeProperties.getManagerType()); kmf.init(ks, storeProperties.getPassword().toCharArray()); return kmf; }
[ "private", "static", "KeyManagerFactory", "getKeyManagerFactory", "(", "InputStream", "keyStoreStream", ",", "StoreProperties", "storeProperties", ")", "throws", "IOException", ",", "GeneralSecurityException", "{", "// use provider if given, otherwise use the first matching security ...
Get key manager factory @param keyStoreStream Keystore input stream @param storeProperties store properties @return Key manager factory @throws IOException @throws GeneralSecurityException
[ "Get", "key", "manager", "factory" ]
train
https://github.com/wcm-io-caravan/caravan-commons/blob/12e605bdfeb5a1ce7404e30d9f32274552cb8ce8/httpclient/src/main/java/io/wcm/caravan/commons/httpclient/impl/helpers/CertificateLoader.java#L140-L154
GwtMaterialDesign/gwt-material
gwt-material/src/main/java/gwt/material/design/client/ui/MaterialListValueBox.java
MaterialListValueBox.addItem
public void addItem(T value, Direction dir, String text) { addItem(value, dir, text, true); }
java
public void addItem(T value, Direction dir, String text) { addItem(value, dir, text, true); }
[ "public", "void", "addItem", "(", "T", "value", ",", "Direction", "dir", ",", "String", "text", ")", "{", "addItem", "(", "value", ",", "dir", ",", "text", ",", "true", ")", ";", "}" ]
Adds an item to the list box, specifying its direction and an initial value for the item. @param value the item's value, to be submitted if it is part of a {@link FormPanel}; cannot be <code>null</code> @param dir the item's direction @param text the text of the item to be added
[ "Adds", "an", "item", "to", "the", "list", "box", "specifying", "its", "direction", "and", "an", "initial", "value", "for", "the", "item", "." ]
train
https://github.com/GwtMaterialDesign/gwt-material/blob/86feefb282b007c0a44784c09e651a50f257138e/gwt-material/src/main/java/gwt/material/design/client/ui/MaterialListValueBox.java#L276-L278
ThreeTen/threetenbp
src/main/java/org/threeten/bp/jdk8/Jdk8Methods.java
Jdk8Methods.safeMultiply
public static int safeMultiply(int a, int b) { long total = (long) a * (long) b; if (total < Integer.MIN_VALUE || total > Integer.MAX_VALUE) { throw new ArithmeticException("Multiplication overflows an int: " + a + " * " + b); } return (int) total; }
java
public static int safeMultiply(int a, int b) { long total = (long) a * (long) b; if (total < Integer.MIN_VALUE || total > Integer.MAX_VALUE) { throw new ArithmeticException("Multiplication overflows an int: " + a + " * " + b); } return (int) total; }
[ "public", "static", "int", "safeMultiply", "(", "int", "a", ",", "int", "b", ")", "{", "long", "total", "=", "(", "long", ")", "a", "*", "(", "long", ")", "b", ";", "if", "(", "total", "<", "Integer", ".", "MIN_VALUE", "||", "total", ">", "Intege...
Safely multiply one int by another. @param a the first value @param b the second value @return the result @throws ArithmeticException if the result overflows an int
[ "Safely", "multiply", "one", "int", "by", "another", "." ]
train
https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/jdk8/Jdk8Methods.java#L215-L221
cdk/cdk
base/core/src/main/java/org/openscience/cdk/ringsearch/JumboCyclicVertexSearch.java
JumboCyclicVertexSearch.indexOfFused
private int indexOfFused(int start, BitSet cycle) { for (int i = start; i < cycles.size(); i++) { if (and(cycles.get(i), cycle).cardinality() > 1) { return i; } } return -1; }
java
private int indexOfFused(int start, BitSet cycle) { for (int i = start; i < cycles.size(); i++) { if (and(cycles.get(i), cycle).cardinality() > 1) { return i; } } return -1; }
[ "private", "int", "indexOfFused", "(", "int", "start", ",", "BitSet", "cycle", ")", "{", "for", "(", "int", "i", "=", "start", ";", "i", "<", "cycles", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "and", "(", "cycles", ".", "get"...
Find the next index that the <i>cycle</i> intersects with by at least two vertices. If the intersect of a vertex set with another contains more then two vertices it cannot be edge disjoint. @param start start searching from here @param cycle test whether any current cycles are fused with this one @return the index of the first fused after 'start', -1 if none
[ "Find", "the", "next", "index", "that", "the", "<i", ">", "cycle<", "/", "i", ">", "intersects", "with", "by", "at", "least", "two", "vertices", ".", "If", "the", "intersect", "of", "a", "vertex", "set", "with", "another", "contains", "more", "then", "...
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/core/src/main/java/org/openscience/cdk/ringsearch/JumboCyclicVertexSearch.java#L327-L334
line/centraldogma
server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java
MetadataService.findPermissions
public CompletableFuture<Collection<Permission>> findPermissions(String projectName, String repoName, String appId) { requireNonNull(projectName, "projectName"); requireNonNull(repoName, "repoName"); requireNonNull(appId, "appId"); return getProject(projectName).thenApply(metadata -> { final RepositoryMetadata repositoryMetadata = metadata.repo(repoName); final TokenRegistration registration = metadata.tokens().getOrDefault(appId, null); // If the token is guest. if (registration == null) { return repositoryMetadata.perRolePermissions().guest(); } final Collection<Permission> p = repositoryMetadata.perTokenPermissions().get(registration.id()); if (p != null) { return p; } return findPerRolePermissions(repositoryMetadata, registration.role()); }); }
java
public CompletableFuture<Collection<Permission>> findPermissions(String projectName, String repoName, String appId) { requireNonNull(projectName, "projectName"); requireNonNull(repoName, "repoName"); requireNonNull(appId, "appId"); return getProject(projectName).thenApply(metadata -> { final RepositoryMetadata repositoryMetadata = metadata.repo(repoName); final TokenRegistration registration = metadata.tokens().getOrDefault(appId, null); // If the token is guest. if (registration == null) { return repositoryMetadata.perRolePermissions().guest(); } final Collection<Permission> p = repositoryMetadata.perTokenPermissions().get(registration.id()); if (p != null) { return p; } return findPerRolePermissions(repositoryMetadata, registration.role()); }); }
[ "public", "CompletableFuture", "<", "Collection", "<", "Permission", ">", ">", "findPermissions", "(", "String", "projectName", ",", "String", "repoName", ",", "String", "appId", ")", "{", "requireNonNull", "(", "projectName", ",", "\"projectName\"", ")", ";", "...
Finds {@link Permission}s which belong to the specified {@code appId} from the specified {@code repoName} in the specified {@code projectName}.
[ "Finds", "{" ]
train
https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java#L602-L622
super-csv/super-csv
super-csv-joda/src/main/java/org/supercsv/cellprocessor/joda/FmtDateTimeZone.java
FmtDateTimeZone.execute
public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); if (!(value instanceof DateTimeZone)) { throw new SuperCsvCellProcessorException(DateTimeZone.class, value, context, this); } final DateTimeZone dateTimeZone = (DateTimeZone) value; final String result = dateTimeZone.toString(); return next.execute(result, context); }
java
public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); if (!(value instanceof DateTimeZone)) { throw new SuperCsvCellProcessorException(DateTimeZone.class, value, context, this); } final DateTimeZone dateTimeZone = (DateTimeZone) value; final String result = dateTimeZone.toString(); return next.execute(result, context); }
[ "public", "Object", "execute", "(", "final", "Object", "value", ",", "final", "CsvContext", "context", ")", "{", "validateInputNotNull", "(", "value", ",", "context", ")", ";", "if", "(", "!", "(", "value", "instanceof", "DateTimeZone", ")", ")", "{", "thr...
{@inheritDoc} @throws SuperCsvCellProcessorException if value is null or not a DateTimeZone
[ "{", "@inheritDoc", "}" ]
train
https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv-joda/src/main/java/org/supercsv/cellprocessor/joda/FmtDateTimeZone.java#L59-L68
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/PayloadNameRequestWrapper.java
PayloadNameRequestWrapper.parseSoapMethodName
private static String parseSoapMethodName(InputStream stream, String charEncoding) { try { // newInstance() et pas newFactory() pour java 1.5 (issue 367) final XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); // disable DTDs entirely for that factory factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); // disable external entities final XMLStreamReader xmlReader; if (charEncoding != null) { xmlReader = factory.createXMLStreamReader(stream, charEncoding); } else { xmlReader = factory.createXMLStreamReader(stream); } //best-effort parsing //start document, go to first tag xmlReader.nextTag(); //expect first tag to be "Envelope" if (!"Envelope".equals(xmlReader.getLocalName())) { LOG.debug("Unexpected first tag of SOAP request: '" + xmlReader.getLocalName() + "' (expected 'Envelope')"); return null; //failed } //scan for body tag if (!scanForChildTag(xmlReader, "Body")) { LOG.debug("Unable to find SOAP 'Body' tag"); return null; //failed } xmlReader.nextTag(); //tag is method name return "." + xmlReader.getLocalName(); } catch (final XMLStreamException e) { LOG.debug("Unable to parse SOAP request", e); //failed return null; } }
java
private static String parseSoapMethodName(InputStream stream, String charEncoding) { try { // newInstance() et pas newFactory() pour java 1.5 (issue 367) final XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); // disable DTDs entirely for that factory factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); // disable external entities final XMLStreamReader xmlReader; if (charEncoding != null) { xmlReader = factory.createXMLStreamReader(stream, charEncoding); } else { xmlReader = factory.createXMLStreamReader(stream); } //best-effort parsing //start document, go to first tag xmlReader.nextTag(); //expect first tag to be "Envelope" if (!"Envelope".equals(xmlReader.getLocalName())) { LOG.debug("Unexpected first tag of SOAP request: '" + xmlReader.getLocalName() + "' (expected 'Envelope')"); return null; //failed } //scan for body tag if (!scanForChildTag(xmlReader, "Body")) { LOG.debug("Unable to find SOAP 'Body' tag"); return null; //failed } xmlReader.nextTag(); //tag is method name return "." + xmlReader.getLocalName(); } catch (final XMLStreamException e) { LOG.debug("Unable to parse SOAP request", e); //failed return null; } }
[ "private", "static", "String", "parseSoapMethodName", "(", "InputStream", "stream", ",", "String", "charEncoding", ")", "{", "try", "{", "// newInstance() et pas newFactory() pour java 1.5 (issue 367)\r", "final", "XMLInputFactory", "factory", "=", "XMLInputFactory", ".", "...
Try to parse SOAP method name from request body stream. Does not close the stream. @param stream SOAP request body stream @nonnull @param charEncoding character encoding of stream, or null for platform default @null @return SOAP method name, or null if unable to parse @null
[ "Try", "to", "parse", "SOAP", "method", "name", "from", "request", "body", "stream", ".", "Does", "not", "close", "the", "stream", "." ]
train
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/PayloadNameRequestWrapper.java#L234-L274
bmwcarit/joynr
java/backend-services/domain-access-controller-jee/src/main/java/io/joynr/accesscontrol/global/jee/DomainRoleEntryManager.java
DomainRoleEntryManager.hasCurrentUserGotRoleForDomain
public boolean hasCurrentUserGotRoleForDomain(Role role, String domain) { try { DomainRoleEntryEntity domainRoleEntry = findByUserIdAndRole(joynrCallingPrincipal.getUsername(), role); return domainRoleEntry != null && domainRoleEntry.getDomains().contains(domain); } catch (ContextNotActiveException e) { logger.debug("No joynr message scope context active. Defaulting to 'true'."); } return true; }
java
public boolean hasCurrentUserGotRoleForDomain(Role role, String domain) { try { DomainRoleEntryEntity domainRoleEntry = findByUserIdAndRole(joynrCallingPrincipal.getUsername(), role); return domainRoleEntry != null && domainRoleEntry.getDomains().contains(domain); } catch (ContextNotActiveException e) { logger.debug("No joynr message scope context active. Defaulting to 'true'."); } return true; }
[ "public", "boolean", "hasCurrentUserGotRoleForDomain", "(", "Role", "role", ",", "String", "domain", ")", "{", "try", "{", "DomainRoleEntryEntity", "domainRoleEntry", "=", "findByUserIdAndRole", "(", "joynrCallingPrincipal", ".", "getUsername", "(", ")", ",", "role", ...
Determine whether the joynr calling principal, if available, has the given role for the given domain. The result will default to <code>true</code> if there is no current user - that is, the call is being made from without of a {@link io.joynr.jeeintegration.api.JoynrJeeMessageScoped joynr calling scope}. This way, the bean functionality can be used to create an admin API which doesn't require a user to be already available in the database, e.g. for initial creation of security settings or providing a RESTful API which is secured by other means. @param role the role the user should have. @param domain the domain for which the current user must have the role. @return <code>true</code> if there is a current user, and that user has the specified role in the given domain, <code>false</code> if there is a current user and they don't. <code>true</code> if there is no current user.
[ "Determine", "whether", "the", "joynr", "calling", "principal", "if", "available", "has", "the", "given", "role", "for", "the", "given", "domain", ".", "The", "result", "will", "default", "to", "<code", ">", "true<", "/", "code", ">", "if", "there", "is", ...
train
https://github.com/bmwcarit/joynr/blob/b7a92bad1cf2f093de080facd2c803560f4c6c26/java/backend-services/domain-access-controller-jee/src/main/java/io/joynr/accesscontrol/global/jee/DomainRoleEntryManager.java#L136-L144
mockito/mockito
src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java
InjectingAnnotationEngine.injectMocks
public void injectMocks(final Object testClassInstance) { Class<?> clazz = testClassInstance.getClass(); Set<Field> mockDependentFields = new HashSet<Field>(); Set<Object> mocks = newMockSafeHashSet(); while (clazz != Object.class) { new InjectMocksScanner(clazz).addTo(mockDependentFields); new MockScanner(testClassInstance, clazz).addPreparedMocks(mocks); onInjection(testClassInstance, clazz, mockDependentFields, mocks); clazz = clazz.getSuperclass(); } new DefaultInjectionEngine().injectMocksOnFields(mockDependentFields, mocks, testClassInstance); }
java
public void injectMocks(final Object testClassInstance) { Class<?> clazz = testClassInstance.getClass(); Set<Field> mockDependentFields = new HashSet<Field>(); Set<Object> mocks = newMockSafeHashSet(); while (clazz != Object.class) { new InjectMocksScanner(clazz).addTo(mockDependentFields); new MockScanner(testClassInstance, clazz).addPreparedMocks(mocks); onInjection(testClassInstance, clazz, mockDependentFields, mocks); clazz = clazz.getSuperclass(); } new DefaultInjectionEngine().injectMocksOnFields(mockDependentFields, mocks, testClassInstance); }
[ "public", "void", "injectMocks", "(", "final", "Object", "testClassInstance", ")", "{", "Class", "<", "?", ">", "clazz", "=", "testClassInstance", ".", "getClass", "(", ")", ";", "Set", "<", "Field", ">", "mockDependentFields", "=", "new", "HashSet", "<", ...
Initializes mock/spies dependencies for objects annotated with &#064;InjectMocks for given testClassInstance. <p> See examples in javadoc for {@link MockitoAnnotations} class. @param testClassInstance Test class, usually <code>this</code>
[ "Initializes", "mock", "/", "spies", "dependencies", "for", "objects", "annotated", "with", "&#064", ";", "InjectMocks", "for", "given", "testClassInstance", ".", "<p", ">", "See", "examples", "in", "javadoc", "for", "{", "@link", "MockitoAnnotations", "}", "cla...
train
https://github.com/mockito/mockito/blob/c5e2b80af76e3192cae7c9550b70c4d1ab312034/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java#L67-L80
ops4j/org.ops4j.pax.exam2
containers/pax-exam-container-karaf/src/main/java/org/ops4j/pax/exam/karaf/options/KarafDistributionOption.java
KarafDistributionOption.editConfigurationFileExtend
public static Option editConfigurationFileExtend(String configurationFilePath, String key, Object value) { return new KarafDistributionConfigurationFileExtendOption(configurationFilePath, key, value); }
java
public static Option editConfigurationFileExtend(String configurationFilePath, String key, Object value) { return new KarafDistributionConfigurationFileExtendOption(configurationFilePath, key, value); }
[ "public", "static", "Option", "editConfigurationFileExtend", "(", "String", "configurationFilePath", ",", "String", "key", ",", "Object", "value", ")", "{", "return", "new", "KarafDistributionConfigurationFileExtendOption", "(", "configurationFilePath", ",", "key", ",", ...
This option allows to extend configurations in each configuration file based on the karaf.home location. The value extends the current value (e.g. a=b to a=a,b) instead of replacing it. If there is no current value it is added. <p> If you would like to have add or replace functionality please use the {@link KarafDistributionConfigurationFilePutOption} instead. @param configurationFilePath configuration file path @param key property key @param value property value @return option
[ "This", "option", "allows", "to", "extend", "configurations", "in", "each", "configuration", "file", "based", "on", "the", "karaf", ".", "home", "location", ".", "The", "value", "extends", "the", "current", "value", "(", "e", ".", "g", ".", "a", "=", "b"...
train
https://github.com/ops4j/org.ops4j.pax.exam2/blob/7f83796cbbb857123d8fc7fe817a7637218d5d77/containers/pax-exam-container-karaf/src/main/java/org/ops4j/pax/exam/karaf/options/KarafDistributionOption.java#L256-L259
Netflix/netflix-commons
netflix-statistics/src/main/java/com/netflix/stats/distribution/DataBuffer.java
DataBuffer.getPercentiles
public double[] getPercentiles(double[] percents, double[] percentiles) { for (int i = 0; i < percents.length; i++) { percentiles[i] = computePercentile(percents[i]); } return percentiles; }
java
public double[] getPercentiles(double[] percents, double[] percentiles) { for (int i = 0; i < percents.length; i++) { percentiles[i] = computePercentile(percents[i]); } return percentiles; }
[ "public", "double", "[", "]", "getPercentiles", "(", "double", "[", "]", "percents", ",", "double", "[", "]", "percentiles", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "percents", ".", "length", ";", "i", "++", ")", "{", "percentile...
Gets the requested percentile statistics. @param percents array of percentile values to compute, which must be in the range {@code [0 .. 100]} @param percentiles array to fill in with the percentile values; must be the same length as {@code percents} @return the {@code percentiles} array @see <a href="http://en.wikipedia.org/wiki/Percentile">Percentile (Wikipedia)</a> @see <a href="http://cnx.org/content/m10805/latest/">Percentile</a>
[ "Gets", "the", "requested", "percentile", "statistics", "." ]
train
https://github.com/Netflix/netflix-commons/blob/7a158af76906d4a9b753e9344ce3e7abeb91dc01/netflix-statistics/src/main/java/com/netflix/stats/distribution/DataBuffer.java#L164-L169
arxanchain/java-common
src/main/java/com/arxanfintech/common/crypto/core/ECKey.java
ECKey.recoverPubBytesFromSignature
public static byte[] recoverPubBytesFromSignature(int recId, ECDSASignature sig, byte[] messageHash) { check(recId >= 0, "recId must be positive"); check(sig.r.signum() >= 0, "r must be positive"); check(sig.s.signum() >= 0, "s must be positive"); check(messageHash != null, "messageHash must not be null"); // 1.0 For j from 0 to h (h == recId here and the loop is outside this function) // 1.1 Let x = r + jn BigInteger n = CURVE.getN(); // Curve order. BigInteger i = BigInteger.valueOf((long) recId / 2); BigInteger x = sig.r.add(i.multiply(n)); // 1.2. Convert the integer x to an octet string X of length mlen using the // conversion routine // specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen = ⌈m/8⌉. // 1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve // point R using the // conversion routine specified in Section 2.3.4. If this conversion routine // outputs “invalid”, then // do another iteration of Step 1. // // More concisely, what these points mean is to use X as a compressed public // key. ECCurve.Fp curve = (ECCurve.Fp) CURVE.getCurve(); BigInteger prime = curve.getQ(); // Bouncy Castle is not consistent about the letter it uses for the prime. if (x.compareTo(prime) >= 0) { // Cannot have point co-ordinates larger than this as everything takes place // modulo Q. return null; } // Compressed keys require you to know an extra bit of data about the y-coord as // there are two possibilities. // So it's encoded in the recId. ECPoint R = decompressKey(x, (recId & 1) == 1); // 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers // responsibility). if (!R.multiply(n).isInfinity()) return null; // 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification. BigInteger e = new BigInteger(1, messageHash); // 1.6. For k from 1 to 2 do the following. (loop is outside this function via // iterating recId) // 1.6.1. Compute a candidate public key as: // Q = mi(r) * (sR - eG) // // Where mi(x) is the modular multiplicative inverse. We transform this into the // following: // Q = (mi(r) * s ** R) + (mi(r) * -e ** G) // Where -e is the modular additive inverse of e, that is z such that z + e = 0 // (mod n). In the above equation // ** is point multiplication and + is point addition (the EC group operator). // // We can find the additive inverse by subtracting e from zero then taking the // mod. For example the additive // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8. BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n); BigInteger rInv = sig.r.modInverse(n); BigInteger srInv = rInv.multiply(sig.s).mod(n); BigInteger eInvrInv = rInv.multiply(eInv).mod(n); ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv); return q.getEncoded(/* compressed */ false); }
java
public static byte[] recoverPubBytesFromSignature(int recId, ECDSASignature sig, byte[] messageHash) { check(recId >= 0, "recId must be positive"); check(sig.r.signum() >= 0, "r must be positive"); check(sig.s.signum() >= 0, "s must be positive"); check(messageHash != null, "messageHash must not be null"); // 1.0 For j from 0 to h (h == recId here and the loop is outside this function) // 1.1 Let x = r + jn BigInteger n = CURVE.getN(); // Curve order. BigInteger i = BigInteger.valueOf((long) recId / 2); BigInteger x = sig.r.add(i.multiply(n)); // 1.2. Convert the integer x to an octet string X of length mlen using the // conversion routine // specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen = ⌈m/8⌉. // 1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve // point R using the // conversion routine specified in Section 2.3.4. If this conversion routine // outputs “invalid”, then // do another iteration of Step 1. // // More concisely, what these points mean is to use X as a compressed public // key. ECCurve.Fp curve = (ECCurve.Fp) CURVE.getCurve(); BigInteger prime = curve.getQ(); // Bouncy Castle is not consistent about the letter it uses for the prime. if (x.compareTo(prime) >= 0) { // Cannot have point co-ordinates larger than this as everything takes place // modulo Q. return null; } // Compressed keys require you to know an extra bit of data about the y-coord as // there are two possibilities. // So it's encoded in the recId. ECPoint R = decompressKey(x, (recId & 1) == 1); // 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers // responsibility). if (!R.multiply(n).isInfinity()) return null; // 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification. BigInteger e = new BigInteger(1, messageHash); // 1.6. For k from 1 to 2 do the following. (loop is outside this function via // iterating recId) // 1.6.1. Compute a candidate public key as: // Q = mi(r) * (sR - eG) // // Where mi(x) is the modular multiplicative inverse. We transform this into the // following: // Q = (mi(r) * s ** R) + (mi(r) * -e ** G) // Where -e is the modular additive inverse of e, that is z such that z + e = 0 // (mod n). In the above equation // ** is point multiplication and + is point addition (the EC group operator). // // We can find the additive inverse by subtracting e from zero then taking the // mod. For example the additive // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8. BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n); BigInteger rInv = sig.r.modInverse(n); BigInteger srInv = rInv.multiply(sig.s).mod(n); BigInteger eInvrInv = rInv.multiply(eInv).mod(n); ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv); return q.getEncoded(/* compressed */ false); }
[ "public", "static", "byte", "[", "]", "recoverPubBytesFromSignature", "(", "int", "recId", ",", "ECDSASignature", "sig", ",", "byte", "[", "]", "messageHash", ")", "{", "check", "(", "recId", ">=", "0", ",", "\"recId must be positive\"", ")", ";", "check", "...
<p> Given the components of a signature and a selector value, recover and return the public key that generated the signature according to the algorithm in SEC1v2 section 4.1.6. </p> <p> The recId is an index from 0 to 3 which indicates which of the 4 possible keys is the correct one. Because the key recovery operation yields multiple potential keys, the correct key must either be stored alongside the signature, or you must be willing to try each recId in turn until you find one that outputs the key you are expecting. </p> <p> If this method returns null it means recovery was not possible and recId should be iterated. </p> <p> Given the above two points, a correct usage of this method is inside a for loop from 0 to 3, and if the output is null OR a key that is not the one you expect, you try again with the next recId. </p> @param recId Which possible key to recover. @param sig the R and S components of the signature, wrapped. @param messageHash Hash of the data that was signed. @return 65-byte encoded public key
[ "<p", ">", "Given", "the", "components", "of", "a", "signature", "and", "a", "selector", "value", "recover", "and", "return", "the", "public", "key", "that", "generated", "the", "signature", "according", "to", "the", "algorithm", "in", "SEC1v2", "section", "...
train
https://github.com/arxanchain/java-common/blob/3ddfedfd948f5bab3fee0b74b85cdce4702ed84e/src/main/java/com/arxanfintech/common/crypto/core/ECKey.java#L1135-L1194
marklogic/java-client-api
marklogic-client-api/src/main/java/com/marklogic/client/example/cookbook/datamovement/BulkLoadFromJdbcRaw.java
BulkLoadFromJdbcRaw.populateSalary
public void populateSalary(ResultSet row, ObjectNode s) throws SQLException { s.put("employeeId", row.getInt("emp_no")); s.put("salary", row.getInt("salary")); Calendar fromDate = Calendar.getInstance(); fromDate.setTime(row.getDate("from_date")); s.put("fromDate", dateFormat.format(fromDate.getTime())); Calendar toDate = Calendar.getInstance(); toDate.setTime(row.getDate("to_date")); s.put("toDate", dateFormat.format(toDate.getTime())); }
java
public void populateSalary(ResultSet row, ObjectNode s) throws SQLException { s.put("employeeId", row.getInt("emp_no")); s.put("salary", row.getInt("salary")); Calendar fromDate = Calendar.getInstance(); fromDate.setTime(row.getDate("from_date")); s.put("fromDate", dateFormat.format(fromDate.getTime())); Calendar toDate = Calendar.getInstance(); toDate.setTime(row.getDate("to_date")); s.put("toDate", dateFormat.format(toDate.getTime())); }
[ "public", "void", "populateSalary", "(", "ResultSet", "row", ",", "ObjectNode", "s", ")", "throws", "SQLException", "{", "s", ".", "put", "(", "\"employeeId\"", ",", "row", ".", "getInt", "(", "\"emp_no\"", ")", ")", ";", "s", ".", "put", "(", "\"salary\...
take data from a JDBC ResultSet (row) and populate an ObjectNode (JSON) object
[ "take", "data", "from", "a", "JDBC", "ResultSet", "(", "row", ")", "and", "populate", "an", "ObjectNode", "(", "JSON", ")", "object" ]
train
https://github.com/marklogic/java-client-api/blob/acf60229a928abd4a8cc4b21b641d56957467da7/marklogic-client-api/src/main/java/com/marklogic/client/example/cookbook/datamovement/BulkLoadFromJdbcRaw.java#L113-L122
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPSpecificationOptionPersistenceImpl.java
CPSpecificationOptionPersistenceImpl.fetchByUUID_G
@Override public CPSpecificationOption fetchByUUID_G(String uuid, long groupId) { return fetchByUUID_G(uuid, groupId, true); }
java
@Override public CPSpecificationOption fetchByUUID_G(String uuid, long groupId) { return fetchByUUID_G(uuid, groupId, true); }
[ "@", "Override", "public", "CPSpecificationOption", "fetchByUUID_G", "(", "String", "uuid", ",", "long", "groupId", ")", "{", "return", "fetchByUUID_G", "(", "uuid", ",", "groupId", ",", "true", ")", ";", "}" ]
Returns the cp specification option where uuid = &#63; and groupId = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache. @param uuid the uuid @param groupId the group ID @return the matching cp specification option, or <code>null</code> if a matching cp specification option could not be found
[ "Returns", "the", "cp", "specification", "option", "where", "uuid", "=", "&#63", ";", "and", "groupId", "=", "&#63", ";", "or", "returns", "<code", ">", "null<", "/", "code", ">", "if", "it", "could", "not", "be", "found", ".", "Uses", "the", "finder",...
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPSpecificationOptionPersistenceImpl.java#L706-L709
samskivert/samskivert
src/main/java/com/samskivert/swing/Controller.java
Controller.configureAction
public static void configureAction (AbstractButton button, String action) { button.setActionCommand(action); button.addActionListener(DISPATCHER); }
java
public static void configureAction (AbstractButton button, String action) { button.setActionCommand(action); button.addActionListener(DISPATCHER); }
[ "public", "static", "void", "configureAction", "(", "AbstractButton", "button", ",", "String", "action", ")", "{", "button", ".", "setActionCommand", "(", "action", ")", ";", "button", ".", "addActionListener", "(", "DISPATCHER", ")", ";", "}" ]
Configures the supplied button with the {@link #DISPATCHER} action listener and the specified action command (which, if it is a method name will be looked up dynamically on the matching controller).
[ "Configures", "the", "supplied", "button", "with", "the", "{" ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/Controller.java#L147-L151
moparisthebest/beehive
beehive-netui-tags/src/main/java/org/apache/beehive/netui/databinding/datagrid/api/DataGridStateFactory.java
DataGridStateFactory.getDataGridURLBuilder
public final DataGridURLBuilder getDataGridURLBuilder(String name, DataGridConfig config) { if(config == null) throw new IllegalArgumentException(Bundle.getErrorString("DataGridStateFactory_nullDataGridConfig")); DataGridStateCodec codec = lookupCodec(name, config); DataGridURLBuilder builder = codec.getDataGridURLBuilder(); return builder; }
java
public final DataGridURLBuilder getDataGridURLBuilder(String name, DataGridConfig config) { if(config == null) throw new IllegalArgumentException(Bundle.getErrorString("DataGridStateFactory_nullDataGridConfig")); DataGridStateCodec codec = lookupCodec(name, config); DataGridURLBuilder builder = codec.getDataGridURLBuilder(); return builder; }
[ "public", "final", "DataGridURLBuilder", "getDataGridURLBuilder", "(", "String", "name", ",", "DataGridConfig", "config", ")", "{", "if", "(", "config", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "Bundle", ".", "getErrorString", "(", "\"Da...
<p> Lookup a {@link DataGridURLBuilder} object given a data grid identifier and a specific {@link DataGridConfig} object. </p> @param name the name of the data grid @param config the {@link DataGridConfig} object to use when creating the grid's {@link DataGridURLBuilder} object. @return the URL builder for a data grid's state object
[ "<p", ">", "Lookup", "a", "{", "@link", "DataGridURLBuilder", "}", "object", "given", "a", "data", "grid", "identifier", "and", "a", "specific", "{", "@link", "DataGridConfig", "}", "object", ".", "<", "/", "p", ">" ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/databinding/datagrid/api/DataGridStateFactory.java#L153-L160
kiegroup/drools
kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/CompiledFEELSemanticMappings.java
CompiledFEELSemanticMappings.lt
public static Boolean lt(Object left, Object right) { return EvalHelper.compare(left, right, null, (l, r) -> l.compareTo(r) < 0); }
java
public static Boolean lt(Object left, Object right) { return EvalHelper.compare(left, right, null, (l, r) -> l.compareTo(r) < 0); }
[ "public", "static", "Boolean", "lt", "(", "Object", "left", ",", "Object", "right", ")", "{", "return", "EvalHelper", ".", "compare", "(", "left", ",", "right", ",", "null", ",", "(", "l", ",", "r", ")", "->", "l", ".", "compareTo", "(", "r", ")", ...
FEEL spec Table 42 and derivations Delegates to {@link EvalHelper} except evaluationcontext
[ "FEEL", "spec", "Table", "42", "and", "derivations", "Delegates", "to", "{" ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/CompiledFEELSemanticMappings.java#L348-L350
hibernate/hibernate-metamodelgen
src/main/java/org/hibernate/jpamodelgen/ClassWriter.java
ClassWriter.generateBody
private static StringBuffer generateBody(MetaEntity entity, Context context) { StringWriter sw = new StringWriter(); PrintWriter pw = null; try { pw = new PrintWriter( sw ); if ( context.addGeneratedAnnotation() ) { pw.println( writeGeneratedAnnotation( entity, context ) ); } if ( context.isAddSuppressWarningsAnnotation() ) { pw.println( writeSuppressWarnings() ); } pw.println( writeStaticMetaModelAnnotation( entity ) ); printClassDeclaration( entity, pw, context ); pw.println(); List<MetaAttribute> members = entity.getMembers(); for ( MetaAttribute metaMember : members ) { pw.println( " " + metaMember.getDeclarationString() ); } pw.println(); pw.println( "}" ); return sw.getBuffer(); } finally { if ( pw != null ) { pw.close(); } } }
java
private static StringBuffer generateBody(MetaEntity entity, Context context) { StringWriter sw = new StringWriter(); PrintWriter pw = null; try { pw = new PrintWriter( sw ); if ( context.addGeneratedAnnotation() ) { pw.println( writeGeneratedAnnotation( entity, context ) ); } if ( context.isAddSuppressWarningsAnnotation() ) { pw.println( writeSuppressWarnings() ); } pw.println( writeStaticMetaModelAnnotation( entity ) ); printClassDeclaration( entity, pw, context ); pw.println(); List<MetaAttribute> members = entity.getMembers(); for ( MetaAttribute metaMember : members ) { pw.println( " " + metaMember.getDeclarationString() ); } pw.println(); pw.println( "}" ); return sw.getBuffer(); } finally { if ( pw != null ) { pw.close(); } } }
[ "private", "static", "StringBuffer", "generateBody", "(", "MetaEntity", "entity", ",", "Context", "context", ")", "{", "StringWriter", "sw", "=", "new", "StringWriter", "(", ")", ";", "PrintWriter", "pw", "=", "null", ";", "try", "{", "pw", "=", "new", "Pr...
Generate everything after import statements. @param entity The meta entity for which to write the body @param context The processing context @return body content
[ "Generate", "everything", "after", "import", "statements", "." ]
train
https://github.com/hibernate/hibernate-metamodelgen/blob/2c87b262bc03b1a5a541789fc00c54e0531a36b2/src/main/java/org/hibernate/jpamodelgen/ClassWriter.java#L103-L136
sarl/sarl
main/externalmaven/io.sarl.maven.docs.generator/src/main/java/io/sarl/maven/docs/AbstractDocumentationMojo.java
AbstractDocumentationMojo.internalExecute
protected String internalExecute(Map<File, File> files, File outputFolder) { String firstErrorMessage = null; for (final Entry<File, File> entry : files.entrySet()) { final File inputFile = entry.getKey(); try { final AbstractMarkerLanguageParser parser = createLanguageParser(inputFile); final File sourceFolder = entry.getValue(); final File relativePath = FileSystem.makeRelative(inputFile, sourceFolder); internalExecute(sourceFolder, inputFile, relativePath, outputFolder, parser); } catch (Throwable exception) { final String errorMessage = formatErrorMessage(inputFile, exception); getLog().error(errorMessage); if (Strings.isEmpty(firstErrorMessage)) { firstErrorMessage = errorMessage; } getLog().debug(exception); } } return firstErrorMessage; }
java
protected String internalExecute(Map<File, File> files, File outputFolder) { String firstErrorMessage = null; for (final Entry<File, File> entry : files.entrySet()) { final File inputFile = entry.getKey(); try { final AbstractMarkerLanguageParser parser = createLanguageParser(inputFile); final File sourceFolder = entry.getValue(); final File relativePath = FileSystem.makeRelative(inputFile, sourceFolder); internalExecute(sourceFolder, inputFile, relativePath, outputFolder, parser); } catch (Throwable exception) { final String errorMessage = formatErrorMessage(inputFile, exception); getLog().error(errorMessage); if (Strings.isEmpty(firstErrorMessage)) { firstErrorMessage = errorMessage; } getLog().debug(exception); } } return firstErrorMessage; }
[ "protected", "String", "internalExecute", "(", "Map", "<", "File", ",", "File", ">", "files", ",", "File", "outputFolder", ")", "{", "String", "firstErrorMessage", "=", "null", ";", "for", "(", "final", "Entry", "<", "File", ",", "File", ">", "entry", ":...
Execute the mojo on the given set of files. @param files the files @param outputFolder the output directory. @return the error message
[ "Execute", "the", "mojo", "on", "the", "given", "set", "of", "files", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/externalmaven/io.sarl.maven.docs.generator/src/main/java/io/sarl/maven/docs/AbstractDocumentationMojo.java#L265-L285
looly/hutool
hutool-poi/src/main/java/cn/hutool/poi/excel/cell/CellUtil.java
CellUtil.getCellValue
public static Object getCellValue(Cell cell, CellEditor cellEditor) { if (null == cell) { return null; } return getCellValue(cell, cell.getCellTypeEnum(), cellEditor); }
java
public static Object getCellValue(Cell cell, CellEditor cellEditor) { if (null == cell) { return null; } return getCellValue(cell, cell.getCellTypeEnum(), cellEditor); }
[ "public", "static", "Object", "getCellValue", "(", "Cell", "cell", ",", "CellEditor", "cellEditor", ")", "{", "if", "(", "null", "==", "cell", ")", "{", "return", "null", ";", "}", "return", "getCellValue", "(", "cell", ",", "cell", ".", "getCellTypeEnum",...
获取单元格值 @param cell {@link Cell}单元格 @param cellEditor 单元格值编辑器。可以通过此编辑器对单元格值做自定义操作 @return 值,类型可能为:Date、Double、Boolean、String
[ "获取单元格值" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-poi/src/main/java/cn/hutool/poi/excel/cell/CellUtil.java#L50-L55
JOML-CI/JOML
src/org/joml/Quaternionf.java
Quaternionf.rotationAxis
public Quaternionf rotationAxis(AxisAngle4f axisAngle) { return rotationAxis(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z); }
java
public Quaternionf rotationAxis(AxisAngle4f axisAngle) { return rotationAxis(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z); }
[ "public", "Quaternionf", "rotationAxis", "(", "AxisAngle4f", "axisAngle", ")", "{", "return", "rotationAxis", "(", "axisAngle", ".", "angle", ",", "axisAngle", ".", "x", ",", "axisAngle", ".", "y", ",", "axisAngle", ".", "z", ")", ";", "}" ]
Set this {@link Quaternionf} to a rotation of the given angle in radians about the supplied axis, all of which are specified via the {@link AxisAngle4f}. @see #rotationAxis(float, float, float, float) @param axisAngle the {@link AxisAngle4f} giving the rotation angle in radians and the axis to rotate about @return this
[ "Set", "this", "{", "@link", "Quaternionf", "}", "to", "a", "rotation", "of", "the", "given", "angle", "in", "radians", "about", "the", "supplied", "axis", "all", "of", "which", "are", "specified", "via", "the", "{", "@link", "AxisAngle4f", "}", "." ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaternionf.java#L511-L513
fuinorg/srcgen4javassist
src/main/java/org/fuin/srcgen4javassist/SgUtils.java
SgUtils.concatPackages
public static String concatPackages(final String package1, final String package2) { if ((package1 == null) || (package1.length() == 0)) { if ((package2 == null) || (package2.length() == 0)) { return ""; } else { return package2; } } else { if ((package2 == null) || (package2.length() == 0)) { return package1; } else { return package1 + "." + package2; } } }
java
public static String concatPackages(final String package1, final String package2) { if ((package1 == null) || (package1.length() == 0)) { if ((package2 == null) || (package2.length() == 0)) { return ""; } else { return package2; } } else { if ((package2 == null) || (package2.length() == 0)) { return package1; } else { return package1 + "." + package2; } } }
[ "public", "static", "String", "concatPackages", "(", "final", "String", "package1", ",", "final", "String", "package2", ")", "{", "if", "(", "(", "package1", "==", "null", ")", "||", "(", "package1", ".", "length", "(", ")", "==", "0", ")", ")", "{", ...
Merge two packages into one. If any package is null or empty no "." will be added. If both packages are null an empty string will be returned. @param package1 First package - Can also be null or empty. @param package2 Second package - Can also be null or empty. @return Both packages added with ".".
[ "Merge", "two", "packages", "into", "one", ".", "If", "any", "package", "is", "null", "or", "empty", "no", ".", "will", "be", "added", ".", "If", "both", "packages", "are", "null", "an", "empty", "string", "will", "be", "returned", "." ]
train
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgUtils.java#L329-L343
greenjoe/sergeants
src/main/java/pl/joegreen/sergeants/simulator/SimulatorFactory.java
SimulatorFactory.createMapFromReplayFile
public static GameMap createMapFromReplayFile(String gioReplayFileLocation) { try { Replay replay = OBJECT_MAPPER.readValue(new File(gioReplayFileLocation), Replay.class); return createMapFromReplay(replay); } catch (IOException e) { throw new RuntimeException("Can not create game map from file: " + gioReplayFileLocation, e); } }
java
public static GameMap createMapFromReplayFile(String gioReplayFileLocation) { try { Replay replay = OBJECT_MAPPER.readValue(new File(gioReplayFileLocation), Replay.class); return createMapFromReplay(replay); } catch (IOException e) { throw new RuntimeException("Can not create game map from file: " + gioReplayFileLocation, e); } }
[ "public", "static", "GameMap", "createMapFromReplayFile", "(", "String", "gioReplayFileLocation", ")", "{", "try", "{", "Replay", "replay", "=", "OBJECT_MAPPER", ".", "readValue", "(", "new", "File", "(", "gioReplayFileLocation", ")", ",", "Replay", ".", "class", ...
GIOReplay files can be downloaded from http://dev.generals.io/replays @param gioReplayFileLocation file location @return a game map
[ "GIOReplay", "files", "can", "be", "downloaded", "from", "http", ":", "//", "dev", ".", "generals", ".", "io", "/", "replays" ]
train
https://github.com/greenjoe/sergeants/blob/db624bcea8597843210f138b82bc4a26b3ec92ca/src/main/java/pl/joegreen/sergeants/simulator/SimulatorFactory.java#L64-L71
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/ZipUtil.java
ZipUtil.addEntry
public static void addEntry(final File zip, final ZipEntrySource entry) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { addEntry(zip, entry, tmpFile); return true; } }); }
java
public static void addEntry(final File zip, final ZipEntrySource entry) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { addEntry(zip, entry, tmpFile); return true; } }); }
[ "public", "static", "void", "addEntry", "(", "final", "File", "zip", ",", "final", "ZipEntrySource", "entry", ")", "{", "operateInPlace", "(", "zip", ",", "new", "InPlaceAction", "(", ")", "{", "public", "boolean", "act", "(", "File", "tmpFile", ")", "{", ...
Changes a zip file, adds one new entry in-place. @param zip an existing ZIP file (only read). @param entry new ZIP entry appended.
[ "Changes", "a", "zip", "file", "adds", "one", "new", "entry", "in", "-", "place", "." ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L2145-L2152
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/GinjectorGenerator.java
GinjectorGenerator.createGinClassLoader
private ClassLoader createGinClassLoader(TreeLogger logger, GeneratorContext context) { Set<String> exceptions = new LinkedHashSet<String>(); exceptions.add("com.google.inject"); // Need the non-super-source version during generation. exceptions.add("javax.inject"); // Need the non-super-source version during generation. exceptions.add("com.google.gwt.inject.client"); // Excluded to allow class-literal comparison. // Required by GWT 2.8.0+ to prevent loading of GWT script only java.lang.JsException class // See: https://github.com/gwtproject/gwt/issues/9311 // See: https://github.com/gwtproject/gwt/commit/1d660d2fc00a5cbfeccf512251f78ab4302ab633 exceptions.add("com.google.gwt.core.client"); exceptions.add("com.google.gwt.core.client.impl"); // Add any excepted packages or classes registered by other developers. exceptions.addAll(getValuesForProperty("gin.classloading.exceptedPackages")); return new GinBridgeClassLoader(context, logger, exceptions); }
java
private ClassLoader createGinClassLoader(TreeLogger logger, GeneratorContext context) { Set<String> exceptions = new LinkedHashSet<String>(); exceptions.add("com.google.inject"); // Need the non-super-source version during generation. exceptions.add("javax.inject"); // Need the non-super-source version during generation. exceptions.add("com.google.gwt.inject.client"); // Excluded to allow class-literal comparison. // Required by GWT 2.8.0+ to prevent loading of GWT script only java.lang.JsException class // See: https://github.com/gwtproject/gwt/issues/9311 // See: https://github.com/gwtproject/gwt/commit/1d660d2fc00a5cbfeccf512251f78ab4302ab633 exceptions.add("com.google.gwt.core.client"); exceptions.add("com.google.gwt.core.client.impl"); // Add any excepted packages or classes registered by other developers. exceptions.addAll(getValuesForProperty("gin.classloading.exceptedPackages")); return new GinBridgeClassLoader(context, logger, exceptions); }
[ "private", "ClassLoader", "createGinClassLoader", "(", "TreeLogger", "logger", ",", "GeneratorContext", "context", ")", "{", "Set", "<", "String", ">", "exceptions", "=", "new", "LinkedHashSet", "<", "String", ">", "(", ")", ";", "exceptions", ".", "add", "(",...
Creates a new gin-specific class loader that will load GWT and non-GWT types such that there is never a conflict, especially with super source. @param logger logger for errors that occur during class loading @param context generator context in which classes are loaded @return new gin class loader @see GinBridgeClassLoader
[ "Creates", "a", "new", "gin", "-", "specific", "class", "loader", "that", "will", "load", "GWT", "and", "non", "-", "GWT", "types", "such", "that", "there", "is", "never", "a", "conflict", "especially", "with", "super", "source", "." ]
train
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/GinjectorGenerator.java#L86-L101
raphw/byte-buddy
byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/loading/ClassInjector.java
UsingLookup.of
public static UsingLookup of(Object lookup) { if (!DISPATCHER.isAlive()) { throw new IllegalStateException("The current VM does not support class definition via method handle lookups"); } else if (!JavaType.METHOD_HANDLES_LOOKUP.isInstance(lookup)) { throw new IllegalArgumentException("Not a method handle lookup: " + lookup); } else if ((DISPATCHER.lookupModes(lookup) & PACKAGE_LOOKUP) == 0) { throw new IllegalArgumentException("Lookup does not imply package-access: " + lookup); } return new UsingLookup(DISPATCHER.dropLookupMode(lookup, Opcodes.ACC_PRIVATE)); }
java
public static UsingLookup of(Object lookup) { if (!DISPATCHER.isAlive()) { throw new IllegalStateException("The current VM does not support class definition via method handle lookups"); } else if (!JavaType.METHOD_HANDLES_LOOKUP.isInstance(lookup)) { throw new IllegalArgumentException("Not a method handle lookup: " + lookup); } else if ((DISPATCHER.lookupModes(lookup) & PACKAGE_LOOKUP) == 0) { throw new IllegalArgumentException("Lookup does not imply package-access: " + lookup); } return new UsingLookup(DISPATCHER.dropLookupMode(lookup, Opcodes.ACC_PRIVATE)); }
[ "public", "static", "UsingLookup", "of", "(", "Object", "lookup", ")", "{", "if", "(", "!", "DISPATCHER", ".", "isAlive", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"The current VM does not support class definition via method handle lookups\"", ...
Creates class injector that defines a class using a method handle lookup. @param lookup The {@code java.lang.invoke.MethodHandles$Lookup} instance to use. @return An appropriate class injector.
[ "Creates", "class", "injector", "that", "defines", "a", "class", "using", "a", "method", "handle", "lookup", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/loading/ClassInjector.java#L1370-L1379
Azure/azure-sdk-for-java
sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ManagedDatabaseVulnerabilityAssessmentScansInner.java
ManagedDatabaseVulnerabilityAssessmentScansInner.getAsync
public Observable<VulnerabilityAssessmentScanRecordInner> getAsync(String resourceGroupName, String managedInstanceName, String databaseName, String scanId) { return getWithServiceResponseAsync(resourceGroupName, managedInstanceName, databaseName, scanId).map(new Func1<ServiceResponse<VulnerabilityAssessmentScanRecordInner>, VulnerabilityAssessmentScanRecordInner>() { @Override public VulnerabilityAssessmentScanRecordInner call(ServiceResponse<VulnerabilityAssessmentScanRecordInner> response) { return response.body(); } }); }
java
public Observable<VulnerabilityAssessmentScanRecordInner> getAsync(String resourceGroupName, String managedInstanceName, String databaseName, String scanId) { return getWithServiceResponseAsync(resourceGroupName, managedInstanceName, databaseName, scanId).map(new Func1<ServiceResponse<VulnerabilityAssessmentScanRecordInner>, VulnerabilityAssessmentScanRecordInner>() { @Override public VulnerabilityAssessmentScanRecordInner call(ServiceResponse<VulnerabilityAssessmentScanRecordInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "VulnerabilityAssessmentScanRecordInner", ">", "getAsync", "(", "String", "resourceGroupName", ",", "String", "managedInstanceName", ",", "String", "databaseName", ",", "String", "scanId", ")", "{", "return", "getWithServiceResponseAsync", "("...
Gets a vulnerability assessment scan record of a database. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param managedInstanceName The name of the managed instance. @param databaseName The name of the database. @param scanId The vulnerability assessment scan Id of the scan to retrieve. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the VulnerabilityAssessmentScanRecordInner object
[ "Gets", "a", "vulnerability", "assessment", "scan", "record", "of", "a", "database", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ManagedDatabaseVulnerabilityAssessmentScansInner.java#L260-L267
UrielCh/ovh-java-sdk
ovh-java-sdk-kube/src/main/java/net/minidev/ovh/api/ApiOvhKube.java
ApiOvhKube.serviceName_updatePolicy_PUT
public void serviceName_updatePolicy_PUT(String serviceName, OvhUpdatePolicy updatePolicy) throws IOException { String qPath = "/kube/{serviceName}/updatePolicy"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "updatePolicy", updatePolicy); exec(qPath, "PUT", sb.toString(), o); }
java
public void serviceName_updatePolicy_PUT(String serviceName, OvhUpdatePolicy updatePolicy) throws IOException { String qPath = "/kube/{serviceName}/updatePolicy"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "updatePolicy", updatePolicy); exec(qPath, "PUT", sb.toString(), o); }
[ "public", "void", "serviceName_updatePolicy_PUT", "(", "String", "serviceName", ",", "OvhUpdatePolicy", "updatePolicy", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/kube/{serviceName}/updatePolicy\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPat...
Change the update policy of your cluster REST: PUT /kube/{serviceName}/updatePolicy @param serviceName [required] Cluster ID @param updatePolicy [required] Update policy API beta
[ "Change", "the", "update", "policy", "of", "your", "cluster" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-kube/src/main/java/net/minidev/ovh/api/ApiOvhKube.java#L294-L300
liyiorg/weixin-popular
src/main/java/weixin/popular/api/ShakeAroundAPI.java
ShakeAroundAPI.deviceUpdate
public static DeviceUpdateResult deviceUpdate(String accessToken, DeviceUpdate deviceUpdate) { return deviceUpdate(accessToken, JsonUtil.toJSONString(deviceUpdate)); }
java
public static DeviceUpdateResult deviceUpdate(String accessToken, DeviceUpdate deviceUpdate) { return deviceUpdate(accessToken, JsonUtil.toJSONString(deviceUpdate)); }
[ "public", "static", "DeviceUpdateResult", "deviceUpdate", "(", "String", "accessToken", ",", "DeviceUpdate", "deviceUpdate", ")", "{", "return", "deviceUpdate", "(", "accessToken", ",", "JsonUtil", ".", "toJSONString", "(", "deviceUpdate", ")", ")", ";", "}" ]
编辑设备信息 @param accessToken accessToken @param deviceUpdate deviceUpdate @return result
[ "编辑设备信息" ]
train
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/ShakeAroundAPI.java#L538-L541
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java
SerializationUtils.fromByteArray
public static <T> T fromByteArray(byte[] data, Class<T> clazz) { return fromByteArray(data, clazz, null); }
java
public static <T> T fromByteArray(byte[] data, Class<T> clazz) { return fromByteArray(data, clazz, null); }
[ "public", "static", "<", "T", ">", "T", "fromByteArray", "(", "byte", "[", "]", "data", ",", "Class", "<", "T", ">", "clazz", ")", "{", "return", "fromByteArray", "(", "data", ",", "clazz", ",", "null", ")", ";", "}" ]
Deserialize a byte array back to an object. <p> If the target class implements {@link ISerializationSupport}, this method calls its {@link ISerializationSupport#toBytes()} method; otherwise FST library is used to serialize the object. </p> @param data @param clazz @return @deprecated since 0.9.2 with no replacement, use {@link #fromByteArrayFst(byte[], Class)} or {@link #fromByteArrayKryo(byte[], Class)}
[ "Deserialize", "a", "byte", "array", "back", "to", "an", "object", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java#L111-L113
lucee/Lucee
core/src/main/java/lucee/runtime/op/Caster.java
Caster.toDate
public static DateTime toDate(Object o, boolean alsoNumbers, TimeZone tz) throws PageException { return DateCaster.toDateAdvanced(o, alsoNumbers ? DateCaster.CONVERTING_TYPE_OFFSET : DateCaster.CONVERTING_TYPE_NONE, tz); }
java
public static DateTime toDate(Object o, boolean alsoNumbers, TimeZone tz) throws PageException { return DateCaster.toDateAdvanced(o, alsoNumbers ? DateCaster.CONVERTING_TYPE_OFFSET : DateCaster.CONVERTING_TYPE_NONE, tz); }
[ "public", "static", "DateTime", "toDate", "(", "Object", "o", ",", "boolean", "alsoNumbers", ",", "TimeZone", "tz", ")", "throws", "PageException", "{", "return", "DateCaster", ".", "toDateAdvanced", "(", "o", ",", "alsoNumbers", "?", "DateCaster", ".", "CONVE...
cast a Object to a DateTime Object @param o Object to cast @param alsoNumbers define if also numbers will casted to a datetime value @param tz @return casted DateTime Object @throws PageException
[ "cast", "a", "Object", "to", "a", "DateTime", "Object" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/op/Caster.java#L2898-L2900
omise/omise-java
src/main/java/co/omise/Serializer.java
Serializer.serializeParams
public <T extends Params> void serializeParams(OutputStream output, T param) throws IOException { // TODO: Add params-specific options. objectMapper.writerFor(param.getClass()).writeValue(output, param); }
java
public <T extends Params> void serializeParams(OutputStream output, T param) throws IOException { // TODO: Add params-specific options. objectMapper.writerFor(param.getClass()).writeValue(output, param); }
[ "public", "<", "T", "extends", "Params", ">", "void", "serializeParams", "(", "OutputStream", "output", ",", "T", "param", ")", "throws", "IOException", "{", "// TODO: Add params-specific options.", "objectMapper", ".", "writerFor", "(", "param", ".", "getClass", ...
Serializes the given parameter object to the output stream. @param output The {@link OutputStream} to serialize the parameter into. @param param The {@link Params} to serialize. @param <T> The type of the parameter object to serialize. @throws IOException on general I/O error.
[ "Serializes", "the", "given", "parameter", "object", "to", "the", "output", "stream", "." ]
train
https://github.com/omise/omise-java/blob/95aafc5e8c21b44e6d00a5a9080b9e353fe98042/src/main/java/co/omise/Serializer.java#L176-L179
crawljax/crawljax
core/src/main/java/com/crawljax/core/plugin/Plugins.java
Plugins.runPostCrawlingPlugins
public void runPostCrawlingPlugins(CrawlSession session, ExitStatus exitReason) { LOGGER.debug("Running PostCrawlingPlugins..."); counters.get(PostCrawlingPlugin.class).inc(); for (Plugin plugin : plugins.get(PostCrawlingPlugin.class)) { if (plugin instanceof PostCrawlingPlugin) { try { LOGGER.debug("Calling plugin {}", plugin); ((PostCrawlingPlugin) plugin).postCrawling(session, exitReason); } catch (RuntimeException e) { reportFailingPlugin(plugin, e); } } } }
java
public void runPostCrawlingPlugins(CrawlSession session, ExitStatus exitReason) { LOGGER.debug("Running PostCrawlingPlugins..."); counters.get(PostCrawlingPlugin.class).inc(); for (Plugin plugin : plugins.get(PostCrawlingPlugin.class)) { if (plugin instanceof PostCrawlingPlugin) { try { LOGGER.debug("Calling plugin {}", plugin); ((PostCrawlingPlugin) plugin).postCrawling(session, exitReason); } catch (RuntimeException e) { reportFailingPlugin(plugin, e); } } } }
[ "public", "void", "runPostCrawlingPlugins", "(", "CrawlSession", "session", ",", "ExitStatus", "exitReason", ")", "{", "LOGGER", ".", "debug", "(", "\"Running PostCrawlingPlugins...\"", ")", ";", "counters", ".", "get", "(", "PostCrawlingPlugin", ".", "class", ")", ...
load and run the postCrawlingPlugins. PostCrawlingPlugins are executed after the crawling is finished Warning: changing the session can change the behavior of other post crawl plugins. It is not a clone! @param exitReason The reason Crawljax has stopped. @param session the current {@link CrawlSession} for this crawler.
[ "load", "and", "run", "the", "postCrawlingPlugins", ".", "PostCrawlingPlugins", "are", "executed", "after", "the", "crawling", "is", "finished", "Warning", ":", "changing", "the", "session", "can", "change", "the", "behavior", "of", "other", "post", "crawl", "pl...
train
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/plugin/Plugins.java#L203-L217
alkacon/opencms-core
src/org/opencms/relations/CmsCategoryService.java
CmsCategoryService.clearCategoriesForResource
public void clearCategoriesForResource(CmsObject cms, String resourcePath) throws CmsException { CmsRelationFilter filter = CmsRelationFilter.TARGETS; filter = filter.filterType(CmsRelationType.CATEGORY); cms.deleteRelationsFromResource(resourcePath, filter); }
java
public void clearCategoriesForResource(CmsObject cms, String resourcePath) throws CmsException { CmsRelationFilter filter = CmsRelationFilter.TARGETS; filter = filter.filterType(CmsRelationType.CATEGORY); cms.deleteRelationsFromResource(resourcePath, filter); }
[ "public", "void", "clearCategoriesForResource", "(", "CmsObject", "cms", ",", "String", "resourcePath", ")", "throws", "CmsException", "{", "CmsRelationFilter", "filter", "=", "CmsRelationFilter", ".", "TARGETS", ";", "filter", "=", "filter", ".", "filterType", "(",...
Removes the given resource from all categories.<p> @param cms the cms context @param resourcePath the resource to reset the categories for @throws CmsException if something goes wrong
[ "Removes", "the", "given", "resource", "from", "all", "categories", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/relations/CmsCategoryService.java#L150-L155
jamesdbloom/mockserver
mockserver-core/src/main/java/org/mockserver/model/HttpResponse.java
HttpResponse.withBody
public HttpResponse withBody(String body, Charset charset) { if (body != null) { this.body = new StringBody(body, charset); } return this; }
java
public HttpResponse withBody(String body, Charset charset) { if (body != null) { this.body = new StringBody(body, charset); } return this; }
[ "public", "HttpResponse", "withBody", "(", "String", "body", ",", "Charset", "charset", ")", "{", "if", "(", "body", "!=", "null", ")", "{", "this", ".", "body", "=", "new", "StringBody", "(", "body", ",", "charset", ")", ";", "}", "return", "this", ...
Set response body to return a string response body with the specified encoding. <b>Note:</b> The character set of the response will be forced to the specified charset, even if the Content-Type header specifies otherwise. @param body a string @param charset character set the string will be encoded in
[ "Set", "response", "body", "to", "return", "a", "string", "response", "body", "with", "the", "specified", "encoding", ".", "<b", ">", "Note", ":", "<", "/", "b", ">", "The", "character", "set", "of", "the", "response", "will", "be", "forced", "to", "th...
train
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/model/HttpResponse.java#L100-L105
OpenLiberty/open-liberty
dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/ws/impl/WSJobOperatorImpl.java
WSJobOperatorImpl.createJobInstance
@Override public WSJobInstance createJobInstance(String appName, String jobXMLName, String jsl, String correlationId) { if (authService != null) { authService.authorizedJobSubmission(); } return batchKernelService.createJobInstance(appName, jobXMLName, batchSecurityHelper.getRunAsUser(), jsl, correlationId); }
java
@Override public WSJobInstance createJobInstance(String appName, String jobXMLName, String jsl, String correlationId) { if (authService != null) { authService.authorizedJobSubmission(); } return batchKernelService.createJobInstance(appName, jobXMLName, batchSecurityHelper.getRunAsUser(), jsl, correlationId); }
[ "@", "Override", "public", "WSJobInstance", "createJobInstance", "(", "String", "appName", ",", "String", "jobXMLName", ",", "String", "jsl", ",", "String", "correlationId", ")", "{", "if", "(", "authService", "!=", "null", ")", "{", "authService", ".", "autho...
@param appName @param jobXMLName @return newly created JobInstance (Note: job instance must be started separately) Note: Inline JSL takes precedence over JSL within .war
[ "@param", "appName", "@param", "jobXMLName" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/ws/impl/WSJobOperatorImpl.java#L156-L165
square/javapoet
src/main/java/com/squareup/javapoet/ParameterizedTypeName.java
ParameterizedTypeName.nestedClass
public ParameterizedTypeName nestedClass(String name) { checkNotNull(name, "name == null"); return new ParameterizedTypeName(this, rawType.nestedClass(name), new ArrayList<>(), new ArrayList<>()); }
java
public ParameterizedTypeName nestedClass(String name) { checkNotNull(name, "name == null"); return new ParameterizedTypeName(this, rawType.nestedClass(name), new ArrayList<>(), new ArrayList<>()); }
[ "public", "ParameterizedTypeName", "nestedClass", "(", "String", "name", ")", "{", "checkNotNull", "(", "name", ",", "\"name == null\"", ")", ";", "return", "new", "ParameterizedTypeName", "(", "this", ",", "rawType", ".", "nestedClass", "(", "name", ")", ",", ...
Returns a new {@link ParameterizedTypeName} instance for the specified {@code name} as nested inside this class.
[ "Returns", "a", "new", "{" ]
train
https://github.com/square/javapoet/blob/0f93da9a3d9a1da8d29fc993409fcf83d40452bc/src/main/java/com/squareup/javapoet/ParameterizedTypeName.java#L96-L100
groupon/odo
proxylib/src/main/java/com/groupon/odo/proxylib/ServerRedirectService.java
ServerRedirectService.activateServerGroup
public void activateServerGroup(int groupId, int clientId) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_CLIENT + " SET " + Constants.CLIENT_ACTIVESERVERGROUP + " = ? " + " WHERE " + Constants.GENERIC_ID + " = ? " ); statement.setInt(1, groupId); statement.setInt(2, clientId); statement.executeUpdate(); statement.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
public void activateServerGroup(int groupId, int clientId) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_CLIENT + " SET " + Constants.CLIENT_ACTIVESERVERGROUP + " = ? " + " WHERE " + Constants.GENERIC_ID + " = ? " ); statement.setInt(1, groupId); statement.setInt(2, clientId); statement.executeUpdate(); statement.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
[ "public", "void", "activateServerGroup", "(", "int", "groupId", ",", "int", "clientId", ")", "{", "PreparedStatement", "statement", "=", "null", ";", "try", "(", "Connection", "sqlConnection", "=", "sqlService", ".", "getConnection", "(", ")", ")", "{", "state...
Activate a server group @param groupId ID of group @param clientId client ID
[ "Activate", "a", "server", "group" ]
train
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxylib/src/main/java/com/groupon/odo/proxylib/ServerRedirectService.java#L444-L468
GoogleCloudPlatform/bigdata-interop
gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageFileSystem.java
GoogleCloudStorageFileSystem.updateTimestampsForParentDirectories
protected void updateTimestampsForParentDirectories( List<URI> modifiedObjects, List<URI> excludedParents) throws IOException { logger.atFine().log( "updateTimestampsForParentDirectories(%s, %s)", modifiedObjects, excludedParents); TimestampUpdatePredicate updatePredicate = options.getShouldIncludeInTimestampUpdatesPredicate(); Set<URI> excludedParentPathsSet = new HashSet<>(excludedParents); Set<URI> parentUrisToUpdate = Sets.newHashSetWithExpectedSize(modifiedObjects.size()); for (URI modifiedObjectUri : modifiedObjects) { URI parentPathUri = getParentPath(modifiedObjectUri); if (!excludedParentPathsSet.contains(parentPathUri) && updatePredicate.shouldUpdateTimestamp(parentPathUri)) { parentUrisToUpdate.add(parentPathUri); } } Map<String, byte[]> modificationAttributes = new HashMap<>(); FileInfo.addModificationTimeToAttributes(modificationAttributes, Clock.SYSTEM); List<UpdatableItemInfo> itemUpdates = new ArrayList<>(parentUrisToUpdate.size()); for (URI parentUri : parentUrisToUpdate) { StorageResourceId resourceId = pathCodec.validatePathAndGetId(parentUri, true); if (!resourceId.isBucket() && !resourceId.isRoot()) { itemUpdates.add(new UpdatableItemInfo(resourceId, modificationAttributes)); } } if (!itemUpdates.isEmpty()) { gcs.updateItems(itemUpdates); } else { logger.atFine().log("All paths were excluded from directory timestamp updating."); } }
java
protected void updateTimestampsForParentDirectories( List<URI> modifiedObjects, List<URI> excludedParents) throws IOException { logger.atFine().log( "updateTimestampsForParentDirectories(%s, %s)", modifiedObjects, excludedParents); TimestampUpdatePredicate updatePredicate = options.getShouldIncludeInTimestampUpdatesPredicate(); Set<URI> excludedParentPathsSet = new HashSet<>(excludedParents); Set<URI> parentUrisToUpdate = Sets.newHashSetWithExpectedSize(modifiedObjects.size()); for (URI modifiedObjectUri : modifiedObjects) { URI parentPathUri = getParentPath(modifiedObjectUri); if (!excludedParentPathsSet.contains(parentPathUri) && updatePredicate.shouldUpdateTimestamp(parentPathUri)) { parentUrisToUpdate.add(parentPathUri); } } Map<String, byte[]> modificationAttributes = new HashMap<>(); FileInfo.addModificationTimeToAttributes(modificationAttributes, Clock.SYSTEM); List<UpdatableItemInfo> itemUpdates = new ArrayList<>(parentUrisToUpdate.size()); for (URI parentUri : parentUrisToUpdate) { StorageResourceId resourceId = pathCodec.validatePathAndGetId(parentUri, true); if (!resourceId.isBucket() && !resourceId.isRoot()) { itemUpdates.add(new UpdatableItemInfo(resourceId, modificationAttributes)); } } if (!itemUpdates.isEmpty()) { gcs.updateItems(itemUpdates); } else { logger.atFine().log("All paths were excluded from directory timestamp updating."); } }
[ "protected", "void", "updateTimestampsForParentDirectories", "(", "List", "<", "URI", ">", "modifiedObjects", ",", "List", "<", "URI", ">", "excludedParents", ")", "throws", "IOException", "{", "logger", ".", "atFine", "(", ")", ".", "log", "(", "\"updateTimesta...
For each listed modified object, attempt to update the modification time of the parent directory. @param modifiedObjects The objects that have been modified @param excludedParents A list of parent directories that we shouldn't attempt to update.
[ "For", "each", "listed", "modified", "object", "attempt", "to", "update", "the", "modification", "time", "of", "the", "parent", "directory", "." ]
train
https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageFileSystem.java#L1306-L1341
Azure/azure-sdk-for-java
dns/resource-manager/v2016_04_01/src/main/java/com/microsoft/azure/management/dns/v2016_04_01/implementation/ZonesInner.java
ZonesInner.deleteAsync
public Observable<ZoneDeleteResultInner> deleteAsync(String resourceGroupName, String zoneName, String ifMatch) { return deleteWithServiceResponseAsync(resourceGroupName, zoneName, ifMatch).map(new Func1<ServiceResponse<ZoneDeleteResultInner>, ZoneDeleteResultInner>() { @Override public ZoneDeleteResultInner call(ServiceResponse<ZoneDeleteResultInner> response) { return response.body(); } }); }
java
public Observable<ZoneDeleteResultInner> deleteAsync(String resourceGroupName, String zoneName, String ifMatch) { return deleteWithServiceResponseAsync(resourceGroupName, zoneName, ifMatch).map(new Func1<ServiceResponse<ZoneDeleteResultInner>, ZoneDeleteResultInner>() { @Override public ZoneDeleteResultInner call(ServiceResponse<ZoneDeleteResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ZoneDeleteResultInner", ">", "deleteAsync", "(", "String", "resourceGroupName", ",", "String", "zoneName", ",", "String", "ifMatch", ")", "{", "return", "deleteWithServiceResponseAsync", "(", "resourceGroupName", ",", "zoneName", ",", "if...
Deletes a DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be undone. @param resourceGroupName The name of the resource group. @param zoneName The name of the DNS zone (without a terminating dot). @param ifMatch The etag of the DNS zone. Omit this value to always delete the current zone. Specify the last-seen etag value to prevent accidentally deleting any concurrent changes. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Deletes", "a", "DNS", "zone", ".", "WARNING", ":", "All", "DNS", "records", "in", "the", "zone", "will", "also", "be", "deleted", ".", "This", "operation", "cannot", "be", "undone", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/dns/resource-manager/v2016_04_01/src/main/java/com/microsoft/azure/management/dns/v2016_04_01/implementation/ZonesInner.java#L400-L407
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/TypesafeConfigUtils.java
TypesafeConfigUtils.getObject
public static Object getObject(Config config, String path) { try { return config.getAnyRef(path); } catch (ConfigException.Missing | ConfigException.WrongType e) { if (e instanceof ConfigException.WrongType) { LOGGER.warn(e.getMessage(), e); } return null; } }
java
public static Object getObject(Config config, String path) { try { return config.getAnyRef(path); } catch (ConfigException.Missing | ConfigException.WrongType e) { if (e instanceof ConfigException.WrongType) { LOGGER.warn(e.getMessage(), e); } return null; } }
[ "public", "static", "Object", "getObject", "(", "Config", "config", ",", "String", "path", ")", "{", "try", "{", "return", "config", ".", "getAnyRef", "(", "path", ")", ";", "}", "catch", "(", "ConfigException", ".", "Missing", "|", "ConfigException", ".",...
Get a configuration as Java object. Return {@code null} if missing or wrong type. @param config @param path @return
[ "Get", "a", "configuration", "as", "Java", "object", ".", "Return", "{", "@code", "null", "}", "if", "missing", "or", "wrong", "type", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/TypesafeConfigUtils.java#L765-L774
thorntail/thorntail
core/container/src/main/java/org/wildfly/swarm/container/runtime/xmlconfig/StandaloneXMLParser.java
StandaloneXMLParser.addDelegate
public StandaloneXMLParser addDelegate(QName elementName, XMLElementReader<List<ModelNode>> parser) { this.recognizedNames.add(elementName); xmlMapper.registerRootElement(elementName, parser); return this; }
java
public StandaloneXMLParser addDelegate(QName elementName, XMLElementReader<List<ModelNode>> parser) { this.recognizedNames.add(elementName); xmlMapper.registerRootElement(elementName, parser); return this; }
[ "public", "StandaloneXMLParser", "addDelegate", "(", "QName", "elementName", ",", "XMLElementReader", "<", "List", "<", "ModelNode", ">", ">", "parser", ")", "{", "this", ".", "recognizedNames", ".", "add", "(", "elementName", ")", ";", "xmlMapper", ".", "regi...
Add a parser for a subpart of the XML model. @param elementName the FQ element name (i.e. subsystem name) @param parser creates ModelNode's from XML input @return
[ "Add", "a", "parser", "for", "a", "subpart", "of", "the", "XML", "model", "." ]
train
https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/container/runtime/xmlconfig/StandaloneXMLParser.java#L110-L114
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/sampling/StratifiedSampling.java
StratifiedSampling.randomSampling
public static TransposeDataCollection randomSampling(TransposeDataList strataIdList, AssociativeArray nh, boolean withReplacement) { TransposeDataCollection sampledIds = new TransposeDataCollection(); for(Map.Entry<Object, FlatDataList> entry : strataIdList.entrySet()) { Object strata = entry.getKey(); Number sampleN = ((Number)nh.get(strata)); if(sampleN==null) { continue; } sampledIds.put(strata, SimpleRandomSampling.randomSampling(entry.getValue(), sampleN.intValue(), withReplacement)); } return sampledIds; }
java
public static TransposeDataCollection randomSampling(TransposeDataList strataIdList, AssociativeArray nh, boolean withReplacement) { TransposeDataCollection sampledIds = new TransposeDataCollection(); for(Map.Entry<Object, FlatDataList> entry : strataIdList.entrySet()) { Object strata = entry.getKey(); Number sampleN = ((Number)nh.get(strata)); if(sampleN==null) { continue; } sampledIds.put(strata, SimpleRandomSampling.randomSampling(entry.getValue(), sampleN.intValue(), withReplacement)); } return sampledIds; }
[ "public", "static", "TransposeDataCollection", "randomSampling", "(", "TransposeDataList", "strataIdList", ",", "AssociativeArray", "nh", ",", "boolean", "withReplacement", ")", "{", "TransposeDataCollection", "sampledIds", "=", "new", "TransposeDataCollection", "(", ")", ...
Samples nh ids from each strata by using Stratified Sampling @param strataIdList @param nh @param withReplacement @return
[ "Samples", "nh", "ids", "from", "each", "strata", "by", "using", "Stratified", "Sampling" ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/sampling/StratifiedSampling.java#L63-L78
HanSolo/tilesfx
src/main/java/eu/hansolo/tilesfx/tools/Helper.java
Helper.snapToTicks
public static double snapToTicks(final double MIN_VALUE, final double MAX_VALUE, final double VALUE, final int MINOR_TICK_COUNT, final double MAJOR_TICK_UNIT) { double v = VALUE; int minorTickCount = clamp(0, 10, MINOR_TICK_COUNT); double majorTickUnit = Double.compare(MAJOR_TICK_UNIT, 0.0) <= 0 ? 0.25 : MAJOR_TICK_UNIT; double tickSpacing; if (minorTickCount != 0) { tickSpacing = majorTickUnit / (Math.max(minorTickCount, 0) + 1); } else { tickSpacing = majorTickUnit; } int prevTick = (int) ((v - MIN_VALUE) / tickSpacing); double prevTickValue = prevTick * tickSpacing + MIN_VALUE; double nextTickValue = (prevTick + 1) * tickSpacing + MIN_VALUE; v = nearest(prevTickValue, v, nextTickValue); return clamp(MIN_VALUE, MAX_VALUE, v); }
java
public static double snapToTicks(final double MIN_VALUE, final double MAX_VALUE, final double VALUE, final int MINOR_TICK_COUNT, final double MAJOR_TICK_UNIT) { double v = VALUE; int minorTickCount = clamp(0, 10, MINOR_TICK_COUNT); double majorTickUnit = Double.compare(MAJOR_TICK_UNIT, 0.0) <= 0 ? 0.25 : MAJOR_TICK_UNIT; double tickSpacing; if (minorTickCount != 0) { tickSpacing = majorTickUnit / (Math.max(minorTickCount, 0) + 1); } else { tickSpacing = majorTickUnit; } int prevTick = (int) ((v - MIN_VALUE) / tickSpacing); double prevTickValue = prevTick * tickSpacing + MIN_VALUE; double nextTickValue = (prevTick + 1) * tickSpacing + MIN_VALUE; v = nearest(prevTickValue, v, nextTickValue); return clamp(MIN_VALUE, MAX_VALUE, v); }
[ "public", "static", "double", "snapToTicks", "(", "final", "double", "MIN_VALUE", ",", "final", "double", "MAX_VALUE", ",", "final", "double", "VALUE", ",", "final", "int", "MINOR_TICK_COUNT", ",", "final", "double", "MAJOR_TICK_UNIT", ")", "{", "double", "v", ...
Can be used to implement discrete steps e.g. on a slider. @param MIN_VALUE The min value of the range @param MAX_VALUE The max value of the range @param VALUE The value to snap @param MINOR_TICK_COUNT The number of ticks between 2 major tick marks @param MAJOR_TICK_UNIT The distance between 2 major tick marks @return The value snapped to the next tick mark defined by the given parameters
[ "Can", "be", "used", "to", "implement", "discrete", "steps", "e", ".", "g", ".", "on", "a", "slider", "." ]
train
https://github.com/HanSolo/tilesfx/blob/36eb07b1119017beb851dad95256439224d1fcf4/src/main/java/eu/hansolo/tilesfx/tools/Helper.java#L500-L519
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/f/FundamentalLinear8.java
FundamentalLinear8.process
public boolean process( List<AssociatedPair> points , DMatrixRMaj solution ) { if( points.size() < 8 ) throw new IllegalArgumentException("Must be at least 8 points. Was only "+points.size()); // use normalized coordinates for pixel and calibrated // TODO re-evaluate decision to normalize for calibrated case LowLevelMultiViewOps.computeNormalization(points, N1, N2); createA(points,A); if (process(A,solution)) return false; // undo normalization on F PerspectiveOps.multTranA(N2.matrix(),solution,N1.matrix(),solution); if( computeFundamental ) return projectOntoFundamentalSpace(solution); else return projectOntoEssential(solution); }
java
public boolean process( List<AssociatedPair> points , DMatrixRMaj solution ) { if( points.size() < 8 ) throw new IllegalArgumentException("Must be at least 8 points. Was only "+points.size()); // use normalized coordinates for pixel and calibrated // TODO re-evaluate decision to normalize for calibrated case LowLevelMultiViewOps.computeNormalization(points, N1, N2); createA(points,A); if (process(A,solution)) return false; // undo normalization on F PerspectiveOps.multTranA(N2.matrix(),solution,N1.matrix(),solution); if( computeFundamental ) return projectOntoFundamentalSpace(solution); else return projectOntoEssential(solution); }
[ "public", "boolean", "process", "(", "List", "<", "AssociatedPair", ">", "points", ",", "DMatrixRMaj", "solution", ")", "{", "if", "(", "points", ".", "size", "(", ")", "<", "8", ")", "throw", "new", "IllegalArgumentException", "(", "\"Must be at least 8 point...
<p> Computes a fundamental or essential matrix from a set of associated point correspondences. </p> @param points List of corresponding image coordinates. In pixel for fundamental matrix or normalized coordinates for essential matrix. @return true If successful or false if it failed
[ "<p", ">", "Computes", "a", "fundamental", "or", "essential", "matrix", "from", "a", "set", "of", "associated", "point", "correspondences", ".", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/f/FundamentalLinear8.java#L70-L89
OpenLiberty/open-liberty
dev/com.ibm.ws.diagnostics/src/com/ibm/ws/diagnostics/AbstractMBeanIntrospector.java
AbstractMBeanIntrospector.getFormattedCompositeData
String getFormattedCompositeData(CompositeData cd, String indent) { StringBuilder sb = new StringBuilder(); indent += INDENT; CompositeType type = cd.getCompositeType(); for (String key : type.keySet()) { sb.append("\n").append(indent); sb.append(key).append(": "); OpenType<?> openType = type.getType(key); if (openType instanceof SimpleType) { sb.append(cd.get(key)); } else if (openType instanceof CompositeType) { CompositeData nestedData = (CompositeData) cd.get(key); sb.append(getFormattedCompositeData(nestedData, indent)); } else if (openType instanceof TabularType) { TabularData tabularData = (TabularData) cd.get(key); sb.append(tabularData); } } return String.valueOf(sb); }
java
String getFormattedCompositeData(CompositeData cd, String indent) { StringBuilder sb = new StringBuilder(); indent += INDENT; CompositeType type = cd.getCompositeType(); for (String key : type.keySet()) { sb.append("\n").append(indent); sb.append(key).append(": "); OpenType<?> openType = type.getType(key); if (openType instanceof SimpleType) { sb.append(cd.get(key)); } else if (openType instanceof CompositeType) { CompositeData nestedData = (CompositeData) cd.get(key); sb.append(getFormattedCompositeData(nestedData, indent)); } else if (openType instanceof TabularType) { TabularData tabularData = (TabularData) cd.get(key); sb.append(tabularData); } } return String.valueOf(sb); }
[ "String", "getFormattedCompositeData", "(", "CompositeData", "cd", ",", "String", "indent", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "indent", "+=", "INDENT", ";", "CompositeType", "type", "=", "cd", ".", "getCompositeType", ...
Format an open MBean composite data attribute. @param cd the composite data attribute @param indent the current indent level of the formatted report @return the formatted composite data
[ "Format", "an", "open", "MBean", "composite", "data", "attribute", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.diagnostics/src/com/ibm/ws/diagnostics/AbstractMBeanIntrospector.java#L242-L261