repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 204 | func_name stringlengths 5 103 | whole_func_string stringlengths 87 3.44k | language stringclasses 1
value | func_code_string stringlengths 87 3.44k | func_code_tokens listlengths 21 714 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 482 | split_name stringclasses 1
value | func_code_url stringlengths 102 309 |
|---|---|---|---|---|---|---|---|---|---|---|
skjolber/3d-bin-container-packing | src/main/java/com/github/skjolberg/packing/Container.java | Container.getFreeLevelSpace | public Dimension getFreeLevelSpace() {
int remainder = height - getStackHeight();
if(remainder < 0) {
throw new IllegalArgumentException("Remaining free space is negative at " + remainder + " for " + this);
}
return new Dimension(width, depth, remainder);
} | java | public Dimension getFreeLevelSpace() {
int remainder = height - getStackHeight();
if(remainder < 0) {
throw new IllegalArgumentException("Remaining free space is negative at " + remainder + " for " + this);
}
return new Dimension(width, depth, remainder);
} | [
"public",
"Dimension",
"getFreeLevelSpace",
"(",
")",
"{",
"int",
"remainder",
"=",
"height",
"-",
"getStackHeight",
"(",
")",
";",
"if",
"(",
"remainder",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Remaining free space is negative at ... | Get the free level space, i.e. container height with height of
levels subtracted.
@return free height and box dimension | [
"Get",
"the",
"free",
"level",
"space",
"i",
".",
"e",
".",
"container",
"height",
"with",
"height",
"of",
"levels",
"subtracted",
"."
] | train | https://github.com/skjolber/3d-bin-container-packing/blob/9609bc7515322b2de2cad0dfb3d2f72607e71aae/src/main/java/com/github/skjolberg/packing/Container.java#L148-L154 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/Provider.java | Provider.getService | public synchronized Service getService(String type, String algorithm) {
checkInitialized();
// avoid allocating a new key object if possible
ServiceKey key = previousKey;
if (key.matches(type, algorithm) == false) {
key = new ServiceKey(type, algorithm, false);
previousKey = key;
}
if (serviceMap != null) {
Service service = serviceMap.get(key);
if (service != null) {
return service;
}
}
ensureLegacyParsed();
return (legacyMap != null) ? legacyMap.get(key) : null;
} | java | public synchronized Service getService(String type, String algorithm) {
checkInitialized();
// avoid allocating a new key object if possible
ServiceKey key = previousKey;
if (key.matches(type, algorithm) == false) {
key = new ServiceKey(type, algorithm, false);
previousKey = key;
}
if (serviceMap != null) {
Service service = serviceMap.get(key);
if (service != null) {
return service;
}
}
ensureLegacyParsed();
return (legacyMap != null) ? legacyMap.get(key) : null;
} | [
"public",
"synchronized",
"Service",
"getService",
"(",
"String",
"type",
",",
"String",
"algorithm",
")",
"{",
"checkInitialized",
"(",
")",
";",
"// avoid allocating a new key object if possible",
"ServiceKey",
"key",
"=",
"previousKey",
";",
"if",
"(",
"key",
"."... | Get the service describing this Provider's implementation of the
specified type of this algorithm or alias. If no such
implementation exists, this method returns null. If there are two
matching services, one added to this provider using
{@link #putService putService()} and one added via {@link #put put()},
the service added via {@link #putService putService()} is returned.
@param type the type of {@link Service service} requested
(for example, <code>MessageDigest</code>)
@param algorithm the case insensitive algorithm name (or alternate
alias) of the service requested (for example, <code>SHA-1</code>)
@return the service describing this Provider's matching service
or null if no such service exists
@throws NullPointerException if type or algorithm is null
@since 1.5 | [
"Get",
"the",
"service",
"describing",
"this",
"Provider",
"s",
"implementation",
"of",
"the",
"specified",
"type",
"of",
"this",
"algorithm",
"or",
"alias",
".",
"If",
"no",
"such",
"implementation",
"exists",
"this",
"method",
"returns",
"null",
".",
"If",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/Provider.java#L707-L723 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/ObjectStreamClass.java | ObjectStreamClass.inSamePackage | private boolean inSamePackage(Class<?> c1, Class<?> c2) {
String nameC1 = c1.getName();
String nameC2 = c2.getName();
int indexDotC1 = nameC1.lastIndexOf('.');
int indexDotC2 = nameC2.lastIndexOf('.');
if (indexDotC1 != indexDotC2) {
return false; // cannot be in the same package if indices are not the same
}
if (indexDotC1 == -1) {
return true; // both of them are in default package
}
return nameC1.regionMatches(0, nameC2, 0, indexDotC1);
} | java | private boolean inSamePackage(Class<?> c1, Class<?> c2) {
String nameC1 = c1.getName();
String nameC2 = c2.getName();
int indexDotC1 = nameC1.lastIndexOf('.');
int indexDotC2 = nameC2.lastIndexOf('.');
if (indexDotC1 != indexDotC2) {
return false; // cannot be in the same package if indices are not the same
}
if (indexDotC1 == -1) {
return true; // both of them are in default package
}
return nameC1.regionMatches(0, nameC2, 0, indexDotC1);
} | [
"private",
"boolean",
"inSamePackage",
"(",
"Class",
"<",
"?",
">",
"c1",
",",
"Class",
"<",
"?",
">",
"c2",
")",
"{",
"String",
"nameC1",
"=",
"c1",
".",
"getName",
"(",
")",
";",
"String",
"nameC2",
"=",
"c2",
".",
"getName",
"(",
")",
";",
"in... | Checks if two classes belong to the same package.
@param c1
one of the classes to test.
@param c2
the other class to test.
@return {@code true} if the two classes belong to the same package,
{@code false} otherwise. | [
"Checks",
"if",
"two",
"classes",
"belong",
"to",
"the",
"same",
"package",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/ObjectStreamClass.java#L750-L762 |
apache/incubator-gobblin | gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/retention/HivePartitionVersionRetentionReaper.java | HivePartitionVersionRetentionReaper.clean | @Override
public void clean()
throws IOException {
Path versionLocation = ((HivePartitionRetentionVersion) this.datasetVersion).getLocation();
Path datasetLocation = ((CleanableHivePartitionDataset) this.cleanableDataset).getLocation();
String completeName = ((HivePartitionRetentionVersion) this.datasetVersion).datasetURN();
State state = new State(this.state);
this.versionOwnerFs = ProxyUtils.getOwnerFs(state, this.versionOwner);
try (HiveProxyQueryExecutor queryExecutor = ProxyUtils
.getQueryExecutor(state, this.versionOwner, this.backUpOwner)) {
if (!this.versionOwnerFs.exists(versionLocation)) {
log.info("Data versionLocation doesn't exist. Metadata will be dropped for the version " + completeName);
} else if (datasetLocation.toString().equalsIgnoreCase(versionLocation.toString())) {
log.info(
"Dataset location is same as version location. Won't delete the data but metadata will be dropped for the version "
+ completeName);
} else if (this.simulate) {
log.info("Simulate is set to true. Won't move the version " + completeName);
return;
} else if (completeName.contains(ComplianceConfigurationKeys.STAGING)) {
log.info("Deleting data from version " + completeName);
this.versionOwnerFs.delete(versionLocation, true);
} else if (completeName.contains(ComplianceConfigurationKeys.BACKUP)) {
executeAlterQueries(queryExecutor);
Path newVersionLocationParent = getNewVersionLocation().getParent();
log.info("Creating new dir " + newVersionLocationParent.toString());
this.versionOwnerFs.mkdirs(newVersionLocationParent);
log.info("Moving data from " + versionLocation + " to " + getNewVersionLocation());
fsMove(versionLocation, getNewVersionLocation());
FsPermission permission = new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.NONE);
HadoopUtils
.setPermissions(newVersionLocationParent, this.versionOwner, this.backUpOwner, this.versionOwnerFs,
permission);
}
executeDropVersionQueries(queryExecutor);
}
} | java | @Override
public void clean()
throws IOException {
Path versionLocation = ((HivePartitionRetentionVersion) this.datasetVersion).getLocation();
Path datasetLocation = ((CleanableHivePartitionDataset) this.cleanableDataset).getLocation();
String completeName = ((HivePartitionRetentionVersion) this.datasetVersion).datasetURN();
State state = new State(this.state);
this.versionOwnerFs = ProxyUtils.getOwnerFs(state, this.versionOwner);
try (HiveProxyQueryExecutor queryExecutor = ProxyUtils
.getQueryExecutor(state, this.versionOwner, this.backUpOwner)) {
if (!this.versionOwnerFs.exists(versionLocation)) {
log.info("Data versionLocation doesn't exist. Metadata will be dropped for the version " + completeName);
} else if (datasetLocation.toString().equalsIgnoreCase(versionLocation.toString())) {
log.info(
"Dataset location is same as version location. Won't delete the data but metadata will be dropped for the version "
+ completeName);
} else if (this.simulate) {
log.info("Simulate is set to true. Won't move the version " + completeName);
return;
} else if (completeName.contains(ComplianceConfigurationKeys.STAGING)) {
log.info("Deleting data from version " + completeName);
this.versionOwnerFs.delete(versionLocation, true);
} else if (completeName.contains(ComplianceConfigurationKeys.BACKUP)) {
executeAlterQueries(queryExecutor);
Path newVersionLocationParent = getNewVersionLocation().getParent();
log.info("Creating new dir " + newVersionLocationParent.toString());
this.versionOwnerFs.mkdirs(newVersionLocationParent);
log.info("Moving data from " + versionLocation + " to " + getNewVersionLocation());
fsMove(versionLocation, getNewVersionLocation());
FsPermission permission = new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.NONE);
HadoopUtils
.setPermissions(newVersionLocationParent, this.versionOwner, this.backUpOwner, this.versionOwnerFs,
permission);
}
executeDropVersionQueries(queryExecutor);
}
} | [
"@",
"Override",
"public",
"void",
"clean",
"(",
")",
"throws",
"IOException",
"{",
"Path",
"versionLocation",
"=",
"(",
"(",
"HivePartitionRetentionVersion",
")",
"this",
".",
"datasetVersion",
")",
".",
"getLocation",
"(",
")",
";",
"Path",
"datasetLocation",
... | If simulate is set to true, will simply return.
If a version is pointing to a non-existing location, then drop the partition and close the jdbc connection.
If a version is pointing to the same location as of the dataset, then drop the partition and close the jdbc connection.
If a version is staging, it's data will be deleted and metadata is dropped.
IF a versions is backup, it's data will be moved to a backup dir, current metadata will be dropped and it will
be registered in the backup db. | [
"If",
"simulate",
"is",
"set",
"to",
"true",
"will",
"simply",
"return",
".",
"If",
"a",
"version",
"is",
"pointing",
"to",
"a",
"non",
"-",
"existing",
"location",
"then",
"drop",
"the",
"partition",
"and",
"close",
"the",
"jdbc",
"connection",
".",
"If... | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/retention/HivePartitionVersionRetentionReaper.java#L83-L122 |
amzn/ion-java | src/com/amazon/ion/impl/LocalSymbolTableImports.java | LocalSymbolTableImports.prepBaseSids | private static int prepBaseSids(int[] baseSids, SymbolTable[] imports)
{
SymbolTable firstImport = imports[0];
assert firstImport.isSystemTable()
: "first symtab must be a system symtab";
baseSids[0] = 0;
int total = firstImport.getMaxId();
for (int i = 1; i < imports.length; i++)
{
SymbolTable importedTable = imports[i];
if (importedTable.isLocalTable() || importedTable.isSystemTable())
{
String message = "only non-system shared tables can be imported";
throw new IllegalArgumentException(message);
}
baseSids[i] = total;
total += imports[i].getMaxId();
}
return total;
} | java | private static int prepBaseSids(int[] baseSids, SymbolTable[] imports)
{
SymbolTable firstImport = imports[0];
assert firstImport.isSystemTable()
: "first symtab must be a system symtab";
baseSids[0] = 0;
int total = firstImport.getMaxId();
for (int i = 1; i < imports.length; i++)
{
SymbolTable importedTable = imports[i];
if (importedTable.isLocalTable() || importedTable.isSystemTable())
{
String message = "only non-system shared tables can be imported";
throw new IllegalArgumentException(message);
}
baseSids[i] = total;
total += imports[i].getMaxId();
}
return total;
} | [
"private",
"static",
"int",
"prepBaseSids",
"(",
"int",
"[",
"]",
"baseSids",
",",
"SymbolTable",
"[",
"]",
"imports",
")",
"{",
"SymbolTable",
"firstImport",
"=",
"imports",
"[",
"0",
"]",
";",
"assert",
"firstImport",
".",
"isSystemTable",
"(",
")",
":",... | Collects the necessary maxId info. from the passed-in {@code imports}
and populates the {@code baseSids} array.
@return the sum of all imports' maxIds
@throws IllegalArgumentException
if any symtab beyond the first is a local or system symtab | [
"Collects",
"the",
"necessary",
"maxId",
"info",
".",
"from",
"the",
"passed",
"-",
"in",
"{",
"@code",
"imports",
"}",
"and",
"populates",
"the",
"{",
"@code",
"baseSids",
"}",
"array",
"."
] | train | https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/impl/LocalSymbolTableImports.java#L140-L165 |
languagetool-org/languagetool | languagetool-core/src/main/java/org/languagetool/JLanguageTool.java | JLanguageTool.getAnalyzedSentence | public AnalyzedSentence getAnalyzedSentence(String sentence) throws IOException {
SimpleInputSentence cacheKey = new SimpleInputSentence(sentence, language);
AnalyzedSentence cachedSentence = cache != null ? cache.getIfPresent(cacheKey) : null;
if (cachedSentence != null) {
return cachedSentence;
} else {
AnalyzedSentence raw = getRawAnalyzedSentence(sentence);
AnalyzedSentence disambig = language.getDisambiguator().disambiguate(raw);
AnalyzedSentence analyzedSentence = new AnalyzedSentence(disambig.getTokens(), raw.getTokens());
if (language.getPostDisambiguationChunker() != null) {
language.getPostDisambiguationChunker().addChunkTags(Arrays.asList(analyzedSentence.getTokens()));
}
if (cache != null) {
cache.put(cacheKey, analyzedSentence);
}
return analyzedSentence;
}
} | java | public AnalyzedSentence getAnalyzedSentence(String sentence) throws IOException {
SimpleInputSentence cacheKey = new SimpleInputSentence(sentence, language);
AnalyzedSentence cachedSentence = cache != null ? cache.getIfPresent(cacheKey) : null;
if (cachedSentence != null) {
return cachedSentence;
} else {
AnalyzedSentence raw = getRawAnalyzedSentence(sentence);
AnalyzedSentence disambig = language.getDisambiguator().disambiguate(raw);
AnalyzedSentence analyzedSentence = new AnalyzedSentence(disambig.getTokens(), raw.getTokens());
if (language.getPostDisambiguationChunker() != null) {
language.getPostDisambiguationChunker().addChunkTags(Arrays.asList(analyzedSentence.getTokens()));
}
if (cache != null) {
cache.put(cacheKey, analyzedSentence);
}
return analyzedSentence;
}
} | [
"public",
"AnalyzedSentence",
"getAnalyzedSentence",
"(",
"String",
"sentence",
")",
"throws",
"IOException",
"{",
"SimpleInputSentence",
"cacheKey",
"=",
"new",
"SimpleInputSentence",
"(",
"sentence",
",",
"language",
")",
";",
"AnalyzedSentence",
"cachedSentence",
"="... | Tokenizes the given {@code sentence} into words and analyzes it,
and then disambiguates POS tags.
@param sentence sentence to be analyzed | [
"Tokenizes",
"the",
"given",
"{"
] | train | https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/JLanguageTool.java#L947-L964 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.createRegexEntityModel | public UUID createRegexEntityModel(UUID appId, String versionId, RegexModelCreateObject regexEntityExtractorCreateObj) {
return createRegexEntityModelWithServiceResponseAsync(appId, versionId, regexEntityExtractorCreateObj).toBlocking().single().body();
} | java | public UUID createRegexEntityModel(UUID appId, String versionId, RegexModelCreateObject regexEntityExtractorCreateObj) {
return createRegexEntityModelWithServiceResponseAsync(appId, versionId, regexEntityExtractorCreateObj).toBlocking().single().body();
} | [
"public",
"UUID",
"createRegexEntityModel",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"RegexModelCreateObject",
"regexEntityExtractorCreateObj",
")",
"{",
"return",
"createRegexEntityModelWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"regexEnt... | Adds a regex entity model to the application version.
@param appId The application ID.
@param versionId The version ID.
@param regexEntityExtractorCreateObj A model object containing the name and regex pattern for the new regex entity extractor.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the UUID object if successful. | [
"Adds",
"a",
"regex",
"entity",
"model",
"to",
"the",
"application",
"version",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L7297-L7299 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.setSubscribedResourceAsDeleted | public void setSubscribedResourceAsDeleted(CmsRequestContext context, String poolName, CmsResource resource)
throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
m_driverManager.setSubscribedResourceAsDeleted(dbc, poolName, resource);
} catch (Exception e) {
dbc.report(
null,
Messages.get().container(
Messages.ERR_SET_SUBSCRIBED_RESOURCE_AS_DELETED_1,
context.getSitePath(resource)),
e);
} finally {
dbc.clear();
}
} | java | public void setSubscribedResourceAsDeleted(CmsRequestContext context, String poolName, CmsResource resource)
throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
m_driverManager.setSubscribedResourceAsDeleted(dbc, poolName, resource);
} catch (Exception e) {
dbc.report(
null,
Messages.get().container(
Messages.ERR_SET_SUBSCRIBED_RESOURCE_AS_DELETED_1,
context.getSitePath(resource)),
e);
} finally {
dbc.clear();
}
} | [
"public",
"void",
"setSubscribedResourceAsDeleted",
"(",
"CmsRequestContext",
"context",
",",
"String",
"poolName",
",",
"CmsResource",
"resource",
")",
"throws",
"CmsException",
"{",
"CmsDbContext",
"dbc",
"=",
"m_dbContextFactory",
".",
"getDbContext",
"(",
"context",... | Marks a subscribed resource as deleted.<p>
@param context the request context
@param poolName the name of the database pool to use
@param resource the subscribed resource to mark as deleted
@throws CmsException if something goes wrong | [
"Marks",
"a",
"subscribed",
"resource",
"as",
"deleted",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L6104-L6122 |
UrielCh/ovh-java-sdk | ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java | ApiOvhMe.installationTemplate_templateName_partitionScheme_schemeName_partition_POST | public void installationTemplate_templateName_partitionScheme_schemeName_partition_POST(String templateName, String schemeName, OvhTemplateOsFileSystemEnum filesystem, String mountpoint, Long raid, Long size, Long step, OvhTemplatePartitionTypeEnum type, String volumeName) throws IOException {
String qPath = "/me/installationTemplate/{templateName}/partitionScheme/{schemeName}/partition";
StringBuilder sb = path(qPath, templateName, schemeName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "filesystem", filesystem);
addBody(o, "mountpoint", mountpoint);
addBody(o, "raid", raid);
addBody(o, "size", size);
addBody(o, "step", step);
addBody(o, "type", type);
addBody(o, "volumeName", volumeName);
exec(qPath, "POST", sb.toString(), o);
} | java | public void installationTemplate_templateName_partitionScheme_schemeName_partition_POST(String templateName, String schemeName, OvhTemplateOsFileSystemEnum filesystem, String mountpoint, Long raid, Long size, Long step, OvhTemplatePartitionTypeEnum type, String volumeName) throws IOException {
String qPath = "/me/installationTemplate/{templateName}/partitionScheme/{schemeName}/partition";
StringBuilder sb = path(qPath, templateName, schemeName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "filesystem", filesystem);
addBody(o, "mountpoint", mountpoint);
addBody(o, "raid", raid);
addBody(o, "size", size);
addBody(o, "step", step);
addBody(o, "type", type);
addBody(o, "volumeName", volumeName);
exec(qPath, "POST", sb.toString(), o);
} | [
"public",
"void",
"installationTemplate_templateName_partitionScheme_schemeName_partition_POST",
"(",
"String",
"templateName",
",",
"String",
"schemeName",
",",
"OvhTemplateOsFileSystemEnum",
"filesystem",
",",
"String",
"mountpoint",
",",
"Long",
"raid",
",",
"Long",
"size"... | Add a partition in this partitioning scheme
REST: POST /me/installationTemplate/{templateName}/partitionScheme/{schemeName}/partition
@param type [required]
@param volumeName [required] The volume name needed for proxmox distribution
@param raid [required]
@param mountpoint [required] partition mount point
@param size [required] size of partition in Mb, 0 => rest of the space
@param step [required]
@param filesystem [required] Partition filesytem
@param templateName [required] This template name
@param schemeName [required] name of this partitioning scheme | [
"Add",
"a",
"partition",
"in",
"this",
"partitioning",
"scheme"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L3649-L3661 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/LoggerOddities.java | LoggerOddities.visitCode | @Override
public void visitCode(Code obj) {
stack.resetForMethodEntry(this);
Method m = getMethod();
if (Values.CONSTRUCTOR.equals(m.getName())) {
for (String parmSig : SignatureUtils.getParameterSignatures(m.getSignature())) {
if (SignatureUtils.classToSignature(SLF4J_LOGGER).equals(parmSig) || SignatureUtils.classToSignature(LOG4J_LOGGER).equals(parmSig)
|| SignatureUtils.classToSignature(LOG4J2_LOGGER).equals(parmSig) || SignatureUtils.classToSignature(COMMONS_LOGGER).equals(parmSig)) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_SUSPECT_LOG_PARAMETER.name(), NORMAL_PRIORITY).addClass(this).addMethod(this));
}
}
}
isStaticInitializer = Values.STATIC_INITIALIZER.equals(m.getName());
super.visitCode(obj);
} | java | @Override
public void visitCode(Code obj) {
stack.resetForMethodEntry(this);
Method m = getMethod();
if (Values.CONSTRUCTOR.equals(m.getName())) {
for (String parmSig : SignatureUtils.getParameterSignatures(m.getSignature())) {
if (SignatureUtils.classToSignature(SLF4J_LOGGER).equals(parmSig) || SignatureUtils.classToSignature(LOG4J_LOGGER).equals(parmSig)
|| SignatureUtils.classToSignature(LOG4J2_LOGGER).equals(parmSig) || SignatureUtils.classToSignature(COMMONS_LOGGER).equals(parmSig)) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_SUSPECT_LOG_PARAMETER.name(), NORMAL_PRIORITY).addClass(this).addMethod(this));
}
}
}
isStaticInitializer = Values.STATIC_INITIALIZER.equals(m.getName());
super.visitCode(obj);
} | [
"@",
"Override",
"public",
"void",
"visitCode",
"(",
"Code",
"obj",
")",
"{",
"stack",
".",
"resetForMethodEntry",
"(",
"this",
")",
";",
"Method",
"m",
"=",
"getMethod",
"(",
")",
";",
"if",
"(",
"Values",
".",
"CONSTRUCTOR",
".",
"equals",
"(",
"m",
... | implements the visitor to reset the stack
@param obj
the context object of the currently parsed code block | [
"implements",
"the",
"visitor",
"to",
"reset",
"the",
"stack"
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/LoggerOddities.java#L154-L169 |
apereo/cas | support/cas-server-support-cosmosdb-core/src/main/java/org/apereo/cas/cosmosdb/CosmosDbObjectFactory.java | CosmosDbObjectFactory.createDocumentDbTemplate | public DocumentDbTemplate createDocumentDbTemplate(final DocumentDbFactory documentDbFactory,
final BaseCosmosDbProperties properties) {
val documentDbMappingContext = createDocumentDbMappingContext();
val mappingDocumentDbConverter = createMappingDocumentDbConverter(documentDbMappingContext);
return new DocumentDbTemplate(documentDbFactory, mappingDocumentDbConverter, properties.getDatabase());
} | java | public DocumentDbTemplate createDocumentDbTemplate(final DocumentDbFactory documentDbFactory,
final BaseCosmosDbProperties properties) {
val documentDbMappingContext = createDocumentDbMappingContext();
val mappingDocumentDbConverter = createMappingDocumentDbConverter(documentDbMappingContext);
return new DocumentDbTemplate(documentDbFactory, mappingDocumentDbConverter, properties.getDatabase());
} | [
"public",
"DocumentDbTemplate",
"createDocumentDbTemplate",
"(",
"final",
"DocumentDbFactory",
"documentDbFactory",
",",
"final",
"BaseCosmosDbProperties",
"properties",
")",
"{",
"val",
"documentDbMappingContext",
"=",
"createDocumentDbMappingContext",
"(",
")",
";",
"val",
... | Create document db template document db template.
@param documentDbFactory the document db factory
@param properties the properties
@return the document db template | [
"Create",
"document",
"db",
"template",
"document",
"db",
"template",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-cosmosdb-core/src/main/java/org/apereo/cas/cosmosdb/CosmosDbObjectFactory.java#L103-L108 |
elki-project/elki | elki-database/src/main/java/de/lmu/ifi/dbs/elki/database/query/knn/LinearScanPrimitiveDistanceKNNQuery.java | LinearScanPrimitiveDistanceKNNQuery.linearScanBatchKNN | protected void linearScanBatchKNN(List<O> objs, List<KNNHeap> heaps) {
final PrimitiveDistanceFunction<? super O> rawdist = this.rawdist;
final Relation<? extends O> relation = getRelation();
final int size = objs.size();
// Linear scan style KNN.
for(DBIDIter iter = relation.getDBIDs().iter(); iter.valid(); iter.advance()) {
O candidate = relation.get(iter);
for(int index = 0; index < size; index++) {
final KNNHeap heap = heaps.get(index);
final double dist = rawdist.distance(objs.get(index), candidate);
if(dist <= heap.getKNNDistance()) {
heap.insert(dist, iter);
}
}
}
} | java | protected void linearScanBatchKNN(List<O> objs, List<KNNHeap> heaps) {
final PrimitiveDistanceFunction<? super O> rawdist = this.rawdist;
final Relation<? extends O> relation = getRelation();
final int size = objs.size();
// Linear scan style KNN.
for(DBIDIter iter = relation.getDBIDs().iter(); iter.valid(); iter.advance()) {
O candidate = relation.get(iter);
for(int index = 0; index < size; index++) {
final KNNHeap heap = heaps.get(index);
final double dist = rawdist.distance(objs.get(index), candidate);
if(dist <= heap.getKNNDistance()) {
heap.insert(dist, iter);
}
}
}
} | [
"protected",
"void",
"linearScanBatchKNN",
"(",
"List",
"<",
"O",
">",
"objs",
",",
"List",
"<",
"KNNHeap",
">",
"heaps",
")",
"{",
"final",
"PrimitiveDistanceFunction",
"<",
"?",
"super",
"O",
">",
"rawdist",
"=",
"this",
".",
"rawdist",
";",
"final",
"... | Perform a linear scan batch kNN for primitive distance functions.
@param objs Objects list
@param heaps Heaps array | [
"Perform",
"a",
"linear",
"scan",
"batch",
"kNN",
"for",
"primitive",
"distance",
"functions",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-database/src/main/java/de/lmu/ifi/dbs/elki/database/query/knn/LinearScanPrimitiveDistanceKNNQuery.java#L124-L139 |
kaazing/gateway | mina.core/core/src/main/java/org/apache/mina/proxy/handlers/http/ntlm/NTLMUtilities.java | NTLMUtilities.extractTargetNameFromType2Message | public static String extractTargetNameFromType2Message(byte[] msg,
Integer msgFlags) throws UnsupportedEncodingException {
// Read the security buffer to determine where the target name
// is stored and what it's length is
byte[] targetName = readSecurityBufferTarget(msg, 12);
// now we convert it to a string
int flags = msgFlags == null ? extractFlagsFromType2Message(msg)
: msgFlags;
if (ByteUtilities.isFlagSet(flags, FLAG_NEGOTIATE_UNICODE)) {
return new String(targetName, "UTF-16LE");
}
return new String(targetName, "ASCII");
} | java | public static String extractTargetNameFromType2Message(byte[] msg,
Integer msgFlags) throws UnsupportedEncodingException {
// Read the security buffer to determine where the target name
// is stored and what it's length is
byte[] targetName = readSecurityBufferTarget(msg, 12);
// now we convert it to a string
int flags = msgFlags == null ? extractFlagsFromType2Message(msg)
: msgFlags;
if (ByteUtilities.isFlagSet(flags, FLAG_NEGOTIATE_UNICODE)) {
return new String(targetName, "UTF-16LE");
}
return new String(targetName, "ASCII");
} | [
"public",
"static",
"String",
"extractTargetNameFromType2Message",
"(",
"byte",
"[",
"]",
"msg",
",",
"Integer",
"msgFlags",
")",
"throws",
"UnsupportedEncodingException",
"{",
"// Read the security buffer to determine where the target name",
"// is stored and what it's length is",... | Extracts the target name from the type 2 message.
@param msg the type 2 message byte array
@param msgFlags the flags if null then flags are extracted from the
type 2 message
@return the target name
@throws UnsupportedEncodingException if unable to use the
needed UTF-16LE or ASCII charsets | [
"Extracts",
"the",
"target",
"name",
"from",
"the",
"type",
"2",
"message",
"."
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.core/core/src/main/java/org/apache/mina/proxy/handlers/http/ntlm/NTLMUtilities.java#L306-L320 |
katjahahn/PortEx | src/main/java/com/github/katjahahn/tools/Hasher.java | Hasher.fileHash | public static byte[] fileHash(File file, MessageDigest messageDigest)
throws IOException {
return computeHash(file, messageDigest, 0L, file.length());
} | java | public static byte[] fileHash(File file, MessageDigest messageDigest)
throws IOException {
return computeHash(file, messageDigest, 0L, file.length());
} | [
"public",
"static",
"byte",
"[",
"]",
"fileHash",
"(",
"File",
"file",
",",
"MessageDigest",
"messageDigest",
")",
"throws",
"IOException",
"{",
"return",
"computeHash",
"(",
"file",
",",
"messageDigest",
",",
"0L",
",",
"file",
".",
"length",
"(",
")",
")... | Returns the hash value of the file for the specified messageDigest.
@param file
to compute the hash value for
@param messageDigest
the message digest algorithm
@return hash value of the file
@throws IOException | [
"Returns",
"the",
"hash",
"value",
"of",
"the",
"file",
"for",
"the",
"specified",
"messageDigest",
"."
] | train | https://github.com/katjahahn/PortEx/blob/319f08560aa58e3d5d7abe346ffdf623d6dc6990/src/main/java/com/github/katjahahn/tools/Hasher.java#L126-L129 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/spider/BatchObjectUpdater.java | BatchObjectUpdater.updateBatch | private boolean updateBatch(DBObjectBatch dbObjBatch, BatchResult batchResult) throws IOException {
Map<String, Map<String, String>> objCurrScalarMap = getCurrentScalars(dbObjBatch);
Map<String, Map<String, Integer>> targObjShardNos = getLinkTargetShardNumbers(dbObjBatch);
for (DBObject dbObj : dbObjBatch.getObjects()) {
checkCommit();
Map<String, String> currScalarMap = objCurrScalarMap.get(dbObj.getObjectID());
ObjectResult objResult = updateObject(dbObj, currScalarMap, targObjShardNos);
batchResult.addObjectResult(objResult);
}
commitTransaction();
return batchResult.hasUpdates();
} | java | private boolean updateBatch(DBObjectBatch dbObjBatch, BatchResult batchResult) throws IOException {
Map<String, Map<String, String>> objCurrScalarMap = getCurrentScalars(dbObjBatch);
Map<String, Map<String, Integer>> targObjShardNos = getLinkTargetShardNumbers(dbObjBatch);
for (DBObject dbObj : dbObjBatch.getObjects()) {
checkCommit();
Map<String, String> currScalarMap = objCurrScalarMap.get(dbObj.getObjectID());
ObjectResult objResult = updateObject(dbObj, currScalarMap, targObjShardNos);
batchResult.addObjectResult(objResult);
}
commitTransaction();
return batchResult.hasUpdates();
} | [
"private",
"boolean",
"updateBatch",
"(",
"DBObjectBatch",
"dbObjBatch",
",",
"BatchResult",
"batchResult",
")",
"throws",
"IOException",
"{",
"Map",
"<",
"String",
",",
"Map",
"<",
"String",
",",
"String",
">",
">",
"objCurrScalarMap",
"=",
"getCurrentScalars",
... | Update each object in the given batch, updating BatchResult accordingly. | [
"Update",
"each",
"object",
"in",
"the",
"given",
"batch",
"updating",
"BatchResult",
"accordingly",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/BatchObjectUpdater.java#L174-L185 |
lessthanoptimal/BoofCV | main/boofcv-sfm/src/main/java/boofcv/factory/sfm/FactoryMotion2D.java | FactoryMotion2D.createMotion2D | public static <I extends ImageBase<I>, IT extends InvertibleTransform>
ImageMotion2D<I,IT> createMotion2D( int ransacIterations , double inlierThreshold,int outlierPrune,
int absoluteMinimumTracks, double respawnTrackFraction,
double respawnCoverageFraction,
boolean refineEstimate ,
PointTracker<I> tracker , IT motionModel ) {
ModelManager<IT> manager;
ModelGenerator<IT,AssociatedPair> fitter;
DistanceFromModel<IT,AssociatedPair> distance;
ModelFitter<IT,AssociatedPair> modelRefiner = null;
if( motionModel instanceof Homography2D_F64) {
GenerateHomographyLinear mf = new GenerateHomographyLinear(true);
manager = (ModelManager)new ModelManagerHomography2D_F64();
fitter = (ModelGenerator)mf;
if( refineEstimate )
modelRefiner = (ModelFitter)mf;
distance = (DistanceFromModel)new DistanceHomographySq();
} else if( motionModel instanceof Affine2D_F64) {
manager = (ModelManager)new ModelManagerAffine2D_F64();
GenerateAffine2D mf = new GenerateAffine2D();
fitter = (ModelGenerator)mf;
if( refineEstimate )
modelRefiner = (ModelFitter)mf;
distance = (DistanceFromModel)new DistanceAffine2DSq();
} else if( motionModel instanceof Se2_F64) {
manager = (ModelManager)new ModelManagerSe2_F64();
MotionTransformPoint<Se2_F64, Point2D_F64> alg = new MotionSe2PointSVD_F64();
GenerateSe2_AssociatedPair mf = new GenerateSe2_AssociatedPair(alg);
fitter = (ModelGenerator)mf;
distance = (DistanceFromModel)new DistanceSe2Sq();
// no refine, already optimal
} else {
throw new RuntimeException("Unknown model type: "+motionModel.getClass().getSimpleName());
}
ModelMatcher<IT,AssociatedPair> modelMatcher =
new Ransac(123123,manager,fitter,distance,ransacIterations,inlierThreshold);
ImageMotionPointTrackerKey<I,IT> lowlevel =
new ImageMotionPointTrackerKey<>(tracker, modelMatcher, modelRefiner, motionModel, outlierPrune);
ImageMotionPtkSmartRespawn<I,IT> smartRespawn =
new ImageMotionPtkSmartRespawn<>(lowlevel,
absoluteMinimumTracks, respawnTrackFraction, respawnCoverageFraction);
return new WrapImageMotionPtkSmartRespawn<>(smartRespawn);
} | java | public static <I extends ImageBase<I>, IT extends InvertibleTransform>
ImageMotion2D<I,IT> createMotion2D( int ransacIterations , double inlierThreshold,int outlierPrune,
int absoluteMinimumTracks, double respawnTrackFraction,
double respawnCoverageFraction,
boolean refineEstimate ,
PointTracker<I> tracker , IT motionModel ) {
ModelManager<IT> manager;
ModelGenerator<IT,AssociatedPair> fitter;
DistanceFromModel<IT,AssociatedPair> distance;
ModelFitter<IT,AssociatedPair> modelRefiner = null;
if( motionModel instanceof Homography2D_F64) {
GenerateHomographyLinear mf = new GenerateHomographyLinear(true);
manager = (ModelManager)new ModelManagerHomography2D_F64();
fitter = (ModelGenerator)mf;
if( refineEstimate )
modelRefiner = (ModelFitter)mf;
distance = (DistanceFromModel)new DistanceHomographySq();
} else if( motionModel instanceof Affine2D_F64) {
manager = (ModelManager)new ModelManagerAffine2D_F64();
GenerateAffine2D mf = new GenerateAffine2D();
fitter = (ModelGenerator)mf;
if( refineEstimate )
modelRefiner = (ModelFitter)mf;
distance = (DistanceFromModel)new DistanceAffine2DSq();
} else if( motionModel instanceof Se2_F64) {
manager = (ModelManager)new ModelManagerSe2_F64();
MotionTransformPoint<Se2_F64, Point2D_F64> alg = new MotionSe2PointSVD_F64();
GenerateSe2_AssociatedPair mf = new GenerateSe2_AssociatedPair(alg);
fitter = (ModelGenerator)mf;
distance = (DistanceFromModel)new DistanceSe2Sq();
// no refine, already optimal
} else {
throw new RuntimeException("Unknown model type: "+motionModel.getClass().getSimpleName());
}
ModelMatcher<IT,AssociatedPair> modelMatcher =
new Ransac(123123,manager,fitter,distance,ransacIterations,inlierThreshold);
ImageMotionPointTrackerKey<I,IT> lowlevel =
new ImageMotionPointTrackerKey<>(tracker, modelMatcher, modelRefiner, motionModel, outlierPrune);
ImageMotionPtkSmartRespawn<I,IT> smartRespawn =
new ImageMotionPtkSmartRespawn<>(lowlevel,
absoluteMinimumTracks, respawnTrackFraction, respawnCoverageFraction);
return new WrapImageMotionPtkSmartRespawn<>(smartRespawn);
} | [
"public",
"static",
"<",
"I",
"extends",
"ImageBase",
"<",
"I",
">",
",",
"IT",
"extends",
"InvertibleTransform",
">",
"ImageMotion2D",
"<",
"I",
",",
"IT",
">",
"createMotion2D",
"(",
"int",
"ransacIterations",
",",
"double",
"inlierThreshold",
",",
"int",
... | Estimates the 2D motion of an image using different models.
@param ransacIterations Number of RANSAC iterations
@param inlierThreshold Threshold which defines an inlier.
@param outlierPrune If a feature is an outlier for this many turns in a row it is dropped. Try 2
@param absoluteMinimumTracks New features will be respawned if the number of inliers drop below this number.
@param respawnTrackFraction If the fraction of current inliers to the original number of inliers drops below
this fraction then new features are spawned. Try 0.3
@param respawnCoverageFraction If the area covered drops by this fraction then spawn more features. Try 0.8
@param refineEstimate Should it refine the model estimate using all inliers.
@param tracker Point feature tracker.
@param motionModel Instance of the model model used. Affine2D_F64 or Homography2D_F64
@param <I> Image input type.
@param <IT> Model model
@return ImageMotion2D | [
"Estimates",
"the",
"2D",
"motion",
"of",
"an",
"image",
"using",
"different",
"models",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-sfm/src/main/java/boofcv/factory/sfm/FactoryMotion2D.java#L73-L121 |
JodaOrg/joda-time | src/main/java/org/joda/time/LocalDate.java | LocalDate.toDateTime | public DateTime toDateTime(LocalTime time, DateTimeZone zone) {
if (time == null) {
return toDateTimeAtCurrentTime(zone);
}
if (getChronology() != time.getChronology()) {
throw new IllegalArgumentException("The chronology of the time does not match");
}
Chronology chrono = getChronology().withZone(zone);
return new DateTime(
getYear(), getMonthOfYear(), getDayOfMonth(),
time.getHourOfDay(), time.getMinuteOfHour(),
time.getSecondOfMinute(), time.getMillisOfSecond(), chrono);
} | java | public DateTime toDateTime(LocalTime time, DateTimeZone zone) {
if (time == null) {
return toDateTimeAtCurrentTime(zone);
}
if (getChronology() != time.getChronology()) {
throw new IllegalArgumentException("The chronology of the time does not match");
}
Chronology chrono = getChronology().withZone(zone);
return new DateTime(
getYear(), getMonthOfYear(), getDayOfMonth(),
time.getHourOfDay(), time.getMinuteOfHour(),
time.getSecondOfMinute(), time.getMillisOfSecond(), chrono);
} | [
"public",
"DateTime",
"toDateTime",
"(",
"LocalTime",
"time",
",",
"DateTimeZone",
"zone",
")",
"{",
"if",
"(",
"time",
"==",
"null",
")",
"{",
"return",
"toDateTimeAtCurrentTime",
"(",
"zone",
")",
";",
"}",
"if",
"(",
"getChronology",
"(",
")",
"!=",
"... | Converts this object to a DateTime using a LocalTime to fill in the
missing fields.
<p>
The resulting chronology is determined by the chronology of this
LocalDate plus the time zone. The chronology of the time must match.
<p>
If the time is null, this method delegates to {@link #toDateTimeAtCurrentTime(DateTimeZone)}
and the following documentation does not apply.
<p>
When the time zone is applied, the local date-time may be affected by daylight saving.
In a daylight saving gap, when the local time does not exist,
this method will throw an exception.
In a daylight saving overlap, when the same local time occurs twice,
this method returns the first occurrence of the local time.
<p>
This instance is immutable and unaffected by this method call.
@param time the time of day to use, null uses current time
@param zone the zone to get the DateTime in, null means default
@return the DateTime instance
@throws IllegalArgumentException if the chronology of the time does not match
@throws IllegalInstantException if the local time does not exist when the time zone is applied | [
"Converts",
"this",
"object",
"to",
"a",
"DateTime",
"using",
"a",
"LocalTime",
"to",
"fill",
"in",
"the",
"missing",
"fields",
".",
"<p",
">",
"The",
"resulting",
"chronology",
"is",
"determined",
"by",
"the",
"chronology",
"of",
"this",
"LocalDate",
"plus"... | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/LocalDate.java#L950-L962 |
getsentry/sentry-java | sentry-logback/src/main/java/io/sentry/logback/SentryAppender.java | SentryAppender.createSentryExceptionFrom | protected SentryException createSentryExceptionFrom(IThrowableProxy throwableProxy,
StackTraceInterface stackTrace) {
String exceptionMessage = throwableProxy.getMessage();
String[] packageNameSimpleName = extractPackageSimpleClassName(throwableProxy.getClassName());
String exceptionPackageName = packageNameSimpleName[0];
String exceptionClassName = packageNameSimpleName[1];
return new SentryException(exceptionMessage, exceptionClassName, exceptionPackageName, stackTrace);
} | java | protected SentryException createSentryExceptionFrom(IThrowableProxy throwableProxy,
StackTraceInterface stackTrace) {
String exceptionMessage = throwableProxy.getMessage();
String[] packageNameSimpleName = extractPackageSimpleClassName(throwableProxy.getClassName());
String exceptionPackageName = packageNameSimpleName[0];
String exceptionClassName = packageNameSimpleName[1];
return new SentryException(exceptionMessage, exceptionClassName, exceptionPackageName, stackTrace);
} | [
"protected",
"SentryException",
"createSentryExceptionFrom",
"(",
"IThrowableProxy",
"throwableProxy",
",",
"StackTraceInterface",
"stackTrace",
")",
"{",
"String",
"exceptionMessage",
"=",
"throwableProxy",
".",
"getMessage",
"(",
")",
";",
"String",
"[",
"]",
"package... | Given a {@link IThrowableProxy} and a {@link StackTraceInterface} return
a {@link SentryException} to be reported to Sentry.
@param throwableProxy Information detailing a Throwable
@param stackTrace The stacktrace associated with the Throwable.
@return A {@link SentryException} object ready to be sent to Sentry. | [
"Given",
"a",
"{",
"@link",
"IThrowableProxy",
"}",
"and",
"a",
"{",
"@link",
"StackTraceInterface",
"}",
"return",
"a",
"{",
"@link",
"SentryException",
"}",
"to",
"be",
"reported",
"to",
"Sentry",
"."
] | train | https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry-logback/src/main/java/io/sentry/logback/SentryAppender.java#L204-L212 |
wildfly/wildfly-core | patching/src/main/java/org/jboss/as/patching/tool/PatchOperationTarget.java | PatchOperationTarget.createHost | public static final PatchOperationTarget createHost(final String hostName, final ModelControllerClient client) {
final PathElement host = PathElement.pathElement(HOST, hostName);
final PathAddress address = PathAddress.EMPTY_ADDRESS.append(host, CORE_SERVICES);
return new RemotePatchOperationTarget(address, client);
} | java | public static final PatchOperationTarget createHost(final String hostName, final ModelControllerClient client) {
final PathElement host = PathElement.pathElement(HOST, hostName);
final PathAddress address = PathAddress.EMPTY_ADDRESS.append(host, CORE_SERVICES);
return new RemotePatchOperationTarget(address, client);
} | [
"public",
"static",
"final",
"PatchOperationTarget",
"createHost",
"(",
"final",
"String",
"hostName",
",",
"final",
"ModelControllerClient",
"client",
")",
"{",
"final",
"PathElement",
"host",
"=",
"PathElement",
".",
"pathElement",
"(",
"HOST",
",",
"hostName",
... | Create a host target.
@param hostName the host name
@param client the connected controller client to the master host.
@return the remote target | [
"Create",
"a",
"host",
"target",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/patching/src/main/java/org/jboss/as/patching/tool/PatchOperationTarget.java#L99-L103 |
looly/hutool | hutool-crypto/src/main/java/cn/hutool/crypto/SecureUtil.java | SecureUtil.generatePublicKey | public static PublicKey generatePublicKey(String algorithm, KeySpec keySpec) {
return KeyUtil.generatePublicKey(algorithm, keySpec);
} | java | public static PublicKey generatePublicKey(String algorithm, KeySpec keySpec) {
return KeyUtil.generatePublicKey(algorithm, keySpec);
} | [
"public",
"static",
"PublicKey",
"generatePublicKey",
"(",
"String",
"algorithm",
",",
"KeySpec",
"keySpec",
")",
"{",
"return",
"KeyUtil",
".",
"generatePublicKey",
"(",
"algorithm",
",",
"keySpec",
")",
";",
"}"
] | 生成公钥,仅用于非对称加密<br>
算法见:https://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#KeyFactory
@param algorithm 算法
@param keySpec {@link KeySpec}
@return 公钥 {@link PublicKey}
@since 3.1.1 | [
"生成公钥,仅用于非对称加密<br",
">",
"算法见:https",
":",
"//",
"docs",
".",
"oracle",
".",
"com",
"/",
"javase",
"/",
"7",
"/",
"docs",
"/",
"technotes",
"/",
"guides",
"/",
"security",
"/",
"StandardNames",
".",
"html#KeyFactory"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-crypto/src/main/java/cn/hutool/crypto/SecureUtil.java#L191-L193 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/cpc/CpcSketch.java | CpcSketch.updateWindowed | private static void updateWindowed(final CpcSketch sketch, final int rowCol) {
assert ((sketch.windowOffset >= 0) && (sketch.windowOffset <= 56));
final int k = 1 << sketch.lgK;
final long c32pre = sketch.numCoupons << 5;
assert c32pre >= (3L * k); // C < 3K/32, in other words flavor >= HYBRID
final long c8pre = sketch.numCoupons << 3;
final int w8pre = sketch.windowOffset << 3;
assert c8pre < ((27L + w8pre) * k); // C < (K * 27/8) + (K * windowOffset)
boolean isNovel = false; //novel if new coupon
final int col = rowCol & 63;
if (col < sketch.windowOffset) { // track the surprising 0's "before" the window
isNovel = PairTable.maybeDelete(sketch.pairTable, rowCol); // inverted logic
}
else if (col < (sketch.windowOffset + 8)) { // track the 8 bits inside the window
assert (col >= sketch.windowOffset);
final int row = rowCol >>> 6;
final byte oldBits = sketch.slidingWindow[row];
final byte newBits = (byte) (oldBits | (1 << (col - sketch.windowOffset)));
if (newBits != oldBits) {
sketch.slidingWindow[row] = newBits;
isNovel = true;
}
}
else { // track the surprising 1's "after" the window
assert col >= (sketch.windowOffset + 8);
isNovel = PairTable.maybeInsert(sketch.pairTable, rowCol); // normal logic
}
if (isNovel) {
sketch.numCoupons += 1;
updateHIP(sketch, rowCol);
final long c8post = sketch.numCoupons << 3;
if (c8post >= ((27L + w8pre) * k)) {
modifyOffset(sketch, sketch.windowOffset + 1);
assert (sketch.windowOffset >= 1) && (sketch.windowOffset <= 56);
final int w8post = sketch.windowOffset << 3;
assert c8post < ((27L + w8post) * k); // C < (K * 27/8) + (K * windowOffset)
}
}
} | java | private static void updateWindowed(final CpcSketch sketch, final int rowCol) {
assert ((sketch.windowOffset >= 0) && (sketch.windowOffset <= 56));
final int k = 1 << sketch.lgK;
final long c32pre = sketch.numCoupons << 5;
assert c32pre >= (3L * k); // C < 3K/32, in other words flavor >= HYBRID
final long c8pre = sketch.numCoupons << 3;
final int w8pre = sketch.windowOffset << 3;
assert c8pre < ((27L + w8pre) * k); // C < (K * 27/8) + (K * windowOffset)
boolean isNovel = false; //novel if new coupon
final int col = rowCol & 63;
if (col < sketch.windowOffset) { // track the surprising 0's "before" the window
isNovel = PairTable.maybeDelete(sketch.pairTable, rowCol); // inverted logic
}
else if (col < (sketch.windowOffset + 8)) { // track the 8 bits inside the window
assert (col >= sketch.windowOffset);
final int row = rowCol >>> 6;
final byte oldBits = sketch.slidingWindow[row];
final byte newBits = (byte) (oldBits | (1 << (col - sketch.windowOffset)));
if (newBits != oldBits) {
sketch.slidingWindow[row] = newBits;
isNovel = true;
}
}
else { // track the surprising 1's "after" the window
assert col >= (sketch.windowOffset + 8);
isNovel = PairTable.maybeInsert(sketch.pairTable, rowCol); // normal logic
}
if (isNovel) {
sketch.numCoupons += 1;
updateHIP(sketch, rowCol);
final long c8post = sketch.numCoupons << 3;
if (c8post >= ((27L + w8pre) * k)) {
modifyOffset(sketch, sketch.windowOffset + 1);
assert (sketch.windowOffset >= 1) && (sketch.windowOffset <= 56);
final int w8post = sketch.windowOffset << 3;
assert c8post < ((27L + w8post) * k); // C < (K * 27/8) + (K * windowOffset)
}
}
} | [
"private",
"static",
"void",
"updateWindowed",
"(",
"final",
"CpcSketch",
"sketch",
",",
"final",
"int",
"rowCol",
")",
"{",
"assert",
"(",
"(",
"sketch",
".",
"windowOffset",
">=",
"0",
")",
"&&",
"(",
"sketch",
".",
"windowOffset",
"<=",
"56",
")",
")"... | The flavor is HYBRID, PINNED, or SLIDING.
@param sketch the given sketch
@param rowCol the given rowCol | [
"The",
"flavor",
"is",
"HYBRID",
"PINNED",
"or",
"SLIDING",
"."
] | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/cpc/CpcSketch.java#L586-L627 |
ModeShape/modeshape | modeshape-schematic/src/main/java/org/modeshape/schematic/DocumentFactory.java | DocumentFactory.newDocument | public static EditableDocument newDocument( String name1,
Object value1,
String name2,
Object value2 ) {
return new DocumentEditor(new BasicDocument(name1, value1, name2, value2), DEFAULT_FACTORY);
} | java | public static EditableDocument newDocument( String name1,
Object value1,
String name2,
Object value2 ) {
return new DocumentEditor(new BasicDocument(name1, value1, name2, value2), DEFAULT_FACTORY);
} | [
"public",
"static",
"EditableDocument",
"newDocument",
"(",
"String",
"name1",
",",
"Object",
"value1",
",",
"String",
"name2",
",",
"Object",
"value2",
")",
"{",
"return",
"new",
"DocumentEditor",
"(",
"new",
"BasicDocument",
"(",
"name1",
",",
"value1",
",",... | Create a new editable document, initialized with two fields, that can be used as a new document entry in a SchematicDb or
as nested documents for other documents.
@param name1 the name of the first field in the resulting document; if null, the field will not be added to the returned
document
@param value1 the value of the first field in the resulting document
@param name2 the name of the second field in the resulting document; if null, the field will not be added to the returned
document
@param value2 the value of the second field in the resulting document
@return the editable document; never null | [
"Create",
"a",
"new",
"editable",
"document",
"initialized",
"with",
"two",
"fields",
"that",
"can",
"be",
"used",
"as",
"a",
"new",
"document",
"entry",
"in",
"a",
"SchematicDb",
"or",
"as",
"nested",
"documents",
"for",
"other",
"documents",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-schematic/src/main/java/org/modeshape/schematic/DocumentFactory.java#L86-L91 |
google/closure-compiler | src/com/google/javascript/jscomp/TypedScopeCreator.java | TypedScopeCreator.createScope | @Override
public TypedScope createScope(Node root, AbstractScope<?, ?> parent) {
checkArgument(parent == null || parent instanceof TypedScope);
TypedScope typedParent = (TypedScope) parent;
TypedScope scope = memoized.get(root);
if (scope != null) {
checkState(typedParent == scope.getParent());
} else {
scope = createScopeInternal(root, typedParent);
memoized.put(root, scope);
}
return scope;
} | java | @Override
public TypedScope createScope(Node root, AbstractScope<?, ?> parent) {
checkArgument(parent == null || parent instanceof TypedScope);
TypedScope typedParent = (TypedScope) parent;
TypedScope scope = memoized.get(root);
if (scope != null) {
checkState(typedParent == scope.getParent());
} else {
scope = createScopeInternal(root, typedParent);
memoized.put(root, scope);
}
return scope;
} | [
"@",
"Override",
"public",
"TypedScope",
"createScope",
"(",
"Node",
"root",
",",
"AbstractScope",
"<",
"?",
",",
"?",
">",
"parent",
")",
"{",
"checkArgument",
"(",
"parent",
"==",
"null",
"||",
"parent",
"instanceof",
"TypedScope",
")",
";",
"TypedScope",
... | Creates a scope with all types declared. Declares newly discovered types
and type properties in the type registry. | [
"Creates",
"a",
"scope",
"with",
"all",
"types",
"declared",
".",
"Declares",
"newly",
"discovered",
"types",
"and",
"type",
"properties",
"in",
"the",
"type",
"registry",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedScopeCreator.java#L366-L379 |
hankcs/HanLP | src/main/java/com/hankcs/hanlp/mining/cluster/ClusterAnalyzer.java | ClusterAnalyzer.refined_vector_value | double refined_vector_value(SparseVector composite, SparseVector vec, int sign)
{
double sum = 0.0;
for (Map.Entry<Integer, Double> entry : vec.entrySet())
{
sum += Math.pow(entry.getValue(), 2) + sign * 2 * composite.get(entry.getKey()) * entry.getValue();
}
return sum;
} | java | double refined_vector_value(SparseVector composite, SparseVector vec, int sign)
{
double sum = 0.0;
for (Map.Entry<Integer, Double> entry : vec.entrySet())
{
sum += Math.pow(entry.getValue(), 2) + sign * 2 * composite.get(entry.getKey()) * entry.getValue();
}
return sum;
} | [
"double",
"refined_vector_value",
"(",
"SparseVector",
"composite",
",",
"SparseVector",
"vec",
",",
"int",
"sign",
")",
"{",
"double",
"sum",
"=",
"0.0",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"Integer",
",",
"Double",
">",
"entry",
":",
"vec",
".",... | c^2 - 2c(a + c) + d^2 - 2d(b + d)
@param composite (a+c,b+d)
@param vec (c,d)
@param sign
@return | [
"c^2",
"-",
"2c",
"(",
"a",
"+",
"c",
")",
"+",
"d^2",
"-",
"2d",
"(",
"b",
"+",
"d",
")"
] | train | https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/mining/cluster/ClusterAnalyzer.java#L339-L347 |
roboconf/roboconf-platform | core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java | Utils.logException | public static void logException( Logger logger, Throwable t ) {
logException( logger, Level.FINEST, t );
} | java | public static void logException( Logger logger, Throwable t ) {
logException( logger, Level.FINEST, t );
} | [
"public",
"static",
"void",
"logException",
"(",
"Logger",
"logger",
",",
"Throwable",
"t",
")",
"{",
"logException",
"(",
"logger",
",",
"Level",
".",
"FINEST",
",",
"t",
")",
";",
"}"
] | Logs an exception with the given logger and the FINEST level.
@param logger the logger
@param t an exception or a throwable | [
"Logs",
"an",
"exception",
"with",
"the",
"given",
"logger",
"and",
"the",
"FINEST",
"level",
"."
] | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java#L1136-L1138 |
JodaOrg/joda-time | src/main/java/org/joda/time/Minutes.java | Minutes.minutesBetween | public static Minutes minutesBetween(ReadableInstant start, ReadableInstant end) {
int amount = BaseSingleFieldPeriod.between(start, end, DurationFieldType.minutes());
return Minutes.minutes(amount);
} | java | public static Minutes minutesBetween(ReadableInstant start, ReadableInstant end) {
int amount = BaseSingleFieldPeriod.between(start, end, DurationFieldType.minutes());
return Minutes.minutes(amount);
} | [
"public",
"static",
"Minutes",
"minutesBetween",
"(",
"ReadableInstant",
"start",
",",
"ReadableInstant",
"end",
")",
"{",
"int",
"amount",
"=",
"BaseSingleFieldPeriod",
".",
"between",
"(",
"start",
",",
"end",
",",
"DurationFieldType",
".",
"minutes",
"(",
")"... | Creates a <code>Minutes</code> representing the number of whole minutes
between the two specified datetimes.
@param start the start instant, must not be null
@param end the end instant, must not be null
@return the period in minutes
@throws IllegalArgumentException if the instants are null or invalid | [
"Creates",
"a",
"<code",
">",
"Minutes<",
"/",
"code",
">",
"representing",
"the",
"number",
"of",
"whole",
"minutes",
"between",
"the",
"two",
"specified",
"datetimes",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/Minutes.java#L100-L103 |
forge/core | resources/api/src/main/java/org/jboss/forge/addon/resource/util/ResourceUtil.java | ResourceUtil.getDigest | public static byte[] getDigest(Resource<?> resource, MessageDigest digest)
{
try (InputStream stream = resource.getResourceInputStream();
DigestInputStream digestStream = new DigestInputStream(stream, digest))
{
byte[] buffer = new byte[16384];
while (digestStream.read(buffer, 0, buffer.length) != -1)
{
}
}
catch (IOException e)
{
throw new IllegalStateException("Error calculating digest for resource [" + resource.getFullyQualifiedName()
+ "]", e);
}
return digest.digest();
} | java | public static byte[] getDigest(Resource<?> resource, MessageDigest digest)
{
try (InputStream stream = resource.getResourceInputStream();
DigestInputStream digestStream = new DigestInputStream(stream, digest))
{
byte[] buffer = new byte[16384];
while (digestStream.read(buffer, 0, buffer.length) != -1)
{
}
}
catch (IOException e)
{
throw new IllegalStateException("Error calculating digest for resource [" + resource.getFullyQualifiedName()
+ "]", e);
}
return digest.digest();
} | [
"public",
"static",
"byte",
"[",
"]",
"getDigest",
"(",
"Resource",
"<",
"?",
">",
"resource",
",",
"MessageDigest",
"digest",
")",
"{",
"try",
"(",
"InputStream",
"stream",
"=",
"resource",
".",
"getResourceInputStream",
"(",
")",
";",
"DigestInputStream",
... | Returns the {@link Byte} array message digest of {@link #getResourceInputStream()} using the given
{@link MessageDigest}. | [
"Returns",
"the",
"{"
] | train | https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/resources/api/src/main/java/org/jboss/forge/addon/resource/util/ResourceUtil.java#L55-L71 |
looly/hutool | hutool-db/src/main/java/cn/hutool/db/StatementUtil.java | StatementUtil.prepareStatement | public static PreparedStatement prepareStatement(Connection conn, String sql, Object... params) throws SQLException {
Assert.notBlank(sql, "Sql String must be not blank!");
sql = sql.trim();
SqlLog.INSTASNCE.log(sql, params);
PreparedStatement ps;
if (StrUtil.startWithIgnoreCase(sql, "insert")) {
// 插入默认返回主键
ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
} else {
ps = conn.prepareStatement(sql);
}
return fillParams(ps, params);
} | java | public static PreparedStatement prepareStatement(Connection conn, String sql, Object... params) throws SQLException {
Assert.notBlank(sql, "Sql String must be not blank!");
sql = sql.trim();
SqlLog.INSTASNCE.log(sql, params);
PreparedStatement ps;
if (StrUtil.startWithIgnoreCase(sql, "insert")) {
// 插入默认返回主键
ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
} else {
ps = conn.prepareStatement(sql);
}
return fillParams(ps, params);
} | [
"public",
"static",
"PreparedStatement",
"prepareStatement",
"(",
"Connection",
"conn",
",",
"String",
"sql",
",",
"Object",
"...",
"params",
")",
"throws",
"SQLException",
"{",
"Assert",
".",
"notBlank",
"(",
"sql",
",",
"\"Sql String must be not blank!\"",
")",
... | 创建{@link PreparedStatement}
@param conn 数据库连接
@param sql SQL语句,使用"?"做为占位符
@param params "?"对应参数列表
@return {@link PreparedStatement}
@throws SQLException SQL异常
@since 3.2.3 | [
"创建",
"{",
"@link",
"PreparedStatement",
"}"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/StatementUtil.java#L138-L151 |
apache/flink | flink-core/src/main/java/org/apache/flink/core/fs/FileSystem.java | FileSystem.loadHadoopFsFactory | private static FileSystemFactory loadHadoopFsFactory() {
final ClassLoader cl = FileSystem.class.getClassLoader();
// first, see if the Flink runtime classes are available
final Class<? extends FileSystemFactory> factoryClass;
try {
factoryClass = Class
.forName("org.apache.flink.runtime.fs.hdfs.HadoopFsFactory", false, cl)
.asSubclass(FileSystemFactory.class);
}
catch (ClassNotFoundException e) {
LOG.info("No Flink runtime dependency present. " +
"The extended set of supported File Systems via Hadoop is not available.");
return new UnsupportedSchemeFactory("Flink runtime classes missing in classpath/dependencies.");
}
catch (Exception | LinkageError e) {
LOG.warn("Flink's Hadoop file system factory could not be loaded", e);
return new UnsupportedSchemeFactory("Flink's Hadoop file system factory could not be loaded", e);
}
// check (for eager and better exception messages) if the Hadoop classes are available here
try {
Class.forName("org.apache.hadoop.conf.Configuration", false, cl);
Class.forName("org.apache.hadoop.fs.FileSystem", false, cl);
}
catch (ClassNotFoundException e) {
LOG.info("Hadoop is not in the classpath/dependencies. " +
"The extended set of supported File Systems via Hadoop is not available.");
return new UnsupportedSchemeFactory("Hadoop is not in the classpath/dependencies.");
}
// Create the factory.
try {
return factoryClass.newInstance();
}
catch (Exception | LinkageError e) {
LOG.warn("Flink's Hadoop file system factory could not be created", e);
return new UnsupportedSchemeFactory("Flink's Hadoop file system factory could not be created", e);
}
} | java | private static FileSystemFactory loadHadoopFsFactory() {
final ClassLoader cl = FileSystem.class.getClassLoader();
// first, see if the Flink runtime classes are available
final Class<? extends FileSystemFactory> factoryClass;
try {
factoryClass = Class
.forName("org.apache.flink.runtime.fs.hdfs.HadoopFsFactory", false, cl)
.asSubclass(FileSystemFactory.class);
}
catch (ClassNotFoundException e) {
LOG.info("No Flink runtime dependency present. " +
"The extended set of supported File Systems via Hadoop is not available.");
return new UnsupportedSchemeFactory("Flink runtime classes missing in classpath/dependencies.");
}
catch (Exception | LinkageError e) {
LOG.warn("Flink's Hadoop file system factory could not be loaded", e);
return new UnsupportedSchemeFactory("Flink's Hadoop file system factory could not be loaded", e);
}
// check (for eager and better exception messages) if the Hadoop classes are available here
try {
Class.forName("org.apache.hadoop.conf.Configuration", false, cl);
Class.forName("org.apache.hadoop.fs.FileSystem", false, cl);
}
catch (ClassNotFoundException e) {
LOG.info("Hadoop is not in the classpath/dependencies. " +
"The extended set of supported File Systems via Hadoop is not available.");
return new UnsupportedSchemeFactory("Hadoop is not in the classpath/dependencies.");
}
// Create the factory.
try {
return factoryClass.newInstance();
}
catch (Exception | LinkageError e) {
LOG.warn("Flink's Hadoop file system factory could not be created", e);
return new UnsupportedSchemeFactory("Flink's Hadoop file system factory could not be created", e);
}
} | [
"private",
"static",
"FileSystemFactory",
"loadHadoopFsFactory",
"(",
")",
"{",
"final",
"ClassLoader",
"cl",
"=",
"FileSystem",
".",
"class",
".",
"getClassLoader",
"(",
")",
";",
"// first, see if the Flink runtime classes are available",
"final",
"Class",
"<",
"?",
... | Utility loader for the Hadoop file system factory.
We treat the Hadoop FS factory in a special way, because we use it as a catch
all for file systems schemes not supported directly in Flink.
<p>This method does a set of eager checks for availability of certain classes, to
be able to give better error messages. | [
"Utility",
"loader",
"for",
"the",
"Hadoop",
"file",
"system",
"factory",
".",
"We",
"treat",
"the",
"Hadoop",
"FS",
"factory",
"in",
"a",
"special",
"way",
"because",
"we",
"use",
"it",
"as",
"a",
"catch",
"all",
"for",
"file",
"systems",
"schemes",
"no... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/core/fs/FileSystem.java#L1038-L1077 |
ldapchai/ldapchai | src/main/java/com/novell/ldapchai/util/StringHelper.java | StringHelper.convertStrToInt | public static int convertStrToInt( final String string, final int defaultValue )
{
if ( string == null )
{
return defaultValue;
}
try
{
return Integer.parseInt( string );
}
catch ( Exception e )
{
return defaultValue;
}
} | java | public static int convertStrToInt( final String string, final int defaultValue )
{
if ( string == null )
{
return defaultValue;
}
try
{
return Integer.parseInt( string );
}
catch ( Exception e )
{
return defaultValue;
}
} | [
"public",
"static",
"int",
"convertStrToInt",
"(",
"final",
"String",
"string",
",",
"final",
"int",
"defaultValue",
")",
"{",
"if",
"(",
"string",
"==",
"null",
")",
"{",
"return",
"defaultValue",
";",
"}",
"try",
"{",
"return",
"Integer",
".",
"parseInt"... | Convert a string to an int value. If an error occurs during the conversion,
the default value is returned instead. Unlike the {@link Integer#parseInt(String)}
method, this method will not throw an exception.
@param string value to test
@param defaultValue value to return in case of difficulting converting.
@return the int value contained in the string, otherwise the default value. | [
"Convert",
"a",
"string",
"to",
"an",
"int",
"value",
".",
"If",
"an",
"error",
"occurs",
"during",
"the",
"conversion",
"the",
"default",
"value",
"is",
"returned",
"instead",
".",
"Unlike",
"the",
"{",
"@link",
"Integer#parseInt",
"(",
"String",
")",
"}"... | train | https://github.com/ldapchai/ldapchai/blob/a6d4b5dbfa4e270db0ce70892512cbe39e64b874/src/main/java/com/novell/ldapchai/util/StringHelper.java#L64-L79 |
mapbox/mapbox-java | services-directions/src/main/java/com/mapbox/api/directions/v5/MapboxDirections.java | MapboxDirections.enqueueCall | @Override
public void enqueueCall(final Callback<DirectionsResponse> callback) {
getCall().enqueue(new Callback<DirectionsResponse>() {
@Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
DirectionsResponseFactory factory = new DirectionsResponseFactory(MapboxDirections.this);
Response<DirectionsResponse> generatedResponse = factory.generate(response);
callback.onResponse(call, generatedResponse);
}
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
callback.onFailure(call, throwable);
}
});
} | java | @Override
public void enqueueCall(final Callback<DirectionsResponse> callback) {
getCall().enqueue(new Callback<DirectionsResponse>() {
@Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
DirectionsResponseFactory factory = new DirectionsResponseFactory(MapboxDirections.this);
Response<DirectionsResponse> generatedResponse = factory.generate(response);
callback.onResponse(call, generatedResponse);
}
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
callback.onFailure(call, throwable);
}
});
} | [
"@",
"Override",
"public",
"void",
"enqueueCall",
"(",
"final",
"Callback",
"<",
"DirectionsResponse",
">",
"callback",
")",
"{",
"getCall",
"(",
")",
".",
"enqueue",
"(",
"new",
"Callback",
"<",
"DirectionsResponse",
">",
"(",
")",
"{",
"@",
"Override",
"... | Wrapper method for Retrofits {@link Call#enqueue(Callback)} call returning a response specific
to the Directions API. Use this method to make a directions request on the Main Thread.
@param callback a {@link Callback} which is used once the {@link DirectionsResponse} is
created.
@since 1.0.0 | [
"Wrapper",
"method",
"for",
"Retrofits",
"{",
"@link",
"Call#enqueue",
"(",
"Callback",
")",
"}",
"call",
"returning",
"a",
"response",
"specific",
"to",
"the",
"Directions",
"API",
".",
"Use",
"this",
"method",
"to",
"make",
"a",
"directions",
"request",
"o... | train | https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-directions/src/main/java/com/mapbox/api/directions/v5/MapboxDirections.java#L170-L185 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.purgeDeletedKeyAsync | public ServiceFuture<Void> purgeDeletedKeyAsync(String vaultBaseUrl, String keyName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(purgeDeletedKeyWithServiceResponseAsync(vaultBaseUrl, keyName), serviceCallback);
} | java | public ServiceFuture<Void> purgeDeletedKeyAsync(String vaultBaseUrl, String keyName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(purgeDeletedKeyWithServiceResponseAsync(vaultBaseUrl, keyName), serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"Void",
">",
"purgeDeletedKeyAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"keyName",
",",
"final",
"ServiceCallback",
"<",
"Void",
">",
"serviceCallback",
")",
"{",
"return",
"ServiceFuture",
".",
"fromResponse",
"(",
"purg... | Permanently deletes the specified key.
The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the keys/purge permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param keyName The name of the key
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Permanently",
"deletes",
"the",
"specified",
"key",
".",
"The",
"Purge",
"Deleted",
"Key",
"operation",
"is",
"applicable",
"for",
"soft",
"-",
"delete",
"enabled",
"vaults",
".",
"While",
"the",
"operation",
"can",
"be",
"invoked",
"on",
"any",
"vault",
"i... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L3159-L3161 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/util/StringUtils.java | StringUtils.printToFile | public static void printToFile(String filename, String message, boolean append) {
printToFile(new File(filename), message, append);
} | java | public static void printToFile(String filename, String message, boolean append) {
printToFile(new File(filename), message, append);
} | [
"public",
"static",
"void",
"printToFile",
"(",
"String",
"filename",
",",
"String",
"message",
",",
"boolean",
"append",
")",
"{",
"printToFile",
"(",
"new",
"File",
"(",
"filename",
")",
",",
"message",
",",
"append",
")",
";",
"}"
] | Prints to a file. If the file already exists, appends if
<code>append=true</code>, and overwrites if <code>append=false</code> | [
"Prints",
"to",
"a",
"file",
".",
"If",
"the",
"file",
"already",
"exists",
"appends",
"if",
"<code",
">",
"append",
"=",
"true<",
"/",
"code",
">",
"and",
"overwrites",
"if",
"<code",
">",
"append",
"=",
"false<",
"/",
"code",
">"
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/StringUtils.java#L960-L962 |
junit-team/junit4 | src/main/java/org/junit/Assert.java | Assert.assertEquals | public static void assertEquals(String message, Object expected,
Object actual) {
if (equalsRegardingNull(expected, actual)) {
return;
}
if (expected instanceof String && actual instanceof String) {
String cleanMessage = message == null ? "" : message;
throw new ComparisonFailure(cleanMessage, (String) expected,
(String) actual);
} else {
failNotEquals(message, expected, actual);
}
} | java | public static void assertEquals(String message, Object expected,
Object actual) {
if (equalsRegardingNull(expected, actual)) {
return;
}
if (expected instanceof String && actual instanceof String) {
String cleanMessage = message == null ? "" : message;
throw new ComparisonFailure(cleanMessage, (String) expected,
(String) actual);
} else {
failNotEquals(message, expected, actual);
}
} | [
"public",
"static",
"void",
"assertEquals",
"(",
"String",
"message",
",",
"Object",
"expected",
",",
"Object",
"actual",
")",
"{",
"if",
"(",
"equalsRegardingNull",
"(",
"expected",
",",
"actual",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"expected",
... | Asserts that two objects are equal. If they are not, an
{@link AssertionError} is thrown with the given message. If
<code>expected</code> and <code>actual</code> are <code>null</code>,
they are considered equal.
@param message the identifying message for the {@link AssertionError} (<code>null</code>
okay)
@param expected expected value
@param actual actual value | [
"Asserts",
"that",
"two",
"objects",
"are",
"equal",
".",
"If",
"they",
"are",
"not",
"an",
"{",
"@link",
"AssertionError",
"}",
"is",
"thrown",
"with",
"the",
"given",
"message",
".",
"If",
"<code",
">",
"expected<",
"/",
"code",
">",
"and",
"<code",
... | train | https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/Assert.java#L110-L122 |
Cornutum/tcases | tcases-lib/src/main/java/org/cornutum/tcases/generator/TupleGenerator.java | TupleGenerator.getValidTupleSet | private VarTupleSet getValidTupleSet( RandSeq randSeq, FunctionInputDef inputDef)
{
List<Tuple> validTuples = new ArrayList<Tuple>();
// Get tuple sets required for each specified combiner, ordered for "greedy" processing, i.e. biggest tuples first.
// For this purpose, "all permutations" is considered the maximum tuple size, even though in practice it might not be.
getCombiners()
.stream()
.sorted( byTupleSize_)
.forEach( combiner -> validTuples.addAll( RandSeq.order( randSeq, combiner.getTuples( inputDef))));
// For all input variables that do not belong to a combiner tuple set...
List<VarDef> uncombinedVars =
IteratorUtils.toList(
IteratorUtils.filteredIterator(
new VarDefIterator( inputDef),
this::isUncombined));
if( !uncombinedVars.isEmpty())
{
// ... add the default tuples.
int defaultTupleSize = getDefaultTupleSize();
int varCount = uncombinedVars.size();
validTuples.addAll(
RandSeq.order(
randSeq,
getUncombinedTuples(
uncombinedVars,
Math.min(
varCount,
defaultTupleSize < 1? varCount : defaultTupleSize))));
}
return new VarTupleSet( validTuples);
} | java | private VarTupleSet getValidTupleSet( RandSeq randSeq, FunctionInputDef inputDef)
{
List<Tuple> validTuples = new ArrayList<Tuple>();
// Get tuple sets required for each specified combiner, ordered for "greedy" processing, i.e. biggest tuples first.
// For this purpose, "all permutations" is considered the maximum tuple size, even though in practice it might not be.
getCombiners()
.stream()
.sorted( byTupleSize_)
.forEach( combiner -> validTuples.addAll( RandSeq.order( randSeq, combiner.getTuples( inputDef))));
// For all input variables that do not belong to a combiner tuple set...
List<VarDef> uncombinedVars =
IteratorUtils.toList(
IteratorUtils.filteredIterator(
new VarDefIterator( inputDef),
this::isUncombined));
if( !uncombinedVars.isEmpty())
{
// ... add the default tuples.
int defaultTupleSize = getDefaultTupleSize();
int varCount = uncombinedVars.size();
validTuples.addAll(
RandSeq.order(
randSeq,
getUncombinedTuples(
uncombinedVars,
Math.min(
varCount,
defaultTupleSize < 1? varCount : defaultTupleSize))));
}
return new VarTupleSet( validTuples);
} | [
"private",
"VarTupleSet",
"getValidTupleSet",
"(",
"RandSeq",
"randSeq",
",",
"FunctionInputDef",
"inputDef",
")",
"{",
"List",
"<",
"Tuple",
">",
"validTuples",
"=",
"new",
"ArrayList",
"<",
"Tuple",
">",
"(",
")",
";",
"// Get tuple sets required for each specifie... | Returns the all valid input tuples required for generated test cases. | [
"Returns",
"the",
"all",
"valid",
"input",
"tuples",
"required",
"for",
"generated",
"test",
"cases",
"."
] | train | https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-lib/src/main/java/org/cornutum/tcases/generator/TupleGenerator.java#L623-L657 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/CollectionReference.java | CollectionReference.getParent | @Nullable
public DocumentReference getParent() {
ResourcePath parent = path.getParent();
return parent.isDocument() ? new DocumentReference(firestore, parent) : null;
} | java | @Nullable
public DocumentReference getParent() {
ResourcePath parent = path.getParent();
return parent.isDocument() ? new DocumentReference(firestore, parent) : null;
} | [
"@",
"Nullable",
"public",
"DocumentReference",
"getParent",
"(",
")",
"{",
"ResourcePath",
"parent",
"=",
"path",
".",
"getParent",
"(",
")",
";",
"return",
"parent",
".",
"isDocument",
"(",
")",
"?",
"new",
"DocumentReference",
"(",
"firestore",
",",
"pare... | Returns a DocumentReference to the containing Document if this is a subcollection, else null.
@return A DocumentReference pointing to the parent document. | [
"Returns",
"a",
"DocumentReference",
"to",
"the",
"containing",
"Document",
"if",
"this",
"is",
"a",
"subcollection",
"else",
"null",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/CollectionReference.java#L70-L74 |
fommil/matrix-toolkits-java | src/main/java/no/uib/cipr/matrix/sparse/Arrays.java | Arrays.binarySearchGreater | public static int binarySearchGreater(int[] index, int key, int begin,
int end) {
return binarySearchInterval(index, key, begin, end, true);
} | java | public static int binarySearchGreater(int[] index, int key, int begin,
int end) {
return binarySearchInterval(index, key, begin, end, true);
} | [
"public",
"static",
"int",
"binarySearchGreater",
"(",
"int",
"[",
"]",
"index",
",",
"int",
"key",
",",
"int",
"begin",
",",
"int",
"end",
")",
"{",
"return",
"binarySearchInterval",
"(",
"index",
",",
"key",
",",
"begin",
",",
"end",
",",
"true",
")"... | Searches for a key in a sorted array, and returns an index to an element
which is greater than or equal key.
@param index
Sorted array of integers
@param key
Search for something equal or greater
@param begin
Start posisiton in the index
@param end
One past the end position in the index
@return end if nothing greater or equal was found, else an index
satisfying the search criteria | [
"Searches",
"for",
"a",
"key",
"in",
"a",
"sorted",
"array",
"and",
"returns",
"an",
"index",
"to",
"an",
"element",
"which",
"is",
"greater",
"than",
"or",
"equal",
"key",
"."
] | train | https://github.com/fommil/matrix-toolkits-java/blob/6157618bc86bcda3749af2a60bf869d8f3292960/src/main/java/no/uib/cipr/matrix/sparse/Arrays.java#L51-L54 |
box/box-java-sdk | src/main/java/com/box/sdk/BoxMetadataFilter.java | BoxMetadataFilter.addDateRangeFilter | public void addDateRangeFilter(String key, DateRange dateRange) {
JsonObject opObj = new JsonObject();
if (dateRange.getFromDate() != null) {
String dateGtString = BoxDateFormat.format(dateRange.getFromDate());
//workaround replacing + and - 000 at the end with 'Z'
dateGtString = dateGtString.replaceAll("(\\+|-)(?!-\\|?!\\+)\\d+$", "Z");
opObj.add("gt", dateGtString);
}
if (dateRange.getToDate() != null) {
String dateLtString = BoxDateFormat.format(dateRange.getToDate());
//workaround replacing + and - 000 at the end with 'Z'
dateLtString = dateLtString.replaceAll("(\\+|-)(?!-\\|?!\\+)\\d+$", "Z");
opObj.add("lt", dateLtString);
}
this.filtersList.add(key, opObj);
} | java | public void addDateRangeFilter(String key, DateRange dateRange) {
JsonObject opObj = new JsonObject();
if (dateRange.getFromDate() != null) {
String dateGtString = BoxDateFormat.format(dateRange.getFromDate());
//workaround replacing + and - 000 at the end with 'Z'
dateGtString = dateGtString.replaceAll("(\\+|-)(?!-\\|?!\\+)\\d+$", "Z");
opObj.add("gt", dateGtString);
}
if (dateRange.getToDate() != null) {
String dateLtString = BoxDateFormat.format(dateRange.getToDate());
//workaround replacing + and - 000 at the end with 'Z'
dateLtString = dateLtString.replaceAll("(\\+|-)(?!-\\|?!\\+)\\d+$", "Z");
opObj.add("lt", dateLtString);
}
this.filtersList.add(key, opObj);
} | [
"public",
"void",
"addDateRangeFilter",
"(",
"String",
"key",
",",
"DateRange",
"dateRange",
")",
"{",
"JsonObject",
"opObj",
"=",
"new",
"JsonObject",
"(",
")",
";",
"if",
"(",
"dateRange",
".",
"getFromDate",
"(",
")",
"!=",
"null",
")",
"{",
"String",
... | Set a filter to the filterList, example: key=documentNumber, gt : "", lt : "".
@param key the key that the filter should be looking for.
@param dateRange the date range that is start and end dates | [
"Set",
"a",
"filter",
"to",
"the",
"filterList",
"example",
":",
"key",
"=",
"documentNumber",
"gt",
":",
"lt",
":",
"."
] | train | https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxMetadataFilter.java#L73-L91 |
jbundle/jbundle | base/model/src/main/java/org/jbundle/base/model/Utility.java | Utility.copyTreeToNode | public static Node copyTreeToNode(Node tree, Node node)
{
DOMResult result = new DOMResult(node);
if (Utility.copyTreeToResult(tree, result))
return node.getLastChild();
else
return null; // Failure
} | java | public static Node copyTreeToNode(Node tree, Node node)
{
DOMResult result = new DOMResult(node);
if (Utility.copyTreeToResult(tree, result))
return node.getLastChild();
else
return null; // Failure
} | [
"public",
"static",
"Node",
"copyTreeToNode",
"(",
"Node",
"tree",
",",
"Node",
"node",
")",
"{",
"DOMResult",
"result",
"=",
"new",
"DOMResult",
"(",
"node",
")",
";",
"if",
"(",
"Utility",
".",
"copyTreeToResult",
"(",
"tree",
",",
"result",
")",
")",
... | Copy DOM tree to a SOAP tree.
@param tree
@param node
@return The parent of the new child node. | [
"Copy",
"DOM",
"tree",
"to",
"a",
"SOAP",
"tree",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/model/src/main/java/org/jbundle/base/model/Utility.java#L768-L775 |
alkacon/opencms-core | src/org/opencms/ui/apps/logfile/CmsLogFileView.java | CmsLogFileView.selectLogFile | private void selectLogFile(List<Appender> appender, String filePath) {
for (Appender app : appender) {
String fileName = CmsLogFileApp.getFileName(app);
if ((fileName != null) && fileName.equals(filePath)) {
m_logfile.select(fileName);
return;
}
}
if (!appender.isEmpty()) {
Appender app = appender.get(0);
String fileName = CmsLogFileApp.getFileName(app);
if (fileName != null) {
m_logfile.select(fileName); //Default, take file from root appender
}
}
} | java | private void selectLogFile(List<Appender> appender, String filePath) {
for (Appender app : appender) {
String fileName = CmsLogFileApp.getFileName(app);
if ((fileName != null) && fileName.equals(filePath)) {
m_logfile.select(fileName);
return;
}
}
if (!appender.isEmpty()) {
Appender app = appender.get(0);
String fileName = CmsLogFileApp.getFileName(app);
if (fileName != null) {
m_logfile.select(fileName); //Default, take file from root appender
}
}
} | [
"private",
"void",
"selectLogFile",
"(",
"List",
"<",
"Appender",
">",
"appender",
",",
"String",
"filePath",
")",
"{",
"for",
"(",
"Appender",
"app",
":",
"appender",
")",
"{",
"String",
"fileName",
"=",
"CmsLogFileApp",
".",
"getFileName",
"(",
"app",
")... | Selects the currently set log file.<p>
@param appender all given appender
@param filePath of log file | [
"Selects",
"the",
"currently",
"set",
"log",
"file",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/logfile/CmsLogFileView.java#L237-L254 |
steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/FstInputOutput.java | FstInputOutput.writeFstToBinaryStream | public static void writeFstToBinaryStream(Fst fst, ObjectOutput out) throws IOException {
out.writeInt(CURRENT_VERSION);
writeStringMap(fst.getInputSymbols(), out);
writeStringMap(fst.getOutputSymbols(), out);
out.writeBoolean(fst.isUsingStateSymbols()); // whether or not we used a state symbol table
if (fst.isUsingStateSymbols()) {
writeStringMap(fst.getStateSymbols(), out);
}
out.writeInt(fst.getStartState().getId());
out.writeObject(fst.getSemiring());
out.writeInt(fst.getStateCount());
Map<State, Integer> stateMap = new IdentityHashMap<>(fst.getStateCount());
for (int i = 0; i < fst.getStateCount(); i++) {
State s = fst.getState(i);
out.writeInt(s.getArcCount());
out.writeDouble(s.getFinalWeight());
out.writeInt(s.getId());
stateMap.put(s, i);
}
int numStates = fst.getStateCount();
for (int i = 0; i < numStates; i++) {
State s = fst.getState(i);
int numArcs = s.getArcCount();
for (int j = 0; j < numArcs; j++) {
Arc a = s.getArc(j);
out.writeInt(a.getIlabel());
out.writeInt(a.getOlabel());
out.writeDouble(a.getWeight());
out.writeInt(stateMap.get(a.getNextState()));
}
}
} | java | public static void writeFstToBinaryStream(Fst fst, ObjectOutput out) throws IOException {
out.writeInt(CURRENT_VERSION);
writeStringMap(fst.getInputSymbols(), out);
writeStringMap(fst.getOutputSymbols(), out);
out.writeBoolean(fst.isUsingStateSymbols()); // whether or not we used a state symbol table
if (fst.isUsingStateSymbols()) {
writeStringMap(fst.getStateSymbols(), out);
}
out.writeInt(fst.getStartState().getId());
out.writeObject(fst.getSemiring());
out.writeInt(fst.getStateCount());
Map<State, Integer> stateMap = new IdentityHashMap<>(fst.getStateCount());
for (int i = 0; i < fst.getStateCount(); i++) {
State s = fst.getState(i);
out.writeInt(s.getArcCount());
out.writeDouble(s.getFinalWeight());
out.writeInt(s.getId());
stateMap.put(s, i);
}
int numStates = fst.getStateCount();
for (int i = 0; i < numStates; i++) {
State s = fst.getState(i);
int numArcs = s.getArcCount();
for (int j = 0; j < numArcs; j++) {
Arc a = s.getArc(j);
out.writeInt(a.getIlabel());
out.writeInt(a.getOlabel());
out.writeDouble(a.getWeight());
out.writeInt(stateMap.get(a.getNextState()));
}
}
} | [
"public",
"static",
"void",
"writeFstToBinaryStream",
"(",
"Fst",
"fst",
",",
"ObjectOutput",
"out",
")",
"throws",
"IOException",
"{",
"out",
".",
"writeInt",
"(",
"CURRENT_VERSION",
")",
";",
"writeStringMap",
"(",
"fst",
".",
"getInputSymbols",
"(",
")",
",... | Serializes the current Fst instance to an ObjectOutput
@param out the ObjectOutput. It should be already be initialized by the caller. | [
"Serializes",
"the",
"current",
"Fst",
"instance",
"to",
"an",
"ObjectOutput"
] | train | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/FstInputOutput.java#L186-L220 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/SimpleDateFormat.java | SimpleDateFormat.subParse | private int subParse(String text, int start, char ch, int count,
boolean obeyCount, boolean allowNegative,
boolean[] ambiguousYear, Calendar cal,
MessageFormat numericLeapMonthFormatter, Output<TimeType> tzTimeType) {
return subParse(text, start, ch, count, obeyCount, allowNegative, ambiguousYear, cal, null, null, null);
} | java | private int subParse(String text, int start, char ch, int count,
boolean obeyCount, boolean allowNegative,
boolean[] ambiguousYear, Calendar cal,
MessageFormat numericLeapMonthFormatter, Output<TimeType> tzTimeType) {
return subParse(text, start, ch, count, obeyCount, allowNegative, ambiguousYear, cal, null, null, null);
} | [
"private",
"int",
"subParse",
"(",
"String",
"text",
",",
"int",
"start",
",",
"char",
"ch",
",",
"int",
"count",
",",
"boolean",
"obeyCount",
",",
"boolean",
"allowNegative",
",",
"boolean",
"[",
"]",
"ambiguousYear",
",",
"Calendar",
"cal",
",",
"Message... | Overloading to provide default argument (null) for day period. | [
"Overloading",
"to",
"provide",
"default",
"argument",
"(",
"null",
")",
"for",
"day",
"period",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/SimpleDateFormat.java#L3048-L3053 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/util/ArrayUtil.java | ArrayUtil.writeBytes | public static void writeBytes(byte b[], int offset, byte[] value) {
System.arraycopy(value, 0, b, offset, value.length);
} | java | public static void writeBytes(byte b[], int offset, byte[] value) {
System.arraycopy(value, 0, b, offset, value.length);
} | [
"public",
"static",
"void",
"writeBytes",
"(",
"byte",
"b",
"[",
"]",
",",
"int",
"offset",
",",
"byte",
"[",
"]",
"value",
")",
"{",
"System",
".",
"arraycopy",
"(",
"value",
",",
"0",
",",
"b",
",",
"offset",
",",
"value",
".",
"length",
")",
"... | Serializes a byte[] into a byte array at a specific offset
@param b byte array in which to write a byte[] value.
@param offset offset within byte array to start writing.
@param value byte[] to write to byte array. | [
"Serializes",
"a",
"byte",
"[]",
"into",
"a",
"byte",
"array",
"at",
"a",
"specific",
"offset"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/util/ArrayUtil.java#L160-L162 |
LearnLib/automatalib | util/src/main/java/net/automatalib/util/minimizer/TransitionLabel.java | TransitionLabel.addToSet | public boolean addToSet(State<S, EP> state) {
boolean first = list.isEmpty();
if (first || !setContents.get(state.getId())) {
list.add(state);
setContents.set(state.getId());
}
return first;
} | java | public boolean addToSet(State<S, EP> state) {
boolean first = list.isEmpty();
if (first || !setContents.get(state.getId())) {
list.add(state);
setContents.set(state.getId());
}
return first;
} | [
"public",
"boolean",
"addToSet",
"(",
"State",
"<",
"S",
",",
"EP",
">",
"state",
")",
"{",
"boolean",
"first",
"=",
"list",
".",
"isEmpty",
"(",
")",
";",
"if",
"(",
"first",
"||",
"!",
"setContents",
".",
"get",
"(",
"state",
".",
"getId",
"(",
... | Adds a state to the associated state set. Note that a state can be in the sets of various transition labels.
@param state
the state to be added.
@return <code>true</code> if this was the first state to be added to the set, <code>false</code> otherwise. | [
"Adds",
"a",
"state",
"to",
"the",
"associated",
"state",
"set",
".",
"Note",
"that",
"a",
"state",
"can",
"be",
"in",
"the",
"sets",
"of",
"various",
"transition",
"labels",
"."
] | train | https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/util/src/main/java/net/automatalib/util/minimizer/TransitionLabel.java#L111-L118 |
smartsheet-platform/smartsheet-java-sdk | src/main/java/com/smartsheet/api/internal/DiscussionCommentResourcesImpl.java | DiscussionCommentResourcesImpl.addCommentWithAttachment | public Comment addCommentWithAttachment(long sheetId, long discussionId, Comment comment, File file, String contentType) throws SmartsheetException, IOException{
String path = "sheets/" + sheetId + "/discussions/" + discussionId + "/comments";
Util.throwIfNull(sheetId, comment, file, contentType);
return this.addCommentWithAttachment(path, comment, new FileInputStream(file), contentType, file.getName());
} | java | public Comment addCommentWithAttachment(long sheetId, long discussionId, Comment comment, File file, String contentType) throws SmartsheetException, IOException{
String path = "sheets/" + sheetId + "/discussions/" + discussionId + "/comments";
Util.throwIfNull(sheetId, comment, file, contentType);
return this.addCommentWithAttachment(path, comment, new FileInputStream(file), contentType, file.getName());
} | [
"public",
"Comment",
"addCommentWithAttachment",
"(",
"long",
"sheetId",
",",
"long",
"discussionId",
",",
"Comment",
"comment",
",",
"File",
"file",
",",
"String",
"contentType",
")",
"throws",
"SmartsheetException",
",",
"IOException",
"{",
"String",
"path",
"="... | Add a comment to a discussion with an attachment.
It mirrors to the following Smartsheet REST API method: POST /discussion/{discussionId}/comments
@param sheetId the sheet id
@param discussionId the dicussion id
@param comment the comment to add
@param file the file to be attached
@param contentType the type of file
@return the created comment
@throws IllegalArgumentException if any argument is null or empty string
@throws InvalidRequestException if there is any problem with the REST API request
@throws AuthorizationException if there is any problem with the REST API authorization (access token)
@throws ResourceNotFoundException if the resource cannot be found
@throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
@throws SmartsheetException if there is any other error during the operation
@throws IOException is there is any error with file | [
"Add",
"a",
"comment",
"to",
"a",
"discussion",
"with",
"an",
"attachment",
"."
] | train | https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/DiscussionCommentResourcesImpl.java#L86-L91 |
cdk/cdk | legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKMCS.java | CDKMCS.hasCommonAtom | private static boolean hasCommonAtom(IBond bondA, IBond bondB) {
return bondA.contains(bondB.getBegin()) || bondA.contains(bondB.getEnd());
} | java | private static boolean hasCommonAtom(IBond bondA, IBond bondB) {
return bondA.contains(bondB.getBegin()) || bondA.contains(bondB.getEnd());
} | [
"private",
"static",
"boolean",
"hasCommonAtom",
"(",
"IBond",
"bondA",
",",
"IBond",
"bondB",
")",
"{",
"return",
"bondA",
".",
"contains",
"(",
"bondB",
".",
"getBegin",
"(",
")",
")",
"||",
"bondA",
".",
"contains",
"(",
"bondB",
".",
"getEnd",
"(",
... | Determines if two bonds have at least one atom in common.
@param atom first bondA1
@param bondB second bondA1
@return the symbol of the common atom or "" if
the 2 bonds have no common atom | [
"Determines",
"if",
"two",
"bonds",
"have",
"at",
"least",
"one",
"atom",
"in",
"common",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKMCS.java#L908-L910 |
innoq/LiQID | ldap-connector/src/main/java/com/innoq/ldap/connector/LdapHelper.java | LdapHelper.getEntry | public Node getEntry(final String cn, final String owner) {
// TODO implement me!
Node entry = new LdapEntry(cn, owner);
return entry;
} | java | public Node getEntry(final String cn, final String owner) {
// TODO implement me!
Node entry = new LdapEntry(cn, owner);
return entry;
} | [
"public",
"Node",
"getEntry",
"(",
"final",
"String",
"cn",
",",
"final",
"String",
"owner",
")",
"{",
"// TODO implement me!",
"Node",
"entry",
"=",
"new",
"LdapEntry",
"(",
"cn",
",",
"owner",
")",
";",
"return",
"entry",
";",
"}"
] | Returns an Sub-Entry of an LDAP User/LDAP Group.
@param cn of that Entry.
@param owner DN of Parent Node.
@return a new Entry. | [
"Returns",
"an",
"Sub",
"-",
"Entry",
"of",
"an",
"LDAP",
"User",
"/",
"LDAP",
"Group",
"."
] | train | https://github.com/innoq/LiQID/blob/ae3de2c1fd78c40219780d510eba57c931901279/ldap-connector/src/main/java/com/innoq/ldap/connector/LdapHelper.java#L275-L279 |
BotMill/fb-botmill | src/main/java/co/aurasphere/botmill/fb/FbBot.java | FbBot.addActionFrame | public void addActionFrame(FbBotMillEvent event, AutoReply reply) {
ActionFrame frame = new ActionFrame(event, reply);
this.actionFrameList.add(frame);
} | java | public void addActionFrame(FbBotMillEvent event, AutoReply reply) {
ActionFrame frame = new ActionFrame(event, reply);
this.actionFrameList.add(frame);
} | [
"public",
"void",
"addActionFrame",
"(",
"FbBotMillEvent",
"event",
",",
"AutoReply",
"reply",
")",
"{",
"ActionFrame",
"frame",
"=",
"new",
"ActionFrame",
"(",
"event",
",",
"reply",
")",
";",
"this",
".",
"actionFrameList",
".",
"add",
"(",
"frame",
")",
... | Adds an {@link ActionFrame} to this bot.
@param event
the {@link FbBotMillEvent} to handle.
@param reply
the {@link AutoReply} which should handle the event. | [
"Adds",
"an",
"{",
"@link",
"ActionFrame",
"}",
"to",
"this",
"bot",
"."
] | train | https://github.com/BotMill/fb-botmill/blob/d94da3615a7339822c137ef75c92a03d791ee969/src/main/java/co/aurasphere/botmill/fb/FbBot.java#L154-L157 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/schema/SchemaService.java | SchemaService.verifyStorageServiceOption | private StorageService verifyStorageServiceOption(ApplicationDefinition currAppDef, ApplicationDefinition appDef) {
// Verify or assign StorageService
String ssName = getStorageServiceOption(appDef);
StorageService storageService = getStorageService(appDef);
Utils.require(storageService != null, "StorageService is unknown or hasn't been initialized: %s", ssName);
// Currently, StorageService can't be changed.
if (currAppDef != null) {
String currSSName = getStorageServiceOption(currAppDef);
Utils.require(currSSName.equals(ssName), "'StorageService' cannot be changed for application: %s", appDef.getAppName());
}
return storageService;
} | java | private StorageService verifyStorageServiceOption(ApplicationDefinition currAppDef, ApplicationDefinition appDef) {
// Verify or assign StorageService
String ssName = getStorageServiceOption(appDef);
StorageService storageService = getStorageService(appDef);
Utils.require(storageService != null, "StorageService is unknown or hasn't been initialized: %s", ssName);
// Currently, StorageService can't be changed.
if (currAppDef != null) {
String currSSName = getStorageServiceOption(currAppDef);
Utils.require(currSSName.equals(ssName), "'StorageService' cannot be changed for application: %s", appDef.getAppName());
}
return storageService;
} | [
"private",
"StorageService",
"verifyStorageServiceOption",
"(",
"ApplicationDefinition",
"currAppDef",
",",
"ApplicationDefinition",
"appDef",
")",
"{",
"// Verify or assign StorageService\r",
"String",
"ssName",
"=",
"getStorageServiceOption",
"(",
"appDef",
")",
";",
"Stora... | change, ensure it hasn't changed. Return the application's StorageService object. | [
"change",
"ensure",
"it",
"hasn",
"t",
"changed",
".",
"Return",
"the",
"application",
"s",
"StorageService",
"object",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/schema/SchemaService.java#L369-L381 |
jbundle/jbundle | base/remote/src/main/java/org/jbundle/base/remote/BaseSession.java | BaseSession.doRemoteAction | public Object doRemoteAction(String strCommand, Map<String, Object> properties) throws DBException, RemoteException
{
synchronized (this.getTask())
{ // Just being careful (in case the user decides to do some data access)
// Don't override this, override doRemoteCommand(xxx);
return this.handleRemoteCommand(strCommand, properties, this);
}
} | java | public Object doRemoteAction(String strCommand, Map<String, Object> properties) throws DBException, RemoteException
{
synchronized (this.getTask())
{ // Just being careful (in case the user decides to do some data access)
// Don't override this, override doRemoteCommand(xxx);
return this.handleRemoteCommand(strCommand, properties, this);
}
} | [
"public",
"Object",
"doRemoteAction",
"(",
"String",
"strCommand",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"throws",
"DBException",
",",
"RemoteException",
"{",
"synchronized",
"(",
"this",
".",
"getTask",
"(",
")",
")",
"{",
"// Ju... | Do a remote action.
@param strCommand Command to perform remotely.
@param properties Properties for this command (optional).
@return boolean success. | [
"Do",
"a",
"remote",
"action",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/remote/src/main/java/org/jbundle/base/remote/BaseSession.java#L155-L162 |
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/dsl/PathBuilder.java | PathBuilder.get | @SuppressWarnings("unchecked")
public <A extends Comparable<?>> ComparablePath<A> get(ComparablePath<A> path) {
ComparablePath<A> newPath = getComparable(toString(path), (Class<A>) path.getType());
return addMetadataOf(newPath, path);
} | java | @SuppressWarnings("unchecked")
public <A extends Comparable<?>> ComparablePath<A> get(ComparablePath<A> path) {
ComparablePath<A> newPath = getComparable(toString(path), (Class<A>) path.getType());
return addMetadataOf(newPath, path);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"A",
"extends",
"Comparable",
"<",
"?",
">",
">",
"ComparablePath",
"<",
"A",
">",
"get",
"(",
"ComparablePath",
"<",
"A",
">",
"path",
")",
"{",
"ComparablePath",
"<",
"A",
">",
"newPath... | Create a new Comparable typed path
@param <A>
@param path existing path
@return property path | [
"Create",
"a",
"new",
"Comparable",
"typed",
"path"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/PathBuilder.java#L233-L237 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LocalNetworkGatewaysInner.java | LocalNetworkGatewaysInner.getByResourceGroup | public LocalNetworkGatewayInner getByResourceGroup(String resourceGroupName, String localNetworkGatewayName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, localNetworkGatewayName).toBlocking().single().body();
} | java | public LocalNetworkGatewayInner getByResourceGroup(String resourceGroupName, String localNetworkGatewayName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, localNetworkGatewayName).toBlocking().single().body();
} | [
"public",
"LocalNetworkGatewayInner",
"getByResourceGroup",
"(",
"String",
"resourceGroupName",
",",
"String",
"localNetworkGatewayName",
")",
"{",
"return",
"getByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"localNetworkGatewayName",
")",
".",
"toBlo... | Gets the specified local network gateway in a resource group.
@param resourceGroupName The name of the resource group.
@param localNetworkGatewayName The name of the local network gateway.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the LocalNetworkGatewayInner object if successful. | [
"Gets",
"the",
"specified",
"local",
"network",
"gateway",
"in",
"a",
"resource",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LocalNetworkGatewaysInner.java#L285-L287 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WFileWidgetRenderer.java | WFileWidgetRenderer.doRender | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WFileWidget fileWidget = (WFileWidget) component;
XmlStringBuilder xml = renderContext.getWriter();
boolean readOnly = fileWidget.isReadOnly();
xml.appendTagOpen(TAG_NAME);
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
xml.appendOptionalAttribute("hidden", component.isHidden(), "true");
if (readOnly) {
xml.appendAttribute("readOnly", "true");
xml.appendEnd();
return;
}
xml.appendOptionalAttribute("disabled", fileWidget.isDisabled(), "true");
xml.appendOptionalAttribute("required", fileWidget.isMandatory(), "true");
xml.appendOptionalAttribute("toolTip", fileWidget.getToolTip());
xml.appendOptionalAttribute("accessibleText", fileWidget.getAccessibleText());
xml.appendOptionalAttribute("acceptedMimeTypes", typesToString(fileWidget.getFileTypes()));
long maxFileSize = fileWidget.getMaxFileSize();
xml.appendOptionalAttribute("maxFileSize", maxFileSize > 0, maxFileSize);
List<Diagnostic> diags = fileWidget.getDiagnostics(Diagnostic.ERROR);
if (diags == null || diags.isEmpty()) {
xml.appendEnd();
return;
}
xml.appendClose();
DiagnosticRenderUtil.renderDiagnostics(fileWidget, renderContext);
xml.appendEndTag(TAG_NAME);
} | java | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WFileWidget fileWidget = (WFileWidget) component;
XmlStringBuilder xml = renderContext.getWriter();
boolean readOnly = fileWidget.isReadOnly();
xml.appendTagOpen(TAG_NAME);
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
xml.appendOptionalAttribute("hidden", component.isHidden(), "true");
if (readOnly) {
xml.appendAttribute("readOnly", "true");
xml.appendEnd();
return;
}
xml.appendOptionalAttribute("disabled", fileWidget.isDisabled(), "true");
xml.appendOptionalAttribute("required", fileWidget.isMandatory(), "true");
xml.appendOptionalAttribute("toolTip", fileWidget.getToolTip());
xml.appendOptionalAttribute("accessibleText", fileWidget.getAccessibleText());
xml.appendOptionalAttribute("acceptedMimeTypes", typesToString(fileWidget.getFileTypes()));
long maxFileSize = fileWidget.getMaxFileSize();
xml.appendOptionalAttribute("maxFileSize", maxFileSize > 0, maxFileSize);
List<Diagnostic> diags = fileWidget.getDiagnostics(Diagnostic.ERROR);
if (diags == null || diags.isEmpty()) {
xml.appendEnd();
return;
}
xml.appendClose();
DiagnosticRenderUtil.renderDiagnostics(fileWidget, renderContext);
xml.appendEndTag(TAG_NAME);
} | [
"@",
"Override",
"public",
"void",
"doRender",
"(",
"final",
"WComponent",
"component",
",",
"final",
"WebXmlRenderContext",
"renderContext",
")",
"{",
"WFileWidget",
"fileWidget",
"=",
"(",
"WFileWidget",
")",
"component",
";",
"XmlStringBuilder",
"xml",
"=",
"re... | Paints the given WFileWidget.
@param component the WFileWidget to paint.
@param renderContext the RenderContext to paint to. | [
"Paints",
"the",
"given",
"WFileWidget",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WFileWidgetRenderer.java#L29-L61 |
google/closure-templates | java/src/com/google/template/soy/basetree/MixinParentNode.java | MixinParentNode.replaceChild | public void replaceChild(int index, N newChild) {
checkNotNull(newChild);
tryRemoveFromOldParent(newChild);
N oldChild = children.set(index, newChild);
oldChild.setParent(null);
newChild.setParent(master);
} | java | public void replaceChild(int index, N newChild) {
checkNotNull(newChild);
tryRemoveFromOldParent(newChild);
N oldChild = children.set(index, newChild);
oldChild.setParent(null);
newChild.setParent(master);
} | [
"public",
"void",
"replaceChild",
"(",
"int",
"index",
",",
"N",
"newChild",
")",
"{",
"checkNotNull",
"(",
"newChild",
")",
";",
"tryRemoveFromOldParent",
"(",
"newChild",
")",
";",
"N",
"oldChild",
"=",
"children",
".",
"set",
"(",
"index",
",",
"newChil... | Replaces the child at the given index with the given new child.
@param index The index of the child to replace.
@param newChild The new child. | [
"Replaces",
"the",
"child",
"at",
"the",
"given",
"index",
"with",
"the",
"given",
"new",
"child",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/basetree/MixinParentNode.java#L164-L170 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/TdeCertificatesInner.java | TdeCertificatesInner.beginCreate | public void beginCreate(String resourceGroupName, String serverName, TdeCertificateInner parameters) {
beginCreateWithServiceResponseAsync(resourceGroupName, serverName, parameters).toBlocking().single().body();
} | java | public void beginCreate(String resourceGroupName, String serverName, TdeCertificateInner parameters) {
beginCreateWithServiceResponseAsync(resourceGroupName, serverName, parameters).toBlocking().single().body();
} | [
"public",
"void",
"beginCreate",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"TdeCertificateInner",
"parameters",
")",
"{",
"beginCreateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
"parameters",
")",
".",
"toBloc... | Creates a TDE certificate for a given server.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param parameters The requested TDE certificate to be created or updated.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Creates",
"a",
"TDE",
"certificate",
"for",
"a",
"given",
"server",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/TdeCertificatesInner.java#L152-L154 |
openengsb/openengsb | components/util/src/main/java/org/openengsb/core/util/CipherUtils.java | CipherUtils.deserializePrivateKey | public static PrivateKey deserializePrivateKey(byte[] keyData, String algorithm) {
LOGGER.trace("deserialize private key from data using algorithm \"{}\"", algorithm);
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(keyData);
try {
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
return keyFactory.generatePrivate(privSpec);
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException("provided data could not be converted to a PrivateKey for algorithm "
+ algorithm, e);
}
} | java | public static PrivateKey deserializePrivateKey(byte[] keyData, String algorithm) {
LOGGER.trace("deserialize private key from data using algorithm \"{}\"", algorithm);
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(keyData);
try {
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
return keyFactory.generatePrivate(privSpec);
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException("provided data could not be converted to a PrivateKey for algorithm "
+ algorithm, e);
}
} | [
"public",
"static",
"PrivateKey",
"deserializePrivateKey",
"(",
"byte",
"[",
"]",
"keyData",
",",
"String",
"algorithm",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"deserialize private key from data using algorithm \\\"{}\\\"\"",
",",
"algorithm",
")",
";",
"PKCS8EncodedK... | converts a byte[] that originally was created using {@link PrivateKey#getEncoded()} back to the corresponding
instance.
Example: CipherUtils.deserializePrivateKey(data, "RSA") | [
"converts",
"a",
"byte",
"[]",
"that",
"originally",
"was",
"created",
"using",
"{",
"@link",
"PrivateKey#getEncoded",
"()",
"}",
"back",
"to",
"the",
"corresponding",
"instance",
"."
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/util/src/main/java/org/openengsb/core/util/CipherUtils.java#L145-L155 |
moparisthebest/beehive | beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletBeanContext.java | ServletBeanContext.getResourceAsStream | public InputStream getResourceAsStream(String name, BeanContextChild bcc)
throws IllegalArgumentException
{
ServletContext sc = getServletContext();
if ( sc != null )
return sc.getResourceAsStream( name );
return null;
} | java | public InputStream getResourceAsStream(String name, BeanContextChild bcc)
throws IllegalArgumentException
{
ServletContext sc = getServletContext();
if ( sc != null )
return sc.getResourceAsStream( name );
return null;
} | [
"public",
"InputStream",
"getResourceAsStream",
"(",
"String",
"name",
",",
"BeanContextChild",
"bcc",
")",
"throws",
"IllegalArgumentException",
"{",
"ServletContext",
"sc",
"=",
"getServletContext",
"(",
")",
";",
"if",
"(",
"sc",
"!=",
"null",
")",
"return",
... | Override BeanContext.getResourceAsStream() so it delegates to the current ServletContext.
@param name the resource name
@param bcc the specified child
@return an <code>InputStream</code> for reading the resource, or
<code>null</code> if the resource could not be found.
@throws IllegalArgumentException <code>IllegalArgumentException</code> if the resource is not valid | [
"Override",
"BeanContext",
".",
"getResourceAsStream",
"()",
"so",
"it",
"delegates",
"to",
"the",
"current",
"ServletContext",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletBeanContext.java#L191-L199 |
inkstand-io/scribble | scribble-net/src/main/java/io/inkstand/scribble/net/NetworkMatchers.java | NetworkMatchers.remotePort | public static NetworkPort remotePort(String hostname, int port){
return new RemoteNetworkPort(hostname, port, NetworkPort.Type.TCP);
} | java | public static NetworkPort remotePort(String hostname, int port){
return new RemoteNetworkPort(hostname, port, NetworkPort.Type.TCP);
} | [
"public",
"static",
"NetworkPort",
"remotePort",
"(",
"String",
"hostname",
",",
"int",
"port",
")",
"{",
"return",
"new",
"RemoteNetworkPort",
"(",
"hostname",
",",
"port",
",",
"NetworkPort",
".",
"Type",
".",
"TCP",
")",
";",
"}"
] | Creates a type-safe tcp port pointing ot a remote host and port.
@param hostname
the hostname of the remote host
@param port
the port of the remote host
@return a {@link NetworkPort} instance describing the tcp port | [
"Creates",
"a",
"type",
"-",
"safe",
"tcp",
"port",
"pointing",
"ot",
"a",
"remote",
"host",
"and",
"port",
"."
] | train | https://github.com/inkstand-io/scribble/blob/66e67553bad4b1ff817e1715fd1d3dd833406744/scribble-net/src/main/java/io/inkstand/scribble/net/NetworkMatchers.java#L88-L90 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.importKeyAsync | public ServiceFuture<KeyBundle> importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, final ServiceCallback<KeyBundle> serviceCallback) {
return ServiceFuture.fromResponse(importKeyWithServiceResponseAsync(vaultBaseUrl, keyName, key), serviceCallback);
} | java | public ServiceFuture<KeyBundle> importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, final ServiceCallback<KeyBundle> serviceCallback) {
return ServiceFuture.fromResponse(importKeyWithServiceResponseAsync(vaultBaseUrl, keyName, key), serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"KeyBundle",
">",
"importKeyAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"keyName",
",",
"JsonWebKey",
"key",
",",
"final",
"ServiceCallback",
"<",
"KeyBundle",
">",
"serviceCallback",
")",
"{",
"return",
"ServiceFuture",
"... | Imports an externally created key, stores it, and returns key parameters and attributes to the client.
The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param keyName Name for the imported key.
@param key The Json web key
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Imports",
"an",
"externally",
"created",
"key",
"stores",
"it",
"and",
"returns",
"key",
"parameters",
"and",
"attributes",
"to",
"the",
"client",
".",
"The",
"import",
"key",
"operation",
"may",
"be",
"used",
"to",
"import",
"any",
"key",
"type",
"into",
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L891-L893 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerHandlerImpl.java | TransformerHandlerImpl.endElement | public void endElement(String uri, String localName, String qName)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#endElement: " + qName);
if (m_contentHandler != null)
{
m_contentHandler.endElement(uri, localName, qName);
}
} | java | public void endElement(String uri, String localName, String qName)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#endElement: " + qName);
if (m_contentHandler != null)
{
m_contentHandler.endElement(uri, localName, qName);
}
} | [
"public",
"void",
"endElement",
"(",
"String",
"uri",
",",
"String",
"localName",
",",
"String",
"qName",
")",
"throws",
"SAXException",
"{",
"if",
"(",
"DEBUG",
")",
"System",
".",
"out",
".",
"println",
"(",
"\"TransformerHandlerImpl#endElement: \"",
"+",
"q... | Filter an end element event.
@param uri The element's Namespace URI, or the empty string.
@param localName The element's local name, or the empty string.
@param qName The element's qualified (prefixed) name, or the empty
string.
@throws SAXException The client may throw
an exception during processing.
@see org.xml.sax.ContentHandler#endElement | [
"Filter",
"an",
"end",
"element",
"event",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerHandlerImpl.java#L515-L526 |
jenkinsci/artifactory-plugin | src/main/java/org/jfrog/hudson/pipeline/declarative/utils/DeclarativePipelineUtils.java | DeclarativePipelineUtils.readBuildDataFile | public static BuildDataFile readBuildDataFile(FilePath ws, final String buildNumber, final String stepName, final String stepId) throws IOException, InterruptedException {
return createAndGetTempDir(ws).act(new ReadBuildDataFileCallable(buildNumber, stepName, stepId));
} | java | public static BuildDataFile readBuildDataFile(FilePath ws, final String buildNumber, final String stepName, final String stepId) throws IOException, InterruptedException {
return createAndGetTempDir(ws).act(new ReadBuildDataFileCallable(buildNumber, stepName, stepId));
} | [
"public",
"static",
"BuildDataFile",
"readBuildDataFile",
"(",
"FilePath",
"ws",
",",
"final",
"String",
"buildNumber",
",",
"final",
"String",
"stepName",
",",
"final",
"String",
"stepId",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"return",
... | Read pipeline build data from @tmp/artifactory-pipeline-cache/build-number directory.
Used to transfer data between different steps in declarative pipelines.
@param buildNumber - The build number.
@param stepName - The step name - One of 'artifactoryMaven', 'mavenDeploy', 'mavenResolve', 'buildInfo' and other declarative pipeline steps.
@param stepId - The step id specified in the pipeline.
@throws IOException - In case of no read permissions. | [
"Read",
"pipeline",
"build",
"data",
"from",
"@tmp",
"/",
"artifactory",
"-",
"pipeline",
"-",
"cache",
"/",
"build",
"-",
"number",
"directory",
".",
"Used",
"to",
"transfer",
"data",
"between",
"different",
"steps",
"in",
"declarative",
"pipelines",
"."
] | train | https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/pipeline/declarative/utils/DeclarativePipelineUtils.java#L53-L55 |
liferay/com-liferay-commerce | commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceListUserSegmentEntryRelPersistenceImpl.java | CommercePriceListUserSegmentEntryRelPersistenceImpl.findByCommercePriceListId | @Override
public List<CommercePriceListUserSegmentEntryRel> findByCommercePriceListId(
long commercePriceListId, int start, int end) {
return findByCommercePriceListId(commercePriceListId, start, end, null);
} | java | @Override
public List<CommercePriceListUserSegmentEntryRel> findByCommercePriceListId(
long commercePriceListId, int start, int end) {
return findByCommercePriceListId(commercePriceListId, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommercePriceListUserSegmentEntryRel",
">",
"findByCommercePriceListId",
"(",
"long",
"commercePriceListId",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByCommercePriceListId",
"(",
"commercePriceListId",
","... | Returns a range of all the commerce price list user segment entry rels where commercePriceListId = ?.
<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 CommercePriceListUserSegmentEntryRelModelImpl}. 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 commercePriceListId the commerce price list ID
@param start the lower bound of the range of commerce price list user segment entry rels
@param end the upper bound of the range of commerce price list user segment entry rels (not inclusive)
@return the range of matching commerce price list user segment entry rels | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"price",
"list",
"user",
"segment",
"entry",
"rels",
"where",
"commercePriceListId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceListUserSegmentEntryRelPersistenceImpl.java#L1570-L1574 |
lastaflute/lasta-di | src/main/java/org/lastaflute/di/util/LdiSrl.java | LdiSrl.substringFirstFrontIgnoreCase | public static String substringFirstFrontIgnoreCase(final String str, final String... delimiters) {
assertStringNotNull(str);
return doSubstringFirstRear(false, false, true, str, delimiters);
} | java | public static String substringFirstFrontIgnoreCase(final String str, final String... delimiters) {
assertStringNotNull(str);
return doSubstringFirstRear(false, false, true, str, delimiters);
} | [
"public",
"static",
"String",
"substringFirstFrontIgnoreCase",
"(",
"final",
"String",
"str",
",",
"final",
"String",
"...",
"delimiters",
")",
"{",
"assertStringNotNull",
"(",
"str",
")",
";",
"return",
"doSubstringFirstRear",
"(",
"false",
",",
"false",
",",
"... | Extract front sub-string from first-found delimiter ignoring case.
<pre>
substringFirstFront("foo.bar/baz.qux", "A", "U")
returns "foo.b"
</pre>
@param str The target string. (NotNull)
@param delimiters The array of delimiters. (NotNull)
@return The part of string. (NotNull: if delimiter not found, returns argument-plain string) | [
"Extract",
"front",
"sub",
"-",
"string",
"from",
"first",
"-",
"found",
"delimiter",
"ignoring",
"case",
".",
"<pre",
">",
"substringFirstFront",
"(",
"foo",
".",
"bar",
"/",
"baz",
".",
"qux",
"A",
"U",
")",
"returns",
"foo",
".",
"b",
"<",
"/",
"p... | train | https://github.com/lastaflute/lasta-di/blob/c4e123610c53a04cc836c5e456660e32d613447b/src/main/java/org/lastaflute/di/util/LdiSrl.java#L642-L645 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCrossConnectionsInner.java | ExpressRouteCrossConnectionsInner.updateTagsAsync | public Observable<ExpressRouteCrossConnectionInner> updateTagsAsync(String resourceGroupName, String crossConnectionName) {
return updateTagsWithServiceResponseAsync(resourceGroupName, crossConnectionName).map(new Func1<ServiceResponse<ExpressRouteCrossConnectionInner>, ExpressRouteCrossConnectionInner>() {
@Override
public ExpressRouteCrossConnectionInner call(ServiceResponse<ExpressRouteCrossConnectionInner> response) {
return response.body();
}
});
} | java | public Observable<ExpressRouteCrossConnectionInner> updateTagsAsync(String resourceGroupName, String crossConnectionName) {
return updateTagsWithServiceResponseAsync(resourceGroupName, crossConnectionName).map(new Func1<ServiceResponse<ExpressRouteCrossConnectionInner>, ExpressRouteCrossConnectionInner>() {
@Override
public ExpressRouteCrossConnectionInner call(ServiceResponse<ExpressRouteCrossConnectionInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ExpressRouteCrossConnectionInner",
">",
"updateTagsAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"crossConnectionName",
")",
"{",
"return",
"updateTagsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"crossConnectionName",
"... | Updates an express route cross connection tags.
@param resourceGroupName The name of the resource group.
@param crossConnectionName The name of the cross connection.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Updates",
"an",
"express",
"route",
"cross",
"connection",
"tags",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCrossConnectionsInner.java#L635-L642 |
infinispan/infinispan | query/src/main/java/org/infinispan/query/affinity/FixedShardsDistribution.java | FixedShardsDistribution.populateSegments | private void populateSegments(int[] shardsNumPerServer, List<Set<Integer>> segmentsPerServer, List<Address> nodes) {
int shardId = 0;
int n = 0;
Set<Integer> remainingSegments = new HashSet<>();
for (Address node : nodes) {
Collection<Integer> primarySegments = segmentsPerServer.get(n);
int shardQuantity = shardsNumPerServer[n];
if (shardQuantity == 0) {
remainingSegments.addAll(segmentsPerServer.get(n++));
continue;
}
shardsPerAddressMap.computeIfAbsent(node, a -> new HashSet<>(shardQuantity));
List<Set<Integer>> segments = this.split(primarySegments, shardsNumPerServer[n++]);
for (Collection<Integer> shardSegments : segments) {
String id = String.valueOf(shardId++);
shardSegments.forEach(seg -> shardPerSegmentMap.put(seg, id));
shardsPerAddressMap.get(node).add(id);
addressPerShardMap.put(id, node);
}
}
if (!remainingSegments.isEmpty()) {
Iterator<String> shardIterator = Stream.iterate(0, i -> (i + 1) % numShards).map(String::valueOf).iterator();
for (Integer segment : remainingSegments) {
shardPerSegmentMap.put(segment, shardIterator.next());
}
}
} | java | private void populateSegments(int[] shardsNumPerServer, List<Set<Integer>> segmentsPerServer, List<Address> nodes) {
int shardId = 0;
int n = 0;
Set<Integer> remainingSegments = new HashSet<>();
for (Address node : nodes) {
Collection<Integer> primarySegments = segmentsPerServer.get(n);
int shardQuantity = shardsNumPerServer[n];
if (shardQuantity == 0) {
remainingSegments.addAll(segmentsPerServer.get(n++));
continue;
}
shardsPerAddressMap.computeIfAbsent(node, a -> new HashSet<>(shardQuantity));
List<Set<Integer>> segments = this.split(primarySegments, shardsNumPerServer[n++]);
for (Collection<Integer> shardSegments : segments) {
String id = String.valueOf(shardId++);
shardSegments.forEach(seg -> shardPerSegmentMap.put(seg, id));
shardsPerAddressMap.get(node).add(id);
addressPerShardMap.put(id, node);
}
}
if (!remainingSegments.isEmpty()) {
Iterator<String> shardIterator = Stream.iterate(0, i -> (i + 1) % numShards).map(String::valueOf).iterator();
for (Integer segment : remainingSegments) {
shardPerSegmentMap.put(segment, shardIterator.next());
}
}
} | [
"private",
"void",
"populateSegments",
"(",
"int",
"[",
"]",
"shardsNumPerServer",
",",
"List",
"<",
"Set",
"<",
"Integer",
">",
">",
"segmentsPerServer",
",",
"List",
"<",
"Address",
">",
"nodes",
")",
"{",
"int",
"shardId",
"=",
"0",
";",
"int",
"n",
... | Associates segments to each shard.
@param shardsNumPerServer numbers of shards allocated for each server
@param segmentsPerServer the primary owned segments of each server
@param nodes the members of the cluster | [
"Associates",
"segments",
"to",
"each",
"shard",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/query/src/main/java/org/infinispan/query/affinity/FixedShardsDistribution.java#L66-L92 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java | ToStringBuilder.reflectionToString | @GwtIncompatible("incompatible method")
public static String reflectionToString(final Object object, final ToStringStyle style, final boolean outputTransients) {
return ReflectionToStringBuilder.toString(object, style, outputTransients, false, null);
} | java | @GwtIncompatible("incompatible method")
public static String reflectionToString(final Object object, final ToStringStyle style, final boolean outputTransients) {
return ReflectionToStringBuilder.toString(object, style, outputTransients, false, null);
} | [
"@",
"GwtIncompatible",
"(",
"\"incompatible method\"",
")",
"public",
"static",
"String",
"reflectionToString",
"(",
"final",
"Object",
"object",
",",
"final",
"ToStringStyle",
"style",
",",
"final",
"boolean",
"outputTransients",
")",
"{",
"return",
"ReflectionToStr... | <p>Uses <code>ReflectionToStringBuilder</code> to generate a
<code>toString</code> for the specified object.</p>
@param object the Object to be output
@param style the style of the <code>toString</code> to create, may be <code>null</code>
@param outputTransients whether to include transient fields
@return the String result
@see ReflectionToStringBuilder#toString(Object,ToStringStyle,boolean) | [
"<p",
">",
"Uses",
"<code",
">",
"ReflectionToStringBuilder<",
"/",
"code",
">",
"to",
"generate",
"a",
"<code",
">",
"toString<",
"/",
"code",
">",
"for",
"the",
"specified",
"object",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java#L180-L183 |
tango-controls/JTango | server/src/main/java/org/tango/server/events/EventImpl.java | EventImpl.pushDevFailedEvent | protected void pushDevFailedEvent(final DevFailed devFailed, ZMQ.Socket eventSocket) throws DevFailed {
xlogger.entry();
eventTrigger.updateProperties();
eventTrigger.setError(devFailed);
if (isSendEvent()) {
try {
synchronized (eventSocket) {
EventUtilities.sendToSocket(eventSocket, fullName, counter++, true, EventUtilities.marshall(devFailed));
}
} catch (final org.zeromq.ZMQException e) {
throw DevFailedUtils.newDevFailed(e);
}
}
xlogger.exit();
} | java | protected void pushDevFailedEvent(final DevFailed devFailed, ZMQ.Socket eventSocket) throws DevFailed {
xlogger.entry();
eventTrigger.updateProperties();
eventTrigger.setError(devFailed);
if (isSendEvent()) {
try {
synchronized (eventSocket) {
EventUtilities.sendToSocket(eventSocket, fullName, counter++, true, EventUtilities.marshall(devFailed));
}
} catch (final org.zeromq.ZMQException e) {
throw DevFailedUtils.newDevFailed(e);
}
}
xlogger.exit();
} | [
"protected",
"void",
"pushDevFailedEvent",
"(",
"final",
"DevFailed",
"devFailed",
",",
"ZMQ",
".",
"Socket",
"eventSocket",
")",
"throws",
"DevFailed",
"{",
"xlogger",
".",
"entry",
"(",
")",
";",
"eventTrigger",
".",
"updateProperties",
"(",
")",
";",
"event... | Fire an event containing a DevFailed.
@param devFailed the failed object to be sent.
@param eventSocket
@throws DevFailed | [
"Fire",
"an",
"event",
"containing",
"a",
"DevFailed",
"."
] | train | https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/events/EventImpl.java#L261-L275 |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java | BytecodeUtils.numericConversion | public static Expression numericConversion(final Expression expr, final Type to) {
if (to.equals(expr.resultType())) {
return expr;
}
if (!isNumericPrimitive(to) || !isNumericPrimitive(expr.resultType())) {
throw new IllegalArgumentException("Cannot convert from " + expr.resultType() + " to " + to);
}
return new Expression(to, expr.features()) {
@Override
protected void doGen(CodeBuilder adapter) {
expr.gen(adapter);
adapter.cast(expr.resultType(), to);
}
};
} | java | public static Expression numericConversion(final Expression expr, final Type to) {
if (to.equals(expr.resultType())) {
return expr;
}
if (!isNumericPrimitive(to) || !isNumericPrimitive(expr.resultType())) {
throw new IllegalArgumentException("Cannot convert from " + expr.resultType() + " to " + to);
}
return new Expression(to, expr.features()) {
@Override
protected void doGen(CodeBuilder adapter) {
expr.gen(adapter);
adapter.cast(expr.resultType(), to);
}
};
} | [
"public",
"static",
"Expression",
"numericConversion",
"(",
"final",
"Expression",
"expr",
",",
"final",
"Type",
"to",
")",
"{",
"if",
"(",
"to",
".",
"equals",
"(",
"expr",
".",
"resultType",
"(",
")",
")",
")",
"{",
"return",
"expr",
";",
"}",
"if",
... | Returns an expression that does a numeric conversion cast from the given expression to the
given type.
@throws IllegalArgumentException if either the expression or the target type is not a numeric
primitive | [
"Returns",
"an",
"expression",
"that",
"does",
"a",
"numeric",
"conversion",
"cast",
"from",
"the",
"given",
"expression",
"to",
"the",
"given",
"type",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java#L409-L423 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/javax/crypto/Mac.java | Mac.update | public final void update(byte[] input, int offset, int len)
throws IllegalStateException {
chooseFirstProvider();
if (initialized == false) {
throw new IllegalStateException("MAC not initialized");
}
if (input != null) {
if ((offset < 0) || (len > (input.length - offset)) || (len < 0))
throw new IllegalArgumentException("Bad arguments");
spi.engineUpdate(input, offset, len);
}
} | java | public final void update(byte[] input, int offset, int len)
throws IllegalStateException {
chooseFirstProvider();
if (initialized == false) {
throw new IllegalStateException("MAC not initialized");
}
if (input != null) {
if ((offset < 0) || (len > (input.length - offset)) || (len < 0))
throw new IllegalArgumentException("Bad arguments");
spi.engineUpdate(input, offset, len);
}
} | [
"public",
"final",
"void",
"update",
"(",
"byte",
"[",
"]",
"input",
",",
"int",
"offset",
",",
"int",
"len",
")",
"throws",
"IllegalStateException",
"{",
"chooseFirstProvider",
"(",
")",
";",
"if",
"(",
"initialized",
"==",
"false",
")",
"{",
"throw",
"... | Processes the first <code>len</code> bytes in <code>input</code>,
starting at <code>offset</code> inclusive.
@param input the input buffer.
@param offset the offset in <code>input</code> where the input starts.
@param len the number of bytes to process.
@exception IllegalStateException if this <code>Mac</code> has not been
initialized. | [
"Processes",
"the",
"first",
"<code",
">",
"len<",
"/",
"code",
">",
"bytes",
"in",
"<code",
">",
"input<",
"/",
"code",
">",
"starting",
"at",
"<code",
">",
"offset<",
"/",
"code",
">",
"inclusive",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/javax/crypto/Mac.java#L557-L569 |
ops4j/org.ops4j.pax.exam1 | pax-exam/src/main/java/org/ops4j/pax/exam/CoreOptions.java | CoreOptions.mavenConfiguration | public static MavenPluginGeneratedConfigOption mavenConfiguration( String url )
{
validateNotEmpty( url, "specified configuration url must not be empty " );
try
{
return mavenConfiguration( new URL( url ) );
} catch( MalformedURLException mE )
{
throw new IllegalArgumentException( "url " + url + " is not a valid url", mE );
}
} | java | public static MavenPluginGeneratedConfigOption mavenConfiguration( String url )
{
validateNotEmpty( url, "specified configuration url must not be empty " );
try
{
return mavenConfiguration( new URL( url ) );
} catch( MalformedURLException mE )
{
throw new IllegalArgumentException( "url " + url + " is not a valid url", mE );
}
} | [
"public",
"static",
"MavenPluginGeneratedConfigOption",
"mavenConfiguration",
"(",
"String",
"url",
")",
"{",
"validateNotEmpty",
"(",
"url",
",",
"\"specified configuration url must not be empty \"",
")",
";",
"try",
"{",
"return",
"mavenConfiguration",
"(",
"new",
"URL"... | Creates a {@link org.ops4j.pax.exam.options.MavenPluginGeneratedConfigOption}.
@param url of configuration to be used
@return Args option with file written from paxexam plugin | [
"Creates",
"a",
"{",
"@link",
"org",
".",
"ops4j",
".",
"pax",
".",
"exam",
".",
"options",
".",
"MavenPluginGeneratedConfigOption",
"}",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.exam1/blob/7c8742208117ff91bd24bcd3a185d2d019f7000f/pax-exam/src/main/java/org/ops4j/pax/exam/CoreOptions.java#L672-L682 |
eurekaclinical/eurekaclinical-common | src/main/java/org/eurekaclinical/common/comm/clients/EurekaClinicalClient.java | EurekaClinicalClient.doPostMultipart | public void doPostMultipart(String path, FormDataMultiPart formDataMultiPart) throws ClientException {
this.readLock.lock();
try {
ClientResponse response = getResourceWrapper()
.rewritten(path, HttpMethod.POST)
.type(Boundary.addBoundary(MediaType.MULTIPART_FORM_DATA_TYPE))
.post(ClientResponse.class, formDataMultiPart);
errorIfStatusNotEqualTo(response, ClientResponse.Status.OK, ClientResponse.Status.NO_CONTENT);
response.close();
} catch (ClientHandlerException ex) {
throw new ClientException(ClientResponse.Status.INTERNAL_SERVER_ERROR, ex.getMessage());
} finally {
this.readLock.unlock();
}
} | java | public void doPostMultipart(String path, FormDataMultiPart formDataMultiPart) throws ClientException {
this.readLock.lock();
try {
ClientResponse response = getResourceWrapper()
.rewritten(path, HttpMethod.POST)
.type(Boundary.addBoundary(MediaType.MULTIPART_FORM_DATA_TYPE))
.post(ClientResponse.class, formDataMultiPart);
errorIfStatusNotEqualTo(response, ClientResponse.Status.OK, ClientResponse.Status.NO_CONTENT);
response.close();
} catch (ClientHandlerException ex) {
throw new ClientException(ClientResponse.Status.INTERNAL_SERVER_ERROR, ex.getMessage());
} finally {
this.readLock.unlock();
}
} | [
"public",
"void",
"doPostMultipart",
"(",
"String",
"path",
",",
"FormDataMultiPart",
"formDataMultiPart",
")",
"throws",
"ClientException",
"{",
"this",
".",
"readLock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"ClientResponse",
"response",
"=",
"getResourceWrappe... | Submits a multi-part form. Adds appropriate Accepts and Content Type
headers.
@param path the API to call.
@param formDataMultiPart the multi-part form content.
@throws ClientException if a status code other than 200 (OK) and 204 (No
Content) is returned. | [
"Submits",
"a",
"multi",
"-",
"part",
"form",
".",
"Adds",
"appropriate",
"Accepts",
"and",
"Content",
"Type",
"headers",
"."
] | train | https://github.com/eurekaclinical/eurekaclinical-common/blob/1867102ff43fe94e519f76a074d5f5923e9be61c/src/main/java/org/eurekaclinical/common/comm/clients/EurekaClinicalClient.java#L639-L653 |
OpenLiberty/open-liberty | dev/com.ibm.ws.repository/src/com/ibm/ws/repository/strategies/writeable/AddThenHideOldStrategy.java | AddThenHideOldStrategy.returnNonBetaResourceOrNull | private RepositoryResource returnNonBetaResourceOrNull(RepositoryResource res1, RepositoryResource res2) {
if (isBeta(res1) && !isBeta(res2)) {
return res2;
} else if (!isBeta(res1) && isBeta(res2)) {
return res1;
} else {
return null;
}
} | java | private RepositoryResource returnNonBetaResourceOrNull(RepositoryResource res1, RepositoryResource res2) {
if (isBeta(res1) && !isBeta(res2)) {
return res2;
} else if (!isBeta(res1) && isBeta(res2)) {
return res1;
} else {
return null;
}
} | [
"private",
"RepositoryResource",
"returnNonBetaResourceOrNull",
"(",
"RepositoryResource",
"res1",
",",
"RepositoryResource",
"res2",
")",
"{",
"if",
"(",
"isBeta",
"(",
"res1",
")",
"&&",
"!",
"isBeta",
"(",
"res2",
")",
")",
"{",
"return",
"res2",
";",
"}",
... | Take in two resources. If one (only) is beta return the non beta one | [
"Take",
"in",
"two",
"resources",
".",
"If",
"one",
"(",
"only",
")",
"is",
"beta",
"return",
"the",
"non",
"beta",
"one"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository/src/com/ibm/ws/repository/strategies/writeable/AddThenHideOldStrategy.java#L288-L296 |
mabe02/lanterna | src/main/java/com/googlecode/lanterna/gui2/AbstractInteractableComponent.java | AbstractInteractableComponent.onEnterFocus | @Override
public final void onEnterFocus(FocusChangeDirection direction, Interactable previouslyInFocus) {
inFocus = true;
afterEnterFocus(direction, previouslyInFocus);
} | java | @Override
public final void onEnterFocus(FocusChangeDirection direction, Interactable previouslyInFocus) {
inFocus = true;
afterEnterFocus(direction, previouslyInFocus);
} | [
"@",
"Override",
"public",
"final",
"void",
"onEnterFocus",
"(",
"FocusChangeDirection",
"direction",
",",
"Interactable",
"previouslyInFocus",
")",
"{",
"inFocus",
"=",
"true",
";",
"afterEnterFocus",
"(",
"direction",
",",
"previouslyInFocus",
")",
";",
"}"
] | {@inheritDoc}
<p>
This method is final in {@code AbstractInteractableComponent}, please override {@code afterEnterFocus} instead | [
"{"
] | train | https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/gui2/AbstractInteractableComponent.java#L63-L67 |
opentelecoms-org/jsmpp | jsmpp/src/main/java/org/jsmpp/bean/DeliveryReceipt.java | DeliveryReceipt.getDeliveryReceiptValue | private static String getDeliveryReceiptValue(String attrName, String source)
throws IndexOutOfBoundsException {
String tmpAttr = attrName + ":";
int startIndex = source.indexOf(tmpAttr);
if (startIndex < 0) {
return null;
}
startIndex = startIndex + tmpAttr.length();
int endIndex = source.indexOf(" ", startIndex);
if (endIndex > 0) {
return source.substring(startIndex, endIndex);
}
return source.substring(startIndex);
} | java | private static String getDeliveryReceiptValue(String attrName, String source)
throws IndexOutOfBoundsException {
String tmpAttr = attrName + ":";
int startIndex = source.indexOf(tmpAttr);
if (startIndex < 0) {
return null;
}
startIndex = startIndex + tmpAttr.length();
int endIndex = source.indexOf(" ", startIndex);
if (endIndex > 0) {
return source.substring(startIndex, endIndex);
}
return source.substring(startIndex);
} | [
"private",
"static",
"String",
"getDeliveryReceiptValue",
"(",
"String",
"attrName",
",",
"String",
"source",
")",
"throws",
"IndexOutOfBoundsException",
"{",
"String",
"tmpAttr",
"=",
"attrName",
"+",
"\":\"",
";",
"int",
"startIndex",
"=",
"source",
".",
"indexO... | Get the delivery receipt attribute value.
@param attrName is the attribute name.
@param source the original source id:IIIIIIIIII sub:SSS dlvrd:DDD submit
date:YYMMDDhhmm done date:YYMMDDhhmm stat:DDDDDDD err:E
Text:....................
@return the value of specified attribute.
@throws IndexOutOfBoundsException | [
"Get",
"the",
"delivery",
"receipt",
"attribute",
"value",
"."
] | train | https://github.com/opentelecoms-org/jsmpp/blob/acc15e73e7431deabc803731971b15323315baaf/jsmpp/src/main/java/org/jsmpp/bean/DeliveryReceipt.java#L378-L391 |
FasterXML/woodstox | src/main/java/com/ctc/wstx/sr/TypedStreamReader.java | TypedStreamReader.getAttributeAsArray | @Override
public int getAttributeAsArray(int index, TypedArrayDecoder tad) throws XMLStreamException
{
if (mCurrToken != START_ELEMENT) {
throw new IllegalStateException(ErrorConsts.ERR_STATE_NOT_STELEM);
}
return mAttrCollector.decodeValues(index, tad, this);
} | java | @Override
public int getAttributeAsArray(int index, TypedArrayDecoder tad) throws XMLStreamException
{
if (mCurrToken != START_ELEMENT) {
throw new IllegalStateException(ErrorConsts.ERR_STATE_NOT_STELEM);
}
return mAttrCollector.decodeValues(index, tad, this);
} | [
"@",
"Override",
"public",
"int",
"getAttributeAsArray",
"(",
"int",
"index",
",",
"TypedArrayDecoder",
"tad",
")",
"throws",
"XMLStreamException",
"{",
"if",
"(",
"mCurrToken",
"!=",
"START_ELEMENT",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"ErrorC... | Method that allows reading contents of an attribute as an array
of whitespace-separate tokens, decoded using specified decoder.
@return Number of tokens decoded, 0 if none found | [
"Method",
"that",
"allows",
"reading",
"contents",
"of",
"an",
"attribute",
"as",
"an",
"array",
"of",
"whitespace",
"-",
"separate",
"tokens",
"decoded",
"using",
"specified",
"decoder",
"."
] | train | https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/sr/TypedStreamReader.java#L694-L701 |
jbundle/jbundle | base/screen/model/src/main/java/org/jbundle/base/screen/model/ScreenField.java | ScreenField.printEndRecordData | public void printEndRecordData(Rec record, PrintWriter out, int iPrintOptions)
{
this.getScreenFieldView().printEndRecordData(record, out, iPrintOptions);
} | java | public void printEndRecordData(Rec record, PrintWriter out, int iPrintOptions)
{
this.getScreenFieldView().printEndRecordData(record, out, iPrintOptions);
} | [
"public",
"void",
"printEndRecordData",
"(",
"Rec",
"record",
",",
"PrintWriter",
"out",
",",
"int",
"iPrintOptions",
")",
"{",
"this",
".",
"getScreenFieldView",
"(",
")",
".",
"printEndRecordData",
"(",
"record",
",",
"out",
",",
"iPrintOptions",
")",
";",
... | Display the end record in input format.
@return true if default params were found for this form.
@param out The http output stream.
@exception DBException File exception. | [
"Display",
"the",
"end",
"record",
"in",
"input",
"format",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/ScreenField.java#L864-L867 |
rterp/GMapsFX | GMapsFX/src/main/java/com/lynden/gmapsfx/util/MarkerImageFactory.java | MarkerImageFactory.createMarkerImage | public static String createMarkerImage(String uri, String type) {
Logger.getLogger(MarkerImageFactory.class.getName()).log(Level.FINEST, "createMarkerImage using: {0}", uri);
String dataURI = null;
if (uri.startsWith("file:")) {
return createMarkerImageFromFile(uri, type);
}
URL myURL = MarkerImageFactory.class.getResource(uri);
if (myURL != null) {
String myURI = myURL.toExternalForm();
Image img = new Image(myURI);
String imageMimeType = "image/" + type;
try {
dataURI = "data:" + imageMimeType + ";base64,(" +
javax.xml.bind.DatatypeConverter.printBase64Binary(getImageBytes(SwingFXUtils.fromFXImage(img, null), type)) + ")";
} catch (IOException ioe) {
Logger.getLogger(MarkerImageFactory.class.getName()).log(Level.WARNING, "Cannot create marker image", ioe);
dataURI = null;
}
}
return dataURI;
} | java | public static String createMarkerImage(String uri, String type) {
Logger.getLogger(MarkerImageFactory.class.getName()).log(Level.FINEST, "createMarkerImage using: {0}", uri);
String dataURI = null;
if (uri.startsWith("file:")) {
return createMarkerImageFromFile(uri, type);
}
URL myURL = MarkerImageFactory.class.getResource(uri);
if (myURL != null) {
String myURI = myURL.toExternalForm();
Image img = new Image(myURI);
String imageMimeType = "image/" + type;
try {
dataURI = "data:" + imageMimeType + ";base64,(" +
javax.xml.bind.DatatypeConverter.printBase64Binary(getImageBytes(SwingFXUtils.fromFXImage(img, null), type)) + ")";
} catch (IOException ioe) {
Logger.getLogger(MarkerImageFactory.class.getName()).log(Level.WARNING, "Cannot create marker image", ioe);
dataURI = null;
}
}
return dataURI;
} | [
"public",
"static",
"String",
"createMarkerImage",
"(",
"String",
"uri",
",",
"String",
"type",
")",
"{",
"Logger",
".",
"getLogger",
"(",
"MarkerImageFactory",
".",
"class",
".",
"getName",
"(",
")",
")",
".",
"log",
"(",
"Level",
".",
"FINEST",
",",
"\... | Takes a URI for an image contained within an application jar file and
converts it into a data URI for use in a MarkerOptions object.
<p>
Usage:
<p>
markerOptions.icon(MarkerImageFactory.createMarkerImage("/path/to/my/image.jpg", "jpg"));
<p>
Currently tested to work with "jpg" and "png" files.
@param uri
@param type
@return | [
"Takes",
"a",
"URI",
"for",
"an",
"image",
"contained",
"within",
"an",
"application",
"jar",
"file",
"and",
"converts",
"it",
"into",
"a",
"data",
"URI",
"for",
"use",
"in",
"a",
"MarkerOptions",
"object",
".",
"<p",
">",
"Usage",
":",
"<p",
">",
"mar... | train | https://github.com/rterp/GMapsFX/blob/4623d3f768e8ad78fc50ee32dd204d236e01059f/GMapsFX/src/main/java/com/lynden/gmapsfx/util/MarkerImageFactory.java#L49-L77 |
cloudfoundry/uaa | samples/api/src/main/java/org/cloudfoundry/identity/api/web/ContentTypeFilter.java | ContentTypeFilter.doFilter | @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
for (String path : mediaTypes.keySet()) {
if (matches(httpServletRequest, path)) {
response.setContentType(mediaTypes.get(path));
break;
}
}
chain.doFilter(request, response);
} | java | @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
for (String path : mediaTypes.keySet()) {
if (matches(httpServletRequest, path)) {
response.setContentType(mediaTypes.get(path));
break;
}
}
chain.doFilter(request, response);
} | [
"@",
"Override",
"public",
"void",
"doFilter",
"(",
"ServletRequest",
"request",
",",
"ServletResponse",
"response",
",",
"FilterChain",
"chain",
")",
"throws",
"IOException",
",",
"ServletException",
"{",
"HttpServletRequest",
"httpServletRequest",
"=",
"(",
"HttpSer... | Add a content type header to any request whose path matches one of the
supplied paths. | [
"Add",
"a",
"content",
"type",
"header",
"to",
"any",
"request",
"whose",
"path",
"matches",
"one",
"of",
"the",
"supplied",
"paths",
"."
] | train | https://github.com/cloudfoundry/uaa/blob/e8df3d7060580c92d33461106399f9e4f36e3cd2/samples/api/src/main/java/org/cloudfoundry/identity/api/web/ContentTypeFilter.java#L59-L71 |
protostuff/protostuff | protostuff-runtime/src/main/java/io/protostuff/runtime/RuntimeSchema.java | RuntimeSchema.createFrom | public static <T> RuntimeSchema<T> createFrom(Class<T> typeClass,
String[] exclusions, IdStrategy strategy)
{
HashSet<String> set = new HashSet<String>();
for (String exclusion : exclusions)
set.add(exclusion);
return createFrom(typeClass, set, strategy);
} | java | public static <T> RuntimeSchema<T> createFrom(Class<T> typeClass,
String[] exclusions, IdStrategy strategy)
{
HashSet<String> set = new HashSet<String>();
for (String exclusion : exclusions)
set.add(exclusion);
return createFrom(typeClass, set, strategy);
} | [
"public",
"static",
"<",
"T",
">",
"RuntimeSchema",
"<",
"T",
">",
"createFrom",
"(",
"Class",
"<",
"T",
">",
"typeClass",
",",
"String",
"[",
"]",
"exclusions",
",",
"IdStrategy",
"strategy",
")",
"{",
"HashSet",
"<",
"String",
">",
"set",
"=",
"new",... | Generates a schema from the given class with the exclusion of certain fields. | [
"Generates",
"a",
"schema",
"from",
"the",
"given",
"class",
"with",
"the",
"exclusion",
"of",
"certain",
"fields",
"."
] | train | https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-runtime/src/main/java/io/protostuff/runtime/RuntimeSchema.java#L193-L201 |
ironjacamar/ironjacamar | codegenerator/src/main/java/org/ironjacamar/codegenerator/BaseProfile.java | BaseProfile.generateAntXml | void generateAntXml(Definition def, String outputDir)
{
try
{
FileWriter antfw = Utils.createFile("build.xml", outputDir);
BuildXmlGen bxGen = new BuildXmlGen();
bxGen.generate(def, antfw);
antfw.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
} | java | void generateAntXml(Definition def, String outputDir)
{
try
{
FileWriter antfw = Utils.createFile("build.xml", outputDir);
BuildXmlGen bxGen = new BuildXmlGen();
bxGen.generate(def, antfw);
antfw.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
} | [
"void",
"generateAntXml",
"(",
"Definition",
"def",
",",
"String",
"outputDir",
")",
"{",
"try",
"{",
"FileWriter",
"antfw",
"=",
"Utils",
".",
"createFile",
"(",
"\"build.xml\"",
",",
"outputDir",
")",
";",
"BuildXmlGen",
"bxGen",
"=",
"new",
"BuildXmlGen",
... | generate ant build.xml
@param def Definition
@param outputDir output directory | [
"generate",
"ant",
"build",
".",
"xml"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/BaseProfile.java#L337-L350 |
apache/groovy | src/main/java/org/codehaus/groovy/transform/ImmutableASTTransformation.java | ImmutableASTTransformation.checkImmutable | @SuppressWarnings("Unchecked")
public static Object checkImmutable(String className, String fieldName, Object field) {
if (field == null || field instanceof Enum || ImmutablePropertyUtils.isBuiltinImmutable(field.getClass().getName())) return field;
if (field instanceof Collection) return DefaultGroovyMethods.asImmutable((Collection) field);
if (getAnnotationByName(field, "groovy.transform.Immutable") != null) return field;
final String typeName = field.getClass().getName();
throw new RuntimeException(createErrorMessage(className, fieldName, typeName, "constructing"));
} | java | @SuppressWarnings("Unchecked")
public static Object checkImmutable(String className, String fieldName, Object field) {
if (field == null || field instanceof Enum || ImmutablePropertyUtils.isBuiltinImmutable(field.getClass().getName())) return field;
if (field instanceof Collection) return DefaultGroovyMethods.asImmutable((Collection) field);
if (getAnnotationByName(field, "groovy.transform.Immutable") != null) return field;
final String typeName = field.getClass().getName();
throw new RuntimeException(createErrorMessage(className, fieldName, typeName, "constructing"));
} | [
"@",
"SuppressWarnings",
"(",
"\"Unchecked\"",
")",
"public",
"static",
"Object",
"checkImmutable",
"(",
"String",
"className",
",",
"String",
"fieldName",
",",
"Object",
"field",
")",
"{",
"if",
"(",
"field",
"==",
"null",
"||",
"field",
"instanceof",
"Enum",... | This method exists to be binary compatible with 1.7 - 1.8.6 compiled code. | [
"This",
"method",
"exists",
"to",
"be",
"binary",
"compatible",
"with",
"1",
".",
"7",
"-",
"1",
".",
"8",
".",
"6",
"compiled",
"code",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/ImmutableASTTransformation.java#L329-L337 |
mozilla/rhino | src/org/mozilla/javascript/ScriptRuntime.java | ScriptRuntime.jsDelegatesTo | public static boolean jsDelegatesTo(Scriptable lhs, Scriptable rhs) {
Scriptable proto = lhs.getPrototype();
while (proto != null) {
if (proto.equals(rhs)) return true;
proto = proto.getPrototype();
}
return false;
} | java | public static boolean jsDelegatesTo(Scriptable lhs, Scriptable rhs) {
Scriptable proto = lhs.getPrototype();
while (proto != null) {
if (proto.equals(rhs)) return true;
proto = proto.getPrototype();
}
return false;
} | [
"public",
"static",
"boolean",
"jsDelegatesTo",
"(",
"Scriptable",
"lhs",
",",
"Scriptable",
"rhs",
")",
"{",
"Scriptable",
"proto",
"=",
"lhs",
".",
"getPrototype",
"(",
")",
";",
"while",
"(",
"proto",
"!=",
"null",
")",
"{",
"if",
"(",
"proto",
".",
... | Delegates to
@return true iff rhs appears in lhs' proto chain | [
"Delegates",
"to"
] | train | https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/ScriptRuntime.java#L3422-L3431 |
rterp/GMapsFX | GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/JavascriptRuntime.java | JavascriptRuntime.getArrayFunction | @Override
public String getArrayFunction(String function, Object[] ary) {
if (ary == null || ary.length == 0) {
return function + "([]);";
}
StringBuilder sb = new StringBuilder();
sb.append(function).append("([");
for (Object arg : ary) {
if (arg instanceof JavascriptObject) {
sb.append(((JavascriptObject) arg).getVariableName()).append(",");
} else {
sb.append(getArgString(arg)).append(",");
}
}
sb.replace(sb.length() - 1, sb.length(), "]").append(")");
return sb.toString();
} | java | @Override
public String getArrayFunction(String function, Object[] ary) {
if (ary == null || ary.length == 0) {
return function + "([]);";
}
StringBuilder sb = new StringBuilder();
sb.append(function).append("([");
for (Object arg : ary) {
if (arg instanceof JavascriptObject) {
sb.append(((JavascriptObject) arg).getVariableName()).append(",");
} else {
sb.append(getArgString(arg)).append(",");
}
}
sb.replace(sb.length() - 1, sb.length(), "]").append(")");
return sb.toString();
} | [
"@",
"Override",
"public",
"String",
"getArrayFunction",
"(",
"String",
"function",
",",
"Object",
"[",
"]",
"ary",
")",
"{",
"if",
"(",
"ary",
"==",
"null",
"||",
"ary",
".",
"length",
"==",
"0",
")",
"{",
"return",
"function",
"+",
"\"([]);\"",
";",
... | Gets an array function as a String, which then can be passed to the
execute() method.
@param function The function to invoke
@param ary The array of arguments to pass to the function.
@return A string which can be passed to the JavaScript environment to
invoke the function | [
"Gets",
"an",
"array",
"function",
"as",
"a",
"String",
"which",
"then",
"can",
"be",
"passed",
"to",
"the",
"execute",
"()",
"method",
"."
] | train | https://github.com/rterp/GMapsFX/blob/4623d3f768e8ad78fc50ee32dd204d236e01059f/GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/JavascriptRuntime.java#L147-L164 |
Azure/autorest-clientruntime-for-java | azure-client-runtime/src/main/java/com/microsoft/azure/AzureClient.java | AzureClient.pollPutOrPatchSingleAsync | private <T> Single<PollingState<T>> pollPutOrPatchSingleAsync(final PollingState<T> pollingState, final Type resourceType) {
pollingState.withResourceType(resourceType);
pollingState.withSerializerAdapter(restClient().serializerAdapter());
if (pollingState.isStatusTerminal()) {
if (pollingState.isStatusSucceeded() && pollingState.resource() == null) {
return updateStateFromGetResourceOperationAsync(pollingState, pollingState.putOrPatchResourceUri()).toSingle();
}
return Single.just(pollingState);
}
return putOrPatchPollingDispatcher(pollingState, pollingState.putOrPatchResourceUri())
.map(new Func1<PollingState<T>, PollingState<T>>() {
@Override
public PollingState<T> call(PollingState<T> tPollingState) {
tPollingState.throwCloudExceptionIfInFailedState();
return tPollingState;
}
})
.flatMap(new Func1<PollingState<T>, Observable<PollingState<T>>>() {
@Override
public Observable<PollingState<T>> call(PollingState<T> tPollingState) {
if (pollingState.isStatusSucceeded() && pollingState.resource() == null) {
return updateStateFromGetResourceOperationAsync(pollingState, pollingState.putOrPatchResourceUri());
}
return Observable.just(tPollingState);
}
})
.toSingle();
} | java | private <T> Single<PollingState<T>> pollPutOrPatchSingleAsync(final PollingState<T> pollingState, final Type resourceType) {
pollingState.withResourceType(resourceType);
pollingState.withSerializerAdapter(restClient().serializerAdapter());
if (pollingState.isStatusTerminal()) {
if (pollingState.isStatusSucceeded() && pollingState.resource() == null) {
return updateStateFromGetResourceOperationAsync(pollingState, pollingState.putOrPatchResourceUri()).toSingle();
}
return Single.just(pollingState);
}
return putOrPatchPollingDispatcher(pollingState, pollingState.putOrPatchResourceUri())
.map(new Func1<PollingState<T>, PollingState<T>>() {
@Override
public PollingState<T> call(PollingState<T> tPollingState) {
tPollingState.throwCloudExceptionIfInFailedState();
return tPollingState;
}
})
.flatMap(new Func1<PollingState<T>, Observable<PollingState<T>>>() {
@Override
public Observable<PollingState<T>> call(PollingState<T> tPollingState) {
if (pollingState.isStatusSucceeded() && pollingState.resource() == null) {
return updateStateFromGetResourceOperationAsync(pollingState, pollingState.putOrPatchResourceUri());
}
return Observable.just(tPollingState);
}
})
.toSingle();
} | [
"private",
"<",
"T",
">",
"Single",
"<",
"PollingState",
"<",
"T",
">",
">",
"pollPutOrPatchSingleAsync",
"(",
"final",
"PollingState",
"<",
"T",
">",
"pollingState",
",",
"final",
"Type",
"resourceType",
")",
"{",
"pollingState",
".",
"withResourceType",
"(",... | Given a polling state representing state of a PUT or PATCH operation, this method returns {@link Single} object,
when subscribed to it, a single poll will be performed and emits the latest polling state. A poll will be
performed only if the current polling state is not in terminal state.
Note: this method does not implicitly introduce concurrency, by default the deferred action will be executed
in scheduler (if any) set for the provided observable.
@param pollingState the current polling state
@param <T> the type of the resource
@param resourceType the java.lang.reflect.Type of the resource.
@return the observable of which a subscription will lead single polling action. | [
"Given",
"a",
"polling",
"state",
"representing",
"state",
"of",
"a",
"PUT",
"or",
"PATCH",
"operation",
"this",
"method",
"returns",
"{",
"@link",
"Single",
"}",
"object",
"when",
"subscribed",
"to",
"it",
"a",
"single",
"poll",
"will",
"be",
"performed",
... | train | https://github.com/Azure/autorest-clientruntime-for-java/blob/04621e07dbb0456dd5459dd641f06a9fd4f3abad/azure-client-runtime/src/main/java/com/microsoft/azure/AzureClient.java#L190-L217 |
jbundle/osgi | core/src/main/java/org/jbundle/util/osgi/finder/BaseClassFinderService.java | BaseClassFinderService.findResourceURL | public URL findResourceURL(String resourcePath, String versionRange)
{
//if (ClassServiceBootstrap.repositoryAdmin == null)
// return null;
URL url = this.getResourceFromBundle(null, resourcePath, versionRange);
if (url == null) {
Object resource = this.deployThisResource(ClassFinderActivator.getPackageName(resourcePath, true), versionRange, false);
if (resource != null)
url = this.getResourceFromBundle(resource, resourcePath, versionRange);
}
return url;
} | java | public URL findResourceURL(String resourcePath, String versionRange)
{
//if (ClassServiceBootstrap.repositoryAdmin == null)
// return null;
URL url = this.getResourceFromBundle(null, resourcePath, versionRange);
if (url == null) {
Object resource = this.deployThisResource(ClassFinderActivator.getPackageName(resourcePath, true), versionRange, false);
if (resource != null)
url = this.getResourceFromBundle(resource, resourcePath, versionRange);
}
return url;
} | [
"public",
"URL",
"findResourceURL",
"(",
"String",
"resourcePath",
",",
"String",
"versionRange",
")",
"{",
"//if (ClassServiceBootstrap.repositoryAdmin == null)",
"// return null;",
"URL",
"url",
"=",
"this",
".",
"getResourceFromBundle",
"(",
"null",
",",
"resourcePa... | Find, resolve, and return this resource's URL.
@param resourcePath
@return The class definition or null if not found. | [
"Find",
"resolve",
"and",
"return",
"this",
"resource",
"s",
"URL",
"."
] | train | https://github.com/jbundle/osgi/blob/beb02aef78736a4f799aaac001c8f0327bf0536c/core/src/main/java/org/jbundle/util/osgi/finder/BaseClassFinderService.java#L114-L128 |
xetorthio/jedis | src/main/java/redis/clients/jedis/BinaryJedis.java | BinaryJedis.sinterstore | @Override
public Long sinterstore(final byte[] dstkey, final byte[]... keys) {
checkIsInMultiOrPipeline();
client.sinterstore(dstkey, keys);
return client.getIntegerReply();
} | java | @Override
public Long sinterstore(final byte[] dstkey, final byte[]... keys) {
checkIsInMultiOrPipeline();
client.sinterstore(dstkey, keys);
return client.getIntegerReply();
} | [
"@",
"Override",
"public",
"Long",
"sinterstore",
"(",
"final",
"byte",
"[",
"]",
"dstkey",
",",
"final",
"byte",
"[",
"]",
"...",
"keys",
")",
"{",
"checkIsInMultiOrPipeline",
"(",
")",
";",
"client",
".",
"sinterstore",
"(",
"dstkey",
",",
"keys",
")",... | This commanad works exactly like {@link #sinter(byte[]...) SINTER} but instead of being returned
the resulting set is stored as dstkey.
<p>
Time complexity O(N*M) worst case where N is the cardinality of the smallest set and M the
number of sets
@param dstkey
@param keys
@return Status code reply | [
"This",
"commanad",
"works",
"exactly",
"like",
"{"
] | train | https://github.com/xetorthio/jedis/blob/ef4ab403f9d8fd88bd05092fea96de2e9db0bede/src/main/java/redis/clients/jedis/BinaryJedis.java#L1535-L1540 |
docusign/docusign-java-client | src/main/java/com/docusign/esign/api/TemplatesApi.java | TemplatesApi.getDocumentPageImage | public byte[] getDocumentPageImage(String accountId, String templateId, String documentId, String pageNumber) throws ApiException {
return getDocumentPageImage(accountId, templateId, documentId, pageNumber, null);
} | java | public byte[] getDocumentPageImage(String accountId, String templateId, String documentId, String pageNumber) throws ApiException {
return getDocumentPageImage(accountId, templateId, documentId, pageNumber, null);
} | [
"public",
"byte",
"[",
"]",
"getDocumentPageImage",
"(",
"String",
"accountId",
",",
"String",
"templateId",
",",
"String",
"documentId",
",",
"String",
"pageNumber",
")",
"throws",
"ApiException",
"{",
"return",
"getDocumentPageImage",
"(",
"accountId",
",",
"tem... | Gets a page image from a template for display.
Retrieves a page image for display from the specified template.
@param accountId The external account number (int) or account ID Guid. (required)
@param templateId The ID of the template being accessed. (required)
@param documentId The ID of the document being accessed. (required)
@param pageNumber The page number being accessed. (required)
@return byte[] | [
"Gets",
"a",
"page",
"image",
"from",
"a",
"template",
"for",
"display",
".",
"Retrieves",
"a",
"page",
"image",
"for",
"display",
"from",
"the",
"specified",
"template",
"."
] | train | https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/TemplatesApi.java#L1369-L1371 |
nohana/Amalgam | amalgam/src/main/java/com/amalgam/content/pm/PackageManagerUtils.java | PackageManagerUtils.getSignaturePackageInfo | public static PackageInfo getSignaturePackageInfo(Context context, String targetPackage) throws NameNotFoundException {
PackageManager manager = context.getPackageManager();
return manager.getPackageInfo(targetPackage, PackageManager.GET_SIGNATURES);
} | java | public static PackageInfo getSignaturePackageInfo(Context context, String targetPackage) throws NameNotFoundException {
PackageManager manager = context.getPackageManager();
return manager.getPackageInfo(targetPackage, PackageManager.GET_SIGNATURES);
} | [
"public",
"static",
"PackageInfo",
"getSignaturePackageInfo",
"(",
"Context",
"context",
",",
"String",
"targetPackage",
")",
"throws",
"NameNotFoundException",
"{",
"PackageManager",
"manager",
"=",
"context",
".",
"getPackageManager",
"(",
")",
";",
"return",
"manag... | Get the {@link android.content.pm.PackageInfo} that contains signature info.
@param context the context.
@param targetPackage the the target package name.
@return the {@link android.content.pm.PackageInfo}
@throws NameNotFoundException if no package found. | [
"Get",
"the",
"{"
] | train | https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/content/pm/PackageManagerUtils.java#L111-L114 |
spring-projects/spring-android | spring-android-core/src/main/java/org/springframework/util/ClassUtils.java | ClassUtils.isCacheSafe | public static boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) {
Assert.notNull(clazz, "Class must not be null");
try {
ClassLoader target = clazz.getClassLoader();
if (target == null) {
return true;
}
ClassLoader cur = classLoader;
if (cur == target) {
return true;
}
while (cur != null) {
cur = cur.getParent();
if (cur == target) {
return true;
}
}
return false;
}
catch (SecurityException ex) {
// Probably from the system ClassLoader - let's consider it safe.
return true;
}
} | java | public static boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) {
Assert.notNull(clazz, "Class must not be null");
try {
ClassLoader target = clazz.getClassLoader();
if (target == null) {
return true;
}
ClassLoader cur = classLoader;
if (cur == target) {
return true;
}
while (cur != null) {
cur = cur.getParent();
if (cur == target) {
return true;
}
}
return false;
}
catch (SecurityException ex) {
// Probably from the system ClassLoader - let's consider it safe.
return true;
}
} | [
"public",
"static",
"boolean",
"isCacheSafe",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"ClassLoader",
"classLoader",
")",
"{",
"Assert",
".",
"notNull",
"(",
"clazz",
",",
"\"Class must not be null\"",
")",
";",
"try",
"{",
"ClassLoader",
"target",
"=",
"c... | Check whether the given class is cache-safe in the given context,
i.e. whether it is loaded by the given ClassLoader or a parent of it.
@param clazz the class to analyze
@param classLoader the ClassLoader to potentially cache metadata in | [
"Check",
"whether",
"the",
"given",
"class",
"is",
"cache",
"-",
"safe",
"in",
"the",
"given",
"context",
"i",
".",
"e",
".",
"whether",
"it",
"is",
"loaded",
"by",
"the",
"given",
"ClassLoader",
"or",
"a",
"parent",
"of",
"it",
"."
] | train | https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-core/src/main/java/org/springframework/util/ClassUtils.java#L396-L419 |
azkaban/azkaban | az-core/src/main/java/azkaban/utils/PropsUtils.java | PropsUtils.fromJSONString | public static Props fromJSONString(final String json) throws IOException {
final Map<String, String> obj = (Map<String, String>) JSONUtils.parseJSONFromString(json);
final Props props = new Props(null, obj);
return props;
} | java | public static Props fromJSONString(final String json) throws IOException {
final Map<String, String> obj = (Map<String, String>) JSONUtils.parseJSONFromString(json);
final Props props = new Props(null, obj);
return props;
} | [
"public",
"static",
"Props",
"fromJSONString",
"(",
"final",
"String",
"json",
")",
"throws",
"IOException",
"{",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"obj",
"=",
"(",
"Map",
"<",
"String",
",",
"String",
">",
")",
"JSONUtils",
".",
"parseJ... | Convert json String to Prop Object
@param json json formatted string
@return a new constructed Prop Object
@throws IOException exception on parsing json string to prop object | [
"Convert",
"json",
"String",
"to",
"Prop",
"Object"
] | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/az-core/src/main/java/azkaban/utils/PropsUtils.java#L387-L391 |
teatrove/teatrove | trove/src/main/java/org/teatrove/trove/util/IntHashMap.java | IntHashMap.put | public Object put(Object key, Object value) {
if (key instanceof Number) {
return put( ((Number)key).intValue(), value );
}
else {
throw new UnsupportedOperationException
("IntHashMap key must be a number");
}
} | java | public Object put(Object key, Object value) {
if (key instanceof Number) {
return put( ((Number)key).intValue(), value );
}
else {
throw new UnsupportedOperationException
("IntHashMap key must be a number");
}
} | [
"public",
"Object",
"put",
"(",
"Object",
"key",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"key",
"instanceof",
"Number",
")",
"{",
"return",
"put",
"(",
"(",
"(",
"Number",
")",
"key",
")",
".",
"intValue",
"(",
")",
",",
"value",
")",
";",
"... | Associates the specified value with the specified key in this map.
If the map previously contained a mapping for this key, the old
value is replaced.
@param key key with which the specified value is to be associated.
@param value value to be associated with the specified key.
@return previous value associated with specified key, or <tt>null</tt>
if there was no mapping for key. A <tt>null</tt> return can
also indicate that the IntHashMap previously associated
<tt>null</tt> with the specified key. | [
"Associates",
"the",
"specified",
"value",
"with",
"the",
"specified",
"key",
"in",
"this",
"map",
".",
"If",
"the",
"map",
"previously",
"contained",
"a",
"mapping",
"for",
"this",
"key",
"the",
"old",
"value",
"is",
"replaced",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/util/IntHashMap.java#L299-L307 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geometry/GrahamScanConvexHull2D.java | GrahamScanConvexHull2D.isLeft | protected final int isLeft(double[] a, double[] b, double[] o) {
final double cross = getRX(a, o) * getRY(b, o) - getRY(a, o) * getRX(b, o);
if(cross == 0) {
// Compare manhattan distances - same angle!
final double dista = Math.abs(getRX(a, o)) + Math.abs(getRY(a, o));
final double distb = Math.abs(getRX(b, o)) + Math.abs(getRY(b, o));
return Double.compare(dista, distb);
}
return Double.compare(cross, 0);
} | java | protected final int isLeft(double[] a, double[] b, double[] o) {
final double cross = getRX(a, o) * getRY(b, o) - getRY(a, o) * getRX(b, o);
if(cross == 0) {
// Compare manhattan distances - same angle!
final double dista = Math.abs(getRX(a, o)) + Math.abs(getRY(a, o));
final double distb = Math.abs(getRX(b, o)) + Math.abs(getRY(b, o));
return Double.compare(dista, distb);
}
return Double.compare(cross, 0);
} | [
"protected",
"final",
"int",
"isLeft",
"(",
"double",
"[",
"]",
"a",
",",
"double",
"[",
"]",
"b",
",",
"double",
"[",
"]",
"o",
")",
"{",
"final",
"double",
"cross",
"=",
"getRX",
"(",
"a",
",",
"o",
")",
"*",
"getRY",
"(",
"b",
",",
"o",
")... | Test whether a point is left of the other wrt. the origin.
@param a double[] A
@param b double[] B
@param o Origin double[]
@return +1 when left, 0 when same, -1 when right | [
"Test",
"whether",
"a",
"point",
"is",
"left",
"of",
"the",
"other",
"wrt",
".",
"the",
"origin",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geometry/GrahamScanConvexHull2D.java#L193-L202 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RuleBasedNumberFormat.java | RuleBasedNumberFormat.getRuleSetDisplayName | public String getRuleSetDisplayName(String ruleSetName, ULocale loc) {
String[] rsnames = publicRuleSetNames;
for (int ix = 0; ix < rsnames.length; ++ix) {
if (rsnames[ix].equals(ruleSetName)) {
String[] names = getNameListForLocale(loc);
if (names != null) {
return names[ix];
}
return rsnames[ix].substring(1);
}
}
throw new IllegalArgumentException("unrecognized rule set name: " + ruleSetName);
} | java | public String getRuleSetDisplayName(String ruleSetName, ULocale loc) {
String[] rsnames = publicRuleSetNames;
for (int ix = 0; ix < rsnames.length; ++ix) {
if (rsnames[ix].equals(ruleSetName)) {
String[] names = getNameListForLocale(loc);
if (names != null) {
return names[ix];
}
return rsnames[ix].substring(1);
}
}
throw new IllegalArgumentException("unrecognized rule set name: " + ruleSetName);
} | [
"public",
"String",
"getRuleSetDisplayName",
"(",
"String",
"ruleSetName",
",",
"ULocale",
"loc",
")",
"{",
"String",
"[",
"]",
"rsnames",
"=",
"publicRuleSetNames",
";",
"for",
"(",
"int",
"ix",
"=",
"0",
";",
"ix",
"<",
"rsnames",
".",
"length",
";",
"... | Return the rule set display name for the provided rule set and locale.
The locale is matched against the locales for which there is display name data, using
normal fallback rules. If no locale matches, the default display name is returned.
@return the display name for the rule set
@see #getRuleSetDisplayNames
@throws IllegalArgumentException if ruleSetName is not a valid rule set name for this format | [
"Return",
"the",
"rule",
"set",
"display",
"name",
"for",
"the",
"provided",
"rule",
"set",
"and",
"locale",
".",
"The",
"locale",
"is",
"matched",
"against",
"the",
"locales",
"for",
"which",
"there",
"is",
"display",
"name",
"data",
"using",
"normal",
"f... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RuleBasedNumberFormat.java#L1098-L1110 |
salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/service/warden/WardenNotifier.java | WardenNotifier.sendWardenEmailToUser | protected void sendWardenEmailToUser(NotificationContext context, SubSystem subSystem) {
EntityManager em = emf.get();
PrincipalUser user = getWardenUser(context.getAlert().getName());
SuspensionRecord record = SuspensionRecord.findByUserAndSubsystem(em, user, subSystem);
Set<String> to = new HashSet<>();
to.add(user.getEmail());
String subject = "Warden Email Notification";
StringBuilder message = new StringBuilder();
message.append(MessageFormat.format("<p>{0} has been suspended from the Argus system for violating the following policy</p>",
user.getUserName()));
message.append(MessageFormat.format("Subsystem: {0}", subSystem.toString()));
message.append(MessageFormat.format("<br>Policy: {0}",
context.getAlert().getName().replace(WARDEN_ALERT_NAME_PREFIX + user.getUserName() + "-", "")));
message.append(MessageFormat.format("<br>Threshold: {0}", context.getAlert().getTriggers().get(0).getThreshold()));
message.append(MessageFormat.format("<br>Triggering Value: {0}", context.getTriggerEventValue()));
if (record.getSuspendedUntil() == -1) {
message.append("<br> You have been suspended indefinitely");
} else {
message.append(MessageFormat.format("<br>Reinstatement Time: {0}", DATE_FORMATTER.get().format(new Date(record.getSuspendedUntil()))));
}
_mailService.sendMessage(to, subject, message.toString(), "text/html; charset=utf-8", MailService.Priority.HIGH);
to.clear();
to.add("argus-admin@salesforce.com");
message.append("<p><a href='").append(getAlertUrl(context.getAlert().getId())).append("'>Click here to view alert definition.</a><br/>");
_mailService.sendMessage(to, subject, message.toString(), "text/html; charset=utf-8", MailService.Priority.HIGH);
} | java | protected void sendWardenEmailToUser(NotificationContext context, SubSystem subSystem) {
EntityManager em = emf.get();
PrincipalUser user = getWardenUser(context.getAlert().getName());
SuspensionRecord record = SuspensionRecord.findByUserAndSubsystem(em, user, subSystem);
Set<String> to = new HashSet<>();
to.add(user.getEmail());
String subject = "Warden Email Notification";
StringBuilder message = new StringBuilder();
message.append(MessageFormat.format("<p>{0} has been suspended from the Argus system for violating the following policy</p>",
user.getUserName()));
message.append(MessageFormat.format("Subsystem: {0}", subSystem.toString()));
message.append(MessageFormat.format("<br>Policy: {0}",
context.getAlert().getName().replace(WARDEN_ALERT_NAME_PREFIX + user.getUserName() + "-", "")));
message.append(MessageFormat.format("<br>Threshold: {0}", context.getAlert().getTriggers().get(0).getThreshold()));
message.append(MessageFormat.format("<br>Triggering Value: {0}", context.getTriggerEventValue()));
if (record.getSuspendedUntil() == -1) {
message.append("<br> You have been suspended indefinitely");
} else {
message.append(MessageFormat.format("<br>Reinstatement Time: {0}", DATE_FORMATTER.get().format(new Date(record.getSuspendedUntil()))));
}
_mailService.sendMessage(to, subject, message.toString(), "text/html; charset=utf-8", MailService.Priority.HIGH);
to.clear();
to.add("argus-admin@salesforce.com");
message.append("<p><a href='").append(getAlertUrl(context.getAlert().getId())).append("'>Click here to view alert definition.</a><br/>");
_mailService.sendMessage(to, subject, message.toString(), "text/html; charset=utf-8", MailService.Priority.HIGH);
} | [
"protected",
"void",
"sendWardenEmailToUser",
"(",
"NotificationContext",
"context",
",",
"SubSystem",
"subSystem",
")",
"{",
"EntityManager",
"em",
"=",
"emf",
".",
"get",
"(",
")",
";",
"PrincipalUser",
"user",
"=",
"getWardenUser",
"(",
"context",
".",
"getAl... | Sends an email to user and admin with information on suspension and when user will be reinstated.
@param context Notification context of the warden notifier
@param subSystem The sub system user has been suspended from | [
"Sends",
"an",
"email",
"to",
"user",
"and",
"admin",
"with",
"information",
"on",
"suspension",
"and",
"when",
"user",
"will",
"be",
"reinstated",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/service/warden/WardenNotifier.java#L177-L205 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/context/Context.java | Context.executeWithinProcessApplication | public static <T> T executeWithinProcessApplication(Callable<T> callback, ProcessApplicationReference processApplicationReference) {
return executeWithinProcessApplication(callback, processApplicationReference, null);
} | java | public static <T> T executeWithinProcessApplication(Callable<T> callback, ProcessApplicationReference processApplicationReference) {
return executeWithinProcessApplication(callback, processApplicationReference, null);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"executeWithinProcessApplication",
"(",
"Callable",
"<",
"T",
">",
"callback",
",",
"ProcessApplicationReference",
"processApplicationReference",
")",
"{",
"return",
"executeWithinProcessApplication",
"(",
"callback",
",",
"proces... | Use {@link #executeWithinProcessApplication(Callable, ProcessApplicationReference, InvocationContext)}
instead if an {@link InvocationContext} is available. | [
"Use",
"{"
] | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/context/Context.java#L181-L183 |
kiegroup/jbpm | jbpm-services/jbpm-kie-services/src/main/java/org/jbpm/kie/services/impl/utils/PreUndeployOperations.java | PreUndeployOperations.abortUnitActiveProcessInstances | public static Function<DeploymentUnit, Boolean> abortUnitActiveProcessInstances(final RuntimeDataService runtimeDataService, final DeploymentService deploymentService) {
return unit -> {
Collection<ProcessInstanceDesc> activeProcesses = runtimeDataService.getProcessInstancesByDeploymentId(unit.getIdentifier(), activeProcessInstancessStates, new QueryContext(0, -1));
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(unit.getIdentifier());
if (deployedUnit == null) {
throw new IllegalStateException("Undeploy forbidden - No deployments available for " + unit.getIdentifier());
}
for (ProcessInstanceDesc instanceDesc : activeProcesses) {
RuntimeManager manager = deployedUnit.getRuntimeManager();
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(instanceDesc.getId()));
try {
KieSession ksession = engine.getKieSession();
ksession.abortProcessInstance(instanceDesc.getId());
} catch (Exception e) {
logger.error("Undeploy forbidden - Error aborting process instances for deployment unit {} due to: {}", unit.getIdentifier(), e.getMessage());
return false;
} finally {
manager.disposeRuntimeEngine(engine);
}
}
return true;
};
} | java | public static Function<DeploymentUnit, Boolean> abortUnitActiveProcessInstances(final RuntimeDataService runtimeDataService, final DeploymentService deploymentService) {
return unit -> {
Collection<ProcessInstanceDesc> activeProcesses = runtimeDataService.getProcessInstancesByDeploymentId(unit.getIdentifier(), activeProcessInstancessStates, new QueryContext(0, -1));
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(unit.getIdentifier());
if (deployedUnit == null) {
throw new IllegalStateException("Undeploy forbidden - No deployments available for " + unit.getIdentifier());
}
for (ProcessInstanceDesc instanceDesc : activeProcesses) {
RuntimeManager manager = deployedUnit.getRuntimeManager();
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(instanceDesc.getId()));
try {
KieSession ksession = engine.getKieSession();
ksession.abortProcessInstance(instanceDesc.getId());
} catch (Exception e) {
logger.error("Undeploy forbidden - Error aborting process instances for deployment unit {} due to: {}", unit.getIdentifier(), e.getMessage());
return false;
} finally {
manager.disposeRuntimeEngine(engine);
}
}
return true;
};
} | [
"public",
"static",
"Function",
"<",
"DeploymentUnit",
",",
"Boolean",
">",
"abortUnitActiveProcessInstances",
"(",
"final",
"RuntimeDataService",
"runtimeDataService",
",",
"final",
"DeploymentService",
"deploymentService",
")",
"{",
"return",
"unit",
"->",
"{",
"Colle... | Returns a function that checks if a given {@link DeploymentUnit} has active process instances instances, aborts them and,
if nothing wrong happened, lets the undeployment operation continue.
@param runtimeDataService a {@link RuntimeDataService} to query the process instances
@param deploymentService a {@link DeploymentService} to provide access to the deployed unit. | [
"Returns",
"a",
"function",
"that",
"checks",
"if",
"a",
"given",
"{"
] | train | https://github.com/kiegroup/jbpm/blob/c3473c728aa382ebbea01e380c5e754a96647b82/jbpm-services/jbpm-kie-services/src/main/java/org/jbpm/kie/services/impl/utils/PreUndeployOperations.java#L74-L100 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/KeySet.java | KeySet.singleKey | public static KeySet singleKey(Key key) {
return new KeySet(false, ImmutableList.of(key), ImmutableList.<KeyRange>of());
} | java | public static KeySet singleKey(Key key) {
return new KeySet(false, ImmutableList.of(key), ImmutableList.<KeyRange>of());
} | [
"public",
"static",
"KeySet",
"singleKey",
"(",
"Key",
"key",
")",
"{",
"return",
"new",
"KeySet",
"(",
"false",
",",
"ImmutableList",
".",
"of",
"(",
"key",
")",
",",
"ImmutableList",
".",
"<",
"KeyRange",
">",
"of",
"(",
")",
")",
";",
"}"
] | Creates a key set containing a single key. {@code key} should contain exactly as many elements
as there are columns in the primary or index key with this this key set is used. | [
"Creates",
"a",
"key",
"set",
"containing",
"a",
"single",
"key",
".",
"{"
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/KeySet.java#L49-L51 |
grails/grails-core | grails-plugin-controllers/src/main/groovy/org/grails/plugins/web/controllers/api/ControllersDomainBindingApi.java | ControllersDomainBindingApi.initialize | public static void initialize(Object instance, Map namedArgs) {
PersistentEntity dc = getDomainClass(instance);
if (dc == null) {
DataBindingUtils.bindObjectToInstance(instance, namedArgs);
}
else {
DataBindingUtils.bindObjectToDomainInstance(dc, instance, namedArgs);
DataBindingUtils.assignBidirectionalAssociations(instance, namedArgs, dc);
}
autowire(instance);
} | java | public static void initialize(Object instance, Map namedArgs) {
PersistentEntity dc = getDomainClass(instance);
if (dc == null) {
DataBindingUtils.bindObjectToInstance(instance, namedArgs);
}
else {
DataBindingUtils.bindObjectToDomainInstance(dc, instance, namedArgs);
DataBindingUtils.assignBidirectionalAssociations(instance, namedArgs, dc);
}
autowire(instance);
} | [
"public",
"static",
"void",
"initialize",
"(",
"Object",
"instance",
",",
"Map",
"namedArgs",
")",
"{",
"PersistentEntity",
"dc",
"=",
"getDomainClass",
"(",
"instance",
")",
";",
"if",
"(",
"dc",
"==",
"null",
")",
"{",
"DataBindingUtils",
".",
"bindObjectT... | A map based constructor that binds the named arguments to the target instance
@param instance The target instance
@param namedArgs The named arguments | [
"A",
"map",
"based",
"constructor",
"that",
"binds",
"the",
"named",
"arguments",
"to",
"the",
"target",
"instance"
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-plugin-controllers/src/main/groovy/org/grails/plugins/web/controllers/api/ControllersDomainBindingApi.java#L58-L68 |
looly/hutool | hutool-cron/src/main/java/cn/hutool/cron/Scheduler.java | Scheduler.updatePattern | public Scheduler updatePattern(String id, CronPattern pattern) {
this.taskTable.updatePattern(id, pattern);
return this;
} | java | public Scheduler updatePattern(String id, CronPattern pattern) {
this.taskTable.updatePattern(id, pattern);
return this;
} | [
"public",
"Scheduler",
"updatePattern",
"(",
"String",
"id",
",",
"CronPattern",
"pattern",
")",
"{",
"this",
".",
"taskTable",
".",
"updatePattern",
"(",
"id",
",",
"pattern",
")",
";",
"return",
"this",
";",
"}"
] | 更新Task执行的时间规则
@param id Task的ID
@param pattern {@link CronPattern}
@return this
@since 4.0.10 | [
"更新Task执行的时间规则"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-cron/src/main/java/cn/hutool/cron/Scheduler.java#L279-L282 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/data/conversion/converters/BigDecimalConverter.java | BigDecimalConverter.canConvert | @Override
public boolean canConvert(Class<?> fromType, Class<?> toType) {
return fromType != null && isAssignableTo(fromType, String.class) && BigDecimal.class.equals(toType);
} | java | @Override
public boolean canConvert(Class<?> fromType, Class<?> toType) {
return fromType != null && isAssignableTo(fromType, String.class) && BigDecimal.class.equals(toType);
} | [
"@",
"Override",
"public",
"boolean",
"canConvert",
"(",
"Class",
"<",
"?",
">",
"fromType",
",",
"Class",
"<",
"?",
">",
"toType",
")",
"{",
"return",
"fromType",
"!=",
"null",
"&&",
"isAssignableTo",
"(",
"fromType",
",",
"String",
".",
"class",
")",
... | Determines whether this {@link Converter} can convert {@link Object Objects}
{@link Class from type} {@link Class to type}.
@param fromType {@link Class type} to convert from.
@param toType {@link Class type} to convert to.
@return a boolean indicating whether this {@link Converter} can convert {@link Object Objects}
{@link Class from type} {@link Class to type}.
@see org.cp.elements.data.conversion.ConversionService#canConvert(Class, Class)
@see #canConvert(Object, Class) | [
"Determines",
"whether",
"this",
"{",
"@link",
"Converter",
"}",
"can",
"convert",
"{",
"@link",
"Object",
"Objects",
"}",
"{",
"@link",
"Class",
"from",
"type",
"}",
"{",
"@link",
"Class",
"to",
"type",
"}",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/data/conversion/converters/BigDecimalConverter.java#L61-L64 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.