repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
depsypher/pngtastic | src/main/java/com/googlecode/pngtastic/core/processing/Base64.java | Base64.decodeFileToFile | public static void decodeFileToFile(String infile, String outfile) throws IOException {
byte[] decoded = Base64.decodeFromFile(infile);
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(new FileOutputStream(outfile));
out.write(decoded);
} catch (IOException e) {
throw e; // Catch and release to execute finally{}
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception ex) {
}
}
} | java | public static void decodeFileToFile(String infile, String outfile) throws IOException {
byte[] decoded = Base64.decodeFromFile(infile);
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(new FileOutputStream(outfile));
out.write(decoded);
} catch (IOException e) {
throw e; // Catch and release to execute finally{}
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception ex) {
}
}
} | [
"public",
"static",
"void",
"decodeFileToFile",
"(",
"String",
"infile",
",",
"String",
"outfile",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"decoded",
"=",
"Base64",
".",
"decodeFromFile",
"(",
"infile",
")",
";",
"java",
".",
"io",
".",
"Outpu... | Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
@param infile Input file
@param outfile Output file
@throws java.io.IOException if there is an error
@since 2.2 | [
"Reads",
"<tt",
">",
"infile<",
"/",
"tt",
">",
"and",
"decodes",
"it",
"to",
"<tt",
">",
"outfile<",
"/",
"tt",
">",
"."
] | train | https://github.com/depsypher/pngtastic/blob/13fd2a63dd8b2febd7041273889a1bba4f2a6a07/src/main/java/com/googlecode/pngtastic/core/processing/Base64.java#L1470-L1486 |
Syncleus/aparapi | src/main/java/com/aparapi/internal/kernel/KernelProfile.java | KernelProfile.onStart | void onStart(Device device) {
KernelDeviceProfile currentDeviceProfile = deviceProfiles.get(device);
if (currentDeviceProfile == null) {
currentDeviceProfile = new KernelDeviceProfile(this, kernelClass, device);
KernelDeviceProfile existingProfile = deviceProfiles.putIfAbsent(device, currentDeviceProfile);
if (existingProfile != null) {
currentDeviceProfile = existingProfile;
}
}
currentDeviceProfile.onEvent(ProfilingEvent.START);
currentDevice.set(device);
} | java | void onStart(Device device) {
KernelDeviceProfile currentDeviceProfile = deviceProfiles.get(device);
if (currentDeviceProfile == null) {
currentDeviceProfile = new KernelDeviceProfile(this, kernelClass, device);
KernelDeviceProfile existingProfile = deviceProfiles.putIfAbsent(device, currentDeviceProfile);
if (existingProfile != null) {
currentDeviceProfile = existingProfile;
}
}
currentDeviceProfile.onEvent(ProfilingEvent.START);
currentDevice.set(device);
} | [
"void",
"onStart",
"(",
"Device",
"device",
")",
"{",
"KernelDeviceProfile",
"currentDeviceProfile",
"=",
"deviceProfiles",
".",
"get",
"(",
"device",
")",
";",
"if",
"(",
"currentDeviceProfile",
"==",
"null",
")",
"{",
"currentDeviceProfile",
"=",
"new",
"Kerne... | Starts a profiling information gathering sequence for the current thread invoking this method
regarding the specified execution device.
@param device | [
"Starts",
"a",
"profiling",
"information",
"gathering",
"sequence",
"for",
"the",
"current",
"thread",
"invoking",
"this",
"method",
"regarding",
"the",
"specified",
"execution",
"device",
"."
] | train | https://github.com/Syncleus/aparapi/blob/6d5892c8e69854b3968c541023de37cf4762bd24/src/main/java/com/aparapi/internal/kernel/KernelProfile.java#L76-L88 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerIdentityImpl.java | TransformerIdentityImpl.processingInstruction | public void processingInstruction(String target, String data)
throws SAXException
{
flushStartDoc();
m_resultContentHandler.processingInstruction(target, data);
} | java | public void processingInstruction(String target, String data)
throws SAXException
{
flushStartDoc();
m_resultContentHandler.processingInstruction(target, data);
} | [
"public",
"void",
"processingInstruction",
"(",
"String",
"target",
",",
"String",
"data",
")",
"throws",
"SAXException",
"{",
"flushStartDoc",
"(",
")",
";",
"m_resultContentHandler",
".",
"processingInstruction",
"(",
"target",
",",
"data",
")",
";",
"}"
] | Receive notification of a processing instruction.
<p>By default, do nothing. Application writers may override this
method in a subclass to take specific actions for each
processing instruction, such as setting status variables or
invoking other methods.</p>
@param target The processing instruction target.
@param data The processing instruction data, or null if
none is supplied.
@throws org.xml.sax.SAXException Any SAX exception, possibly
wrapping another exception.
@see org.xml.sax.ContentHandler#processingInstruction
@throws SAXException | [
"Receive",
"notification",
"of",
"a",
"processing",
"instruction",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerIdentityImpl.java#L1170-L1175 |
Impetus/Kundera | src/jpa-engine/fallback-impl/src/main/java/com/impetus/kundera/index/LuceneIndexer.java | LuceneIndexer.updateDocument | public void updateDocument(String id, Document document, String EmbeddedEntityFieldName)
{
if (log.isDebugEnabled())
{
log.debug("Updateing indexed document: {} for in file system using Lucene", document);
}
IndexWriter w = getIndexWriter();
try
{
Term term = null;
if (EmbeddedEntityFieldName == null)
{
term = new Term(IndexingConstants.ENTITY_ID_FIELD, id);
}
else
{
term = new Term(EmbeddedEntityFieldName, id);
}
w.updateDocument(term, document);
}
catch (LuceneIndexingException lie)
{
log.error("Error while updating LuceneIndexer, Caused by :.", lie);
throw new LuceneIndexingException(lie);
}
catch (IOException ioe)
{
log.error("Error while reading Lucene indexes, Caused by :.", ioe);
}
} | java | public void updateDocument(String id, Document document, String EmbeddedEntityFieldName)
{
if (log.isDebugEnabled())
{
log.debug("Updateing indexed document: {} for in file system using Lucene", document);
}
IndexWriter w = getIndexWriter();
try
{
Term term = null;
if (EmbeddedEntityFieldName == null)
{
term = new Term(IndexingConstants.ENTITY_ID_FIELD, id);
}
else
{
term = new Term(EmbeddedEntityFieldName, id);
}
w.updateDocument(term, document);
}
catch (LuceneIndexingException lie)
{
log.error("Error while updating LuceneIndexer, Caused by :.", lie);
throw new LuceneIndexingException(lie);
}
catch (IOException ioe)
{
log.error("Error while reading Lucene indexes, Caused by :.", ioe);
}
} | [
"public",
"void",
"updateDocument",
"(",
"String",
"id",
",",
"Document",
"document",
",",
"String",
"EmbeddedEntityFieldName",
")",
"{",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Updateing indexed document: {} for... | Indexes document in file system using lucene.
@param metadata
the metadata
@param document
the document | [
"Indexes",
"document",
"in",
"file",
"system",
"using",
"lucene",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/fallback-impl/src/main/java/com/impetus/kundera/index/LuceneIndexer.java#L498-L530 |
jglobus/JGlobus | io/src/main/java/org/globus/io/gass/server/JobOutputStream.java | JobOutputStream.write | public void write(byte[] b, int off, int len)
throws IOException {
String s = new String(b, off, len);
listener.outputChanged(s);
} | java | public void write(byte[] b, int off, int len)
throws IOException {
String s = new String(b, off, len);
listener.outputChanged(s);
} | [
"public",
"void",
"write",
"(",
"byte",
"[",
"]",
"b",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"String",
"s",
"=",
"new",
"String",
"(",
"b",
",",
"off",
",",
"len",
")",
";",
"listener",
".",
"outputChanged",
"(",
... | Converts the byte array to a string and forwards
it to the job output listener.
<BR>Called by the GassServer. | [
"Converts",
"the",
"byte",
"array",
"to",
"a",
"string",
"and",
"forwards",
"it",
"to",
"the",
"job",
"output",
"listener",
".",
"<BR",
">",
"Called",
"by",
"the",
"GassServer",
"."
] | train | https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/io/src/main/java/org/globus/io/gass/server/JobOutputStream.java#L57-L61 |
brettwooldridge/HikariCP | src/main/java/com/zaxxer/hikari/util/UtilityElf.java | UtilityElf.createThreadPoolExecutor | public static ThreadPoolExecutor createThreadPoolExecutor(final int queueSize, final String threadName, ThreadFactory threadFactory, final RejectedExecutionHandler policy)
{
if (threadFactory == null) {
threadFactory = new DefaultThreadFactory(threadName, true);
}
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(queueSize);
ThreadPoolExecutor executor = new ThreadPoolExecutor(1 /*core*/, 1 /*max*/, 5 /*keepalive*/, SECONDS, queue, threadFactory, policy);
executor.allowCoreThreadTimeOut(true);
return executor;
} | java | public static ThreadPoolExecutor createThreadPoolExecutor(final int queueSize, final String threadName, ThreadFactory threadFactory, final RejectedExecutionHandler policy)
{
if (threadFactory == null) {
threadFactory = new DefaultThreadFactory(threadName, true);
}
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(queueSize);
ThreadPoolExecutor executor = new ThreadPoolExecutor(1 /*core*/, 1 /*max*/, 5 /*keepalive*/, SECONDS, queue, threadFactory, policy);
executor.allowCoreThreadTimeOut(true);
return executor;
} | [
"public",
"static",
"ThreadPoolExecutor",
"createThreadPoolExecutor",
"(",
"final",
"int",
"queueSize",
",",
"final",
"String",
"threadName",
",",
"ThreadFactory",
"threadFactory",
",",
"final",
"RejectedExecutionHandler",
"policy",
")",
"{",
"if",
"(",
"threadFactory",... | Create a ThreadPoolExecutor.
@param queueSize the queue size
@param threadName the thread name
@param threadFactory an optional ThreadFactory
@param policy the RejectedExecutionHandler policy
@return a ThreadPoolExecutor | [
"Create",
"a",
"ThreadPoolExecutor",
"."
] | train | https://github.com/brettwooldridge/HikariCP/blob/c509ec1a3f1e19769ee69323972f339cf098ff4b/src/main/java/com/zaxxer/hikari/util/UtilityElf.java#L125-L135 |
duracloud/duracloud | irodsstorageprovider/src/main/java/org/duracloud/irodsstorage/IrodsStorageProvider.java | IrodsStorageProvider.getSpaces | @Override
public Iterator<String> getSpaces() {
ConnectOperation co =
new ConnectOperation(host, port, username, password, zone);
log.trace("Listing spaces");
try {
return listDirectories(baseDirectory, co.getConnection());
} catch (IOException e) {
log.error("Could not connect to iRODS", e);
throw new StorageException(e);
}
} | java | @Override
public Iterator<String> getSpaces() {
ConnectOperation co =
new ConnectOperation(host, port, username, password, zone);
log.trace("Listing spaces");
try {
return listDirectories(baseDirectory, co.getConnection());
} catch (IOException e) {
log.error("Could not connect to iRODS", e);
throw new StorageException(e);
}
} | [
"@",
"Override",
"public",
"Iterator",
"<",
"String",
">",
"getSpaces",
"(",
")",
"{",
"ConnectOperation",
"co",
"=",
"new",
"ConnectOperation",
"(",
"host",
",",
"port",
",",
"username",
",",
"password",
",",
"zone",
")",
";",
"log",
".",
"trace",
"(",
... | Return a list of irods spaces. IRODS spaces are directories under
the baseDirectory of this provider.
@return | [
"Return",
"a",
"list",
"of",
"irods",
"spaces",
".",
"IRODS",
"spaces",
"are",
"directories",
"under",
"the",
"baseDirectory",
"of",
"this",
"provider",
"."
] | train | https://github.com/duracloud/duracloud/blob/dc4f3a1716d43543cc3b2e1880605f9389849b66/irodsstorageprovider/src/main/java/org/duracloud/irodsstorage/IrodsStorageProvider.java#L104-L116 |
apache/reef | lang/java/reef-common/src/main/java/org/apache/reef/runtime/common/driver/evaluator/AllocatedEvaluatorImpl.java | AllocatedEvaluatorImpl.makeEvaluatorConfiguration | private Configuration makeEvaluatorConfiguration(final Configuration contextConfiguration,
final Optional<Configuration> serviceConfiguration,
final Optional<Configuration> taskConfiguration) {
final String contextConfigurationString = this.configurationSerializer.toString(contextConfiguration);
final Optional<String> taskConfigurationString;
if (taskConfiguration.isPresent()) {
taskConfigurationString = Optional.of(this.configurationSerializer.toString(taskConfiguration.get()));
} else {
taskConfigurationString = Optional.empty();
}
final Optional<Configuration> mergedServiceConfiguration = makeRootServiceConfiguration(serviceConfiguration);
if (mergedServiceConfiguration.isPresent()) {
final String serviceConfigurationString = this.configurationSerializer.toString(mergedServiceConfiguration.get());
return makeEvaluatorConfiguration(contextConfigurationString, Optional.<String>empty(),
Optional.of(serviceConfigurationString), taskConfigurationString);
} else {
return makeEvaluatorConfiguration(
contextConfigurationString, Optional.<String>empty(), Optional.<String>empty(), taskConfigurationString);
}
} | java | private Configuration makeEvaluatorConfiguration(final Configuration contextConfiguration,
final Optional<Configuration> serviceConfiguration,
final Optional<Configuration> taskConfiguration) {
final String contextConfigurationString = this.configurationSerializer.toString(contextConfiguration);
final Optional<String> taskConfigurationString;
if (taskConfiguration.isPresent()) {
taskConfigurationString = Optional.of(this.configurationSerializer.toString(taskConfiguration.get()));
} else {
taskConfigurationString = Optional.empty();
}
final Optional<Configuration> mergedServiceConfiguration = makeRootServiceConfiguration(serviceConfiguration);
if (mergedServiceConfiguration.isPresent()) {
final String serviceConfigurationString = this.configurationSerializer.toString(mergedServiceConfiguration.get());
return makeEvaluatorConfiguration(contextConfigurationString, Optional.<String>empty(),
Optional.of(serviceConfigurationString), taskConfigurationString);
} else {
return makeEvaluatorConfiguration(
contextConfigurationString, Optional.<String>empty(), Optional.<String>empty(), taskConfigurationString);
}
} | [
"private",
"Configuration",
"makeEvaluatorConfiguration",
"(",
"final",
"Configuration",
"contextConfiguration",
",",
"final",
"Optional",
"<",
"Configuration",
">",
"serviceConfiguration",
",",
"final",
"Optional",
"<",
"Configuration",
">",
"taskConfiguration",
")",
"{"... | Make configuration for evaluator.
@param contextConfiguration
@param serviceConfiguration
@param taskConfiguration
@return Configuration | [
"Make",
"configuration",
"for",
"evaluator",
"."
] | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-common/src/main/java/org/apache/reef/runtime/common/driver/evaluator/AllocatedEvaluatorImpl.java#L279-L301 |
livetribe/livetribe-slp | core/src/main/java/org/livetribe/slp/Attributes.java | Attributes.from | public static Attributes from(Map<String, String> stringMap)
{
if (stringMap == null || stringMap.size() == 0) return NONE;
Attributes result = new Attributes();
for (Map.Entry<String, String> entry : stringMap.entrySet())
{
result.attributes.put(Tag.from(entry.getKey(), false), Value.from(entry.getValue()));
}
return result;
} | java | public static Attributes from(Map<String, String> stringMap)
{
if (stringMap == null || stringMap.size() == 0) return NONE;
Attributes result = new Attributes();
for (Map.Entry<String, String> entry : stringMap.entrySet())
{
result.attributes.put(Tag.from(entry.getKey(), false), Value.from(entry.getValue()));
}
return result;
} | [
"public",
"static",
"Attributes",
"from",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"stringMap",
")",
"{",
"if",
"(",
"stringMap",
"==",
"null",
"||",
"stringMap",
".",
"size",
"(",
")",
"==",
"0",
")",
"return",
"NONE",
";",
"Attributes",
"result... | Creates an <code>Attributes</code> object converting the given string map.
The keys and values are not escaped.
@param stringMap The string map containing the attributes convert
@return a new Attributes instance obtained converting the given string map
@throws ServiceLocationException If the conversion fails | [
"Creates",
"an",
"<code",
">",
"Attributes<",
"/",
"code",
">",
"object",
"converting",
"the",
"given",
"string",
"map",
".",
"The",
"keys",
"and",
"values",
"are",
"not",
"escaped",
"."
] | train | https://github.com/livetribe/livetribe-slp/blob/6cc13dbe81feab133fe3dd291ca081cbc6e1f591/core/src/main/java/org/livetribe/slp/Attributes.java#L95-L107 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java | ApiOvhDedicatedCloud.serviceName_changeProperties_POST | public OvhTask serviceName_changeProperties_POST(String serviceName, String description, Boolean sslV3, OvhUserAccessPolicyEnum userAccessPolicy, Long userLimitConcurrentSession, OvhUserLogoutPolicyEnum userLogoutPolicy, Long userSessionTimeout) throws IOException {
String qPath = "/dedicatedCloud/{serviceName}/changeProperties";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "description", description);
addBody(o, "sslV3", sslV3);
addBody(o, "userAccessPolicy", userAccessPolicy);
addBody(o, "userLimitConcurrentSession", userLimitConcurrentSession);
addBody(o, "userLogoutPolicy", userLogoutPolicy);
addBody(o, "userSessionTimeout", userSessionTimeout);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask serviceName_changeProperties_POST(String serviceName, String description, Boolean sslV3, OvhUserAccessPolicyEnum userAccessPolicy, Long userLimitConcurrentSession, OvhUserLogoutPolicyEnum userLogoutPolicy, Long userSessionTimeout) throws IOException {
String qPath = "/dedicatedCloud/{serviceName}/changeProperties";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "description", description);
addBody(o, "sslV3", sslV3);
addBody(o, "userAccessPolicy", userAccessPolicy);
addBody(o, "userLimitConcurrentSession", userLimitConcurrentSession);
addBody(o, "userLogoutPolicy", userLogoutPolicy);
addBody(o, "userSessionTimeout", userSessionTimeout);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"serviceName_changeProperties_POST",
"(",
"String",
"serviceName",
",",
"String",
"description",
",",
"Boolean",
"sslV3",
",",
"OvhUserAccessPolicyEnum",
"userAccessPolicy",
",",
"Long",
"userLimitConcurrentSession",
",",
"OvhUserLogoutPolicyEnum",
"userL... | Update this Private Cloud properties.
REST: POST /dedicatedCloud/{serviceName}/changeProperties
@param sslV3 [required] Enable SSL v3 support. Warning: this option is not recommended as it was recognized as a security breach. If this is enabled, we advise you to enable the filtered User access policy
@param userLimitConcurrentSession [required] The maximum amount of connected users allowed on the Private Cloud management interface
@param description [required] Description of your Private Cloud
@param userLogoutPolicy [required] Logout policy of your Private Cloud
@param userAccessPolicy [required] Access policy of your Private Cloud: opened to every IPs or filtered
@param userSessionTimeout [required] The timeout (in seconds) for the user sessions on the Private Cloud management interface. 0 value disable the timeout
@param serviceName [required] Domain of the service | [
"Update",
"this",
"Private",
"Cloud",
"properties",
"."
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L1195-L1207 |
michael-rapp/AndroidBottomSheet | library/src/main/java/de/mrapp/android/bottomsheet/BottomSheet.java | BottomSheet.setItem | public final void setItem(final int index, final int id, @NonNull final CharSequence title,
@Nullable final Drawable icon) {
Item item = new Item(id, title);
item.setIcon(icon);
adapter.set(index, item);
adaptGridViewHeight();
} | java | public final void setItem(final int index, final int id, @NonNull final CharSequence title,
@Nullable final Drawable icon) {
Item item = new Item(id, title);
item.setIcon(icon);
adapter.set(index, item);
adaptGridViewHeight();
} | [
"public",
"final",
"void",
"setItem",
"(",
"final",
"int",
"index",
",",
"final",
"int",
"id",
",",
"@",
"NonNull",
"final",
"CharSequence",
"title",
",",
"@",
"Nullable",
"final",
"Drawable",
"icon",
")",
"{",
"Item",
"item",
"=",
"new",
"Item",
"(",
... | Replaces the item at a specific index with another item.
@param index
The index of the item, which should be replaced, as an {@link Integer} value
@param id
The id of the item, which should be added, as an {@link Integer} value. The id must
be at least 0
@param title
The title of the item, which should be added, as an instance of the type {@link
CharSequence}. The title may neither be null, nor empty
@param icon
The icon of the item, which should be added, as an instance of the class {@link
Drawable}, or null, if no item should be used | [
"Replaces",
"the",
"item",
"at",
"a",
"specific",
"index",
"with",
"another",
"item",
"."
] | train | https://github.com/michael-rapp/AndroidBottomSheet/blob/6e4690ee9f63b14a7b143d3a3717b5f8a11ca503/library/src/main/java/de/mrapp/android/bottomsheet/BottomSheet.java#L2079-L2085 |
UrielCh/ovh-java-sdk | ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java | ApiOvhMe.availableAutomaticPaymentMeans_GET | public OvhAutomaticPaymentMean availableAutomaticPaymentMeans_GET() throws IOException {
String qPath = "/me/availableAutomaticPaymentMeans";
StringBuilder sb = path(qPath);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhAutomaticPaymentMean.class);
} | java | public OvhAutomaticPaymentMean availableAutomaticPaymentMeans_GET() throws IOException {
String qPath = "/me/availableAutomaticPaymentMeans";
StringBuilder sb = path(qPath);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhAutomaticPaymentMean.class);
} | [
"public",
"OvhAutomaticPaymentMean",
"availableAutomaticPaymentMeans_GET",
"(",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/me/availableAutomaticPaymentMeans\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
")",
";",
"String",
"resp",
"=",
... | List available payment methods in this Nic's country
REST: GET /me/availableAutomaticPaymentMeans | [
"List",
"available",
"payment",
"methods",
"in",
"this",
"Nic",
"s",
"country"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L374-L379 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/trifocal/TrifocalExtractGeometries.java | TrifocalExtractGeometries.extractEpipoles | public void extractEpipoles( Point3D_F64 e2 , Point3D_F64 e3 ) {
e2.set(this.e2);
e3.set(this.e3);
} | java | public void extractEpipoles( Point3D_F64 e2 , Point3D_F64 e3 ) {
e2.set(this.e2);
e3.set(this.e3);
} | [
"public",
"void",
"extractEpipoles",
"(",
"Point3D_F64",
"e2",
",",
"Point3D_F64",
"e3",
")",
"{",
"e2",
".",
"set",
"(",
"this",
".",
"e2",
")",
";",
"e3",
".",
"set",
"(",
"this",
".",
"e3",
")",
";",
"}"
] | Extracts the epipoles from the trifocal tensor. Extracted epipoles will have a norm of 1
as an artifact of using SVD.
@param e2 Output: Epipole in image 2. Homogeneous coordinates. Modified
@param e3 Output: Epipole in image 3. Homogeneous coordinates. Modified | [
"Extracts",
"the",
"epipoles",
"from",
"the",
"trifocal",
"tensor",
".",
"Extracted",
"epipoles",
"will",
"have",
"a",
"norm",
"of",
"1",
"as",
"an",
"artifact",
"of",
"using",
"SVD",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/trifocal/TrifocalExtractGeometries.java#L144-L147 |
joinfaces/joinfaces | joinfaces-tools/joinfaces-scan-tools/src/main/java/org/joinfaces/tools/ScanResultHandler.java | ScanResultHandler.writeClassMap | protected void writeClassMap(File file, Map<String, ? extends Collection<String>> classMap) throws IOException {
File baseDir = file.getParentFile();
if (baseDir.isDirectory() || baseDir.mkdirs()) {
//noinspection CharsetObjectCanBeUsed
try (PrintWriter printWriter = new PrintWriter(file, "UTF-8")) {
classMap.forEach((key, value) -> {
printWriter.print(key);
printWriter.print("=");
printWriter.println(String.join(",", value));
});
}
}
else {
throw new IOException(baseDir + " does not exist and could not be created");
}
} | java | protected void writeClassMap(File file, Map<String, ? extends Collection<String>> classMap) throws IOException {
File baseDir = file.getParentFile();
if (baseDir.isDirectory() || baseDir.mkdirs()) {
//noinspection CharsetObjectCanBeUsed
try (PrintWriter printWriter = new PrintWriter(file, "UTF-8")) {
classMap.forEach((key, value) -> {
printWriter.print(key);
printWriter.print("=");
printWriter.println(String.join(",", value));
});
}
}
else {
throw new IOException(baseDir + " does not exist and could not be created");
}
} | [
"protected",
"void",
"writeClassMap",
"(",
"File",
"file",
",",
"Map",
"<",
"String",
",",
"?",
"extends",
"Collection",
"<",
"String",
">",
">",
"classMap",
")",
"throws",
"IOException",
"{",
"File",
"baseDir",
"=",
"file",
".",
"getParentFile",
"(",
")",... | Helper method which writes a map of class names to the given file.
@param file The target file in which the class names should be written.
@param classMap The class names which should be written in the target file.
@throws IOException when the class names could not be written to the target file. | [
"Helper",
"method",
"which",
"writes",
"a",
"map",
"of",
"class",
"names",
"to",
"the",
"given",
"file",
"."
] | train | https://github.com/joinfaces/joinfaces/blob/c9fc811a9eaf695820951f2c04715297dd1e6d66/joinfaces-tools/joinfaces-scan-tools/src/main/java/org/joinfaces/tools/ScanResultHandler.java#L76-L93 |
fcrepo3/fcrepo | fcrepo-server/src/main/java/org/fcrepo/server/journal/helpers/JournalHelper.java | JournalHelper.createInstanceAccordingToParameter | public static Object createInstanceAccordingToParameter(String parameterName,
Class<?>[] argClasses,
Object[] args,
Map<String, String> parameters)
throws JournalException {
String className = parameters.get(parameterName);
if (className == null) {
throw new JournalException("No parameter '" + parameterName + "'");
}
return createInstanceFromClassname(className, argClasses, args);
} | java | public static Object createInstanceAccordingToParameter(String parameterName,
Class<?>[] argClasses,
Object[] args,
Map<String, String> parameters)
throws JournalException {
String className = parameters.get(parameterName);
if (className == null) {
throw new JournalException("No parameter '" + parameterName + "'");
}
return createInstanceFromClassname(className, argClasses, args);
} | [
"public",
"static",
"Object",
"createInstanceAccordingToParameter",
"(",
"String",
"parameterName",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"argClasses",
",",
"Object",
"[",
"]",
"args",
",",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
")",
"throw... | Look in the system parameters and create an instance of the named class.
@param parameterName
The name of the system parameter that contains the classname
@param argClasses
What types of arguments are required by the constructor?
@param args
Arguments to provide to the instance constructor.
@param parameters
The system parameters
@return the new instance created | [
"Look",
"in",
"the",
"system",
"parameters",
"and",
"create",
"an",
"instance",
"of",
"the",
"named",
"class",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/helpers/JournalHelper.java#L92-L102 |
FaritorKang/unmz-common-util | src/main/java/net/unmz/java/util/json/JsonUtils.java | JsonUtils.toBean | public static <T> T toBean(String text, Class<T> clazz) {
return JSON.parseObject(text, clazz);
} | java | public static <T> T toBean(String text, Class<T> clazz) {
return JSON.parseObject(text, clazz);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"toBean",
"(",
"String",
"text",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"return",
"JSON",
".",
"parseObject",
"(",
"text",
",",
"clazz",
")",
";",
"}"
] | 指定泛型,JSON串转对象
@param text JSON串
@param clazz 对象类型
@param <T> 对象泛型
@return 转换得到的对象 | [
"指定泛型,JSON串转对象"
] | train | https://github.com/FaritorKang/unmz-common-util/blob/2912b8889b85ed910d536f85b24b6fa68035814a/src/main/java/net/unmz/java/util/json/JsonUtils.java#L77-L79 |
networknt/light-4j | utility/src/main/java/com/networknt/utility/StringUtils.java | StringUtils.startsWith | private static boolean startsWith(final CharSequence str, final CharSequence prefix, final boolean ignoreCase) {
if (str == null || prefix == null) {
return str == prefix;
}
if (prefix.length() > str.length()) {
return false;
}
return CharSequenceUtils.regionMatches(str, ignoreCase, 0, prefix, 0, prefix.length());
} | java | private static boolean startsWith(final CharSequence str, final CharSequence prefix, final boolean ignoreCase) {
if (str == null || prefix == null) {
return str == prefix;
}
if (prefix.length() > str.length()) {
return false;
}
return CharSequenceUtils.regionMatches(str, ignoreCase, 0, prefix, 0, prefix.length());
} | [
"private",
"static",
"boolean",
"startsWith",
"(",
"final",
"CharSequence",
"str",
",",
"final",
"CharSequence",
"prefix",
",",
"final",
"boolean",
"ignoreCase",
")",
"{",
"if",
"(",
"str",
"==",
"null",
"||",
"prefix",
"==",
"null",
")",
"{",
"return",
"s... | <p>Check if a CharSequence starts with a specified prefix (optionally case insensitive).</p>
@see java.lang.String#startsWith(String)
@param str the CharSequence to check, may be null
@param prefix the prefix to find, may be null
@param ignoreCase indicates whether the compare should ignore case
(case insensitive) or not.
@return {@code true} if the CharSequence starts with the prefix or
both {@code null} | [
"<p",
">",
"Check",
"if",
"a",
"CharSequence",
"starts",
"with",
"a",
"specified",
"prefix",
"(",
"optionally",
"case",
"insensitive",
")",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/utility/src/main/java/com/networknt/utility/StringUtils.java#L826-L834 |
Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/impl/Scheduler.java | Scheduler.newThreadFactory | private static ThreadFactory newThreadFactory(final String id) {
return new ThreadFactory() {
private final AtomicInteger next = new AtomicInteger();
@Override public Thread newThread(Runnable r) {
final String name = "spectator-" + id + "-" + next.getAndIncrement();
final Thread t = new Thread(r, name);
t.setDaemon(true);
return t;
}
};
} | java | private static ThreadFactory newThreadFactory(final String id) {
return new ThreadFactory() {
private final AtomicInteger next = new AtomicInteger();
@Override public Thread newThread(Runnable r) {
final String name = "spectator-" + id + "-" + next.getAndIncrement();
final Thread t = new Thread(r, name);
t.setDaemon(true);
return t;
}
};
} | [
"private",
"static",
"ThreadFactory",
"newThreadFactory",
"(",
"final",
"String",
"id",
")",
"{",
"return",
"new",
"ThreadFactory",
"(",
")",
"{",
"private",
"final",
"AtomicInteger",
"next",
"=",
"new",
"AtomicInteger",
"(",
")",
";",
"@",
"Override",
"public... | Create a thread factory using thread names based on the id. All threads will
be configured as daemon threads. | [
"Create",
"a",
"thread",
"factory",
"using",
"thread",
"names",
"based",
"on",
"the",
"id",
".",
"All",
"threads",
"will",
"be",
"configured",
"as",
"daemon",
"threads",
"."
] | train | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/impl/Scheduler.java#L88-L99 |
BotMill/fb-botmill | src/main/java/co/aurasphere/botmill/fb/FbBotMillServlet.java | FbBotMillServlet.doPost | @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
logger.trace("POST received!");
MessengerCallback callback = new MessengerCallback();
// Extrapolates and logs the JSON for debugging.
String json = readerToString(req.getReader());
logger.debug("JSON input: " + json);
// Parses the request as a MessengerCallback.
try {
callback = FbBotMillJsonUtils.fromJson(json, MessengerCallback.class);
} catch (Exception e) {
logger.error("Error during MessengerCallback parsing: ", e);
return;
}
// If the received POST is a MessengerCallback, it forwards the last
// envelope of all the callbacks received to the registered bots.
if (callback != null) {
List<MessengerCallbackEntry> callbackEntries = callback.getEntry();
if (callbackEntries != null) {
for (MessengerCallbackEntry entry : callbackEntries) {
List<MessageEnvelope> envelopes = entry.getMessaging();
if (envelopes != null) {
MessageEnvelope lastEnvelope = envelopes.get(envelopes.size() - 1);
IncomingToOutgoingMessageHandler.getInstance().process(lastEnvelope);
}
}
}
}
// Always set to ok.
resp.setStatus(HttpServletResponse.SC_OK);
} | java | @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
logger.trace("POST received!");
MessengerCallback callback = new MessengerCallback();
// Extrapolates and logs the JSON for debugging.
String json = readerToString(req.getReader());
logger.debug("JSON input: " + json);
// Parses the request as a MessengerCallback.
try {
callback = FbBotMillJsonUtils.fromJson(json, MessengerCallback.class);
} catch (Exception e) {
logger.error("Error during MessengerCallback parsing: ", e);
return;
}
// If the received POST is a MessengerCallback, it forwards the last
// envelope of all the callbacks received to the registered bots.
if (callback != null) {
List<MessengerCallbackEntry> callbackEntries = callback.getEntry();
if (callbackEntries != null) {
for (MessengerCallbackEntry entry : callbackEntries) {
List<MessageEnvelope> envelopes = entry.getMessaging();
if (envelopes != null) {
MessageEnvelope lastEnvelope = envelopes.get(envelopes.size() - 1);
IncomingToOutgoingMessageHandler.getInstance().process(lastEnvelope);
}
}
}
}
// Always set to ok.
resp.setStatus(HttpServletResponse.SC_OK);
} | [
"@",
"Override",
"protected",
"void",
"doPost",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"resp",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"logger",
".",
"trace",
"(",
"\"POST received!\"",
")",
";",
"MessengerCallback",
"callb... | Specifies how to handle a POST request. It parses the request as a
{@link MessengerCallback} object. If the request is not a
MessengerCallback, then the FbBotMillServlet logs an error and does
nothing, otherwise it will forward the request to all registered bots in
order to let them process the callbacks.
@param req
the req
@param resp
the resp
@throws ServletException
the servlet exception
@throws IOException
Signals that an I/O exception has occurred. | [
"Specifies",
"how",
"to",
"handle",
"a",
"POST",
"request",
".",
"It",
"parses",
"the",
"request",
"as",
"a",
"{",
"@link",
"MessengerCallback",
"}",
"object",
".",
"If",
"the",
"request",
"is",
"not",
"a",
"MessengerCallback",
"then",
"the",
"FbBotMillServl... | train | https://github.com/BotMill/fb-botmill/blob/d94da3615a7339822c137ef75c92a03d791ee969/src/main/java/co/aurasphere/botmill/fb/FbBotMillServlet.java#L149-L184 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/InstanceInfo.java | InstanceInfo.of | public static InstanceInfo of(
InstanceId instanceId,
MachineTypeId machineType,
AttachedDisk disk,
NetworkInterface networkInterface) {
return newBuilder(instanceId, machineType)
.setAttachedDisks(ImmutableList.of(disk))
.setNetworkInterfaces(ImmutableList.of(networkInterface))
.build();
} | java | public static InstanceInfo of(
InstanceId instanceId,
MachineTypeId machineType,
AttachedDisk disk,
NetworkInterface networkInterface) {
return newBuilder(instanceId, machineType)
.setAttachedDisks(ImmutableList.of(disk))
.setNetworkInterfaces(ImmutableList.of(networkInterface))
.build();
} | [
"public",
"static",
"InstanceInfo",
"of",
"(",
"InstanceId",
"instanceId",
",",
"MachineTypeId",
"machineType",
",",
"AttachedDisk",
"disk",
",",
"NetworkInterface",
"networkInterface",
")",
"{",
"return",
"newBuilder",
"(",
"instanceId",
",",
"machineType",
")",
".... | Returns an {@code InstanceInfo} object given the instance identity, the machine type, a disk to
attach to the instance and a network interface. {@code disk} must be a boot disk (i.e. {@link
AttachedDisk.AttachedDiskConfiguration#boot()} returns {@code true}). | [
"Returns",
"an",
"{"
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/InstanceInfo.java#L645-L654 |
infinispan/infinispan | query/src/main/java/org/infinispan/query/Search.java | Search.getQueryFactory | public static QueryFactory getQueryFactory(Cache<?, ?> cache) {
if (cache == null || cache.getAdvancedCache() == null) {
throw new IllegalArgumentException("cache parameter shall not be null");
}
AdvancedCache<?, ?> advancedCache = cache.getAdvancedCache();
ensureAccessPermissions(advancedCache);
EmbeddedQueryEngine queryEngine = SecurityActions.getCacheComponentRegistry(advancedCache).getComponent(EmbeddedQueryEngine.class);
if (queryEngine == null) {
throw log.queryModuleNotInitialised();
}
return new EmbeddedQueryFactory(queryEngine);
} | java | public static QueryFactory getQueryFactory(Cache<?, ?> cache) {
if (cache == null || cache.getAdvancedCache() == null) {
throw new IllegalArgumentException("cache parameter shall not be null");
}
AdvancedCache<?, ?> advancedCache = cache.getAdvancedCache();
ensureAccessPermissions(advancedCache);
EmbeddedQueryEngine queryEngine = SecurityActions.getCacheComponentRegistry(advancedCache).getComponent(EmbeddedQueryEngine.class);
if (queryEngine == null) {
throw log.queryModuleNotInitialised();
}
return new EmbeddedQueryFactory(queryEngine);
} | [
"public",
"static",
"QueryFactory",
"getQueryFactory",
"(",
"Cache",
"<",
"?",
",",
"?",
">",
"cache",
")",
"{",
"if",
"(",
"cache",
"==",
"null",
"||",
"cache",
".",
"getAdvancedCache",
"(",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentE... | Obtain the query factory for building DSL based Ickle queries. | [
"Obtain",
"the",
"query",
"factory",
"for",
"building",
"DSL",
"based",
"Ickle",
"queries",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/query/src/main/java/org/infinispan/query/Search.java#L66-L77 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/mapreduce/aggregation/Aggregations.java | Aggregations.longMax | public static <Key, Value> Aggregation<Key, Long, Long> longMax() {
return new AggregationAdapter(new LongMaxAggregation<Key, Value>());
} | java | public static <Key, Value> Aggregation<Key, Long, Long> longMax() {
return new AggregationAdapter(new LongMaxAggregation<Key, Value>());
} | [
"public",
"static",
"<",
"Key",
",",
"Value",
">",
"Aggregation",
"<",
"Key",
",",
"Long",
",",
"Long",
">",
"longMax",
"(",
")",
"{",
"return",
"new",
"AggregationAdapter",
"(",
"new",
"LongMaxAggregation",
"<",
"Key",
",",
"Value",
">",
"(",
")",
")"... | Returns an aggregation to find the long maximum of all supplied values.<br/>
This aggregation is similar to: <pre>SELECT MAX(value) FROM x</pre>
@param <Key> the input key type
@param <Value> the supplied value type
@return the maximum value over all supplied values | [
"Returns",
"an",
"aggregation",
"to",
"find",
"the",
"long",
"maximum",
"of",
"all",
"supplied",
"values",
".",
"<br",
"/",
">",
"This",
"aggregation",
"is",
"similar",
"to",
":",
"<pre",
">",
"SELECT",
"MAX",
"(",
"value",
")",
"FROM",
"x<",
"/",
"pre... | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/mapreduce/aggregation/Aggregations.java#L186-L188 |
overturetool/overture | core/codegen/platform/src/main/java/org/overture/codegen/ir/CodeGenBase.java | CodeGenBase.genIrStatus | protected void genIrStatus(List<IRStatus<PIR>> statuses, INode node)
throws AnalysisException
{
IRStatus<PIR> status = generator.generateFrom(node);
if (status != null)
{
statuses.add(status);
}
} | java | protected void genIrStatus(List<IRStatus<PIR>> statuses, INode node)
throws AnalysisException
{
IRStatus<PIR> status = generator.generateFrom(node);
if (status != null)
{
statuses.add(status);
}
} | [
"protected",
"void",
"genIrStatus",
"(",
"List",
"<",
"IRStatus",
"<",
"PIR",
">",
">",
"statuses",
",",
"INode",
"node",
")",
"throws",
"AnalysisException",
"{",
"IRStatus",
"<",
"PIR",
">",
"status",
"=",
"generator",
".",
"generateFrom",
"(",
"node",
")... | This method translates a VDM node into an IR status.
@param statuses
A list of previously generated IR statuses. The generated IR status will be added to this list.
@param node
The VDM node from which we generate an IR status
@throws AnalysisException
If something goes wrong during the construction of the IR status. | [
"This",
"method",
"translates",
"a",
"VDM",
"node",
"into",
"an",
"IR",
"status",
"."
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/codegen/platform/src/main/java/org/overture/codegen/ir/CodeGenBase.java#L138-L147 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/accesslayer/StatementManager.java | StatementManager.bindValues | public int bindValues(PreparedStatement stmt, ValueContainer[] values, int index) throws SQLException
{
if (values != null)
{
for (int i = 0; i < values.length; i++)
{
setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());
index++;
}
}
return index;
} | java | public int bindValues(PreparedStatement stmt, ValueContainer[] values, int index) throws SQLException
{
if (values != null)
{
for (int i = 0; i < values.length; i++)
{
setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());
index++;
}
}
return index;
} | [
"public",
"int",
"bindValues",
"(",
"PreparedStatement",
"stmt",
",",
"ValueContainer",
"[",
"]",
"values",
",",
"int",
"index",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"values",
"!=",
"null",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i"... | binds the given array of values (if not null) starting from the given
parameter index
@return the next parameter index | [
"binds",
"the",
"given",
"array",
"of",
"values",
"(",
"if",
"not",
"null",
")",
"starting",
"from",
"the",
"given",
"parameter",
"index"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/StatementManager.java#L533-L544 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/util/FirstNonNullHelper.java | FirstNonNullHelper.firstNonNull | public static <T, R> R firstNonNull(Function<T, R> function, Collection<T> values) {
return values == null ? null : firstNonNull(function, values.stream());
} | java | public static <T, R> R firstNonNull(Function<T, R> function, Collection<T> values) {
return values == null ? null : firstNonNull(function, values.stream());
} | [
"public",
"static",
"<",
"T",
",",
"R",
">",
"R",
"firstNonNull",
"(",
"Function",
"<",
"T",
",",
"R",
">",
"function",
",",
"Collection",
"<",
"T",
">",
"values",
")",
"{",
"return",
"values",
"==",
"null",
"?",
"null",
":",
"firstNonNull",
"(",
"... | Gets first result of function which is not null.
@param <T> type of values.
@param <R> element to return.
@param function function to apply to each value.
@param values all possible values to apply function to.
@return first result which was not null,
OR <code>null</code> if either result for all values was <code>null</code> or values was <code>null</code>. | [
"Gets",
"first",
"result",
"of",
"function",
"which",
"is",
"not",
"null",
"."
] | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/FirstNonNullHelper.java#L50-L52 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java | LambdaToMethod.makeSyntheticVar | private VarSymbol makeSyntheticVar(long flags, String name, Type type, Symbol owner) {
return makeSyntheticVar(flags, names.fromString(name), type, owner);
} | java | private VarSymbol makeSyntheticVar(long flags, String name, Type type, Symbol owner) {
return makeSyntheticVar(flags, names.fromString(name), type, owner);
} | [
"private",
"VarSymbol",
"makeSyntheticVar",
"(",
"long",
"flags",
",",
"String",
"name",
",",
"Type",
"type",
",",
"Symbol",
"owner",
")",
"{",
"return",
"makeSyntheticVar",
"(",
"flags",
",",
"names",
".",
"fromString",
"(",
"name",
")",
",",
"type",
",",... | Create new synthetic variable with given flags, name, type, owner | [
"Create",
"new",
"synthetic",
"variable",
"with",
"given",
"flags",
"name",
"type",
"owner"
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java#L775-L777 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging.core/src/com/ibm/ws/logging/internal/BundleManifest.java | BundleManifest.parseHeader | void parseHeader(String header, Set<String> packages) {
if (header != null && header.length() > 0) {
List<String> splitPackages = new ArrayList<String>();
// We can't just split() on commas, because there may be things in quotes, like uses clauses
int lastIndex = 0;
boolean inQuotedSection = false;
int i = 0;
for (i = 0; i < header.length(); i++) {
if ((header.charAt(i) == ',') && !(inQuotedSection)) {
String packagePlusAttributesAndDirectives = header.substring(lastIndex, i);
lastIndex = i + 1;
splitPackages.add(packagePlusAttributesAndDirectives);
} else if (header.charAt(i) == '"') {
inQuotedSection = !inQuotedSection;
}
}
// Add the last string
splitPackages.add(header.substring(lastIndex, i));
// Now go through and handle the attributes
for (String packagePlusAttributesAndDirectives : splitPackages) {
String[] bits = packagePlusAttributesAndDirectives.split(";");
// We could also process ibm-api-type and other declarations here to get better information if we need it
packages.add(bits[0]);
}
}
} | java | void parseHeader(String header, Set<String> packages) {
if (header != null && header.length() > 0) {
List<String> splitPackages = new ArrayList<String>();
// We can't just split() on commas, because there may be things in quotes, like uses clauses
int lastIndex = 0;
boolean inQuotedSection = false;
int i = 0;
for (i = 0; i < header.length(); i++) {
if ((header.charAt(i) == ',') && !(inQuotedSection)) {
String packagePlusAttributesAndDirectives = header.substring(lastIndex, i);
lastIndex = i + 1;
splitPackages.add(packagePlusAttributesAndDirectives);
} else if (header.charAt(i) == '"') {
inQuotedSection = !inQuotedSection;
}
}
// Add the last string
splitPackages.add(header.substring(lastIndex, i));
// Now go through and handle the attributes
for (String packagePlusAttributesAndDirectives : splitPackages) {
String[] bits = packagePlusAttributesAndDirectives.split(";");
// We could also process ibm-api-type and other declarations here to get better information if we need it
packages.add(bits[0]);
}
}
} | [
"void",
"parseHeader",
"(",
"String",
"header",
",",
"Set",
"<",
"String",
">",
"packages",
")",
"{",
"if",
"(",
"header",
"!=",
"null",
"&&",
"header",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"List",
"<",
"String",
">",
"splitPackages",
"=",
... | This algorithm is nuts. Bnd has a nice on in OSGIHeader.
@param header
@param packages | [
"This",
"algorithm",
"is",
"nuts",
".",
"Bnd",
"has",
"a",
"nice",
"on",
"in",
"OSGIHeader",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.core/src/com/ibm/ws/logging/internal/BundleManifest.java#L61-L89 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Math.java | Math.copySign | public static float copySign(float magnitude, float sign) {
return Float.intBitsToFloat((Float.floatToRawIntBits(sign) &
(FloatConsts.SIGN_BIT_MASK)) |
(Float.floatToRawIntBits(magnitude) &
(FloatConsts.EXP_BIT_MASK |
FloatConsts.SIGNIF_BIT_MASK)));
} | java | public static float copySign(float magnitude, float sign) {
return Float.intBitsToFloat((Float.floatToRawIntBits(sign) &
(FloatConsts.SIGN_BIT_MASK)) |
(Float.floatToRawIntBits(magnitude) &
(FloatConsts.EXP_BIT_MASK |
FloatConsts.SIGNIF_BIT_MASK)));
} | [
"public",
"static",
"float",
"copySign",
"(",
"float",
"magnitude",
",",
"float",
"sign",
")",
"{",
"return",
"Float",
".",
"intBitsToFloat",
"(",
"(",
"Float",
".",
"floatToRawIntBits",
"(",
"sign",
")",
"&",
"(",
"FloatConsts",
".",
"SIGN_BIT_MASK",
")",
... | Returns the first floating-point argument with the sign of the
second floating-point argument. Note that unlike the {@link
StrictMath#copySign(float, float) StrictMath.copySign}
method, this method does not require NaN {@code sign}
arguments to be treated as positive values; implementations are
permitted to treat some NaN arguments as positive and other NaN
arguments as negative to allow greater performance.
@param magnitude the parameter providing the magnitude of the result
@param sign the parameter providing the sign of the result
@return a value with the magnitude of {@code magnitude}
and the sign of {@code sign}.
@since 1.6 | [
"Returns",
"the",
"first",
"floating",
"-",
"point",
"argument",
"with",
"the",
"sign",
"of",
"the",
"second",
"floating",
"-",
"point",
"argument",
".",
"Note",
"that",
"unlike",
"the",
"{",
"@link",
"StrictMath#copySign",
"(",
"float",
"float",
")",
"Stric... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Math.java#L1793-L1799 |
mapsforge/mapsforge | mapsforge-map/src/main/java/org/mapsforge/map/layer/renderer/CanvasRasterer.java | CanvasRasterer.fillOutsideAreas | void fillOutsideAreas(int color, Rectangle insideArea) {
this.canvas.setClipDifference((int) insideArea.left, (int) insideArea.top, (int) insideArea.getWidth(), (int) insideArea.getHeight());
this.canvas.fillColor(color);
this.canvas.resetClip();
} | java | void fillOutsideAreas(int color, Rectangle insideArea) {
this.canvas.setClipDifference((int) insideArea.left, (int) insideArea.top, (int) insideArea.getWidth(), (int) insideArea.getHeight());
this.canvas.fillColor(color);
this.canvas.resetClip();
} | [
"void",
"fillOutsideAreas",
"(",
"int",
"color",
",",
"Rectangle",
"insideArea",
")",
"{",
"this",
".",
"canvas",
".",
"setClipDifference",
"(",
"(",
"int",
")",
"insideArea",
".",
"left",
",",
"(",
"int",
")",
"insideArea",
".",
"top",
",",
"(",
"int",
... | Fills the area outside the specificed rectangle with color.
This method is used to blank out areas that fall outside the map area.
@param color the fill color for the outside area
@param insideArea the inside area on which not to draw | [
"Fills",
"the",
"area",
"outside",
"the",
"specificed",
"rectangle",
"with",
"color",
".",
"This",
"method",
"is",
"used",
"to",
"blank",
"out",
"areas",
"that",
"fall",
"outside",
"the",
"map",
"area",
"."
] | train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map/src/main/java/org/mapsforge/map/layer/renderer/CanvasRasterer.java#L112-L116 |
oehf/ipf-oht-atna | auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/events/ihe/GenericIHEAuditEventMessage.java | GenericIHEAuditEventMessage.addDestinationActiveParticipant | public void addDestinationActiveParticipant(String userId, String altUserId, String userName, String networkId, boolean isRequestor)
{
addActiveParticipant(
userId,
altUserId,
userName,
isRequestor,
Collections.singletonList(new DICOMActiveParticipantRoleIdCodes.Destination()),
networkId);
} | java | public void addDestinationActiveParticipant(String userId, String altUserId, String userName, String networkId, boolean isRequestor)
{
addActiveParticipant(
userId,
altUserId,
userName,
isRequestor,
Collections.singletonList(new DICOMActiveParticipantRoleIdCodes.Destination()),
networkId);
} | [
"public",
"void",
"addDestinationActiveParticipant",
"(",
"String",
"userId",
",",
"String",
"altUserId",
",",
"String",
"userName",
",",
"String",
"networkId",
",",
"boolean",
"isRequestor",
")",
"{",
"addActiveParticipant",
"(",
"userId",
",",
"altUserId",
",",
... | Adds an Active Participant block representing the destination participant
@param userId The Active Participant's User ID
@param altUserId The Active Participant's Alternate UserID
@param userName The Active Participant's UserName
@param networkId The Active Participant's Network Access Point ID
@param isRequestor Whether the participant represents the requestor | [
"Adds",
"an",
"Active",
"Participant",
"block",
"representing",
"the",
"destination",
"participant"
] | train | https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/events/ihe/GenericIHEAuditEventMessage.java#L115-L124 |
future-architect/uroborosql | src/main/java/jp/co/future/uroborosql/utils/BeanAccessor.java | BeanAccessor.walkFields | private static void walkFields(final Class<?> cls, final Map<String, Field> fieldMap) {
if (cls.equals(Object.class)) {
return;
}
Class<?> superClass = cls.getSuperclass();
walkFields(superClass, fieldMap);
Arrays.stream(cls.getDeclaredFields())
.filter(f -> !Modifier.isStatic(f.getModifiers()))
.forEach(f -> fieldMap.put(f.getName(), f));
} | java | private static void walkFields(final Class<?> cls, final Map<String, Field> fieldMap) {
if (cls.equals(Object.class)) {
return;
}
Class<?> superClass = cls.getSuperclass();
walkFields(superClass, fieldMap);
Arrays.stream(cls.getDeclaredFields())
.filter(f -> !Modifier.isStatic(f.getModifiers()))
.forEach(f -> fieldMap.put(f.getName(), f));
} | [
"private",
"static",
"void",
"walkFields",
"(",
"final",
"Class",
"<",
"?",
">",
"cls",
",",
"final",
"Map",
"<",
"String",
",",
"Field",
">",
"fieldMap",
")",
"{",
"if",
"(",
"cls",
".",
"equals",
"(",
"Object",
".",
"class",
")",
")",
"{",
"retur... | 指定したクラスの持つ全てのフィールドを再帰的に探索して取得する
@param cls 型
@param fieldMap {@literal Map<String, Field>j} | [
"指定したクラスの持つ全てのフィールドを再帰的に探索して取得する"
] | train | https://github.com/future-architect/uroborosql/blob/4c26db51defdac3c6ed16866e33ab45e190e2e0c/src/main/java/jp/co/future/uroborosql/utils/BeanAccessor.java#L103-L112 |
vincentk/joptimizer | src/main/java/com/joptimizer/optimizers/LPPrimalDualMethod.java | LPPrimalDualMethod.gradSum | protected DoubleMatrix1D gradSum(double t, DoubleMatrix1D fiX) {
DoubleMatrix1D gradSum = F1.make(getDim());
for(int i=0; i<dim; i++){
double d = 0;
d += 1. / (t * fiX.getQuick(i));
d += -1. / (t * fiX.getQuick(getDim() + i));
gradSum.setQuick(i, d);
}
return gradSum;
} | java | protected DoubleMatrix1D gradSum(double t, DoubleMatrix1D fiX) {
DoubleMatrix1D gradSum = F1.make(getDim());
for(int i=0; i<dim; i++){
double d = 0;
d += 1. / (t * fiX.getQuick(i));
d += -1. / (t * fiX.getQuick(getDim() + i));
gradSum.setQuick(i, d);
}
return gradSum;
} | [
"protected",
"DoubleMatrix1D",
"gradSum",
"(",
"double",
"t",
",",
"DoubleMatrix1D",
"fiX",
")",
"{",
"DoubleMatrix1D",
"gradSum",
"=",
"F1",
".",
"make",
"(",
"getDim",
"(",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"dim",
";",... | Calculates the second term of the first row of (11.55) "Convex Optimization".
@see "Convex Optimization, 11.55" | [
"Calculates",
"the",
"second",
"term",
"of",
"the",
"first",
"row",
"of",
"(",
"11",
".",
"55",
")",
"Convex",
"Optimization",
"."
] | train | https://github.com/vincentk/joptimizer/blob/65064c1bb0b26c7261358021e4c93d06dd43564f/src/main/java/com/joptimizer/optimizers/LPPrimalDualMethod.java#L718-L727 |
phxql/argon2-jvm | src/main/java/de/mkammerer/argon2/Argon2Helper.java | Argon2Helper.findIterations | public static int findIterations(Argon2 argon2, long maxMillisecs, int memory, int parallelism, IterationLogger logger) {
char[] password = "password".toCharArray();
warmup(argon2, password);
long took;
int iterations = 0;
do {
iterations++;
long start = System.nanoTime() / MILLIS_IN_NANOS;
argon2.hash(iterations, memory, parallelism, password);
long end = System.nanoTime() / MILLIS_IN_NANOS;
took = end - start;
logger.log(iterations, took);
} while (took <= maxMillisecs);
return iterations - 1;
} | java | public static int findIterations(Argon2 argon2, long maxMillisecs, int memory, int parallelism, IterationLogger logger) {
char[] password = "password".toCharArray();
warmup(argon2, password);
long took;
int iterations = 0;
do {
iterations++;
long start = System.nanoTime() / MILLIS_IN_NANOS;
argon2.hash(iterations, memory, parallelism, password);
long end = System.nanoTime() / MILLIS_IN_NANOS;
took = end - start;
logger.log(iterations, took);
} while (took <= maxMillisecs);
return iterations - 1;
} | [
"public",
"static",
"int",
"findIterations",
"(",
"Argon2",
"argon2",
",",
"long",
"maxMillisecs",
",",
"int",
"memory",
",",
"int",
"parallelism",
",",
"IterationLogger",
"logger",
")",
"{",
"char",
"[",
"]",
"password",
"=",
"\"password\"",
".",
"toCharArray... | Finds the number of iterations so that the hash function takes at most the given number of milliseconds.
@param argon2 Argon2 instance.
@param maxMillisecs Maximum number of milliseconds the hash function must take.
@param memory Memory. See {@link Argon2#hash(int, int, int, char[])}.
@param parallelism Parallelism. See {@link Argon2#hash(int, int, int, char[])}.
@param logger Logger which gets called with the runtime of the tested iteration steps.
@return The number of iterations so that the hash function takes at most the given number of milliseconds. | [
"Finds",
"the",
"number",
"of",
"iterations",
"so",
"that",
"the",
"hash",
"function",
"takes",
"at",
"most",
"the",
"given",
"number",
"of",
"milliseconds",
"."
] | train | https://github.com/phxql/argon2-jvm/blob/27a13907729e67e98cca53eba279e109b60f04f1/src/main/java/de/mkammerer/argon2/Argon2Helper.java#L57-L75 |
vanilladb/vanillacore | src/main/java/org/vanilladb/core/storage/tx/recovery/RecoveryMgr.java | RecoveryMgr.logSetVal | public LogSeqNum logSetVal(Buffer buff, int offset, Constant newVal) {
if (enableLogging) {
BlockId blk = buff.block();
if (isTempBlock(blk))
return null;
return new SetValueRecord(txNum, blk, offset, buff.getVal(offset, newVal.getType()), newVal).writeToLog();
} else
return null;
} | java | public LogSeqNum logSetVal(Buffer buff, int offset, Constant newVal) {
if (enableLogging) {
BlockId blk = buff.block();
if (isTempBlock(blk))
return null;
return new SetValueRecord(txNum, blk, offset, buff.getVal(offset, newVal.getType()), newVal).writeToLog();
} else
return null;
} | [
"public",
"LogSeqNum",
"logSetVal",
"(",
"Buffer",
"buff",
",",
"int",
"offset",
",",
"Constant",
"newVal",
")",
"{",
"if",
"(",
"enableLogging",
")",
"{",
"BlockId",
"blk",
"=",
"buff",
".",
"block",
"(",
")",
";",
"if",
"(",
"isTempBlock",
"(",
"blk"... | Writes a set value record to the log.
@param buff
the buffer containing the page
@param offset
the offset of the value in the page
@param newVal
the value to be written
@return the LSN of the log record, or -1 if updates to temporary files | [
"Writes",
"a",
"set",
"value",
"record",
"to",
"the",
"log",
"."
] | train | https://github.com/vanilladb/vanillacore/blob/d9a34e876b1b83226036d1fa982a614bbef59bd1/src/main/java/org/vanilladb/core/storage/tx/recovery/RecoveryMgr.java#L142-L150 |
atbashEE/atbash-config | geronimo-config/src/main/java/org/apache/geronimo/config/cdi/ConfigInjectionBean.java | ConfigInjectionBean.getConfigKey | static String getConfigKey(InjectionPoint ip, ConfigProperty configProperty) {
String key = configProperty.name();
if (key.length() > 0) {
return key;
}
if (ip.getAnnotated() instanceof AnnotatedMember) {
AnnotatedMember member = (AnnotatedMember) ip.getAnnotated();
AnnotatedType declaringType = member.getDeclaringType();
if (declaringType != null) {
return declaringType.getJavaClass().getCanonicalName() + "." + member.getJavaMember().getName();
}
}
throw new IllegalStateException("Could not find default name for @ConfigProperty InjectionPoint " + ip);
} | java | static String getConfigKey(InjectionPoint ip, ConfigProperty configProperty) {
String key = configProperty.name();
if (key.length() > 0) {
return key;
}
if (ip.getAnnotated() instanceof AnnotatedMember) {
AnnotatedMember member = (AnnotatedMember) ip.getAnnotated();
AnnotatedType declaringType = member.getDeclaringType();
if (declaringType != null) {
return declaringType.getJavaClass().getCanonicalName() + "." + member.getJavaMember().getName();
}
}
throw new IllegalStateException("Could not find default name for @ConfigProperty InjectionPoint " + ip);
} | [
"static",
"String",
"getConfigKey",
"(",
"InjectionPoint",
"ip",
",",
"ConfigProperty",
"configProperty",
")",
"{",
"String",
"key",
"=",
"configProperty",
".",
"name",
"(",
")",
";",
"if",
"(",
"key",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"return... | Get the property key to use.
In case the {@link ConfigProperty#name()} is empty we will try to determine the key name from the InjectionPoint. | [
"Get",
"the",
"property",
"key",
"to",
"use",
".",
"In",
"case",
"the",
"{"
] | train | https://github.com/atbashEE/atbash-config/blob/80c06c6e535957514ffb51380948ecd351d5068c/geronimo-config/src/main/java/org/apache/geronimo/config/cdi/ConfigInjectionBean.java#L170-L184 |
JoeKerouac/utils | src/main/java/com/joe/utils/common/DateUtil.java | DateUtil.isToday | public static boolean isToday(String date, String format) {
String now = getFormatDate(SHORT);
String target = getFormatDate(SHORT, parse(date, format));
return now.equals(target);
} | java | public static boolean isToday(String date, String format) {
String now = getFormatDate(SHORT);
String target = getFormatDate(SHORT, parse(date, format));
return now.equals(target);
} | [
"public",
"static",
"boolean",
"isToday",
"(",
"String",
"date",
",",
"String",
"format",
")",
"{",
"String",
"now",
"=",
"getFormatDate",
"(",
"SHORT",
")",
";",
"String",
"target",
"=",
"getFormatDate",
"(",
"SHORT",
",",
"parse",
"(",
"date",
",",
"fo... | 查询时间是否在今日
@param date 时间字符串
@param format 时间字符串的格式
@return 如果指定日期对象在今天则返回<code>true</code> | [
"查询时间是否在今日"
] | train | https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/common/DateUtil.java#L240-L244 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/distribution/LaplaceDistribution.java | LaplaceDistribution.logpdf | public static double logpdf(double val, double rate) {
return FastMath.log(.5 * rate) - rate * Math.abs(val);
} | java | public static double logpdf(double val, double rate) {
return FastMath.log(.5 * rate) - rate * Math.abs(val);
} | [
"public",
"static",
"double",
"logpdf",
"(",
"double",
"val",
",",
"double",
"rate",
")",
"{",
"return",
"FastMath",
".",
"log",
"(",
".5",
"*",
"rate",
")",
"-",
"rate",
"*",
"Math",
".",
"abs",
"(",
"val",
")",
";",
"}"
] | PDF, static version
@param val Value to compute PDF at
@param rate Rate parameter (1/scale)
@return probability density | [
"PDF",
"static",
"version"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/distribution/LaplaceDistribution.java#L151-L153 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java | HtmlDocletWriter.addSummaryComment | public void addSummaryComment(Element element, Content htmltree) {
addSummaryComment(element, utils.getFirstSentenceTrees(element), htmltree);
} | java | public void addSummaryComment(Element element, Content htmltree) {
addSummaryComment(element, utils.getFirstSentenceTrees(element), htmltree);
} | [
"public",
"void",
"addSummaryComment",
"(",
"Element",
"element",
",",
"Content",
"htmltree",
")",
"{",
"addSummaryComment",
"(",
"element",
",",
"utils",
".",
"getFirstSentenceTrees",
"(",
"element",
")",
",",
"htmltree",
")",
";",
"}"
] | Adds the summary content.
@param element the Element for which the summary will be generated
@param htmltree the documentation tree to which the summary will be added | [
"Adds",
"the",
"summary",
"content",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java#L1658-L1660 |
google/error-prone | core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByChecker.java | GuardedByChecker.isRWLock | private static boolean isRWLock(GuardedByExpression guard, VisitorState state) {
Type guardType = guard.type();
if (guardType == null) {
return false;
}
Symbol rwLockSymbol = state.getSymbolFromString(JUC_READ_WRITE_LOCK);
if (rwLockSymbol == null) {
return false;
}
return state.getTypes().isSubtype(guardType, rwLockSymbol.type);
} | java | private static boolean isRWLock(GuardedByExpression guard, VisitorState state) {
Type guardType = guard.type();
if (guardType == null) {
return false;
}
Symbol rwLockSymbol = state.getSymbolFromString(JUC_READ_WRITE_LOCK);
if (rwLockSymbol == null) {
return false;
}
return state.getTypes().isSubtype(guardType, rwLockSymbol.type);
} | [
"private",
"static",
"boolean",
"isRWLock",
"(",
"GuardedByExpression",
"guard",
",",
"VisitorState",
"state",
")",
"{",
"Type",
"guardType",
"=",
"guard",
".",
"type",
"(",
")",
";",
"if",
"(",
"guardType",
"==",
"null",
")",
"{",
"return",
"false",
";",
... | Returns true if the lock expression corresponds to a {@code
java.util.concurrent.locks.ReadWriteLock}. | [
"Returns",
"true",
"if",
"the",
"lock",
"expression",
"corresponds",
"to",
"a",
"{"
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByChecker.java#L191-L203 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java | IoUtil.read | public static String read(ReadableByteChannel channel, Charset charset) throws IORuntimeException {
FastByteArrayOutputStream out = read(channel);
return null == charset ? out.toString() : out.toString(charset);
} | java | public static String read(ReadableByteChannel channel, Charset charset) throws IORuntimeException {
FastByteArrayOutputStream out = read(channel);
return null == charset ? out.toString() : out.toString(charset);
} | [
"public",
"static",
"String",
"read",
"(",
"ReadableByteChannel",
"channel",
",",
"Charset",
"charset",
")",
"throws",
"IORuntimeException",
"{",
"FastByteArrayOutputStream",
"out",
"=",
"read",
"(",
"channel",
")",
";",
"return",
"null",
"==",
"charset",
"?",
"... | 从流中读取内容,读取完毕后并不关闭流
@param channel 可读通道,读取完毕后并不关闭通道
@param charset 字符集
@return 内容
@throws IORuntimeException IO异常
@since 4.5.0 | [
"从流中读取内容,读取完毕后并不关闭流"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java#L423-L426 |
Stratio/deep-spark | deep-cassandra/src/main/java/com/stratio/deep/cassandra/thrift/ThriftRangeUtils.java | ThriftRangeUtils.getRanges | public List<DeepTokenRange> getRanges() {
try {
List<TokenRange> tokenRanges;
ThriftClient client = ThriftClient.build(host, rpcPort);
try {
tokenRanges = client.describe_local_ring(keyspace);
} catch (TApplicationException e) {
if (e.getType() == TApplicationException.UNKNOWN_METHOD) {
tokenRanges = client.describe_ring(keyspace);
} else {
throw new DeepGenericException("Unknown server error", e);
}
}
client.close();
List<DeepTokenRange> deepTokenRanges = new ArrayList<>(tokenRanges.size());
for (TokenRange tokenRange : tokenRanges) {
Comparable start = tokenAsComparable(tokenRange.getStart_token());
Comparable end = tokenAsComparable(tokenRange.getEnd_token());
deepTokenRanges.add(new DeepTokenRange(start, end, tokenRange.getEndpoints()));
}
return deepTokenRanges;
} catch (TException e) {
throw new DeepGenericException("No available replicas for get ring token ranges", e);
}
} | java | public List<DeepTokenRange> getRanges() {
try {
List<TokenRange> tokenRanges;
ThriftClient client = ThriftClient.build(host, rpcPort);
try {
tokenRanges = client.describe_local_ring(keyspace);
} catch (TApplicationException e) {
if (e.getType() == TApplicationException.UNKNOWN_METHOD) {
tokenRanges = client.describe_ring(keyspace);
} else {
throw new DeepGenericException("Unknown server error", e);
}
}
client.close();
List<DeepTokenRange> deepTokenRanges = new ArrayList<>(tokenRanges.size());
for (TokenRange tokenRange : tokenRanges) {
Comparable start = tokenAsComparable(tokenRange.getStart_token());
Comparable end = tokenAsComparable(tokenRange.getEnd_token());
deepTokenRanges.add(new DeepTokenRange(start, end, tokenRange.getEndpoints()));
}
return deepTokenRanges;
} catch (TException e) {
throw new DeepGenericException("No available replicas for get ring token ranges", e);
}
} | [
"public",
"List",
"<",
"DeepTokenRange",
">",
"getRanges",
"(",
")",
"{",
"try",
"{",
"List",
"<",
"TokenRange",
">",
"tokenRanges",
";",
"ThriftClient",
"client",
"=",
"ThriftClient",
".",
"build",
"(",
"host",
",",
"rpcPort",
")",
";",
"try",
"{",
"tok... | Returns the token ranges of the Cassandra ring that will be mapped to Spark partitions.
The returned ranges are the Cassandra's physical ones, without any splitting.
@return the list of Cassandra ring token ranges. | [
"Returns",
"the",
"token",
"ranges",
"of",
"the",
"Cassandra",
"ring",
"that",
"will",
"be",
"mapped",
"to",
"Spark",
"partitions",
".",
"The",
"returned",
"ranges",
"are",
"the",
"Cassandra",
"s",
"physical",
"ones",
"without",
"any",
"splitting",
"."
] | train | https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-cassandra/src/main/java/com/stratio/deep/cassandra/thrift/ThriftRangeUtils.java#L125-L152 |
pravega/pravega | shared/protocol/src/main/java/io/pravega/shared/segment/StreamSegmentNameUtils.java | StreamSegmentNameUtils.getQualifiedTableName | public static String getQualifiedTableName(String scope, String... tokens) {
Preconditions.checkArgument(tokens != null && tokens.length > 0);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%s/%s", scope, TABLES));
for (String token : tokens) {
sb.append('/');
sb.append(token);
}
return sb.toString();
} | java | public static String getQualifiedTableName(String scope, String... tokens) {
Preconditions.checkArgument(tokens != null && tokens.length > 0);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%s/%s", scope, TABLES));
for (String token : tokens) {
sb.append('/');
sb.append(token);
}
return sb.toString();
} | [
"public",
"static",
"String",
"getQualifiedTableName",
"(",
"String",
"scope",
",",
"String",
"...",
"tokens",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"tokens",
"!=",
"null",
"&&",
"tokens",
".",
"length",
">",
"0",
")",
";",
"StringBuilder",
"... | Method to generate Fully Qualified table name using scope, and other tokens to be used to compose the table name.
The composed name has following format \<scope\>/_tables/\<tokens[0]\>/\<tokens[1]\>...
@param scope scope in which table segment to create
@param tokens tokens used for composing table segment name
@return Fully qualified table segment name composed of supplied tokens. | [
"Method",
"to",
"generate",
"Fully",
"Qualified",
"table",
"name",
"using",
"scope",
"and",
"other",
"tokens",
"to",
"be",
"used",
"to",
"compose",
"the",
"table",
"name",
".",
"The",
"composed",
"name",
"has",
"following",
"format",
"\\",
"<scope",
"\\",
... | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/shared/protocol/src/main/java/io/pravega/shared/segment/StreamSegmentNameUtils.java#L322-L331 |
lucee/Lucee | core/src/main/java/lucee/runtime/converter/ScriptConverter.java | ScriptConverter._serializeList | private void _serializeList(List list, StringBuilder sb, Set<Object> done) throws ConverterException {
sb.append(goIn());
sb.append("[");
boolean doIt = false;
ListIterator it = list.listIterator();
while (it.hasNext()) {
if (doIt) sb.append(',');
doIt = true;
_serialize(it.next(), sb, done);
}
sb.append(']');
} | java | private void _serializeList(List list, StringBuilder sb, Set<Object> done) throws ConverterException {
sb.append(goIn());
sb.append("[");
boolean doIt = false;
ListIterator it = list.listIterator();
while (it.hasNext()) {
if (doIt) sb.append(',');
doIt = true;
_serialize(it.next(), sb, done);
}
sb.append(']');
} | [
"private",
"void",
"_serializeList",
"(",
"List",
"list",
",",
"StringBuilder",
"sb",
",",
"Set",
"<",
"Object",
">",
"done",
")",
"throws",
"ConverterException",
"{",
"sb",
".",
"append",
"(",
"goIn",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"[... | serialize a List (as Array)
@param list List to serialize
@param sb
@param done
@throws ConverterException | [
"serialize",
"a",
"List",
"(",
"as",
"Array",
")"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/converter/ScriptConverter.java#L163-L176 |
line/armeria | zookeeper/src/main/java/com/linecorp/armeria/server/zookeeper/ZooKeeperUpdatingListenerBuilder.java | ZooKeeperUpdatingListenerBuilder.build | public ZooKeeperUpdatingListener build() {
final boolean internalClient;
if (client == null) {
client = CuratorFrameworkFactory.builder()
.connectString(connectionStr)
.retryPolicy(ZooKeeperDefaults.DEFAULT_RETRY_POLICY)
.connectionTimeoutMs(connectTimeoutMillis)
.sessionTimeoutMs(sessionTimeoutMillis)
.build();
internalClient = true;
} else {
internalClient = false;
}
return new ZooKeeperUpdatingListener(client, zNodePath, nodeValueCodec, endpoint, internalClient);
} | java | public ZooKeeperUpdatingListener build() {
final boolean internalClient;
if (client == null) {
client = CuratorFrameworkFactory.builder()
.connectString(connectionStr)
.retryPolicy(ZooKeeperDefaults.DEFAULT_RETRY_POLICY)
.connectionTimeoutMs(connectTimeoutMillis)
.sessionTimeoutMs(sessionTimeoutMillis)
.build();
internalClient = true;
} else {
internalClient = false;
}
return new ZooKeeperUpdatingListener(client, zNodePath, nodeValueCodec, endpoint, internalClient);
} | [
"public",
"ZooKeeperUpdatingListener",
"build",
"(",
")",
"{",
"final",
"boolean",
"internalClient",
";",
"if",
"(",
"client",
"==",
"null",
")",
"{",
"client",
"=",
"CuratorFrameworkFactory",
".",
"builder",
"(",
")",
".",
"connectString",
"(",
"connectionStr",... | Returns a newly-created {@link ZooKeeperUpdatingListener} instance that registers the server to
ZooKeeper when the server starts. | [
"Returns",
"a",
"newly",
"-",
"created",
"{"
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/zookeeper/src/main/java/com/linecorp/armeria/server/zookeeper/ZooKeeperUpdatingListenerBuilder.java#L192-L207 |
xcesco/kripton | kripton/src/main/java/com/abubusoft/kripton/xml/XMLSerializer.java | XMLSerializer.setProperty | public void setProperty(String name, Object value) throws IllegalArgumentException, IllegalStateException {
if (name == null) {
throw new IllegalArgumentException("property name can not be null");
}
if (PROPERTY_SERIALIZER_INDENTATION.equals(name)) {
indentationString = (String) value;
} else if (PROPERTY_SERIALIZER_LINE_SEPARATOR.equals(name)) {
lineSeparator = (String) value;
} else if (PROPERTY_LOCATION.equals(name)) {
location = (String) value;
} else {
throw new IllegalStateException("unsupported property " + name);
}
writeLineSepartor = lineSeparator != null && lineSeparator.length() > 0;
writeIndentation = indentationString != null && indentationString.length() > 0;
// optimize - do not write when nothing to write ...
doIndent = indentationString != null && (writeLineSepartor || writeIndentation);
// NOTE: when indentationString == null there is no indentation
// (even though writeLineSeparator may be true ...)
rebuildIndentationBuf();
seenTag = false; // for consistency
} | java | public void setProperty(String name, Object value) throws IllegalArgumentException, IllegalStateException {
if (name == null) {
throw new IllegalArgumentException("property name can not be null");
}
if (PROPERTY_SERIALIZER_INDENTATION.equals(name)) {
indentationString = (String) value;
} else if (PROPERTY_SERIALIZER_LINE_SEPARATOR.equals(name)) {
lineSeparator = (String) value;
} else if (PROPERTY_LOCATION.equals(name)) {
location = (String) value;
} else {
throw new IllegalStateException("unsupported property " + name);
}
writeLineSepartor = lineSeparator != null && lineSeparator.length() > 0;
writeIndentation = indentationString != null && indentationString.length() > 0;
// optimize - do not write when nothing to write ...
doIndent = indentationString != null && (writeLineSepartor || writeIndentation);
// NOTE: when indentationString == null there is no indentation
// (even though writeLineSeparator may be true ...)
rebuildIndentationBuf();
seenTag = false; // for consistency
} | [
"public",
"void",
"setProperty",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"throws",
"IllegalArgumentException",
",",
"IllegalStateException",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"property na... | Sets the property.
@param name the name
@param value the value
@throws IllegalArgumentException the illegal argument exception
@throws IllegalStateException the illegal state exception | [
"Sets",
"the",
"property",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton/src/main/java/com/abubusoft/kripton/xml/XMLSerializer.java#L440-L461 |
jeremybrooks/jinx | src/main/java/net/jeremybrooks/jinx/api/PlacesApi.java | PlacesApi.getChildrenWithPhotosPublic | public Places getChildrenWithPhotosPublic(String placeId, String woeId) throws JinxException {
if (JinxUtils.isNullOrEmpty(placeId)) {
JinxUtils.validateParams(woeId);
}
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.places.getChildrenWithPhotosPublic");
if (JinxUtils.isNullOrEmpty(placeId)) {
params.put("woe_id", woeId);
} else {
params.put("place_id", placeId);
}
return jinx.flickrGet(params, Places.class, false);
} | java | public Places getChildrenWithPhotosPublic(String placeId, String woeId) throws JinxException {
if (JinxUtils.isNullOrEmpty(placeId)) {
JinxUtils.validateParams(woeId);
}
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.places.getChildrenWithPhotosPublic");
if (JinxUtils.isNullOrEmpty(placeId)) {
params.put("woe_id", woeId);
} else {
params.put("place_id", placeId);
}
return jinx.flickrGet(params, Places.class, false);
} | [
"public",
"Places",
"getChildrenWithPhotosPublic",
"(",
"String",
"placeId",
",",
"String",
"woeId",
")",
"throws",
"JinxException",
"{",
"if",
"(",
"JinxUtils",
".",
"isNullOrEmpty",
"(",
"placeId",
")",
")",
"{",
"JinxUtils",
".",
"validateParams",
"(",
"woeId... | Return a list of locations with public photos that are parented by a Where on Earth (WOE) or Places ID.
Authentication
<p>
This method does not require authentication.
<p>
You must provide a valid placesId or woeId. If you provide both, the placesId will be used.
<p>
@param placeId a Flickr places Id.
@param woeId a Where On Earth (WOE) id.
@return places with public photos in the specified area.
@throws JinxException if required parameters are missing, or if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.places.getChildrenWithPhotosPublic.html">flickr.places.getChildrenWithPhotosPublic</a> | [
"Return",
"a",
"list",
"of",
"locations",
"with",
"public",
"photos",
"that",
"are",
"parented",
"by",
"a",
"Where",
"on",
"Earth",
"(",
"WOE",
")",
"or",
"Places",
"ID",
".",
"Authentication",
"<p",
">",
"This",
"method",
"does",
"not",
"require",
"auth... | train | https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/PlacesApi.java#L128-L140 |
apache/incubator-gobblin | gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/hive/HiveDataset.java | HiveDataset.resolveConfig | @VisibleForTesting
protected static Config resolveConfig(Config datasetConfig, DbAndTable realDbAndTable, DbAndTable logicalDbAndTable) {
Preconditions.checkNotNull(datasetConfig, "Dataset config should not be null");
Preconditions.checkNotNull(realDbAndTable, "Real DB and table should not be null");
Preconditions.checkNotNull(logicalDbAndTable, "Logical DB and table should not be null");
Properties resolvedProperties = new Properties();
Config resolvedConfig = datasetConfig.resolve();
for (Map.Entry<String, ConfigValue> entry : resolvedConfig.entrySet()) {
if (ConfigValueType.LIST.equals(entry.getValue().valueType())) {
List<String> rawValueList = resolvedConfig.getStringList(entry.getKey());
List<String> resolvedValueList = Lists.newArrayList();
for (String rawValue : rawValueList) {
String resolvedValue = StringUtils.replaceEach(rawValue,
new String[] { DATABASE_TOKEN, TABLE_TOKEN, LOGICAL_DB_TOKEN, LOGICAL_TABLE_TOKEN },
new String[] { realDbAndTable.getDb(), realDbAndTable.getTable(), logicalDbAndTable.getDb(), logicalDbAndTable.getTable() });
resolvedValueList.add(resolvedValue);
}
StringBuilder listToStringWithQuotes = new StringBuilder();
for (String resolvedValueStr : resolvedValueList) {
if (listToStringWithQuotes.length() > 0) {
listToStringWithQuotes.append(",");
}
listToStringWithQuotes.append("\"").append(resolvedValueStr).append("\"");
}
resolvedProperties.setProperty(entry.getKey(), listToStringWithQuotes.toString());
} else {
String resolvedValue = StringUtils.replaceEach(resolvedConfig.getString(entry.getKey()),
new String[] { DATABASE_TOKEN, TABLE_TOKEN, LOGICAL_DB_TOKEN, LOGICAL_TABLE_TOKEN },
new String[] { realDbAndTable.getDb(), realDbAndTable.getTable(), logicalDbAndTable.getDb(), logicalDbAndTable.getTable() });
resolvedProperties.setProperty(entry.getKey(), resolvedValue);
}
}
return ConfigUtils.propertiesToConfig(resolvedProperties);
} | java | @VisibleForTesting
protected static Config resolveConfig(Config datasetConfig, DbAndTable realDbAndTable, DbAndTable logicalDbAndTable) {
Preconditions.checkNotNull(datasetConfig, "Dataset config should not be null");
Preconditions.checkNotNull(realDbAndTable, "Real DB and table should not be null");
Preconditions.checkNotNull(logicalDbAndTable, "Logical DB and table should not be null");
Properties resolvedProperties = new Properties();
Config resolvedConfig = datasetConfig.resolve();
for (Map.Entry<String, ConfigValue> entry : resolvedConfig.entrySet()) {
if (ConfigValueType.LIST.equals(entry.getValue().valueType())) {
List<String> rawValueList = resolvedConfig.getStringList(entry.getKey());
List<String> resolvedValueList = Lists.newArrayList();
for (String rawValue : rawValueList) {
String resolvedValue = StringUtils.replaceEach(rawValue,
new String[] { DATABASE_TOKEN, TABLE_TOKEN, LOGICAL_DB_TOKEN, LOGICAL_TABLE_TOKEN },
new String[] { realDbAndTable.getDb(), realDbAndTable.getTable(), logicalDbAndTable.getDb(), logicalDbAndTable.getTable() });
resolvedValueList.add(resolvedValue);
}
StringBuilder listToStringWithQuotes = new StringBuilder();
for (String resolvedValueStr : resolvedValueList) {
if (listToStringWithQuotes.length() > 0) {
listToStringWithQuotes.append(",");
}
listToStringWithQuotes.append("\"").append(resolvedValueStr).append("\"");
}
resolvedProperties.setProperty(entry.getKey(), listToStringWithQuotes.toString());
} else {
String resolvedValue = StringUtils.replaceEach(resolvedConfig.getString(entry.getKey()),
new String[] { DATABASE_TOKEN, TABLE_TOKEN, LOGICAL_DB_TOKEN, LOGICAL_TABLE_TOKEN },
new String[] { realDbAndTable.getDb(), realDbAndTable.getTable(), logicalDbAndTable.getDb(), logicalDbAndTable.getTable() });
resolvedProperties.setProperty(entry.getKey(), resolvedValue);
}
}
return ConfigUtils.propertiesToConfig(resolvedProperties);
} | [
"@",
"VisibleForTesting",
"protected",
"static",
"Config",
"resolveConfig",
"(",
"Config",
"datasetConfig",
",",
"DbAndTable",
"realDbAndTable",
",",
"DbAndTable",
"logicalDbAndTable",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"datasetConfig",
",",
"\"Dataset... | *
Replace various tokens (DB, TABLE, LOGICAL_DB, LOGICAL_TABLE) with their values.
@param datasetConfig The config object that needs to be resolved with final values.
@param realDbAndTable Real DB and Table .
@param logicalDbAndTable Logical DB and Table.
@return Resolved config object. | [
"*",
"Replace",
"various",
"tokens",
"(",
"DB",
"TABLE",
"LOGICAL_DB",
"LOGICAL_TABLE",
")",
"with",
"their",
"values",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/hive/HiveDataset.java#L263-L298 |
qiujiayu/AutoLoadCache | src/main/java/com/jarvis/cache/CacheHandler.java | CacheHandler.getCacheKey | private CacheKeyTO getCacheKey(CacheAopProxyChain pjp, Object[] arguments, ExCache exCache, Object result) {
Object target = pjp.getTarget();
String methodName = pjp.getMethod().getName();
String keyExpression = exCache.key();
if (null == keyExpression || keyExpression.trim().length() == 0) {
return null;
}
String hfieldExpression = exCache.hfield();
return getCacheKey(target, methodName, arguments, keyExpression, hfieldExpression, result, true);
} | java | private CacheKeyTO getCacheKey(CacheAopProxyChain pjp, Object[] arguments, ExCache exCache, Object result) {
Object target = pjp.getTarget();
String methodName = pjp.getMethod().getName();
String keyExpression = exCache.key();
if (null == keyExpression || keyExpression.trim().length() == 0) {
return null;
}
String hfieldExpression = exCache.hfield();
return getCacheKey(target, methodName, arguments, keyExpression, hfieldExpression, result, true);
} | [
"private",
"CacheKeyTO",
"getCacheKey",
"(",
"CacheAopProxyChain",
"pjp",
",",
"Object",
"[",
"]",
"arguments",
",",
"ExCache",
"exCache",
",",
"Object",
"result",
")",
"{",
"Object",
"target",
"=",
"pjp",
".",
"getTarget",
"(",
")",
";",
"String",
"methodNa... | 生成缓存 Key
@param pjp
@param arguments
@param exCache
@param result 执行结果值
@return 缓存Key | [
"生成缓存",
"Key"
] | train | https://github.com/qiujiayu/AutoLoadCache/blob/8121c146f1a420fa6d6832e849acadb547c13622/src/main/java/com/jarvis/cache/CacheHandler.java#L503-L512 |
google/error-prone-javac | src/jdk.jshell/share/classes/jdk/internal/jshell/tool/Startup.java | Startup.readFile | private static StartupEntry readFile(String filename, String context, MessageHandler mh) {
if (filename != null) {
try {
byte[] encoded = Files.readAllBytes(toPathResolvingUserHome(filename));
return new StartupEntry(false, filename, new String(encoded),
LocalDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)));
} catch (AccessDeniedException e) {
mh.errormsg("jshell.err.file.not.accessible", context, filename, e.getMessage());
} catch (NoSuchFileException e) {
String resource = getResource(filename);
if (resource != null) {
// Not found as file, but found as resource
return new StartupEntry(true, filename, resource);
}
mh.errormsg("jshell.err.file.not.found", context, filename);
} catch (Exception e) {
mh.errormsg("jshell.err.file.exception", context, filename, e);
}
} else {
mh.errormsg("jshell.err.file.filename", context);
}
return null;
} | java | private static StartupEntry readFile(String filename, String context, MessageHandler mh) {
if (filename != null) {
try {
byte[] encoded = Files.readAllBytes(toPathResolvingUserHome(filename));
return new StartupEntry(false, filename, new String(encoded),
LocalDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)));
} catch (AccessDeniedException e) {
mh.errormsg("jshell.err.file.not.accessible", context, filename, e.getMessage());
} catch (NoSuchFileException e) {
String resource = getResource(filename);
if (resource != null) {
// Not found as file, but found as resource
return new StartupEntry(true, filename, resource);
}
mh.errormsg("jshell.err.file.not.found", context, filename);
} catch (Exception e) {
mh.errormsg("jshell.err.file.exception", context, filename, e);
}
} else {
mh.errormsg("jshell.err.file.filename", context);
}
return null;
} | [
"private",
"static",
"StartupEntry",
"readFile",
"(",
"String",
"filename",
",",
"String",
"context",
",",
"MessageHandler",
"mh",
")",
"{",
"if",
"(",
"filename",
"!=",
"null",
")",
"{",
"try",
"{",
"byte",
"[",
"]",
"encoded",
"=",
"Files",
".",
"readA... | Read a external file or a resource.
@param filename file/resource to access
@param context printable non-natural language context for errors
@param mh handler for error messages
@return file as startup entry, or null when error (message has been printed) | [
"Read",
"a",
"external",
"file",
"or",
"a",
"resource",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/Startup.java#L294-L317 |
Netflix/eureka | eureka-client/src/main/java/com/netflix/discovery/shared/transport/EurekaHttpClients.java | EurekaHttpClients.failFastOnInitCheck | private static void failFastOnInitCheck(EurekaClientConfig clientConfig, String msg) {
if ("true".equals(clientConfig.getExperimental("clientTransportFailFastOnInit"))) {
throw new RuntimeException(msg);
}
} | java | private static void failFastOnInitCheck(EurekaClientConfig clientConfig, String msg) {
if ("true".equals(clientConfig.getExperimental("clientTransportFailFastOnInit"))) {
throw new RuntimeException(msg);
}
} | [
"private",
"static",
"void",
"failFastOnInitCheck",
"(",
"EurekaClientConfig",
"clientConfig",
",",
"String",
"msg",
")",
"{",
"if",
"(",
"\"true\"",
".",
"equals",
"(",
"clientConfig",
".",
"getExperimental",
"(",
"\"clientTransportFailFastOnInit\"",
")",
")",
")",... | potential future feature, guarding with experimental flag for now | [
"potential",
"future",
"feature",
"guarding",
"with",
"experimental",
"flag",
"for",
"now"
] | train | https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-client/src/main/java/com/netflix/discovery/shared/transport/EurekaHttpClients.java#L322-L326 |
JodaOrg/joda-convert | src/main/java/org/joda/convert/StringConvert.java | StringConvert.findFromStringConstructorByType | private <T> Constructor<T> findFromStringConstructorByType(Class<T> cls) {
try {
return cls.getDeclaredConstructor(String.class);
} catch (NoSuchMethodException ex) {
try {
return cls.getDeclaredConstructor(CharSequence.class);
} catch (NoSuchMethodException ex2) {
throw new IllegalArgumentException("Constructor not found", ex2);
}
}
} | java | private <T> Constructor<T> findFromStringConstructorByType(Class<T> cls) {
try {
return cls.getDeclaredConstructor(String.class);
} catch (NoSuchMethodException ex) {
try {
return cls.getDeclaredConstructor(CharSequence.class);
} catch (NoSuchMethodException ex2) {
throw new IllegalArgumentException("Constructor not found", ex2);
}
}
} | [
"private",
"<",
"T",
">",
"Constructor",
"<",
"T",
">",
"findFromStringConstructorByType",
"(",
"Class",
"<",
"T",
">",
"cls",
")",
"{",
"try",
"{",
"return",
"cls",
".",
"getDeclaredConstructor",
"(",
"String",
".",
"class",
")",
";",
"}",
"catch",
"(",... | Finds the conversion method.
@param <T> the type of the converter
@param cls the class to find a method for, not null
@return the method to call, null means use {@code toString} | [
"Finds",
"the",
"conversion",
"method",
"."
] | train | https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/StringConvert.java#L840-L850 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ExamplesImpl.java | ExamplesImpl.addAsync | public Observable<LabelExampleResponse> addAsync(UUID appId, String versionId, ExampleLabelObject exampleLabelObject) {
return addWithServiceResponseAsync(appId, versionId, exampleLabelObject).map(new Func1<ServiceResponse<LabelExampleResponse>, LabelExampleResponse>() {
@Override
public LabelExampleResponse call(ServiceResponse<LabelExampleResponse> response) {
return response.body();
}
});
} | java | public Observable<LabelExampleResponse> addAsync(UUID appId, String versionId, ExampleLabelObject exampleLabelObject) {
return addWithServiceResponseAsync(appId, versionId, exampleLabelObject).map(new Func1<ServiceResponse<LabelExampleResponse>, LabelExampleResponse>() {
@Override
public LabelExampleResponse call(ServiceResponse<LabelExampleResponse> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"LabelExampleResponse",
">",
"addAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"ExampleLabelObject",
"exampleLabelObject",
")",
"{",
"return",
"addWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"exampleLab... | Adds a labeled example to the application.
@param appId The application ID.
@param versionId The version ID.
@param exampleLabelObject An example label with the expected intent and entities.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the LabelExampleResponse object | [
"Adds",
"a",
"labeled",
"example",
"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/ExamplesImpl.java#L124-L131 |
apache/reef | lang/java/reef-runtime-local/src/main/java/org/apache/reef/runtime/local/client/FileSet.java | FileSet.addNamesTo | ConfigurationModule addNamesTo(final ConfigurationModule input, final OptionalParameter<String> field) {
ConfigurationModule result = input;
for (final String fileName : this.fileNames()) {
result = result.set(field, fileName);
}
return result;
} | java | ConfigurationModule addNamesTo(final ConfigurationModule input, final OptionalParameter<String> field) {
ConfigurationModule result = input;
for (final String fileName : this.fileNames()) {
result = result.set(field, fileName);
}
return result;
} | [
"ConfigurationModule",
"addNamesTo",
"(",
"final",
"ConfigurationModule",
"input",
",",
"final",
"OptionalParameter",
"<",
"String",
">",
"field",
")",
"{",
"ConfigurationModule",
"result",
"=",
"input",
";",
"for",
"(",
"final",
"String",
"fileName",
":",
"this",... | Adds the file names of this FileSet to the given field of the given ConfigurationModule.
@param input the ConfigurationModule to fill out
@param field the field to add the files in this set to.
@return the filled out ConfigurationModule | [
"Adds",
"the",
"file",
"names",
"of",
"this",
"FileSet",
"to",
"the",
"given",
"field",
"of",
"the",
"given",
"ConfigurationModule",
"."
] | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-runtime-local/src/main/java/org/apache/reef/runtime/local/client/FileSet.java#L106-L112 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/utils/RegionMap.java | RegionMap.toSubRegion | public RegionMap toSubRegion( double n, double s, double w, double e ) {
double originalXres = getXres();
double originalYres = getYres();
double originalWest = getWest();
double originalSouth = getSouth();
double envWest = w;
double deltaX = (envWest - originalWest) % originalXres;
double newWest = envWest - deltaX;
double envSouth = s;
double deltaY = (envSouth - originalSouth) % originalYres;
double newSouth = envSouth - deltaY;
double newWidth = e - w;
double deltaW = newWidth % originalXres;
newWidth = newWidth - deltaW + originalXres;
double newHeight = n - s;
double deltaH = newHeight % originalYres;
newHeight = newHeight - deltaH + originalYres;
double newNorth = newSouth + newHeight;
double newEast = newWest + newWidth;
int rows = (int) ((newHeight) / originalYres);
int cols = (int) ((newWidth) / originalXres);
double newXres = (newWidth) / cols;
double newYres = (newHeight) / rows;
RegionMap regionMap = CoverageUtilities.makeRegionParamsMap(newNorth, newSouth, newWest, newEast, newXres, newYres, cols,
rows);
return regionMap;
} | java | public RegionMap toSubRegion( double n, double s, double w, double e ) {
double originalXres = getXres();
double originalYres = getYres();
double originalWest = getWest();
double originalSouth = getSouth();
double envWest = w;
double deltaX = (envWest - originalWest) % originalXres;
double newWest = envWest - deltaX;
double envSouth = s;
double deltaY = (envSouth - originalSouth) % originalYres;
double newSouth = envSouth - deltaY;
double newWidth = e - w;
double deltaW = newWidth % originalXres;
newWidth = newWidth - deltaW + originalXres;
double newHeight = n - s;
double deltaH = newHeight % originalYres;
newHeight = newHeight - deltaH + originalYres;
double newNorth = newSouth + newHeight;
double newEast = newWest + newWidth;
int rows = (int) ((newHeight) / originalYres);
int cols = (int) ((newWidth) / originalXres);
double newXres = (newWidth) / cols;
double newYres = (newHeight) / rows;
RegionMap regionMap = CoverageUtilities.makeRegionParamsMap(newNorth, newSouth, newWest, newEast, newXres, newYres, cols,
rows);
return regionMap;
} | [
"public",
"RegionMap",
"toSubRegion",
"(",
"double",
"n",
",",
"double",
"s",
",",
"double",
"w",
",",
"double",
"e",
")",
"{",
"double",
"originalXres",
"=",
"getXres",
"(",
")",
";",
"double",
"originalYres",
"=",
"getYres",
"(",
")",
";",
"double",
... | Creates a new {@link RegionMap} cropped on the new bounds and snapped on the original grid.
<p><b>The supplied bounds are contained in the resulting region.</b></p>
@param n the new north.
@param s the new south.
@param w the new west.
@param e the new east.
@return the new {@link RegionMap}. | [
"Creates",
"a",
"new",
"{",
"@link",
"RegionMap",
"}",
"cropped",
"on",
"the",
"new",
"bounds",
"and",
"snapped",
"on",
"the",
"original",
"grid",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/RegionMap.java#L214-L248 |
tango-controls/JTango | client/src/main/java/fr/soleil/tango/clientapi/InsertExtractUtils.java | InsertExtractUtils.extractRead | public static Object extractRead(final DeviceAttribute da, final AttrDataFormat format) throws DevFailed {
if (da == null) {
throw DevFailedUtils.newDevFailed(ERROR_MSG_DA);
}
return InsertExtractFactory.getAttributeExtractor(da.getType()).extractRead(da, format);
} | java | public static Object extractRead(final DeviceAttribute da, final AttrDataFormat format) throws DevFailed {
if (da == null) {
throw DevFailedUtils.newDevFailed(ERROR_MSG_DA);
}
return InsertExtractFactory.getAttributeExtractor(da.getType()).extractRead(da, format);
} | [
"public",
"static",
"Object",
"extractRead",
"(",
"final",
"DeviceAttribute",
"da",
",",
"final",
"AttrDataFormat",
"format",
")",
"throws",
"DevFailed",
"{",
"if",
"(",
"da",
"==",
"null",
")",
"{",
"throw",
"DevFailedUtils",
".",
"newDevFailed",
"(",
"ERROR_... | Extract read values to an object for SCALAR, SPECTRUM and IMAGE
@param da
@return single value for SCALAR, array of primitives for SPECTRUM, 2D array of primitives for IMAGE
@throws DevFailed | [
"Extract",
"read",
"values",
"to",
"an",
"object",
"for",
"SCALAR",
"SPECTRUM",
"and",
"IMAGE"
] | train | https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/client/src/main/java/fr/soleil/tango/clientapi/InsertExtractUtils.java#L44-L49 |
Azure/azure-sdk-for-java | datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/ComputePoliciesInner.java | ComputePoliciesInner.listByAccountAsync | public Observable<Page<ComputePolicyInner>> listByAccountAsync(final String resourceGroupName, final String accountName) {
return listByAccountWithServiceResponseAsync(resourceGroupName, accountName)
.map(new Func1<ServiceResponse<Page<ComputePolicyInner>>, Page<ComputePolicyInner>>() {
@Override
public Page<ComputePolicyInner> call(ServiceResponse<Page<ComputePolicyInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<ComputePolicyInner>> listByAccountAsync(final String resourceGroupName, final String accountName) {
return listByAccountWithServiceResponseAsync(resourceGroupName, accountName)
.map(new Func1<ServiceResponse<Page<ComputePolicyInner>>, Page<ComputePolicyInner>>() {
@Override
public Page<ComputePolicyInner> call(ServiceResponse<Page<ComputePolicyInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"ComputePolicyInner",
">",
">",
"listByAccountAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"accountName",
")",
"{",
"return",
"listByAccountWithServiceResponseAsync",
"(",
"resourceGroupName",
","... | Lists the Data Lake Analytics compute policies within the specified Data Lake Analytics account. An account supports, at most, 50 policies.
@param resourceGroupName The name of the Azure resource group.
@param accountName The name of the Data Lake Analytics account.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ComputePolicyInner> object | [
"Lists",
"the",
"Data",
"Lake",
"Analytics",
"compute",
"policies",
"within",
"the",
"specified",
"Data",
"Lake",
"Analytics",
"account",
".",
"An",
"account",
"supports",
"at",
"most",
"50",
"policies",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/ComputePoliciesInner.java#L142-L150 |
azkaban/azkaban | azkaban-common/src/main/java/azkaban/sla/SlaOption.java | SlaOption.toObject | public Map<String, Object> toObject() {
final List<String> slaActions = new ArrayList<>();
final Map<String, Object> slaInfo = new HashMap<>();
slaInfo.put(SlaOptionDeprecated.INFO_FLOW_NAME, this.flowName);
if (hasAlert()) {
slaActions.add(SlaOptionDeprecated.ACTION_ALERT);
slaInfo.put(SlaOptionDeprecated.ALERT_TYPE, ALERT_TYPE_EMAIL);
}
if (hasKill()) {
if (this.type.getComponent() == ComponentType.FLOW) {
slaActions.add(SlaOptionDeprecated.ACTION_CANCEL_FLOW);
} else { // JOB
slaActions.add(SlaOptionDeprecated.ACTION_KILL_JOB);
}
}
if (this.type.getComponent() == ComponentType.JOB) {
slaInfo.put(SlaOptionDeprecated.INFO_JOB_NAME, this.jobName);
}
String slaType;
switch (this.type) {
case FLOW_FINISH:
slaType = SlaOptionDeprecated.TYPE_FLOW_FINISH;
break;
case FLOW_SUCCEED:
slaType = SlaOptionDeprecated.TYPE_FLOW_SUCCEED;
break;
case JOB_FINISH:
slaType = SlaOptionDeprecated.TYPE_JOB_FINISH;
break;
case JOB_SUCCEED:
slaType = SlaOptionDeprecated.TYPE_JOB_SUCCEED;
break;
default:
throw new IllegalStateException("unsupported SLA type " + this.type.getName());
}
slaInfo.put(SlaOptionDeprecated.INFO_DURATION, durationToString(this.duration));
slaInfo.put(SlaOptionDeprecated.INFO_EMAIL_LIST, emails);
SlaOptionDeprecated slaOption = new SlaOptionDeprecated(slaType, slaActions, slaInfo);
return slaOption.toObject();
} | java | public Map<String, Object> toObject() {
final List<String> slaActions = new ArrayList<>();
final Map<String, Object> slaInfo = new HashMap<>();
slaInfo.put(SlaOptionDeprecated.INFO_FLOW_NAME, this.flowName);
if (hasAlert()) {
slaActions.add(SlaOptionDeprecated.ACTION_ALERT);
slaInfo.put(SlaOptionDeprecated.ALERT_TYPE, ALERT_TYPE_EMAIL);
}
if (hasKill()) {
if (this.type.getComponent() == ComponentType.FLOW) {
slaActions.add(SlaOptionDeprecated.ACTION_CANCEL_FLOW);
} else { // JOB
slaActions.add(SlaOptionDeprecated.ACTION_KILL_JOB);
}
}
if (this.type.getComponent() == ComponentType.JOB) {
slaInfo.put(SlaOptionDeprecated.INFO_JOB_NAME, this.jobName);
}
String slaType;
switch (this.type) {
case FLOW_FINISH:
slaType = SlaOptionDeprecated.TYPE_FLOW_FINISH;
break;
case FLOW_SUCCEED:
slaType = SlaOptionDeprecated.TYPE_FLOW_SUCCEED;
break;
case JOB_FINISH:
slaType = SlaOptionDeprecated.TYPE_JOB_FINISH;
break;
case JOB_SUCCEED:
slaType = SlaOptionDeprecated.TYPE_JOB_SUCCEED;
break;
default:
throw new IllegalStateException("unsupported SLA type " + this.type.getName());
}
slaInfo.put(SlaOptionDeprecated.INFO_DURATION, durationToString(this.duration));
slaInfo.put(SlaOptionDeprecated.INFO_EMAIL_LIST, emails);
SlaOptionDeprecated slaOption = new SlaOptionDeprecated(slaType, slaActions, slaInfo);
return slaOption.toObject();
} | [
"public",
"Map",
"<",
"String",
",",
"Object",
">",
"toObject",
"(",
")",
"{",
"final",
"List",
"<",
"String",
">",
"slaActions",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"slaInfo",
"=",
"new",
... | Convert the SLA option to the original JSON format, used by {@link SlaOptionDeprecated}.
@return the JSON format for {@link SlaOptionDeprecated}. | [
"Convert",
"the",
"SLA",
"option",
"to",
"the",
"original",
"JSON",
"format",
"used",
"by",
"{",
"@link",
"SlaOptionDeprecated",
"}",
"."
] | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/sla/SlaOption.java#L212-L256 |
alkacon/opencms-core | src/org/opencms/ugc/CmsUgcEditService.java | CmsUgcEditService.handleUpload | protected void handleUpload(HttpServletRequest request, HttpServletResponse response) {
String sessionIdStr = request.getParameter(CmsUgcConstants.PARAM_SESSION_ID);
CmsUUID sessionId = new CmsUUID(sessionIdStr);
CmsUgcSession session = CmsUgcSessionFactory.getInstance().getSession(request, sessionId);
session.getFormUploadHelper().processFormSubmitRequest(request);
} | java | protected void handleUpload(HttpServletRequest request, HttpServletResponse response) {
String sessionIdStr = request.getParameter(CmsUgcConstants.PARAM_SESSION_ID);
CmsUUID sessionId = new CmsUUID(sessionIdStr);
CmsUgcSession session = CmsUgcSessionFactory.getInstance().getSession(request, sessionId);
session.getFormUploadHelper().processFormSubmitRequest(request);
} | [
"protected",
"void",
"handleUpload",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"{",
"String",
"sessionIdStr",
"=",
"request",
".",
"getParameter",
"(",
"CmsUgcConstants",
".",
"PARAM_SESSION_ID",
")",
";",
"CmsUUID",
"sessionId... | Handles all multipart requests.<p>
@param request the request
@param response the response | [
"Handles",
"all",
"multipart",
"requests",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ugc/CmsUgcEditService.java#L227-L233 |
groupon/odo | client/src/main/java/com/groupon/odo/client/Client.java | Client.setOverrideRepeatCount | public boolean setOverrideRepeatCount(String pathName, String methodName, Integer ordinal, Integer repeatCount) {
try {
String methodId = getOverrideIdForMethodName(methodName).toString();
BasicNameValuePair[] params = {
new BasicNameValuePair("profileIdentifier", this._profileName),
new BasicNameValuePair("ordinal", ordinal.toString()),
new BasicNameValuePair("repeatNumber", repeatCount.toString())
};
JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + "/" + methodId, params));
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
} | java | public boolean setOverrideRepeatCount(String pathName, String methodName, Integer ordinal, Integer repeatCount) {
try {
String methodId = getOverrideIdForMethodName(methodName).toString();
BasicNameValuePair[] params = {
new BasicNameValuePair("profileIdentifier", this._profileName),
new BasicNameValuePair("ordinal", ordinal.toString()),
new BasicNameValuePair("repeatNumber", repeatCount.toString())
};
JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + "/" + methodId, params));
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
} | [
"public",
"boolean",
"setOverrideRepeatCount",
"(",
"String",
"pathName",
",",
"String",
"methodName",
",",
"Integer",
"ordinal",
",",
"Integer",
"repeatCount",
")",
"{",
"try",
"{",
"String",
"methodId",
"=",
"getOverrideIdForMethodName",
"(",
"methodName",
")",
... | Set the repeat count of an override at ordinal index
@param pathName Path name
@param methodName Fully qualified method name
@param ordinal 1-based index of the override within the overrides of type methodName
@param repeatCount new repeat count to set
@return true if success, false otherwise | [
"Set",
"the",
"repeat",
"count",
"of",
"an",
"override",
"at",
"ordinal",
"index"
] | train | https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/client/src/main/java/com/groupon/odo/client/Client.java#L652-L667 |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.setScratchData | public void setScratchData(ScratchBank bank, byte[] data) {
ScratchData sd = ScratchData.create(bank, data);
sendMessage(BeanMessageID.BT_SET_SCRATCH, sd);
} | java | public void setScratchData(ScratchBank bank, byte[] data) {
ScratchData sd = ScratchData.create(bank, data);
sendMessage(BeanMessageID.BT_SET_SCRATCH, sd);
} | [
"public",
"void",
"setScratchData",
"(",
"ScratchBank",
"bank",
",",
"byte",
"[",
"]",
"data",
")",
"{",
"ScratchData",
"sd",
"=",
"ScratchData",
".",
"create",
"(",
"bank",
",",
"data",
")",
";",
"sendMessage",
"(",
"BeanMessageID",
".",
"BT_SET_SCRATCH",
... | Set a scratch bank data value with raw bytes.
@param bank The {@link com.punchthrough.bean.sdk.message.ScratchBank} being set
@param data The bytes to write into the scratch bank | [
"Set",
"a",
"scratch",
"bank",
"data",
"value",
"with",
"raw",
"bytes",
"."
] | train | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L926-L929 |
apache/groovy | subprojects/groovy-swing/src/main/java/org/codehaus/groovy/runtime/SwingGroovyMethods.java | SwingGroovyMethods.putAt | public static void putAt(DefaultListModel self, int index, Object e) {
self.set(index, e);
} | java | public static void putAt(DefaultListModel self, int index, Object e) {
self.set(index, e);
} | [
"public",
"static",
"void",
"putAt",
"(",
"DefaultListModel",
"self",
",",
"int",
"index",
",",
"Object",
"e",
")",
"{",
"self",
".",
"set",
"(",
"index",
",",
"e",
")",
";",
"}"
] | Allow DefaultListModel to work with subscript operators.<p>
<b>WARNING:</b> this operation does not replace the element at the
specified index, rather it inserts the element at that index, thus
increasing the size of of the model by 1.
@param self a DefaultListModel
@param index an index
@param e the element to insert at the given index
@since 1.6.4 | [
"Allow",
"DefaultListModel",
"to",
"work",
"with",
"subscript",
"operators",
".",
"<p",
">",
"<b",
">",
"WARNING",
":",
"<",
"/",
"b",
">",
"this",
"operation",
"does",
"not",
"replace",
"the",
"element",
"at",
"the",
"specified",
"index",
"rather",
"it",
... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/runtime/SwingGroovyMethods.java#L230-L232 |
sebastiangraf/treetank | coremodules/core/src/main/java/org/treetank/access/conf/StorageConfiguration.java | StorageConfiguration.deserialize | public static StorageConfiguration deserialize(final File pFile) throws TTIOException {
try {
FileReader fileReader = new FileReader(new File(pFile, Paths.ConfigBinary.getFile().getName()));
JsonReader jsonReader = new JsonReader(fileReader);
jsonReader.beginObject();
jsonReader.nextName();
File file = new File(jsonReader.nextString());
jsonReader.endObject();
jsonReader.close();
fileReader.close();
return new StorageConfiguration(file);
} catch (IOException ioexc) {
throw new TTIOException(ioexc);
}
} | java | public static StorageConfiguration deserialize(final File pFile) throws TTIOException {
try {
FileReader fileReader = new FileReader(new File(pFile, Paths.ConfigBinary.getFile().getName()));
JsonReader jsonReader = new JsonReader(fileReader);
jsonReader.beginObject();
jsonReader.nextName();
File file = new File(jsonReader.nextString());
jsonReader.endObject();
jsonReader.close();
fileReader.close();
return new StorageConfiguration(file);
} catch (IOException ioexc) {
throw new TTIOException(ioexc);
}
} | [
"public",
"static",
"StorageConfiguration",
"deserialize",
"(",
"final",
"File",
"pFile",
")",
"throws",
"TTIOException",
"{",
"try",
"{",
"FileReader",
"fileReader",
"=",
"new",
"FileReader",
"(",
"new",
"File",
"(",
"pFile",
",",
"Paths",
".",
"ConfigBinary",
... | Generate a StorageConfiguration out of a file.
@param pFile
where the StorageConfiguration lies in as json
@return a new {@link StorageConfiguration} class
@throws TTIOException | [
"Generate",
"a",
"StorageConfiguration",
"out",
"of",
"a",
"file",
"."
] | train | https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/coremodules/core/src/main/java/org/treetank/access/conf/StorageConfiguration.java#L172-L186 |
jronrun/benayn | benayn-ustyle/src/main/java/com/benayn/ustyle/Dater.java | Dater.of | public static Dater of(Date date, String pattern) {
return of(date).with(pattern);
} | java | public static Dater of(Date date, String pattern) {
return of(date).with(pattern);
} | [
"public",
"static",
"Dater",
"of",
"(",
"Date",
"date",
",",
"String",
"pattern",
")",
"{",
"return",
"of",
"(",
"date",
")",
".",
"with",
"(",
"pattern",
")",
";",
"}"
] | Returns a new Dater instance with the given date and pattern
@param date
@return | [
"Returns",
"a",
"new",
"Dater",
"instance",
"with",
"the",
"given",
"date",
"and",
"pattern"
] | train | https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/Dater.java#L244-L246 |
kiswanij/jk-util | src/main/java/com/jk/util/JKHttpUtil.java | JKHttpUtil.requestUrl | public static String requestUrl(final String url, final String method, final Properties header, final String body) {
try {
final URL siteUrl = new URL(url);
final HttpURLConnection connection = (HttpURLConnection) siteUrl.openConnection();
connection.setRequestMethod(method);
final Enumeration<?> keys = header.keys();
while (keys.hasMoreElements()) {
final String key = (String) keys.nextElement();
connection.addRequestProperty(key, header.getProperty(key));
}
connection.setDoOutput(true);
final OutputStream out = connection.getOutputStream();
out.write(body.getBytes());
connection.connect();
final int errorCode = connection.getResponseCode();
if (errorCode != HttpURLConnection.HTTP_OK) {
throw new JKHttpException(connection.getResponseMessage(), errorCode);
}
final String response = JKIOUtil.convertToString(connection.getInputStream());
return response;
} catch (IOException e) {
throw new JKHttpException(e);
}
} | java | public static String requestUrl(final String url, final String method, final Properties header, final String body) {
try {
final URL siteUrl = new URL(url);
final HttpURLConnection connection = (HttpURLConnection) siteUrl.openConnection();
connection.setRequestMethod(method);
final Enumeration<?> keys = header.keys();
while (keys.hasMoreElements()) {
final String key = (String) keys.nextElement();
connection.addRequestProperty(key, header.getProperty(key));
}
connection.setDoOutput(true);
final OutputStream out = connection.getOutputStream();
out.write(body.getBytes());
connection.connect();
final int errorCode = connection.getResponseCode();
if (errorCode != HttpURLConnection.HTTP_OK) {
throw new JKHttpException(connection.getResponseMessage(), errorCode);
}
final String response = JKIOUtil.convertToString(connection.getInputStream());
return response;
} catch (IOException e) {
throw new JKHttpException(e);
}
} | [
"public",
"static",
"String",
"requestUrl",
"(",
"final",
"String",
"url",
",",
"final",
"String",
"method",
",",
"final",
"Properties",
"header",
",",
"final",
"String",
"body",
")",
"{",
"try",
"{",
"final",
"URL",
"siteUrl",
"=",
"new",
"URL",
"(",
"u... | Send http request.
@param url the url
@param method the method
@param header the header
@param body the body
@return the string | [
"Send",
"http",
"request",
"."
] | train | https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKHttpUtil.java#L98-L124 |
pietermartin/sqlg | sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/EdgeLabel.java | EdgeLabel.removeInVertexLabel | void removeInVertexLabel(VertexLabel lbl, boolean preserveData) {
this.uncommittedRemovedInVertexLabels.add(lbl);
if (!preserveData) {
deleteColumn(lbl.getFullName() + Topology.IN_VERTEX_COLUMN_END);
}
} | java | void removeInVertexLabel(VertexLabel lbl, boolean preserveData) {
this.uncommittedRemovedInVertexLabels.add(lbl);
if (!preserveData) {
deleteColumn(lbl.getFullName() + Topology.IN_VERTEX_COLUMN_END);
}
} | [
"void",
"removeInVertexLabel",
"(",
"VertexLabel",
"lbl",
",",
"boolean",
"preserveData",
")",
"{",
"this",
".",
"uncommittedRemovedInVertexLabels",
".",
"add",
"(",
"lbl",
")",
";",
"if",
"(",
"!",
"preserveData",
")",
"{",
"deleteColumn",
"(",
"lbl",
".",
... | remove a vertex label from the in collection
@param lbl the vertex label
@param preserveData should we keep the sql data? | [
"remove",
"a",
"vertex",
"label",
"from",
"the",
"in",
"collection"
] | train | https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/EdgeLabel.java#L1245-L1250 |
MKLab-ITI/multimedia-indexing | src/main/java/gr/iti/mklab/visual/utilities/ImageIOGreyScale.java | ImageIOGreyScale.createImageInputStream | public static ImageInputStream createImageInputStream(Object input) throws IOException {
if (input == null) {
throw new IllegalArgumentException("input == null!");
}
Iterator iter;
// Ensure category is present
try {
iter = theRegistry.getServiceProviders(ImageInputStreamSpi.class, true);
} catch (IllegalArgumentException e) {
return null;
}
boolean usecache = getUseCache() && hasCachePermission();
while (iter.hasNext()) {
ImageInputStreamSpi spi = (ImageInputStreamSpi) iter.next();
if (spi.getInputClass().isInstance(input)) {
try {
return spi.createInputStreamInstance(input, usecache, getCacheDirectory());
} catch (IOException e) {
throw new IIOException("Can't create cache file!", e);
}
}
}
return null;
} | java | public static ImageInputStream createImageInputStream(Object input) throws IOException {
if (input == null) {
throw new IllegalArgumentException("input == null!");
}
Iterator iter;
// Ensure category is present
try {
iter = theRegistry.getServiceProviders(ImageInputStreamSpi.class, true);
} catch (IllegalArgumentException e) {
return null;
}
boolean usecache = getUseCache() && hasCachePermission();
while (iter.hasNext()) {
ImageInputStreamSpi spi = (ImageInputStreamSpi) iter.next();
if (spi.getInputClass().isInstance(input)) {
try {
return spi.createInputStreamInstance(input, usecache, getCacheDirectory());
} catch (IOException e) {
throw new IIOException("Can't create cache file!", e);
}
}
}
return null;
} | [
"public",
"static",
"ImageInputStream",
"createImageInputStream",
"(",
"Object",
"input",
")",
"throws",
"IOException",
"{",
"if",
"(",
"input",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"input == null!\"",
")",
";",
"}",
"Iterator... | Returns an <code>ImageInputStream</code> that will take its input from the given <code>Object</code>.
The set of <code>ImageInputStreamSpi</code>s registered with the <code>IIORegistry</code> class is
queried and the first one that is able to take input from the supplied object is used to create the
returned <code>ImageInputStream</code>. If no suitable <code>ImageInputStreamSpi</code> exists,
<code>null</code> is returned.
<p>
The current cache settings from <code>getUseCache</code>and <code>getCacheDirectory</code> will be used
to control caching.
@param input
an <code>Object</code> to be used as an input source, such as a <code>File</code>, readable
<code>RandomAccessFile</code>, or <code>InputStream</code>.
@return an <code>ImageInputStream</code>, or <code>null</code>.
@exception IllegalArgumentException
if <code>input</code> is <code>null</code>.
@exception IOException
if a cache file is needed but cannot be created.
@see javax.imageio.spi.ImageInputStreamSpi | [
"Returns",
"an",
"<code",
">",
"ImageInputStream<",
"/",
"code",
">",
"that",
"will",
"take",
"its",
"input",
"from",
"the",
"given",
"<code",
">",
"Object<",
"/",
"code",
">",
".",
"The",
"set",
"of",
"<code",
">",
"ImageInputStreamSpi<",
"/",
"code",
"... | train | https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/ImageIOGreyScale.java#L296-L323 |
knowm/Sundial | src/main/java/org/knowm/sundial/SundialJobScheduler.java | SundialJobScheduler.getAllJobsAndTriggers | public static Map<String, List<Trigger>> getAllJobsAndTriggers()
throws SundialSchedulerException {
Map<String, List<Trigger>> allJobsMap = new TreeMap<String, List<Trigger>>();
try {
Set<String> allJobKeys = getScheduler().getJobKeys();
for (String jobKey : allJobKeys) {
List<Trigger> triggers = getScheduler().getTriggersOfJob(jobKey);
allJobsMap.put(jobKey, triggers);
}
} catch (SchedulerException e) {
throw new SundialSchedulerException("COULD NOT GET JOB NAMES!!!", e);
}
return allJobsMap;
} | java | public static Map<String, List<Trigger>> getAllJobsAndTriggers()
throws SundialSchedulerException {
Map<String, List<Trigger>> allJobsMap = new TreeMap<String, List<Trigger>>();
try {
Set<String> allJobKeys = getScheduler().getJobKeys();
for (String jobKey : allJobKeys) {
List<Trigger> triggers = getScheduler().getTriggersOfJob(jobKey);
allJobsMap.put(jobKey, triggers);
}
} catch (SchedulerException e) {
throw new SundialSchedulerException("COULD NOT GET JOB NAMES!!!", e);
}
return allJobsMap;
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"List",
"<",
"Trigger",
">",
">",
"getAllJobsAndTriggers",
"(",
")",
"throws",
"SundialSchedulerException",
"{",
"Map",
"<",
"String",
",",
"List",
"<",
"Trigger",
">",
">",
"allJobsMap",
"=",
"new",
"TreeMap",
... | Generates a Map of all Job names with corresponding Triggers
@return | [
"Generates",
"a",
"Map",
"of",
"all",
"Job",
"names",
"with",
"corresponding",
"Triggers"
] | train | https://github.com/knowm/Sundial/blob/0d61549fdfb8d6f884a1f2eed7e32ad39e2f4c62/src/main/java/org/knowm/sundial/SundialJobScheduler.java#L525-L540 |
JDBDT/jdbdt | src/main/java/org/jdbdt/JDBDT.java | JDBDT.assertInserted | @SafeVarargs
public static void assertInserted(String message, DataSet... dataSets) throws DBAssertionError {
multipleInsertAssertions(CallInfo.create(message), dataSets);
} | java | @SafeVarargs
public static void assertInserted(String message, DataSet... dataSets) throws DBAssertionError {
multipleInsertAssertions(CallInfo.create(message), dataSets);
} | [
"@",
"SafeVarargs",
"public",
"static",
"void",
"assertInserted",
"(",
"String",
"message",
",",
"DataSet",
"...",
"dataSets",
")",
"throws",
"DBAssertionError",
"{",
"multipleInsertAssertions",
"(",
"CallInfo",
".",
"create",
"(",
"message",
")",
",",
"dataSets",... | Assert that database changed only by insertion of given
data sets (error message variant).
@param message Assertion error message.
@param dataSets Data sets.
@throws DBAssertionError if the assertion fails.
@see #assertInserted(String,DataSet)
@since 1.2 | [
"Assert",
"that",
"database",
"changed",
"only",
"by",
"insertion",
"of",
"given",
"data",
"sets",
"(",
"error",
"message",
"variant",
")",
"."
] | train | https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/JDBDT.java#L546-L549 |
jboss/jboss-jstl-api_spec | src/main/java/org/apache/taglibs/standard/tag/common/sql/DataSourceWrapper.java | DataSourceWrapper.getConnection | public Connection getConnection(String username, String password)
throws SQLException {
throw new SQLException(Resources.getMessage("NOT_SUPPORTED"));
} | java | public Connection getConnection(String username, String password)
throws SQLException {
throw new SQLException(Resources.getMessage("NOT_SUPPORTED"));
} | [
"public",
"Connection",
"getConnection",
"(",
"String",
"username",
",",
"String",
"password",
")",
"throws",
"SQLException",
"{",
"throw",
"new",
"SQLException",
"(",
"Resources",
".",
"getMessage",
"(",
"\"NOT_SUPPORTED\"",
")",
")",
";",
"}"
] | Always throws a SQLException. Username and password are set
in the constructor and can not be changed. | [
"Always",
"throws",
"a",
"SQLException",
".",
"Username",
"and",
"password",
"are",
"set",
"in",
"the",
"constructor",
"and",
"can",
"not",
"be",
"changed",
"."
] | train | https://github.com/jboss/jboss-jstl-api_spec/blob/4ad412ae5be1ae606b8d33c188cb3d98bfcbe84c/src/main/java/org/apache/taglibs/standard/tag/common/sql/DataSourceWrapper.java#L111-L114 |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/square/DetectFiducialSquareImage.java | DetectFiducialSquareImage.addPattern | public int addPattern(GrayU8 inputBinary, double lengthSide) {
if( inputBinary == null ) {
throw new IllegalArgumentException("Input image is null.");
} else if( lengthSide <= 0 ) {
throw new IllegalArgumentException("Parameter lengthSide must be more than zero");
} else if(ImageStatistics.max(inputBinary) > 1 )
throw new IllegalArgumentException("A binary image is composed on 0 and 1 pixels. This isn't binary!");
// see if it needs to be resized
if ( inputBinary.width != squareLength || inputBinary.height != squareLength ) {
// need to create a new image and rescale it to better handle the resizing
GrayF32 inputGray = new GrayF32(inputBinary.width,inputBinary.height);
ConvertImage.convert(inputBinary,inputGray);
PixelMath.multiply(inputGray,255,inputGray);
GrayF32 scaled = new GrayF32(squareLength,squareLength);
// See if it can use the better algorithm for scaling down the image
if( inputBinary.width > squareLength && inputBinary.height > squareLength ) {
AverageDownSampleOps.down(inputGray,scaled);
} else {
new FDistort(inputGray,scaled).scaleExt().apply();
}
GThresholdImageOps.threshold(scaled,binary,255/2.0,false);
} else {
binary.setTo(inputBinary);
}
// describe it in 4 different orientations
FiducialDef def = new FiducialDef();
def.lengthSide = lengthSide;
// CCW rotation so that the index refers to how many CW rotation it takes to put it into the nominal pose
binaryToDef(binary, def.desc[0]);
ImageMiscOps.rotateCCW(binary);
binaryToDef(binary, def.desc[1]);
ImageMiscOps.rotateCCW(binary);
binaryToDef(binary, def.desc[2]);
ImageMiscOps.rotateCCW(binary);
binaryToDef(binary, def.desc[3]);
int index = targets.size();
targets.add( def );
return index;
} | java | public int addPattern(GrayU8 inputBinary, double lengthSide) {
if( inputBinary == null ) {
throw new IllegalArgumentException("Input image is null.");
} else if( lengthSide <= 0 ) {
throw new IllegalArgumentException("Parameter lengthSide must be more than zero");
} else if(ImageStatistics.max(inputBinary) > 1 )
throw new IllegalArgumentException("A binary image is composed on 0 and 1 pixels. This isn't binary!");
// see if it needs to be resized
if ( inputBinary.width != squareLength || inputBinary.height != squareLength ) {
// need to create a new image and rescale it to better handle the resizing
GrayF32 inputGray = new GrayF32(inputBinary.width,inputBinary.height);
ConvertImage.convert(inputBinary,inputGray);
PixelMath.multiply(inputGray,255,inputGray);
GrayF32 scaled = new GrayF32(squareLength,squareLength);
// See if it can use the better algorithm for scaling down the image
if( inputBinary.width > squareLength && inputBinary.height > squareLength ) {
AverageDownSampleOps.down(inputGray,scaled);
} else {
new FDistort(inputGray,scaled).scaleExt().apply();
}
GThresholdImageOps.threshold(scaled,binary,255/2.0,false);
} else {
binary.setTo(inputBinary);
}
// describe it in 4 different orientations
FiducialDef def = new FiducialDef();
def.lengthSide = lengthSide;
// CCW rotation so that the index refers to how many CW rotation it takes to put it into the nominal pose
binaryToDef(binary, def.desc[0]);
ImageMiscOps.rotateCCW(binary);
binaryToDef(binary, def.desc[1]);
ImageMiscOps.rotateCCW(binary);
binaryToDef(binary, def.desc[2]);
ImageMiscOps.rotateCCW(binary);
binaryToDef(binary, def.desc[3]);
int index = targets.size();
targets.add( def );
return index;
} | [
"public",
"int",
"addPattern",
"(",
"GrayU8",
"inputBinary",
",",
"double",
"lengthSide",
")",
"{",
"if",
"(",
"inputBinary",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Input image is null.\"",
")",
";",
"}",
"else",
"if",
"(",... | Adds a new image to the detector. Image must be gray-scale and is converted into
a binary image using the specified threshold. All input images are rescaled to be
square and of the appropriate size. Thus the original shape of the image doesn't
matter. Square shapes are highly recommended since that's what the target looks like.
@param inputBinary Binary input image pattern. 0 = black, 1 = white.
@param lengthSide How long one of the sides of the target is in world units.
@return The ID of the provided image | [
"Adds",
"a",
"new",
"image",
"to",
"the",
"detector",
".",
"Image",
"must",
"be",
"gray",
"-",
"scale",
"and",
"is",
"converted",
"into",
"a",
"binary",
"image",
"using",
"the",
"specified",
"threshold",
".",
"All",
"input",
"images",
"are",
"rescaled",
... | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/square/DetectFiducialSquareImage.java#L114-L158 |
emilsjolander/sprinkles | library/src/main/java/se/emilsjolander/sprinkles/ManyQuery.java | ManyQuery.getAsync | public int getAsync(android.support.v4.app.LoaderManager lm, ResultHandler<T> handler, Class<? extends Model>... respondsToUpdatedOf) {
if (Model.class.isAssignableFrom(resultClass)) {
respondsToUpdatedOf = Utils.concatArrays(respondsToUpdatedOf, new Class[]{resultClass});
}
final int loaderId = placeholderQuery.hashCode();
lm.restartLoader(loaderId, null, getSupportLoaderCallbacks(rawQuery, resultClass, handler, respondsToUpdatedOf));
return loaderId;
} | java | public int getAsync(android.support.v4.app.LoaderManager lm, ResultHandler<T> handler, Class<? extends Model>... respondsToUpdatedOf) {
if (Model.class.isAssignableFrom(resultClass)) {
respondsToUpdatedOf = Utils.concatArrays(respondsToUpdatedOf, new Class[]{resultClass});
}
final int loaderId = placeholderQuery.hashCode();
lm.restartLoader(loaderId, null, getSupportLoaderCallbacks(rawQuery, resultClass, handler, respondsToUpdatedOf));
return loaderId;
} | [
"public",
"int",
"getAsync",
"(",
"android",
".",
"support",
".",
"v4",
".",
"app",
".",
"LoaderManager",
"lm",
",",
"ResultHandler",
"<",
"T",
">",
"handler",
",",
"Class",
"<",
"?",
"extends",
"Model",
">",
"...",
"respondsToUpdatedOf",
")",
"{",
"if",... | Execute the query asynchronously
@param lm
The loader manager to use for loading the data
@param handler
The ResultHandler to notify of the query result and any updates to that result.
@param respondsToUpdatedOf
A list of models excluding the queried model that should also trigger a update to the result if they change.
@return the id of the loader. | [
"Execute",
"the",
"query",
"asynchronously"
] | train | https://github.com/emilsjolander/sprinkles/blob/3a666f18ee5158db6fe3b4f4346b470481559606/library/src/main/java/se/emilsjolander/sprinkles/ManyQuery.java#L94-L101 |
alkacon/opencms-core | src/org/opencms/util/CmsFileUtil.java | CmsFileUtil.readFully | public static byte[] readFully(InputStream in, boolean closeInputStream) throws IOException {
if (in instanceof ByteArrayInputStream) {
// content can be read in one pass
return readFully(in, in.available(), closeInputStream);
}
// copy buffer
byte[] xfer = new byte[2048];
// output buffer
ByteArrayOutputStream out = new ByteArrayOutputStream(xfer.length);
// transfer data from input to output in xfer-sized chunks.
for (int bytesRead = in.read(xfer, 0, xfer.length); bytesRead >= 0; bytesRead = in.read(xfer, 0, xfer.length)) {
if (bytesRead > 0) {
out.write(xfer, 0, bytesRead);
}
}
if (closeInputStream) {
in.close();
}
out.close();
return out.toByteArray();
} | java | public static byte[] readFully(InputStream in, boolean closeInputStream) throws IOException {
if (in instanceof ByteArrayInputStream) {
// content can be read in one pass
return readFully(in, in.available(), closeInputStream);
}
// copy buffer
byte[] xfer = new byte[2048];
// output buffer
ByteArrayOutputStream out = new ByteArrayOutputStream(xfer.length);
// transfer data from input to output in xfer-sized chunks.
for (int bytesRead = in.read(xfer, 0, xfer.length); bytesRead >= 0; bytesRead = in.read(xfer, 0, xfer.length)) {
if (bytesRead > 0) {
out.write(xfer, 0, bytesRead);
}
}
if (closeInputStream) {
in.close();
}
out.close();
return out.toByteArray();
} | [
"public",
"static",
"byte",
"[",
"]",
"readFully",
"(",
"InputStream",
"in",
",",
"boolean",
"closeInputStream",
")",
"throws",
"IOException",
"{",
"if",
"(",
"in",
"instanceof",
"ByteArrayInputStream",
")",
"{",
"// content can be read in one pass",
"return",
"read... | Reads all bytes from the given input stream, conditionally closes the given input stream
and returns the result in an array.<p>
@param in the input stream to read the bytes from
@return the byte content of the input stream
@param closeInputStream if true the given stream will be closed afterwards
@throws IOException in case of errors in the underlying java.io methods used | [
"Reads",
"all",
"bytes",
"from",
"the",
"given",
"input",
"stream",
"conditionally",
"closes",
"the",
"given",
"input",
"stream",
"and",
"returns",
"the",
"result",
"in",
"an",
"array",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsFileUtil.java#L657-L680 |
qiujuer/Genius-Android | caprice/ui/src/main/java/net/qiujuer/genius/ui/widget/EditText.java | EditText.checkShowTitle | private void checkShowTitle(Editable s, boolean skipChange) {
// in this we can check width
if (isShowTitle() && getWidth() > 0) {
boolean have = s != null && s.length() > 0;
if (have != isHaveText || (have && skipChange)) {
isHaveText = have;
animateShowTitle(isHaveText);
}
}
} | java | private void checkShowTitle(Editable s, boolean skipChange) {
// in this we can check width
if (isShowTitle() && getWidth() > 0) {
boolean have = s != null && s.length() > 0;
if (have != isHaveText || (have && skipChange)) {
isHaveText = have;
animateShowTitle(isHaveText);
}
}
} | [
"private",
"void",
"checkShowTitle",
"(",
"Editable",
"s",
",",
"boolean",
"skipChange",
")",
"{",
"// in this we can check width",
"if",
"(",
"isShowTitle",
"(",
")",
"&&",
"getWidth",
"(",
")",
">",
"0",
")",
"{",
"boolean",
"have",
"=",
"s",
"!=",
"null... | Check show hint title
@param s The text, if the have same string we should move hint
@param skipChange on showed we not refresh ui, but skipChange=true,
we can skip the check | [
"Check",
"show",
"hint",
"title"
] | train | https://github.com/qiujuer/Genius-Android/blob/babefaf1321f5883a21cada582b6fa5104adc648/caprice/ui/src/main/java/net/qiujuer/genius/ui/widget/EditText.java#L282-L291 |
BranchMetrics/android-branch-deep-linking | Branch-SDK/src/io/branch/referral/ServerRequestQueue.java | ServerRequestQueue.moveInstallOrOpenToFront | @SuppressWarnings("unused")
void moveInstallOrOpenToFront(ServerRequest request, int networkCount, Branch.BranchReferralInitListener callback) {
synchronized (reqQueueLockObject) {
Iterator<ServerRequest> iter = queue.iterator();
while (iter.hasNext()) {
ServerRequest req = iter.next();
if (req != null && (req instanceof ServerRequestRegisterInstall || req instanceof ServerRequestRegisterOpen)) {
//Remove all install or open in queue. Since this method is called each time on Install/open there will be only one
//instance of open/Install in queue. So we can break as we see the first open/install
iter.remove();
break;
}
}
}
insert(request, networkCount == 0 ? 0 : 1);
} | java | @SuppressWarnings("unused")
void moveInstallOrOpenToFront(ServerRequest request, int networkCount, Branch.BranchReferralInitListener callback) {
synchronized (reqQueueLockObject) {
Iterator<ServerRequest> iter = queue.iterator();
while (iter.hasNext()) {
ServerRequest req = iter.next();
if (req != null && (req instanceof ServerRequestRegisterInstall || req instanceof ServerRequestRegisterOpen)) {
//Remove all install or open in queue. Since this method is called each time on Install/open there will be only one
//instance of open/Install in queue. So we can break as we see the first open/install
iter.remove();
break;
}
}
}
insert(request, networkCount == 0 ? 0 : 1);
} | [
"@",
"SuppressWarnings",
"(",
"\"unused\"",
")",
"void",
"moveInstallOrOpenToFront",
"(",
"ServerRequest",
"request",
",",
"int",
"networkCount",
",",
"Branch",
".",
"BranchReferralInitListener",
"callback",
")",
"{",
"synchronized",
"(",
"reqQueueLockObject",
")",
"{... | <p>Moves any {@link ServerRequest} of type {@link ServerRequestRegisterInstall}
or {@link ServerRequestRegisterOpen} to the front of the queue.</p>
@param request A {@link ServerRequest} of type open or install which need to be moved to the front of the queue.
@param networkCount An {@link Integer} value that indicates whether or not to insert the
request at the front of the queue or not.
@param callback A {Branch.BranchReferralInitListener} instance for open or install callback. | [
"<p",
">",
"Moves",
"any",
"{",
"@link",
"ServerRequest",
"}",
"of",
"type",
"{",
"@link",
"ServerRequestRegisterInstall",
"}",
"or",
"{",
"@link",
"ServerRequestRegisterOpen",
"}",
"to",
"the",
"front",
"of",
"the",
"queue",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/ServerRequestQueue.java#L329-L346 |
sarl/sarl | main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/launching/dialog/SARLAgentMainLaunchConfigurationTab.java | SARLAgentMainLaunchConfigurationTab.createLaunchOptionEditor | protected void createLaunchOptionEditor(Composite parent, String text) {
final Group group = SWTFactory.createGroup(parent, text, 1, 1, GridData.FILL_HORIZONTAL);
this.showLogoOptionButton = createCheckButton(group, Messages.MainLaunchConfigurationTab_14);
this.showLogoOptionButton.addSelectionListener(this.defaultListener);
this.showLogInfoButton = createCheckButton(group, Messages.MainLaunchConfigurationTab_15);
this.showLogInfoButton.addSelectionListener(this.defaultListener);
this.offlineButton = createCheckButton(group, Messages.MainLaunchConfigurationTab_16);
this.offlineButton.addSelectionListener(this.defaultListener);
this.enableAssertionsInRunModeButton = createCheckButton(group, Messages.SARLMainLaunchConfigurationTab_2);
this.enableAssertionsInRunModeButton.addSelectionListener(this.defaultListener);
this.enableAssertionsInDebugModeButton = createCheckButton(group, Messages.SARLMainLaunchConfigurationTab_1);
this.enableAssertionsInDebugModeButton.addSelectionListener(this.defaultListener);
this.runInEclipseButton = createCheckButton(group, Messages.SARLMainLaunchConfigurationTab_0);
this.runInEclipseButton.addSelectionListener(this.defaultListener);
} | java | protected void createLaunchOptionEditor(Composite parent, String text) {
final Group group = SWTFactory.createGroup(parent, text, 1, 1, GridData.FILL_HORIZONTAL);
this.showLogoOptionButton = createCheckButton(group, Messages.MainLaunchConfigurationTab_14);
this.showLogoOptionButton.addSelectionListener(this.defaultListener);
this.showLogInfoButton = createCheckButton(group, Messages.MainLaunchConfigurationTab_15);
this.showLogInfoButton.addSelectionListener(this.defaultListener);
this.offlineButton = createCheckButton(group, Messages.MainLaunchConfigurationTab_16);
this.offlineButton.addSelectionListener(this.defaultListener);
this.enableAssertionsInRunModeButton = createCheckButton(group, Messages.SARLMainLaunchConfigurationTab_2);
this.enableAssertionsInRunModeButton.addSelectionListener(this.defaultListener);
this.enableAssertionsInDebugModeButton = createCheckButton(group, Messages.SARLMainLaunchConfigurationTab_1);
this.enableAssertionsInDebugModeButton.addSelectionListener(this.defaultListener);
this.runInEclipseButton = createCheckButton(group, Messages.SARLMainLaunchConfigurationTab_0);
this.runInEclipseButton.addSelectionListener(this.defaultListener);
} | [
"protected",
"void",
"createLaunchOptionEditor",
"(",
"Composite",
"parent",
",",
"String",
"text",
")",
"{",
"final",
"Group",
"group",
"=",
"SWTFactory",
".",
"createGroup",
"(",
"parent",
",",
"text",
",",
"1",
",",
"1",
",",
"GridData",
".",
"FILL_HORIZO... | Creates the widgets for configuring the launch options.
@param parent the parent composite.
@param text the label of the group. | [
"Creates",
"the",
"widgets",
"for",
"configuring",
"the",
"launch",
"options",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/launching/dialog/SARLAgentMainLaunchConfigurationTab.java#L226-L240 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/AnnotationUtils.java | AnnotationUtils.memberEquals | @GwtIncompatible("incompatible method")
private static boolean memberEquals(final Class<?> type, final Object o1, final Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (type.isArray()) {
return arrayMemberEquals(type.getComponentType(), o1, o2);
}
if (type.isAnnotation()) {
return equals((Annotation) o1, (Annotation) o2);
}
return o1.equals(o2);
} | java | @GwtIncompatible("incompatible method")
private static boolean memberEquals(final Class<?> type, final Object o1, final Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (type.isArray()) {
return arrayMemberEquals(type.getComponentType(), o1, o2);
}
if (type.isAnnotation()) {
return equals((Annotation) o1, (Annotation) o2);
}
return o1.equals(o2);
} | [
"@",
"GwtIncompatible",
"(",
"\"incompatible method\"",
")",
"private",
"static",
"boolean",
"memberEquals",
"(",
"final",
"Class",
"<",
"?",
">",
"type",
",",
"final",
"Object",
"o1",
",",
"final",
"Object",
"o2",
")",
"{",
"if",
"(",
"o1",
"==",
"o2",
... | Helper method for checking whether two objects of the given type are
equal. This method is used to compare the parameters of two annotation
instances.
@param type the type of the objects to be compared
@param o1 the first object
@param o2 the second object
@return a flag whether these objects are equal | [
"Helper",
"method",
"for",
"checking",
"whether",
"two",
"objects",
"of",
"the",
"given",
"type",
"are",
"equal",
".",
"This",
"method",
"is",
"used",
"to",
"compare",
"the",
"parameters",
"of",
"two",
"annotation",
"instances",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/AnnotationUtils.java#L269-L284 |
liferay/com-liferay-commerce | commerce-product-type-virtual-order-service/src/main/java/com/liferay/commerce/product/type/virtual/order/service/persistence/impl/CommerceVirtualOrderItemPersistenceImpl.java | CommerceVirtualOrderItemPersistenceImpl.findAll | @Override
public List<CommerceVirtualOrderItem> findAll(int start, int end) {
return findAll(start, end, null);
} | java | @Override
public List<CommerceVirtualOrderItem> findAll(int start, int end) {
return findAll(start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceVirtualOrderItem",
">",
"findAll",
"(",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findAll",
"(",
"start",
",",
"end",
",",
"null",
")",
";",
"}"
] | Returns a range of all the commerce virtual order items.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceVirtualOrderItemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param start the lower bound of the range of commerce virtual order items
@param end the upper bound of the range of commerce virtual order items (not inclusive)
@return the range of commerce virtual order items | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"virtual",
"order",
"items",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-type-virtual-order-service/src/main/java/com/liferay/commerce/product/type/virtual/order/service/persistence/impl/CommerceVirtualOrderItemPersistenceImpl.java#L2369-L2372 |
banq/jdonframework | JdonAccessory/jdon-struts1x/src/main/java/com/jdon/strutsutil/ModelViewAction.java | ModelViewAction.execute | public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Debug.logVerbose("[JdonFramework]--> enter ModelViewAction process ", module);
intContext(this.getServlet().getServletContext());
ModelForm modelForm = FormBeanUtil.getModelForm(actionMapping, actionForm, request);
if ((UtilValidate.isEmpty(modelForm.getAction())) || modelForm.getAction().equalsIgnoreCase(ModelForm.CREATE_STR)) {
Debug.logVerbose("[JdonFramework]--> enter create process ", module);
modelForm.setAction(ModelForm.CREATE_STR);
createViewPage.doCreate(actionMapping, modelForm, request);
} else if (modelForm.getAction().equalsIgnoreCase(ModelForm.EDIT_STR)) {
Debug.logVerbose("[JdonFramework]--> enter " + ModelForm.EDIT_STR + " process ", module);
Object model = editeViewPage.getModelForEdit(actionMapping, modelForm, request, this.servlet.getServletContext());
if (model == null) // not found the model
return errorsForward(modelForm.getAction(), actionMapping, request);
} else if (modelForm.getAction().equalsIgnoreCase(ModelForm.VIEW_STR)) {
Debug.logVerbose("[JdonFramework]--> enter " + ModelForm.VIEW_STR + " process ", module);
Object model = editeViewPage.getModelForEdit(actionMapping, modelForm, request, this.servlet.getServletContext());
if (model == null) // not found the model
return errorsForward(modelForm.getAction(), actionMapping, request);
} else {// other regard as create
Debug.logVerbose("[JdonFramework]-->action value not supported, enter create process2 ", module);
modelForm.setAction(ModelForm.CREATE_STR);
createViewPage.doCreate(actionMapping, modelForm, request);
}
Debug.logVerbose("[JdonFramework]--> push the jsp that forward name is '" + modelForm.getAction() + "'", module);
return actionMapping.findForward(modelForm.getAction());
} | java | public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Debug.logVerbose("[JdonFramework]--> enter ModelViewAction process ", module);
intContext(this.getServlet().getServletContext());
ModelForm modelForm = FormBeanUtil.getModelForm(actionMapping, actionForm, request);
if ((UtilValidate.isEmpty(modelForm.getAction())) || modelForm.getAction().equalsIgnoreCase(ModelForm.CREATE_STR)) {
Debug.logVerbose("[JdonFramework]--> enter create process ", module);
modelForm.setAction(ModelForm.CREATE_STR);
createViewPage.doCreate(actionMapping, modelForm, request);
} else if (modelForm.getAction().equalsIgnoreCase(ModelForm.EDIT_STR)) {
Debug.logVerbose("[JdonFramework]--> enter " + ModelForm.EDIT_STR + " process ", module);
Object model = editeViewPage.getModelForEdit(actionMapping, modelForm, request, this.servlet.getServletContext());
if (model == null) // not found the model
return errorsForward(modelForm.getAction(), actionMapping, request);
} else if (modelForm.getAction().equalsIgnoreCase(ModelForm.VIEW_STR)) {
Debug.logVerbose("[JdonFramework]--> enter " + ModelForm.VIEW_STR + " process ", module);
Object model = editeViewPage.getModelForEdit(actionMapping, modelForm, request, this.servlet.getServletContext());
if (model == null) // not found the model
return errorsForward(modelForm.getAction(), actionMapping, request);
} else {// other regard as create
Debug.logVerbose("[JdonFramework]-->action value not supported, enter create process2 ", module);
modelForm.setAction(ModelForm.CREATE_STR);
createViewPage.doCreate(actionMapping, modelForm, request);
}
Debug.logVerbose("[JdonFramework]--> push the jsp that forward name is '" + modelForm.getAction() + "'", module);
return actionMapping.findForward(modelForm.getAction());
} | [
"public",
"ActionForward",
"execute",
"(",
"ActionMapping",
"actionMapping",
",",
"ActionForm",
"actionForm",
",",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"Exception",
"{",
"Debug",
".",
"logVerbose",
"(",
"\"[JdonFramewor... | accept the form submit, action parameter must be : create or edit; if
not, will directly forward the jsp page mapping for the action value; | [
"accept",
"the",
"form",
"submit",
"action",
"parameter",
"must",
"be",
":",
"create",
"or",
"edit",
";",
"if",
"not",
"will",
"directly",
"forward",
"the",
"jsp",
"page",
"mapping",
"for",
"the",
"action",
"value",
";"
] | train | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/JdonAccessory/jdon-struts1x/src/main/java/com/jdon/strutsutil/ModelViewAction.java#L65-L98 |
michael-rapp/AndroidUtil | library/src/main/java/de/mrapp/android/util/logging/Logger.java | Logger.logError | public final void logError(@NonNull final Class<?> tag, @NonNull final String message) {
Condition.INSTANCE.ensureNotNull(tag, "The tag may not be null");
Condition.INSTANCE.ensureNotNull(message, "The message may not be null");
Condition.INSTANCE.ensureNotEmpty(message, "The message may not be empty");
if (LogLevel.ERROR.getRank() >= getLogLevel().getRank()) {
Log.e(ClassUtil.INSTANCE.getTruncatedName(tag), message);
}
} | java | public final void logError(@NonNull final Class<?> tag, @NonNull final String message) {
Condition.INSTANCE.ensureNotNull(tag, "The tag may not be null");
Condition.INSTANCE.ensureNotNull(message, "The message may not be null");
Condition.INSTANCE.ensureNotEmpty(message, "The message may not be empty");
if (LogLevel.ERROR.getRank() >= getLogLevel().getRank()) {
Log.e(ClassUtil.INSTANCE.getTruncatedName(tag), message);
}
} | [
"public",
"final",
"void",
"logError",
"(",
"@",
"NonNull",
"final",
"Class",
"<",
"?",
">",
"tag",
",",
"@",
"NonNull",
"final",
"String",
"message",
")",
"{",
"Condition",
".",
"INSTANCE",
".",
"ensureNotNull",
"(",
"tag",
",",
"\"The tag may not be null\"... | Logs a specific message on the log level ERROR.
@param tag
The tag, which identifies the source of the log message, as an instance of the class
{@link Class}. The tag may not be null
@param message
The message, which should be logged, as a {@link String}. The message may neither be
null, nor empty | [
"Logs",
"a",
"specific",
"message",
"on",
"the",
"log",
"level",
"ERROR",
"."
] | train | https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/logging/Logger.java#L262-L270 |
ckpoint/CheckPoint | src/main/java/hsim/checkpoint/core/repository/index/util/ValidationIndexUtil.java | ValidationIndexUtil.removeIndexData | public static void removeIndexData(ValidationData data, ValidationDataIndex index) {
String key = index.getKey(data);
List<ValidationData> datas = index.get(key);
if (!datas.isEmpty()) {
datas = datas.stream().filter(d -> !d.getId().equals(data.getId())).collect(Collectors.toList());
}
if (datas.isEmpty()) {
index.getMap().remove(key);
} else {
index.getMap().put(key, datas);
}
} | java | public static void removeIndexData(ValidationData data, ValidationDataIndex index) {
String key = index.getKey(data);
List<ValidationData> datas = index.get(key);
if (!datas.isEmpty()) {
datas = datas.stream().filter(d -> !d.getId().equals(data.getId())).collect(Collectors.toList());
}
if (datas.isEmpty()) {
index.getMap().remove(key);
} else {
index.getMap().put(key, datas);
}
} | [
"public",
"static",
"void",
"removeIndexData",
"(",
"ValidationData",
"data",
",",
"ValidationDataIndex",
"index",
")",
"{",
"String",
"key",
"=",
"index",
".",
"getKey",
"(",
"data",
")",
";",
"List",
"<",
"ValidationData",
">",
"datas",
"=",
"index",
".",
... | Remove index data.
@param data the data
@param index the index | [
"Remove",
"index",
"data",
"."
] | train | https://github.com/ckpoint/CheckPoint/blob/2c2b1a87a88485d49ea6afa34acdf16ef4134f19/src/main/java/hsim/checkpoint/core/repository/index/util/ValidationIndexUtil.java#L37-L50 |
IBM/ibm-cos-sdk-java | ibm-cos-java-sdk-s3/src/main/java/com/ibm/cloud/objectstorage/services/s3/transfer/internal/UploadCallable.java | UploadCallable.initiateMultipartUpload | private String initiateMultipartUpload(PutObjectRequest origReq, boolean isUsingEncryption) {
InitiateMultipartUploadRequest req = null;
if (isUsingEncryption && origReq instanceof EncryptedPutObjectRequest) {
req = new EncryptedInitiateMultipartUploadRequest(
origReq.getBucketName(), origReq.getKey()).withCannedACL(
origReq.getCannedAcl()).withObjectMetadata(origReq.getMetadata());
((EncryptedInitiateMultipartUploadRequest) req)
.setMaterialsDescription(((EncryptedPutObjectRequest) origReq).getMaterialsDescription());
} else {
req = new InitiateMultipartUploadRequest(origReq.getBucketName(), origReq.getKey())
.withCannedACL(origReq.getCannedAcl())
.withObjectMetadata(origReq.getMetadata());
}
TransferManager.appendMultipartUserAgent(req);
req.withAccessControlList(origReq.getAccessControlList())
.withRequesterPays(origReq.isRequesterPays())
.withStorageClass(origReq.getStorageClass())
.withRedirectLocation(origReq.getRedirectLocation())
.withSSECustomerKey(origReq.getSSECustomerKey())
.withSSEAwsKeyManagementParams(origReq.getSSEAwsKeyManagementParams())
.withGeneralProgressListener(origReq.getGeneralProgressListener())
.withRequestMetricCollector(origReq.getRequestMetricCollector())
;
String uploadId = s3.initiateMultipartUpload(req).getUploadId();
log.debug("Initiated new multipart upload: " + uploadId);
return uploadId;
} | java | private String initiateMultipartUpload(PutObjectRequest origReq, boolean isUsingEncryption) {
InitiateMultipartUploadRequest req = null;
if (isUsingEncryption && origReq instanceof EncryptedPutObjectRequest) {
req = new EncryptedInitiateMultipartUploadRequest(
origReq.getBucketName(), origReq.getKey()).withCannedACL(
origReq.getCannedAcl()).withObjectMetadata(origReq.getMetadata());
((EncryptedInitiateMultipartUploadRequest) req)
.setMaterialsDescription(((EncryptedPutObjectRequest) origReq).getMaterialsDescription());
} else {
req = new InitiateMultipartUploadRequest(origReq.getBucketName(), origReq.getKey())
.withCannedACL(origReq.getCannedAcl())
.withObjectMetadata(origReq.getMetadata());
}
TransferManager.appendMultipartUserAgent(req);
req.withAccessControlList(origReq.getAccessControlList())
.withRequesterPays(origReq.isRequesterPays())
.withStorageClass(origReq.getStorageClass())
.withRedirectLocation(origReq.getRedirectLocation())
.withSSECustomerKey(origReq.getSSECustomerKey())
.withSSEAwsKeyManagementParams(origReq.getSSEAwsKeyManagementParams())
.withGeneralProgressListener(origReq.getGeneralProgressListener())
.withRequestMetricCollector(origReq.getRequestMetricCollector())
;
String uploadId = s3.initiateMultipartUpload(req).getUploadId();
log.debug("Initiated new multipart upload: " + uploadId);
return uploadId;
} | [
"private",
"String",
"initiateMultipartUpload",
"(",
"PutObjectRequest",
"origReq",
",",
"boolean",
"isUsingEncryption",
")",
"{",
"InitiateMultipartUploadRequest",
"req",
"=",
"null",
";",
"if",
"(",
"isUsingEncryption",
"&&",
"origReq",
"instanceof",
"EncryptedPutObject... | Initiates a multipart upload and returns the upload id
@param isUsingEncryption | [
"Initiates",
"a",
"multipart",
"upload",
"and",
"returns",
"the",
"upload",
"id"
] | train | https://github.com/IBM/ibm-cos-sdk-java/blob/d0bb2dd754c328a05e7dba8dc42e28b271b6daf2/ibm-cos-java-sdk-s3/src/main/java/com/ibm/cloud/objectstorage/services/s3/transfer/internal/UploadCallable.java#L331-L362 |
wisdom-framework/wisdom | core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/WatcherUtils.java | WatcherUtils.hasExtension | public static boolean hasExtension(File file, String... extensions) {
String extension = FilenameUtils.getExtension(file.getName());
for (String s : extensions) {
if (extension.equalsIgnoreCase(s) || ("." + extension).equalsIgnoreCase(s)) {
return true;
}
}
return false;
} | java | public static boolean hasExtension(File file, String... extensions) {
String extension = FilenameUtils.getExtension(file.getName());
for (String s : extensions) {
if (extension.equalsIgnoreCase(s) || ("." + extension).equalsIgnoreCase(s)) {
return true;
}
}
return false;
} | [
"public",
"static",
"boolean",
"hasExtension",
"(",
"File",
"file",
",",
"String",
"...",
"extensions",
")",
"{",
"String",
"extension",
"=",
"FilenameUtils",
".",
"getExtension",
"(",
"file",
".",
"getName",
"(",
")",
")",
";",
"for",
"(",
"String",
"s",
... | Checks whether the given file has one of the given extension.
@param file the file
@param extensions the extensions
@return {@literal true} if the file has one of the given extension, {@literal false} otherwise | [
"Checks",
"whether",
"the",
"given",
"file",
"has",
"one",
"of",
"the",
"given",
"extension",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/WatcherUtils.java#L159-L167 |
LableOrg/java-uniqueid | uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/SynchronizedUniqueIDGeneratorFactory.java | SynchronizedUniqueIDGeneratorFactory.generatorFor | public static synchronized IDGenerator generatorFor(SynchronizedGeneratorIdentity synchronizedGeneratorIdentity,
Mode mode)
throws IOException {
String instanceKey = synchronizedGeneratorIdentity.getZNode();
if (!instances.containsKey(instanceKey)) {
logger.debug("Creating new instance.");
instances.putIfAbsent(instanceKey, new BaseUniqueIDGenerator(synchronizedGeneratorIdentity, mode));
}
return instances.get(instanceKey);
} | java | public static synchronized IDGenerator generatorFor(SynchronizedGeneratorIdentity synchronizedGeneratorIdentity,
Mode mode)
throws IOException {
String instanceKey = synchronizedGeneratorIdentity.getZNode();
if (!instances.containsKey(instanceKey)) {
logger.debug("Creating new instance.");
instances.putIfAbsent(instanceKey, new BaseUniqueIDGenerator(synchronizedGeneratorIdentity, mode));
}
return instances.get(instanceKey);
} | [
"public",
"static",
"synchronized",
"IDGenerator",
"generatorFor",
"(",
"SynchronizedGeneratorIdentity",
"synchronizedGeneratorIdentity",
",",
"Mode",
"mode",
")",
"throws",
"IOException",
"{",
"String",
"instanceKey",
"=",
"synchronizedGeneratorIdentity",
".",
"getZNode",
... | Get the synchronized ID generator instance.
@param synchronizedGeneratorIdentity An instance of {@link SynchronizedGeneratorIdentity} to (re)use for
acquiring the generator ID.
@param mode Generator mode.
@return An instance of this class.
@throws IOException Thrown when something went wrong trying to find the cluster ID or trying to claim a
generator ID. | [
"Get",
"the",
"synchronized",
"ID",
"generator",
"instance",
"."
] | train | https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/SynchronizedUniqueIDGeneratorFactory.java#L78-L88 |
bbossgroups/bboss-elasticsearch | bboss-elasticsearch/src/main/java/org/frameworkset/elasticsearch/AbstractElasticSearchIndexRequestBuilderFactory.java | AbstractElasticSearchIndexRequestBuilderFactory.getIndexName | protected String getIndexName(String indexPrefix, long timestamp) {
return new StringBuilder(indexPrefix).append('-')
.append(fastDateFormat.format(timestamp)).toString();
} | java | protected String getIndexName(String indexPrefix, long timestamp) {
return new StringBuilder(indexPrefix).append('-')
.append(fastDateFormat.format(timestamp)).toString();
} | [
"protected",
"String",
"getIndexName",
"(",
"String",
"indexPrefix",
",",
"long",
"timestamp",
")",
"{",
"return",
"new",
"StringBuilder",
"(",
"indexPrefix",
")",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"fastDateFormat",
".",
"format",
"(",
... | Gets the name of the index to use for an index request
@param indexPrefix
Prefix of index name to use -- as configured on the sink
@param timestamp
timestamp (millis) to format / use
@return index name of the form 'indexPrefix-formattedTimestamp' | [
"Gets",
"the",
"name",
"of",
"the",
"index",
"to",
"use",
"for",
"an",
"index",
"request"
] | train | https://github.com/bbossgroups/bboss-elasticsearch/blob/31717c8aa2c4c880987be53aeeb8a0cf5183c3a7/bboss-elasticsearch/src/main/java/org/frameworkset/elasticsearch/AbstractElasticSearchIndexRequestBuilderFactory.java#L95-L98 |
ironjacamar/ironjacamar | codegenerator/src/main/java/org/ironjacamar/codegenerator/code/ActivationCodeGen.java | ActivationCodeGen.writeGetAs | private void writeGetAs(Definition def, Writer out, int indent) throws IOException
{
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Get activation spec class\n");
writeWithIndent(out, indent, " * @return Activation spec\n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent, "public " + def.getAsClass() + " getActivationSpec()");
writeLeftCurlyBracket(out, indent);
writeWithIndent(out, indent + 1, "return spec;");
writeRightCurlyBracket(out, indent);
writeEol(out);
} | java | private void writeGetAs(Definition def, Writer out, int indent) throws IOException
{
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Get activation spec class\n");
writeWithIndent(out, indent, " * @return Activation spec\n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent, "public " + def.getAsClass() + " getActivationSpec()");
writeLeftCurlyBracket(out, indent);
writeWithIndent(out, indent + 1, "return spec;");
writeRightCurlyBracket(out, indent);
writeEol(out);
} | [
"private",
"void",
"writeGetAs",
"(",
"Definition",
"def",
",",
"Writer",
"out",
",",
"int",
"indent",
")",
"throws",
"IOException",
"{",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"/**\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",... | Output get activation spec method
@param def definition
@param out Writer
@param indent space number
@throws IOException ioException | [
"Output",
"get",
"activation",
"spec",
"method"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/ActivationCodeGen.java#L136-L149 |
NoraUi/NoraUi | src/main/java/com/github/noraui/application/steps/CommonSteps.java | CommonSteps.updateDate | @Conditioned
@Quand("Je mets à jour la date '(.*)-(.*)' avec une '(.*)' date '(.*)'[\\.|\\?]")
@When("I update date '(.*)-(.*)' with a '(.*)' date '(.*)'[\\.|\\?]")
public void updateDate(String page, String elementName, String dateType, String dateOrKey, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException {
final String date = Context.getValue(dateOrKey) != null ? Context.getValue(dateOrKey) : dateOrKey;
if (!"".equals(date)) {
final PageElement pageElement = Page.getInstance(page).getPageElementByKey('-' + elementName);
if (date.matches(Constants.DATE_FORMAT_REG_EXP)) {
updateDateValidated(pageElement, dateType, date);
} else {
new Result.Failure<>(date, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_WRONG_DATE_FORMAT), date, elementName), false, pageElement.getPage().getCallBack());
}
}
} | java | @Conditioned
@Quand("Je mets à jour la date '(.*)-(.*)' avec une '(.*)' date '(.*)'[\\.|\\?]")
@When("I update date '(.*)-(.*)' with a '(.*)' date '(.*)'[\\.|\\?]")
public void updateDate(String page, String elementName, String dateType, String dateOrKey, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException {
final String date = Context.getValue(dateOrKey) != null ? Context.getValue(dateOrKey) : dateOrKey;
if (!"".equals(date)) {
final PageElement pageElement = Page.getInstance(page).getPageElementByKey('-' + elementName);
if (date.matches(Constants.DATE_FORMAT_REG_EXP)) {
updateDateValidated(pageElement, dateType, date);
} else {
new Result.Failure<>(date, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_WRONG_DATE_FORMAT), date, elementName), false, pageElement.getPage().getCallBack());
}
}
} | [
"@",
"Conditioned",
"@",
"Quand",
"(",
"\"Je mets à jour la date '(.*)-(.*)' avec une '(.*)' date '(.*)'[\\\\.|\\\\?]\")",
"\r",
"@",
"When",
"(",
"\"I update date '(.*)-(.*)' with a '(.*)' date '(.*)'[\\\\.|\\\\?]\"",
")",
"public",
"void",
"updateDate",
"(",
"String",
"page",
"... | Update a html input text with a date.
@param page
The concerned page of elementName
@param elementName
is target element
@param dateOrKey
Is the new date (date or date in context (after a save))
@param dateType
'future', 'future_strict', 'today' or 'any'
@param conditions
list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
@throws TechnicalException
is throws if you have a technical error (format, configuration, datas, ...) in NoraUi.
Exception with a message (no screenshot, no exception)
@throws FailureException
if the scenario encounters a functional error | [
"Update",
"a",
"html",
"input",
"text",
"with",
"a",
"date",
"."
] | train | https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/CommonSteps.java#L526-L539 |
salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/util/Option.java | Option.findOption | public static Option findOption(String name, Option[] options) {
for (int i = 0; i < options.length; i++) {
if (options[i].getName().equals(name)) {
return options[i];
}
}
return null;
} | java | public static Option findOption(String name, Option[] options) {
for (int i = 0; i < options.length; i++) {
if (options[i].getName().equals(name)) {
return options[i];
}
}
return null;
} | [
"public",
"static",
"Option",
"findOption",
"(",
"String",
"name",
",",
"Option",
"[",
"]",
"options",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"options",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"options",
"[",
"i",
... | Returns an option with the given name.
@param name The option name to search for
@param options The list of options to search through
@return The named option from the list or null if it doesn't exist | [
"Returns",
"an",
"option",
"with",
"the",
"given",
"name",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/util/Option.java#L170-L177 |
alipay/sofa-rpc | core-impl/client/src/main/java/com/alipay/sofa/rpc/client/AllConnectConnectionHolder.java | AllConnectConnectionHolder.printFailure | protected void printFailure(String interfaceId, ProviderInfo providerInfo, ClientTransport transport) {
if (LOGGER.isInfoEnabled(consumerConfig.getAppName())) {
LOGGER.infoWithApp(consumerConfig.getAppName(), "Connect to {} provider:{} failure !", interfaceId,
providerInfo);
}
} | java | protected void printFailure(String interfaceId, ProviderInfo providerInfo, ClientTransport transport) {
if (LOGGER.isInfoEnabled(consumerConfig.getAppName())) {
LOGGER.infoWithApp(consumerConfig.getAppName(), "Connect to {} provider:{} failure !", interfaceId,
providerInfo);
}
} | [
"protected",
"void",
"printFailure",
"(",
"String",
"interfaceId",
",",
"ProviderInfo",
"providerInfo",
",",
"ClientTransport",
"transport",
")",
"{",
"if",
"(",
"LOGGER",
".",
"isInfoEnabled",
"(",
"consumerConfig",
".",
"getAppName",
"(",
")",
")",
")",
"{",
... | 打印连接失败日志
@param interfaceId 接口名称
@param providerInfo 服务端
@param transport 连接 | [
"打印连接失败日志"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core-impl/client/src/main/java/com/alipay/sofa/rpc/client/AllConnectConnectionHolder.java#L711-L716 |
radkovo/SwingBox | src/main/java/org/fit/cssbox/swingbox/view/DelegateView.java | DelegateView.preferenceChanged | @Override
public void preferenceChanged(View child, boolean width, boolean height)
{
if (parent != null)
{
parent.preferenceChanged(child, width, height);
}
} | java | @Override
public void preferenceChanged(View child, boolean width, boolean height)
{
if (parent != null)
{
parent.preferenceChanged(child, width, height);
}
} | [
"@",
"Override",
"public",
"void",
"preferenceChanged",
"(",
"View",
"child",
",",
"boolean",
"width",
",",
"boolean",
"height",
")",
"{",
"if",
"(",
"parent",
"!=",
"null",
")",
"{",
"parent",
".",
"preferenceChanged",
"(",
"child",
",",
"width",
",",
"... | Specifies that a preference has changed. Child views can call this on the
parent to indicate that the preference has changed. The root view routes
this to invalidate on the hosting component.
<p>
This can be called on a different thread from the event dispatching
thread and is basically unsafe to propagate into the component. To make
this safe, the operation is transferred over to the event dispatching
thread for completion. It is a design goal that all view methods be safe
to call without concern for concurrency, and this behavior helps make
that true.
@param child
the child view
@param width
true if the width preference has changed
@param height
true if the height preference has changed | [
"Specifies",
"that",
"a",
"preference",
"has",
"changed",
".",
"Child",
"views",
"can",
"call",
"this",
"on",
"the",
"parent",
"to",
"indicate",
"that",
"the",
"preference",
"has",
"changed",
".",
"The",
"root",
"view",
"routes",
"this",
"to",
"invalidate",
... | train | https://github.com/radkovo/SwingBox/blob/ff370f3dc54d248e4c8852c17513618c83c25984/src/main/java/org/fit/cssbox/swingbox/view/DelegateView.java#L246-L253 |
leancloud/java-sdk-all | core/src/main/java/cn/leancloud/AVObject.java | AVObject.createWithoutData | public static AVObject createWithoutData(String className, String objectId) {
AVObject object = new AVObject(className);
object.setObjectId(objectId);
return object;
} | java | public static AVObject createWithoutData(String className, String objectId) {
AVObject object = new AVObject(className);
object.setObjectId(objectId);
return object;
} | [
"public",
"static",
"AVObject",
"createWithoutData",
"(",
"String",
"className",
",",
"String",
"objectId",
")",
"{",
"AVObject",
"object",
"=",
"new",
"AVObject",
"(",
"className",
")",
";",
"object",
".",
"setObjectId",
"(",
"objectId",
")",
";",
"return",
... | create a new instance with particular classname and objectId.
@param className class name
@param objectId object id
@return | [
"create",
"a",
"new",
"instance",
"with",
"particular",
"classname",
"and",
"objectId",
"."
] | train | https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/core/src/main/java/cn/leancloud/AVObject.java#L1006-L1010 |
kiegroup/jbpm | jbpm-query-jpa/src/main/java/org/jbpm/query/jpa/impl/QueryCriteriaUtil.java | QueryCriteriaUtil.createPredicateFromIntersectingCriteriaList | private <R,T> Predicate createPredicateFromIntersectingCriteriaList(CriteriaQuery<R> query, CriteriaBuilder builder, Class<T> queryType, List<QueryCriteria> intersectingCriteriaList, QueryWhere queryWhere ) {
combineIntersectingRangeCriteria(intersectingCriteriaList);
assert intersectingCriteriaList.size() > 0 : "Empty list of currently intersecting criteria!";
Predicate [] intersectingPredicates = new Predicate[intersectingCriteriaList.size()];
int i = 0;
for( QueryCriteria intersectingCriteria : intersectingCriteriaList ) {
Predicate predicate = createPredicateFromSingleOrGroupCriteria(query, builder, queryType, intersectingCriteria, queryWhere );
assert predicate != null : "Null predicate when evaluating individual intersecting criteria [" + intersectingCriteria.toString() + "]";
intersectingPredicates[i++] = predicate;
}
Predicate predicate;
if( intersectingPredicates.length > 1 ) {
predicate = builder.and(intersectingPredicates);
} else {
predicate = intersectingPredicates[0];
}
return predicate;
} | java | private <R,T> Predicate createPredicateFromIntersectingCriteriaList(CriteriaQuery<R> query, CriteriaBuilder builder, Class<T> queryType, List<QueryCriteria> intersectingCriteriaList, QueryWhere queryWhere ) {
combineIntersectingRangeCriteria(intersectingCriteriaList);
assert intersectingCriteriaList.size() > 0 : "Empty list of currently intersecting criteria!";
Predicate [] intersectingPredicates = new Predicate[intersectingCriteriaList.size()];
int i = 0;
for( QueryCriteria intersectingCriteria : intersectingCriteriaList ) {
Predicate predicate = createPredicateFromSingleOrGroupCriteria(query, builder, queryType, intersectingCriteria, queryWhere );
assert predicate != null : "Null predicate when evaluating individual intersecting criteria [" + intersectingCriteria.toString() + "]";
intersectingPredicates[i++] = predicate;
}
Predicate predicate;
if( intersectingPredicates.length > 1 ) {
predicate = builder.and(intersectingPredicates);
} else {
predicate = intersectingPredicates[0];
}
return predicate;
} | [
"private",
"<",
"R",
",",
"T",
">",
"Predicate",
"createPredicateFromIntersectingCriteriaList",
"(",
"CriteriaQuery",
"<",
"R",
">",
"query",
",",
"CriteriaBuilder",
"builder",
",",
"Class",
"<",
"T",
">",
"queryType",
",",
"List",
"<",
"QueryCriteria",
">",
"... | This method is necessary because the AND operator in SQL has precedence over the OR operator.
</p>
That means that intersecting criteria should always be grouped together (and processed first, basically), which is essentially
what this method does.
@param query The {@link CriteriaQuery} that is being built
@param intersectingCriteriaList The list of intersecting (ANDed) {@link QueryCriteria}
@param builder The {@link CriteriaBuilder} builder instance
@param queryType The (persistent {@link Entity}) {@link Class} that we are querying on
@return A {@link Predicate} created on the basis of the given {@link List} of {@link QueryCriteria} | [
"This",
"method",
"is",
"necessary",
"because",
"the",
"AND",
"operator",
"in",
"SQL",
"has",
"precedence",
"over",
"the",
"OR",
"operator",
".",
"<",
"/",
"p",
">",
"That",
"means",
"that",
"intersecting",
"criteria",
"should",
"always",
"be",
"grouped",
... | train | https://github.com/kiegroup/jbpm/blob/c3473c728aa382ebbea01e380c5e754a96647b82/jbpm-query-jpa/src/main/java/org/jbpm/query/jpa/impl/QueryCriteriaUtil.java#L289-L308 |
Azure/azure-sdk-for-java | labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/EnvironmentSettingsInner.java | EnvironmentSettingsInner.claimAnyAsync | public Observable<Void> claimAnyAsync(String resourceGroupName, String labAccountName, String labName, String environmentSettingName) {
return claimAnyWithServiceResponseAsync(resourceGroupName, labAccountName, labName, environmentSettingName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> claimAnyAsync(String resourceGroupName, String labAccountName, String labName, String environmentSettingName) {
return claimAnyWithServiceResponseAsync(resourceGroupName, labAccountName, labName, environmentSettingName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"claimAnyAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"labAccountName",
",",
"String",
"labName",
",",
"String",
"environmentSettingName",
")",
"{",
"return",
"claimAnyWithServiceResponseAsync",
"(",
"resourceGroup... | Claims a random environment for a user in an environment settings.
@param resourceGroupName The name of the resource group.
@param labAccountName The name of the lab Account.
@param labName The name of the lab.
@param environmentSettingName The name of the environment Setting.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful. | [
"Claims",
"a",
"random",
"environment",
"for",
"a",
"user",
"in",
"an",
"environment",
"settings",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/EnvironmentSettingsInner.java#L1133-L1140 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/query/Criteria.java | Criteria.addOrderBy | public void addOrderBy(String fieldName, boolean sortAscending)
{
if (fieldName != null)
{
_getOrderby().add(new FieldHelper(fieldName, sortAscending));
}
} | java | public void addOrderBy(String fieldName, boolean sortAscending)
{
if (fieldName != null)
{
_getOrderby().add(new FieldHelper(fieldName, sortAscending));
}
} | [
"public",
"void",
"addOrderBy",
"(",
"String",
"fieldName",
",",
"boolean",
"sortAscending",
")",
"{",
"if",
"(",
"fieldName",
"!=",
"null",
")",
"{",
"_getOrderby",
"(",
")",
".",
"add",
"(",
"new",
"FieldHelper",
"(",
"fieldName",
",",
"sortAscending",
"... | Adds a field for orderBy
@param fieldName the field name to be used
@param sortAscending true for ASCENDING, false for DESCENDING
@deprecated use QueryByCriteria#addOrderBy | [
"Adds",
"a",
"field",
"for",
"orderBy"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/Criteria.java#L572-L578 |
prestodb/presto | presto-hive/src/main/java/com/facebook/presto/hive/metastore/SemiTransactionalHiveMetastore.java | SemiTransactionalHiveMetastore.recursiveDeleteFiles | private static RecursiveDeleteResult recursiveDeleteFiles(HdfsEnvironment hdfsEnvironment, HdfsContext context, Path directory, List<String> filePrefixes, boolean deleteEmptyDirectories)
{
FileSystem fileSystem;
try {
fileSystem = hdfsEnvironment.getFileSystem(context, directory);
if (!fileSystem.exists(directory)) {
return new RecursiveDeleteResult(true, ImmutableList.of());
}
}
catch (IOException e) {
ImmutableList.Builder<String> notDeletedItems = ImmutableList.builder();
notDeletedItems.add(directory.toString() + "/**");
return new RecursiveDeleteResult(false, notDeletedItems.build());
}
return doRecursiveDeleteFiles(fileSystem, directory, filePrefixes, deleteEmptyDirectories);
} | java | private static RecursiveDeleteResult recursiveDeleteFiles(HdfsEnvironment hdfsEnvironment, HdfsContext context, Path directory, List<String> filePrefixes, boolean deleteEmptyDirectories)
{
FileSystem fileSystem;
try {
fileSystem = hdfsEnvironment.getFileSystem(context, directory);
if (!fileSystem.exists(directory)) {
return new RecursiveDeleteResult(true, ImmutableList.of());
}
}
catch (IOException e) {
ImmutableList.Builder<String> notDeletedItems = ImmutableList.builder();
notDeletedItems.add(directory.toString() + "/**");
return new RecursiveDeleteResult(false, notDeletedItems.build());
}
return doRecursiveDeleteFiles(fileSystem, directory, filePrefixes, deleteEmptyDirectories);
} | [
"private",
"static",
"RecursiveDeleteResult",
"recursiveDeleteFiles",
"(",
"HdfsEnvironment",
"hdfsEnvironment",
",",
"HdfsContext",
"context",
",",
"Path",
"directory",
",",
"List",
"<",
"String",
">",
"filePrefixes",
",",
"boolean",
"deleteEmptyDirectories",
")",
"{",... | Attempt to recursively remove eligible files and/or directories in {@code directory}.
<p>
When {@code filePrefixes} is not present, all files (but not necessarily directories) will be
ineligible. If all files shall be deleted, you can use an empty string as {@code filePrefixes}.
<p>
When {@code deleteEmptySubDirectory} is true, any empty directory (including directories that
were originally empty, and directories that become empty after files prefixed with
{@code filePrefixes} are deleted) will be eligible.
<p>
This method will not delete anything that's neither a directory nor a file.
@param filePrefixes prefix of files that should be deleted
@param deleteEmptyDirectories whether empty directories should be deleted | [
"Attempt",
"to",
"recursively",
"remove",
"eligible",
"files",
"and",
"/",
"or",
"directories",
"in",
"{",
"@code",
"directory",
"}",
".",
"<p",
">",
"When",
"{",
"@code",
"filePrefixes",
"}",
"is",
"not",
"present",
"all",
"files",
"(",
"but",
"not",
"n... | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-hive/src/main/java/com/facebook/presto/hive/metastore/SemiTransactionalHiveMetastore.java#L1749-L1766 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/BaseTraceFormatter.java | BaseTraceFormatter.formatMessage | @Override
public String formatMessage(LogRecord logRecord) {
if (System.getSecurityManager() == null) {
return formatMessage(logRecord, logRecord.getParameters(), true);
} else {
final LogRecord f_logRecord = logRecord;
return AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
return formatMessage(f_logRecord, f_logRecord.getParameters(), true);
}
});
}
} | java | @Override
public String formatMessage(LogRecord logRecord) {
if (System.getSecurityManager() == null) {
return formatMessage(logRecord, logRecord.getParameters(), true);
} else {
final LogRecord f_logRecord = logRecord;
return AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
return formatMessage(f_logRecord, f_logRecord.getParameters(), true);
}
});
}
} | [
"@",
"Override",
"public",
"String",
"formatMessage",
"(",
"LogRecord",
"logRecord",
")",
"{",
"if",
"(",
"System",
".",
"getSecurityManager",
"(",
")",
"==",
"null",
")",
"{",
"return",
"formatMessage",
"(",
"logRecord",
",",
"logRecord",
".",
"getParameters"... | {@inheritDoc} <br />
We override this method because in some JVMs, it is synchronized (why on earth?!?!). | [
"{"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/BaseTraceFormatter.java#L222-L236 |
jasminb/jsonapi-converter | src/main/java/com/github/jasminb/jsonapi/ResourceConverter.java | ResourceConverter.parseRelationship | private Object parseRelationship(JsonNode relationshipDataNode, Class<?> type)
throws IOException, IllegalAccessException, InstantiationException {
if (ValidationUtils.isRelationshipParsable(relationshipDataNode)) {
String identifier = createIdentifier(relationshipDataNode);
if (resourceCache.contains(identifier)) {
return resourceCache.get(identifier);
} else {
// Never cache relationship objects
resourceCache.lock();
try {
return readObject(relationshipDataNode, type, true);
} finally {
resourceCache.unlock();
}
}
}
return null;
} | java | private Object parseRelationship(JsonNode relationshipDataNode, Class<?> type)
throws IOException, IllegalAccessException, InstantiationException {
if (ValidationUtils.isRelationshipParsable(relationshipDataNode)) {
String identifier = createIdentifier(relationshipDataNode);
if (resourceCache.contains(identifier)) {
return resourceCache.get(identifier);
} else {
// Never cache relationship objects
resourceCache.lock();
try {
return readObject(relationshipDataNode, type, true);
} finally {
resourceCache.unlock();
}
}
}
return null;
} | [
"private",
"Object",
"parseRelationship",
"(",
"JsonNode",
"relationshipDataNode",
",",
"Class",
"<",
"?",
">",
"type",
")",
"throws",
"IOException",
",",
"IllegalAccessException",
",",
"InstantiationException",
"{",
"if",
"(",
"ValidationUtils",
".",
"isRelationshipP... | Creates relationship object by consuming provided 'data' node.
@param relationshipDataNode relationship data node
@param type object type
@return created object or <code>null</code> in case data node is not valid
@throws IOException
@throws IllegalAccessException
@throws InstantiationException | [
"Creates",
"relationship",
"object",
"by",
"consuming",
"provided",
"data",
"node",
"."
] | train | https://github.com/jasminb/jsonapi-converter/blob/73b41c3b9274e70e62b3425071ca8afdc7bddaf6/src/main/java/com/github/jasminb/jsonapi/ResourceConverter.java#L576-L595 |
Netflix/conductor | client/src/main/java/com/netflix/conductor/client/http/WorkflowClient.java | WorkflowClient.terminateWorkflow | public void terminateWorkflow(String workflowId, String reason) {
Preconditions.checkArgument(StringUtils.isNotBlank(workflowId), "workflow id cannot be blank");
delete(new Object[]{"reason", reason}, "workflow/{workflowId}", workflowId);
} | java | public void terminateWorkflow(String workflowId, String reason) {
Preconditions.checkArgument(StringUtils.isNotBlank(workflowId), "workflow id cannot be blank");
delete(new Object[]{"reason", reason}, "workflow/{workflowId}", workflowId);
} | [
"public",
"void",
"terminateWorkflow",
"(",
"String",
"workflowId",
",",
"String",
"reason",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"workflowId",
")",
",",
"\"workflow id cannot be blank\"",
")",
";",
"delete",
... | Terminates the execution of the given workflow instance
@param workflowId the id of the workflow to be terminated
@param reason the reason to be logged and displayed | [
"Terminates",
"the",
"execution",
"of",
"the",
"given",
"workflow",
"instance"
] | train | https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/client/src/main/java/com/netflix/conductor/client/http/WorkflowClient.java#L333-L336 |
jenkinsci/jenkins | core/src/main/java/jenkins/model/Jenkins.java | Jenkins.toVersion | private static @CheckForNull VersionNumber toVersion(@CheckForNull String versionString) {
if (versionString == null) {
return null;
}
try {
return new VersionNumber(versionString);
} catch (NumberFormatException e) {
try {
// for non-released version of Jenkins, this looks like "1.345 (private-foobar), so try to approximate.
int idx = versionString.indexOf(' ');
if (idx > 0) {
return new VersionNumber(versionString.substring(0,idx));
}
} catch (NumberFormatException ignored) {
// fall through
}
// totally unparseable
return null;
} catch (IllegalArgumentException e) {
// totally unparseable
return null;
}
} | java | private static @CheckForNull VersionNumber toVersion(@CheckForNull String versionString) {
if (versionString == null) {
return null;
}
try {
return new VersionNumber(versionString);
} catch (NumberFormatException e) {
try {
// for non-released version of Jenkins, this looks like "1.345 (private-foobar), so try to approximate.
int idx = versionString.indexOf(' ');
if (idx > 0) {
return new VersionNumber(versionString.substring(0,idx));
}
} catch (NumberFormatException ignored) {
// fall through
}
// totally unparseable
return null;
} catch (IllegalArgumentException e) {
// totally unparseable
return null;
}
} | [
"private",
"static",
"@",
"CheckForNull",
"VersionNumber",
"toVersion",
"(",
"@",
"CheckForNull",
"String",
"versionString",
")",
"{",
"if",
"(",
"versionString",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"return",
"new",
"VersionNumber",... | Parses a version string into {@link VersionNumber}, or null if it's not parseable as a version number
(such as when Jenkins is run with "mvn hudson-dev:run") | [
"Parses",
"a",
"version",
"string",
"into",
"{"
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/model/Jenkins.java#L5077-L5101 |
rometools/rome | rome-propono/src/main/java/com/rometools/propono/atom/server/impl/FileBasedCollection.java | FileBasedCollection.getFeedDocument | public Feed getFeedDocument() throws AtomException {
InputStream in = null;
synchronized (FileStore.getFileStore()) {
in = FileStore.getFileStore().getFileInputStream(getFeedPath());
if (in == null) {
in = createDefaultFeedDocument(contextURI + servletPath + "/" + handle + "/" + collection);
}
}
try {
final WireFeedInput input = new WireFeedInput();
final WireFeed wireFeed = input.build(new InputStreamReader(in, "UTF-8"));
return (Feed) wireFeed;
} catch (final Exception ex) {
throw new AtomException(ex);
}
} | java | public Feed getFeedDocument() throws AtomException {
InputStream in = null;
synchronized (FileStore.getFileStore()) {
in = FileStore.getFileStore().getFileInputStream(getFeedPath());
if (in == null) {
in = createDefaultFeedDocument(contextURI + servletPath + "/" + handle + "/" + collection);
}
}
try {
final WireFeedInput input = new WireFeedInput();
final WireFeed wireFeed = input.build(new InputStreamReader(in, "UTF-8"));
return (Feed) wireFeed;
} catch (final Exception ex) {
throw new AtomException(ex);
}
} | [
"public",
"Feed",
"getFeedDocument",
"(",
")",
"throws",
"AtomException",
"{",
"InputStream",
"in",
"=",
"null",
";",
"synchronized",
"(",
"FileStore",
".",
"getFileStore",
"(",
")",
")",
"{",
"in",
"=",
"FileStore",
".",
"getFileStore",
"(",
")",
".",
"ge... | Get feed document representing collection.
@throws com.rometools.rome.propono.atom.server.AtomException On error retrieving feed file.
@return Atom Feed representing collection. | [
"Get",
"feed",
"document",
"representing",
"collection",
"."
] | train | https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome-propono/src/main/java/com/rometools/propono/atom/server/impl/FileBasedCollection.java#L130-L145 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/TagsApi.java | TagsApi.updateRelease | public Release updateRelease(Object projectIdOrPath, String tagName, String releaseNotes) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("description", releaseNotes);
Response response = put(Response.Status.OK, formData.asMap(),
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "tags", tagName, "release");
return (response.readEntity(Release.class));
} | java | public Release updateRelease(Object projectIdOrPath, String tagName, String releaseNotes) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("description", releaseNotes);
Response response = put(Response.Status.OK, formData.asMap(),
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "tags", tagName, "release");
return (response.readEntity(Release.class));
} | [
"public",
"Release",
"updateRelease",
"(",
"Object",
"projectIdOrPath",
",",
"String",
"tagName",
",",
"String",
"releaseNotes",
")",
"throws",
"GitLabApiException",
"{",
"Form",
"formData",
"=",
"new",
"GitLabApiForm",
"(",
")",
".",
"withParam",
"(",
"\"descript... | Updates the release notes of a given release.
<pre><code>GitLab Endpoint: PUT /projects/:id/repository/tags/:tagName/release</code></pre>
@param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path
@param tagName the name of a tag
@param releaseNotes release notes with markdown support
@return a Tag instance containing info on the newly created tag
@throws GitLabApiException if any exception occurs | [
"Updates",
"the",
"release",
"notes",
"of",
"a",
"given",
"release",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/TagsApi.java#L233-L238 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.