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 |
|---|---|---|---|---|---|---|---|---|---|---|
westnordost/osmapi | src/main/java/de/westnordost/osmapi/user/UserPreferencesDao.java | UserPreferencesDao.setAll | public void setAll(Map<String, String> preferences)
{
// check it before sending it to the server in order to be able to raise a precise exception
for(Map.Entry<String,String> preference : preferences.entrySet())
{
checkPreferenceKeyLength(preference.getKey());
checkPreferenceValueLength(preference.getValue());
}
final Map<String, String> prefs = preferences;
osm.makeAuthenticatedRequest(
USERPREFS, "PUT", new XmlWriter()
{
@Override
protected void write() throws IOException
{
begin("osm");
begin("preferences");
for (Map.Entry<String, String> preference : prefs.entrySet())
{
begin("preference");
attribute("k", preference.getKey());
attribute("v", preference.getValue());
end();
}
end();
end();
}
});
} | java | public void setAll(Map<String, String> preferences)
{
// check it before sending it to the server in order to be able to raise a precise exception
for(Map.Entry<String,String> preference : preferences.entrySet())
{
checkPreferenceKeyLength(preference.getKey());
checkPreferenceValueLength(preference.getValue());
}
final Map<String, String> prefs = preferences;
osm.makeAuthenticatedRequest(
USERPREFS, "PUT", new XmlWriter()
{
@Override
protected void write() throws IOException
{
begin("osm");
begin("preferences");
for (Map.Entry<String, String> preference : prefs.entrySet())
{
begin("preference");
attribute("k", preference.getKey());
attribute("v", preference.getValue());
end();
}
end();
end();
}
});
} | [
"public",
"void",
"setAll",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"preferences",
")",
"{",
"// check it before sending it to the server in order to be able to raise a precise exception",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"pre... | Sets all the given preference keys to the given preference values.
@param preferences preferences to set. Each key and each value must be less than 256
characters.
@throws OsmAuthorizationException if this application is not authorized to change the
user's preferences. (Permission.CHANGE_PREFERENCES) | [
"Sets",
"all",
"the",
"given",
"preference",
"keys",
"to",
"the",
"given",
"preference",
"values",
"."
] | train | https://github.com/westnordost/osmapi/blob/dda6978fd12e117d0cf17812bc22037f61e22c4b/src/main/java/de/westnordost/osmapi/user/UserPreferencesDao.java#L81-L112 |
networknt/light-4j | metrics/src/main/java/io/dropwizard/metrics/UniformSnapshot.java | UniformSnapshot.dump | @Override
public void dump(OutputStream output) {
try (PrintWriter out = new PrintWriter(new OutputStreamWriter(output, UTF_8))) {
for (long value : values) {
out.printf("%d%n", value);
}
}
} | java | @Override
public void dump(OutputStream output) {
try (PrintWriter out = new PrintWriter(new OutputStreamWriter(output, UTF_8))) {
for (long value : values) {
out.printf("%d%n", value);
}
}
} | [
"@",
"Override",
"public",
"void",
"dump",
"(",
"OutputStream",
"output",
")",
"{",
"try",
"(",
"PrintWriter",
"out",
"=",
"new",
"PrintWriter",
"(",
"new",
"OutputStreamWriter",
"(",
"output",
",",
"UTF_8",
")",
")",
")",
"{",
"for",
"(",
"long",
"value... | Writes the values of the snapshot to the given stream.
@param output an output stream | [
"Writes",
"the",
"values",
"of",
"the",
"snapshot",
"to",
"the",
"given",
"stream",
"."
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/metrics/src/main/java/io/dropwizard/metrics/UniformSnapshot.java#L201-L208 |
infinispan/infinispan | core/src/main/java/org/infinispan/atomic/impl/FineGrainedAtomicMapProxyImpl.java | FineGrainedAtomicMapProxyImpl.removeMap | public static void removeMap(Cache<Object, Object> cache, Object group) {
FunctionalMapImpl<Object, Object> fmap = FunctionalMapImpl.create(cache.getAdvancedCache());
FunctionalMap.ReadWriteMap<Object, Object> rw = ReadWriteMapImpl.create(fmap).withParams(Param.LockingMode.SKIP);
new TransactionHelper(cache.getAdvancedCache()).run(() -> {
Set<Object> keys = wait(rw.eval(group, AtomicKeySetImpl.RemoveMap.instance()));
if (keys != null) {
removeAll(cache, group, keys);
}
return null;
});
} | java | public static void removeMap(Cache<Object, Object> cache, Object group) {
FunctionalMapImpl<Object, Object> fmap = FunctionalMapImpl.create(cache.getAdvancedCache());
FunctionalMap.ReadWriteMap<Object, Object> rw = ReadWriteMapImpl.create(fmap).withParams(Param.LockingMode.SKIP);
new TransactionHelper(cache.getAdvancedCache()).run(() -> {
Set<Object> keys = wait(rw.eval(group, AtomicKeySetImpl.RemoveMap.instance()));
if (keys != null) {
removeAll(cache, group, keys);
}
return null;
});
} | [
"public",
"static",
"void",
"removeMap",
"(",
"Cache",
"<",
"Object",
",",
"Object",
">",
"cache",
",",
"Object",
"group",
")",
"{",
"FunctionalMapImpl",
"<",
"Object",
",",
"Object",
">",
"fmap",
"=",
"FunctionalMapImpl",
".",
"create",
"(",
"cache",
".",... | Warning: with pessimistic locking/optimistic locking without WSC, when the map is removed and a new key is added
before the removal transaction commit, the map may be removed but the key left dangling. | [
"Warning",
":",
"with",
"pessimistic",
"locking",
"/",
"optimistic",
"locking",
"without",
"WSC",
"when",
"the",
"map",
"is",
"removed",
"and",
"a",
"new",
"key",
"is",
"added",
"before",
"the",
"removal",
"transaction",
"commit",
"the",
"map",
"may",
"be",
... | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/atomic/impl/FineGrainedAtomicMapProxyImpl.java#L114-L124 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/javax/crypto/Mac.java | Mac.getInstance | public static final Mac getInstance(String algorithm, String provider)
throws NoSuchAlgorithmException, NoSuchProviderException {
Instance instance = JceSecurity.getInstance
("Mac", MacSpi.class, algorithm, provider);
return new Mac((MacSpi)instance.impl, instance.provider, algorithm);
} | java | public static final Mac getInstance(String algorithm, String provider)
throws NoSuchAlgorithmException, NoSuchProviderException {
Instance instance = JceSecurity.getInstance
("Mac", MacSpi.class, algorithm, provider);
return new Mac((MacSpi)instance.impl, instance.provider, algorithm);
} | [
"public",
"static",
"final",
"Mac",
"getInstance",
"(",
"String",
"algorithm",
",",
"String",
"provider",
")",
"throws",
"NoSuchAlgorithmException",
",",
"NoSuchProviderException",
"{",
"Instance",
"instance",
"=",
"JceSecurity",
".",
"getInstance",
"(",
"\"Mac\"",
... | Returns a <code>Mac</code> object that implements the
specified MAC algorithm.
<p> A new Mac object encapsulating the
MacSpi implementation from the specified provider
is returned. The specified provider must be registered
in the security provider list.
<p> Note that the list of registered providers may be retrieved via
the {@link Security#getProviders() Security.getProviders()} method.
@param algorithm the standard name of the requested MAC algorithm.
See the Mac section in the <a href=
"{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/StandardNames.html#Mac">
Java Cryptography Architecture Standard Algorithm Name Documentation</a>
for information about standard algorithm names.
@param provider the name of the provider.
@return the new <code>Mac</code> object.
@exception NoSuchAlgorithmException if a MacSpi
implementation for the specified algorithm is not
available from the specified provider.
@exception NoSuchProviderException if the specified provider is not
registered in the security provider list.
@exception IllegalArgumentException if the <code>provider</code>
is null or empty.
@see java.security.Provider | [
"Returns",
"a",
"<code",
">",
"Mac<",
"/",
"code",
">",
"object",
"that",
"implements",
"the",
"specified",
"MAC",
"algorithm",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/javax/crypto/Mac.java#L289-L294 |
jboss-integration/fuse-bxms-integ | switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/exchange/KnowledgeExchangeHandler.java | KnowledgeExchangeHandler.getInteger | protected Integer getInteger(Exchange exchange, Message message, String name) {
Object value = getObject(exchange, message, name);
if (value instanceof Integer) {
return (Integer)value;
} else if (value instanceof Number) {
return Integer.valueOf(((Number)value).intValue());
} else if (value instanceof String) {
return Integer.valueOf(((String)value).trim());
}
return null;
} | java | protected Integer getInteger(Exchange exchange, Message message, String name) {
Object value = getObject(exchange, message, name);
if (value instanceof Integer) {
return (Integer)value;
} else if (value instanceof Number) {
return Integer.valueOf(((Number)value).intValue());
} else if (value instanceof String) {
return Integer.valueOf(((String)value).trim());
}
return null;
} | [
"protected",
"Integer",
"getInteger",
"(",
"Exchange",
"exchange",
",",
"Message",
"message",
",",
"String",
"name",
")",
"{",
"Object",
"value",
"=",
"getObject",
"(",
"exchange",
",",
"message",
",",
"name",
")",
";",
"if",
"(",
"value",
"instanceof",
"I... | Gets an Integer context property.
@param exchange the exchange
@param message the message
@param name the name
@return the property | [
"Gets",
"an",
"Integer",
"context",
"property",
"."
] | train | https://github.com/jboss-integration/fuse-bxms-integ/blob/ca5c012bf867ea15d1250f0991af3cd7e708aaaf/switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/exchange/KnowledgeExchangeHandler.java#L202-L212 |
alexvasilkov/AndroidCommons | library/src/main/java/com/alexvasilkov/android/commons/state/InstanceStateManager.java | InstanceStateManager.saveInstanceState | @NonNull
public static <T> Bundle saveInstanceState(@NonNull T obj, @Nullable Bundle outState) {
if (outState == null) {
outState = new Bundle();
}
return new InstanceStateManager<>(obj).saveState(outState);
} | java | @NonNull
public static <T> Bundle saveInstanceState(@NonNull T obj, @Nullable Bundle outState) {
if (outState == null) {
outState = new Bundle();
}
return new InstanceStateManager<>(obj).saveState(outState);
} | [
"@",
"NonNull",
"public",
"static",
"<",
"T",
">",
"Bundle",
"saveInstanceState",
"(",
"@",
"NonNull",
"T",
"obj",
",",
"@",
"Nullable",
"Bundle",
"outState",
")",
"{",
"if",
"(",
"outState",
"==",
"null",
")",
"{",
"outState",
"=",
"new",
"Bundle",
"(... | Saving instance state of the given {@code obj} into {@code outState}.<br/>
Supposed to be called from
{@link android.app.Activity#onSaveInstanceState(android.os.Bundle)} or
{@link android.app.Fragment#onSaveInstanceState(android.os.Bundle)}.<br/>
Activity or Fragment itself can be used as {@code obj} parameter. | [
"Saving",
"instance",
"state",
"of",
"the",
"given",
"{"
] | train | https://github.com/alexvasilkov/AndroidCommons/blob/aca9f6d5acfc6bd3694984b7f89956e1a0146ddb/library/src/main/java/com/alexvasilkov/android/commons/state/InstanceStateManager.java#L45-L51 |
gilberto-torrezan/gwt-views | src/main/java/com/github/gilbertotorrezan/gwtviews/client/URLToken.java | URLToken.getParameter | public String getParameter(String name, String defaultValue) {
String value = parameters.get(name);
if (value == null){
value = defaultValue;
}
return value;
} | java | public String getParameter(String name, String defaultValue) {
String value = parameters.get(name);
if (value == null){
value = defaultValue;
}
return value;
} | [
"public",
"String",
"getParameter",
"(",
"String",
"name",
",",
"String",
"defaultValue",
")",
"{",
"String",
"value",
"=",
"parameters",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"value",
"=",
"defaultValue",
";",
... | Gets a parameter extracted from the History token.
For example, if the token is: <pre>{@code tokenId¶m1=value1 }</pre>the call to <code>getParameter("param1", "def")</code> will return <code>value1</code>.
@param name The name of the parameter
@param defaultValue The value to be returned when the parameter value is <code>null</code>
@return The value of the parameter, or <code>defaultValue</code> if not found.
When the token is something like <pre>{@code tokenId¶m1¶m2 }</pre> with a name without a explicit value, an empty String is returned. | [
"Gets",
"a",
"parameter",
"extracted",
"from",
"the",
"History",
"token",
".",
"For",
"example",
"if",
"the",
"token",
"is",
":",
"<pre",
">",
"{",
"@code",
"tokenId¶m1",
"=",
"value1",
"}",
"<",
"/",
"pre",
">",
"the",
"call",
"to",
"<code",
">",
... | train | https://github.com/gilberto-torrezan/gwt-views/blob/c6511435d14b5aa93a722b0e861230d0ae2159e5/src/main/java/com/github/gilbertotorrezan/gwtviews/client/URLToken.java#L201-L207 |
CODAIT/stocator | src/main/java/com/ibm/stocator/fs/cos/BlockingThreadPoolExecutorService.java | BlockingThreadPoolExecutorService.getNamedThreadFactory | static ThreadFactory getNamedThreadFactory(final String prefix) {
SecurityManager s = System.getSecurityManager();
final ThreadGroup threadGroup = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
return new ThreadFactory() {
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final int poolNum = POOLNUMBER.getAndIncrement();
private final ThreadGroup group = threadGroup;
@Override
public Thread newThread(Runnable r) {
final String name =
prefix + "-pool" + poolNum + "-t" + threadNumber.getAndIncrement();
return new Thread(group, r, name);
}
};
} | java | static ThreadFactory getNamedThreadFactory(final String prefix) {
SecurityManager s = System.getSecurityManager();
final ThreadGroup threadGroup = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
return new ThreadFactory() {
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final int poolNum = POOLNUMBER.getAndIncrement();
private final ThreadGroup group = threadGroup;
@Override
public Thread newThread(Runnable r) {
final String name =
prefix + "-pool" + poolNum + "-t" + threadNumber.getAndIncrement();
return new Thread(group, r, name);
}
};
} | [
"static",
"ThreadFactory",
"getNamedThreadFactory",
"(",
"final",
"String",
"prefix",
")",
"{",
"SecurityManager",
"s",
"=",
"System",
".",
"getSecurityManager",
"(",
")",
";",
"final",
"ThreadGroup",
"threadGroup",
"=",
"(",
"s",
"!=",
"null",
")",
"?",
"s",
... | Returns a {@link java.util.concurrent.ThreadFactory} that names each
created thread uniquely,
with a common prefix.
@param prefix The prefix of every created Thread's name
@return a {@link java.util.concurrent.ThreadFactory} that names threads | [
"Returns",
"a",
"{",
"@link",
"java",
".",
"util",
".",
"concurrent",
".",
"ThreadFactory",
"}",
"that",
"names",
"each",
"created",
"thread",
"uniquely",
"with",
"a",
"common",
"prefix",
"."
] | train | https://github.com/CODAIT/stocator/blob/35969cadd2e8faa6fdac45e8bec1799fdd3d8299/src/main/java/com/ibm/stocator/fs/cos/BlockingThreadPoolExecutorService.java#L63-L80 |
lucee/Lucee | core/src/main/java/lucee/commons/io/ini/IniFile.java | IniFile.setKeyValue | public void setKeyValue(String strSection, String key, String value) {
Map section = getSectionEL(strSection);
if (section == null) {
section = newMap();
sections.put(strSection.toLowerCase(), section);
}
section.put(key.toLowerCase(), value);
} | java | public void setKeyValue(String strSection, String key, String value) {
Map section = getSectionEL(strSection);
if (section == null) {
section = newMap();
sections.put(strSection.toLowerCase(), section);
}
section.put(key.toLowerCase(), value);
} | [
"public",
"void",
"setKeyValue",
"(",
"String",
"strSection",
",",
"String",
"key",
",",
"String",
"value",
")",
"{",
"Map",
"section",
"=",
"getSectionEL",
"(",
"strSection",
")",
";",
"if",
"(",
"section",
"==",
"null",
")",
"{",
"section",
"=",
"newMa... | Sets the KeyValue attribute of the IniFile object
@param strSection the section to set
@param key the key of the new value
@param value the value to set | [
"Sets",
"the",
"KeyValue",
"attribute",
"of",
"the",
"IniFile",
"object"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/io/ini/IniFile.java#L80-L87 |
alkacon/opencms-core | src-gwt/org/opencms/ade/galleries/client/ui/CmsCategoriesTab.java | CmsCategoriesTab.fillContent | public void fillContent(List<CmsCategoryTreeEntry> categoryRoot, List<String> selected) {
setInitOpen(true);
updateContentTree(categoryRoot, selected);
} | java | public void fillContent(List<CmsCategoryTreeEntry> categoryRoot, List<String> selected) {
setInitOpen(true);
updateContentTree(categoryRoot, selected);
} | [
"public",
"void",
"fillContent",
"(",
"List",
"<",
"CmsCategoryTreeEntry",
">",
"categoryRoot",
",",
"List",
"<",
"String",
">",
"selected",
")",
"{",
"setInitOpen",
"(",
"true",
")",
";",
"updateContentTree",
"(",
"categoryRoot",
",",
"selected",
")",
";",
... | Fill the content of the categories tab panel.<p>
@param categoryRoot the category tree root entry
@param selected the selected categories | [
"Fill",
"the",
"content",
"of",
"the",
"categories",
"tab",
"panel",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/ui/CmsCategoriesTab.java#L127-L132 |
versionone/VersionOne.SDK.Java.ObjectModel | src/main/java/com/versionone/om/Project.java | Project.getTotalDone | public Double getTotalDone(WorkitemFilter filter, boolean includeChildProjects) {
filter = (filter != null) ? filter : new WorkitemFilter();
return getRollup("Workitems", "Actuals.Value", filter,
includeChildProjects);
} | java | public Double getTotalDone(WorkitemFilter filter, boolean includeChildProjects) {
filter = (filter != null) ? filter : new WorkitemFilter();
return getRollup("Workitems", "Actuals.Value", filter,
includeChildProjects);
} | [
"public",
"Double",
"getTotalDone",
"(",
"WorkitemFilter",
"filter",
",",
"boolean",
"includeChildProjects",
")",
"{",
"filter",
"=",
"(",
"filter",
"!=",
"null",
")",
"?",
"filter",
":",
"new",
"WorkitemFilter",
"(",
")",
";",
"return",
"getRollup",
"(",
"\... | Retrieves the total done for all workitems in this project optionally
filtered.
@param filter Criteria to filter workitems on.
@param includeChildProjects If true, include open sub projects, otherwise
only include this project.
@return total done for selected workitems. | [
"Retrieves",
"the",
"total",
"done",
"for",
"all",
"workitems",
"in",
"this",
"project",
"optionally",
"filtered",
"."
] | train | https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/om/Project.java#L1155-L1160 |
mabe02/lanterna | src/main/java/com/googlecode/lanterna/gui2/TextBox.java | TextBox.setCaretPosition | public synchronized TextBox setCaretPosition(int line, int column) {
if(line < 0) {
line = 0;
}
else if(line >= lines.size()) {
line = lines.size() - 1;
}
if(column < 0) {
column = 0;
}
else if(column > lines.get(line).length()) {
column = lines.get(line).length();
}
caretPosition = caretPosition.withRow(line).withColumn(column);
return this;
} | java | public synchronized TextBox setCaretPosition(int line, int column) {
if(line < 0) {
line = 0;
}
else if(line >= lines.size()) {
line = lines.size() - 1;
}
if(column < 0) {
column = 0;
}
else if(column > lines.get(line).length()) {
column = lines.get(line).length();
}
caretPosition = caretPosition.withRow(line).withColumn(column);
return this;
} | [
"public",
"synchronized",
"TextBox",
"setCaretPosition",
"(",
"int",
"line",
",",
"int",
"column",
")",
"{",
"if",
"(",
"line",
"<",
"0",
")",
"{",
"line",
"=",
"0",
";",
"}",
"else",
"if",
"(",
"line",
">=",
"lines",
".",
"size",
"(",
")",
")",
... | Moves the text caret position to a new position in the {@link TextBox}. For single-line {@link TextBox}:es, the
line component is not used. If one of the positions are out of bounds, it is automatically set back into range.
@param line Which line inside the {@link TextBox} to move the caret to (0 being the first line), ignored if the
{@link TextBox} is single-line
@param column What column on the specified line to move the text caret to (0 being the first column)
@return Itself | [
"Moves",
"the",
"text",
"caret",
"position",
"to",
"a",
"new",
"position",
"in",
"the",
"{"
] | train | https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/gui2/TextBox.java#L291-L306 |
jpush/jmessage-api-java-client | src/main/java/cn/jmessage/api/JMessageClient.java | JMessageClient.sendSingleTextByAdmin | public SendMessageResult sendSingleTextByAdmin(String targetId, String fromId, MessageBody body)
throws APIConnectionException, APIRequestException {
return sendMessage(_sendVersion, "single", targetId, "admin",fromId, MessageType.TEXT, body);
} | java | public SendMessageResult sendSingleTextByAdmin(String targetId, String fromId, MessageBody body)
throws APIConnectionException, APIRequestException {
return sendMessage(_sendVersion, "single", targetId, "admin",fromId, MessageType.TEXT, body);
} | [
"public",
"SendMessageResult",
"sendSingleTextByAdmin",
"(",
"String",
"targetId",
",",
"String",
"fromId",
",",
"MessageBody",
"body",
")",
"throws",
"APIConnectionException",
",",
"APIRequestException",
"{",
"return",
"sendMessage",
"(",
"_sendVersion",
",",
"\"single... | Send single text message by admin
@param targetId target user's id
@param fromId sender's id
@param body message body, include text and extra(if needed).
@return return msg_id
@throws APIConnectionException connect exception
@throws APIRequestException request exception | [
"Send",
"single",
"text",
"message",
"by",
"admin"
] | train | https://github.com/jpush/jmessage-api-java-client/blob/767f5fb15e9fe5a546c00f6e68b64f6dd53c617c/src/main/java/cn/jmessage/api/JMessageClient.java#L472-L475 |
nmorel/gwt-jackson | gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/BeanJsonDeserializerCreator.java | BeanJsonDeserializerCreator.buildNewInstanceMethodForDefaultConstructor | private void buildNewInstanceMethodForDefaultConstructor( MethodSpec.Builder newInstanceMethodBuilder, MethodSpec createMethod ) {
newInstanceMethodBuilder.addStatement( "return new $T($N(), bufferedProperties)",
parameterizedName( Instance.class, beanInfo.getType() ), createMethod );
} | java | private void buildNewInstanceMethodForDefaultConstructor( MethodSpec.Builder newInstanceMethodBuilder, MethodSpec createMethod ) {
newInstanceMethodBuilder.addStatement( "return new $T($N(), bufferedProperties)",
parameterizedName( Instance.class, beanInfo.getType() ), createMethod );
} | [
"private",
"void",
"buildNewInstanceMethodForDefaultConstructor",
"(",
"MethodSpec",
".",
"Builder",
"newInstanceMethodBuilder",
",",
"MethodSpec",
"createMethod",
")",
"{",
"newInstanceMethodBuilder",
".",
"addStatement",
"(",
"\"return new $T($N(), bufferedProperties)\"",
",",
... | Generate the instance builder class body for a default constructor. We directly instantiate the bean at the builder creation and we
set the properties to it
@param newInstanceMethodBuilder builder for the
{@link InstanceBuilder#newInstance(JsonReader, JsonDeserializationContext, JsonDeserializerParameters, Map, Map)}
method
@param createMethod the create method | [
"Generate",
"the",
"instance",
"builder",
"class",
"body",
"for",
"a",
"default",
"constructor",
".",
"We",
"directly",
"instantiate",
"the",
"bean",
"at",
"the",
"builder",
"creation",
"and",
"we",
"set",
"the",
"properties",
"to",
"it"
] | train | https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/BeanJsonDeserializerCreator.java#L282-L285 |
OrienteerBAP/wicket-orientdb | wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/query/filter/FilterCriteriaType.java | FilterCriteriaType.createAndRegister | public static FilterCriteriaType createAndRegister(String name, boolean collection, boolean map) {
FilterCriteriaType type = create(name, collection, map);
register(type);
return type;
} | java | public static FilterCriteriaType createAndRegister(String name, boolean collection, boolean map) {
FilterCriteriaType type = create(name, collection, map);
register(type);
return type;
} | [
"public",
"static",
"FilterCriteriaType",
"createAndRegister",
"(",
"String",
"name",
",",
"boolean",
"collection",
",",
"boolean",
"map",
")",
"{",
"FilterCriteriaType",
"type",
"=",
"create",
"(",
"name",
",",
"collection",
",",
"map",
")",
";",
"register",
... | Create and register {@link FilterCriteriaType}
@param name name of current {@link FilterCriteriaType}
@param collection if true - {@link FilterCriteriaType} include {@link IModel} with {@link Collection}
@param map d
@return new {@link FilterCriteriaType}
@throws IllegalStateException if {@link FilterCriteriaType} with current name if already registered | [
"Create",
"and",
"register",
"{"
] | train | https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/query/filter/FilterCriteriaType.java#L99-L103 |
haraldk/TwelveMonkeys | common/common-io/src/main/java/com/twelvemonkeys/io/FileUtil.java | FileUtil.copyDir | private static boolean copyDir(File pFrom, File pTo, boolean pOverWrite) throws IOException {
if (pTo.exists() && !pTo.isDirectory()) {
throw new IOException("A directory may only be copied to another directory, not to a file");
}
pTo.mkdirs(); // mkdir?
boolean allOkay = true;
File[] files = pFrom.listFiles();
for (File file : files) {
if (!copy(file, new File(pTo, file.getName()), pOverWrite)) {
allOkay = false;
}
}
return allOkay;
} | java | private static boolean copyDir(File pFrom, File pTo, boolean pOverWrite) throws IOException {
if (pTo.exists() && !pTo.isDirectory()) {
throw new IOException("A directory may only be copied to another directory, not to a file");
}
pTo.mkdirs(); // mkdir?
boolean allOkay = true;
File[] files = pFrom.listFiles();
for (File file : files) {
if (!copy(file, new File(pTo, file.getName()), pOverWrite)) {
allOkay = false;
}
}
return allOkay;
} | [
"private",
"static",
"boolean",
"copyDir",
"(",
"File",
"pFrom",
",",
"File",
"pTo",
",",
"boolean",
"pOverWrite",
")",
"throws",
"IOException",
"{",
"if",
"(",
"pTo",
".",
"exists",
"(",
")",
"&&",
"!",
"pTo",
".",
"isDirectory",
"(",
")",
")",
"{",
... | Copies a directory recursively. If the destination folder does not exist,
it is created
@param pFrom the source directory
@param pTo the destination directory
@param pOverWrite {@code true} if we should allow overwrting existing files
@return {@code true} if all files were copied sucessfully
@throws IOException if {@code pTo} exists, and it not a directory,
or if copying of any of the files in the folder fails | [
"Copies",
"a",
"directory",
"recursively",
".",
"If",
"the",
"destination",
"folder",
"does",
"not",
"exist",
"it",
"is",
"created"
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-io/src/main/java/com/twelvemonkeys/io/FileUtil.java#L282-L296 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/config/Config.java | Config.setReliableTopicConfigs | public Config setReliableTopicConfigs(Map<String, ReliableTopicConfig> reliableTopicConfigs) {
this.reliableTopicConfigs.clear();
this.reliableTopicConfigs.putAll(reliableTopicConfigs);
for (Entry<String, ReliableTopicConfig> entry : reliableTopicConfigs.entrySet()) {
entry.getValue().setName(entry.getKey());
}
return this;
} | java | public Config setReliableTopicConfigs(Map<String, ReliableTopicConfig> reliableTopicConfigs) {
this.reliableTopicConfigs.clear();
this.reliableTopicConfigs.putAll(reliableTopicConfigs);
for (Entry<String, ReliableTopicConfig> entry : reliableTopicConfigs.entrySet()) {
entry.getValue().setName(entry.getKey());
}
return this;
} | [
"public",
"Config",
"setReliableTopicConfigs",
"(",
"Map",
"<",
"String",
",",
"ReliableTopicConfig",
">",
"reliableTopicConfigs",
")",
"{",
"this",
".",
"reliableTopicConfigs",
".",
"clear",
"(",
")",
";",
"this",
".",
"reliableTopicConfigs",
".",
"putAll",
"(",
... | Sets the map of reliable topic configurations, mapped by config name.
The config name may be a pattern with which the configuration will be
obtained in the future.
@param reliableTopicConfigs the reliable topic configuration map to set
@return this config instance | [
"Sets",
"the",
"map",
"of",
"reliable",
"topic",
"configurations",
"mapped",
"by",
"config",
"name",
".",
"The",
"config",
"name",
"may",
"be",
"a",
"pattern",
"with",
"which",
"the",
"configuration",
"will",
"be",
"obtained",
"in",
"the",
"future",
"."
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/Config.java#L1746-L1753 |
bbottema/outlook-message-parser | src/main/java/org/simplejavamail/outlookmessageparser/OutlookMessageParser.java | OutlookMessageParser.parseAttachment | private void parseAttachment(final DirectoryEntry dir, final OutlookMessage msg)
throws IOException {
final OutlookFileAttachment attachment = new OutlookFileAttachment();
// iterate through all document entries
for (final Iterator<?> iter = dir.getEntries(); iter.hasNext(); ) {
final Entry entry = (Entry) iter.next();
if (entry.isDocumentEntry()) {
// the document entry may contain information about the attachment
final DocumentEntry de = (DocumentEntry) entry;
final OutlookMessageProperty msgProp = getMessagePropertyFromDocumentEntry(de);
// we provide the class and data of the document entry to the attachment.
// The attachment implementation has to know the semantics of the field names
attachment.setProperty(msgProp);
} else {
// a directory within the attachment directory entry means that a .msg file is attached at this point.
// we recursively parse this .msg file and add it as a OutlookMsgAttachment object to the current OutlookMessage object.
final OutlookMessage attachmentMsg = new OutlookMessage(rtf2htmlConverter);
final OutlookMsgAttachment msgAttachment = new OutlookMsgAttachment(attachmentMsg);
msg.addAttachment(msgAttachment);
checkDirectoryEntry((DirectoryEntry) entry, attachmentMsg);
}
}
// only if there was really an attachment, we add this object to the OutlookMessage object
if (attachment.getSize() > -1) {
attachment.checkMimeTag();
msg.addAttachment(attachment);
}
} | java | private void parseAttachment(final DirectoryEntry dir, final OutlookMessage msg)
throws IOException {
final OutlookFileAttachment attachment = new OutlookFileAttachment();
// iterate through all document entries
for (final Iterator<?> iter = dir.getEntries(); iter.hasNext(); ) {
final Entry entry = (Entry) iter.next();
if (entry.isDocumentEntry()) {
// the document entry may contain information about the attachment
final DocumentEntry de = (DocumentEntry) entry;
final OutlookMessageProperty msgProp = getMessagePropertyFromDocumentEntry(de);
// we provide the class and data of the document entry to the attachment.
// The attachment implementation has to know the semantics of the field names
attachment.setProperty(msgProp);
} else {
// a directory within the attachment directory entry means that a .msg file is attached at this point.
// we recursively parse this .msg file and add it as a OutlookMsgAttachment object to the current OutlookMessage object.
final OutlookMessage attachmentMsg = new OutlookMessage(rtf2htmlConverter);
final OutlookMsgAttachment msgAttachment = new OutlookMsgAttachment(attachmentMsg);
msg.addAttachment(msgAttachment);
checkDirectoryEntry((DirectoryEntry) entry, attachmentMsg);
}
}
// only if there was really an attachment, we add this object to the OutlookMessage object
if (attachment.getSize() > -1) {
attachment.checkMimeTag();
msg.addAttachment(attachment);
}
} | [
"private",
"void",
"parseAttachment",
"(",
"final",
"DirectoryEntry",
"dir",
",",
"final",
"OutlookMessage",
"msg",
")",
"throws",
"IOException",
"{",
"final",
"OutlookFileAttachment",
"attachment",
"=",
"new",
"OutlookFileAttachment",
"(",
")",
";",
"// iterate throu... | Creates an {@link OutlookAttachment} object based on
the given directory entry. The entry may either
point to an attached file or to an
attached .msg file, which will be added
as a {@link OutlookMsgAttachment} object instead.
@param dir The directory entry containing the attachment document entry and some other document entries describing the attachment (name, extension, mime
type, ...)
@param msg The {@link OutlookMessage} object that this attachment should be added to.
@throws IOException Thrown if the attachment could not be parsed/read. | [
"Creates",
"an",
"{",
"@link",
"OutlookAttachment",
"}",
"object",
"based",
"on",
"the",
"given",
"directory",
"entry",
".",
"The",
"entry",
"may",
"either",
"point",
"to",
"an",
"attached",
"file",
"or",
"to",
"an",
"attached",
".",
"msg",
"file",
"which"... | train | https://github.com/bbottema/outlook-message-parser/blob/ea7d59da33c8a62dfc2e0aa64d2f8f7c903ccb0e/src/main/java/org/simplejavamail/outlookmessageparser/OutlookMessageParser.java#L564-L596 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/ForkOperatorUtils.java | ForkOperatorUtils.getPropertyNameForBranch | public static String getPropertyNameForBranch(WorkUnitState workUnitState, String key) {
Preconditions.checkNotNull(workUnitState, "Cannot get a property from a null WorkUnit");
Preconditions.checkNotNull(key, "Cannot get a the value for a null key");
if (!workUnitState.contains(ConfigurationKeys.FORK_BRANCH_ID_KEY)) {
return key;
}
return workUnitState.getPropAsInt(ConfigurationKeys.FORK_BRANCH_ID_KEY) >= 0
? key + "." + workUnitState.getPropAsInt(ConfigurationKeys.FORK_BRANCH_ID_KEY) : key;
} | java | public static String getPropertyNameForBranch(WorkUnitState workUnitState, String key) {
Preconditions.checkNotNull(workUnitState, "Cannot get a property from a null WorkUnit");
Preconditions.checkNotNull(key, "Cannot get a the value for a null key");
if (!workUnitState.contains(ConfigurationKeys.FORK_BRANCH_ID_KEY)) {
return key;
}
return workUnitState.getPropAsInt(ConfigurationKeys.FORK_BRANCH_ID_KEY) >= 0
? key + "." + workUnitState.getPropAsInt(ConfigurationKeys.FORK_BRANCH_ID_KEY) : key;
} | [
"public",
"static",
"String",
"getPropertyNameForBranch",
"(",
"WorkUnitState",
"workUnitState",
",",
"String",
"key",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"workUnitState",
",",
"\"Cannot get a property from a null WorkUnit\"",
")",
";",
"Preconditions",
"... | Get a new property key from an original one based on the branch id. The method assumes the branch id specified by
the {@link ConfigurationKeys#FORK_BRANCH_ID_KEY} parameter in the given WorkUnitState. The fork id key specifies
which fork this parameter belongs to. Note this method will only provide the aforementioned functionality for
{@link org.apache.gobblin.converter.Converter}s. To get the same functionality in {@link org.apache.gobblin.writer.DataWriter}s use
the {@link org.apache.gobblin.writer.DataWriterBuilder#forBranch(int)} to construct a writer with a specific branch id.
@param workUnitState contains the fork id key
@param key property key
@return a new property key | [
"Get",
"a",
"new",
"property",
"key",
"from",
"an",
"original",
"one",
"based",
"on",
"the",
"branch",
"id",
".",
"The",
"method",
"assumes",
"the",
"branch",
"id",
"specified",
"by",
"the",
"{",
"@link",
"ConfigurationKeys#FORK_BRANCH_ID_KEY",
"}",
"parameter... | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ForkOperatorUtils.java#L74-L83 |
strator-dev/greenpepper | greenpepper/greenpepper-server/src/main/java/com/greenpepper/server/GreenPepperServerServiceImpl.java | GreenPepperServerServiceImpl.getAllEnvironmentTypes | public List<EnvironmentType> getAllEnvironmentTypes() throws GreenPepperServerException {
try {
sessionService.startSession();
List<EnvironmentType> envTypes = sutDao.getAllEnvironmentTypes();
log.debug("Retrieved All Environment Types number: " + envTypes.size());
return envTypes;
} catch (Exception ex) {
throw handleException(ERROR, ex);
} finally {
sessionService.closeSession();
}
} | java | public List<EnvironmentType> getAllEnvironmentTypes() throws GreenPepperServerException {
try {
sessionService.startSession();
List<EnvironmentType> envTypes = sutDao.getAllEnvironmentTypes();
log.debug("Retrieved All Environment Types number: " + envTypes.size());
return envTypes;
} catch (Exception ex) {
throw handleException(ERROR, ex);
} finally {
sessionService.closeSession();
}
} | [
"public",
"List",
"<",
"EnvironmentType",
">",
"getAllEnvironmentTypes",
"(",
")",
"throws",
"GreenPepperServerException",
"{",
"try",
"{",
"sessionService",
".",
"startSession",
"(",
")",
";",
"List",
"<",
"EnvironmentType",
">",
"envTypes",
"=",
"sutDao",
".",
... | <p>getAllEnvironmentTypes.</p>
@inheritDoc NO NEEDS TO SECURE THIS
@return a {@link java.util.List} object.
@throws com.greenpepper.server.GreenPepperServerException if any. | [
"<p",
">",
"getAllEnvironmentTypes",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/greenpepper-server/src/main/java/com/greenpepper/server/GreenPepperServerServiceImpl.java#L146-L160 |
awslabs/amazon-sqs-java-extended-client-lib | src/main/java/com/amazon/sqs/javamessaging/AmazonSQSExtendedClientBase.java | AmazonSQSExtendedClientBase.deleteMessageBatch | public DeleteMessageBatchResult deleteMessageBatch(String queueUrl, List<DeleteMessageBatchRequestEntry> entries)
throws AmazonServiceException, AmazonClientException {
return amazonSqsToBeExtended.deleteMessageBatch(queueUrl, entries);
} | java | public DeleteMessageBatchResult deleteMessageBatch(String queueUrl, List<DeleteMessageBatchRequestEntry> entries)
throws AmazonServiceException, AmazonClientException {
return amazonSqsToBeExtended.deleteMessageBatch(queueUrl, entries);
} | [
"public",
"DeleteMessageBatchResult",
"deleteMessageBatch",
"(",
"String",
"queueUrl",
",",
"List",
"<",
"DeleteMessageBatchRequestEntry",
">",
"entries",
")",
"throws",
"AmazonServiceException",
",",
"AmazonClientException",
"{",
"return",
"amazonSqsToBeExtended",
".",
"de... | <p>
Deletes up to ten messages from the specified queue. This is a batch
version of DeleteMessage. The result of the delete action on each message
is reported individually in the response.
</p>
<p>
<b>IMPORTANT:</b> Because the batch request can result in a combination
of successful and unsuccessful actions, you should check for batch errors
even when the call returns an HTTP status code of 200.
</p>
<p>
<b>NOTE:</b>Some API actions take lists of parameters. These lists are
specified using the param.n notation. Values of n are integers starting
from 1. For example, a parameter list with two elements looks like this:
</p>
<p>
<code>&Attribute.1=this</code>
</p>
<p>
<code>&Attribute.2=that</code>
</p>
@param queueUrl
The URL of the Amazon SQS queue to take action on.
@param entries
A list of receipt handles for the messages to be deleted.
@return The response from the DeleteMessageBatch service method, as
returned by AmazonSQS.
@throws BatchEntryIdsNotDistinctException
@throws TooManyEntriesInBatchRequestException
@throws InvalidBatchEntryIdException
@throws EmptyBatchRequestException
@throws AmazonClientException
If any internal errors are encountered inside the client
while attempting to make the request or handle the response.
For example if a network connection is not available.
@throws AmazonServiceException
If an error response is returned by AmazonSQS indicating
either a problem with the data in the request, or a server
side issue. | [
"<p",
">",
"Deletes",
"up",
"to",
"ten",
"messages",
"from",
"the",
"specified",
"queue",
".",
"This",
"is",
"a",
"batch",
"version",
"of",
"DeleteMessage",
".",
"The",
"result",
"of",
"the",
"delete",
"action",
"on",
"each",
"message",
"is",
"reported",
... | train | https://github.com/awslabs/amazon-sqs-java-extended-client-lib/blob/df0c6251b99e682d6179938fe784590e662b84ea/src/main/java/com/amazon/sqs/javamessaging/AmazonSQSExtendedClientBase.java#L1768-L1772 |
cdk/cdk | base/core/src/main/java/org/openscience/cdk/tools/manipulator/BondManipulator.java | BondManipulator.getMaximumBondOrder | public static IBond.Order getMaximumBondOrder(IBond.Order firstOrder, IBond.Order secondOrder) {
if (firstOrder == Order.UNSET) {
if (secondOrder == Order.UNSET) throw new IllegalArgumentException("Both bond orders are unset");
return secondOrder;
}
if (secondOrder == Order.UNSET) {
if (firstOrder == Order.UNSET) throw new IllegalArgumentException("Both bond orders are unset");
return firstOrder;
}
if (isHigherOrder(firstOrder, secondOrder))
return firstOrder;
else
return secondOrder;
} | java | public static IBond.Order getMaximumBondOrder(IBond.Order firstOrder, IBond.Order secondOrder) {
if (firstOrder == Order.UNSET) {
if (secondOrder == Order.UNSET) throw new IllegalArgumentException("Both bond orders are unset");
return secondOrder;
}
if (secondOrder == Order.UNSET) {
if (firstOrder == Order.UNSET) throw new IllegalArgumentException("Both bond orders are unset");
return firstOrder;
}
if (isHigherOrder(firstOrder, secondOrder))
return firstOrder;
else
return secondOrder;
} | [
"public",
"static",
"IBond",
".",
"Order",
"getMaximumBondOrder",
"(",
"IBond",
".",
"Order",
"firstOrder",
",",
"IBond",
".",
"Order",
"secondOrder",
")",
"{",
"if",
"(",
"firstOrder",
"==",
"Order",
".",
"UNSET",
")",
"{",
"if",
"(",
"secondOrder",
"==",... | Returns the maximum bond order for the two bond orders.
@param firstOrder first bond order to compare
@param secondOrder second bond order to compare
@return The maximum bond order found | [
"Returns",
"the",
"maximum",
"bond",
"order",
"for",
"the",
"two",
"bond",
"orders",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/core/src/main/java/org/openscience/cdk/tools/manipulator/BondManipulator.java#L247-L261 |
osglworks/java-tool | src/main/java/org/osgl/util/E.java | E.illegalArgumentIf | public static void illegalArgumentIf(boolean tester, String msg, Object... args) {
if (tester) {
throw new IllegalArgumentException(S.fmt(msg, args));
}
} | java | public static void illegalArgumentIf(boolean tester, String msg, Object... args) {
if (tester) {
throw new IllegalArgumentException(S.fmt(msg, args));
}
} | [
"public",
"static",
"void",
"illegalArgumentIf",
"(",
"boolean",
"tester",
",",
"String",
"msg",
",",
"Object",
"...",
"args",
")",
"{",
"if",
"(",
"tester",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"S",
".",
"fmt",
"(",
"msg",
",",
"ar... | Throws out an {@link IllegalArgumentException} with error message specified
if `tester` is `true`.
@param tester
when `true` then throw out the exception.
@param msg
the error message format pattern.
@param args
the error message format arguments. | [
"Throws",
"out",
"an",
"{",
"@link",
"IllegalArgumentException",
"}",
"with",
"error",
"message",
"specified",
"if",
"tester",
"is",
"true",
"."
] | train | https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/util/E.java#L695-L699 |
baratine/baratine | web/src/main/java/com/caucho/v5/health/warning/WarningSystem.java | WarningSystem.sendWarning | public void sendWarning(Object source, Throwable e)
{
try {
e.printStackTrace();
String msg = e.toString();
String s = getClass().getSimpleName() + ": " + e;
// if warning is high-priority then send to high priority handlers first
System.err.println(s);
for (WarningHandler handler : _priorityHandlers) {
try {
handler.warning(source, msg);
} catch (Throwable e1) {
// WarningService must not throw exception
log.log(Level.WARNING, e1.toString(), e1);
}
}
// now send to the all handlers regardless of if its high priority
for (WarningHandler handler : _handlers) {
try {
handler.warning(source, msg);
} catch (Throwable e1) {
// WarningService must not throw exception
log.log(Level.WARNING, e1.toString(), e1);
}
}
log.warning(s);
} catch (Throwable e1) {
// WarningService must not throw exception
log.log(Level.WARNING, e1.toString(), e1);
}
} | java | public void sendWarning(Object source, Throwable e)
{
try {
e.printStackTrace();
String msg = e.toString();
String s = getClass().getSimpleName() + ": " + e;
// if warning is high-priority then send to high priority handlers first
System.err.println(s);
for (WarningHandler handler : _priorityHandlers) {
try {
handler.warning(source, msg);
} catch (Throwable e1) {
// WarningService must not throw exception
log.log(Level.WARNING, e1.toString(), e1);
}
}
// now send to the all handlers regardless of if its high priority
for (WarningHandler handler : _handlers) {
try {
handler.warning(source, msg);
} catch (Throwable e1) {
// WarningService must not throw exception
log.log(Level.WARNING, e1.toString(), e1);
}
}
log.warning(s);
} catch (Throwable e1) {
// WarningService must not throw exception
log.log(Level.WARNING, e1.toString(), e1);
}
} | [
"public",
"void",
"sendWarning",
"(",
"Object",
"source",
",",
"Throwable",
"e",
")",
"{",
"try",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"String",
"msg",
"=",
"e",
".",
"toString",
"(",
")",
";",
"String",
"s",
"=",
"getClass",
"(",
")",
... | Send a warning message to any registered handlers. A high priority warning
only goes to all handlers, high priority first. High priority handlers do
not receive non-high priority warnings.
@param source source of the message, usually you
@param msg test to print or send as an alert
@param isHighPriority set true to send to high priority warning handlers | [
"Send",
"a",
"warning",
"message",
"to",
"any",
"registered",
"handlers",
".",
"A",
"high",
"priority",
"warning",
"only",
"goes",
"to",
"all",
"handlers",
"high",
"priority",
"first",
".",
"High",
"priority",
"handlers",
"do",
"not",
"receive",
"non",
"-",
... | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/web/src/main/java/com/caucho/v5/health/warning/WarningSystem.java#L117-L153 |
rterp/GMapsFX | GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/JavascriptObject.java | JavascriptObject.invokeJavascriptReturnValue | protected <T> T invokeJavascriptReturnValue(String function, Class<T> returnType, Object... args) {
Object returnObject = invokeJavascript(function, args);
if (returnObject != null) {
return (T) returnObject;
} else {
return null;
}
} | java | protected <T> T invokeJavascriptReturnValue(String function, Class<T> returnType, Object... args) {
Object returnObject = invokeJavascript(function, args);
if (returnObject != null) {
return (T) returnObject;
} else {
return null;
}
} | [
"protected",
"<",
"T",
">",
"T",
"invokeJavascriptReturnValue",
"(",
"String",
"function",
",",
"Class",
"<",
"T",
">",
"returnType",
",",
"Object",
"...",
"args",
")",
"{",
"Object",
"returnObject",
"=",
"invokeJavascript",
"(",
"function",
",",
"args",
")"... | Invoke the specified JavaScript function in the JavaScript runtime.
@param <T>
@param function The function to invoke
@param returnType The type of object to return
@param args Any arguments to pass to the function
@return The result of the function. | [
"Invoke",
"the",
"specified",
"JavaScript",
"function",
"in",
"the",
"JavaScript",
"runtime",
"."
] | train | https://github.com/rterp/GMapsFX/blob/4623d3f768e8ad78fc50ee32dd204d236e01059f/GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/JavascriptObject.java#L264-L271 |
kuujo/vertigo | core/src/main/java/net/kuujo/vertigo/Vertigo.java | Vertigo.undeployNetwork | public Vertigo undeployNetwork(String cluster, String name) {
return undeployNetwork(cluster, name, null);
} | java | public Vertigo undeployNetwork(String cluster, String name) {
return undeployNetwork(cluster, name, null);
} | [
"public",
"Vertigo",
"undeployNetwork",
"(",
"String",
"cluster",
",",
"String",
"name",
")",
"{",
"return",
"undeployNetwork",
"(",
"cluster",
",",
"name",
",",
"null",
")",
";",
"}"
] | Undeploys a complete network from the given cluster.<p>
This method does not require a network configuration for undeployment. Vertigo
will load the configuration from the fault-tolerant data store and undeploy
components internally. This allows networks to be undeployed without the network
configuration.
@param cluster The cluster from which to undeploy the network.
@param name The name of the network to undeploy.
@return The Vertigo instance. | [
"Undeploys",
"a",
"complete",
"network",
"from",
"the",
"given",
"cluster",
".",
"<p",
">"
] | train | https://github.com/kuujo/vertigo/blob/c5869dbc5fff89eb5262e83f7a81719b01a5ba6f/core/src/main/java/net/kuujo/vertigo/Vertigo.java#L598-L600 |
ngageoint/geopackage-android-map | geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java | StyleUtils.setFeatureStyle | public static boolean setFeatureStyle(MarkerOptions markerOptions, FeatureStyleExtension featureStyleExtension, FeatureRow featureRow, float density, IconCache iconCache) {
FeatureStyle featureStyle = featureStyleExtension.getFeatureStyle(featureRow);
return setFeatureStyle(markerOptions, featureStyle, density, iconCache);
} | java | public static boolean setFeatureStyle(MarkerOptions markerOptions, FeatureStyleExtension featureStyleExtension, FeatureRow featureRow, float density, IconCache iconCache) {
FeatureStyle featureStyle = featureStyleExtension.getFeatureStyle(featureRow);
return setFeatureStyle(markerOptions, featureStyle, density, iconCache);
} | [
"public",
"static",
"boolean",
"setFeatureStyle",
"(",
"MarkerOptions",
"markerOptions",
",",
"FeatureStyleExtension",
"featureStyleExtension",
",",
"FeatureRow",
"featureRow",
",",
"float",
"density",
",",
"IconCache",
"iconCache",
")",
"{",
"FeatureStyle",
"featureStyle... | Set the feature row style (icon or style) into the marker options
@param markerOptions marker options
@param featureStyleExtension feature style extension
@param featureRow feature row
@param density display density: {@link android.util.DisplayMetrics#density}
@param iconCache icon cache
@return true if icon or style was set into the marker options | [
"Set",
"the",
"feature",
"row",
"style",
"(",
"icon",
"or",
"style",
")",
"into",
"the",
"marker",
"options"
] | train | https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L142-L147 |
kite-sdk/kite | kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/manager/DefaultSchemaManager.java | DefaultSchemaManager.refreshManagedSchemaCache | @Override
public void refreshManagedSchemaCache(String tableName, String entityName) {
ManagedSchema managedSchema = managedSchemaDao.getManagedSchema(tableName,
entityName);
if (managedSchema != null) {
getManagedSchemaMap().put(
getManagedSchemaMapKey(managedSchema.getTable(),
managedSchema.getName()), managedSchema);
}
} | java | @Override
public void refreshManagedSchemaCache(String tableName, String entityName) {
ManagedSchema managedSchema = managedSchemaDao.getManagedSchema(tableName,
entityName);
if (managedSchema != null) {
getManagedSchemaMap().put(
getManagedSchemaMapKey(managedSchema.getTable(),
managedSchema.getName()), managedSchema);
}
} | [
"@",
"Override",
"public",
"void",
"refreshManagedSchemaCache",
"(",
"String",
"tableName",
",",
"String",
"entityName",
")",
"{",
"ManagedSchema",
"managedSchema",
"=",
"managedSchemaDao",
".",
"getManagedSchema",
"(",
"tableName",
",",
"entityName",
")",
";",
"if"... | Update the managedSchemaMap for the entry defined by tableName and
entityName.
@param tableName
The table name of the managed schema
@param entityName
The entity name of the managed schema | [
"Update",
"the",
"managedSchemaMap",
"for",
"the",
"entry",
"defined",
"by",
"tableName",
"and",
"entityName",
"."
] | train | https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/manager/DefaultSchemaManager.java#L344-L353 |
diirt/util | src/main/java/org/epics/util/stats/Ranges.java | Ranges.absRange | public static Range absRange(Range range) {
if (range.getMinimum().doubleValue() >= 0 && range.getMaximum().doubleValue() >= 0) {
return range;
} else if (range.getMinimum().doubleValue() < 0 && range.getMaximum().doubleValue() < 0) {
return range(- range.getMaximum().doubleValue(), - range.getMinimum().doubleValue());
} else {
return range(0, Math.max(range.getMinimum().doubleValue(), range.getMaximum().doubleValue()));
}
} | java | public static Range absRange(Range range) {
if (range.getMinimum().doubleValue() >= 0 && range.getMaximum().doubleValue() >= 0) {
return range;
} else if (range.getMinimum().doubleValue() < 0 && range.getMaximum().doubleValue() < 0) {
return range(- range.getMaximum().doubleValue(), - range.getMinimum().doubleValue());
} else {
return range(0, Math.max(range.getMinimum().doubleValue(), range.getMaximum().doubleValue()));
}
} | [
"public",
"static",
"Range",
"absRange",
"(",
"Range",
"range",
")",
"{",
"if",
"(",
"range",
".",
"getMinimum",
"(",
")",
".",
"doubleValue",
"(",
")",
">=",
"0",
"&&",
"range",
".",
"getMaximum",
"(",
")",
".",
"doubleValue",
"(",
")",
">=",
"0",
... | Returns the range of the absolute values within the range.
<p>
If the range is all positive, it returns the same range.
@param range a range
@return the range of the absolute values | [
"Returns",
"the",
"range",
"of",
"the",
"absolute",
"values",
"within",
"the",
"range",
".",
"<p",
">",
"If",
"the",
"range",
"is",
"all",
"positive",
"it",
"returns",
"the",
"same",
"range",
"."
] | train | https://github.com/diirt/util/blob/24aca0a173a635aaf0b78d213a3fee8d4f91c077/src/main/java/org/epics/util/stats/Ranges.java#L22-L30 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java | JobsImpl.listAsync | public ServiceFuture<List<CloudJob>> listAsync(final JobListOptions jobListOptions, final ListOperationCallback<CloudJob> serviceCallback) {
return AzureServiceFuture.fromHeaderPageResponse(
listSinglePageAsync(jobListOptions),
new Func1<String, Observable<ServiceResponseWithHeaders<Page<CloudJob>, JobListHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<CloudJob>, JobListHeaders>> call(String nextPageLink) {
JobListNextOptions jobListNextOptions = null;
if (jobListOptions != null) {
jobListNextOptions = new JobListNextOptions();
jobListNextOptions.withClientRequestId(jobListOptions.clientRequestId());
jobListNextOptions.withReturnClientRequestId(jobListOptions.returnClientRequestId());
jobListNextOptions.withOcpDate(jobListOptions.ocpDate());
}
return listNextSinglePageAsync(nextPageLink, jobListNextOptions);
}
},
serviceCallback);
} | java | public ServiceFuture<List<CloudJob>> listAsync(final JobListOptions jobListOptions, final ListOperationCallback<CloudJob> serviceCallback) {
return AzureServiceFuture.fromHeaderPageResponse(
listSinglePageAsync(jobListOptions),
new Func1<String, Observable<ServiceResponseWithHeaders<Page<CloudJob>, JobListHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<CloudJob>, JobListHeaders>> call(String nextPageLink) {
JobListNextOptions jobListNextOptions = null;
if (jobListOptions != null) {
jobListNextOptions = new JobListNextOptions();
jobListNextOptions.withClientRequestId(jobListOptions.clientRequestId());
jobListNextOptions.withReturnClientRequestId(jobListOptions.returnClientRequestId());
jobListNextOptions.withOcpDate(jobListOptions.ocpDate());
}
return listNextSinglePageAsync(nextPageLink, jobListNextOptions);
}
},
serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"List",
"<",
"CloudJob",
">",
">",
"listAsync",
"(",
"final",
"JobListOptions",
"jobListOptions",
",",
"final",
"ListOperationCallback",
"<",
"CloudJob",
">",
"serviceCallback",
")",
"{",
"return",
"AzureServiceFuture",
".",
"fromHead... | Lists all of the jobs in the specified account.
@param jobListOptions Additional parameters for the operation
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Lists",
"all",
"of",
"the",
"jobs",
"in",
"the",
"specified",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java#L2366-L2383 |
pressgang-ccms/PressGangCCMSBuilder | src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookXMLPreProcessor.java | DocBookXMLPreProcessor.processSeeAlsoInjections | public void processSeeAlsoInjections(final SpecNodeWithRelationships specNode, final Document doc, final boolean useFixedUrls) {
processSeeAlsoInjections(specNode, doc, doc.getDocumentElement(), useFixedUrls);
} | java | public void processSeeAlsoInjections(final SpecNodeWithRelationships specNode, final Document doc, final boolean useFixedUrls) {
processSeeAlsoInjections(specNode, doc, doc.getDocumentElement(), useFixedUrls);
} | [
"public",
"void",
"processSeeAlsoInjections",
"(",
"final",
"SpecNodeWithRelationships",
"specNode",
",",
"final",
"Document",
"doc",
",",
"final",
"boolean",
"useFixedUrls",
")",
"{",
"processSeeAlsoInjections",
"(",
"specNode",
",",
"doc",
",",
"doc",
".",
"getDoc... | Insert a itemized list into the end of the topic with any RELATED relationships that exists for the Spec Topic. The title
for the list is set to "See Also:".
@param specNode The content spec node to process the injection for.
@param doc The DOM Document object that represents the topics XML.
@param useFixedUrls Whether fixed URL's should be used in the injected links. | [
"Insert",
"a",
"itemized",
"list",
"into",
"the",
"end",
"of",
"the",
"topic",
"with",
"any",
"RELATED",
"relationships",
"that",
"exists",
"for",
"the",
"Spec",
"Topic",
".",
"The",
"title",
"for",
"the",
"list",
"is",
"set",
"to",
"See",
"Also",
":",
... | train | https://github.com/pressgang-ccms/PressGangCCMSBuilder/blob/5436d36ba1b3c5baa246b270e5fc350e6778bce8/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookXMLPreProcessor.java#L954-L956 |
OpenLiberty/open-liberty | dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/ProbeManagerImpl.java | ProbeManagerImpl.addProbesByListener | synchronized void addProbesByListener(ProbeListener listener, Collection<ProbeImpl> probes) {
Set<ProbeImpl> listenerProbes = probesByListener.get(listener);
if (listenerProbes == null) {
listenerProbes = new HashSet<ProbeImpl>();
probesByListener.put(listener, listenerProbes);
}
listenerProbes.addAll(probes);
} | java | synchronized void addProbesByListener(ProbeListener listener, Collection<ProbeImpl> probes) {
Set<ProbeImpl> listenerProbes = probesByListener.get(listener);
if (listenerProbes == null) {
listenerProbes = new HashSet<ProbeImpl>();
probesByListener.put(listener, listenerProbes);
}
listenerProbes.addAll(probes);
} | [
"synchronized",
"void",
"addProbesByListener",
"(",
"ProbeListener",
"listener",
",",
"Collection",
"<",
"ProbeImpl",
">",
"probes",
")",
"{",
"Set",
"<",
"ProbeImpl",
">",
"listenerProbes",
"=",
"probesByListener",
".",
"get",
"(",
"listener",
")",
";",
"if",
... | Associate the specified collection of probes with the specified listener.
@param listener the listener that probes are fired to
@param probes the probes fired to the listener | [
"Associate",
"the",
"specified",
"collection",
"of",
"probes",
"with",
"the",
"specified",
"listener",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/ProbeManagerImpl.java#L749-L756 |
alkacon/opencms-core | src-gwt/org/opencms/ade/galleries/client/ui/CmsCategoriesTab.java | CmsCategoriesTab.updateContentTree | @SuppressWarnings("unchecked")
public void updateContentTree(List<CmsCategoryTreeEntry> treeEntries, List<String> selectedCategories) {
clearList();
if (m_categories == null) {
m_categories = new HashMap<String, CmsCategoryBean>();
}
if ((treeEntries != null) && !treeEntries.isEmpty()) {
// add the first level and children
for (CmsCategoryTreeEntry category : treeEntries) {
// set the category tree item and add to list
CmsTreeItem treeItem = buildTreeItem(category, selectedCategories);
treeItem.setTree((CmsTree<CmsTreeItem>)m_scrollList);
addChildren(treeItem, category.getChildren(), selectedCategories);
addWidgetToList(treeItem);
treeItem.setOpen(true, false);
}
} else {
showIsEmptyLabel();
}
} | java | @SuppressWarnings("unchecked")
public void updateContentTree(List<CmsCategoryTreeEntry> treeEntries, List<String> selectedCategories) {
clearList();
if (m_categories == null) {
m_categories = new HashMap<String, CmsCategoryBean>();
}
if ((treeEntries != null) && !treeEntries.isEmpty()) {
// add the first level and children
for (CmsCategoryTreeEntry category : treeEntries) {
// set the category tree item and add to list
CmsTreeItem treeItem = buildTreeItem(category, selectedCategories);
treeItem.setTree((CmsTree<CmsTreeItem>)m_scrollList);
addChildren(treeItem, category.getChildren(), selectedCategories);
addWidgetToList(treeItem);
treeItem.setOpen(true, false);
}
} else {
showIsEmptyLabel();
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"void",
"updateContentTree",
"(",
"List",
"<",
"CmsCategoryTreeEntry",
">",
"treeEntries",
",",
"List",
"<",
"String",
">",
"selectedCategories",
")",
"{",
"clearList",
"(",
")",
";",
"if",
"(",
"m_... | Updates the content of th categories tree.<p>
@param treeEntries the root category entry
@param selectedCategories the categories to select after update | [
"Updates",
"the",
"content",
"of",
"th",
"categories",
"tree",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/ui/CmsCategoriesTab.java#L255-L275 |
rundeck/rundeck | core/src/main/java/com/dtolabs/utils/Mapper.java | Mapper.zip | public static Map zip(List keys, List values) {
return zip(keys, values, false);
} | java | public static Map zip(List keys, List values) {
return zip(keys, values, false);
} | [
"public",
"static",
"Map",
"zip",
"(",
"List",
"keys",
",",
"List",
"values",
")",
"{",
"return",
"zip",
"(",
"keys",
",",
"values",
",",
"false",
")",
";",
"}"
] | Creates a map where the object at index N from the first List is the key for the object at index N of the second
List. <br> By default discards both key and value if either one is null.
@param keys List of keys
@param values List of values
@return map | [
"Creates",
"a",
"map",
"where",
"the",
"object",
"at",
"index",
"N",
"from",
"the",
"first",
"List",
"is",
"the",
"key",
"for",
"the",
"object",
"at",
"index",
"N",
"of",
"the",
"second",
"List",
".",
"<br",
">",
"By",
"default",
"discards",
"both",
... | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/utils/Mapper.java#L166-L168 |
mikepenz/FastAdapter | library-core/src/main/java/com/mikepenz/fastadapter/FastAdapter.java | FastAdapter.getHolderAdapterItem | @SuppressWarnings("unchecked")
public static <Item extends IItem> Item getHolderAdapterItem(@Nullable RecyclerView.ViewHolder holder, int position) {
if (holder != null) {
Object tag = holder.itemView.getTag(com.mikepenz.fastadapter.R.id.fastadapter_item_adapter);
if (tag instanceof FastAdapter) {
return (Item) ((FastAdapter) tag).getItem(position);
}
}
return null;
} | java | @SuppressWarnings("unchecked")
public static <Item extends IItem> Item getHolderAdapterItem(@Nullable RecyclerView.ViewHolder holder, int position) {
if (holder != null) {
Object tag = holder.itemView.getTag(com.mikepenz.fastadapter.R.id.fastadapter_item_adapter);
if (tag instanceof FastAdapter) {
return (Item) ((FastAdapter) tag).getItem(position);
}
}
return null;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"Item",
"extends",
"IItem",
">",
"Item",
"getHolderAdapterItem",
"(",
"@",
"Nullable",
"RecyclerView",
".",
"ViewHolder",
"holder",
",",
"int",
"position",
")",
"{",
"if",
"(",
"holde... | convenient helper method to get the Item from a holder
@param holder the ViewHolder for which we want to retrieve the item
@param position the position for which we want to retrieve the item
@return the Item found for the given position and that ViewHolder | [
"convenient",
"helper",
"method",
"to",
"get",
"the",
"Item",
"from",
"a",
"holder"
] | train | https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-core/src/main/java/com/mikepenz/fastadapter/FastAdapter.java#L1403-L1412 |
jamesagnew/hapi-fhir | hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/index/DaoSearchParamSynchronizer.java | DaoSearchParamSynchronizer.tryToReuseIndexEntities | private <T extends BaseResourceIndex> void tryToReuseIndexEntities(List<T> theIndexesToRemove, List<T> theIndexesToAdd) {
for (int addIndex = 0; addIndex < theIndexesToAdd.size(); addIndex++) {
// If there are no more rows to remove, there's nothing we can reuse
if (theIndexesToRemove.isEmpty()) {
break;
}
T targetEntity = theIndexesToAdd.get(addIndex);
if (targetEntity.getId() != null) {
continue;
}
// Take a row we were going to remove, and repurpose its ID
T entityToReuse = theIndexesToRemove.remove(theIndexesToRemove.size() - 1);
targetEntity.setId(entityToReuse.getId());
}
} | java | private <T extends BaseResourceIndex> void tryToReuseIndexEntities(List<T> theIndexesToRemove, List<T> theIndexesToAdd) {
for (int addIndex = 0; addIndex < theIndexesToAdd.size(); addIndex++) {
// If there are no more rows to remove, there's nothing we can reuse
if (theIndexesToRemove.isEmpty()) {
break;
}
T targetEntity = theIndexesToAdd.get(addIndex);
if (targetEntity.getId() != null) {
continue;
}
// Take a row we were going to remove, and repurpose its ID
T entityToReuse = theIndexesToRemove.remove(theIndexesToRemove.size() - 1);
targetEntity.setId(entityToReuse.getId());
}
} | [
"private",
"<",
"T",
"extends",
"BaseResourceIndex",
">",
"void",
"tryToReuseIndexEntities",
"(",
"List",
"<",
"T",
">",
"theIndexesToRemove",
",",
"List",
"<",
"T",
">",
"theIndexesToAdd",
")",
"{",
"for",
"(",
"int",
"addIndex",
"=",
"0",
";",
"addIndex",
... | The logic here is that often times when we update a resource we are dropping
one index row and adding another. This method tries to reuse rows that would otherwise
have been deleted by updating them with the contents of rows that would have
otherwise been added. In other words, we're trying to replace
"one delete + one insert" with "one update"
@param theIndexesToRemove The rows that would be removed
@param theIndexesToAdd The rows that would be added | [
"The",
"logic",
"here",
"is",
"that",
"often",
"times",
"when",
"we",
"update",
"a",
"resource",
"we",
"are",
"dropping",
"one",
"index",
"row",
"and",
"adding",
"another",
".",
"This",
"method",
"tries",
"to",
"reuse",
"rows",
"that",
"would",
"otherwise"... | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/index/DaoSearchParamSynchronizer.java#L83-L100 |
jtrfp/javamod | src/main/java/de/quippy/javamod/multimedia/mp3/id3/MP3FileID3Controller.java | MP3FileID3Controller.setGenre | public void setGenre(String genre, int type)
{
if (allow(type&ID3V1))
{
id3v1.setGenreString(genre);
}
if (allow(type&ID3V2))
{
id3v2.setTextFrame(ID3v2Frames.CONTENT_TYPE, genre);
}
} | java | public void setGenre(String genre, int type)
{
if (allow(type&ID3V1))
{
id3v1.setGenreString(genre);
}
if (allow(type&ID3V2))
{
id3v2.setTextFrame(ID3v2Frames.CONTENT_TYPE, genre);
}
} | [
"public",
"void",
"setGenre",
"(",
"String",
"genre",
",",
"int",
"type",
")",
"{",
"if",
"(",
"allow",
"(",
"type",
"&",
"ID3V1",
")",
")",
"{",
"id3v1",
".",
"setGenreString",
"(",
"genre",
")",
";",
"}",
"if",
"(",
"allow",
"(",
"type",
"&",
"... | Set the genre of this mp3.
@param genre the genre of the mp3 | [
"Set",
"the",
"genre",
"of",
"this",
"mp3",
"."
] | train | https://github.com/jtrfp/javamod/blob/cda4fe943a589dc49415f4413453e2eece72076a/src/main/java/de/quippy/javamod/multimedia/mp3/id3/MP3FileID3Controller.java#L227-L237 |
haifengl/smile | math/src/main/java/smile/math/Math.java | Math.JensenShannonDivergence | public static double JensenShannonDivergence(SparseArray x, SparseArray y) {
if (x.isEmpty()) {
throw new IllegalArgumentException("List x is empty.");
}
if (y.isEmpty()) {
throw new IllegalArgumentException("List y is empty.");
}
Iterator<SparseArray.Entry> iterX = x.iterator();
Iterator<SparseArray.Entry> iterY = y.iterator();
SparseArray.Entry a = iterX.hasNext() ? iterX.next() : null;
SparseArray.Entry b = iterY.hasNext() ? iterY.next() : null;
double js = 0.0;
while (a != null && b != null) {
if (a.i < b.i) {
double mi = a.x / 2;
js += a.x * Math.log(a.x / mi);
a = iterX.hasNext() ? iterX.next() : null;
} else if (a.i > b.i) {
double mi = b.x / 2;
js += b.x * Math.log(b.x / mi);
b = iterY.hasNext() ? iterY.next() : null;
} else {
double mi = (a.x + b.x) / 2;
js += a.x * Math.log(a.x / mi) + b.x * Math.log(b.x / mi);
a = iterX.hasNext() ? iterX.next() : null;
b = iterY.hasNext() ? iterY.next() : null;
}
}
return js / 2;
} | java | public static double JensenShannonDivergence(SparseArray x, SparseArray y) {
if (x.isEmpty()) {
throw new IllegalArgumentException("List x is empty.");
}
if (y.isEmpty()) {
throw new IllegalArgumentException("List y is empty.");
}
Iterator<SparseArray.Entry> iterX = x.iterator();
Iterator<SparseArray.Entry> iterY = y.iterator();
SparseArray.Entry a = iterX.hasNext() ? iterX.next() : null;
SparseArray.Entry b = iterY.hasNext() ? iterY.next() : null;
double js = 0.0;
while (a != null && b != null) {
if (a.i < b.i) {
double mi = a.x / 2;
js += a.x * Math.log(a.x / mi);
a = iterX.hasNext() ? iterX.next() : null;
} else if (a.i > b.i) {
double mi = b.x / 2;
js += b.x * Math.log(b.x / mi);
b = iterY.hasNext() ? iterY.next() : null;
} else {
double mi = (a.x + b.x) / 2;
js += a.x * Math.log(a.x / mi) + b.x * Math.log(b.x / mi);
a = iterX.hasNext() ? iterX.next() : null;
b = iterY.hasNext() ? iterY.next() : null;
}
}
return js / 2;
} | [
"public",
"static",
"double",
"JensenShannonDivergence",
"(",
"SparseArray",
"x",
",",
"SparseArray",
"y",
")",
"{",
"if",
"(",
"x",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"List x is empty.\"",
")",
";",
"}",
"... | Jensen-Shannon divergence JS(P||Q) = (KL(P||M) + KL(Q||M)) / 2, where
M = (P+Q)/2. The Jensen-Shannon divergence is a popular
method of measuring the similarity between two probability distributions.
It is also known as information radius or total divergence to the average.
It is based on the Kullback-Leibler divergence, with the difference that
it is always a finite value. The square root of the Jensen-Shannon divergence
is a metric. | [
"Jensen",
"-",
"Shannon",
"divergence",
"JS",
"(",
"P||Q",
")",
"=",
"(",
"KL",
"(",
"P||M",
")",
"+",
"KL",
"(",
"Q||M",
"))",
"/",
"2",
"where",
"M",
"=",
"(",
"P",
"+",
"Q",
")",
"/",
"2",
".",
"The",
"Jensen",
"-",
"Shannon",
"divergence",
... | train | https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/Math.java#L2413-L2449 |
googolmo/OkVolley | sample/src/main/java/im/amomo/volley/sample/DrawerFragment.java | DrawerFragment.setUp | public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
@Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
} | java | public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
@Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
} | [
"public",
"void",
"setUp",
"(",
"int",
"fragmentId",
",",
"DrawerLayout",
"drawerLayout",
")",
"{",
"mFragmentContainerView",
"=",
"getActivity",
"(",
")",
".",
"findViewById",
"(",
"fragmentId",
")",
";",
"mDrawerLayout",
"=",
"drawerLayout",
";",
"// set a custo... | Users of this fragment must call this method to set up the navigation drawer interactions.
@param fragmentId The android:id of this fragment in its activity's layout.
@param drawerLayout The DrawerLayout containing this fragment's UI. | [
"Users",
"of",
"this",
"fragment",
"must",
"call",
"this",
"method",
"to",
"set",
"up",
"the",
"navigation",
"drawer",
"interactions",
"."
] | train | https://github.com/googolmo/OkVolley/blob/5c41df7cf1a8156c85e179a3c4af8a1c1485ffec/sample/src/main/java/im/amomo/volley/sample/DrawerFragment.java#L87-L138 |
crawljax/crawljax | core/src/main/java/com/crawljax/core/state/StateMachine.java | StateMachine.addStateToCurrentState | private StateVertex addStateToCurrentState(StateVertex newState, Eventable eventable) {
LOGGER.debug("addStateToCurrentState currentState: {} newState {}",
currentState.getName(), newState.getName());
// Add the state to the stateFlowGraph. Store the result
StateVertex cloneState = stateFlowGraph.putIfAbsent(newState);
// Is there a clone detected?
if (cloneState != null) {
LOGGER.info("CLONE State detected: {} and {} are the same.", newState.getName(),
cloneState.getName());
LOGGER.debug("CLONE CURRENT STATE: {}", currentState.getName());
LOGGER.debug("CLONE STATE: {}", cloneState.getName());
LOGGER.debug("CLONE CLICKABLE: {}", eventable);
boolean added = stateFlowGraph.addEdge(currentState, cloneState, eventable);
if (!added) {
LOGGER.debug("Clone edge !! Need to fix the crawlPath??");
}
} else {
stateFlowGraph.addEdge(currentState, newState, eventable);
LOGGER.info("State {} added to the StateMachine.", newState.getName());
}
return cloneState;
} | java | private StateVertex addStateToCurrentState(StateVertex newState, Eventable eventable) {
LOGGER.debug("addStateToCurrentState currentState: {} newState {}",
currentState.getName(), newState.getName());
// Add the state to the stateFlowGraph. Store the result
StateVertex cloneState = stateFlowGraph.putIfAbsent(newState);
// Is there a clone detected?
if (cloneState != null) {
LOGGER.info("CLONE State detected: {} and {} are the same.", newState.getName(),
cloneState.getName());
LOGGER.debug("CLONE CURRENT STATE: {}", currentState.getName());
LOGGER.debug("CLONE STATE: {}", cloneState.getName());
LOGGER.debug("CLONE CLICKABLE: {}", eventable);
boolean added = stateFlowGraph.addEdge(currentState, cloneState, eventable);
if (!added) {
LOGGER.debug("Clone edge !! Need to fix the crawlPath??");
}
} else {
stateFlowGraph.addEdge(currentState, newState, eventable);
LOGGER.info("State {} added to the StateMachine.", newState.getName());
}
return cloneState;
} | [
"private",
"StateVertex",
"addStateToCurrentState",
"(",
"StateVertex",
"newState",
",",
"Eventable",
"eventable",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"addStateToCurrentState currentState: {} newState {}\"",
",",
"currentState",
".",
"getName",
"(",
")",
",",
"newS... | Adds the newState and the edge between the currentState and the newState on the SFG.
@param newState the new state.
@param eventable the clickable causing the new state.
@return the clone state iff newState is a clone, else returns null | [
"Adds",
"the",
"newState",
"and",
"the",
"edge",
"between",
"the",
"currentState",
"and",
"the",
"newState",
"on",
"the",
"SFG",
"."
] | train | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/state/StateMachine.java#L97-L121 |
mapbox/mapbox-navigation-android | libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/MapboxOfflineRouter.java | MapboxOfflineRouter.removeTiles | public void removeTiles(String version, BoundingBox boundingBox, OnOfflineTilesRemovedCallback callback) {
offlineNavigator.removeTiles(new File(tilePath, version).getAbsolutePath(), boundingBox.southwest(),
boundingBox.northeast(), callback);
} | java | public void removeTiles(String version, BoundingBox boundingBox, OnOfflineTilesRemovedCallback callback) {
offlineNavigator.removeTiles(new File(tilePath, version).getAbsolutePath(), boundingBox.southwest(),
boundingBox.northeast(), callback);
} | [
"public",
"void",
"removeTiles",
"(",
"String",
"version",
",",
"BoundingBox",
"boundingBox",
",",
"OnOfflineTilesRemovedCallback",
"callback",
")",
"{",
"offlineNavigator",
".",
"removeTiles",
"(",
"new",
"File",
"(",
"tilePath",
",",
"version",
")",
".",
"getAbs... | Removes tiles within / intersected by a bounding box
<p>
Note that calling {@link MapboxOfflineRouter#findRoute(OfflineRoute, OnOfflineRouteFoundCallback)} while
{@link MapboxOfflineRouter#removeTiles(String, BoundingBox, OnOfflineTilesRemovedCallback)} could lead
to undefine behavior
</p>
@param version version of offline tiles to use
@param boundingBox bounding box within which routing tiles should be removed
@param callback a callback that will be fired when the routing tiles have been removed completely | [
"Removes",
"tiles",
"within",
"/",
"intersected",
"by",
"a",
"bounding",
"box",
"<p",
">",
"Note",
"that",
"calling",
"{",
"@link",
"MapboxOfflineRouter#findRoute",
"(",
"OfflineRoute",
"OnOfflineRouteFoundCallback",
")",
"}",
"while",
"{",
"@link",
"MapboxOfflineRo... | train | https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/MapboxOfflineRouter.java#L104-L107 |
gallandarakhneorg/afc | core/vmutils/src/main/java/org/arakhne/afc/vmutil/asserts/AssertMessages.java | AssertMessages.invalidTrueValue | @Pure
@Inline(value = "AssertMessages.invalidTrueValue(0, $1)", imported = {AssertMessages.class})
public static String invalidTrueValue(String functionName) {
return invalidTrueValue(0, functionName);
} | java | @Pure
@Inline(value = "AssertMessages.invalidTrueValue(0, $1)", imported = {AssertMessages.class})
public static String invalidTrueValue(String functionName) {
return invalidTrueValue(0, functionName);
} | [
"@",
"Pure",
"@",
"Inline",
"(",
"value",
"=",
"\"AssertMessages.invalidTrueValue(0, $1)\"",
",",
"imported",
"=",
"{",
"AssertMessages",
".",
"class",
"}",
")",
"public",
"static",
"String",
"invalidTrueValue",
"(",
"String",
"functionName",
")",
"{",
"return",
... | The value of first Parameter must be <code>false</code>.
@param functionName the name of the function that should reply <code>false</code>.
@return the error message. | [
"The",
"value",
"of",
"first",
"Parameter",
"must",
"be",
"<code",
">",
"false<",
"/",
"code",
">",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/vmutils/src/main/java/org/arakhne/afc/vmutil/asserts/AssertMessages.java#L93-L97 |
apache/flink | flink-core/src/main/java/org/apache/flink/util/Preconditions.java | Preconditions.checkElementIndex | public static void checkElementIndex(int index, int size, @Nullable String errorMessage) {
checkArgument(size >= 0, "Size was negative.");
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(String.valueOf(errorMessage) + " Index: " + index + ", Size: " + size);
}
} | java | public static void checkElementIndex(int index, int size, @Nullable String errorMessage) {
checkArgument(size >= 0, "Size was negative.");
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(String.valueOf(errorMessage) + " Index: " + index + ", Size: " + size);
}
} | [
"public",
"static",
"void",
"checkElementIndex",
"(",
"int",
"index",
",",
"int",
"size",
",",
"@",
"Nullable",
"String",
"errorMessage",
")",
"{",
"checkArgument",
"(",
"size",
">=",
"0",
",",
"\"Size was negative.\"",
")",
";",
"if",
"(",
"index",
"<",
"... | Ensures that the given index is valid for an array, list or string of the given size.
@param index index to check
@param size size of the array, list or string
@param errorMessage The message for the {@code IndexOutOfBoundsException} that is thrown if the check fails.
@throws IllegalArgumentException Thrown, if size is negative.
@throws IndexOutOfBoundsException Thrown, if the index negative or greater than or equal to size | [
"Ensures",
"that",
"the",
"given",
"index",
"is",
"valid",
"for",
"an",
"array",
"list",
"or",
"string",
"of",
"the",
"given",
"size",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/Preconditions.java#L247-L252 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/CountersTable.java | CountersTable.appendBtoFList | void appendBtoFList(NodeSetDTM flist, NodeSetDTM blist)
{
int n = blist.size();
for (int i = (n - 1); i >= 0; i--)
{
flist.addElement(blist.item(i));
}
} | java | void appendBtoFList(NodeSetDTM flist, NodeSetDTM blist)
{
int n = blist.size();
for (int i = (n - 1); i >= 0; i--)
{
flist.addElement(blist.item(i));
}
} | [
"void",
"appendBtoFList",
"(",
"NodeSetDTM",
"flist",
",",
"NodeSetDTM",
"blist",
")",
"{",
"int",
"n",
"=",
"blist",
".",
"size",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"(",
"n",
"-",
"1",
")",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
... | Add a list of counted nodes that were built in backwards document
order, or a list of counted nodes that are in forwards document
order.
@param flist Vector of nodes built in forwards document order
@param blist Vector of nodes built in backwards document order | [
"Add",
"a",
"list",
"of",
"counted",
"nodes",
"that",
"were",
"built",
"in",
"backwards",
"document",
"order",
"or",
"a",
"list",
"of",
"counted",
"nodes",
"that",
"are",
"in",
"forwards",
"document",
"order",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/CountersTable.java#L98-L107 |
Azure/azure-sdk-for-java | logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountAssembliesInner.java | IntegrationAccountAssembliesInner.createOrUpdate | public AssemblyDefinitionInner createOrUpdate(String resourceGroupName, String integrationAccountName, String assemblyArtifactName, AssemblyDefinitionInner assemblyArtifact) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, assemblyArtifactName, assemblyArtifact).toBlocking().single().body();
} | java | public AssemblyDefinitionInner createOrUpdate(String resourceGroupName, String integrationAccountName, String assemblyArtifactName, AssemblyDefinitionInner assemblyArtifact) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, assemblyArtifactName, assemblyArtifact).toBlocking().single().body();
} | [
"public",
"AssemblyDefinitionInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"integrationAccountName",
",",
"String",
"assemblyArtifactName",
",",
"AssemblyDefinitionInner",
"assemblyArtifact",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsy... | Create or update an assembly for an integration account.
@param resourceGroupName The resource group name.
@param integrationAccountName The integration account name.
@param assemblyArtifactName The assembly artifact name.
@param assemblyArtifact The assembly artifact.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the AssemblyDefinitionInner object if successful. | [
"Create",
"or",
"update",
"an",
"assembly",
"for",
"an",
"integration",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountAssembliesInner.java#L278-L280 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/db/KeyArea.java | KeyArea.addSortParams | public String addSortParams(boolean bIncludeFileName, boolean bForceUniqueKey)
{
String strSort = DBConstants.BLANK;
int iKeyFieldCount = this.getKeyFields(bForceUniqueKey, false);
for (int iKeyFieldSeq = DBConstants.MAIN_KEY_FIELD; iKeyFieldSeq < iKeyFieldCount; iKeyFieldSeq++)
{
KeyField keyField = this.getKeyField(iKeyFieldSeq, bForceUniqueKey);
BaseField field = keyField.getField(DBConstants.FILE_KEY_AREA);
if (strSort.length() > 0)
strSort += ",";
strSort += field.getFieldName(true, bIncludeFileName);
if (keyField.getKeyOrder() == DBConstants.DESCENDING)
strSort += " DESC"; // Descending
}
if (strSort.length() > 0)
strSort = " ORDER BY " + strSort;
return strSort;
} | java | public String addSortParams(boolean bIncludeFileName, boolean bForceUniqueKey)
{
String strSort = DBConstants.BLANK;
int iKeyFieldCount = this.getKeyFields(bForceUniqueKey, false);
for (int iKeyFieldSeq = DBConstants.MAIN_KEY_FIELD; iKeyFieldSeq < iKeyFieldCount; iKeyFieldSeq++)
{
KeyField keyField = this.getKeyField(iKeyFieldSeq, bForceUniqueKey);
BaseField field = keyField.getField(DBConstants.FILE_KEY_AREA);
if (strSort.length() > 0)
strSort += ",";
strSort += field.getFieldName(true, bIncludeFileName);
if (keyField.getKeyOrder() == DBConstants.DESCENDING)
strSort += " DESC"; // Descending
}
if (strSort.length() > 0)
strSort = " ORDER BY " + strSort;
return strSort;
} | [
"public",
"String",
"addSortParams",
"(",
"boolean",
"bIncludeFileName",
",",
"boolean",
"bForceUniqueKey",
")",
"{",
"String",
"strSort",
"=",
"DBConstants",
".",
"BLANK",
";",
"int",
"iKeyFieldCount",
"=",
"this",
".",
"getKeyFields",
"(",
"bForceUniqueKey",
","... | Setup the SQL Sort String.
@param bIncludeFileName If true, include the filename with the fieldname in the string.
@param bForceUniqueKey If params must be unique, if they aren't, add the unique key to the end.
@return The SQL sort string. | [
"Setup",
"the",
"SQL",
"Sort",
"String",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/KeyArea.java#L236-L253 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPTextWriter.java | JBBPTextWriter.Obj | public JBBPTextWriter Obj(final int objId, final Object[] array, int off, int len) throws IOException {
while (len-- > 0) {
this.Obj(objId, array[off++]);
}
return this;
} | java | public JBBPTextWriter Obj(final int objId, final Object[] array, int off, int len) throws IOException {
while (len-- > 0) {
this.Obj(objId, array[off++]);
}
return this;
} | [
"public",
"JBBPTextWriter",
"Obj",
"(",
"final",
"int",
"objId",
",",
"final",
"Object",
"[",
"]",
"array",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"while",
"(",
"len",
"--",
">",
"0",
")",
"{",
"this",
".",
"Obj",
... | Print objects from array.
@param objId object id which will be provided to a converter as extra info
@param array array of objects, must not be null
@param off offset to the first element to be printed
@param len number of elements to be printed
@return the context
@throws IOException it will be thrown for transport errors | [
"Print",
"objects",
"from",
"array",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPTextWriter.java#L1305-L1310 |
UrielCh/ovh-java-sdk | ovh-java-sdk-store/src/main/java/net/minidev/ovh/api/ApiOvhStore.java | ApiOvhStore.partner_partnerId_DELETE | public String partner_partnerId_DELETE(String partnerId) throws IOException {
String qPath = "/store/partner/{partnerId}";
StringBuilder sb = path(qPath, partnerId);
String resp = exec(qPath, "DELETE", sb.toString(), null);
return convertTo(resp, String.class);
} | java | public String partner_partnerId_DELETE(String partnerId) throws IOException {
String qPath = "/store/partner/{partnerId}";
StringBuilder sb = path(qPath, partnerId);
String resp = exec(qPath, "DELETE", sb.toString(), null);
return convertTo(resp, String.class);
} | [
"public",
"String",
"partner_partnerId_DELETE",
"(",
"String",
"partnerId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/store/partner/{partnerId}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"partnerId",
")",
";",
"String",
"r... | Delete partner
REST: DELETE /store/partner/{partnerId}
@param partnerId [required] Id of the object to fetch
API beta | [
"Delete",
"partner"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-store/src/main/java/net/minidev/ovh/api/ApiOvhStore.java#L404-L409 |
looly/hulu | src/main/java/com/xiaoleilu/hulu/Response.java | Response.addCookie | public final static void addCookie(String name, String value, int maxAgeInSeconds) {
addCookie(name, value, maxAgeInSeconds, "/", null);
} | java | public final static void addCookie(String name, String value, int maxAgeInSeconds) {
addCookie(name, value, maxAgeInSeconds, "/", null);
} | [
"public",
"final",
"static",
"void",
"addCookie",
"(",
"String",
"name",
",",
"String",
"value",
",",
"int",
"maxAgeInSeconds",
")",
"{",
"addCookie",
"(",
"name",
",",
"value",
",",
"maxAgeInSeconds",
",",
"\"/\"",
",",
"null",
")",
";",
"}"
] | 设定返回给客户端的Cookie<br>
Path: "/"<br>
No Domain
@param name cookie名
@param value cookie值
@param maxAgeInSeconds -1: 关闭浏览器清除Cookie. 0: 立即清除Cookie. n>0 : Cookie存在的秒数. | [
"设定返回给客户端的Cookie<br",
">",
"Path",
":",
"/",
"<br",
">",
"No",
"Domain"
] | train | https://github.com/looly/hulu/blob/4072de684e2e2f28ac8a3a44c0d5a690b289ef28/src/main/java/com/xiaoleilu/hulu/Response.java#L226-L228 |
jronrun/benayn | benayn-ustyle/src/main/java/com/benayn/ustyle/Dater.java | Dater.of | public static Dater of(String date, DateStyle dateStyle) {
return from(date).with(dateStyle);
} | java | public static Dater of(String date, DateStyle dateStyle) {
return from(date).with(dateStyle);
} | [
"public",
"static",
"Dater",
"of",
"(",
"String",
"date",
",",
"DateStyle",
"dateStyle",
")",
"{",
"return",
"from",
"(",
"date",
")",
".",
"with",
"(",
"dateStyle",
")",
";",
"}"
] | Returns a new Dater instance with the given date and date style
@param date
@return | [
"Returns",
"a",
"new",
"Dater",
"instance",
"with",
"the",
"given",
"date",
"and",
"date",
"style"
] | train | https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/Dater.java#L234-L236 |
OpenFeign/feign | core/src/main/java/feign/Feign.java | Feign.configKey | public static String configKey(Class targetType, Method method) {
StringBuilder builder = new StringBuilder();
builder.append(targetType.getSimpleName());
builder.append('#').append(method.getName()).append('(');
for (Type param : method.getGenericParameterTypes()) {
param = Types.resolve(targetType, targetType, param);
builder.append(Types.getRawType(param).getSimpleName()).append(',');
}
if (method.getParameterTypes().length > 0) {
builder.deleteCharAt(builder.length() - 1);
}
return builder.append(')').toString();
} | java | public static String configKey(Class targetType, Method method) {
StringBuilder builder = new StringBuilder();
builder.append(targetType.getSimpleName());
builder.append('#').append(method.getName()).append('(');
for (Type param : method.getGenericParameterTypes()) {
param = Types.resolve(targetType, targetType, param);
builder.append(Types.getRawType(param).getSimpleName()).append(',');
}
if (method.getParameterTypes().length > 0) {
builder.deleteCharAt(builder.length() - 1);
}
return builder.append(')').toString();
} | [
"public",
"static",
"String",
"configKey",
"(",
"Class",
"targetType",
",",
"Method",
"method",
")",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"builder",
".",
"append",
"(",
"targetType",
".",
"getSimpleName",
"(",
")",
")"... | Configuration keys are formatted as unresolved <a href=
"http://docs.oracle.com/javase/6/docs/jdk/api/javadoc/doclet/com/sun/javadoc/SeeTag.html" >see
tags</a>. This method exposes that format, in case you need to create the same value as
{@link MethodMetadata#configKey()} for correlation purposes.
<p>
Here are some sample encodings:
<pre>
<ul>
<li>{@code Route53}: would match a class {@code route53.Route53}</li>
<li>{@code Route53#list()}: would match a method {@code route53.Route53#list()}</li>
<li>{@code Route53#listAt(Marker)}: would match a method {@code
route53.Route53#listAt(Marker)}</li>
<li>{@code Route53#listByNameAndType(String, String)}: would match a method {@code
route53.Route53#listAt(String, String)}</li>
</ul>
</pre>
Note that there is no whitespace expected in a key!
@param targetType {@link feign.Target#type() type} of the Feign interface.
@param method invoked method, present on {@code type} or its super.
@see MethodMetadata#configKey() | [
"Configuration",
"keys",
"are",
"formatted",
"as",
"unresolved",
"<a",
"href",
"=",
"http",
":",
"//",
"docs",
".",
"oracle",
".",
"com",
"/",
"javase",
"/",
"6",
"/",
"docs",
"/",
"jdk",
"/",
"api",
"/",
"javadoc",
"/",
"doclet",
"/",
"com",
"/",
... | train | https://github.com/OpenFeign/feign/blob/318fb0e955b8cfcf64f70d6aeea0ba5795f8a7eb/core/src/main/java/feign/Feign.java#L67-L79 |
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.createPatternAnyEntityModelAsync | public Observable<UUID> createPatternAnyEntityModelAsync(UUID appId, String versionId, PatternAnyModelCreateObject extractorCreateObject) {
return createPatternAnyEntityModelWithServiceResponseAsync(appId, versionId, extractorCreateObject).map(new Func1<ServiceResponse<UUID>, UUID>() {
@Override
public UUID call(ServiceResponse<UUID> response) {
return response.body();
}
});
} | java | public Observable<UUID> createPatternAnyEntityModelAsync(UUID appId, String versionId, PatternAnyModelCreateObject extractorCreateObject) {
return createPatternAnyEntityModelWithServiceResponseAsync(appId, versionId, extractorCreateObject).map(new Func1<ServiceResponse<UUID>, UUID>() {
@Override
public UUID call(ServiceResponse<UUID> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"UUID",
">",
"createPatternAnyEntityModelAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"PatternAnyModelCreateObject",
"extractorCreateObject",
")",
"{",
"return",
"createPatternAnyEntityModelWithServiceResponseAsync",
"(",
"appId"... | Adds a pattern.any entity extractor to the application.
@param appId The application ID.
@param versionId The version ID.
@param extractorCreateObject A model object containing the name and explicit list for the new Pattern.Any entity extractor.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the UUID object | [
"Adds",
"a",
"pattern",
".",
"any",
"entity",
"extractor",
"to",
"the",
"application",
"."
] | 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#L7594-L7601 |
lettuce-io/lettuce-core | src/main/java/io/lettuce/core/dynamic/support/ResolvableType.java | ResolvableType.getNested | public ResolvableType getNested(int nestingLevel, Map<Integer, Integer> typeIndexesPerLevel) {
ResolvableType result = this;
for (int i = 2; i <= nestingLevel; i++) {
if (result.isArray()) {
result = result.getComponentType();
} else {
// Handle derived types
while (result != ResolvableType.NONE && !result.hasGenerics()) {
result = result.getSuperType();
}
Integer index = (typeIndexesPerLevel != null ? typeIndexesPerLevel.get(i) : null);
index = (index == null ? result.getGenerics().length - 1 : index);
result = result.getGeneric(index);
}
}
return result;
} | java | public ResolvableType getNested(int nestingLevel, Map<Integer, Integer> typeIndexesPerLevel) {
ResolvableType result = this;
for (int i = 2; i <= nestingLevel; i++) {
if (result.isArray()) {
result = result.getComponentType();
} else {
// Handle derived types
while (result != ResolvableType.NONE && !result.hasGenerics()) {
result = result.getSuperType();
}
Integer index = (typeIndexesPerLevel != null ? typeIndexesPerLevel.get(i) : null);
index = (index == null ? result.getGenerics().length - 1 : index);
result = result.getGeneric(index);
}
}
return result;
} | [
"public",
"ResolvableType",
"getNested",
"(",
"int",
"nestingLevel",
",",
"Map",
"<",
"Integer",
",",
"Integer",
">",
"typeIndexesPerLevel",
")",
"{",
"ResolvableType",
"result",
"=",
"this",
";",
"for",
"(",
"int",
"i",
"=",
"2",
";",
"i",
"<=",
"nestingL... | Return a {@link ResolvableType} for the specified nesting level. The nesting level refers to the specific generic
parameter that should be returned. A nesting level of 1 indicates this type; 2 indicates the first nested generic; 3 the
second; and so on. For example, given {@code List<Set<Integer>>} level 1 refers to the {@code List}, level 2 the
{@code Set}, and level 3 the {@code Integer}.
<p>
The {@code typeIndexesPerLevel} map can be used to reference a specific generic for the given level. For example, an
index of 0 would refer to a {@code Map} key; whereas, 1 would refer to the value. If the map does not contain a value for
a specific level the last generic will be used (e.g. a {@code Map} value).
<p>
Nesting levels may also apply to array types; for example given {@code String[]}, a nesting level of 2 refers to
{@code String}.
<p>
If a type does not {@link #hasGenerics() contain} generics the {@link #getSuperType() supertype} hierarchy will be
considered.
@param nestingLevel the required nesting level, indexed from 1 for the current type, 2 for the first nested generic, 3
for the second and so on
@param typeIndexesPerLevel a map containing the generic index for a given nesting level (may be {@code null})
@return a {@link ResolvableType} for the nested level or {@link #NONE} | [
"Return",
"a",
"{",
"@link",
"ResolvableType",
"}",
"for",
"the",
"specified",
"nesting",
"level",
".",
"The",
"nesting",
"level",
"refers",
"to",
"the",
"specific",
"generic",
"parameter",
"that",
"should",
"be",
"returned",
".",
"A",
"nesting",
"level",
"o... | train | https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/support/ResolvableType.java#L518-L534 |
exoplatform/jcr | exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/JobWorkspaceRestore.java | JobWorkspaceRestore.removeWorkspace | protected void removeWorkspace(ManageableRepository mr, String workspaceName) throws RepositoryException
{
boolean isExists = false;
for (String wsName : mr.getWorkspaceNames())
if (workspaceName.equals(wsName))
{
isExists = true;
break;
}
if (isExists)
{
if (!mr.canRemoveWorkspace(workspaceName))
{
WorkspaceContainerFacade wc = mr.getWorkspaceContainer(workspaceName);
SessionRegistry sessionRegistry = (SessionRegistry)wc.getComponent(SessionRegistry.class);
sessionRegistry.closeSessions(workspaceName);
}
mr.removeWorkspace(workspaceName);
}
} | java | protected void removeWorkspace(ManageableRepository mr, String workspaceName) throws RepositoryException
{
boolean isExists = false;
for (String wsName : mr.getWorkspaceNames())
if (workspaceName.equals(wsName))
{
isExists = true;
break;
}
if (isExists)
{
if (!mr.canRemoveWorkspace(workspaceName))
{
WorkspaceContainerFacade wc = mr.getWorkspaceContainer(workspaceName);
SessionRegistry sessionRegistry = (SessionRegistry)wc.getComponent(SessionRegistry.class);
sessionRegistry.closeSessions(workspaceName);
}
mr.removeWorkspace(workspaceName);
}
} | [
"protected",
"void",
"removeWorkspace",
"(",
"ManageableRepository",
"mr",
",",
"String",
"workspaceName",
")",
"throws",
"RepositoryException",
"{",
"boolean",
"isExists",
"=",
"false",
";",
"for",
"(",
"String",
"wsName",
":",
"mr",
".",
"getWorkspaceNames",
"("... | Remove workspace.
@param mr
ManageableRepository, the manageable repository
@param workspaceName
String, the workspace name
@throws RepositoryException
will be generated the RepositoryException | [
"Remove",
"workspace",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/JobWorkspaceRestore.java#L248-L270 |
DDTH/ddth-kafka | src/main/java/com/github/ddth/kafka/internal/KafkaMsgConsumer.java | KafkaMsgConsumer._checkAndSubscribe | private void _checkAndSubscribe(KafkaConsumer<?, ?> consumer, String topic) {
synchronized (consumer) {
Set<String> subscription = consumer.subscription();
if (subscription == null || !subscription.contains(topic)) {
consumer.subscribe(Arrays.asList(topic));
}
}
} | java | private void _checkAndSubscribe(KafkaConsumer<?, ?> consumer, String topic) {
synchronized (consumer) {
Set<String> subscription = consumer.subscription();
if (subscription == null || !subscription.contains(topic)) {
consumer.subscribe(Arrays.asList(topic));
}
}
} | [
"private",
"void",
"_checkAndSubscribe",
"(",
"KafkaConsumer",
"<",
"?",
",",
"?",
">",
"consumer",
",",
"String",
"topic",
")",
"{",
"synchronized",
"(",
"consumer",
")",
"{",
"Set",
"<",
"String",
">",
"subscription",
"=",
"consumer",
".",
"subscription",
... | Subscribes to a topic.
@param consumer
@param topic
@since 1.3.2 | [
"Subscribes",
"to",
"a",
"topic",
"."
] | train | https://github.com/DDTH/ddth-kafka/blob/aaeb8536e28a109ac0b69022f0ea4bbf5696b76f/src/main/java/com/github/ddth/kafka/internal/KafkaMsgConsumer.java#L422-L429 |
alkacon/opencms-core | src/org/opencms/workplace/editors/CmsEditorDisplayOptions.java | CmsEditorDisplayOptions.getOptionValue | public String getOptionValue(String key, String defaultValue, Properties displayOptions) {
if (displayOptions == null) {
return defaultValue;
}
return displayOptions.getProperty(key, defaultValue);
} | java | public String getOptionValue(String key, String defaultValue, Properties displayOptions) {
if (displayOptions == null) {
return defaultValue;
}
return displayOptions.getProperty(key, defaultValue);
} | [
"public",
"String",
"getOptionValue",
"(",
"String",
"key",
",",
"String",
"defaultValue",
",",
"Properties",
"displayOptions",
")",
"{",
"if",
"(",
"displayOptions",
"==",
"null",
")",
"{",
"return",
"defaultValue",
";",
"}",
"return",
"displayOptions",
".",
... | Returns the value for the given key from the display options.<p>
@param key he element key name which should be read
@param defaultValue the default value to use in case the property is not found
@param displayOptions the display options for the current user
@return the value for the given key from the display options | [
"Returns",
"the",
"value",
"for",
"the",
"given",
"key",
"from",
"the",
"display",
"options",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/editors/CmsEditorDisplayOptions.java#L223-L229 |
caspervg/SC4D-LEX4J | lex4j/src/main/java/net/caspervg/lex4j/route/UserRoute.java | UserRoute.postRegistration | public void postRegistration(String username, String password, String email, String fullname) {
ClientResource resource = new ClientResource(Route.REGISTER.url());
Form form = new Form();
form.add("username", username);
form.add("password_1", password);
form.add("password_2", password);
form.add("email", email);
form.add("fullname", fullname);
resource.post(form);
} | java | public void postRegistration(String username, String password, String email, String fullname) {
ClientResource resource = new ClientResource(Route.REGISTER.url());
Form form = new Form();
form.add("username", username);
form.add("password_1", password);
form.add("password_2", password);
form.add("email", email);
form.add("fullname", fullname);
resource.post(form);
} | [
"public",
"void",
"postRegistration",
"(",
"String",
"username",
",",
"String",
"password",
",",
"String",
"email",
",",
"String",
"fullname",
")",
"{",
"ClientResource",
"resource",
"=",
"new",
"ClientResource",
"(",
"Route",
".",
"REGISTER",
".",
"url",
"(",... | Registers a new user for the SC4D LEX
@param username the username for the new user
@param password the password for the new user
@param email the e-mail for the new user
@param fullname the name for the new user (can be blank) | [
"Registers",
"a",
"new",
"user",
"for",
"the",
"SC4D",
"LEX"
] | train | https://github.com/caspervg/SC4D-LEX4J/blob/3d086ec70c817119a88573c2e23af27276cdb1d6/lex4j/src/main/java/net/caspervg/lex4j/route/UserRoute.java#L168-L179 |
alkacon/opencms-core | src/org/opencms/workplace/explorer/CmsExplorerTypeAccess.java | CmsExplorerTypeAccess.addAccessEntry | public void addAccessEntry(String key, String value) {
m_accessControl.put(key, value);
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_ADD_ACCESS_ENTRY_2, key, value));
}
} | java | public void addAccessEntry(String key, String value) {
m_accessControl.put(key, value);
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_ADD_ACCESS_ENTRY_2, key, value));
}
} | [
"public",
"void",
"addAccessEntry",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"m_accessControl",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"if",
"(",
"LOG",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"Mes... | Adds a single access entry to the map of access entries of the explorer type setting.<p>
This stores the configuration data in a map which is used in the initialize process
to create the access control list.<p>
@param key the principal of the ace
@param value the permissions for the principal | [
"Adds",
"a",
"single",
"access",
"entry",
"to",
"the",
"map",
"of",
"access",
"entries",
"of",
"the",
"explorer",
"type",
"setting",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/explorer/CmsExplorerTypeAccess.java#L105-L111 |
SonarSource/sonarqube | sonar-core/src/main/java/org/sonar/core/util/stream/MoreCollectors.java | MoreCollectors.index | public static <K, E> Collector<E, ImmutableListMultimap.Builder<K, E>, ImmutableListMultimap<K, E>> index(Function<? super E, K> keyFunction) {
return index(keyFunction, Function.<E>identity());
} | java | public static <K, E> Collector<E, ImmutableListMultimap.Builder<K, E>, ImmutableListMultimap<K, E>> index(Function<? super E, K> keyFunction) {
return index(keyFunction, Function.<E>identity());
} | [
"public",
"static",
"<",
"K",
",",
"E",
">",
"Collector",
"<",
"E",
",",
"ImmutableListMultimap",
".",
"Builder",
"<",
"K",
",",
"E",
">",
",",
"ImmutableListMultimap",
"<",
"K",
",",
"E",
">",
">",
"index",
"(",
"Function",
"<",
"?",
"super",
"E",
... | Creates an {@link com.google.common.collect.ImmutableListMultimap} from the stream where the values are the values
in the stream and the keys are the result of the provided {@link Function keyFunction} applied to each value in the
stream.
<p>
Neither {@link Function keyFunction} nor {@link Function valueFunction} can return {@code null}, otherwise a
{@link NullPointerException} will be thrown.
</p>
@throws NullPointerException if {@code keyFunction} or {@code valueFunction} is {@code null}.
@throws NullPointerException if result of {@code keyFunction} or {@code valueFunction} is {@code null}. | [
"Creates",
"an",
"{",
"@link",
"com",
".",
"google",
".",
"common",
".",
"collect",
".",
"ImmutableListMultimap",
"}",
"from",
"the",
"stream",
"where",
"the",
"values",
"are",
"the",
"values",
"in",
"the",
"stream",
"and",
"the",
"keys",
"are",
"the",
"... | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-core/src/main/java/org/sonar/core/util/stream/MoreCollectors.java#L316-L318 |
ThreeTen/threetenbp | src/main/java/org/threeten/bp/LocalDate.java | LocalDate.plusMonths | public LocalDate plusMonths(long monthsToAdd) {
if (monthsToAdd == 0) {
return this;
}
long monthCount = year * 12L + (month - 1);
long calcMonths = monthCount + monthsToAdd; // safe overflow
int newYear = YEAR.checkValidIntValue(Jdk8Methods.floorDiv(calcMonths, 12));
int newMonth = Jdk8Methods.floorMod(calcMonths, 12) + 1;
return resolvePreviousValid(newYear, newMonth, day);
} | java | public LocalDate plusMonths(long monthsToAdd) {
if (monthsToAdd == 0) {
return this;
}
long monthCount = year * 12L + (month - 1);
long calcMonths = monthCount + monthsToAdd; // safe overflow
int newYear = YEAR.checkValidIntValue(Jdk8Methods.floorDiv(calcMonths, 12));
int newMonth = Jdk8Methods.floorMod(calcMonths, 12) + 1;
return resolvePreviousValid(newYear, newMonth, day);
} | [
"public",
"LocalDate",
"plusMonths",
"(",
"long",
"monthsToAdd",
")",
"{",
"if",
"(",
"monthsToAdd",
"==",
"0",
")",
"{",
"return",
"this",
";",
"}",
"long",
"monthCount",
"=",
"year",
"*",
"12L",
"+",
"(",
"month",
"-",
"1",
")",
";",
"long",
"calcM... | Returns a copy of this {@code LocalDate} with the specified period in months added.
<p>
This method adds the specified amount to the months field in three steps:
<ol>
<li>Add the input months to the month-of-year field</li>
<li>Check if the resulting date would be invalid</li>
<li>Adjust the day-of-month to the last valid day if necessary</li>
</ol>
<p>
For example, 2007-03-31 plus one month would result in the invalid date
2007-04-31. Instead of returning an invalid result, the last valid day
of the month, 2007-04-30, is selected instead.
<p>
This instance is immutable and unaffected by this method call.
@param monthsToAdd the months to add, may be negative
@return a {@code LocalDate} based on this date with the months added, not null
@throws DateTimeException if the result exceeds the supported date range | [
"Returns",
"a",
"copy",
"of",
"this",
"{",
"@code",
"LocalDate",
"}",
"with",
"the",
"specified",
"period",
"in",
"months",
"added",
".",
"<p",
">",
"This",
"method",
"adds",
"the",
"specified",
"amount",
"to",
"the",
"months",
"field",
"in",
"three",
"s... | train | https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/LocalDate.java#L1133-L1142 |
mojohaus/jaxb2-maven-plugin | src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternFileFilter.java | PatternFileFilter.createIncludeFilterList | public static List<Filter<File>> createIncludeFilterList(final Log log,
final String... patterns) {
return createFilterList(log, true, patterns);
} | java | public static List<Filter<File>> createIncludeFilterList(final Log log,
final String... patterns) {
return createFilterList(log, true, patterns);
} | [
"public",
"static",
"List",
"<",
"Filter",
"<",
"File",
">",
">",
"createIncludeFilterList",
"(",
"final",
"Log",
"log",
",",
"final",
"String",
"...",
"patterns",
")",
"{",
"return",
"createFilterList",
"(",
"log",
",",
"true",
",",
"patterns",
")",
";",
... | Creates a new List containing an include-mode PatternFileFilter using the supplied patternStrings which
are interpreted as file suffixes. (I.e. prepended with {@code PATTERN_LETTER_DIGIT_PUNCT} and compiled to
Patterns). The {@code FILE_PATH_CONVERTER} is used to convert Files to strings.
@param patterns A List of suffix patterns to be used in creating a new ExclusionRegularExpressionFileFilter.
@param log The active Maven Log.
@return A List containing a PatternFileFilter using the supplied suffix patterns to match Files.
@see PatternFileFilter | [
"Creates",
"a",
"new",
"List",
"containing",
"an",
"include",
"-",
"mode",
"PatternFileFilter",
"using",
"the",
"supplied",
"patternStrings",
"which",
"are",
"interpreted",
"as",
"file",
"suffixes",
".",
"(",
"I",
".",
"e",
".",
"prepended",
"with",
"{",
"@c... | train | https://github.com/mojohaus/jaxb2-maven-plugin/blob/e3c4e47943b15282e5a6e850bbfb1588d8452a0a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternFileFilter.java#L167-L170 |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/config/builders/WriteBehindConfigurationBuilder.java | WriteBehindConfigurationBuilder.newBatchedWriteBehindConfiguration | public static BatchedWriteBehindConfigurationBuilder newBatchedWriteBehindConfiguration(long maxDelay, TimeUnit maxDelayUnit, int batchSize) {
return new BatchedWriteBehindConfigurationBuilder(maxDelay, maxDelayUnit, batchSize);
} | java | public static BatchedWriteBehindConfigurationBuilder newBatchedWriteBehindConfiguration(long maxDelay, TimeUnit maxDelayUnit, int batchSize) {
return new BatchedWriteBehindConfigurationBuilder(maxDelay, maxDelayUnit, batchSize);
} | [
"public",
"static",
"BatchedWriteBehindConfigurationBuilder",
"newBatchedWriteBehindConfiguration",
"(",
"long",
"maxDelay",
",",
"TimeUnit",
"maxDelayUnit",
",",
"int",
"batchSize",
")",
"{",
"return",
"new",
"BatchedWriteBehindConfigurationBuilder",
"(",
"maxDelay",
",",
... | Creates a new builder for {@link WriteBehindConfiguration} that supports batching.
@param maxDelay the max delay for a batch
@param maxDelayUnit the max delay unit
@param batchSize the batch size
@return a new builder | [
"Creates",
"a",
"new",
"builder",
"for",
"{",
"@link",
"WriteBehindConfiguration",
"}",
"that",
"supports",
"batching",
"."
] | train | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/config/builders/WriteBehindConfigurationBuilder.java#L57-L59 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/text/StrSpliter.java | StrSpliter.split | public static List<String> split(String str, Pattern separatorPattern, int limit, boolean isTrim, boolean ignoreEmpty){
if(StrUtil.isEmpty(str)){
return new ArrayList<String>(0);
}
if(limit == 1){
return addToList(new ArrayList<String>(1), str, isTrim, ignoreEmpty);
}
if(null == separatorPattern){//分隔符为空时按照空白符切分
return split(str, limit);
}
final Matcher matcher = separatorPattern.matcher(str);
final ArrayList<String> list = new ArrayList<>();
int len = str.length();
int start = 0;
while(matcher.find()){
addToList(list, str.substring(start, matcher.start()), isTrim, ignoreEmpty);
start = matcher.end();
//检查是否超出范围(最大允许limit-1个,剩下一个留给末尾字符串)
if(limit > 0 && list.size() > limit-2){
break;
}
}
return addToList(list, str.substring(start, len), isTrim, ignoreEmpty);
} | java | public static List<String> split(String str, Pattern separatorPattern, int limit, boolean isTrim, boolean ignoreEmpty){
if(StrUtil.isEmpty(str)){
return new ArrayList<String>(0);
}
if(limit == 1){
return addToList(new ArrayList<String>(1), str, isTrim, ignoreEmpty);
}
if(null == separatorPattern){//分隔符为空时按照空白符切分
return split(str, limit);
}
final Matcher matcher = separatorPattern.matcher(str);
final ArrayList<String> list = new ArrayList<>();
int len = str.length();
int start = 0;
while(matcher.find()){
addToList(list, str.substring(start, matcher.start()), isTrim, ignoreEmpty);
start = matcher.end();
//检查是否超出范围(最大允许limit-1个,剩下一个留给末尾字符串)
if(limit > 0 && list.size() > limit-2){
break;
}
}
return addToList(list, str.substring(start, len), isTrim, ignoreEmpty);
} | [
"public",
"static",
"List",
"<",
"String",
">",
"split",
"(",
"String",
"str",
",",
"Pattern",
"separatorPattern",
",",
"int",
"limit",
",",
"boolean",
"isTrim",
",",
"boolean",
"ignoreEmpty",
")",
"{",
"if",
"(",
"StrUtil",
".",
"isEmpty",
"(",
"str",
"... | 通过正则切分字符串
@param str 字符串
@param separatorPattern 分隔符正则{@link Pattern}
@param limit 限制分片数
@param isTrim 是否去除切分字符串后每个元素两边的空格
@param ignoreEmpty 是否忽略空串
@return 切分后的集合
@since 3.0.8 | [
"通过正则切分字符串"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/text/StrSpliter.java#L414-L440 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-dialogflow/src/main/java/com/google/cloud/dialogflow/v2beta1/IntentsClient.java | IntentsClient.createIntent | public final Intent createIntent(ProjectAgentName parent, Intent intent) {
CreateIntentRequest request =
CreateIntentRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.setIntent(intent)
.build();
return createIntent(request);
} | java | public final Intent createIntent(ProjectAgentName parent, Intent intent) {
CreateIntentRequest request =
CreateIntentRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.setIntent(intent)
.build();
return createIntent(request);
} | [
"public",
"final",
"Intent",
"createIntent",
"(",
"ProjectAgentName",
"parent",
",",
"Intent",
"intent",
")",
"{",
"CreateIntentRequest",
"request",
"=",
"CreateIntentRequest",
".",
"newBuilder",
"(",
")",
".",
"setParent",
"(",
"parent",
"==",
"null",
"?",
"nul... | Creates an intent in the specified agent.
<p>Sample code:
<pre><code>
try (IntentsClient intentsClient = IntentsClient.create()) {
ProjectAgentName parent = ProjectAgentName.of("[PROJECT]");
Intent intent = Intent.newBuilder().build();
Intent response = intentsClient.createIntent(parent, intent);
}
</code></pre>
@param parent Required. The agent to create a intent for. Format: `projects/<Project
ID>/agent`.
@param intent Required. The intent to create.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"an",
"intent",
"in",
"the",
"specified",
"agent",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-dialogflow/src/main/java/com/google/cloud/dialogflow/v2beta1/IntentsClient.java#L567-L575 |
netty/netty | common/src/main/java/io/netty/util/AsciiString.java | AsciiString.containsContentEqualsIgnoreCase | public static boolean containsContentEqualsIgnoreCase(Collection<CharSequence> collection, CharSequence value) {
for (CharSequence v : collection) {
if (contentEqualsIgnoreCase(value, v)) {
return true;
}
}
return false;
} | java | public static boolean containsContentEqualsIgnoreCase(Collection<CharSequence> collection, CharSequence value) {
for (CharSequence v : collection) {
if (contentEqualsIgnoreCase(value, v)) {
return true;
}
}
return false;
} | [
"public",
"static",
"boolean",
"containsContentEqualsIgnoreCase",
"(",
"Collection",
"<",
"CharSequence",
">",
"collection",
",",
"CharSequence",
"value",
")",
"{",
"for",
"(",
"CharSequence",
"v",
":",
"collection",
")",
"{",
"if",
"(",
"contentEqualsIgnoreCase",
... | Determine if {@code collection} contains {@code value} and using
{@link #contentEqualsIgnoreCase(CharSequence, CharSequence)} to compare values.
@param collection The collection to look for and equivalent element as {@code value}.
@param value The value to look for in {@code collection}.
@return {@code true} if {@code collection} contains {@code value} according to
{@link #contentEqualsIgnoreCase(CharSequence, CharSequence)}. {@code false} otherwise.
@see #contentEqualsIgnoreCase(CharSequence, CharSequence) | [
"Determine",
"if",
"{"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/AsciiString.java#L1472-L1479 |
mgledi/DRUMS | src/main/java/com/unister/semweb/drums/storable/GeneralStructure.java | GeneralStructure.addValuePart | public boolean addValuePart(String name, Basic_Field_Types type) throws IOException {
return addValuePart(name, type.size);
} | java | public boolean addValuePart(String name, Basic_Field_Types type) throws IOException {
return addValuePart(name, type.size);
} | [
"public",
"boolean",
"addValuePart",
"(",
"String",
"name",
",",
"Basic_Field_Types",
"type",
")",
"throws",
"IOException",
"{",
"return",
"addValuePart",
"(",
"name",
",",
"type",
".",
"size",
")",
";",
"}"
] | Adds a new ValuePart. This is a wrapper method for <code>addKeyPart(String, int)</code>.
@param name
the name of the key part. With this name you can access this part
@param type
the type of the key part.
@return true if adding the value part was successful
@throws IOException | [
"Adds",
"a",
"new",
"ValuePart",
".",
"This",
"is",
"a",
"wrapper",
"method",
"for",
"<code",
">",
"addKeyPart",
"(",
"String",
"int",
")",
"<",
"/",
"code",
">",
"."
] | train | https://github.com/mgledi/DRUMS/blob/a670f17a2186c9a15725f26617d77ce8e444e072/src/main/java/com/unister/semweb/drums/storable/GeneralStructure.java#L111-L113 |
xmlunit/xmlunit | xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/SimpleXpathEngine.java | SimpleXpathEngine.getMatchingNodes | public NodeList getMatchingNodes(String select, Document document)
throws ConfigurationException, XpathException {
try {
return getXPathResultNode(select, document).getChildNodes();
} catch (TransformerException ex) {
throw new XpathException("Failed to apply stylesheet", ex);
}
} | java | public NodeList getMatchingNodes(String select, Document document)
throws ConfigurationException, XpathException {
try {
return getXPathResultNode(select, document).getChildNodes();
} catch (TransformerException ex) {
throw new XpathException("Failed to apply stylesheet", ex);
}
} | [
"public",
"NodeList",
"getMatchingNodes",
"(",
"String",
"select",
",",
"Document",
"document",
")",
"throws",
"ConfigurationException",
",",
"XpathException",
"{",
"try",
"{",
"return",
"getXPathResultNode",
"(",
"select",
",",
"document",
")",
".",
"getChildNodes"... | Execute the specified xpath syntax <code>select</code> expression
on the specified document and return the list of nodes (could have
length zero) that match
@param select
@param document
@return list of matching nodes | [
"Execute",
"the",
"specified",
"xpath",
"syntax",
"<code",
">",
"select<",
"/",
"code",
">",
"expression",
"on",
"the",
"specified",
"document",
"and",
"return",
"the",
"list",
"of",
"nodes",
"(",
"could",
"have",
"length",
"zero",
")",
"that",
"match"
] | train | https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/SimpleXpathEngine.java#L205-L212 |
jamesagnew/hapi-fhir | hapi-fhir-structures-r4/src/main/java/org/hl7/fhir/r4/model/IdType.java | IdType.withServerBase | @Override
public IdType withServerBase(String theServerBase, String theResourceType) {
if (isLocal() || isUrn()) {
return new IdType(getValueAsString());
}
return new IdType(theServerBase, theResourceType, getIdPart(), getVersionIdPart());
} | java | @Override
public IdType withServerBase(String theServerBase, String theResourceType) {
if (isLocal() || isUrn()) {
return new IdType(getValueAsString());
}
return new IdType(theServerBase, theResourceType, getIdPart(), getVersionIdPart());
} | [
"@",
"Override",
"public",
"IdType",
"withServerBase",
"(",
"String",
"theServerBase",
",",
"String",
"theResourceType",
")",
"{",
"if",
"(",
"isLocal",
"(",
")",
"||",
"isUrn",
"(",
")",
")",
"{",
"return",
"new",
"IdType",
"(",
"getValueAsString",
"(",
"... | Returns a view of this ID as a fully qualified URL, given a server base and
resource name (which will only be used if the ID does not already contain
those respective parts). Essentially, because IdType can contain either a
complete URL or a partial one (or even jut a simple ID), this method may be
used to translate into a complete URL.
@param theServerBase The server base (e.g. "http://example.com/fhir")
@param theResourceType The resource name (e.g. "Patient")
@return A fully qualified URL for this ID (e.g.
"http://example.com/fhir/Patient/1") | [
"Returns",
"a",
"view",
"of",
"this",
"ID",
"as",
"a",
"fully",
"qualified",
"URL",
"given",
"a",
"server",
"base",
"and",
"resource",
"name",
"(",
"which",
"will",
"only",
"be",
"used",
"if",
"the",
"ID",
"does",
"not",
"already",
"contain",
"those",
... | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-structures-r4/src/main/java/org/hl7/fhir/r4/model/IdType.java#L702-L708 |
aws/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/util/XpathUtils.java | XpathUtils.asFloat | public static Float asFloat(String expression, Node node)
throws XPathExpressionException {
return asFloat(expression, node, xpath());
} | java | public static Float asFloat(String expression, Node node)
throws XPathExpressionException {
return asFloat(expression, node, xpath());
} | [
"public",
"static",
"Float",
"asFloat",
"(",
"String",
"expression",
",",
"Node",
"node",
")",
"throws",
"XPathExpressionException",
"{",
"return",
"asFloat",
"(",
"expression",
",",
"node",
",",
"xpath",
"(",
")",
")",
";",
"}"
] | Evaluates the specified XPath expression and returns the result as a
Float.
<p>
This method can be expensive as a new xpath is instantiated per
invocation. Consider passing in the xpath explicitly via {
{@link #asDouble(String, Node, XPath)} instead. Note {@link XPath} is
not thread-safe and not reentrant.
@param expression
The XPath expression to evaluate.
@param node
The node to run the expression on.
@return The Float result.
@throws XPathExpressionException
If there was a problem processing the specified XPath
expression. | [
"Evaluates",
"the",
"specified",
"XPath",
"expression",
"and",
"returns",
"the",
"result",
"as",
"a",
"Float",
".",
"<p",
">",
"This",
"method",
"can",
"be",
"expensive",
"as",
"a",
"new",
"xpath",
"is",
"instantiated",
"per",
"invocation",
".",
"Consider",
... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/util/XpathUtils.java#L347-L350 |
JOML-CI/JOML | src/org/joml/Matrix3x2f.java | Matrix3x2f.scaling | public Matrix3x2f scaling(float x, float y) {
m00 = x;
m01 = 0.0f;
m10 = 0.0f;
m11 = y;
m20 = 0.0f;
m21 = 0.0f;
return this;
} | java | public Matrix3x2f scaling(float x, float y) {
m00 = x;
m01 = 0.0f;
m10 = 0.0f;
m11 = y;
m20 = 0.0f;
m21 = 0.0f;
return this;
} | [
"public",
"Matrix3x2f",
"scaling",
"(",
"float",
"x",
",",
"float",
"y",
")",
"{",
"m00",
"=",
"x",
";",
"m01",
"=",
"0.0f",
";",
"m10",
"=",
"0.0f",
";",
"m11",
"=",
"y",
";",
"m20",
"=",
"0.0f",
";",
"m21",
"=",
"0.0f",
";",
"return",
"this",... | Set this matrix to be a simple scale matrix.
@param x
the scale in x
@param y
the scale in y
@return this | [
"Set",
"this",
"matrix",
"to",
"be",
"a",
"simple",
"scale",
"matrix",
"."
] | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3x2f.java#L1583-L1591 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java | CollUtil.contains | public static boolean contains(Collection<?> collection, Object value) {
return isNotEmpty(collection) && collection.contains(value);
} | java | public static boolean contains(Collection<?> collection, Object value) {
return isNotEmpty(collection) && collection.contains(value);
} | [
"public",
"static",
"boolean",
"contains",
"(",
"Collection",
"<",
"?",
">",
"collection",
",",
"Object",
"value",
")",
"{",
"return",
"isNotEmpty",
"(",
"collection",
")",
"&&",
"collection",
".",
"contains",
"(",
"value",
")",
";",
"}"
] | 判断指定集合是否包含指定值,如果集合为空(null或者空),返回{@code false},否则找到元素返回{@code true}
@param collection 集合
@param value 需要查找的值
@return 如果集合为空(null或者空),返回{@code false},否则找到元素返回{@code true}
@since 4.1.10 | [
"判断指定集合是否包含指定值,如果集合为空(null或者空),返回",
"{",
"@code",
"false",
"}",
",否则找到元素返回",
"{",
"@code",
"true",
"}"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java#L216-L218 |
grpc/grpc-java | core/src/main/java/io/grpc/internal/TransportFrameUtil.java | TransportFrameUtil.toHttp2Headers | public static byte[][] toHttp2Headers(Metadata headers) {
byte[][] serializedHeaders = InternalMetadata.serialize(headers);
// TODO(carl-mastrangelo): eventually remove this once all callers are updated.
if (serializedHeaders == null) {
return new byte[][]{};
}
int k = 0;
for (int i = 0; i < serializedHeaders.length; i += 2) {
byte[] key = serializedHeaders[i];
byte[] value = serializedHeaders[i + 1];
if (endsWith(key, binaryHeaderSuffixBytes)) {
// Binary header.
serializedHeaders[k] = key;
serializedHeaders[k + 1]
= InternalMetadata.BASE64_ENCODING_OMIT_PADDING.encode(value).getBytes(US_ASCII);
k += 2;
} else {
// Non-binary header.
// Filter out headers that contain non-spec-compliant ASCII characters.
// TODO(zhangkun83): only do such check in development mode since it's expensive
if (isSpecCompliantAscii(value)) {
serializedHeaders[k] = key;
serializedHeaders[k + 1] = value;
k += 2;
} else {
String keyString = new String(key, US_ASCII);
logger.warning("Metadata key=" + keyString + ", value=" + Arrays.toString(value)
+ " contains invalid ASCII characters");
}
}
}
// Fast path, everything worked out fine.
if (k == serializedHeaders.length) {
return serializedHeaders;
}
return Arrays.copyOfRange(serializedHeaders, 0, k);
} | java | public static byte[][] toHttp2Headers(Metadata headers) {
byte[][] serializedHeaders = InternalMetadata.serialize(headers);
// TODO(carl-mastrangelo): eventually remove this once all callers are updated.
if (serializedHeaders == null) {
return new byte[][]{};
}
int k = 0;
for (int i = 0; i < serializedHeaders.length; i += 2) {
byte[] key = serializedHeaders[i];
byte[] value = serializedHeaders[i + 1];
if (endsWith(key, binaryHeaderSuffixBytes)) {
// Binary header.
serializedHeaders[k] = key;
serializedHeaders[k + 1]
= InternalMetadata.BASE64_ENCODING_OMIT_PADDING.encode(value).getBytes(US_ASCII);
k += 2;
} else {
// Non-binary header.
// Filter out headers that contain non-spec-compliant ASCII characters.
// TODO(zhangkun83): only do such check in development mode since it's expensive
if (isSpecCompliantAscii(value)) {
serializedHeaders[k] = key;
serializedHeaders[k + 1] = value;
k += 2;
} else {
String keyString = new String(key, US_ASCII);
logger.warning("Metadata key=" + keyString + ", value=" + Arrays.toString(value)
+ " contains invalid ASCII characters");
}
}
}
// Fast path, everything worked out fine.
if (k == serializedHeaders.length) {
return serializedHeaders;
}
return Arrays.copyOfRange(serializedHeaders, 0, k);
} | [
"public",
"static",
"byte",
"[",
"]",
"[",
"]",
"toHttp2Headers",
"(",
"Metadata",
"headers",
")",
"{",
"byte",
"[",
"]",
"[",
"]",
"serializedHeaders",
"=",
"InternalMetadata",
".",
"serialize",
"(",
"headers",
")",
";",
"// TODO(carl-mastrangelo): eventually r... | Transform the given headers to a format where only spec-compliant ASCII characters are allowed.
Binary header values are encoded by Base64 in the result. It is safe to modify the returned
array, but not to modify any of the underlying byte arrays.
@return the interleaved keys and values. | [
"Transform",
"the",
"given",
"headers",
"to",
"a",
"format",
"where",
"only",
"spec",
"-",
"compliant",
"ASCII",
"characters",
"are",
"allowed",
".",
"Binary",
"header",
"values",
"are",
"encoded",
"by",
"Base64",
"in",
"the",
"result",
".",
"It",
"is",
"s... | train | https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/core/src/main/java/io/grpc/internal/TransportFrameUtil.java#L50-L86 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/SerializedFormBuilder.java | SerializedFormBuilder.buildMethodTags | public void buildMethodTags(XMLNode node, Content methodsContentTree) {
methodWriter.addMemberTags((MethodDoc) currentMember, methodsContentTree);
MethodDoc method = (MethodDoc)currentMember;
if (method.name().compareTo("writeExternal") == 0
&& method.tags("serialData").length == 0) {
if (configuration.serialwarn) {
configuration.getDocletSpecificMsg().warning(
currentMember.position(), "doclet.MissingSerialDataTag",
method.containingClass().qualifiedName(), method.name());
}
}
} | java | public void buildMethodTags(XMLNode node, Content methodsContentTree) {
methodWriter.addMemberTags((MethodDoc) currentMember, methodsContentTree);
MethodDoc method = (MethodDoc)currentMember;
if (method.name().compareTo("writeExternal") == 0
&& method.tags("serialData").length == 0) {
if (configuration.serialwarn) {
configuration.getDocletSpecificMsg().warning(
currentMember.position(), "doclet.MissingSerialDataTag",
method.containingClass().qualifiedName(), method.name());
}
}
} | [
"public",
"void",
"buildMethodTags",
"(",
"XMLNode",
"node",
",",
"Content",
"methodsContentTree",
")",
"{",
"methodWriter",
".",
"addMemberTags",
"(",
"(",
"MethodDoc",
")",
"currentMember",
",",
"methodsContentTree",
")",
";",
"MethodDoc",
"method",
"=",
"(",
... | Build the method tags.
@param node the XML element that specifies which components to document
@param methodsContentTree content tree to which the documentation will be added | [
"Build",
"the",
"method",
"tags",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/SerializedFormBuilder.java#L351-L362 |
gosu-lang/gosu-lang | gosu-core-api/src/main/java/gw/lang/parser/StandardCoercionManager.java | StandardCoercionManager.verifyTypesComparable | public IType verifyTypesComparable( IType lhsType, IType rhsType, boolean bBiDirectional ) throws ParseException
{
return verifyTypesComparable( lhsType, rhsType, bBiDirectional, null );
} | java | public IType verifyTypesComparable( IType lhsType, IType rhsType, boolean bBiDirectional ) throws ParseException
{
return verifyTypesComparable( lhsType, rhsType, bBiDirectional, null );
} | [
"public",
"IType",
"verifyTypesComparable",
"(",
"IType",
"lhsType",
",",
"IType",
"rhsType",
",",
"boolean",
"bBiDirectional",
")",
"throws",
"ParseException",
"{",
"return",
"verifyTypesComparable",
"(",
"lhsType",
",",
"rhsType",
",",
"bBiDirectional",
",",
"null... | private TypeSystemAwareCache<TypesComp, IType> getCompCache() { return _compCache; } | [
"private",
"TypeSystemAwareCache<TypesComp",
"IType",
">",
"getCompCache",
"()",
"{",
"return",
"_compCache",
";",
"}"
] | train | https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/lang/parser/StandardCoercionManager.java#L672-L675 |
konvergeio/cofoja | src/main/java/com/google/java/contract/core/agent/SpecificationMethodAdapter.java | SpecificationMethodAdapter.invokeOldValues | @Requires({
"kind != null",
"kind.isOld()",
"list != null"
})
protected void invokeOldValues(ContractKind kind, List<Integer> list) {
List<MethodContractHandle> olds =
contracts.getMethodHandles(kind, methodName, methodDesc, 0);
if (olds.isEmpty()) {
return;
}
for (MethodContractHandle h : olds) {
MethodNode contractMethod = injectContractMethod(h);
int k = h.getKey();
if (!statik) {
loadThis();
}
loadArgs();
invokeContractMethod(contractMethod);
storeLocal(list.get(k));
}
} | java | @Requires({
"kind != null",
"kind.isOld()",
"list != null"
})
protected void invokeOldValues(ContractKind kind, List<Integer> list) {
List<MethodContractHandle> olds =
contracts.getMethodHandles(kind, methodName, methodDesc, 0);
if (olds.isEmpty()) {
return;
}
for (MethodContractHandle h : olds) {
MethodNode contractMethod = injectContractMethod(h);
int k = h.getKey();
if (!statik) {
loadThis();
}
loadArgs();
invokeContractMethod(contractMethod);
storeLocal(list.get(k));
}
} | [
"@",
"Requires",
"(",
"{",
"\"kind != null\"",
",",
"\"kind.isOld()\"",
",",
"\"list != null\"",
"}",
")",
"protected",
"void",
"invokeOldValues",
"(",
"ContractKind",
"kind",
",",
"List",
"<",
"Integer",
">",
"list",
")",
"{",
"List",
"<",
"MethodContractHandle... | Injects calls to old value contract methods. old value contract
methods get called with, in this order:
<ul>
<li>the {@code this} pointer, if any;
<li>and the original method's parameters.
</ul>
@param kind either OLD or SIGNAL_OLD
@param list the list that holds the allocated old value variable
indexes | [
"Injects",
"calls",
"to",
"old",
"value",
"contract",
"methods",
".",
"old",
"value",
"contract",
"methods",
"get",
"called",
"with",
"in",
"this",
"order",
":"
] | train | https://github.com/konvergeio/cofoja/blob/6ded58fa05eb5bf85f16353c8dd4c70bee59121a/src/main/java/com/google/java/contract/core/agent/SpecificationMethodAdapter.java#L354-L378 |
vanilladb/vanillacore | src/main/java/org/vanilladb/core/storage/tx/concurrency/LockTable.java | LockTable.isLock | void isLock(Object obj, long txNum) {
Object anchor = getAnchor(obj);
txWaitMap.put(txNum, anchor);
synchronized (anchor) {
Lockers lks = prepareLockers(obj);
if (hasIsLock(lks, txNum))
return;
try {
long timestamp = System.currentTimeMillis();
while (!isLockable(lks, txNum) && !waitingTooLong(timestamp)) {
avoidDeadlock(lks, txNum, IS_LOCK);
lks.requestSet.add(txNum);
anchor.wait(MAX_TIME);
lks.requestSet.remove(txNum);
}
if (!isLockable(lks, txNum))
throw new LockAbortException();
lks.isLockers.add(txNum);
getObjectSet(txNum).add(obj);
} catch (InterruptedException e) {
throw new LockAbortException();
}
}
txWaitMap.remove(txNum);
} | java | void isLock(Object obj, long txNum) {
Object anchor = getAnchor(obj);
txWaitMap.put(txNum, anchor);
synchronized (anchor) {
Lockers lks = prepareLockers(obj);
if (hasIsLock(lks, txNum))
return;
try {
long timestamp = System.currentTimeMillis();
while (!isLockable(lks, txNum) && !waitingTooLong(timestamp)) {
avoidDeadlock(lks, txNum, IS_LOCK);
lks.requestSet.add(txNum);
anchor.wait(MAX_TIME);
lks.requestSet.remove(txNum);
}
if (!isLockable(lks, txNum))
throw new LockAbortException();
lks.isLockers.add(txNum);
getObjectSet(txNum).add(obj);
} catch (InterruptedException e) {
throw new LockAbortException();
}
}
txWaitMap.remove(txNum);
} | [
"void",
"isLock",
"(",
"Object",
"obj",
",",
"long",
"txNum",
")",
"{",
"Object",
"anchor",
"=",
"getAnchor",
"(",
"obj",
")",
";",
"txWaitMap",
".",
"put",
"(",
"txNum",
",",
"anchor",
")",
";",
"synchronized",
"(",
"anchor",
")",
"{",
"Lockers",
"l... | Grants an islock on the specified item. If any conflict lock exists when
the method is called, then the calling thread will be placed on a wait
list until the lock is released. If the thread remains on the wait list
for a certain amount of time, then an exception is thrown.
@param obj
a lockable item
@param txNum
a transaction number | [
"Grants",
"an",
"islock",
"on",
"the",
"specified",
"item",
".",
"If",
"any",
"conflict",
"lock",
"exists",
"when",
"the",
"method",
"is",
"called",
"then",
"the",
"calling",
"thread",
"will",
"be",
"placed",
"on",
"a",
"wait",
"list",
"until",
"the",
"l... | train | https://github.com/vanilladb/vanillacore/blob/d9a34e876b1b83226036d1fa982a614bbef59bd1/src/main/java/org/vanilladb/core/storage/tx/concurrency/LockTable.java#L308-L333 |
netheosgithub/pcs_api | java/src/main/java/net/netheos/pcsapi/utils/PcsUtils.java | PcsUtils.downloadDataToSink | public static void downloadDataToSink( CResponse response, ByteSink byteSink )
{
InputStream is = null;
ByteSinkStream bss = null;
boolean success = false;
try {
long contentLength = response.getContentLength();
if ( contentLength >= 0 ) {
// content length is known: inform any listener
byteSink.setExpectedLength( contentLength );
}
long current = 0;
is = response.openStream();
bss = byteSink.openStream();
byte[] buffer = new byte[ 8 * 1024 ];
int len;
while ( ( len = is.read( buffer ) ) != -1 ) {
current += len;
bss.write( buffer, 0, len );
}
if ( contentLength < 0 ) {
// content length was unknown; inform listener operation is terminated
byteSink.setExpectedLength( current );
}
bss.flush();
bss.close();
bss = null;
success = true;
} catch ( IOException ex ) {
throw new CStorageException( ex.getMessage(), ex );
} finally {
if ( bss != null && !success ) {
bss.abort();
}
PcsUtils.closeQuietly( is );
PcsUtils.closeQuietly( bss );
}
} | java | public static void downloadDataToSink( CResponse response, ByteSink byteSink )
{
InputStream is = null;
ByteSinkStream bss = null;
boolean success = false;
try {
long contentLength = response.getContentLength();
if ( contentLength >= 0 ) {
// content length is known: inform any listener
byteSink.setExpectedLength( contentLength );
}
long current = 0;
is = response.openStream();
bss = byteSink.openStream();
byte[] buffer = new byte[ 8 * 1024 ];
int len;
while ( ( len = is.read( buffer ) ) != -1 ) {
current += len;
bss.write( buffer, 0, len );
}
if ( contentLength < 0 ) {
// content length was unknown; inform listener operation is terminated
byteSink.setExpectedLength( current );
}
bss.flush();
bss.close();
bss = null;
success = true;
} catch ( IOException ex ) {
throw new CStorageException( ex.getMessage(), ex );
} finally {
if ( bss != null && !success ) {
bss.abort();
}
PcsUtils.closeQuietly( is );
PcsUtils.closeQuietly( bss );
}
} | [
"public",
"static",
"void",
"downloadDataToSink",
"(",
"CResponse",
"response",
",",
"ByteSink",
"byteSink",
")",
"{",
"InputStream",
"is",
"=",
"null",
";",
"ByteSinkStream",
"bss",
"=",
"null",
";",
"boolean",
"success",
"=",
"false",
";",
"try",
"{",
"lon... | Server has answered OK with a file to download as stream.
Open byte sink stream, and copy data from server stream to sink stream
@param response server response to read from
@param byteSink destination | [
"Server",
"has",
"answered",
"OK",
"with",
"a",
"file",
"to",
"download",
"as",
"stream",
"."
] | train | https://github.com/netheosgithub/pcs_api/blob/20691e52e144014f99ca75cb7dedc7ba0c18586c/java/src/main/java/net/netheos/pcsapi/utils/PcsUtils.java#L167-L212 |
igniterealtime/REST-API-Client | src/main/java/org/igniterealtime/restclient/RestClient.java | RestClient.call | @SuppressWarnings("unchecked")
public <T> T call(String methodName, String restPath, Class<T> expectedResponse, Object payload,
Map<String, String> queryParams) {
WebTarget webTarget = createWebTarget(restPath, queryParams);
Response result = webTarget.request().headers(headers).accept(mediaType.getMediaType()).method(
methodName.toString(),
Entity.entity(payload, mediaType.getMediaType()),
Response.class);
if (expectedResponse.getName().equals(Response.class.getName())) {
return (T) result;
}
if (result != null && isStatusCodeOK(result, restPath)) {
return (T) result.readEntity(expectedResponse);
}
throw new WebApplicationException("Unhandled response", result);
} | java | @SuppressWarnings("unchecked")
public <T> T call(String methodName, String restPath, Class<T> expectedResponse, Object payload,
Map<String, String> queryParams) {
WebTarget webTarget = createWebTarget(restPath, queryParams);
Response result = webTarget.request().headers(headers).accept(mediaType.getMediaType()).method(
methodName.toString(),
Entity.entity(payload, mediaType.getMediaType()),
Response.class);
if (expectedResponse.getName().equals(Response.class.getName())) {
return (T) result;
}
if (result != null && isStatusCodeOK(result, restPath)) {
return (T) result.readEntity(expectedResponse);
}
throw new WebApplicationException("Unhandled response", result);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
">",
"T",
"call",
"(",
"String",
"methodName",
",",
"String",
"restPath",
",",
"Class",
"<",
"T",
">",
"expectedResponse",
",",
"Object",
"payload",
",",
"Map",
"<",
"String",
",",
"... | Gets the.
@param <T>
the generic type
@param methodName
the method name
@param restPath
the rest path
@param expectedResponse
the clazz
@param payload
the payload
@param queryParams
the query params
@return the t | [
"Gets",
"the",
"."
] | train | https://github.com/igniterealtime/REST-API-Client/blob/fd544dd770ec2ababa47fef51579522ddce09f05/src/main/java/org/igniterealtime/restclient/RestClient.java#L151-L169 |
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/BackupShortTermRetentionPoliciesInner.java | BackupShortTermRetentionPoliciesInner.updateAsync | public Observable<BackupShortTermRetentionPolicyInner> updateAsync(String resourceGroupName, String serverName, String databaseName, Integer retentionDays) {
return updateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, retentionDays).map(new Func1<ServiceResponse<BackupShortTermRetentionPolicyInner>, BackupShortTermRetentionPolicyInner>() {
@Override
public BackupShortTermRetentionPolicyInner call(ServiceResponse<BackupShortTermRetentionPolicyInner> response) {
return response.body();
}
});
} | java | public Observable<BackupShortTermRetentionPolicyInner> updateAsync(String resourceGroupName, String serverName, String databaseName, Integer retentionDays) {
return updateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, retentionDays).map(new Func1<ServiceResponse<BackupShortTermRetentionPolicyInner>, BackupShortTermRetentionPolicyInner>() {
@Override
public BackupShortTermRetentionPolicyInner call(ServiceResponse<BackupShortTermRetentionPolicyInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"BackupShortTermRetentionPolicyInner",
">",
"updateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
",",
"Integer",
"retentionDays",
")",
"{",
"return",
"updateWithServiceResponseAsync",
"... | Updates a database's short term retention policy.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database.
@param retentionDays The backup retention period in days. This is how many days Point-in-Time Restore will be supported.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Updates",
"a",
"database",
"s",
"short",
"term",
"retention",
"policy",
"."
] | 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/BackupShortTermRetentionPoliciesInner.java#L660-L667 |
datasift/datasift-java | src/main/java/com/datasift/client/accounts/DataSiftAccount.java | DataSiftAccount.getLimit | public FutureData<Limit> getLimit(String identity, String service) {
FutureData<Limit> future = new FutureData<>();
URI uri = newParams().forURL(config.newAPIEndpointURI(IDENTITY + "/" + identity + "/limit/" + service));
Request request = config.http().
GET(uri, new PageReader(newRequestCallback(future, new Limit(), config)));
performRequest(future, request);
return future;
} | java | public FutureData<Limit> getLimit(String identity, String service) {
FutureData<Limit> future = new FutureData<>();
URI uri = newParams().forURL(config.newAPIEndpointURI(IDENTITY + "/" + identity + "/limit/" + service));
Request request = config.http().
GET(uri, new PageReader(newRequestCallback(future, new Limit(), config)));
performRequest(future, request);
return future;
} | [
"public",
"FutureData",
"<",
"Limit",
">",
"getLimit",
"(",
"String",
"identity",
",",
"String",
"service",
")",
"{",
"FutureData",
"<",
"Limit",
">",
"future",
"=",
"new",
"FutureData",
"<>",
"(",
")",
";",
"URI",
"uri",
"=",
"newParams",
"(",
")",
".... | /*
Fetch a Limit
@param identity the ID of the identity
@param service the name of the service
@return The limit for the service in that identity | [
"/",
"*",
"Fetch",
"a",
"Limit"
] | train | https://github.com/datasift/datasift-java/blob/09de124f2a1a507ff6181e59875c6f325290850e/src/main/java/com/datasift/client/accounts/DataSiftAccount.java#L308-L315 |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/restricted/Expression.java | Expression.asCheap | public Expression asCheap() {
if (isCheap()) {
return this;
}
return new Expression(resultType, features.plus(Feature.CHEAP)) {
@Override
protected void doGen(CodeBuilder adapter) {
Expression.this.gen(adapter);
}
};
} | java | public Expression asCheap() {
if (isCheap()) {
return this;
}
return new Expression(resultType, features.plus(Feature.CHEAP)) {
@Override
protected void doGen(CodeBuilder adapter) {
Expression.this.gen(adapter);
}
};
} | [
"public",
"Expression",
"asCheap",
"(",
")",
"{",
"if",
"(",
"isCheap",
"(",
")",
")",
"{",
"return",
"this",
";",
"}",
"return",
"new",
"Expression",
"(",
"resultType",
",",
"features",
".",
"plus",
"(",
"Feature",
".",
"CHEAP",
")",
")",
"{",
"@",
... | Returns an equivalent expression where {@link #isCheap()} returns {@code true}. | [
"Returns",
"an",
"equivalent",
"expression",
"where",
"{"
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/Expression.java#L299-L309 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java | ArrayUtil.contains | public static <T> boolean contains(T[] array, T value) {
return indexOf(array, value) > INDEX_NOT_FOUND;
} | java | public static <T> boolean contains(T[] array, T value) {
return indexOf(array, value) > INDEX_NOT_FOUND;
} | [
"public",
"static",
"<",
"T",
">",
"boolean",
"contains",
"(",
"T",
"[",
"]",
"array",
",",
"T",
"value",
")",
"{",
"return",
"indexOf",
"(",
"array",
",",
"value",
")",
">",
"INDEX_NOT_FOUND",
";",
"}"
] | 数组中是否包含元素
@param <T> 数组元素类型
@param array 数组
@param value 被检查的元素
@return 是否包含 | [
"数组中是否包含元素"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java#L956-L958 |
qiniu/java-sdk | src/main/java/com/qiniu/streaming/StreamingManager.java | StreamingManager.saveAs | public String saveAs(String streamKey, String fileName, long start, long end) throws QiniuException {
return saveAs(streamKey, fileName, start, end, null);
} | java | public String saveAs(String streamKey, String fileName, long start, long end) throws QiniuException {
return saveAs(streamKey, fileName, start, end, null);
} | [
"public",
"String",
"saveAs",
"(",
"String",
"streamKey",
",",
"String",
"fileName",
",",
"long",
"start",
",",
"long",
"end",
")",
"throws",
"QiniuException",
"{",
"return",
"saveAs",
"(",
"streamKey",
",",
"fileName",
",",
"start",
",",
"end",
",",
"null... | * 从直播流数据中录制点播,该方法可以指定录制的时间段
@param streamKey 流名称
@param fileName 录制后保存的文件名
@param start 录制开始的时间戳,单位秒
@param end 录制结束的时间戳,单位秒 | [
"*",
"从直播流数据中录制点播,该方法可以指定录制的时间段"
] | train | https://github.com/qiniu/java-sdk/blob/6c05f3fb718403a496c725b048e9241f80171499/src/main/java/com/qiniu/streaming/StreamingManager.java#L153-L155 |
vst/commons-math-extensions | src/main/java/com/vsthost/rnd/commons/math/ext/linear/EMatrixUtils.java | EMatrixUtils.getColumRange | public static RealMatrix getColumRange (RealMatrix matrix, int start, int end) {
return matrix.getSubMatrix(0, matrix.getRowDimension() - 1, start, end);
} | java | public static RealMatrix getColumRange (RealMatrix matrix, int start, int end) {
return matrix.getSubMatrix(0, matrix.getRowDimension() - 1, start, end);
} | [
"public",
"static",
"RealMatrix",
"getColumRange",
"(",
"RealMatrix",
"matrix",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"matrix",
".",
"getSubMatrix",
"(",
"0",
",",
"matrix",
".",
"getRowDimension",
"(",
")",
"-",
"1",
",",
"start",
... | Returns the column range from the matrix as a new matrix.
@param matrix The input matrix
@param start The index of the column to start with (inclusive)
@param end The index of the column to end with (inclusive)
@return A new matrix with columns specified | [
"Returns",
"the",
"column",
"range",
"from",
"the",
"matrix",
"as",
"a",
"new",
"matrix",
"."
] | train | https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/EMatrixUtils.java#L42-L44 |
alkacon/opencms-core | src/org/opencms/loader/CmsJspLoader.java | CmsJspLoader.getReferencingStrongLinks | public void getReferencingStrongLinks(CmsObject cms, CmsResource resource, Set<String> referencingPaths)
throws CmsException {
CmsRelationFilter filter = CmsRelationFilter.SOURCES.filterType(CmsRelationType.JSP_STRONG);
Iterator<CmsRelation> it = cms.getRelationsForResource(resource, filter).iterator();
while (it.hasNext()) {
CmsRelation relation = it.next();
try {
CmsResource source = relation.getSource(cms, CmsResourceFilter.DEFAULT);
// check if file was already included
if (referencingPaths.contains(source.getRootPath())) {
// no need to include this file more than once
continue;
}
referencingPaths.add(source.getRootPath());
getReferencingStrongLinks(cms, source, referencingPaths);
} catch (CmsException e) {
if (LOG.isErrorEnabled()) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
} | java | public void getReferencingStrongLinks(CmsObject cms, CmsResource resource, Set<String> referencingPaths)
throws CmsException {
CmsRelationFilter filter = CmsRelationFilter.SOURCES.filterType(CmsRelationType.JSP_STRONG);
Iterator<CmsRelation> it = cms.getRelationsForResource(resource, filter).iterator();
while (it.hasNext()) {
CmsRelation relation = it.next();
try {
CmsResource source = relation.getSource(cms, CmsResourceFilter.DEFAULT);
// check if file was already included
if (referencingPaths.contains(source.getRootPath())) {
// no need to include this file more than once
continue;
}
referencingPaths.add(source.getRootPath());
getReferencingStrongLinks(cms, source, referencingPaths);
} catch (CmsException e) {
if (LOG.isErrorEnabled()) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
} | [
"public",
"void",
"getReferencingStrongLinks",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"resource",
",",
"Set",
"<",
"String",
">",
"referencingPaths",
")",
"throws",
"CmsException",
"{",
"CmsRelationFilter",
"filter",
"=",
"CmsRelationFilter",
".",
"SOURCES",
"... | Returns a set of root paths of files that are including the given resource using the 'link.strong' macro.<p>
@param cms the current cms context
@param resource the resource to check
@param referencingPaths the set of already referencing paths, also return parameter
@throws CmsException if something goes wrong | [
"Returns",
"a",
"set",
"of",
"root",
"paths",
"of",
"files",
"that",
"are",
"including",
"the",
"given",
"resource",
"using",
"the",
"link",
".",
"strong",
"macro",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/loader/CmsJspLoader.java#L368-L390 |
Stratio/deep-spark | deep-cassandra/src/main/java/com/stratio/deep/cassandra/thrift/ThriftClient.java | ThriftClient.build | public static ThriftClient build(String host, int port, String keyspace) throws TException {
TTransport transport = new TFramedTransport(new TSocket(host, port));
TProtocol protocol = new TBinaryProtocol(transport);
ThriftClient client = new ThriftClient(protocol);
transport.open();
if (keyspace != null) {
client.set_keyspace(keyspace);
}
return client;
} | java | public static ThriftClient build(String host, int port, String keyspace) throws TException {
TTransport transport = new TFramedTransport(new TSocket(host, port));
TProtocol protocol = new TBinaryProtocol(transport);
ThriftClient client = new ThriftClient(protocol);
transport.open();
if (keyspace != null) {
client.set_keyspace(keyspace);
}
return client;
} | [
"public",
"static",
"ThriftClient",
"build",
"(",
"String",
"host",
",",
"int",
"port",
",",
"String",
"keyspace",
")",
"throws",
"TException",
"{",
"TTransport",
"transport",
"=",
"new",
"TFramedTransport",
"(",
"new",
"TSocket",
"(",
"host",
",",
"port",
"... | Returns a new client for the specified host, setting the specified keyspace.
@param host the Cassandra host address.
@param port the Cassandra host RPC port.
@param keyspace the name of the Cassandra keyspace to set.
@return a new client for the specified host, setting the specified keyspace.
@throws TException if there is any problem with the {@code set_keyspace} call. | [
"Returns",
"a",
"new",
"client",
"for",
"the",
"specified",
"host",
"setting",
"the",
"specified",
"keyspace",
"."
] | train | https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-cassandra/src/main/java/com/stratio/deep/cassandra/thrift/ThriftClient.java#L53-L62 |
salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/service/metric/transform/DownsampleTransform.java | DownsampleTransform.downsamplerReducer | public static Double downsamplerReducer(List<Double> values, String reducerType) {
List<Double> operands = new ArrayList<Double>();
for (Double value : values) {
if (value == null) {
operands.add(0.0);
} else {
operands.add(value);
}
}
InternalReducerType type = InternalReducerType.fromString(reducerType);
switch (type) {
case AVG:
return new Mean().evaluate(Doubles.toArray(operands));
case MIN:
return Collections.min(operands);
case MAX:
return Collections.max(operands);
case SUM:
return new Sum().evaluate(Doubles.toArray(operands), 0, operands.size());
case DEVIATION:
return new StandardDeviation().evaluate(Doubles.toArray(operands));
case COUNT:
values.removeAll(Collections.singleton(null));
return (double) values.size();
case PERCENTILE:
return new Percentile().evaluate(Doubles.toArray(operands), Double.parseDouble(reducerType.substring(1)));
default:
throw new UnsupportedOperationException("Illegal type: " + reducerType + ". Please provide a valid type.");
}
} | java | public static Double downsamplerReducer(List<Double> values, String reducerType) {
List<Double> operands = new ArrayList<Double>();
for (Double value : values) {
if (value == null) {
operands.add(0.0);
} else {
operands.add(value);
}
}
InternalReducerType type = InternalReducerType.fromString(reducerType);
switch (type) {
case AVG:
return new Mean().evaluate(Doubles.toArray(operands));
case MIN:
return Collections.min(operands);
case MAX:
return Collections.max(operands);
case SUM:
return new Sum().evaluate(Doubles.toArray(operands), 0, operands.size());
case DEVIATION:
return new StandardDeviation().evaluate(Doubles.toArray(operands));
case COUNT:
values.removeAll(Collections.singleton(null));
return (double) values.size();
case PERCENTILE:
return new Percentile().evaluate(Doubles.toArray(operands), Double.parseDouble(reducerType.substring(1)));
default:
throw new UnsupportedOperationException("Illegal type: " + reducerType + ". Please provide a valid type.");
}
} | [
"public",
"static",
"Double",
"downsamplerReducer",
"(",
"List",
"<",
"Double",
">",
"values",
",",
"String",
"reducerType",
")",
"{",
"List",
"<",
"Double",
">",
"operands",
"=",
"new",
"ArrayList",
"<",
"Double",
">",
"(",
")",
";",
"for",
"(",
"Double... | Implements down sampling.
@param values The values to down sample.
@param reducerType The type of down sampling to perform.
@return The down sampled result.
@throws UnsupportedOperationException If an unknown down sampling type is specified. | [
"Implements",
"down",
"sampling",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/service/metric/transform/DownsampleTransform.java#L76-L107 |
samskivert/samskivert | src/main/java/com/samskivert/velocity/DispatcherServlet.java | DispatcherServlet.instantiateLogic | protected Logic instantiateLogic (String path, String lclass) {
try {
Class<?> pcl = Class.forName(lclass);
return (Logic)pcl.newInstance();
} catch (ClassNotFoundException cnfe) {
// nothing interesting to report
} catch (Throwable t) {
log.warning("Unable to instantiate logic for application", "path", path,
"lclass", lclass, t);
}
return null;
} | java | protected Logic instantiateLogic (String path, String lclass) {
try {
Class<?> pcl = Class.forName(lclass);
return (Logic)pcl.newInstance();
} catch (ClassNotFoundException cnfe) {
// nothing interesting to report
} catch (Throwable t) {
log.warning("Unable to instantiate logic for application", "path", path,
"lclass", lclass, t);
}
return null;
} | [
"protected",
"Logic",
"instantiateLogic",
"(",
"String",
"path",
",",
"String",
"lclass",
")",
"{",
"try",
"{",
"Class",
"<",
"?",
">",
"pcl",
"=",
"Class",
".",
"forName",
"(",
"lclass",
")",
";",
"return",
"(",
"Logic",
")",
"pcl",
".",
"newInstance"... | Instantiates a logic instance with the supplied class name. May return null if no such class
exists. | [
"Instantiates",
"a",
"logic",
"instance",
"with",
"the",
"supplied",
"class",
"name",
".",
"May",
"return",
"null",
"if",
"no",
"such",
"class",
"exists",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/velocity/DispatcherServlet.java#L597-L608 |
andrehertwig/admintool | admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/contoller/ATSecDBAbctractController.java | ATSecDBAbctractController.handleException | protected <E extends Throwable> Set<ATError> handleException(E e, Log logger,
String key, String messageKey, String defaultMessagePrefix) {
return handleException(e, logger, null, key, null, defaultMessagePrefix, new Object[] {});
} | java | protected <E extends Throwable> Set<ATError> handleException(E e, Log logger,
String key, String messageKey, String defaultMessagePrefix) {
return handleException(e, logger, null, key, null, defaultMessagePrefix, new Object[] {});
} | [
"protected",
"<",
"E",
"extends",
"Throwable",
">",
"Set",
"<",
"ATError",
">",
"handleException",
"(",
"E",
"e",
",",
"Log",
"logger",
",",
"String",
"key",
",",
"String",
"messageKey",
",",
"String",
"defaultMessagePrefix",
")",
"{",
"return",
"handleExcep... | logging the error and creates {@link ATError} list output
@param e
@param logger
@param key
@param messageKey
@param defaultMessagePrefix
@return | [
"logging",
"the",
"error",
"and",
"creates",
"{"
] | train | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/contoller/ATSecDBAbctractController.java#L36-L39 |
alkacon/opencms-core | src/org/opencms/util/CmsFileUtil.java | CmsFileUtil.formatResourceNames | public static String formatResourceNames(CmsRequestContext context, List<CmsResource> resources) {
if (resources == null) {
return null;
}
StringBuffer result = new StringBuffer(128);
Iterator<CmsResource> i = resources.iterator();
while (i.hasNext()) {
CmsResource res = i.next();
String path = res.getRootPath();
if (context != null) {
path = context.removeSiteRoot(path);
}
result.append(path);
if (i.hasNext()) {
result.append(", ");
}
}
return result.toString();
} | java | public static String formatResourceNames(CmsRequestContext context, List<CmsResource> resources) {
if (resources == null) {
return null;
}
StringBuffer result = new StringBuffer(128);
Iterator<CmsResource> i = resources.iterator();
while (i.hasNext()) {
CmsResource res = i.next();
String path = res.getRootPath();
if (context != null) {
path = context.removeSiteRoot(path);
}
result.append(path);
if (i.hasNext()) {
result.append(", ");
}
}
return result.toString();
} | [
"public",
"static",
"String",
"formatResourceNames",
"(",
"CmsRequestContext",
"context",
",",
"List",
"<",
"CmsResource",
">",
"resources",
")",
"{",
"if",
"(",
"resources",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"StringBuffer",
"result",
"=",
... | Returns a comma separated list of resource paths names, with the site root
from the given OpenCms user context removed.<p>
@param context the current users OpenCms context (optional, may be <code>null</code>)
@param resources a List of <code>{@link CmsResource}</code> instances to get the names from
@return a comma separated list of resource paths names | [
"Returns",
"a",
"comma",
"separated",
"list",
"of",
"resource",
"paths",
"names",
"with",
"the",
"site",
"root",
"from",
"the",
"given",
"OpenCms",
"user",
"context",
"removed",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsFileUtil.java#L263-L282 |
nutzam/nutzboot | nutzboot-demo/nutzboot-demo-simple/nutzboot-demo-simple-elasticsearch/src/main/java/io/nutz/demo/simple/utils/ElasticsearchUtil.java | ElasticsearchUtil.createOrUpdateData | public boolean createOrUpdateData(String indexName, String type, String id, Object obj) {
IndexResponse response = getClient().prepareIndex(indexName, type).setId(id).setSource(Lang.obj2map(obj)).execute().actionGet();
return response.getResult() == DocWriteResponse.Result.CREATED || response.getResult() == DocWriteResponse.Result.UPDATED;
} | java | public boolean createOrUpdateData(String indexName, String type, String id, Object obj) {
IndexResponse response = getClient().prepareIndex(indexName, type).setId(id).setSource(Lang.obj2map(obj)).execute().actionGet();
return response.getResult() == DocWriteResponse.Result.CREATED || response.getResult() == DocWriteResponse.Result.UPDATED;
} | [
"public",
"boolean",
"createOrUpdateData",
"(",
"String",
"indexName",
",",
"String",
"type",
",",
"String",
"id",
",",
"Object",
"obj",
")",
"{",
"IndexResponse",
"response",
"=",
"getClient",
"(",
")",
".",
"prepareIndex",
"(",
"indexName",
",",
"type",
")... | 创建或更新文档
@param indexName 索引名
@param type 数据类型(表名)
@param id 主键
@param obj 对象
@return | [
"创建或更新文档"
] | train | https://github.com/nutzam/nutzboot/blob/fd33fd4fdce058eab594f28e4d3202f997e3c66a/nutzboot-demo/nutzboot-demo-simple/nutzboot-demo-simple-elasticsearch/src/main/java/io/nutz/demo/simple/utils/ElasticsearchUtil.java#L109-L112 |
apereo/cas | support/cas-server-support-aup-core/src/main/java/org/apereo/cas/aup/AcceptableUsagePolicyStatus.java | AcceptableUsagePolicyStatus.getPropertyOrDefault | public Collection<Object> getPropertyOrDefault(final String name, final Object defaultValue) {
return getPropertyOrDefault(name, CollectionUtils.wrapList(defaultValue));
} | java | public Collection<Object> getPropertyOrDefault(final String name, final Object defaultValue) {
return getPropertyOrDefault(name, CollectionUtils.wrapList(defaultValue));
} | [
"public",
"Collection",
"<",
"Object",
">",
"getPropertyOrDefault",
"(",
"final",
"String",
"name",
",",
"final",
"Object",
"defaultValue",
")",
"{",
"return",
"getPropertyOrDefault",
"(",
"name",
",",
"CollectionUtils",
".",
"wrapList",
"(",
"defaultValue",
")",
... | Gets property or default.
@param name the name
@param defaultValue the default value
@return the property or default | [
"Gets",
"property",
"or",
"default",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-aup-core/src/main/java/org/apereo/cas/aup/AcceptableUsagePolicyStatus.java#L100-L102 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/raw/KeyEncoder.java | KeyEncoder.encodeDesc | public static void encodeDesc(Double value, byte[] dst, int dstOffset) {
if (value == null) {
DataEncoder.encode(~0x7fffffffffffffffL, dst, dstOffset);
} else {
encodeDesc(value.doubleValue(), dst, dstOffset);
}
} | java | public static void encodeDesc(Double value, byte[] dst, int dstOffset) {
if (value == null) {
DataEncoder.encode(~0x7fffffffffffffffL, dst, dstOffset);
} else {
encodeDesc(value.doubleValue(), dst, dstOffset);
}
} | [
"public",
"static",
"void",
"encodeDesc",
"(",
"Double",
"value",
",",
"byte",
"[",
"]",
"dst",
",",
"int",
"dstOffset",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"DataEncoder",
".",
"encode",
"(",
"~",
"0x7fffffffffffffff",
"L",
",",
"dst"... | Encodes the given Double object into exactly 8 bytes for descending
order. A non-canonical NaN value is used to represent null.
@param value optional Double value to encode
@param dst destination for encoded bytes
@param dstOffset offset into destination array | [
"Encodes",
"the",
"given",
"Double",
"object",
"into",
"exactly",
"8",
"bytes",
"for",
"descending",
"order",
".",
"A",
"non",
"-",
"canonical",
"NaN",
"value",
"is",
"used",
"to",
"represent",
"null",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/KeyEncoder.java#L295-L301 |
threerings/narya | core/src/main/java/com/threerings/crowd/chat/client/ChatDirector.java | ChatDirector.displayInfo | public void displayInfo (String bundle, String message)
{
displaySystem(bundle, message, SystemMessage.INFO, PLACE_CHAT_TYPE);
} | java | public void displayInfo (String bundle, String message)
{
displaySystem(bundle, message, SystemMessage.INFO, PLACE_CHAT_TYPE);
} | [
"public",
"void",
"displayInfo",
"(",
"String",
"bundle",
",",
"String",
"message",
")",
"{",
"displaySystem",
"(",
"bundle",
",",
"message",
",",
"SystemMessage",
".",
"INFO",
",",
"PLACE_CHAT_TYPE",
")",
";",
"}"
] | Display a system INFO message as if it had come from the server. The localtype of the
message will be PLACE_CHAT_TYPE.
Info messages are sent when something happens that was neither directly triggered by the
user, nor requires direct action. | [
"Display",
"a",
"system",
"INFO",
"message",
"as",
"if",
"it",
"had",
"come",
"from",
"the",
"server",
".",
"The",
"localtype",
"of",
"the",
"message",
"will",
"be",
"PLACE_CHAT_TYPE",
"."
] | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/client/ChatDirector.java#L321-L324 |
Graylog2/graylog2-server | graylog2-server/src/main/java/org/graylog2/plugin/Version.java | Version.fromClasspathProperties | public static Version fromClasspathProperties(@Nonnull Class<?> clazz, String path, String propertyName, String gitPath, String gitPropertyName, Version defaultVersion) {
try {
final URL resource = getResource(clazz, path);
final Properties versionProperties = new Properties();
versionProperties.load(resource.openStream());
final com.github.zafarkhaja.semver.Version version = com.github.zafarkhaja.semver.Version.valueOf(versionProperties.getProperty(propertyName));
final int major = version.getMajorVersion();
final int minor = version.getMinorVersion();
final int patch = version.getPatchVersion();
final String qualifier = version.getPreReleaseVersion();
String commitSha = null;
try {
final Properties git = new Properties();
final URL gitResource = getResource(clazz, gitPath);
git.load(gitResource.openStream());
commitSha = git.getProperty(gitPropertyName);
// abbreviate if present and looks like a long sha
if (commitSha != null && commitSha.length() > 7) {
commitSha = commitSha.substring(0, 7);
}
} catch (Exception e) {
LOG.debug("Git commit details are not available, skipping.", e);
}
return from(major, minor, patch, qualifier, commitSha);
} catch (Exception e) {
LOG.error("Unable to read " + path + ", this build has no version number.", e);
}
return defaultVersion;
} | java | public static Version fromClasspathProperties(@Nonnull Class<?> clazz, String path, String propertyName, String gitPath, String gitPropertyName, Version defaultVersion) {
try {
final URL resource = getResource(clazz, path);
final Properties versionProperties = new Properties();
versionProperties.load(resource.openStream());
final com.github.zafarkhaja.semver.Version version = com.github.zafarkhaja.semver.Version.valueOf(versionProperties.getProperty(propertyName));
final int major = version.getMajorVersion();
final int minor = version.getMinorVersion();
final int patch = version.getPatchVersion();
final String qualifier = version.getPreReleaseVersion();
String commitSha = null;
try {
final Properties git = new Properties();
final URL gitResource = getResource(clazz, gitPath);
git.load(gitResource.openStream());
commitSha = git.getProperty(gitPropertyName);
// abbreviate if present and looks like a long sha
if (commitSha != null && commitSha.length() > 7) {
commitSha = commitSha.substring(0, 7);
}
} catch (Exception e) {
LOG.debug("Git commit details are not available, skipping.", e);
}
return from(major, minor, patch, qualifier, commitSha);
} catch (Exception e) {
LOG.error("Unable to read " + path + ", this build has no version number.", e);
}
return defaultVersion;
} | [
"public",
"static",
"Version",
"fromClasspathProperties",
"(",
"@",
"Nonnull",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"path",
",",
"String",
"propertyName",
",",
"String",
"gitPath",
",",
"String",
"gitPropertyName",
",",
"Version",
"defaultVersion",
")... | Try to read the version from {@code path} ({@code propertyName} property)
and {@code gitPath} ({@code gitPropertyName} property) from the classpath.
@param clazz Class where the class loader should be obtained from.
@param path Path of the properties file on the classpath which contains the version information.
@param propertyName The name of the property to read as project version ("major.minor.patch-preReleaseVersion").
@param gitPath Path of the properties file on the classpath which contains the SCM information.
@param gitPropertyName The name of the property to read as git commit SHA.
@param defaultVersion The {@link Version} to return if reading the information from the properties files failed. | [
"Try",
"to",
"read",
"the",
"version",
"from",
"{",
"@code",
"path",
"}",
"(",
"{",
"@code",
"propertyName",
"}",
"property",
")",
"and",
"{",
"@code",
"gitPath",
"}",
"(",
"{",
"@code",
"gitPropertyName",
"}",
"property",
")",
"from",
"the",
"classpath"... | train | https://github.com/Graylog2/graylog2-server/blob/50b565dcead6e0a372236d5c2f8530dc5726fa9b/graylog2-server/src/main/java/org/graylog2/plugin/Version.java#L213-L244 |
OpenLiberty/open-liberty | dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/ws/JoblogUtil.java | JoblogUtil.logRawMsgToJobLogAndTrace | @Trivial
public static void logRawMsgToJobLogAndTrace(Level level, String msg, Logger traceLogger){
logToJoblogIfNotTraceLoggable(level, msg, traceLogger);
logToTrace(level, msg, traceLogger);
} | java | @Trivial
public static void logRawMsgToJobLogAndTrace(Level level, String msg, Logger traceLogger){
logToJoblogIfNotTraceLoggable(level, msg, traceLogger);
logToTrace(level, msg, traceLogger);
} | [
"@",
"Trivial",
"public",
"static",
"void",
"logRawMsgToJobLogAndTrace",
"(",
"Level",
"level",
",",
"String",
"msg",
",",
"Logger",
"traceLogger",
")",
"{",
"logToJoblogIfNotTraceLoggable",
"(",
"level",
",",
"msg",
",",
"traceLogger",
")",
";",
"logToTrace",
"... | logs the message to joblog and trace.
Joblog and trace.log messages will be logged as per supplied logging level
@param level logging level the message was logged at by the code writing the log msg.
@param rawMsg Message is complete, it has already been translated with parameters a filled in,
or it is a raw, non-translated message like an exception or similar trace.
@param traceLogger Logger to use to attempt to log message to trace.log (whether it will or not
depends on config) | [
"logs",
"the",
"message",
"to",
"joblog",
"and",
"trace",
".",
"Joblog",
"and",
"trace",
".",
"log",
"messages",
"will",
"be",
"logged",
"as",
"per",
"supplied",
"logging",
"level"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/ws/JoblogUtil.java#L106-L111 |
phax/ph-oton | ph-oton-uicore/src/main/java/com/helger/photon/uicore/page/handler/AbstractWebPageActionHandlerUndelete.java | AbstractWebPageActionHandlerUndelete.createUndeleteToolbar | @Nonnull
@OverrideOnDemand
protected TOOLBAR_TYPE createUndeleteToolbar (@Nonnull final WPECTYPE aWPEC,
@Nonnull final FORM_TYPE aForm,
@Nonnull final DATATYPE aSelectedObject)
{
final Locale aDisplayLocale = aWPEC.getDisplayLocale ();
final TOOLBAR_TYPE aToolbar = getUIHandler ().createToolbar (aWPEC);
aToolbar.addHiddenField (CPageParam.PARAM_ACTION, CPageParam.ACTION_UNDELETE);
aToolbar.addHiddenField (CPageParam.PARAM_SUBACTION, CPageParam.ACTION_SAVE);
aToolbar.addHiddenField (CPageParam.PARAM_OBJECT, aSelectedObject.getID ());
// Yes button
aToolbar.addSubmitButton (getUndeleteToolbarSubmitButtonText (aDisplayLocale),
getUndeleteToolbarSubmitButtonIcon ());
// No button
aToolbar.addButtonNo (aDisplayLocale);
// Callback
modifyUndeleteToolbar (aWPEC, aToolbar);
return aToolbar;
} | java | @Nonnull
@OverrideOnDemand
protected TOOLBAR_TYPE createUndeleteToolbar (@Nonnull final WPECTYPE aWPEC,
@Nonnull final FORM_TYPE aForm,
@Nonnull final DATATYPE aSelectedObject)
{
final Locale aDisplayLocale = aWPEC.getDisplayLocale ();
final TOOLBAR_TYPE aToolbar = getUIHandler ().createToolbar (aWPEC);
aToolbar.addHiddenField (CPageParam.PARAM_ACTION, CPageParam.ACTION_UNDELETE);
aToolbar.addHiddenField (CPageParam.PARAM_SUBACTION, CPageParam.ACTION_SAVE);
aToolbar.addHiddenField (CPageParam.PARAM_OBJECT, aSelectedObject.getID ());
// Yes button
aToolbar.addSubmitButton (getUndeleteToolbarSubmitButtonText (aDisplayLocale),
getUndeleteToolbarSubmitButtonIcon ());
// No button
aToolbar.addButtonNo (aDisplayLocale);
// Callback
modifyUndeleteToolbar (aWPEC, aToolbar);
return aToolbar;
} | [
"@",
"Nonnull",
"@",
"OverrideOnDemand",
"protected",
"TOOLBAR_TYPE",
"createUndeleteToolbar",
"(",
"@",
"Nonnull",
"final",
"WPECTYPE",
"aWPEC",
",",
"@",
"Nonnull",
"final",
"FORM_TYPE",
"aForm",
",",
"@",
"Nonnull",
"final",
"DATATYPE",
"aSelectedObject",
")",
... | Create toolbar for undeleting an existing object
@param aWPEC
The web page execution context
@param aForm
The handled form. Never <code>null</code>.
@param aSelectedObject
Selected object. Never <code>null</code>.
@return Never <code>null</code>. | [
"Create",
"toolbar",
"for",
"undeleting",
"an",
"existing",
"object"
] | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-uicore/src/main/java/com/helger/photon/uicore/page/handler/AbstractWebPageActionHandlerUndelete.java#L125-L146 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/StringUtils.java | StringUtils.replaceEachRepeatedly | public static String replaceEachRepeatedly(final String text, final String[] searchList, final String[] replacementList) {
// timeToLive should be 0 if not used or nothing to replace, else it's
// the length of the replace array
final int timeToLive = searchList == null ? 0 : searchList.length;
return replaceEach(text, searchList, replacementList, true, timeToLive);
} | java | public static String replaceEachRepeatedly(final String text, final String[] searchList, final String[] replacementList) {
// timeToLive should be 0 if not used or nothing to replace, else it's
// the length of the replace array
final int timeToLive = searchList == null ? 0 : searchList.length;
return replaceEach(text, searchList, replacementList, true, timeToLive);
} | [
"public",
"static",
"String",
"replaceEachRepeatedly",
"(",
"final",
"String",
"text",
",",
"final",
"String",
"[",
"]",
"searchList",
",",
"final",
"String",
"[",
"]",
"replacementList",
")",
"{",
"// timeToLive should be 0 if not used or nothing to replace, else it's",
... | <p>
Replaces all occurrences of Strings within another String.
</p>
<p>
A {@code null} reference passed to this method is a no-op, or if
any "search string" or "string to replace" is null, that replace will be
ignored.
</p>
<pre>
StringUtils.replaceEachRepeatedly(null, *, *) = null
StringUtils.replaceEachRepeatedly("", *, *) = ""
StringUtils.replaceEachRepeatedly("aba", null, null) = "aba"
StringUtils.replaceEachRepeatedly("aba", new String[0], null) = "aba"
StringUtils.replaceEachRepeatedly("aba", null, new String[0]) = "aba"
StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, null) = "aba"
StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""}) = "b"
StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"}) = "aba"
StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
(example of how it repeats)
StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "tcte"
StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}) = IllegalStateException
</pre>
@param text
text to search and replace in, no-op if null
@param searchList
the Strings to search for, no-op if null
@param replacementList
the Strings to replace them with, no-op if null
@return the text with any replacements processed, {@code null} if
null String input
@throws IllegalStateException
if the search is repeating and there is an endless loop due
to outputs of one being inputs to another
@throws IllegalArgumentException
if the lengths of the arrays are not the same (null is ok,
and/or size 0)
@since 2.4 | [
"<p",
">",
"Replaces",
"all",
"occurrences",
"of",
"Strings",
"within",
"another",
"String",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L5657-L5662 |
opencb/datastore | datastore-core/src/main/java/org/opencb/datastore/core/QueryOptions.java | QueryOptions.addToListOption | public Object addToListOption(String key, Object value) {
if (key != null && !key.equals("")) {
if (this.containsKey(key) && this.get(key) != null) {
if (!(this.get(key) instanceof List)) { //If was not a list, getAsList returns an Unmodifiable List.
// Create new modifiable List with the content, and replace.
this.put(key, new ArrayList<>(this.getAsList(key)));
}
try {
this.getList(key).add(value);
} catch (UnsupportedOperationException e) {
List<Object> list = new ArrayList<>(this.getList(key));
list.add(value);
this.put(key, list);
}
} else {
List<Object> list = new ArrayList<>(); //New List instead of "Arrays.asList" or "Collections.singletonList" to avoid unmodifiable list.
list.add(value);
this.put(key, list);
}
return this.getList(key);
}
return null;
} | java | public Object addToListOption(String key, Object value) {
if (key != null && !key.equals("")) {
if (this.containsKey(key) && this.get(key) != null) {
if (!(this.get(key) instanceof List)) { //If was not a list, getAsList returns an Unmodifiable List.
// Create new modifiable List with the content, and replace.
this.put(key, new ArrayList<>(this.getAsList(key)));
}
try {
this.getList(key).add(value);
} catch (UnsupportedOperationException e) {
List<Object> list = new ArrayList<>(this.getList(key));
list.add(value);
this.put(key, list);
}
} else {
List<Object> list = new ArrayList<>(); //New List instead of "Arrays.asList" or "Collections.singletonList" to avoid unmodifiable list.
list.add(value);
this.put(key, list);
}
return this.getList(key);
}
return null;
} | [
"public",
"Object",
"addToListOption",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"key",
"!=",
"null",
"&&",
"!",
"key",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"if",
"(",
"this",
".",
"containsKey",
"(",
"key",
")",
"&&"... | This method safely add a new Object to an exiting option which type is List.
@param key
@param value
@return the list with the new Object inserted. | [
"This",
"method",
"safely",
"add",
"a",
"new",
"Object",
"to",
"an",
"exiting",
"option",
"which",
"type",
"is",
"List",
"."
] | train | https://github.com/opencb/datastore/blob/c6b92b30385d5fc5cc191e2db96c46b0389a88c7/datastore-core/src/main/java/org/opencb/datastore/core/QueryOptions.java#L86-L108 |
iipc/webarchive-commons | src/main/java/org/archive/format/text/charset/CharsetDetector.java | CharsetDetector.getCharsetFromBytes | protected String getCharsetFromBytes(byte buffer[], int len)
throws IOException {
String charsetName = null;
UniversalDetector detector = new UniversalDetector(null);
detector.handleData(buffer, 0, len);
detector.dataEnd();
charsetName = detector.getDetectedCharset();
detector.reset();
if(isCharsetSupported(charsetName)) {
return mapCharset(charsetName);
}
return null;
} | java | protected String getCharsetFromBytes(byte buffer[], int len)
throws IOException {
String charsetName = null;
UniversalDetector detector = new UniversalDetector(null);
detector.handleData(buffer, 0, len);
detector.dataEnd();
charsetName = detector.getDetectedCharset();
detector.reset();
if(isCharsetSupported(charsetName)) {
return mapCharset(charsetName);
}
return null;
} | [
"protected",
"String",
"getCharsetFromBytes",
"(",
"byte",
"buffer",
"[",
"]",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"String",
"charsetName",
"=",
"null",
";",
"UniversalDetector",
"detector",
"=",
"new",
"UniversalDetector",
"(",
"null",
")",
... | Attempts to figure out the character set of the document using
the excellent juniversalchardet library.
@param resource
@return String character encoding found, or null if nothing looked good.
@throws IOException | [
"Attempts",
"to",
"figure",
"out",
"the",
"character",
"set",
"of",
"the",
"document",
"using",
"the",
"excellent",
"juniversalchardet",
"library",
"."
] | train | https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/format/text/charset/CharsetDetector.java#L231-L243 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.