repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
sequencelengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
sequencelengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java | FileUtil.writeLines | public static <T> File writeLines(Collection<T> list, File file, Charset charset, boolean isAppend) throws IORuntimeException {
"""
将列表写入文件
@param <T> 集合元素类型
@param list 列表
@param file 文件
@param charset 字符集
@param isAppend 是否追加
@return 目标文件
@throws IORuntimeException IO异常
"""
return FileWriter.create(file, charset).writeLines(list, isAppend);
} | java | public static <T> File writeLines(Collection<T> list, File file, Charset charset, boolean isAppend) throws IORuntimeException {
return FileWriter.create(file, charset).writeLines(list, isAppend);
} | [
"public",
"static",
"<",
"T",
">",
"File",
"writeLines",
"(",
"Collection",
"<",
"T",
">",
"list",
",",
"File",
"file",
",",
"Charset",
"charset",
",",
"boolean",
"isAppend",
")",
"throws",
"IORuntimeException",
"{",
"return",
"FileWriter",
".",
"create",
"(",
"file",
",",
"charset",
")",
".",
"writeLines",
"(",
"list",
",",
"isAppend",
")",
";",
"}"
] | 将列表写入文件
@param <T> 集合元素类型
@param list 列表
@param file 文件
@param charset 字符集
@param isAppend 是否追加
@return 目标文件
@throws IORuntimeException IO异常 | [
"将列表写入文件"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L3071-L3073 |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/file/FileHelper.java | FileHelper.writeToFile | public static void writeToFile(String pFileName, String pContents, boolean pAppend)
throws IOException {
"""
Method that writes the file contents
@param pFileName
@param pContents
@param pAppend
"""
FileWriter writer = null;
writer = new FileWriter(pFileName, pAppend);
writer.write(pContents);
writer.flush();
writer.close();
} | java | public static void writeToFile(String pFileName, String pContents, boolean pAppend)
throws IOException{
FileWriter writer = null;
writer = new FileWriter(pFileName, pAppend);
writer.write(pContents);
writer.flush();
writer.close();
} | [
"public",
"static",
"void",
"writeToFile",
"(",
"String",
"pFileName",
",",
"String",
"pContents",
",",
"boolean",
"pAppend",
")",
"throws",
"IOException",
"{",
"FileWriter",
"writer",
"=",
"null",
";",
"writer",
"=",
"new",
"FileWriter",
"(",
"pFileName",
",",
"pAppend",
")",
";",
"writer",
".",
"write",
"(",
"pContents",
")",
";",
"writer",
".",
"flush",
"(",
")",
";",
"writer",
".",
"close",
"(",
")",
";",
"}"
] | Method that writes the file contents
@param pFileName
@param pContents
@param pAppend | [
"Method",
"that",
"writes",
"the",
"file",
"contents"
] | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/file/FileHelper.java#L206-L214 |
Alluxio/alluxio | underfs/cos/src/main/java/alluxio/underfs/cos/COSUnderFileSystem.java | COSUnderFileSystem.createInstance | public static COSUnderFileSystem createInstance(AlluxioURI uri, UnderFileSystemConfiguration conf,
AlluxioConfiguration alluxioConf)
throws Exception {
"""
Constructs a new instance of {@link COSUnderFileSystem}.
@param uri the {@link AlluxioURI} for this UFS
@param conf the configuration for this UFS
@param alluxioConf Alluxio configuration
@return the created {@link COSUnderFileSystem} instance
"""
String bucketName = UnderFileSystemUtils.getBucketName(uri);
Preconditions.checkArgument(conf.isSet(PropertyKey.COS_ACCESS_KEY),
"Property %s is required to connect to COS", PropertyKey.COS_ACCESS_KEY);
Preconditions.checkArgument(conf.isSet(PropertyKey.COS_SECRET_KEY),
"Property %s is required to connect to COS", PropertyKey.COS_SECRET_KEY);
Preconditions.checkArgument(conf.isSet(PropertyKey.COS_REGION),
"Property %s is required to connect to COS", PropertyKey.COS_REGION);
Preconditions.checkArgument(conf.isSet(PropertyKey.COS_APP_ID),
"Property %s is required to connect to COS", PropertyKey.COS_APP_ID);
String accessKey = conf.get(PropertyKey.COS_ACCESS_KEY);
String secretKey = conf.get(PropertyKey.COS_SECRET_KEY);
String regionName = conf.get(PropertyKey.COS_REGION);
String appId = conf.get(PropertyKey.COS_APP_ID);
COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
ClientConfig clientConfig = createCOSClientConfig(regionName, conf);
COSClient client = new COSClient(cred, clientConfig);
return new COSUnderFileSystem(uri, client, bucketName, appId, conf, alluxioConf);
} | java | public static COSUnderFileSystem createInstance(AlluxioURI uri, UnderFileSystemConfiguration conf,
AlluxioConfiguration alluxioConf)
throws Exception {
String bucketName = UnderFileSystemUtils.getBucketName(uri);
Preconditions.checkArgument(conf.isSet(PropertyKey.COS_ACCESS_KEY),
"Property %s is required to connect to COS", PropertyKey.COS_ACCESS_KEY);
Preconditions.checkArgument(conf.isSet(PropertyKey.COS_SECRET_KEY),
"Property %s is required to connect to COS", PropertyKey.COS_SECRET_KEY);
Preconditions.checkArgument(conf.isSet(PropertyKey.COS_REGION),
"Property %s is required to connect to COS", PropertyKey.COS_REGION);
Preconditions.checkArgument(conf.isSet(PropertyKey.COS_APP_ID),
"Property %s is required to connect to COS", PropertyKey.COS_APP_ID);
String accessKey = conf.get(PropertyKey.COS_ACCESS_KEY);
String secretKey = conf.get(PropertyKey.COS_SECRET_KEY);
String regionName = conf.get(PropertyKey.COS_REGION);
String appId = conf.get(PropertyKey.COS_APP_ID);
COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
ClientConfig clientConfig = createCOSClientConfig(regionName, conf);
COSClient client = new COSClient(cred, clientConfig);
return new COSUnderFileSystem(uri, client, bucketName, appId, conf, alluxioConf);
} | [
"public",
"static",
"COSUnderFileSystem",
"createInstance",
"(",
"AlluxioURI",
"uri",
",",
"UnderFileSystemConfiguration",
"conf",
",",
"AlluxioConfiguration",
"alluxioConf",
")",
"throws",
"Exception",
"{",
"String",
"bucketName",
"=",
"UnderFileSystemUtils",
".",
"getBucketName",
"(",
"uri",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"conf",
".",
"isSet",
"(",
"PropertyKey",
".",
"COS_ACCESS_KEY",
")",
",",
"\"Property %s is required to connect to COS\"",
",",
"PropertyKey",
".",
"COS_ACCESS_KEY",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"conf",
".",
"isSet",
"(",
"PropertyKey",
".",
"COS_SECRET_KEY",
")",
",",
"\"Property %s is required to connect to COS\"",
",",
"PropertyKey",
".",
"COS_SECRET_KEY",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"conf",
".",
"isSet",
"(",
"PropertyKey",
".",
"COS_REGION",
")",
",",
"\"Property %s is required to connect to COS\"",
",",
"PropertyKey",
".",
"COS_REGION",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"conf",
".",
"isSet",
"(",
"PropertyKey",
".",
"COS_APP_ID",
")",
",",
"\"Property %s is required to connect to COS\"",
",",
"PropertyKey",
".",
"COS_APP_ID",
")",
";",
"String",
"accessKey",
"=",
"conf",
".",
"get",
"(",
"PropertyKey",
".",
"COS_ACCESS_KEY",
")",
";",
"String",
"secretKey",
"=",
"conf",
".",
"get",
"(",
"PropertyKey",
".",
"COS_SECRET_KEY",
")",
";",
"String",
"regionName",
"=",
"conf",
".",
"get",
"(",
"PropertyKey",
".",
"COS_REGION",
")",
";",
"String",
"appId",
"=",
"conf",
".",
"get",
"(",
"PropertyKey",
".",
"COS_APP_ID",
")",
";",
"COSCredentials",
"cred",
"=",
"new",
"BasicCOSCredentials",
"(",
"accessKey",
",",
"secretKey",
")",
";",
"ClientConfig",
"clientConfig",
"=",
"createCOSClientConfig",
"(",
"regionName",
",",
"conf",
")",
";",
"COSClient",
"client",
"=",
"new",
"COSClient",
"(",
"cred",
",",
"clientConfig",
")",
";",
"return",
"new",
"COSUnderFileSystem",
"(",
"uri",
",",
"client",
",",
"bucketName",
",",
"appId",
",",
"conf",
",",
"alluxioConf",
")",
";",
"}"
] | Constructs a new instance of {@link COSUnderFileSystem}.
@param uri the {@link AlluxioURI} for this UFS
@param conf the configuration for this UFS
@param alluxioConf Alluxio configuration
@return the created {@link COSUnderFileSystem} instance | [
"Constructs",
"a",
"new",
"instance",
"of",
"{",
"@link",
"COSUnderFileSystem",
"}",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/underfs/cos/src/main/java/alluxio/underfs/cos/COSUnderFileSystem.java#L75-L97 |
salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/service/schema/ElasticSearchSchemaService.java | ElasticSearchSchemaService.doExtractResponse | @VisibleForTesting
static String doExtractResponse(int statusCode, HttpEntity entity) {
"""
testable version of {@link ElasticSearchSchemaService#extractResponse(Response)}
@param statusCode
@param entity
@return
"""
String message = null;
if (entity != null) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
entity.writeTo(baos);
message = baos.toString("UTF-8");
}
catch (IOException ex) {
throw new SystemException(ex);
}
}
//if the response is in the 400 range, use IllegalArgumentException, which currently translates to a 400 error
if (statusCode>= HttpStatus.SC_BAD_REQUEST && statusCode < HttpStatus.SC_INTERNAL_SERVER_ERROR) {
throw new IllegalArgumentException("Status code: " + statusCode + " . Error occurred. " + message);
}
//everything else that's not in the 200 range, use SystemException, which translates to a 500 error.
if ((statusCode < HttpStatus.SC_OK) || (statusCode >= HttpStatus.SC_MULTIPLE_CHOICES)) {
throw new SystemException("Status code: " + statusCode + " . Error occurred. " + message);
} else {
return message;
}
} | java | @VisibleForTesting
static String doExtractResponse(int statusCode, HttpEntity entity) {
String message = null;
if (entity != null) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
entity.writeTo(baos);
message = baos.toString("UTF-8");
}
catch (IOException ex) {
throw new SystemException(ex);
}
}
//if the response is in the 400 range, use IllegalArgumentException, which currently translates to a 400 error
if (statusCode>= HttpStatus.SC_BAD_REQUEST && statusCode < HttpStatus.SC_INTERNAL_SERVER_ERROR) {
throw new IllegalArgumentException("Status code: " + statusCode + " . Error occurred. " + message);
}
//everything else that's not in the 200 range, use SystemException, which translates to a 500 error.
if ((statusCode < HttpStatus.SC_OK) || (statusCode >= HttpStatus.SC_MULTIPLE_CHOICES)) {
throw new SystemException("Status code: " + statusCode + " . Error occurred. " + message);
} else {
return message;
}
} | [
"@",
"VisibleForTesting",
"static",
"String",
"doExtractResponse",
"(",
"int",
"statusCode",
",",
"HttpEntity",
"entity",
")",
"{",
"String",
"message",
"=",
"null",
";",
"if",
"(",
"entity",
"!=",
"null",
")",
"{",
"try",
"(",
"ByteArrayOutputStream",
"baos",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
")",
"{",
"entity",
".",
"writeTo",
"(",
"baos",
")",
";",
"message",
"=",
"baos",
".",
"toString",
"(",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"SystemException",
"(",
"ex",
")",
";",
"}",
"}",
"//if the response is in the 400 range, use IllegalArgumentException, which currently translates to a 400 error",
"if",
"(",
"statusCode",
">=",
"HttpStatus",
".",
"SC_BAD_REQUEST",
"&&",
"statusCode",
"<",
"HttpStatus",
".",
"SC_INTERNAL_SERVER_ERROR",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Status code: \"",
"+",
"statusCode",
"+",
"\" . Error occurred. \"",
"+",
"message",
")",
";",
"}",
"//everything else that's not in the 200 range, use SystemException, which translates to a 500 error.",
"if",
"(",
"(",
"statusCode",
"<",
"HttpStatus",
".",
"SC_OK",
")",
"||",
"(",
"statusCode",
">=",
"HttpStatus",
".",
"SC_MULTIPLE_CHOICES",
")",
")",
"{",
"throw",
"new",
"SystemException",
"(",
"\"Status code: \"",
"+",
"statusCode",
"+",
"\" . Error occurred. \"",
"+",
"message",
")",
";",
"}",
"else",
"{",
"return",
"message",
";",
"}",
"}"
] | testable version of {@link ElasticSearchSchemaService#extractResponse(Response)}
@param statusCode
@param entity
@return | [
"testable",
"version",
"of",
"{"
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/service/schema/ElasticSearchSchemaService.java#L1410-L1434 |
Azure/azure-sdk-for-java | policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyStatesInner.java | PolicyStatesInner.listQueryResultsForResourceGroupLevelPolicyAssignmentAsync | public Observable<PolicyStatesQueryResultsInner> listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, String policyAssignmentName) {
"""
Queries policy states for the resource group level policy assignment.
@param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest'
@param subscriptionId Microsoft Azure subscription ID.
@param resourceGroupName Resource group name.
@param policyAssignmentName Policy assignment name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PolicyStatesQueryResultsInner object
"""
return listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName, policyAssignmentName).map(new Func1<ServiceResponse<PolicyStatesQueryResultsInner>, PolicyStatesQueryResultsInner>() {
@Override
public PolicyStatesQueryResultsInner call(ServiceResponse<PolicyStatesQueryResultsInner> response) {
return response.body();
}
});
} | java | public Observable<PolicyStatesQueryResultsInner> listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, String policyAssignmentName) {
return listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName, policyAssignmentName).map(new Func1<ServiceResponse<PolicyStatesQueryResultsInner>, PolicyStatesQueryResultsInner>() {
@Override
public PolicyStatesQueryResultsInner call(ServiceResponse<PolicyStatesQueryResultsInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"PolicyStatesQueryResultsInner",
">",
"listQueryResultsForResourceGroupLevelPolicyAssignmentAsync",
"(",
"PolicyStatesResource",
"policyStatesResource",
",",
"String",
"subscriptionId",
",",
"String",
"resourceGroupName",
",",
"String",
"policyAssignmentName",
")",
"{",
"return",
"listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync",
"(",
"policyStatesResource",
",",
"subscriptionId",
",",
"resourceGroupName",
",",
"policyAssignmentName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"PolicyStatesQueryResultsInner",
">",
",",
"PolicyStatesQueryResultsInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"PolicyStatesQueryResultsInner",
"call",
"(",
"ServiceResponse",
"<",
"PolicyStatesQueryResultsInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Queries policy states for the resource group level policy assignment.
@param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest'
@param subscriptionId Microsoft Azure subscription ID.
@param resourceGroupName Resource group name.
@param policyAssignmentName Policy assignment name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PolicyStatesQueryResultsInner object | [
"Queries",
"policy",
"states",
"for",
"the",
"resource",
"group",
"level",
"policy",
"assignment",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyStatesInner.java#L2909-L2916 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/collection/ArrayHelper.java | ArrayHelper.getAllExceptFirst | @Nullable
@ReturnsMutableCopy
public static double [] getAllExceptFirst (@Nullable final double [] aArray, @Nonnegative final int nElementsToSkip) {
"""
Get an array that contains all elements, except for the first <em>n</em>
elements.
@param aArray
The source array. May be <code>null</code>.
@param nElementsToSkip
The number of elements to skip. Must be >= 0!
@return <code>null</code> if the passed array is <code>null</code> or has
≤ elements than elements to be skipped. A non-<code>null</code>
copy of the array without the first elements otherwise.
"""
ValueEnforcer.isGE0 (nElementsToSkip, "ElementsToSkip");
if (nElementsToSkip == 0)
return aArray;
if (aArray == null || nElementsToSkip >= aArray.length)
return null;
return getCopy (aArray, nElementsToSkip, aArray.length - nElementsToSkip);
} | java | @Nullable
@ReturnsMutableCopy
public static double [] getAllExceptFirst (@Nullable final double [] aArray, @Nonnegative final int nElementsToSkip)
{
ValueEnforcer.isGE0 (nElementsToSkip, "ElementsToSkip");
if (nElementsToSkip == 0)
return aArray;
if (aArray == null || nElementsToSkip >= aArray.length)
return null;
return getCopy (aArray, nElementsToSkip, aArray.length - nElementsToSkip);
} | [
"@",
"Nullable",
"@",
"ReturnsMutableCopy",
"public",
"static",
"double",
"[",
"]",
"getAllExceptFirst",
"(",
"@",
"Nullable",
"final",
"double",
"[",
"]",
"aArray",
",",
"@",
"Nonnegative",
"final",
"int",
"nElementsToSkip",
")",
"{",
"ValueEnforcer",
".",
"isGE0",
"(",
"nElementsToSkip",
",",
"\"ElementsToSkip\"",
")",
";",
"if",
"(",
"nElementsToSkip",
"==",
"0",
")",
"return",
"aArray",
";",
"if",
"(",
"aArray",
"==",
"null",
"||",
"nElementsToSkip",
">=",
"aArray",
".",
"length",
")",
"return",
"null",
";",
"return",
"getCopy",
"(",
"aArray",
",",
"nElementsToSkip",
",",
"aArray",
".",
"length",
"-",
"nElementsToSkip",
")",
";",
"}"
] | Get an array that contains all elements, except for the first <em>n</em>
elements.
@param aArray
The source array. May be <code>null</code>.
@param nElementsToSkip
The number of elements to skip. Must be >= 0!
@return <code>null</code> if the passed array is <code>null</code> or has
≤ elements than elements to be skipped. A non-<code>null</code>
copy of the array without the first elements otherwise. | [
"Get",
"an",
"array",
"that",
"contains",
"all",
"elements",
"except",
"for",
"the",
"first",
"<em",
">",
"n<",
"/",
"em",
">",
"elements",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/collection/ArrayHelper.java#L3172-L3183 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/AbstractMemberWriter.java | AbstractMemberWriter.addComment | protected void addComment(ProgramElementDoc member, Content htmltree) {
"""
Add the comment for the given member.
@param member the member being documented.
@param htmltree the content tree to which the comment will be added.
"""
if (member.inlineTags().length > 0) {
writer.addInlineComment(member, htmltree);
}
} | java | protected void addComment(ProgramElementDoc member, Content htmltree) {
if (member.inlineTags().length > 0) {
writer.addInlineComment(member, htmltree);
}
} | [
"protected",
"void",
"addComment",
"(",
"ProgramElementDoc",
"member",
",",
"Content",
"htmltree",
")",
"{",
"if",
"(",
"member",
".",
"inlineTags",
"(",
")",
".",
"length",
">",
"0",
")",
"{",
"writer",
".",
"addInlineComment",
"(",
"member",
",",
"htmltree",
")",
";",
"}",
"}"
] | Add the comment for the given member.
@param member the member being documented.
@param htmltree the content tree to which the comment will be added. | [
"Add",
"the",
"comment",
"for",
"the",
"given",
"member",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/AbstractMemberWriter.java#L369-L373 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/fs/HarFileSystem.java | HarFileSystem.getFileBlockLocations | @Override
public BlockLocation[] getFileBlockLocations(FileStatus file, long start,
long len) throws IOException {
"""
Get block locations from the underlying fs and fix their
offsets and lengths.
@param file the input filestatus to get block locations
@param start the start of the desired range in the contained file
@param len the length of the desired range
@return block locations for this segment of file
@throws IOException
"""
HarStatus hstatus = getFileHarStatus(file.getPath(), null);
Path partPath = new Path(archivePath, hstatus.getPartName());
FileStatus partStatus = fs.getFileStatus(partPath);
// get all part blocks that overlap with the desired file blocks
BlockLocation[] locations =
fs.getFileBlockLocations(partStatus,
hstatus.getStartIndex() + start, len);
return fixBlockLocations(locations, start, len, hstatus.getStartIndex());
} | java | @Override
public BlockLocation[] getFileBlockLocations(FileStatus file, long start,
long len) throws IOException {
HarStatus hstatus = getFileHarStatus(file.getPath(), null);
Path partPath = new Path(archivePath, hstatus.getPartName());
FileStatus partStatus = fs.getFileStatus(partPath);
// get all part blocks that overlap with the desired file blocks
BlockLocation[] locations =
fs.getFileBlockLocations(partStatus,
hstatus.getStartIndex() + start, len);
return fixBlockLocations(locations, start, len, hstatus.getStartIndex());
} | [
"@",
"Override",
"public",
"BlockLocation",
"[",
"]",
"getFileBlockLocations",
"(",
"FileStatus",
"file",
",",
"long",
"start",
",",
"long",
"len",
")",
"throws",
"IOException",
"{",
"HarStatus",
"hstatus",
"=",
"getFileHarStatus",
"(",
"file",
".",
"getPath",
"(",
")",
",",
"null",
")",
";",
"Path",
"partPath",
"=",
"new",
"Path",
"(",
"archivePath",
",",
"hstatus",
".",
"getPartName",
"(",
")",
")",
";",
"FileStatus",
"partStatus",
"=",
"fs",
".",
"getFileStatus",
"(",
"partPath",
")",
";",
"// get all part blocks that overlap with the desired file blocks",
"BlockLocation",
"[",
"]",
"locations",
"=",
"fs",
".",
"getFileBlockLocations",
"(",
"partStatus",
",",
"hstatus",
".",
"getStartIndex",
"(",
")",
"+",
"start",
",",
"len",
")",
";",
"return",
"fixBlockLocations",
"(",
"locations",
",",
"start",
",",
"len",
",",
"hstatus",
".",
"getStartIndex",
"(",
")",
")",
";",
"}"
] | Get block locations from the underlying fs and fix their
offsets and lengths.
@param file the input filestatus to get block locations
@param start the start of the desired range in the contained file
@param len the length of the desired range
@return block locations for this segment of file
@throws IOException | [
"Get",
"block",
"locations",
"from",
"the",
"underlying",
"fs",
"and",
"fix",
"their",
"offsets",
"and",
"lengths",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/HarFileSystem.java#L465-L478 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java | IoUtil.readHex | public static String readHex(InputStream in, int length, boolean toLowerCase) throws IORuntimeException {
"""
读取16进制字符串
@param in {@link InputStream}
@param length 长度
@param toLowerCase true 传换成小写格式 , false 传换成大写格式
@return 16进制字符串
@throws IORuntimeException IO异常
"""
return HexUtil.encodeHexStr(readBytes(in, length), toLowerCase);
} | java | public static String readHex(InputStream in, int length, boolean toLowerCase) throws IORuntimeException {
return HexUtil.encodeHexStr(readBytes(in, length), toLowerCase);
} | [
"public",
"static",
"String",
"readHex",
"(",
"InputStream",
"in",
",",
"int",
"length",
",",
"boolean",
"toLowerCase",
")",
"throws",
"IORuntimeException",
"{",
"return",
"HexUtil",
".",
"encodeHexStr",
"(",
"readBytes",
"(",
"in",
",",
"length",
")",
",",
"toLowerCase",
")",
";",
"}"
] | 读取16进制字符串
@param in {@link InputStream}
@param length 长度
@param toLowerCase true 传换成小写格式 , false 传换成大写格式
@return 16进制字符串
@throws IORuntimeException IO异常 | [
"读取16进制字符串"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java#L569-L571 |
Microsoft/azure-maven-plugins | azure-webapp-maven-plugin/src/main/java/com/microsoft/azure/maven/webapp/handlers/ArtifactHandlerUtils.java | ArtifactHandlerUtils.getRealWarDeployExecutor | public static Runnable getRealWarDeployExecutor(final DeployTarget target, final File war, final String path)
throws MojoExecutionException {
"""
Interfaces WebApp && DeploymentSlot define their own warDeploy API separately.
Ideally, it should be defined in their base interface WebAppBase.
{@link com.microsoft.azure.management.appservice.WebAppBase}
Comparing to abstracting an adapter for WebApp && DeploymentSlot, we choose a lighter solution:
work around to get the real implementation of warDeploy.
"""
if (target instanceof WebAppDeployTarget) {
return new Runnable() {
@Override
public void run() {
((WebAppDeployTarget) target).warDeploy(war, path);
}
};
}
if (target instanceof DeploymentSlotDeployTarget) {
return new Runnable() {
@Override
public void run() {
((DeploymentSlotDeployTarget) target).warDeploy(war, path);
}
};
}
throw new MojoExecutionException(
"The type of deploy target is unknown, supported types are WebApp and DeploymentSlot.");
} | java | public static Runnable getRealWarDeployExecutor(final DeployTarget target, final File war, final String path)
throws MojoExecutionException {
if (target instanceof WebAppDeployTarget) {
return new Runnable() {
@Override
public void run() {
((WebAppDeployTarget) target).warDeploy(war, path);
}
};
}
if (target instanceof DeploymentSlotDeployTarget) {
return new Runnable() {
@Override
public void run() {
((DeploymentSlotDeployTarget) target).warDeploy(war, path);
}
};
}
throw new MojoExecutionException(
"The type of deploy target is unknown, supported types are WebApp and DeploymentSlot.");
} | [
"public",
"static",
"Runnable",
"getRealWarDeployExecutor",
"(",
"final",
"DeployTarget",
"target",
",",
"final",
"File",
"war",
",",
"final",
"String",
"path",
")",
"throws",
"MojoExecutionException",
"{",
"if",
"(",
"target",
"instanceof",
"WebAppDeployTarget",
")",
"{",
"return",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"(",
"(",
"WebAppDeployTarget",
")",
"target",
")",
".",
"warDeploy",
"(",
"war",
",",
"path",
")",
";",
"}",
"}",
";",
"}",
"if",
"(",
"target",
"instanceof",
"DeploymentSlotDeployTarget",
")",
"{",
"return",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"(",
"(",
"DeploymentSlotDeployTarget",
")",
"target",
")",
".",
"warDeploy",
"(",
"war",
",",
"path",
")",
";",
"}",
"}",
";",
"}",
"throw",
"new",
"MojoExecutionException",
"(",
"\"The type of deploy target is unknown, supported types are WebApp and DeploymentSlot.\"",
")",
";",
"}"
] | Interfaces WebApp && DeploymentSlot define their own warDeploy API separately.
Ideally, it should be defined in their base interface WebAppBase.
{@link com.microsoft.azure.management.appservice.WebAppBase}
Comparing to abstracting an adapter for WebApp && DeploymentSlot, we choose a lighter solution:
work around to get the real implementation of warDeploy. | [
"Interfaces",
"WebApp",
"&&",
"DeploymentSlot",
"define",
"their",
"own",
"warDeploy",
"API",
"separately",
".",
"Ideally",
"it",
"should",
"be",
"defined",
"in",
"their",
"base",
"interface",
"WebAppBase",
".",
"{"
] | train | https://github.com/Microsoft/azure-maven-plugins/blob/a254902e820185df1823b1d692c7c1d119490b1e/azure-webapp-maven-plugin/src/main/java/com/microsoft/azure/maven/webapp/handlers/ArtifactHandlerUtils.java#L29-L50 |
baratine/baratine | web/src/main/java/com/caucho/v5/util/CharCursor.java | CharCursor.regionMatches | public boolean regionMatches(char []cb, int offset, int length) {
"""
True if the cursor matches the character buffer
If match fails, return the pointer to its original.
"""
int pos = getIndex();
char ch = current();
for (int i = 0; i < length; i++) {
if (cb[i + offset] != ch) {
setIndex(pos);
return false;
}
ch = next();
}
return true;
} | java | public boolean regionMatches(char []cb, int offset, int length)
{
int pos = getIndex();
char ch = current();
for (int i = 0; i < length; i++) {
if (cb[i + offset] != ch) {
setIndex(pos);
return false;
}
ch = next();
}
return true;
} | [
"public",
"boolean",
"regionMatches",
"(",
"char",
"[",
"]",
"cb",
",",
"int",
"offset",
",",
"int",
"length",
")",
"{",
"int",
"pos",
"=",
"getIndex",
"(",
")",
";",
"char",
"ch",
"=",
"current",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"cb",
"[",
"i",
"+",
"offset",
"]",
"!=",
"ch",
")",
"{",
"setIndex",
"(",
"pos",
")",
";",
"return",
"false",
";",
"}",
"ch",
"=",
"next",
"(",
")",
";",
"}",
"return",
"true",
";",
"}"
] | True if the cursor matches the character buffer
If match fails, return the pointer to its original. | [
"True",
"if",
"the",
"cursor",
"matches",
"the",
"character",
"buffer"
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/web/src/main/java/com/caucho/v5/util/CharCursor.java#L124-L138 |
hawkular/hawkular-agent | hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/JBossASClient.java | JBossASClient.readResource | public ModelNode readResource(Address addr, boolean recursive) throws Exception {
"""
This returns information on the resource at the given address, recursively
returning child nodes with the result if recursive argument is set to <code>true</code>.
This will not return an exception if the address points to a non-existent resource, rather,
it will just return null. You can use this as a test for resource existence.
@param addr the address of the resource
@param recursive if true, return all child data within the resource node
@return the found item or null if not found
@throws Exception if some error prevented the lookup from even happening
"""
final ModelNode request = createRequest(READ_RESOURCE, addr);
request.get("recursive").set(recursive);
final ModelNode results = getModelControllerClient().execute(request, OperationMessageHandler.logging);
if (isSuccess(results)) {
final ModelNode resource = getResults(results);
return resource;
} else {
return null;
}
} | java | public ModelNode readResource(Address addr, boolean recursive) throws Exception {
final ModelNode request = createRequest(READ_RESOURCE, addr);
request.get("recursive").set(recursive);
final ModelNode results = getModelControllerClient().execute(request, OperationMessageHandler.logging);
if (isSuccess(results)) {
final ModelNode resource = getResults(results);
return resource;
} else {
return null;
}
} | [
"public",
"ModelNode",
"readResource",
"(",
"Address",
"addr",
",",
"boolean",
"recursive",
")",
"throws",
"Exception",
"{",
"final",
"ModelNode",
"request",
"=",
"createRequest",
"(",
"READ_RESOURCE",
",",
"addr",
")",
";",
"request",
".",
"get",
"(",
"\"recursive\"",
")",
".",
"set",
"(",
"recursive",
")",
";",
"final",
"ModelNode",
"results",
"=",
"getModelControllerClient",
"(",
")",
".",
"execute",
"(",
"request",
",",
"OperationMessageHandler",
".",
"logging",
")",
";",
"if",
"(",
"isSuccess",
"(",
"results",
")",
")",
"{",
"final",
"ModelNode",
"resource",
"=",
"getResults",
"(",
"results",
")",
";",
"return",
"resource",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] | This returns information on the resource at the given address, recursively
returning child nodes with the result if recursive argument is set to <code>true</code>.
This will not return an exception if the address points to a non-existent resource, rather,
it will just return null. You can use this as a test for resource existence.
@param addr the address of the resource
@param recursive if true, return all child data within the resource node
@return the found item or null if not found
@throws Exception if some error prevented the lookup from even happening | [
"This",
"returns",
"information",
"on",
"the",
"resource",
"at",
"the",
"given",
"address",
"recursively",
"returning",
"child",
"nodes",
"with",
"the",
"result",
"if",
"recursive",
"argument",
"is",
"set",
"to",
"<code",
">",
"true<",
"/",
"code",
">",
".",
"This",
"will",
"not",
"return",
"an",
"exception",
"if",
"the",
"address",
"points",
"to",
"a",
"non",
"-",
"existent",
"resource",
"rather",
"it",
"will",
"just",
"return",
"null",
".",
"You",
"can",
"use",
"this",
"as",
"a",
"test",
"for",
"resource",
"existence",
"."
] | train | https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/JBossASClient.java#L311-L321 |
Harium/keel | src/main/java/com/harium/keel/catalano/math/distance/Distance.java | Distance.QuasiEuclidean | public static double QuasiEuclidean(IntPoint p, IntPoint q) {
"""
Gets the Quasi-Euclidean distance between two points.
@param p IntPoint with X and Y axis coordinates.
@param q IntPoint with X and Y axis coordinates.
@return The Quasi Euclidean distance between p and q.
"""
return QuasiEuclidean(p.x, p.y, q.x, q.y);
} | java | public static double QuasiEuclidean(IntPoint p, IntPoint q) {
return QuasiEuclidean(p.x, p.y, q.x, q.y);
} | [
"public",
"static",
"double",
"QuasiEuclidean",
"(",
"IntPoint",
"p",
",",
"IntPoint",
"q",
")",
"{",
"return",
"QuasiEuclidean",
"(",
"p",
".",
"x",
",",
"p",
".",
"y",
",",
"q",
".",
"x",
",",
"q",
".",
"y",
")",
";",
"}"
] | Gets the Quasi-Euclidean distance between two points.
@param p IntPoint with X and Y axis coordinates.
@param q IntPoint with X and Y axis coordinates.
@return The Quasi Euclidean distance between p and q. | [
"Gets",
"the",
"Quasi",
"-",
"Euclidean",
"distance",
"between",
"two",
"points",
"."
] | train | https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/distance/Distance.java#L790-L792 |
gallandarakhneorg/afc | core/vmutils/src/main/java/org/arakhne/afc/vmutil/VMCommandLine.java | VMCommandLine.launchVMWithJar | @SuppressWarnings("checkstyle:magicnumber")
public static Process launchVMWithJar(File jarFile, String... additionalParams) throws IOException {
"""
Run a jar file inside a new VM.
@param jarFile is the jar file to launch.
@param additionalParams is the list of additional parameters
@return the process that is running the new virtual machine, neither <code>null</code>
@throws IOException when a IO error occurs.
@since 6.2
"""
final String javaBin = getVMBinary();
if (javaBin == null) {
throw new FileNotFoundException("java"); //$NON-NLS-1$
}
final long totalMemory = Runtime.getRuntime().maxMemory() / 1024;
final String userDir = FileSystem.getUserHomeDirectoryName();
final int nParams = 4;
final String[] params = new String[additionalParams.length + nParams];
params[0] = javaBin;
params[1] = "-Xmx" + totalMemory + "k"; //$NON-NLS-1$ //$NON-NLS-2$
params[2] = "-jar"; //$NON-NLS-1$
params[3] = jarFile.getAbsolutePath();
System.arraycopy(additionalParams, 0, params, nParams, additionalParams.length);
return Runtime.getRuntime().exec(params, null, new File(userDir));
} | java | @SuppressWarnings("checkstyle:magicnumber")
public static Process launchVMWithJar(File jarFile, String... additionalParams) throws IOException {
final String javaBin = getVMBinary();
if (javaBin == null) {
throw new FileNotFoundException("java"); //$NON-NLS-1$
}
final long totalMemory = Runtime.getRuntime().maxMemory() / 1024;
final String userDir = FileSystem.getUserHomeDirectoryName();
final int nParams = 4;
final String[] params = new String[additionalParams.length + nParams];
params[0] = javaBin;
params[1] = "-Xmx" + totalMemory + "k"; //$NON-NLS-1$ //$NON-NLS-2$
params[2] = "-jar"; //$NON-NLS-1$
params[3] = jarFile.getAbsolutePath();
System.arraycopy(additionalParams, 0, params, nParams, additionalParams.length);
return Runtime.getRuntime().exec(params, null, new File(userDir));
} | [
"@",
"SuppressWarnings",
"(",
"\"checkstyle:magicnumber\"",
")",
"public",
"static",
"Process",
"launchVMWithJar",
"(",
"File",
"jarFile",
",",
"String",
"...",
"additionalParams",
")",
"throws",
"IOException",
"{",
"final",
"String",
"javaBin",
"=",
"getVMBinary",
"(",
")",
";",
"if",
"(",
"javaBin",
"==",
"null",
")",
"{",
"throw",
"new",
"FileNotFoundException",
"(",
"\"java\"",
")",
";",
"//$NON-NLS-1$",
"}",
"final",
"long",
"totalMemory",
"=",
"Runtime",
".",
"getRuntime",
"(",
")",
".",
"maxMemory",
"(",
")",
"/",
"1024",
";",
"final",
"String",
"userDir",
"=",
"FileSystem",
".",
"getUserHomeDirectoryName",
"(",
")",
";",
"final",
"int",
"nParams",
"=",
"4",
";",
"final",
"String",
"[",
"]",
"params",
"=",
"new",
"String",
"[",
"additionalParams",
".",
"length",
"+",
"nParams",
"]",
";",
"params",
"[",
"0",
"]",
"=",
"javaBin",
";",
"params",
"[",
"1",
"]",
"=",
"\"-Xmx\"",
"+",
"totalMemory",
"+",
"\"k\"",
";",
"//$NON-NLS-1$ //$NON-NLS-2$",
"params",
"[",
"2",
"]",
"=",
"\"-jar\"",
";",
"//$NON-NLS-1$",
"params",
"[",
"3",
"]",
"=",
"jarFile",
".",
"getAbsolutePath",
"(",
")",
";",
"System",
".",
"arraycopy",
"(",
"additionalParams",
",",
"0",
",",
"params",
",",
"nParams",
",",
"additionalParams",
".",
"length",
")",
";",
"return",
"Runtime",
".",
"getRuntime",
"(",
")",
".",
"exec",
"(",
"params",
",",
"null",
",",
"new",
"File",
"(",
"userDir",
")",
")",
";",
"}"
] | Run a jar file inside a new VM.
@param jarFile is the jar file to launch.
@param additionalParams is the list of additional parameters
@return the process that is running the new virtual machine, neither <code>null</code>
@throws IOException when a IO error occurs.
@since 6.2 | [
"Run",
"a",
"jar",
"file",
"inside",
"a",
"new",
"VM",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/vmutils/src/main/java/org/arakhne/afc/vmutil/VMCommandLine.java#L255-L271 |
TheHortonMachine/hortonmachine | gears/src/main/java/oms3/ngmf/util/cosu/luca/Sorter.java | Sorter.compare | @Override
public int compare(Integer o1, Integer o2) {
"""
For ascending,
return 1 if dataArray[o1] is greater than dataArray[o2]
return 0 if dataArray[o1] is equal to dataArray[o2]
return -1 if dataArray[o1] is less than dataArray[o2]
For decending, do it in the opposize way.
"""
double diff = dataArray[o2] - dataArray[o1];
if (diff == 0) {
return 0;
}
if (sortType == ASCENDING) {
return (diff > 0) ? -1 : 1;
} else {
return (diff > 0) ? 1 : -1;
}
} | java | @Override
public int compare(Integer o1, Integer o2) {
double diff = dataArray[o2] - dataArray[o1];
if (diff == 0) {
return 0;
}
if (sortType == ASCENDING) {
return (diff > 0) ? -1 : 1;
} else {
return (diff > 0) ? 1 : -1;
}
} | [
"@",
"Override",
"public",
"int",
"compare",
"(",
"Integer",
"o1",
",",
"Integer",
"o2",
")",
"{",
"double",
"diff",
"=",
"dataArray",
"[",
"o2",
"]",
"-",
"dataArray",
"[",
"o1",
"]",
";",
"if",
"(",
"diff",
"==",
"0",
")",
"{",
"return",
"0",
";",
"}",
"if",
"(",
"sortType",
"==",
"ASCENDING",
")",
"{",
"return",
"(",
"diff",
">",
"0",
")",
"?",
"-",
"1",
":",
"1",
";",
"}",
"else",
"{",
"return",
"(",
"diff",
">",
"0",
")",
"?",
"1",
":",
"-",
"1",
";",
"}",
"}"
] | For ascending,
return 1 if dataArray[o1] is greater than dataArray[o2]
return 0 if dataArray[o1] is equal to dataArray[o2]
return -1 if dataArray[o1] is less than dataArray[o2]
For decending, do it in the opposize way. | [
"For",
"ascending",
"return",
"1",
"if",
"dataArray",
"[",
"o1",
"]",
"is",
"greater",
"than",
"dataArray",
"[",
"o2",
"]",
"return",
"0",
"if",
"dataArray",
"[",
"o1",
"]",
"is",
"equal",
"to",
"dataArray",
"[",
"o2",
"]",
"return",
"-",
"1",
"if",
"dataArray",
"[",
"o1",
"]",
"is",
"less",
"than",
"dataArray",
"[",
"o2",
"]"
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/ngmf/util/cosu/luca/Sorter.java#L32-L43 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/locale/LocaleUtils.java | LocaleUtils.getAvailableLocaleSuffixesForBundle | public static List<String> getAvailableLocaleSuffixesForBundle(String messageBundlePath, String fileSuffix) {
"""
Returns the list of available locale suffixes for a message resource
bundle
@param messageBundlePath
the resource bundle path
@param fileSuffix
the file suffix
@return the list of available locale suffixes for a message resource
bundle
"""
return getAvailableLocaleSuffixesForBundle(messageBundlePath, fileSuffix, null);
} | java | public static List<String> getAvailableLocaleSuffixesForBundle(String messageBundlePath, String fileSuffix) {
return getAvailableLocaleSuffixesForBundle(messageBundlePath, fileSuffix, null);
} | [
"public",
"static",
"List",
"<",
"String",
">",
"getAvailableLocaleSuffixesForBundle",
"(",
"String",
"messageBundlePath",
",",
"String",
"fileSuffix",
")",
"{",
"return",
"getAvailableLocaleSuffixesForBundle",
"(",
"messageBundlePath",
",",
"fileSuffix",
",",
"null",
")",
";",
"}"
] | Returns the list of available locale suffixes for a message resource
bundle
@param messageBundlePath
the resource bundle path
@param fileSuffix
the file suffix
@return the list of available locale suffixes for a message resource
bundle | [
"Returns",
"the",
"list",
"of",
"available",
"locale",
"suffixes",
"for",
"a",
"message",
"resource",
"bundle"
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/locale/LocaleUtils.java#L129-L131 |
jhalterman/failsafe | src/main/java/net/jodah/failsafe/FailsafeExecutor.java | FailsafeExecutor.getAsync | public <T extends R> CompletableFuture<T> getAsync(CheckedSupplier<T> supplier) {
"""
Executes the {@code supplier} asynchronously until a successful result is returned or the configured policies are
exceeded.
<p>
If a configured circuit breaker is open, the resulting future is completed with {@link
CircuitBreakerOpenException}.
@throws NullPointerException if the {@code supplier} is null
@throws RejectedExecutionException if the {@code supplier} cannot be scheduled for execution
"""
return callAsync(execution -> Functions.promiseOf(supplier, execution), false);
} | java | public <T extends R> CompletableFuture<T> getAsync(CheckedSupplier<T> supplier) {
return callAsync(execution -> Functions.promiseOf(supplier, execution), false);
} | [
"public",
"<",
"T",
"extends",
"R",
">",
"CompletableFuture",
"<",
"T",
">",
"getAsync",
"(",
"CheckedSupplier",
"<",
"T",
">",
"supplier",
")",
"{",
"return",
"callAsync",
"(",
"execution",
"->",
"Functions",
".",
"promiseOf",
"(",
"supplier",
",",
"execution",
")",
",",
"false",
")",
";",
"}"
] | Executes the {@code supplier} asynchronously until a successful result is returned or the configured policies are
exceeded.
<p>
If a configured circuit breaker is open, the resulting future is completed with {@link
CircuitBreakerOpenException}.
@throws NullPointerException if the {@code supplier} is null
@throws RejectedExecutionException if the {@code supplier} cannot be scheduled for execution | [
"Executes",
"the",
"{",
"@code",
"supplier",
"}",
"asynchronously",
"until",
"a",
"successful",
"result",
"is",
"returned",
"or",
"the",
"configured",
"policies",
"are",
"exceeded",
".",
"<p",
">",
"If",
"a",
"configured",
"circuit",
"breaker",
"is",
"open",
"the",
"resulting",
"future",
"is",
"completed",
"with",
"{",
"@link",
"CircuitBreakerOpenException",
"}",
"."
] | train | https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/FailsafeExecutor.java#L94-L96 |
kopihao/peasy-recyclerview | peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java | PeasyRecyclerView.enhanceFAB | private void enhanceFAB(final FloatingActionButton fab, MotionEvent e) {
"""
Enhanced FAB UX Logic
Handle RecyclerView scrolled
If all item visible within view port, FAB will show
@param fab FloatingActionButton
@param e MotionEvent
"""
if (hasAllItemsShown()) {
if (fab.getVisibility() != View.VISIBLE) {
fab.show();
}
}
} | java | private void enhanceFAB(final FloatingActionButton fab, MotionEvent e) {
if (hasAllItemsShown()) {
if (fab.getVisibility() != View.VISIBLE) {
fab.show();
}
}
} | [
"private",
"void",
"enhanceFAB",
"(",
"final",
"FloatingActionButton",
"fab",
",",
"MotionEvent",
"e",
")",
"{",
"if",
"(",
"hasAllItemsShown",
"(",
")",
")",
"{",
"if",
"(",
"fab",
".",
"getVisibility",
"(",
")",
"!=",
"View",
".",
"VISIBLE",
")",
"{",
"fab",
".",
"show",
"(",
")",
";",
"}",
"}",
"}"
] | Enhanced FAB UX Logic
Handle RecyclerView scrolled
If all item visible within view port, FAB will show
@param fab FloatingActionButton
@param e MotionEvent | [
"Enhanced",
"FAB",
"UX",
"Logic",
"Handle",
"RecyclerView",
"scrolled",
"If",
"all",
"item",
"visible",
"within",
"view",
"port",
"FAB",
"will",
"show"
] | train | https://github.com/kopihao/peasy-recyclerview/blob/a26071849e5d5b5b1febe685f205558b49908f87/peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java#L243-L249 |
Azure/azure-sdk-for-java | sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/DatabaseRecommendedActionsInner.java | DatabaseRecommendedActionsInner.getAsync | public Observable<RecommendedActionInner> getAsync(String resourceGroupName, String serverName, String databaseName, String advisorName, String recommendedActionName) {
"""
Gets a database recommended action.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database.
@param advisorName The name of the Database Advisor.
@param recommendedActionName The name of Database Recommended Action.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RecommendedActionInner object
"""
return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName, advisorName, recommendedActionName).map(new Func1<ServiceResponse<RecommendedActionInner>, RecommendedActionInner>() {
@Override
public RecommendedActionInner call(ServiceResponse<RecommendedActionInner> response) {
return response.body();
}
});
} | java | public Observable<RecommendedActionInner> getAsync(String resourceGroupName, String serverName, String databaseName, String advisorName, String recommendedActionName) {
return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName, advisorName, recommendedActionName).map(new Func1<ServiceResponse<RecommendedActionInner>, RecommendedActionInner>() {
@Override
public RecommendedActionInner call(ServiceResponse<RecommendedActionInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"RecommendedActionInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
",",
"String",
"advisorName",
",",
"String",
"recommendedActionName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
"databaseName",
",",
"advisorName",
",",
"recommendedActionName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"RecommendedActionInner",
">",
",",
"RecommendedActionInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"RecommendedActionInner",
"call",
"(",
"ServiceResponse",
"<",
"RecommendedActionInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Gets a database recommended action.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database.
@param advisorName The name of the Database Advisor.
@param recommendedActionName The name of Database Recommended Action.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RecommendedActionInner object | [
"Gets",
"a",
"database",
"recommended",
"action",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/DatabaseRecommendedActionsInner.java#L217-L224 |
xiancloud/xian | xian-zookeeper/xian-curator/xian-curator-client/src/main/java/org/apache/curator/utils/ZKPaths.java | ZKPaths.fixForNamespace | public static String fixForNamespace(String namespace, String path, boolean isSequential) {
"""
Apply the namespace to the given path
@param namespace namespace (can be null)
@param path path
@param isSequential if the path is being created with a sequential flag
@return adjusted path
"""
// Child path must be valid in and of itself.
PathUtils.validatePath(path, isSequential);
if ( namespace != null )
{
return makePath(namespace, path);
}
return path;
} | java | public static String fixForNamespace(String namespace, String path, boolean isSequential)
{
// Child path must be valid in and of itself.
PathUtils.validatePath(path, isSequential);
if ( namespace != null )
{
return makePath(namespace, path);
}
return path;
} | [
"public",
"static",
"String",
"fixForNamespace",
"(",
"String",
"namespace",
",",
"String",
"path",
",",
"boolean",
"isSequential",
")",
"{",
"// Child path must be valid in and of itself.",
"PathUtils",
".",
"validatePath",
"(",
"path",
",",
"isSequential",
")",
";",
"if",
"(",
"namespace",
"!=",
"null",
")",
"{",
"return",
"makePath",
"(",
"namespace",
",",
"path",
")",
";",
"}",
"return",
"path",
";",
"}"
] | Apply the namespace to the given path
@param namespace namespace (can be null)
@param path path
@param isSequential if the path is being created with a sequential flag
@return adjusted path | [
"Apply",
"the",
"namespace",
"to",
"the",
"given",
"path"
] | train | https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-zookeeper/xian-curator/xian-curator-client/src/main/java/org/apache/curator/utils/ZKPaths.java#L102-L112 |
apache/incubator-atlas | repository/src/main/java/org/apache/atlas/repository/typestore/GraphBackedTypeStore.java | GraphBackedTypeStore.findVertex | AtlasVertex findVertex(DataTypes.TypeCategory category, String typeName) {
"""
Find vertex for the given type category and name, else create new vertex
@param category
@param typeName
@return vertex
"""
LOG.debug("Finding AtlasVertex for {}.{}", category, typeName);
Iterator results = graph.query().has(Constants.TYPENAME_PROPERTY_KEY, typeName).vertices().iterator();
AtlasVertex vertex = null;
if (results != null && results.hasNext()) {
//There should be just one AtlasVertex with the given typeName
vertex = (AtlasVertex) results.next();
}
return vertex;
} | java | AtlasVertex findVertex(DataTypes.TypeCategory category, String typeName) {
LOG.debug("Finding AtlasVertex for {}.{}", category, typeName);
Iterator results = graph.query().has(Constants.TYPENAME_PROPERTY_KEY, typeName).vertices().iterator();
AtlasVertex vertex = null;
if (results != null && results.hasNext()) {
//There should be just one AtlasVertex with the given typeName
vertex = (AtlasVertex) results.next();
}
return vertex;
} | [
"AtlasVertex",
"findVertex",
"(",
"DataTypes",
".",
"TypeCategory",
"category",
",",
"String",
"typeName",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Finding AtlasVertex for {}.{}\"",
",",
"category",
",",
"typeName",
")",
";",
"Iterator",
"results",
"=",
"graph",
".",
"query",
"(",
")",
".",
"has",
"(",
"Constants",
".",
"TYPENAME_PROPERTY_KEY",
",",
"typeName",
")",
".",
"vertices",
"(",
")",
".",
"iterator",
"(",
")",
";",
"AtlasVertex",
"vertex",
"=",
"null",
";",
"if",
"(",
"results",
"!=",
"null",
"&&",
"results",
".",
"hasNext",
"(",
")",
")",
"{",
"//There should be just one AtlasVertex with the given typeName",
"vertex",
"=",
"(",
"AtlasVertex",
")",
"results",
".",
"next",
"(",
")",
";",
"}",
"return",
"vertex",
";",
"}"
] | Find vertex for the given type category and name, else create new vertex
@param category
@param typeName
@return vertex | [
"Find",
"vertex",
"for",
"the",
"given",
"type",
"category",
"and",
"name",
"else",
"create",
"new",
"vertex"
] | train | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/repository/src/main/java/org/apache/atlas/repository/typestore/GraphBackedTypeStore.java#L333-L343 |
bekkopen/NoCommons | src/main/java/no/bekk/bekkopen/common/Checksums.java | Checksums.calculateMod11CheckSum | public static int calculateMod11CheckSum(int[] weights, StringNumber number) {
"""
Calculate the check sum for the given weights and number.
@param weights The weights
@param number The number
@return The checksum
"""
int c = calculateChecksum(weights, number, false) % 11;
if (c == 1) {
throw new IllegalArgumentException(ERROR_INVALID_CHECKSUM + number);
}
return c == 0 ? 0 : 11 - c;
} | java | public static int calculateMod11CheckSum(int[] weights, StringNumber number) {
int c = calculateChecksum(weights, number, false) % 11;
if (c == 1) {
throw new IllegalArgumentException(ERROR_INVALID_CHECKSUM + number);
}
return c == 0 ? 0 : 11 - c;
} | [
"public",
"static",
"int",
"calculateMod11CheckSum",
"(",
"int",
"[",
"]",
"weights",
",",
"StringNumber",
"number",
")",
"{",
"int",
"c",
"=",
"calculateChecksum",
"(",
"weights",
",",
"number",
",",
"false",
")",
"%",
"11",
";",
"if",
"(",
"c",
"==",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"ERROR_INVALID_CHECKSUM",
"+",
"number",
")",
";",
"}",
"return",
"c",
"==",
"0",
"?",
"0",
":",
"11",
"-",
"c",
";",
"}"
] | Calculate the check sum for the given weights and number.
@param weights The weights
@param number The number
@return The checksum | [
"Calculate",
"the",
"check",
"sum",
"for",
"the",
"given",
"weights",
"and",
"number",
"."
] | train | https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/common/Checksums.java#L14-L20 |
joniles/mpxj | src/main/java/net/sf/mpxj/explorer/ProjectTreeController.java | ProjectTreeController.addViews | private void addViews(MpxjTreeNode parentNode, ProjectFile file) {
"""
Add views to the tree.
@param parentNode parent tree node
@param file views container
"""
for (View view : file.getViews())
{
final View v = view;
MpxjTreeNode childNode = new MpxjTreeNode(view)
{
@Override public String toString()
{
return v.getName();
}
};
parentNode.add(childNode);
}
} | java | private void addViews(MpxjTreeNode parentNode, ProjectFile file)
{
for (View view : file.getViews())
{
final View v = view;
MpxjTreeNode childNode = new MpxjTreeNode(view)
{
@Override public String toString()
{
return v.getName();
}
};
parentNode.add(childNode);
}
} | [
"private",
"void",
"addViews",
"(",
"MpxjTreeNode",
"parentNode",
",",
"ProjectFile",
"file",
")",
"{",
"for",
"(",
"View",
"view",
":",
"file",
".",
"getViews",
"(",
")",
")",
"{",
"final",
"View",
"v",
"=",
"view",
";",
"MpxjTreeNode",
"childNode",
"=",
"new",
"MpxjTreeNode",
"(",
"view",
")",
"{",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"v",
".",
"getName",
"(",
")",
";",
"}",
"}",
";",
"parentNode",
".",
"add",
"(",
"childNode",
")",
";",
"}",
"}"
] | Add views to the tree.
@param parentNode parent tree node
@param file views container | [
"Add",
"views",
"to",
"the",
"tree",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/explorer/ProjectTreeController.java#L398-L412 |
Waikato/moa | moa/src/main/java/moa/classifiers/lazy/neighboursearch/NormalizableDistance.java | NormalizableDistance.updateRangesFirst | public void updateRangesFirst(Instance instance, int numAtt, double[][] ranges) {
"""
Used to initialize the ranges. For this the values of the first
instance is used to save time.
Sets low and high to the values of the first instance and
width to zero.
@param instance the new instance
@param numAtt number of attributes in the model
@param ranges low, high and width values for all attributes
"""
for (int j = 0; j < numAtt; j++) {
if (!instance.isMissing(j)) {
ranges[j][R_MIN] = instance.value(j);
ranges[j][R_MAX] = instance.value(j);
ranges[j][R_WIDTH] = 0.0;
}
else { // if value was missing
ranges[j][R_MIN] = Double.POSITIVE_INFINITY;
ranges[j][R_MAX] = -Double.POSITIVE_INFINITY;
ranges[j][R_WIDTH] = Double.POSITIVE_INFINITY;
}
}
} | java | public void updateRangesFirst(Instance instance, int numAtt, double[][] ranges) {
for (int j = 0; j < numAtt; j++) {
if (!instance.isMissing(j)) {
ranges[j][R_MIN] = instance.value(j);
ranges[j][R_MAX] = instance.value(j);
ranges[j][R_WIDTH] = 0.0;
}
else { // if value was missing
ranges[j][R_MIN] = Double.POSITIVE_INFINITY;
ranges[j][R_MAX] = -Double.POSITIVE_INFINITY;
ranges[j][R_WIDTH] = Double.POSITIVE_INFINITY;
}
}
} | [
"public",
"void",
"updateRangesFirst",
"(",
"Instance",
"instance",
",",
"int",
"numAtt",
",",
"double",
"[",
"]",
"[",
"]",
"ranges",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"numAtt",
";",
"j",
"++",
")",
"{",
"if",
"(",
"!",
"instance",
".",
"isMissing",
"(",
"j",
")",
")",
"{",
"ranges",
"[",
"j",
"]",
"[",
"R_MIN",
"]",
"=",
"instance",
".",
"value",
"(",
"j",
")",
";",
"ranges",
"[",
"j",
"]",
"[",
"R_MAX",
"]",
"=",
"instance",
".",
"value",
"(",
"j",
")",
";",
"ranges",
"[",
"j",
"]",
"[",
"R_WIDTH",
"]",
"=",
"0.0",
";",
"}",
"else",
"{",
"// if value was missing",
"ranges",
"[",
"j",
"]",
"[",
"R_MIN",
"]",
"=",
"Double",
".",
"POSITIVE_INFINITY",
";",
"ranges",
"[",
"j",
"]",
"[",
"R_MAX",
"]",
"=",
"-",
"Double",
".",
"POSITIVE_INFINITY",
";",
"ranges",
"[",
"j",
"]",
"[",
"R_WIDTH",
"]",
"=",
"Double",
".",
"POSITIVE_INFINITY",
";",
"}",
"}",
"}"
] | Used to initialize the ranges. For this the values of the first
instance is used to save time.
Sets low and high to the values of the first instance and
width to zero.
@param instance the new instance
@param numAtt number of attributes in the model
@param ranges low, high and width values for all attributes | [
"Used",
"to",
"initialize",
"the",
"ranges",
".",
"For",
"this",
"the",
"values",
"of",
"the",
"first",
"instance",
"is",
"used",
"to",
"save",
"time",
".",
"Sets",
"low",
"and",
"high",
"to",
"the",
"values",
"of",
"the",
"first",
"instance",
"and",
"width",
"to",
"zero",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/lazy/neighboursearch/NormalizableDistance.java#L494-L507 |
jcuda/jcuda | JCudaJava/src/main/java/jcuda/cuComplex.java | cuComplex.cuCmul | public static cuComplex cuCmul (cuComplex x, cuComplex y) {
"""
Returns the product of the given complex numbers.<br />
<br />
Original comment:<br />
<br />
This implementation could suffer from intermediate overflow even though
the final result would be in range. However, various implementations do
not guard against this (presumably to avoid losing performance), so we
don't do it either to stay competitive.
@param x The first factor
@param y The second factor
@return The product of the given factors
"""
cuComplex prod;
prod = cuCmplx ((cuCreal(x) * cuCreal(y)) - (cuCimag(x) * cuCimag(y)),
(cuCreal(x) * cuCimag(y)) + (cuCimag(x) * cuCreal(y)));
return prod;
} | java | public static cuComplex cuCmul (cuComplex x, cuComplex y)
{
cuComplex prod;
prod = cuCmplx ((cuCreal(x) * cuCreal(y)) - (cuCimag(x) * cuCimag(y)),
(cuCreal(x) * cuCimag(y)) + (cuCimag(x) * cuCreal(y)));
return prod;
} | [
"public",
"static",
"cuComplex",
"cuCmul",
"(",
"cuComplex",
"x",
",",
"cuComplex",
"y",
")",
"{",
"cuComplex",
"prod",
";",
"prod",
"=",
"cuCmplx",
"(",
"(",
"cuCreal",
"(",
"x",
")",
"*",
"cuCreal",
"(",
"y",
")",
")",
"-",
"(",
"cuCimag",
"(",
"x",
")",
"*",
"cuCimag",
"(",
"y",
")",
")",
",",
"(",
"cuCreal",
"(",
"x",
")",
"*",
"cuCimag",
"(",
"y",
")",
")",
"+",
"(",
"cuCimag",
"(",
"x",
")",
"*",
"cuCreal",
"(",
"y",
")",
")",
")",
";",
"return",
"prod",
";",
"}"
] | Returns the product of the given complex numbers.<br />
<br />
Original comment:<br />
<br />
This implementation could suffer from intermediate overflow even though
the final result would be in range. However, various implementations do
not guard against this (presumably to avoid losing performance), so we
don't do it either to stay competitive.
@param x The first factor
@param y The second factor
@return The product of the given factors | [
"Returns",
"the",
"product",
"of",
"the",
"given",
"complex",
"numbers",
".",
"<br",
"/",
">",
"<br",
"/",
">",
"Original",
"comment",
":",
"<br",
"/",
">",
"<br",
"/",
">",
"This",
"implementation",
"could",
"suffer",
"from",
"intermediate",
"overflow",
"even",
"though",
"the",
"final",
"result",
"would",
"be",
"in",
"range",
".",
"However",
"various",
"implementations",
"do",
"not",
"guard",
"against",
"this",
"(",
"presumably",
"to",
"avoid",
"losing",
"performance",
")",
"so",
"we",
"don",
"t",
"do",
"it",
"either",
"to",
"stay",
"competitive",
"."
] | train | https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/cuComplex.java#L122-L128 |
elki-project/elki | elki-data-generator/src/main/java/de/lmu/ifi/dbs/elki/data/synthetic/bymodel/GeneratorSingleCluster.java | GeneratorSingleCluster.addRotation | public void addRotation(int axis1, int axis2, double angle) {
"""
Apply a rotation to the generator
@param axis1 First axis (0 <= axis1 < dim)
@param axis2 Second axis (0 <= axis2 < dim)
@param angle Angle in Radians
"""
if(trans == null) {
trans = new AffineTransformation(dim);
}
trans.addRotation(axis1, axis2, angle);
} | java | public void addRotation(int axis1, int axis2, double angle) {
if(trans == null) {
trans = new AffineTransformation(dim);
}
trans.addRotation(axis1, axis2, angle);
} | [
"public",
"void",
"addRotation",
"(",
"int",
"axis1",
",",
"int",
"axis2",
",",
"double",
"angle",
")",
"{",
"if",
"(",
"trans",
"==",
"null",
")",
"{",
"trans",
"=",
"new",
"AffineTransformation",
"(",
"dim",
")",
";",
"}",
"trans",
".",
"addRotation",
"(",
"axis1",
",",
"axis2",
",",
"angle",
")",
";",
"}"
] | Apply a rotation to the generator
@param axis1 First axis (0 <= axis1 < dim)
@param axis2 Second axis (0 <= axis2 < dim)
@param angle Angle in Radians | [
"Apply",
"a",
"rotation",
"to",
"the",
"generator"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-data-generator/src/main/java/de/lmu/ifi/dbs/elki/data/synthetic/bymodel/GeneratorSingleCluster.java#L134-L139 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/KeyStore.java | KeyStore.getEntry | public final Entry getEntry(String alias, ProtectionParameter protParam)
throws NoSuchAlgorithmException, UnrecoverableEntryException,
KeyStoreException {
"""
Gets a keystore <code>Entry</code> for the specified alias
with the specified protection parameter.
@param alias get the keystore <code>Entry</code> for this alias
@param protParam the <code>ProtectionParameter</code>
used to protect the <code>Entry</code>,
which may be <code>null</code>
@return the keystore <code>Entry</code> for the specified alias,
or <code>null</code> if there is no such entry
@exception NullPointerException if
<code>alias</code> is <code>null</code>
@exception NoSuchAlgorithmException if the algorithm for recovering the
entry cannot be found
@exception UnrecoverableEntryException if the specified
<code>protParam</code> were insufficient or invalid
@exception UnrecoverableKeyException if the entry is a
<code>PrivateKeyEntry</code> or <code>SecretKeyEntry</code>
and the specified <code>protParam</code> does not contain
the information needed to recover the key (e.g. wrong password)
@exception KeyStoreException if the keystore has not been initialized
(loaded).
@see #setEntry(String, KeyStore.Entry, KeyStore.ProtectionParameter)
@since 1.5
"""
if (alias == null) {
throw new NullPointerException("invalid null input");
}
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineGetEntry(alias, protParam);
} | java | public final Entry getEntry(String alias, ProtectionParameter protParam)
throws NoSuchAlgorithmException, UnrecoverableEntryException,
KeyStoreException {
if (alias == null) {
throw new NullPointerException("invalid null input");
}
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineGetEntry(alias, protParam);
} | [
"public",
"final",
"Entry",
"getEntry",
"(",
"String",
"alias",
",",
"ProtectionParameter",
"protParam",
")",
"throws",
"NoSuchAlgorithmException",
",",
"UnrecoverableEntryException",
",",
"KeyStoreException",
"{",
"if",
"(",
"alias",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"invalid null input\"",
")",
";",
"}",
"if",
"(",
"!",
"initialized",
")",
"{",
"throw",
"new",
"KeyStoreException",
"(",
"\"Uninitialized keystore\"",
")",
";",
"}",
"return",
"keyStoreSpi",
".",
"engineGetEntry",
"(",
"alias",
",",
"protParam",
")",
";",
"}"
] | Gets a keystore <code>Entry</code> for the specified alias
with the specified protection parameter.
@param alias get the keystore <code>Entry</code> for this alias
@param protParam the <code>ProtectionParameter</code>
used to protect the <code>Entry</code>,
which may be <code>null</code>
@return the keystore <code>Entry</code> for the specified alias,
or <code>null</code> if there is no such entry
@exception NullPointerException if
<code>alias</code> is <code>null</code>
@exception NoSuchAlgorithmException if the algorithm for recovering the
entry cannot be found
@exception UnrecoverableEntryException if the specified
<code>protParam</code> were insufficient or invalid
@exception UnrecoverableKeyException if the entry is a
<code>PrivateKeyEntry</code> or <code>SecretKeyEntry</code>
and the specified <code>protParam</code> does not contain
the information needed to recover the key (e.g. wrong password)
@exception KeyStoreException if the keystore has not been initialized
(loaded).
@see #setEntry(String, KeyStore.Entry, KeyStore.ProtectionParameter)
@since 1.5 | [
"Gets",
"a",
"keystore",
"<code",
">",
"Entry<",
"/",
"code",
">",
"for",
"the",
"specified",
"alias",
"with",
"the",
"specified",
"protection",
"parameter",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/KeyStore.java#L1322-L1333 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/GVRPicker.java | GVRPicker.makeHit | static GVRPickedObject makeHit(long colliderPointer, float distance, float hitx, float hity, float hitz) {
"""
Internal utility to help JNI add hit objects to the pick list.
"""
GVRCollider collider = GVRCollider.lookup(colliderPointer);
if (collider == null)
{
Log.d(TAG, "makeHit: cannot find collider for %x", colliderPointer);
return null;
}
return new GVRPicker.GVRPickedObject(collider, new float[] { hitx, hity, hitz }, distance);
} | java | static GVRPickedObject makeHit(long colliderPointer, float distance, float hitx, float hity, float hitz)
{
GVRCollider collider = GVRCollider.lookup(colliderPointer);
if (collider == null)
{
Log.d(TAG, "makeHit: cannot find collider for %x", colliderPointer);
return null;
}
return new GVRPicker.GVRPickedObject(collider, new float[] { hitx, hity, hitz }, distance);
} | [
"static",
"GVRPickedObject",
"makeHit",
"(",
"long",
"colliderPointer",
",",
"float",
"distance",
",",
"float",
"hitx",
",",
"float",
"hity",
",",
"float",
"hitz",
")",
"{",
"GVRCollider",
"collider",
"=",
"GVRCollider",
".",
"lookup",
"(",
"colliderPointer",
")",
";",
"if",
"(",
"collider",
"==",
"null",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"makeHit: cannot find collider for %x\"",
",",
"colliderPointer",
")",
";",
"return",
"null",
";",
"}",
"return",
"new",
"GVRPicker",
".",
"GVRPickedObject",
"(",
"collider",
",",
"new",
"float",
"[",
"]",
"{",
"hitx",
",",
"hity",
",",
"hitz",
"}",
",",
"distance",
")",
";",
"}"
] | Internal utility to help JNI add hit objects to the pick list. | [
"Internal",
"utility",
"to",
"help",
"JNI",
"add",
"hit",
"objects",
"to",
"the",
"pick",
"list",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRPicker.java#L1217-L1226 |
jhunters/jprotobuf | v3/src/main/java/com/baidu/bjf/remoting/protobuf/MapEntryLite.java | MapEntryLite.parseInto | public void parseInto(MapFieldLite<K, V> map, CodedInputStream input, ExtensionRegistryLite extensionRegistry)
throws IOException {
"""
Parses an entry off of the input into the map. This helper avoids allocaton of a {@link MapEntryLite} by parsing
directly into the provided {@link MapFieldLite}.
@param map the map
@param input the input
@param extensionRegistry the extension registry
@throws IOException Signals that an I/O exception has occurred.
"""
int length = input.readRawVarint32();
final int oldLimit = input.pushLimit(length);
K key = metadata.defaultKey;
V value = metadata.defaultValue;
while (true) {
int tag = input.readTag();
if (tag == 0) {
break;
}
if (tag == CodedConstant.makeTag(KEY_FIELD_NUMBER, metadata.keyType.getWireType())) {
key = parseField(input, extensionRegistry, metadata.keyType, key);
} else if (tag == CodedConstant.makeTag(VALUE_FIELD_NUMBER, metadata.valueType.getWireType())) {
value = parseField(input, extensionRegistry, metadata.valueType, value);
} else {
if (!input.skipField(tag)) {
break;
}
}
}
input.checkLastTagWas(0);
input.popLimit(oldLimit);
map.put(key, value);
} | java | public void parseInto(MapFieldLite<K, V> map, CodedInputStream input, ExtensionRegistryLite extensionRegistry)
throws IOException {
int length = input.readRawVarint32();
final int oldLimit = input.pushLimit(length);
K key = metadata.defaultKey;
V value = metadata.defaultValue;
while (true) {
int tag = input.readTag();
if (tag == 0) {
break;
}
if (tag == CodedConstant.makeTag(KEY_FIELD_NUMBER, metadata.keyType.getWireType())) {
key = parseField(input, extensionRegistry, metadata.keyType, key);
} else if (tag == CodedConstant.makeTag(VALUE_FIELD_NUMBER, metadata.valueType.getWireType())) {
value = parseField(input, extensionRegistry, metadata.valueType, value);
} else {
if (!input.skipField(tag)) {
break;
}
}
}
input.checkLastTagWas(0);
input.popLimit(oldLimit);
map.put(key, value);
} | [
"public",
"void",
"parseInto",
"(",
"MapFieldLite",
"<",
"K",
",",
"V",
">",
"map",
",",
"CodedInputStream",
"input",
",",
"ExtensionRegistryLite",
"extensionRegistry",
")",
"throws",
"IOException",
"{",
"int",
"length",
"=",
"input",
".",
"readRawVarint32",
"(",
")",
";",
"final",
"int",
"oldLimit",
"=",
"input",
".",
"pushLimit",
"(",
"length",
")",
";",
"K",
"key",
"=",
"metadata",
".",
"defaultKey",
";",
"V",
"value",
"=",
"metadata",
".",
"defaultValue",
";",
"while",
"(",
"true",
")",
"{",
"int",
"tag",
"=",
"input",
".",
"readTag",
"(",
")",
";",
"if",
"(",
"tag",
"==",
"0",
")",
"{",
"break",
";",
"}",
"if",
"(",
"tag",
"==",
"CodedConstant",
".",
"makeTag",
"(",
"KEY_FIELD_NUMBER",
",",
"metadata",
".",
"keyType",
".",
"getWireType",
"(",
")",
")",
")",
"{",
"key",
"=",
"parseField",
"(",
"input",
",",
"extensionRegistry",
",",
"metadata",
".",
"keyType",
",",
"key",
")",
";",
"}",
"else",
"if",
"(",
"tag",
"==",
"CodedConstant",
".",
"makeTag",
"(",
"VALUE_FIELD_NUMBER",
",",
"metadata",
".",
"valueType",
".",
"getWireType",
"(",
")",
")",
")",
"{",
"value",
"=",
"parseField",
"(",
"input",
",",
"extensionRegistry",
",",
"metadata",
".",
"valueType",
",",
"value",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"input",
".",
"skipField",
"(",
"tag",
")",
")",
"{",
"break",
";",
"}",
"}",
"}",
"input",
".",
"checkLastTagWas",
"(",
"0",
")",
";",
"input",
".",
"popLimit",
"(",
"oldLimit",
")",
";",
"map",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}"
] | Parses an entry off of the input into the map. This helper avoids allocaton of a {@link MapEntryLite} by parsing
directly into the provided {@link MapFieldLite}.
@param map the map
@param input the input
@param extensionRegistry the extension registry
@throws IOException Signals that an I/O exception has occurred. | [
"Parses",
"an",
"entry",
"off",
"of",
"the",
"input",
"into",
"the",
"map",
".",
"This",
"helper",
"avoids",
"allocaton",
"of",
"a",
"{",
"@link",
"MapEntryLite",
"}",
"by",
"parsing",
"directly",
"into",
"the",
"provided",
"{",
"@link",
"MapFieldLite",
"}",
"."
] | train | https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/v3/src/main/java/com/baidu/bjf/remoting/protobuf/MapEntryLite.java#L308-L334 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/listeners/CheckpointListener.java | CheckpointListener.loadCheckpointMLN | public static MultiLayerNetwork loadCheckpointMLN(File rootDir, int checkpointNum) {
"""
Load a MultiLayerNetwork for the given checkpoint number
@param rootDir The directory that the checkpoint resides in
@param checkpointNum Checkpoint model to load
@return The loaded model
"""
File f = getFileForCheckpoint(rootDir, checkpointNum);
try {
return ModelSerializer.restoreMultiLayerNetwork(f, true);
} catch (IOException e){
throw new RuntimeException(e);
}
} | java | public static MultiLayerNetwork loadCheckpointMLN(File rootDir, int checkpointNum){
File f = getFileForCheckpoint(rootDir, checkpointNum);
try {
return ModelSerializer.restoreMultiLayerNetwork(f, true);
} catch (IOException e){
throw new RuntimeException(e);
}
} | [
"public",
"static",
"MultiLayerNetwork",
"loadCheckpointMLN",
"(",
"File",
"rootDir",
",",
"int",
"checkpointNum",
")",
"{",
"File",
"f",
"=",
"getFileForCheckpoint",
"(",
"rootDir",
",",
"checkpointNum",
")",
";",
"try",
"{",
"return",
"ModelSerializer",
".",
"restoreMultiLayerNetwork",
"(",
"f",
",",
"true",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] | Load a MultiLayerNetwork for the given checkpoint number
@param rootDir The directory that the checkpoint resides in
@param checkpointNum Checkpoint model to load
@return The loaded model | [
"Load",
"a",
"MultiLayerNetwork",
"for",
"the",
"given",
"checkpoint",
"number"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/listeners/CheckpointListener.java#L465-L472 |
hypercube1024/firefly | firefly-common/src/main/java/com/firefly/utils/collection/HashedArrayTree.java | HashedArrayTree.get | @Override
public T get(int index) {
"""
Returns the value of the element at the specified position.
@param index The index at which to query.
@return The value of the element at that position.
@throws IndexOutOfBoundsException If the index is invalid.
"""
/* Check that this is a valid index. */
if (index < 0 || index >= size())
throw new IndexOutOfBoundsException("Index " + index + ", size " + size());
/* Look up the element. */
return mArrays[computeOffset(index)][computeIndex(index)];
} | java | @Override
public T get(int index) {
/* Check that this is a valid index. */
if (index < 0 || index >= size())
throw new IndexOutOfBoundsException("Index " + index + ", size " + size());
/* Look up the element. */
return mArrays[computeOffset(index)][computeIndex(index)];
} | [
"@",
"Override",
"public",
"T",
"get",
"(",
"int",
"index",
")",
"{",
"/* Check that this is a valid index. */",
"if",
"(",
"index",
"<",
"0",
"||",
"index",
">=",
"size",
"(",
")",
")",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"\"Index \"",
"+",
"index",
"+",
"\", size \"",
"+",
"size",
"(",
")",
")",
";",
"/* Look up the element. */",
"return",
"mArrays",
"[",
"computeOffset",
"(",
"index",
")",
"]",
"[",
"computeIndex",
"(",
"index",
")",
"]",
";",
"}"
] | Returns the value of the element at the specified position.
@param index The index at which to query.
@return The value of the element at that position.
@throws IndexOutOfBoundsException If the index is invalid. | [
"Returns",
"the",
"value",
"of",
"the",
"element",
"at",
"the",
"specified",
"position",
"."
] | train | https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly-common/src/main/java/com/firefly/utils/collection/HashedArrayTree.java#L200-L208 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java | ImgUtil.createImage | public static void createImage(String str, Font font, Color backgroundColor, Color fontColor, ImageOutputStream out) throws IORuntimeException {
"""
根据文字创建PNG图片
@param str 文字
@param font 字体{@link Font}
@param backgroundColor 背景颜色
@param fontColor 字体颜色
@param out 图片输出地
@throws IORuntimeException IO异常
"""
// 获取font的样式应用在str上的整个矩形
Rectangle2D r = font.getStringBounds(str, new FontRenderContext(AffineTransform.getScaleInstance(1, 1), false, false));
int unitHeight = (int) Math.floor(r.getHeight());// 获取单个字符的高度
// 获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度
int width = (int) Math.round(r.getWidth()) + 1;
int height = unitHeight + 3;// 把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度
// 创建图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();
g.setColor(backgroundColor);
g.fillRect(0, 0, width, height);// 先用背景色填充整张图片,也就是背景
g.setColor(fontColor);
g.setFont(font);// 设置画笔字体
g.drawString(str, 0, font.getSize());// 画出字符串
g.dispose();
writePng(image, out);
} | java | public static void createImage(String str, Font font, Color backgroundColor, Color fontColor, ImageOutputStream out) throws IORuntimeException {
// 获取font的样式应用在str上的整个矩形
Rectangle2D r = font.getStringBounds(str, new FontRenderContext(AffineTransform.getScaleInstance(1, 1), false, false));
int unitHeight = (int) Math.floor(r.getHeight());// 获取单个字符的高度
// 获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度
int width = (int) Math.round(r.getWidth()) + 1;
int height = unitHeight + 3;// 把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度
// 创建图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();
g.setColor(backgroundColor);
g.fillRect(0, 0, width, height);// 先用背景色填充整张图片,也就是背景
g.setColor(fontColor);
g.setFont(font);// 设置画笔字体
g.drawString(str, 0, font.getSize());// 画出字符串
g.dispose();
writePng(image, out);
} | [
"public",
"static",
"void",
"createImage",
"(",
"String",
"str",
",",
"Font",
"font",
",",
"Color",
"backgroundColor",
",",
"Color",
"fontColor",
",",
"ImageOutputStream",
"out",
")",
"throws",
"IORuntimeException",
"{",
"// 获取font的样式应用在str上的整个矩形\r",
"Rectangle2D",
"r",
"=",
"font",
".",
"getStringBounds",
"(",
"str",
",",
"new",
"FontRenderContext",
"(",
"AffineTransform",
".",
"getScaleInstance",
"(",
"1",
",",
"1",
")",
",",
"false",
",",
"false",
")",
")",
";",
"int",
"unitHeight",
"=",
"(",
"int",
")",
"Math",
".",
"floor",
"(",
"r",
".",
"getHeight",
"(",
")",
")",
";",
"// 获取单个字符的高度\r",
"// 获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度\r",
"int",
"width",
"=",
"(",
"int",
")",
"Math",
".",
"round",
"(",
"r",
".",
"getWidth",
"(",
")",
")",
"+",
"1",
";",
"int",
"height",
"=",
"unitHeight",
"+",
"3",
";",
"// 把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度\r",
"// 创建图片\r",
"BufferedImage",
"image",
"=",
"new",
"BufferedImage",
"(",
"width",
",",
"height",
",",
"BufferedImage",
".",
"TYPE_INT_BGR",
")",
";",
"Graphics",
"g",
"=",
"image",
".",
"getGraphics",
"(",
")",
";",
"g",
".",
"setColor",
"(",
"backgroundColor",
")",
";",
"g",
".",
"fillRect",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
";",
"// 先用背景色填充整张图片,也就是背景\r",
"g",
".",
"setColor",
"(",
"fontColor",
")",
";",
"g",
".",
"setFont",
"(",
"font",
")",
";",
"// 设置画笔字体\r",
"g",
".",
"drawString",
"(",
"str",
",",
"0",
",",
"font",
".",
"getSize",
"(",
")",
")",
";",
"// 画出字符串\r",
"g",
".",
"dispose",
"(",
")",
";",
"writePng",
"(",
"image",
",",
"out",
")",
";",
"}"
] | 根据文字创建PNG图片
@param str 文字
@param font 字体{@link Font}
@param backgroundColor 背景颜色
@param fontColor 字体颜色
@param out 图片输出地
@throws IORuntimeException IO异常 | [
"根据文字创建PNG图片"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L1269-L1286 |
structurizr/java | structurizr-core/src/com/structurizr/model/Model.java | Model.addDeploymentNode | @Nonnull
public DeploymentNode addDeploymentNode(@Nullable String environment, @Nonnull String name, @Nullable String description, @Nullable String technology) {
"""
Adds a top-level deployment node to this model.
@param environment the name of the deployment environment
@param name the name of the deployment node
@param description the description of the deployment node
@param technology the technology associated with the deployment node
@return a DeploymentNode instance
@throws IllegalArgumentException if the name is not specified, or a top-level deployment node with the same name already exists in the model
"""
return addDeploymentNode(environment, name, description, technology, 1);
} | java | @Nonnull
public DeploymentNode addDeploymentNode(@Nullable String environment, @Nonnull String name, @Nullable String description, @Nullable String technology) {
return addDeploymentNode(environment, name, description, technology, 1);
} | [
"@",
"Nonnull",
"public",
"DeploymentNode",
"addDeploymentNode",
"(",
"@",
"Nullable",
"String",
"environment",
",",
"@",
"Nonnull",
"String",
"name",
",",
"@",
"Nullable",
"String",
"description",
",",
"@",
"Nullable",
"String",
"technology",
")",
"{",
"return",
"addDeploymentNode",
"(",
"environment",
",",
"name",
",",
"description",
",",
"technology",
",",
"1",
")",
";",
"}"
] | Adds a top-level deployment node to this model.
@param environment the name of the deployment environment
@param name the name of the deployment node
@param description the description of the deployment node
@param technology the technology associated with the deployment node
@return a DeploymentNode instance
@throws IllegalArgumentException if the name is not specified, or a top-level deployment node with the same name already exists in the model | [
"Adds",
"a",
"top",
"-",
"level",
"deployment",
"node",
"to",
"this",
"model",
"."
] | train | https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/model/Model.java#L573-L576 |
graphql-java/graphql-java | src/main/java/graphql/schema/GraphQLCodeRegistry.java | GraphQLCodeRegistry.getDataFetcher | public DataFetcher getDataFetcher(GraphQLFieldsContainer parentType, GraphQLFieldDefinition fieldDefinition) {
"""
Returns a data fetcher associated with a field within a container type
@param parentType the container type
@param fieldDefinition the field definition
@return the DataFetcher associated with this field. All fields have data fetchers
"""
return getDataFetcherImpl(parentType, fieldDefinition, dataFetcherMap, systemDataFetcherMap);
} | java | public DataFetcher getDataFetcher(GraphQLFieldsContainer parentType, GraphQLFieldDefinition fieldDefinition) {
return getDataFetcherImpl(parentType, fieldDefinition, dataFetcherMap, systemDataFetcherMap);
} | [
"public",
"DataFetcher",
"getDataFetcher",
"(",
"GraphQLFieldsContainer",
"parentType",
",",
"GraphQLFieldDefinition",
"fieldDefinition",
")",
"{",
"return",
"getDataFetcherImpl",
"(",
"parentType",
",",
"fieldDefinition",
",",
"dataFetcherMap",
",",
"systemDataFetcherMap",
")",
";",
"}"
] | Returns a data fetcher associated with a field within a container type
@param parentType the container type
@param fieldDefinition the field definition
@return the DataFetcher associated with this field. All fields have data fetchers | [
"Returns",
"a",
"data",
"fetcher",
"associated",
"with",
"a",
"field",
"within",
"a",
"container",
"type"
] | train | https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/schema/GraphQLCodeRegistry.java#L57-L59 |
apache/groovy | src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java | StaticTypeCheckingVisitor.storeInferredReturnType | protected ClassNode storeInferredReturnType(final ASTNode node, final ClassNode type) {
"""
Stores the inferred return type of a closure or a method. We are using a separate key to store
inferred return type because the inferred type of a closure is {@link Closure}, which is different
from the inferred type of the code of the closure.
@param node a {@link ClosureExpression} or a {@link MethodNode}
@param type the inferred return type of the code
@return the old value of the inferred type
"""
if (!(node instanceof ClosureExpression)) {
throw new IllegalArgumentException("Storing inferred return type is only allowed on closures but found " + node.getClass());
}
return (ClassNode) node.putNodeMetaData(StaticTypesMarker.INFERRED_RETURN_TYPE, type);
} | java | protected ClassNode storeInferredReturnType(final ASTNode node, final ClassNode type) {
if (!(node instanceof ClosureExpression)) {
throw new IllegalArgumentException("Storing inferred return type is only allowed on closures but found " + node.getClass());
}
return (ClassNode) node.putNodeMetaData(StaticTypesMarker.INFERRED_RETURN_TYPE, type);
} | [
"protected",
"ClassNode",
"storeInferredReturnType",
"(",
"final",
"ASTNode",
"node",
",",
"final",
"ClassNode",
"type",
")",
"{",
"if",
"(",
"!",
"(",
"node",
"instanceof",
"ClosureExpression",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Storing inferred return type is only allowed on closures but found \"",
"+",
"node",
".",
"getClass",
"(",
")",
")",
";",
"}",
"return",
"(",
"ClassNode",
")",
"node",
".",
"putNodeMetaData",
"(",
"StaticTypesMarker",
".",
"INFERRED_RETURN_TYPE",
",",
"type",
")",
";",
"}"
] | Stores the inferred return type of a closure or a method. We are using a separate key to store
inferred return type because the inferred type of a closure is {@link Closure}, which is different
from the inferred type of the code of the closure.
@param node a {@link ClosureExpression} or a {@link MethodNode}
@param type the inferred return type of the code
@return the old value of the inferred type | [
"Stores",
"the",
"inferred",
"return",
"type",
"of",
"a",
"closure",
"or",
"a",
"method",
".",
"We",
"are",
"using",
"a",
"separate",
"key",
"to",
"store",
"inferred",
"return",
"type",
"because",
"the",
"inferred",
"type",
"of",
"a",
"closure",
"is",
"{",
"@link",
"Closure",
"}",
"which",
"is",
"different",
"from",
"the",
"inferred",
"type",
"of",
"the",
"code",
"of",
"the",
"closure",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L5111-L5116 |
beangle/beangle3 | commons/core/src/main/java/org/beangle/commons/collection/MapConverter.java | MapConverter.getBoolean | public Boolean getBoolean(Map<String, Object> data, String name) {
"""
<p>
getBoolean.
</p>
@param data a {@link java.util.Map} object.
@param name a {@link java.lang.String} object.
@return a {@link java.lang.Boolean} object.
"""
return get(data, name, Boolean.class);
} | java | public Boolean getBoolean(Map<String, Object> data, String name) {
return get(data, name, Boolean.class);
} | [
"public",
"Boolean",
"getBoolean",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"data",
",",
"String",
"name",
")",
"{",
"return",
"get",
"(",
"data",
",",
"name",
",",
"Boolean",
".",
"class",
")",
";",
"}"
] | <p>
getBoolean.
</p>
@param data a {@link java.util.Map} object.
@param name a {@link java.lang.String} object.
@return a {@link java.lang.Boolean} object. | [
"<p",
">",
"getBoolean",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/collection/MapConverter.java#L191-L193 |
VueGWT/vue-gwt | processors/src/main/java/com/axellience/vuegwt/processors/component/factory/VueComponentFactoryGenerator.java | VueComponentFactoryGenerator.registerLocalDirectives | private void registerLocalDirectives(Component annotation, MethodSpec.Builder initBuilder) {
"""
Register directives passed to the annotation.
@param annotation The Component annotation on the Component we generate for
@param initBuilder The builder for the init method
"""
try {
Class<?>[] componentsClass = annotation.directives();
if (componentsClass.length > 0) {
addGetDirectivesStatement(initBuilder);
}
Stream
.of(componentsClass)
.forEach(clazz -> initBuilder.addStatement("directives.set($S, new $T())",
directiveToTagName(clazz.getName()),
directiveOptionsName(clazz)));
} catch (MirroredTypesException mte) {
List<DeclaredType> classTypeMirrors = (List<DeclaredType>) mte.getTypeMirrors();
if (!classTypeMirrors.isEmpty()) {
addGetDirectivesStatement(initBuilder);
}
classTypeMirrors.forEach(classTypeMirror -> {
TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();
initBuilder.addStatement("directives.set($S, new $T())",
directiveToTagName(classTypeElement.getSimpleName().toString()),
directiveOptionsName(classTypeElement));
});
}
} | java | private void registerLocalDirectives(Component annotation, MethodSpec.Builder initBuilder) {
try {
Class<?>[] componentsClass = annotation.directives();
if (componentsClass.length > 0) {
addGetDirectivesStatement(initBuilder);
}
Stream
.of(componentsClass)
.forEach(clazz -> initBuilder.addStatement("directives.set($S, new $T())",
directiveToTagName(clazz.getName()),
directiveOptionsName(clazz)));
} catch (MirroredTypesException mte) {
List<DeclaredType> classTypeMirrors = (List<DeclaredType>) mte.getTypeMirrors();
if (!classTypeMirrors.isEmpty()) {
addGetDirectivesStatement(initBuilder);
}
classTypeMirrors.forEach(classTypeMirror -> {
TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();
initBuilder.addStatement("directives.set($S, new $T())",
directiveToTagName(classTypeElement.getSimpleName().toString()),
directiveOptionsName(classTypeElement));
});
}
} | [
"private",
"void",
"registerLocalDirectives",
"(",
"Component",
"annotation",
",",
"MethodSpec",
".",
"Builder",
"initBuilder",
")",
"{",
"try",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"componentsClass",
"=",
"annotation",
".",
"directives",
"(",
")",
";",
"if",
"(",
"componentsClass",
".",
"length",
">",
"0",
")",
"{",
"addGetDirectivesStatement",
"(",
"initBuilder",
")",
";",
"}",
"Stream",
".",
"of",
"(",
"componentsClass",
")",
".",
"forEach",
"(",
"clazz",
"->",
"initBuilder",
".",
"addStatement",
"(",
"\"directives.set($S, new $T())\"",
",",
"directiveToTagName",
"(",
"clazz",
".",
"getName",
"(",
")",
")",
",",
"directiveOptionsName",
"(",
"clazz",
")",
")",
")",
";",
"}",
"catch",
"(",
"MirroredTypesException",
"mte",
")",
"{",
"List",
"<",
"DeclaredType",
">",
"classTypeMirrors",
"=",
"(",
"List",
"<",
"DeclaredType",
">",
")",
"mte",
".",
"getTypeMirrors",
"(",
")",
";",
"if",
"(",
"!",
"classTypeMirrors",
".",
"isEmpty",
"(",
")",
")",
"{",
"addGetDirectivesStatement",
"(",
"initBuilder",
")",
";",
"}",
"classTypeMirrors",
".",
"forEach",
"(",
"classTypeMirror",
"->",
"{",
"TypeElement",
"classTypeElement",
"=",
"(",
"TypeElement",
")",
"classTypeMirror",
".",
"asElement",
"(",
")",
";",
"initBuilder",
".",
"addStatement",
"(",
"\"directives.set($S, new $T())\"",
",",
"directiveToTagName",
"(",
"classTypeElement",
".",
"getSimpleName",
"(",
")",
".",
"toString",
"(",
")",
")",
",",
"directiveOptionsName",
"(",
"classTypeElement",
")",
")",
";",
"}",
")",
";",
"}",
"}"
] | Register directives passed to the annotation.
@param annotation The Component annotation on the Component we generate for
@param initBuilder The builder for the init method | [
"Register",
"directives",
"passed",
"to",
"the",
"annotation",
"."
] | train | https://github.com/VueGWT/vue-gwt/blob/961cd83aed6fe8e2dd80c279847f1b3f62918a1f/processors/src/main/java/com/axellience/vuegwt/processors/component/factory/VueComponentFactoryGenerator.java#L179-L206 |
thinkaurelius/titan | titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/locking/consistentkey/ConsistentKeyLocker.java | ConsistentKeyLocker.handleMutationFailure | private void handleMutationFailure(KeyColumn lockID, StaticBuffer lockKey, WriteResult wr, StoreTransaction txh) throws Throwable {
"""
Log a message and/or throw an exception in response to a lock write
mutation that failed. "Failed" means that the mutation either succeeded
but took longer to complete than configured lock wait time, or that
the call to mutate threw something.
@param lockID coordinates identifying the lock we tried but failed to
acquire
@param lockKey the byte value of the key that we mutated or attempted to
mutate in the lock store
@param wr result of the mutation
@param txh transaction attempting the lock
@throws Throwable if {@link WriteResult#getThrowable()} is not an instance of
{@link com.thinkaurelius.titan.diskstorage.TemporaryBackendException}
"""
Throwable error = wr.getThrowable();
if (null != error) {
if (error instanceof TemporaryBackendException) {
// Log error and continue the loop
log.warn("Temporary exception during lock write", error);
} else {
/*
* A PermanentStorageException or an unchecked exception. Try to
* delete any previous writes and then die. Do not retry even if
* we have retries left.
*/
log.error("Fatal exception encountered during attempted lock write", error);
WriteResult dwr = tryDeleteLockOnce(lockKey, wr.getLockCol(), txh);
if (!dwr.isSuccessful()) {
log.warn("Failed to delete lock write: abandoning potentially-unreleased lock on " + lockID, dwr.getThrowable());
}
throw error;
}
} else {
log.warn("Lock write succeeded but took too long: duration {} exceeded limit {}", wr.getDuration(), lockWait);
}
} | java | private void handleMutationFailure(KeyColumn lockID, StaticBuffer lockKey, WriteResult wr, StoreTransaction txh) throws Throwable {
Throwable error = wr.getThrowable();
if (null != error) {
if (error instanceof TemporaryBackendException) {
// Log error and continue the loop
log.warn("Temporary exception during lock write", error);
} else {
/*
* A PermanentStorageException or an unchecked exception. Try to
* delete any previous writes and then die. Do not retry even if
* we have retries left.
*/
log.error("Fatal exception encountered during attempted lock write", error);
WriteResult dwr = tryDeleteLockOnce(lockKey, wr.getLockCol(), txh);
if (!dwr.isSuccessful()) {
log.warn("Failed to delete lock write: abandoning potentially-unreleased lock on " + lockID, dwr.getThrowable());
}
throw error;
}
} else {
log.warn("Lock write succeeded but took too long: duration {} exceeded limit {}", wr.getDuration(), lockWait);
}
} | [
"private",
"void",
"handleMutationFailure",
"(",
"KeyColumn",
"lockID",
",",
"StaticBuffer",
"lockKey",
",",
"WriteResult",
"wr",
",",
"StoreTransaction",
"txh",
")",
"throws",
"Throwable",
"{",
"Throwable",
"error",
"=",
"wr",
".",
"getThrowable",
"(",
")",
";",
"if",
"(",
"null",
"!=",
"error",
")",
"{",
"if",
"(",
"error",
"instanceof",
"TemporaryBackendException",
")",
"{",
"// Log error and continue the loop",
"log",
".",
"warn",
"(",
"\"Temporary exception during lock write\"",
",",
"error",
")",
";",
"}",
"else",
"{",
"/*\n * A PermanentStorageException or an unchecked exception. Try to\n * delete any previous writes and then die. Do not retry even if\n * we have retries left.\n */",
"log",
".",
"error",
"(",
"\"Fatal exception encountered during attempted lock write\"",
",",
"error",
")",
";",
"WriteResult",
"dwr",
"=",
"tryDeleteLockOnce",
"(",
"lockKey",
",",
"wr",
".",
"getLockCol",
"(",
")",
",",
"txh",
")",
";",
"if",
"(",
"!",
"dwr",
".",
"isSuccessful",
"(",
")",
")",
"{",
"log",
".",
"warn",
"(",
"\"Failed to delete lock write: abandoning potentially-unreleased lock on \"",
"+",
"lockID",
",",
"dwr",
".",
"getThrowable",
"(",
")",
")",
";",
"}",
"throw",
"error",
";",
"}",
"}",
"else",
"{",
"log",
".",
"warn",
"(",
"\"Lock write succeeded but took too long: duration {} exceeded limit {}\"",
",",
"wr",
".",
"getDuration",
"(",
")",
",",
"lockWait",
")",
";",
"}",
"}"
] | Log a message and/or throw an exception in response to a lock write
mutation that failed. "Failed" means that the mutation either succeeded
but took longer to complete than configured lock wait time, or that
the call to mutate threw something.
@param lockID coordinates identifying the lock we tried but failed to
acquire
@param lockKey the byte value of the key that we mutated or attempted to
mutate in the lock store
@param wr result of the mutation
@param txh transaction attempting the lock
@throws Throwable if {@link WriteResult#getThrowable()} is not an instance of
{@link com.thinkaurelius.titan.diskstorage.TemporaryBackendException} | [
"Log",
"a",
"message",
"and",
"/",
"or",
"throw",
"an",
"exception",
"in",
"response",
"to",
"a",
"lock",
"write",
"mutation",
"that",
"failed",
".",
"Failed",
"means",
"that",
"the",
"mutation",
"either",
"succeeded",
"but",
"took",
"longer",
"to",
"complete",
"than",
"configured",
"lock",
"wait",
"time",
"or",
"that",
"the",
"call",
"to",
"mutate",
"threw",
"something",
"."
] | train | https://github.com/thinkaurelius/titan/blob/ee226e52415b8bf43b700afac75fa5b9767993a5/titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/locking/consistentkey/ConsistentKeyLocker.java#L343-L365 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java | NumberUtil.roundStr | public static String roundStr(String numberStr, int scale, RoundingMode roundingMode) {
"""
保留固定位数小数<br>
例如保留四位小数:123.456789 =》 123.4567
@param numberStr 数字值的字符串表现形式
@param scale 保留小数位数
@param roundingMode 保留小数的模式 {@link RoundingMode}
@return 新值
@since 3.2.2
"""
return round(numberStr, scale, roundingMode).toString();
} | java | public static String roundStr(String numberStr, int scale, RoundingMode roundingMode) {
return round(numberStr, scale, roundingMode).toString();
} | [
"public",
"static",
"String",
"roundStr",
"(",
"String",
"numberStr",
",",
"int",
"scale",
",",
"RoundingMode",
"roundingMode",
")",
"{",
"return",
"round",
"(",
"numberStr",
",",
"scale",
",",
"roundingMode",
")",
".",
"toString",
"(",
")",
";",
"}"
] | 保留固定位数小数<br>
例如保留四位小数:123.456789 =》 123.4567
@param numberStr 数字值的字符串表现形式
@param scale 保留小数位数
@param roundingMode 保留小数的模式 {@link RoundingMode}
@return 新值
@since 3.2.2 | [
"保留固定位数小数<br",
">",
"例如保留四位小数:123",
".",
"456789",
"=",
"》",
"123",
".",
"4567"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java#L897-L899 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsBatch.java | DnsBatch.createChangeRequestCallback | private RpcBatch.Callback<Change> createChangeRequestCallback(
final String zoneName,
final DnsBatchResult<ChangeRequest> result,
final boolean nullForNotFound,
final boolean idempotent) {
"""
A joint callback for both "get change request" and "create change request" operations.
"""
return new RpcBatch.Callback<Change>() {
@Override
public void onSuccess(Change response) {
result.success(
response == null
? null
: ChangeRequest.fromPb(options.getService(), zoneName, response));
}
@Override
public void onFailure(GoogleJsonError googleJsonError) {
DnsException serviceException = new DnsException(googleJsonError, idempotent);
if (serviceException.getCode() == HTTP_NOT_FOUND) {
if ("entity.parameters.changeId".equals(serviceException.getLocation())
|| (serviceException.getMessage() != null
&& serviceException.getMessage().contains("parameters.changeId"))) {
// the change id was not found, but the zone exists
result.success(null);
return;
}
// the zone does not exist, so throw an exception
}
result.error(serviceException);
}
};
} | java | private RpcBatch.Callback<Change> createChangeRequestCallback(
final String zoneName,
final DnsBatchResult<ChangeRequest> result,
final boolean nullForNotFound,
final boolean idempotent) {
return new RpcBatch.Callback<Change>() {
@Override
public void onSuccess(Change response) {
result.success(
response == null
? null
: ChangeRequest.fromPb(options.getService(), zoneName, response));
}
@Override
public void onFailure(GoogleJsonError googleJsonError) {
DnsException serviceException = new DnsException(googleJsonError, idempotent);
if (serviceException.getCode() == HTTP_NOT_FOUND) {
if ("entity.parameters.changeId".equals(serviceException.getLocation())
|| (serviceException.getMessage() != null
&& serviceException.getMessage().contains("parameters.changeId"))) {
// the change id was not found, but the zone exists
result.success(null);
return;
}
// the zone does not exist, so throw an exception
}
result.error(serviceException);
}
};
} | [
"private",
"RpcBatch",
".",
"Callback",
"<",
"Change",
">",
"createChangeRequestCallback",
"(",
"final",
"String",
"zoneName",
",",
"final",
"DnsBatchResult",
"<",
"ChangeRequest",
">",
"result",
",",
"final",
"boolean",
"nullForNotFound",
",",
"final",
"boolean",
"idempotent",
")",
"{",
"return",
"new",
"RpcBatch",
".",
"Callback",
"<",
"Change",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onSuccess",
"(",
"Change",
"response",
")",
"{",
"result",
".",
"success",
"(",
"response",
"==",
"null",
"?",
"null",
":",
"ChangeRequest",
".",
"fromPb",
"(",
"options",
".",
"getService",
"(",
")",
",",
"zoneName",
",",
"response",
")",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onFailure",
"(",
"GoogleJsonError",
"googleJsonError",
")",
"{",
"DnsException",
"serviceException",
"=",
"new",
"DnsException",
"(",
"googleJsonError",
",",
"idempotent",
")",
";",
"if",
"(",
"serviceException",
".",
"getCode",
"(",
")",
"==",
"HTTP_NOT_FOUND",
")",
"{",
"if",
"(",
"\"entity.parameters.changeId\"",
".",
"equals",
"(",
"serviceException",
".",
"getLocation",
"(",
")",
")",
"||",
"(",
"serviceException",
".",
"getMessage",
"(",
")",
"!=",
"null",
"&&",
"serviceException",
".",
"getMessage",
"(",
")",
".",
"contains",
"(",
"\"parameters.changeId\"",
")",
")",
")",
"{",
"// the change id was not found, but the zone exists",
"result",
".",
"success",
"(",
"null",
")",
";",
"return",
";",
"}",
"// the zone does not exist, so throw an exception",
"}",
"result",
".",
"error",
"(",
"serviceException",
")",
";",
"}",
"}",
";",
"}"
] | A joint callback for both "get change request" and "create change request" operations. | [
"A",
"joint",
"callback",
"for",
"both",
"get",
"change",
"request",
"and",
"create",
"change",
"request",
"operations",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsBatch.java#L351-L381 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/jdbc/WSJdbcPreparedStatement.java | WSJdbcPreparedStatement.setURL | public void setURL(int i, java.net.URL url) throws SQLException {
"""
<p>Sets the designated parameter to the given java.net.URL value. The driver
converts this to an SQL DATALINK value when it sends it to the database.</p>
@param parameterIndex the first parameter is 1, the second is 2, ...
@param url the java.net.URL object to be set
@exception SQLException If a database access error occurs
"""
// - don't trace user data url.
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(this, tc, "setURL", i);
try {
pstmtImpl.setURL(i, url);
} catch (SQLException ex) {
FFDCFilter.processException(ex,
"com.ibm.ws.rsadapter.jdbc.WSJdbcPreparedStatement.setURL", "1140", this);
throw WSJdbcUtil.mapException(this, ex);
} catch (NullPointerException nullX) {
// No FFDC code needed; we might be closed.
throw runtimeXIfNotClosed(nullX);
}
} | java | public void setURL(int i, java.net.URL url) throws SQLException {
// - don't trace user data url.
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(this, tc, "setURL", i);
try {
pstmtImpl.setURL(i, url);
} catch (SQLException ex) {
FFDCFilter.processException(ex,
"com.ibm.ws.rsadapter.jdbc.WSJdbcPreparedStatement.setURL", "1140", this);
throw WSJdbcUtil.mapException(this, ex);
} catch (NullPointerException nullX) {
// No FFDC code needed; we might be closed.
throw runtimeXIfNotClosed(nullX);
}
} | [
"public",
"void",
"setURL",
"(",
"int",
"i",
",",
"java",
".",
"net",
".",
"URL",
"url",
")",
"throws",
"SQLException",
"{",
"// - don't trace user data url.",
"final",
"boolean",
"isTraceOn",
"=",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
";",
"if",
"(",
"isTraceOn",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"Tr",
".",
"debug",
"(",
"this",
",",
"tc",
",",
"\"setURL\"",
",",
"i",
")",
";",
"try",
"{",
"pstmtImpl",
".",
"setURL",
"(",
"i",
",",
"url",
")",
";",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"FFDCFilter",
".",
"processException",
"(",
"ex",
",",
"\"com.ibm.ws.rsadapter.jdbc.WSJdbcPreparedStatement.setURL\"",
",",
"\"1140\"",
",",
"this",
")",
";",
"throw",
"WSJdbcUtil",
".",
"mapException",
"(",
"this",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"NullPointerException",
"nullX",
")",
"{",
"// No FFDC code needed; we might be closed.",
"throw",
"runtimeXIfNotClosed",
"(",
"nullX",
")",
";",
"}",
"}"
] | <p>Sets the designated parameter to the given java.net.URL value. The driver
converts this to an SQL DATALINK value when it sends it to the database.</p>
@param parameterIndex the first parameter is 1, the second is 2, ...
@param url the java.net.URL object to be set
@exception SQLException If a database access error occurs | [
"<p",
">",
"Sets",
"the",
"designated",
"parameter",
"to",
"the",
"given",
"java",
".",
"net",
".",
"URL",
"value",
".",
"The",
"driver",
"converts",
"this",
"to",
"an",
"SQL",
"DATALINK",
"value",
"when",
"it",
"sends",
"it",
"to",
"the",
"database",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/jdbc/WSJdbcPreparedStatement.java#L1953-L1970 |
Samsung/GearVRf | GVRf/Extensions/3DCursor/IODevices/io_template/src/main/java/com/sample/template/TemplateDevice.java | TemplateDevice.dispatchKeyEvent | public void dispatchKeyEvent(int code, int action) {
"""
Synthesize and forward a KeyEvent to the library.
This call is made from the native layer.
@param code id of the button
@param action integer representing the action taken on the button
"""
int keyCode = 0;
int keyAction = 0;
if (code == BUTTON_1) {
keyCode = KeyEvent.KEYCODE_BUTTON_1;
} else if (code == BUTTON_2) {
keyCode = KeyEvent.KEYCODE_BUTTON_2;
}
if (action == ACTION_DOWN) {
keyAction = KeyEvent.ACTION_DOWN;
} else if (action == ACTION_UP) {
keyAction = KeyEvent.ACTION_UP;
}
KeyEvent keyEvent = new KeyEvent(keyAction, keyCode);
setKeyEvent(keyEvent);
} | java | public void dispatchKeyEvent(int code, int action) {
int keyCode = 0;
int keyAction = 0;
if (code == BUTTON_1) {
keyCode = KeyEvent.KEYCODE_BUTTON_1;
} else if (code == BUTTON_2) {
keyCode = KeyEvent.KEYCODE_BUTTON_2;
}
if (action == ACTION_DOWN) {
keyAction = KeyEvent.ACTION_DOWN;
} else if (action == ACTION_UP) {
keyAction = KeyEvent.ACTION_UP;
}
KeyEvent keyEvent = new KeyEvent(keyAction, keyCode);
setKeyEvent(keyEvent);
} | [
"public",
"void",
"dispatchKeyEvent",
"(",
"int",
"code",
",",
"int",
"action",
")",
"{",
"int",
"keyCode",
"=",
"0",
";",
"int",
"keyAction",
"=",
"0",
";",
"if",
"(",
"code",
"==",
"BUTTON_1",
")",
"{",
"keyCode",
"=",
"KeyEvent",
".",
"KEYCODE_BUTTON_1",
";",
"}",
"else",
"if",
"(",
"code",
"==",
"BUTTON_2",
")",
"{",
"keyCode",
"=",
"KeyEvent",
".",
"KEYCODE_BUTTON_2",
";",
"}",
"if",
"(",
"action",
"==",
"ACTION_DOWN",
")",
"{",
"keyAction",
"=",
"KeyEvent",
".",
"ACTION_DOWN",
";",
"}",
"else",
"if",
"(",
"action",
"==",
"ACTION_UP",
")",
"{",
"keyAction",
"=",
"KeyEvent",
".",
"ACTION_UP",
";",
"}",
"KeyEvent",
"keyEvent",
"=",
"new",
"KeyEvent",
"(",
"keyAction",
",",
"keyCode",
")",
";",
"setKeyEvent",
"(",
"keyEvent",
")",
";",
"}"
] | Synthesize and forward a KeyEvent to the library.
This call is made from the native layer.
@param code id of the button
@param action integer representing the action taken on the button | [
"Synthesize",
"and",
"forward",
"a",
"KeyEvent",
"to",
"the",
"library",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/3DCursor/IODevices/io_template/src/main/java/com/sample/template/TemplateDevice.java#L147-L164 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ReferenceUtil.java | ReferenceUtil.create | public static <T> Reference<T> create(ReferenceType type, T referent) {
"""
获得引用
@param <T> 被引用对象类型
@param type 引用类型枚举
@param referent 被引用对象
@return {@link Reference}
"""
return create(type, referent, null);
} | java | public static <T> Reference<T> create(ReferenceType type, T referent) {
return create(type, referent, null);
} | [
"public",
"static",
"<",
"T",
">",
"Reference",
"<",
"T",
">",
"create",
"(",
"ReferenceType",
"type",
",",
"T",
"referent",
")",
"{",
"return",
"create",
"(",
"type",
",",
"referent",
",",
"null",
")",
";",
"}"
] | 获得引用
@param <T> 被引用对象类型
@param type 引用类型枚举
@param referent 被引用对象
@return {@link Reference} | [
"获得引用"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ReferenceUtil.java#L31-L33 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java | CommonOps_DDF2.elementMult | public static void elementMult( DMatrix2x2 a , DMatrix2x2 b) {
"""
<p>Performs an element by element multiplication operation:<br>
<br>
a<sub>ij</sub> = a<sub>ij</sub> * b<sub>ij</sub> <br>
</p>
@param a The left matrix in the multiplication operation. Modified.
@param b The right matrix in the multiplication operation. Not modified.
"""
a.a11 *= b.a11; a.a12 *= b.a12;
a.a21 *= b.a21; a.a22 *= b.a22;
} | java | public static void elementMult( DMatrix2x2 a , DMatrix2x2 b) {
a.a11 *= b.a11; a.a12 *= b.a12;
a.a21 *= b.a21; a.a22 *= b.a22;
} | [
"public",
"static",
"void",
"elementMult",
"(",
"DMatrix2x2",
"a",
",",
"DMatrix2x2",
"b",
")",
"{",
"a",
".",
"a11",
"*=",
"b",
".",
"a11",
";",
"a",
".",
"a12",
"*=",
"b",
".",
"a12",
";",
"a",
".",
"a21",
"*=",
"b",
".",
"a21",
";",
"a",
".",
"a22",
"*=",
"b",
".",
"a22",
";",
"}"
] | <p>Performs an element by element multiplication operation:<br>
<br>
a<sub>ij</sub> = a<sub>ij</sub> * b<sub>ij</sub> <br>
</p>
@param a The left matrix in the multiplication operation. Modified.
@param b The right matrix in the multiplication operation. Not modified. | [
"<p",
">",
"Performs",
"an",
"element",
"by",
"element",
"multiplication",
"operation",
":",
"<br",
">",
"<br",
">",
"a<sub",
">",
"ij<",
"/",
"sub",
">",
"=",
"a<sub",
">",
"ij<",
"/",
"sub",
">",
"*",
"b<sub",
">",
"ij<",
"/",
"sub",
">",
"<br",
">",
"<",
"/",
"p",
">"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java#L866-L869 |
vdmeer/asciitable | src/main/java/de/vandermeer/asciitable/AsciiTable.java | AsciiTable.setPaddingLeftRight | public AsciiTable setPaddingLeftRight(int paddingLeft, int paddingRight) {
"""
Sets left and right padding for all cells in the table (only if both values are not smaller than 0).
@param paddingLeft new left padding, ignored if smaller than 0
@param paddingRight new right padding, ignored if smaller than 0
@return this to allow chaining
"""
for(AT_Row row : this.rows){
if(row.getType()==TableRowType.CONTENT){
row.setPaddingLeftRight(paddingLeft, paddingRight);
}
}
return this;
} | java | public AsciiTable setPaddingLeftRight(int paddingLeft, int paddingRight){
for(AT_Row row : this.rows){
if(row.getType()==TableRowType.CONTENT){
row.setPaddingLeftRight(paddingLeft, paddingRight);
}
}
return this;
} | [
"public",
"AsciiTable",
"setPaddingLeftRight",
"(",
"int",
"paddingLeft",
",",
"int",
"paddingRight",
")",
"{",
"for",
"(",
"AT_Row",
"row",
":",
"this",
".",
"rows",
")",
"{",
"if",
"(",
"row",
".",
"getType",
"(",
")",
"==",
"TableRowType",
".",
"CONTENT",
")",
"{",
"row",
".",
"setPaddingLeftRight",
"(",
"paddingLeft",
",",
"paddingRight",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
] | Sets left and right padding for all cells in the table (only if both values are not smaller than 0).
@param paddingLeft new left padding, ignored if smaller than 0
@param paddingRight new right padding, ignored if smaller than 0
@return this to allow chaining | [
"Sets",
"left",
"and",
"right",
"padding",
"for",
"all",
"cells",
"in",
"the",
"table",
"(",
"only",
"if",
"both",
"values",
"are",
"not",
"smaller",
"than",
"0",
")",
"."
] | train | https://github.com/vdmeer/asciitable/blob/b6a73710271c89f9c749603be856ba84a969ed5f/src/main/java/de/vandermeer/asciitable/AsciiTable.java#L329-L336 |
JavaMoney/jsr354-api | src/main/java/javax/money/format/AmountFormatQuery.java | AmountFormatQuery.of | public static AmountFormatQuery of(Locale locale, String... providers) {
"""
Creates a simple format query based on a single Locale, similar to {@link java.text.DecimalFormat#getInstance
(java.util.Locale)}.
@param locale the target locale, not null.
@param providers the providers to be used, not null.
@return a new query instance
"""
return AmountFormatQueryBuilder.of(locale).setProviderNames(providers).build();
} | java | public static AmountFormatQuery of(Locale locale, String... providers) {
return AmountFormatQueryBuilder.of(locale).setProviderNames(providers).build();
} | [
"public",
"static",
"AmountFormatQuery",
"of",
"(",
"Locale",
"locale",
",",
"String",
"...",
"providers",
")",
"{",
"return",
"AmountFormatQueryBuilder",
".",
"of",
"(",
"locale",
")",
".",
"setProviderNames",
"(",
"providers",
")",
".",
"build",
"(",
")",
";",
"}"
] | Creates a simple format query based on a single Locale, similar to {@link java.text.DecimalFormat#getInstance
(java.util.Locale)}.
@param locale the target locale, not null.
@param providers the providers to be used, not null.
@return a new query instance | [
"Creates",
"a",
"simple",
"format",
"query",
"based",
"on",
"a",
"single",
"Locale",
"similar",
"to",
"{",
"@link",
"java",
".",
"text",
".",
"DecimalFormat#getInstance",
"(",
"java",
".",
"util",
".",
"Locale",
")",
"}",
"."
] | train | https://github.com/JavaMoney/jsr354-api/blob/49a7ae436eaf45cac1040879185531ef22de5525/src/main/java/javax/money/format/AmountFormatQuery.java#L96-L98 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/h2internal/H2StreamProcessor.java | H2StreamProcessor.updateStreamReadWindow | private void updateStreamReadWindow() throws Http2Exception {
"""
If this stream is receiving a DATA frame, the local read window needs to be updated. If the read window drops below a threshold,
a WINDOW_UPDATE frame will be sent for both the connection and stream to update the windows.
"""
if (currentFrame instanceof FrameData) {
long frameSize = currentFrame.getPayloadLength();
streamReadWindowSize -= frameSize; // decrement stream read window
muxLink.connectionReadWindowSize -= frameSize; // decrement connection read window
// if the stream or connection windows become too small, update the windows
// TODO: decide how often we should update the read window via WINDOW_UPDATE
if (streamReadWindowSize < (muxLink.maxReadWindowSize / 2) ||
muxLink.connectionReadWindowSize < (muxLink.maxReadWindowSize / 2)) {
int windowChange = (int) (muxLink.maxReadWindowSize - this.streamReadWindowSize);
Frame savedFrame = currentFrame; // save off the current frame
if (!this.isStreamClosed()) {
currentFrame = new FrameWindowUpdate(myID, windowChange, false);
writeFrameSync();
currentFrame = savedFrame;
}
long windowSizeIncrement = muxLink.getRemoteConnectionSettings().getMaxFrameSize();
FrameWindowUpdate wuf = new FrameWindowUpdate(0, (int) windowSizeIncrement, false);
this.muxLink.getStream(0).processNextFrame(wuf, Direction.WRITING_OUT);
}
}
} | java | private void updateStreamReadWindow() throws Http2Exception {
if (currentFrame instanceof FrameData) {
long frameSize = currentFrame.getPayloadLength();
streamReadWindowSize -= frameSize; // decrement stream read window
muxLink.connectionReadWindowSize -= frameSize; // decrement connection read window
// if the stream or connection windows become too small, update the windows
// TODO: decide how often we should update the read window via WINDOW_UPDATE
if (streamReadWindowSize < (muxLink.maxReadWindowSize / 2) ||
muxLink.connectionReadWindowSize < (muxLink.maxReadWindowSize / 2)) {
int windowChange = (int) (muxLink.maxReadWindowSize - this.streamReadWindowSize);
Frame savedFrame = currentFrame; // save off the current frame
if (!this.isStreamClosed()) {
currentFrame = new FrameWindowUpdate(myID, windowChange, false);
writeFrameSync();
currentFrame = savedFrame;
}
long windowSizeIncrement = muxLink.getRemoteConnectionSettings().getMaxFrameSize();
FrameWindowUpdate wuf = new FrameWindowUpdate(0, (int) windowSizeIncrement, false);
this.muxLink.getStream(0).processNextFrame(wuf, Direction.WRITING_OUT);
}
}
} | [
"private",
"void",
"updateStreamReadWindow",
"(",
")",
"throws",
"Http2Exception",
"{",
"if",
"(",
"currentFrame",
"instanceof",
"FrameData",
")",
"{",
"long",
"frameSize",
"=",
"currentFrame",
".",
"getPayloadLength",
"(",
")",
";",
"streamReadWindowSize",
"-=",
"frameSize",
";",
"// decrement stream read window",
"muxLink",
".",
"connectionReadWindowSize",
"-=",
"frameSize",
";",
"// decrement connection read window",
"// if the stream or connection windows become too small, update the windows",
"// TODO: decide how often we should update the read window via WINDOW_UPDATE",
"if",
"(",
"streamReadWindowSize",
"<",
"(",
"muxLink",
".",
"maxReadWindowSize",
"/",
"2",
")",
"||",
"muxLink",
".",
"connectionReadWindowSize",
"<",
"(",
"muxLink",
".",
"maxReadWindowSize",
"/",
"2",
")",
")",
"{",
"int",
"windowChange",
"=",
"(",
"int",
")",
"(",
"muxLink",
".",
"maxReadWindowSize",
"-",
"this",
".",
"streamReadWindowSize",
")",
";",
"Frame",
"savedFrame",
"=",
"currentFrame",
";",
"// save off the current frame",
"if",
"(",
"!",
"this",
".",
"isStreamClosed",
"(",
")",
")",
"{",
"currentFrame",
"=",
"new",
"FrameWindowUpdate",
"(",
"myID",
",",
"windowChange",
",",
"false",
")",
";",
"writeFrameSync",
"(",
")",
";",
"currentFrame",
"=",
"savedFrame",
";",
"}",
"long",
"windowSizeIncrement",
"=",
"muxLink",
".",
"getRemoteConnectionSettings",
"(",
")",
".",
"getMaxFrameSize",
"(",
")",
";",
"FrameWindowUpdate",
"wuf",
"=",
"new",
"FrameWindowUpdate",
"(",
"0",
",",
"(",
"int",
")",
"windowSizeIncrement",
",",
"false",
")",
";",
"this",
".",
"muxLink",
".",
"getStream",
"(",
"0",
")",
".",
"processNextFrame",
"(",
"wuf",
",",
"Direction",
".",
"WRITING_OUT",
")",
";",
"}",
"}",
"}"
] | If this stream is receiving a DATA frame, the local read window needs to be updated. If the read window drops below a threshold,
a WINDOW_UPDATE frame will be sent for both the connection and stream to update the windows. | [
"If",
"this",
"stream",
"is",
"receiving",
"a",
"DATA",
"frame",
"the",
"local",
"read",
"window",
"needs",
"to",
"be",
"updated",
".",
"If",
"the",
"read",
"window",
"drops",
"below",
"a",
"threshold",
"a",
"WINDOW_UPDATE",
"frame",
"will",
"be",
"sent",
"for",
"both",
"the",
"connection",
"and",
"stream",
"to",
"update",
"the",
"windows",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/h2internal/H2StreamProcessor.java#L756-L779 |
chrisruffalo/ee-config | src/main/java/com/github/chrisruffalo/eeconfig/resources/configuration/AbstractConfigurationProducer.java | AbstractConfigurationProducer.resloveSource | private ISource resloveSource(Source source, PropertyResolver resolver, Map<Object, Object> bootstrapMap, Map<Object, Object> defaultMap) {
"""
Resolve a given source from the provided {@link Source} annotation
@param source
@param resolver
@return
"""
Class<? extends Locator> locatorClass = source.locator();
if(locatorClass == null) {
locatorClass = NullLocator.class;
}
Locator locator = this.beanResolver.resolveBeanWithDefaultClass(locatorClass, NullLocator.class);
this.logger.trace("Using locator: '{}'", locator.getClass().getName());
// resolve path if enabled
String path = source.value();
if(resolver != null && source.resolve()) {
path = resolver.resolveProperties(path, bootstrapMap, defaultMap);
}
// log path
this.logger.trace("Looking for source at path: '{}'", path);
// locate
ISource foundSource = locator.locate(path);
// log results
this.logger.trace("Source: '{}' (using locator '{}')", foundSource, locator.getClass().getName());
return foundSource;
} | java | private ISource resloveSource(Source source, PropertyResolver resolver, Map<Object, Object> bootstrapMap, Map<Object, Object> defaultMap) {
Class<? extends Locator> locatorClass = source.locator();
if(locatorClass == null) {
locatorClass = NullLocator.class;
}
Locator locator = this.beanResolver.resolveBeanWithDefaultClass(locatorClass, NullLocator.class);
this.logger.trace("Using locator: '{}'", locator.getClass().getName());
// resolve path if enabled
String path = source.value();
if(resolver != null && source.resolve()) {
path = resolver.resolveProperties(path, bootstrapMap, defaultMap);
}
// log path
this.logger.trace("Looking for source at path: '{}'", path);
// locate
ISource foundSource = locator.locate(path);
// log results
this.logger.trace("Source: '{}' (using locator '{}')", foundSource, locator.getClass().getName());
return foundSource;
} | [
"private",
"ISource",
"resloveSource",
"(",
"Source",
"source",
",",
"PropertyResolver",
"resolver",
",",
"Map",
"<",
"Object",
",",
"Object",
">",
"bootstrapMap",
",",
"Map",
"<",
"Object",
",",
"Object",
">",
"defaultMap",
")",
"{",
"Class",
"<",
"?",
"extends",
"Locator",
">",
"locatorClass",
"=",
"source",
".",
"locator",
"(",
")",
";",
"if",
"(",
"locatorClass",
"==",
"null",
")",
"{",
"locatorClass",
"=",
"NullLocator",
".",
"class",
";",
"}",
"Locator",
"locator",
"=",
"this",
".",
"beanResolver",
".",
"resolveBeanWithDefaultClass",
"(",
"locatorClass",
",",
"NullLocator",
".",
"class",
")",
";",
"this",
".",
"logger",
".",
"trace",
"(",
"\"Using locator: '{}'\"",
",",
"locator",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"// resolve path if enabled",
"String",
"path",
"=",
"source",
".",
"value",
"(",
")",
";",
"if",
"(",
"resolver",
"!=",
"null",
"&&",
"source",
".",
"resolve",
"(",
")",
")",
"{",
"path",
"=",
"resolver",
".",
"resolveProperties",
"(",
"path",
",",
"bootstrapMap",
",",
"defaultMap",
")",
";",
"}",
"// log path",
"this",
".",
"logger",
".",
"trace",
"(",
"\"Looking for source at path: '{}'\"",
",",
"path",
")",
";",
"// locate",
"ISource",
"foundSource",
"=",
"locator",
".",
"locate",
"(",
"path",
")",
";",
"// log results",
"this",
".",
"logger",
".",
"trace",
"(",
"\"Source: '{}' (using locator '{}')\"",
",",
"foundSource",
",",
"locator",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"return",
"foundSource",
";",
"}"
] | Resolve a given source from the provided {@link Source} annotation
@param source
@param resolver
@return | [
"Resolve",
"a",
"given",
"source",
"from",
"the",
"provided",
"{",
"@link",
"Source",
"}",
"annotation"
] | train | https://github.com/chrisruffalo/ee-config/blob/6cdc59e2117e97c1997b79a19cbfaa284027e60c/src/main/java/com/github/chrisruffalo/eeconfig/resources/configuration/AbstractConfigurationProducer.java#L109-L132 |
salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/entity/GlobalInterlock.java | GlobalInterlock.refreshLock | public static String refreshLock(EntityManager em, long type, String key, String note) {
"""
Refreshes a global lock of the indicated type if the supplied key is a match for the lock.
@param em The entity manager factory to use. Cannot be null.
@param type The type of key to release.
@param key The key value obtained from the lock creation.
@param note A descriptive note about the lock context.
@return The updated unique key to be used from clients when releasing the lock.
@throws GlobalInterlockException If the lock cannot be refreshed.
"""
EntityTransaction tx = null;
/* refresh the existing lock if it matches the key. */
try {
tx = em.getTransaction();
tx.begin();
GlobalInterlock lock = _findAndRefreshLock(em, type);
if (lock == null) {
throw new GlobalInterlockException("No lock of type " + type + " exists for key " + key + ".");
}
String ref = Long.toHexString(lock.lockTime);
if (ref.equalsIgnoreCase(key)) {
lock.lockTime = System.currentTimeMillis();
lock.note = note;
em.merge(lock);
em.flush();
tx.commit();
return Long.toHexString(lock.lockTime);
}
throw new GlobalInterlockException("This process doesn't own the type " + type + " lock having key " + key + ".");
} finally {
if (tx != null && tx.isActive()) {
tx.rollback();
}
}
} | java | public static String refreshLock(EntityManager em, long type, String key, String note) {
EntityTransaction tx = null;
/* refresh the existing lock if it matches the key. */
try {
tx = em.getTransaction();
tx.begin();
GlobalInterlock lock = _findAndRefreshLock(em, type);
if (lock == null) {
throw new GlobalInterlockException("No lock of type " + type + " exists for key " + key + ".");
}
String ref = Long.toHexString(lock.lockTime);
if (ref.equalsIgnoreCase(key)) {
lock.lockTime = System.currentTimeMillis();
lock.note = note;
em.merge(lock);
em.flush();
tx.commit();
return Long.toHexString(lock.lockTime);
}
throw new GlobalInterlockException("This process doesn't own the type " + type + " lock having key " + key + ".");
} finally {
if (tx != null && tx.isActive()) {
tx.rollback();
}
}
} | [
"public",
"static",
"String",
"refreshLock",
"(",
"EntityManager",
"em",
",",
"long",
"type",
",",
"String",
"key",
",",
"String",
"note",
")",
"{",
"EntityTransaction",
"tx",
"=",
"null",
";",
"/* refresh the existing lock if it matches the key. */",
"try",
"{",
"tx",
"=",
"em",
".",
"getTransaction",
"(",
")",
";",
"tx",
".",
"begin",
"(",
")",
";",
"GlobalInterlock",
"lock",
"=",
"_findAndRefreshLock",
"(",
"em",
",",
"type",
")",
";",
"if",
"(",
"lock",
"==",
"null",
")",
"{",
"throw",
"new",
"GlobalInterlockException",
"(",
"\"No lock of type \"",
"+",
"type",
"+",
"\" exists for key \"",
"+",
"key",
"+",
"\".\"",
")",
";",
"}",
"String",
"ref",
"=",
"Long",
".",
"toHexString",
"(",
"lock",
".",
"lockTime",
")",
";",
"if",
"(",
"ref",
".",
"equalsIgnoreCase",
"(",
"key",
")",
")",
"{",
"lock",
".",
"lockTime",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"lock",
".",
"note",
"=",
"note",
";",
"em",
".",
"merge",
"(",
"lock",
")",
";",
"em",
".",
"flush",
"(",
")",
";",
"tx",
".",
"commit",
"(",
")",
";",
"return",
"Long",
".",
"toHexString",
"(",
"lock",
".",
"lockTime",
")",
";",
"}",
"throw",
"new",
"GlobalInterlockException",
"(",
"\"This process doesn't own the type \"",
"+",
"type",
"+",
"\" lock having key \"",
"+",
"key",
"+",
"\".\"",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"tx",
"!=",
"null",
"&&",
"tx",
".",
"isActive",
"(",
")",
")",
"{",
"tx",
".",
"rollback",
"(",
")",
";",
"}",
"}",
"}"
] | Refreshes a global lock of the indicated type if the supplied key is a match for the lock.
@param em The entity manager factory to use. Cannot be null.
@param type The type of key to release.
@param key The key value obtained from the lock creation.
@param note A descriptive note about the lock context.
@return The updated unique key to be used from clients when releasing the lock.
@throws GlobalInterlockException If the lock cannot be refreshed. | [
"Refreshes",
"a",
"global",
"lock",
"of",
"the",
"indicated",
"type",
"if",
"the",
"supplied",
"key",
"is",
"a",
"match",
"for",
"the",
"lock",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/GlobalInterlock.java#L235-L265 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/AccessAuditContext.java | AccessAuditContext.doAs | public static <T> T doAs(boolean inflowed, SecurityIdentity securityIdentity, InetAddress remoteAddress, PrivilegedExceptionAction<T> action)
throws java.security.PrivilegedActionException {
"""
Perform work with a new {@code AccessAuditContext} as a particular {@code SecurityIdentity}
@param inflowed was the identity inflowed from a remote process?
@param securityIdentity the {@code SecurityIdentity} that the specified {@code action} will run as. May be {@code null}
@param remoteAddress the remote address of the caller.
@param action the work to perform. Cannot be {@code null}
@param <T> the type of teh return value
@return the value returned by the PrivilegedAction's <code>run</code> method
@exception java.security.PrivilegedActionException if the
<code>PrivilegedExceptionAction.run</code>
method throws a checked exception.
@exception NullPointerException if the specified
<code>PrivilegedExceptionAction</code> is
<code>null</code>.
@exception SecurityException if the caller does not have permission
to invoke this method.
"""
final AccessAuditContext previous = contextThreadLocal.get();
try {
contextThreadLocal.set(new AccessAuditContext(inflowed, securityIdentity, remoteAddress, previous));
if (securityIdentity != null) {
return securityIdentity.runAs(action);
} else try {
return action.run();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new PrivilegedActionException(e);
}
} finally {
contextThreadLocal.set(previous);
}
} | java | public static <T> T doAs(boolean inflowed, SecurityIdentity securityIdentity, InetAddress remoteAddress, PrivilegedExceptionAction<T> action)
throws java.security.PrivilegedActionException {
final AccessAuditContext previous = contextThreadLocal.get();
try {
contextThreadLocal.set(new AccessAuditContext(inflowed, securityIdentity, remoteAddress, previous));
if (securityIdentity != null) {
return securityIdentity.runAs(action);
} else try {
return action.run();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new PrivilegedActionException(e);
}
} finally {
contextThreadLocal.set(previous);
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"doAs",
"(",
"boolean",
"inflowed",
",",
"SecurityIdentity",
"securityIdentity",
",",
"InetAddress",
"remoteAddress",
",",
"PrivilegedExceptionAction",
"<",
"T",
">",
"action",
")",
"throws",
"java",
".",
"security",
".",
"PrivilegedActionException",
"{",
"final",
"AccessAuditContext",
"previous",
"=",
"contextThreadLocal",
".",
"get",
"(",
")",
";",
"try",
"{",
"contextThreadLocal",
".",
"set",
"(",
"new",
"AccessAuditContext",
"(",
"inflowed",
",",
"securityIdentity",
",",
"remoteAddress",
",",
"previous",
")",
")",
";",
"if",
"(",
"securityIdentity",
"!=",
"null",
")",
"{",
"return",
"securityIdentity",
".",
"runAs",
"(",
"action",
")",
";",
"}",
"else",
"try",
"{",
"return",
"action",
".",
"run",
"(",
")",
";",
"}",
"catch",
"(",
"RuntimeException",
"e",
")",
"{",
"throw",
"e",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"PrivilegedActionException",
"(",
"e",
")",
";",
"}",
"}",
"finally",
"{",
"contextThreadLocal",
".",
"set",
"(",
"previous",
")",
";",
"}",
"}"
] | Perform work with a new {@code AccessAuditContext} as a particular {@code SecurityIdentity}
@param inflowed was the identity inflowed from a remote process?
@param securityIdentity the {@code SecurityIdentity} that the specified {@code action} will run as. May be {@code null}
@param remoteAddress the remote address of the caller.
@param action the work to perform. Cannot be {@code null}
@param <T> the type of teh return value
@return the value returned by the PrivilegedAction's <code>run</code> method
@exception java.security.PrivilegedActionException if the
<code>PrivilegedExceptionAction.run</code>
method throws a checked exception.
@exception NullPointerException if the specified
<code>PrivilegedExceptionAction</code> is
<code>null</code>.
@exception SecurityException if the caller does not have permission
to invoke this method. | [
"Perform",
"work",
"with",
"a",
"new",
"{",
"@code",
"AccessAuditContext",
"}",
"as",
"a",
"particular",
"{",
"@code",
"SecurityIdentity",
"}",
"@param",
"inflowed",
"was",
"the",
"identity",
"inflowed",
"from",
"a",
"remote",
"process?",
"@param",
"securityIdentity",
"the",
"{",
"@code",
"SecurityIdentity",
"}",
"that",
"the",
"specified",
"{",
"@code",
"action",
"}",
"will",
"run",
"as",
".",
"May",
"be",
"{",
"@code",
"null",
"}",
"@param",
"remoteAddress",
"the",
"remote",
"address",
"of",
"the",
"caller",
".",
"@param",
"action",
"the",
"work",
"to",
"perform",
".",
"Cannot",
"be",
"{",
"@code",
"null",
"}",
"@param",
"<T",
">",
"the",
"type",
"of",
"teh",
"return",
"value",
"@return",
"the",
"value",
"returned",
"by",
"the",
"PrivilegedAction",
"s",
"<code",
">",
"run<",
"/",
"code",
">",
"method"
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AccessAuditContext.java#L248-L265 |
steveohara/j2mod | src/main/java/com/ghgande/j2mod/modbus/io/ModbusSerialTransport.java | ModbusSerialTransport.waitBetweenFrames | void waitBetweenFrames(int transDelayMS, long lastTransactionTimestamp) {
"""
Injects a delay dependent on the last time we received a response or
if a fixed delay has been specified
@param transDelayMS Fixed transaction delay (milliseconds)
@param lastTransactionTimestamp Timestamp of last transaction
"""
// If a fixed delay has been set
if (transDelayMS > 0) {
ModbusUtil.sleep(transDelayMS);
}
else {
// Make use we have a gap of 3.5 characters between adjacent requests
// We have to do the calculations here because it is possible that the caller may have changed
// the connection characteristics if they provided the connection instance
int delay = getInterFrameDelay() / 1000;
// How long since the last message we received
long gapSinceLastMessage = (System.nanoTime() - lastTransactionTimestamp) / NS_IN_A_MS;
if (delay > gapSinceLastMessage) {
long sleepTime = delay - gapSinceLastMessage;
ModbusUtil.sleep(sleepTime);
if (logger.isDebugEnabled()) {
logger.debug("Waited between frames for {} ms", sleepTime);
}
}
}
} | java | void waitBetweenFrames(int transDelayMS, long lastTransactionTimestamp) {
// If a fixed delay has been set
if (transDelayMS > 0) {
ModbusUtil.sleep(transDelayMS);
}
else {
// Make use we have a gap of 3.5 characters between adjacent requests
// We have to do the calculations here because it is possible that the caller may have changed
// the connection characteristics if they provided the connection instance
int delay = getInterFrameDelay() / 1000;
// How long since the last message we received
long gapSinceLastMessage = (System.nanoTime() - lastTransactionTimestamp) / NS_IN_A_MS;
if (delay > gapSinceLastMessage) {
long sleepTime = delay - gapSinceLastMessage;
ModbusUtil.sleep(sleepTime);
if (logger.isDebugEnabled()) {
logger.debug("Waited between frames for {} ms", sleepTime);
}
}
}
} | [
"void",
"waitBetweenFrames",
"(",
"int",
"transDelayMS",
",",
"long",
"lastTransactionTimestamp",
")",
"{",
"// If a fixed delay has been set",
"if",
"(",
"transDelayMS",
">",
"0",
")",
"{",
"ModbusUtil",
".",
"sleep",
"(",
"transDelayMS",
")",
";",
"}",
"else",
"{",
"// Make use we have a gap of 3.5 characters between adjacent requests",
"// We have to do the calculations here because it is possible that the caller may have changed",
"// the connection characteristics if they provided the connection instance",
"int",
"delay",
"=",
"getInterFrameDelay",
"(",
")",
"/",
"1000",
";",
"// How long since the last message we received",
"long",
"gapSinceLastMessage",
"=",
"(",
"System",
".",
"nanoTime",
"(",
")",
"-",
"lastTransactionTimestamp",
")",
"/",
"NS_IN_A_MS",
";",
"if",
"(",
"delay",
">",
"gapSinceLastMessage",
")",
"{",
"long",
"sleepTime",
"=",
"delay",
"-",
"gapSinceLastMessage",
";",
"ModbusUtil",
".",
"sleep",
"(",
"sleepTime",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Waited between frames for {} ms\"",
",",
"sleepTime",
")",
";",
"}",
"}",
"}",
"}"
] | Injects a delay dependent on the last time we received a response or
if a fixed delay has been specified
@param transDelayMS Fixed transaction delay (milliseconds)
@param lastTransactionTimestamp Timestamp of last transaction | [
"Injects",
"a",
"delay",
"dependent",
"on",
"the",
"last",
"time",
"we",
"received",
"a",
"response",
"or",
"if",
"a",
"fixed",
"delay",
"has",
"been",
"specified"
] | train | https://github.com/steveohara/j2mod/blob/67162c55d7c02564e50211a9df06b8314953b5f2/src/main/java/com/ghgande/j2mod/modbus/io/ModbusSerialTransport.java#L593-L617 |
gosu-lang/gosu-lang | gosu-lab/src/main/java/editor/plugin/typeloader/java/JavaDocument.java | JavaDocument.insertString | @Override
public void insertString( int offset, String str, AttributeSet a ) throws BadLocationException {
"""
Override to apply syntax highlighting after the document has been updated
"""
switch( str )
{
case "(":
str = addParenthesis();
break;
case "\n":
str = addWhiteSpace( offset );
break;
case "\"":
str = addMatchingQuotationMark();
break;
case "{":
str = addMatchingBrace( offset );
break;
}
super.insertString( offset, str, a );
processChangedLines( offset, str.length() );
} | java | @Override
public void insertString( int offset, String str, AttributeSet a ) throws BadLocationException
{
switch( str )
{
case "(":
str = addParenthesis();
break;
case "\n":
str = addWhiteSpace( offset );
break;
case "\"":
str = addMatchingQuotationMark();
break;
case "{":
str = addMatchingBrace( offset );
break;
}
super.insertString( offset, str, a );
processChangedLines( offset, str.length() );
} | [
"@",
"Override",
"public",
"void",
"insertString",
"(",
"int",
"offset",
",",
"String",
"str",
",",
"AttributeSet",
"a",
")",
"throws",
"BadLocationException",
"{",
"switch",
"(",
"str",
")",
"{",
"case",
"\"(\"",
":",
"str",
"=",
"addParenthesis",
"(",
")",
";",
"break",
";",
"case",
"\"\\n\"",
":",
"str",
"=",
"addWhiteSpace",
"(",
"offset",
")",
";",
"break",
";",
"case",
"\"\\\"\"",
":",
"str",
"=",
"addMatchingQuotationMark",
"(",
")",
";",
"break",
";",
"case",
"\"{\"",
":",
"str",
"=",
"addMatchingBrace",
"(",
"offset",
")",
";",
"break",
";",
"}",
"super",
".",
"insertString",
"(",
"offset",
",",
"str",
",",
"a",
")",
";",
"processChangedLines",
"(",
"offset",
",",
"str",
".",
"length",
"(",
")",
")",
";",
"}"
] | Override to apply syntax highlighting after the document has been updated | [
"Override",
"to",
"apply",
"syntax",
"highlighting",
"after",
"the",
"document",
"has",
"been",
"updated"
] | train | https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-lab/src/main/java/editor/plugin/typeloader/java/JavaDocument.java#L114-L134 |
jbundle/jbundle | app/program/screen/src/main/java/org/jbundle/app/program/screen/LayoutGridScreen.java | LayoutGridScreen.doCommand | public boolean doCommand(String strCommand, ScreenField sourceSField, int iCommandOptions) {
"""
Process the command.
<br />Step 1 - Process the command if possible and return true if processed.
<br />Step 2 - If I can't process, pass to all children (with me as the source).
<br />Step 3 - If children didn't process, pass to parent (with me as the source).
<br />Note: Never pass to a parent or child that matches the source (to avoid an endless loop).
@param strCommand The command to process.
@param sourceSField The source screen field (to avoid echos).
@param iCommandOptions If this command creates a new screen, create in a new window?
@return true if success.
"""
if (strCommand.equalsIgnoreCase(MenuConstants.FORMDETAIL))
return (this.onForm(null, ScreenConstants.DETAIL_MODE, true, iCommandOptions, null) != null);
else if (strCommand.equalsIgnoreCase(MenuConstants.PRINT))
{
LayoutPrint layoutPrint = new LayoutPrint(this.getMainRecord(), null);
return true;
}
else
return super.doCommand(strCommand, sourceSField, iCommandOptions);
} | java | public boolean doCommand(String strCommand, ScreenField sourceSField, int iCommandOptions)
{
if (strCommand.equalsIgnoreCase(MenuConstants.FORMDETAIL))
return (this.onForm(null, ScreenConstants.DETAIL_MODE, true, iCommandOptions, null) != null);
else if (strCommand.equalsIgnoreCase(MenuConstants.PRINT))
{
LayoutPrint layoutPrint = new LayoutPrint(this.getMainRecord(), null);
return true;
}
else
return super.doCommand(strCommand, sourceSField, iCommandOptions);
} | [
"public",
"boolean",
"doCommand",
"(",
"String",
"strCommand",
",",
"ScreenField",
"sourceSField",
",",
"int",
"iCommandOptions",
")",
"{",
"if",
"(",
"strCommand",
".",
"equalsIgnoreCase",
"(",
"MenuConstants",
".",
"FORMDETAIL",
")",
")",
"return",
"(",
"this",
".",
"onForm",
"(",
"null",
",",
"ScreenConstants",
".",
"DETAIL_MODE",
",",
"true",
",",
"iCommandOptions",
",",
"null",
")",
"!=",
"null",
")",
";",
"else",
"if",
"(",
"strCommand",
".",
"equalsIgnoreCase",
"(",
"MenuConstants",
".",
"PRINT",
")",
")",
"{",
"LayoutPrint",
"layoutPrint",
"=",
"new",
"LayoutPrint",
"(",
"this",
".",
"getMainRecord",
"(",
")",
",",
"null",
")",
";",
"return",
"true",
";",
"}",
"else",
"return",
"super",
".",
"doCommand",
"(",
"strCommand",
",",
"sourceSField",
",",
"iCommandOptions",
")",
";",
"}"
] | Process the command.
<br />Step 1 - Process the command if possible and return true if processed.
<br />Step 2 - If I can't process, pass to all children (with me as the source).
<br />Step 3 - If children didn't process, pass to parent (with me as the source).
<br />Note: Never pass to a parent or child that matches the source (to avoid an endless loop).
@param strCommand The command to process.
@param sourceSField The source screen field (to avoid echos).
@param iCommandOptions If this command creates a new screen, create in a new window?
@return true if success. | [
"Process",
"the",
"command",
".",
"<br",
"/",
">",
"Step",
"1",
"-",
"Process",
"the",
"command",
"if",
"possible",
"and",
"return",
"true",
"if",
"processed",
".",
"<br",
"/",
">",
"Step",
"2",
"-",
"If",
"I",
"can",
"t",
"process",
"pass",
"to",
"all",
"children",
"(",
"with",
"me",
"as",
"the",
"source",
")",
".",
"<br",
"/",
">",
"Step",
"3",
"-",
"If",
"children",
"didn",
"t",
"process",
"pass",
"to",
"parent",
"(",
"with",
"me",
"as",
"the",
"source",
")",
".",
"<br",
"/",
">",
"Note",
":",
"Never",
"pass",
"to",
"a",
"parent",
"or",
"child",
"that",
"matches",
"the",
"source",
"(",
"to",
"avoid",
"an",
"endless",
"loop",
")",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/app/program/screen/src/main/java/org/jbundle/app/program/screen/LayoutGridScreen.java#L122-L133 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java | ComputeNodeOperations.updateComputeNodeUser | public void updateComputeNodeUser(String poolId, String nodeId, String userName, String password, DateTime expiryTime) throws BatchErrorException, IOException {
"""
Updates the specified user account on the specified compute node.
@param poolId The ID of the pool that contains the compute node.
@param nodeId The ID of the compute node where the user account will be updated.
@param userName The name of the user account to update.
@param password The password of the account. If null, the password is removed.
@param expiryTime The time at which the account should expire. If null, the expiry time is replaced with its default value.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
"""
updateComputeNodeUser(poolId, nodeId, userName, password, expiryTime, null);
} | java | public void updateComputeNodeUser(String poolId, String nodeId, String userName, String password, DateTime expiryTime) throws BatchErrorException, IOException {
updateComputeNodeUser(poolId, nodeId, userName, password, expiryTime, null);
} | [
"public",
"void",
"updateComputeNodeUser",
"(",
"String",
"poolId",
",",
"String",
"nodeId",
",",
"String",
"userName",
",",
"String",
"password",
",",
"DateTime",
"expiryTime",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"updateComputeNodeUser",
"(",
"poolId",
",",
"nodeId",
",",
"userName",
",",
"password",
",",
"expiryTime",
",",
"null",
")",
";",
"}"
] | Updates the specified user account on the specified compute node.
@param poolId The ID of the pool that contains the compute node.
@param nodeId The ID of the compute node where the user account will be updated.
@param userName The name of the user account to update.
@param password The password of the account. If null, the password is removed.
@param expiryTime The time at which the account should expire. If null, the expiry time is replaced with its default value.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. | [
"Updates",
"the",
"specified",
"user",
"account",
"on",
"the",
"specified",
"compute",
"node",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java#L146-L148 |
elki-project/elki | elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/ALOCI.java | ALOCI.calculate_MDEF_norm | private static double calculate_MDEF_norm(Node sn, Node cg) {
"""
Method for the MDEF calculation
@param sn Sampling Neighborhood
@param cg Counting Neighborhood
@return MDEF norm
"""
// get the square sum of the counting neighborhoods box counts
long sq = sn.getSquareSum(cg.getLevel() - sn.getLevel());
/*
* if the square sum is equal to box count of the sampling Neighborhood then
* n_hat is equal one, and as cg needs to have at least one Element mdef
* would get zero or lower than zero. This is the case when all of the
* counting Neighborhoods contain one or zero Objects. Additionally, the
* cubic sum, square sum and sampling Neighborhood box count are all equal,
* which leads to sig_n_hat being zero and thus mdef_norm is either negative
* infinite or undefined. As the distribution of the Objects seem quite
* uniform, a mdef_norm value of zero ( = no outlier) is appropriate and
* circumvents the problem of undefined values.
*/
if(sq == sn.getCount()) {
return 0.0;
}
// calculation of mdef according to the paper and standardization as done in
// LOCI
long cb = sn.getCubicSum(cg.getLevel() - sn.getLevel());
double n_hat = (double) sq / sn.getCount();
double sig_n_hat = FastMath.sqrt(cb * sn.getCount() - (sq * sq)) / sn.getCount();
// Avoid NaN - correct result 0.0?
if(sig_n_hat < Double.MIN_NORMAL) {
return 0.0;
}
double mdef = n_hat - cg.getCount();
return mdef / sig_n_hat;
} | java | private static double calculate_MDEF_norm(Node sn, Node cg) {
// get the square sum of the counting neighborhoods box counts
long sq = sn.getSquareSum(cg.getLevel() - sn.getLevel());
/*
* if the square sum is equal to box count of the sampling Neighborhood then
* n_hat is equal one, and as cg needs to have at least one Element mdef
* would get zero or lower than zero. This is the case when all of the
* counting Neighborhoods contain one or zero Objects. Additionally, the
* cubic sum, square sum and sampling Neighborhood box count are all equal,
* which leads to sig_n_hat being zero and thus mdef_norm is either negative
* infinite or undefined. As the distribution of the Objects seem quite
* uniform, a mdef_norm value of zero ( = no outlier) is appropriate and
* circumvents the problem of undefined values.
*/
if(sq == sn.getCount()) {
return 0.0;
}
// calculation of mdef according to the paper and standardization as done in
// LOCI
long cb = sn.getCubicSum(cg.getLevel() - sn.getLevel());
double n_hat = (double) sq / sn.getCount();
double sig_n_hat = FastMath.sqrt(cb * sn.getCount() - (sq * sq)) / sn.getCount();
// Avoid NaN - correct result 0.0?
if(sig_n_hat < Double.MIN_NORMAL) {
return 0.0;
}
double mdef = n_hat - cg.getCount();
return mdef / sig_n_hat;
} | [
"private",
"static",
"double",
"calculate_MDEF_norm",
"(",
"Node",
"sn",
",",
"Node",
"cg",
")",
"{",
"// get the square sum of the counting neighborhoods box counts",
"long",
"sq",
"=",
"sn",
".",
"getSquareSum",
"(",
"cg",
".",
"getLevel",
"(",
")",
"-",
"sn",
".",
"getLevel",
"(",
")",
")",
";",
"/*\n * if the square sum is equal to box count of the sampling Neighborhood then\n * n_hat is equal one, and as cg needs to have at least one Element mdef\n * would get zero or lower than zero. This is the case when all of the\n * counting Neighborhoods contain one or zero Objects. Additionally, the\n * cubic sum, square sum and sampling Neighborhood box count are all equal,\n * which leads to sig_n_hat being zero and thus mdef_norm is either negative\n * infinite or undefined. As the distribution of the Objects seem quite\n * uniform, a mdef_norm value of zero ( = no outlier) is appropriate and\n * circumvents the problem of undefined values.\n */",
"if",
"(",
"sq",
"==",
"sn",
".",
"getCount",
"(",
")",
")",
"{",
"return",
"0.0",
";",
"}",
"// calculation of mdef according to the paper and standardization as done in",
"// LOCI",
"long",
"cb",
"=",
"sn",
".",
"getCubicSum",
"(",
"cg",
".",
"getLevel",
"(",
")",
"-",
"sn",
".",
"getLevel",
"(",
")",
")",
";",
"double",
"n_hat",
"=",
"(",
"double",
")",
"sq",
"/",
"sn",
".",
"getCount",
"(",
")",
";",
"double",
"sig_n_hat",
"=",
"FastMath",
".",
"sqrt",
"(",
"cb",
"*",
"sn",
".",
"getCount",
"(",
")",
"-",
"(",
"sq",
"*",
"sq",
")",
")",
"/",
"sn",
".",
"getCount",
"(",
")",
";",
"// Avoid NaN - correct result 0.0?",
"if",
"(",
"sig_n_hat",
"<",
"Double",
".",
"MIN_NORMAL",
")",
"{",
"return",
"0.0",
";",
"}",
"double",
"mdef",
"=",
"n_hat",
"-",
"cg",
".",
"getCount",
"(",
")",
";",
"return",
"mdef",
"/",
"sig_n_hat",
";",
"}"
] | Method for the MDEF calculation
@param sn Sampling Neighborhood
@param cg Counting Neighborhood
@return MDEF norm | [
"Method",
"for",
"the",
"MDEF",
"calculation"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/ALOCI.java#L259-L287 |
windup/windup | forks/jdt/src/main/java/org/eclipse/jdt/internal/compiler/Compiler.java | Compiler.accept | @Override
public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) {
"""
Add an additional compilation unit into the loop
-> build compilation unit declarations, their bindings and record their results.
"""
// Switch the current policy and compilation result for this unit to the requested one.
CompilationResult unitResult =
new CompilationResult(sourceUnit, this.totalUnits, this.totalUnits, this.options.maxProblemsPerUnit);
unitResult.checkSecondaryTypes = true;
try {
if (this.options.verbose) {
String count = String.valueOf(this.totalUnits + 1);
this.out.println(
Messages.bind(Messages.compilation_request,
new String[] {
count,
count,
new String(sourceUnit.getFileName())
}));
}
// diet parsing for large collection of unit
CompilationUnitDeclaration parsedUnit;
if (this.totalUnits < this.parseThreshold) {
parsedUnit = this.parser.parse(sourceUnit, unitResult);
} else {
parsedUnit = this.parser.dietParse(sourceUnit, unitResult);
}
// initial type binding creation
this.lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);
addCompilationUnit(sourceUnit, parsedUnit);
// binding resolution
this.lookupEnvironment.completeTypeBindings(parsedUnit);
} catch (AbortCompilationUnit e) {
// at this point, currentCompilationUnitResult may not be sourceUnit, but some other
// one requested further along to resolve sourceUnit.
if (unitResult.compilationUnit == sourceUnit) { // only report once
this.requestor.acceptResult(unitResult.tagAsAccepted());
} else {
throw e; // want to abort enclosing request to compile
}
}
} | java | @Override
public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) {
// Switch the current policy and compilation result for this unit to the requested one.
CompilationResult unitResult =
new CompilationResult(sourceUnit, this.totalUnits, this.totalUnits, this.options.maxProblemsPerUnit);
unitResult.checkSecondaryTypes = true;
try {
if (this.options.verbose) {
String count = String.valueOf(this.totalUnits + 1);
this.out.println(
Messages.bind(Messages.compilation_request,
new String[] {
count,
count,
new String(sourceUnit.getFileName())
}));
}
// diet parsing for large collection of unit
CompilationUnitDeclaration parsedUnit;
if (this.totalUnits < this.parseThreshold) {
parsedUnit = this.parser.parse(sourceUnit, unitResult);
} else {
parsedUnit = this.parser.dietParse(sourceUnit, unitResult);
}
// initial type binding creation
this.lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);
addCompilationUnit(sourceUnit, parsedUnit);
// binding resolution
this.lookupEnvironment.completeTypeBindings(parsedUnit);
} catch (AbortCompilationUnit e) {
// at this point, currentCompilationUnitResult may not be sourceUnit, but some other
// one requested further along to resolve sourceUnit.
if (unitResult.compilationUnit == sourceUnit) { // only report once
this.requestor.acceptResult(unitResult.tagAsAccepted());
} else {
throw e; // want to abort enclosing request to compile
}
}
} | [
"@",
"Override",
"public",
"void",
"accept",
"(",
"ICompilationUnit",
"sourceUnit",
",",
"AccessRestriction",
"accessRestriction",
")",
"{",
"// Switch the current policy and compilation result for this unit to the requested one.",
"CompilationResult",
"unitResult",
"=",
"new",
"CompilationResult",
"(",
"sourceUnit",
",",
"this",
".",
"totalUnits",
",",
"this",
".",
"totalUnits",
",",
"this",
".",
"options",
".",
"maxProblemsPerUnit",
")",
";",
"unitResult",
".",
"checkSecondaryTypes",
"=",
"true",
";",
"try",
"{",
"if",
"(",
"this",
".",
"options",
".",
"verbose",
")",
"{",
"String",
"count",
"=",
"String",
".",
"valueOf",
"(",
"this",
".",
"totalUnits",
"+",
"1",
")",
";",
"this",
".",
"out",
".",
"println",
"(",
"Messages",
".",
"bind",
"(",
"Messages",
".",
"compilation_request",
",",
"new",
"String",
"[",
"]",
"{",
"count",
",",
"count",
",",
"new",
"String",
"(",
"sourceUnit",
".",
"getFileName",
"(",
")",
")",
"}",
")",
")",
";",
"}",
"// diet parsing for large collection of unit",
"CompilationUnitDeclaration",
"parsedUnit",
";",
"if",
"(",
"this",
".",
"totalUnits",
"<",
"this",
".",
"parseThreshold",
")",
"{",
"parsedUnit",
"=",
"this",
".",
"parser",
".",
"parse",
"(",
"sourceUnit",
",",
"unitResult",
")",
";",
"}",
"else",
"{",
"parsedUnit",
"=",
"this",
".",
"parser",
".",
"dietParse",
"(",
"sourceUnit",
",",
"unitResult",
")",
";",
"}",
"// initial type binding creation",
"this",
".",
"lookupEnvironment",
".",
"buildTypeBindings",
"(",
"parsedUnit",
",",
"accessRestriction",
")",
";",
"addCompilationUnit",
"(",
"sourceUnit",
",",
"parsedUnit",
")",
";",
"// binding resolution",
"this",
".",
"lookupEnvironment",
".",
"completeTypeBindings",
"(",
"parsedUnit",
")",
";",
"}",
"catch",
"(",
"AbortCompilationUnit",
"e",
")",
"{",
"// at this point, currentCompilationUnitResult may not be sourceUnit, but some other",
"// one requested further along to resolve sourceUnit.",
"if",
"(",
"unitResult",
".",
"compilationUnit",
"==",
"sourceUnit",
")",
"{",
"// only report once",
"this",
".",
"requestor",
".",
"acceptResult",
"(",
"unitResult",
".",
"tagAsAccepted",
"(",
")",
")",
";",
"}",
"else",
"{",
"throw",
"e",
";",
"// want to abort enclosing request to compile",
"}",
"}",
"}"
] | Add an additional compilation unit into the loop
-> build compilation unit declarations, their bindings and record their results. | [
"Add",
"an",
"additional",
"compilation",
"unit",
"into",
"the",
"loop",
"-",
">",
"build",
"compilation",
"unit",
"declarations",
"their",
"bindings",
"and",
"record",
"their",
"results",
"."
] | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/forks/jdt/src/main/java/org/eclipse/jdt/internal/compiler/Compiler.java#L329-L368 |
structlogging/structlogger | structlogger/src/main/java/com/github/structlogging/processor/LogInvocationScanner.java | LogInvocationScanner.formatWithStatementLocation | private String formatWithStatementLocation(String format, StatementInfo statementInfo, Object... args) {
"""
System.format with string representing statement location added at the end
"""
return format(format, args) + format(" [%s:%s]", statementInfo.getSourceFileName(), statementInfo.getLineNumber());
} | java | private String formatWithStatementLocation(String format, StatementInfo statementInfo, Object... args) {
return format(format, args) + format(" [%s:%s]", statementInfo.getSourceFileName(), statementInfo.getLineNumber());
} | [
"private",
"String",
"formatWithStatementLocation",
"(",
"String",
"format",
",",
"StatementInfo",
"statementInfo",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"format",
"(",
"format",
",",
"args",
")",
"+",
"format",
"(",
"\" [%s:%s]\"",
",",
"statementInfo",
".",
"getSourceFileName",
"(",
")",
",",
"statementInfo",
".",
"getLineNumber",
"(",
")",
")",
";",
"}"
] | System.format with string representing statement location added at the end | [
"System",
".",
"format",
"with",
"string",
"representing",
"statement",
"location",
"added",
"at",
"the",
"end"
] | train | https://github.com/structlogging/structlogger/blob/1fcca4e962ef53cbdb94bd72cb556de7f5f9469f/structlogger/src/main/java/com/github/structlogging/processor/LogInvocationScanner.java#L357-L359 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/api/API.java | API.getOneTimeNonce | public String getOneTimeNonce(String apiUrl) {
"""
Returns a one time nonce to be used with the API call specified by the URL
@param apiUrl the API URL
@return a one time nonce
@since 2.6.0
"""
String nonce = Long.toHexString(random.nextLong());
this.nonces.put(nonce, new Nonce(nonce, apiUrl, true));
return nonce;
} | java | public String getOneTimeNonce(String apiUrl) {
String nonce = Long.toHexString(random.nextLong());
this.nonces.put(nonce, new Nonce(nonce, apiUrl, true));
return nonce;
} | [
"public",
"String",
"getOneTimeNonce",
"(",
"String",
"apiUrl",
")",
"{",
"String",
"nonce",
"=",
"Long",
".",
"toHexString",
"(",
"random",
".",
"nextLong",
"(",
")",
")",
";",
"this",
".",
"nonces",
".",
"put",
"(",
"nonce",
",",
"new",
"Nonce",
"(",
"nonce",
",",
"apiUrl",
",",
"true",
")",
")",
";",
"return",
"nonce",
";",
"}"
] | Returns a one time nonce to be used with the API call specified by the URL
@param apiUrl the API URL
@return a one time nonce
@since 2.6.0 | [
"Returns",
"a",
"one",
"time",
"nonce",
"to",
"be",
"used",
"with",
"the",
"API",
"call",
"specified",
"by",
"the",
"URL"
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/api/API.java#L829-L833 |
looly/hutool | hutool-extra/src/main/java/cn/hutool/extra/servlet/ServletUtil.java | ServletUtil.getCookie | public final static Cookie getCookie(HttpServletRequest httpServletRequest, String name) {
"""
获得指定的Cookie
@param httpServletRequest {@link HttpServletRequest}
@param name cookie名
@return Cookie对象
"""
final Map<String, Cookie> cookieMap = readCookieMap(httpServletRequest);
return cookieMap == null ? null : cookieMap.get(name);
} | java | public final static Cookie getCookie(HttpServletRequest httpServletRequest, String name) {
final Map<String, Cookie> cookieMap = readCookieMap(httpServletRequest);
return cookieMap == null ? null : cookieMap.get(name);
} | [
"public",
"final",
"static",
"Cookie",
"getCookie",
"(",
"HttpServletRequest",
"httpServletRequest",
",",
"String",
"name",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"Cookie",
">",
"cookieMap",
"=",
"readCookieMap",
"(",
"httpServletRequest",
")",
";",
"return",
"cookieMap",
"==",
"null",
"?",
"null",
":",
"cookieMap",
".",
"get",
"(",
"name",
")",
";",
"}"
] | 获得指定的Cookie
@param httpServletRequest {@link HttpServletRequest}
@param name cookie名
@return Cookie对象 | [
"获得指定的Cookie"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/servlet/ServletUtil.java#L378-L381 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/SAXBugCollectionHandler.java | SAXBugCollectionHandler.setAnnotationRole | private void setAnnotationRole(Attributes attributes, BugAnnotation bugAnnotation) {
"""
/*
Extract a hash value from an element.
@param qName
name of element containing hash value
@param attributes
element attributes
@return the decoded hash value
@throws SAXException
private byte[] extractHash(String qName, Attributes attributes) throws SAXException {
String encodedHash = getRequiredAttribute(attributes, "value", qName);
byte[] hash;
try {
System.out.println("Extract hash " + encodedHash);
hash = ClassHash.stringToHash(encodedHash);
} catch (IllegalArgumentException e) {
throw new SAXException("Invalid class hash", e);
}
return hash;
}
"""
String role = getOptionalAttribute(attributes, "role");
if (role != null) {
bugAnnotation.setDescription(role);
}
} | java | private void setAnnotationRole(Attributes attributes, BugAnnotation bugAnnotation) {
String role = getOptionalAttribute(attributes, "role");
if (role != null) {
bugAnnotation.setDescription(role);
}
} | [
"private",
"void",
"setAnnotationRole",
"(",
"Attributes",
"attributes",
",",
"BugAnnotation",
"bugAnnotation",
")",
"{",
"String",
"role",
"=",
"getOptionalAttribute",
"(",
"attributes",
",",
"\"role\"",
")",
";",
"if",
"(",
"role",
"!=",
"null",
")",
"{",
"bugAnnotation",
".",
"setDescription",
"(",
"role",
")",
";",
"}",
"}"
] | /*
Extract a hash value from an element.
@param qName
name of element containing hash value
@param attributes
element attributes
@return the decoded hash value
@throws SAXException
private byte[] extractHash(String qName, Attributes attributes) throws SAXException {
String encodedHash = getRequiredAttribute(attributes, "value", qName);
byte[] hash;
try {
System.out.println("Extract hash " + encodedHash);
hash = ClassHash.stringToHash(encodedHash);
} catch (IllegalArgumentException e) {
throw new SAXException("Invalid class hash", e);
}
return hash;
} | [
"/",
"*",
"Extract",
"a",
"hash",
"value",
"from",
"an",
"element",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/SAXBugCollectionHandler.java#L617-L622 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BiologicalAssemblyBuilder.java | BiologicalAssemblyBuilder.addChainFlattened | private void addChainFlattened(Structure s, Chain newChain, String transformId) {
"""
Adds a chain to the given structure to form a biological assembly,
adding the symmetry-expanded chains as new chains with renamed
chain ids and names (in the form originalAsymId_transformId and originalAuthId_transformId).
@param s
@param newChain
@param transformId
"""
newChain.setId(newChain.getId()+SYM_CHAIN_ID_SEPARATOR+transformId);
newChain.setName(newChain.getName()+SYM_CHAIN_ID_SEPARATOR+transformId);
s.addChain(newChain);
} | java | private void addChainFlattened(Structure s, Chain newChain, String transformId) {
newChain.setId(newChain.getId()+SYM_CHAIN_ID_SEPARATOR+transformId);
newChain.setName(newChain.getName()+SYM_CHAIN_ID_SEPARATOR+transformId);
s.addChain(newChain);
} | [
"private",
"void",
"addChainFlattened",
"(",
"Structure",
"s",
",",
"Chain",
"newChain",
",",
"String",
"transformId",
")",
"{",
"newChain",
".",
"setId",
"(",
"newChain",
".",
"getId",
"(",
")",
"+",
"SYM_CHAIN_ID_SEPARATOR",
"+",
"transformId",
")",
";",
"newChain",
".",
"setName",
"(",
"newChain",
".",
"getName",
"(",
")",
"+",
"SYM_CHAIN_ID_SEPARATOR",
"+",
"transformId",
")",
";",
"s",
".",
"addChain",
"(",
"newChain",
")",
";",
"}"
] | Adds a chain to the given structure to form a biological assembly,
adding the symmetry-expanded chains as new chains with renamed
chain ids and names (in the form originalAsymId_transformId and originalAuthId_transformId).
@param s
@param newChain
@param transformId | [
"Adds",
"a",
"chain",
"to",
"the",
"given",
"structure",
"to",
"form",
"a",
"biological",
"assembly",
"adding",
"the",
"symmetry",
"-",
"expanded",
"chains",
"as",
"new",
"chains",
"with",
"renamed",
"chain",
"ids",
"and",
"names",
"(",
"in",
"the",
"form",
"originalAsymId_transformId",
"and",
"originalAuthId_transformId",
")",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BiologicalAssemblyBuilder.java#L235-L239 |
mike10004/common-helper | imnetio-helper/src/main/java/com/github/mike10004/common/image/ImageInfos.java | ImageInfos.readImageSize | public static Dimension readImageSize(byte[] bytes) {
"""
Reads the image size from a byte array containing image data. This
first attempts to use {@link ImageInfo} to read just the header data,
but if that fails the whole image is buffered into memory with
{@link ImageIO#read(java.io.InputStream) }. In any case, this method
never throws an exception; instead, if the image data is unreadable,
it returns a dimension object with zero width and height.
<p>In common deployments, the fallback of loading the image into
memory probably never works, because {@code ImageInfo}'s support is
a superset of JDK image format support. But some installations may
have extra codecs installed, and it's nice to make use of those if
they're there.
@param bytes the image data bytes
@return the image dimensions
"""
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ImageInfo ii = new ImageInfo();
ii.setInput(in);
if (ii.check()) {
return new Dimension(ii.getWidth(), ii.getHeight());
} else {
in.reset();
BufferedImage image;
try {
image = ImageIO.read(in);
if (image == null) {
throw new IOException("failed to read image; format is probably not supported");
}
return new Dimension(image.getWidth(), image.getHeight());
} catch (IOException ex) {
Integer m1 = bytes.length > 0 ? Integer.valueOf(bytes[0]) : null;
Integer m2 = bytes.length > 1 ? Integer.valueOf(bytes[1]) : null;
Logger.getLogger(ImageInfos.class.getName())
.log(Level.FINER, "reading image failed on array of "
+ "length {0} with magic number {1} {2}: {3}",
new Object[]{bytes.length, m1, m2, ex});
return new Dimension(0, 0);
}
}
} | java | public static Dimension readImageSize(byte[] bytes) {
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ImageInfo ii = new ImageInfo();
ii.setInput(in);
if (ii.check()) {
return new Dimension(ii.getWidth(), ii.getHeight());
} else {
in.reset();
BufferedImage image;
try {
image = ImageIO.read(in);
if (image == null) {
throw new IOException("failed to read image; format is probably not supported");
}
return new Dimension(image.getWidth(), image.getHeight());
} catch (IOException ex) {
Integer m1 = bytes.length > 0 ? Integer.valueOf(bytes[0]) : null;
Integer m2 = bytes.length > 1 ? Integer.valueOf(bytes[1]) : null;
Logger.getLogger(ImageInfos.class.getName())
.log(Level.FINER, "reading image failed on array of "
+ "length {0} with magic number {1} {2}: {3}",
new Object[]{bytes.length, m1, m2, ex});
return new Dimension(0, 0);
}
}
} | [
"public",
"static",
"Dimension",
"readImageSize",
"(",
"byte",
"[",
"]",
"bytes",
")",
"{",
"ByteArrayInputStream",
"in",
"=",
"new",
"ByteArrayInputStream",
"(",
"bytes",
")",
";",
"ImageInfo",
"ii",
"=",
"new",
"ImageInfo",
"(",
")",
";",
"ii",
".",
"setInput",
"(",
"in",
")",
";",
"if",
"(",
"ii",
".",
"check",
"(",
")",
")",
"{",
"return",
"new",
"Dimension",
"(",
"ii",
".",
"getWidth",
"(",
")",
",",
"ii",
".",
"getHeight",
"(",
")",
")",
";",
"}",
"else",
"{",
"in",
".",
"reset",
"(",
")",
";",
"BufferedImage",
"image",
";",
"try",
"{",
"image",
"=",
"ImageIO",
".",
"read",
"(",
"in",
")",
";",
"if",
"(",
"image",
"==",
"null",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"failed to read image; format is probably not supported\"",
")",
";",
"}",
"return",
"new",
"Dimension",
"(",
"image",
".",
"getWidth",
"(",
")",
",",
"image",
".",
"getHeight",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"Integer",
"m1",
"=",
"bytes",
".",
"length",
">",
"0",
"?",
"Integer",
".",
"valueOf",
"(",
"bytes",
"[",
"0",
"]",
")",
":",
"null",
";",
"Integer",
"m2",
"=",
"bytes",
".",
"length",
">",
"1",
"?",
"Integer",
".",
"valueOf",
"(",
"bytes",
"[",
"1",
"]",
")",
":",
"null",
";",
"Logger",
".",
"getLogger",
"(",
"ImageInfos",
".",
"class",
".",
"getName",
"(",
")",
")",
".",
"log",
"(",
"Level",
".",
"FINER",
",",
"\"reading image failed on array of \"",
"+",
"\"length {0} with magic number {1} {2}: {3}\"",
",",
"new",
"Object",
"[",
"]",
"{",
"bytes",
".",
"length",
",",
"m1",
",",
"m2",
",",
"ex",
"}",
")",
";",
"return",
"new",
"Dimension",
"(",
"0",
",",
"0",
")",
";",
"}",
"}",
"}"
] | Reads the image size from a byte array containing image data. This
first attempts to use {@link ImageInfo} to read just the header data,
but if that fails the whole image is buffered into memory with
{@link ImageIO#read(java.io.InputStream) }. In any case, this method
never throws an exception; instead, if the image data is unreadable,
it returns a dimension object with zero width and height.
<p>In common deployments, the fallback of loading the image into
memory probably never works, because {@code ImageInfo}'s support is
a superset of JDK image format support. But some installations may
have extra codecs installed, and it's nice to make use of those if
they're there.
@param bytes the image data bytes
@return the image dimensions | [
"Reads",
"the",
"image",
"size",
"from",
"a",
"byte",
"array",
"containing",
"image",
"data",
".",
"This",
"first",
"attempts",
"to",
"use",
"{",
"@link",
"ImageInfo",
"}",
"to",
"read",
"just",
"the",
"header",
"data",
"but",
"if",
"that",
"fails",
"the",
"whole",
"image",
"is",
"buffered",
"into",
"memory",
"with",
"{",
"@link",
"ImageIO#read",
"(",
"java",
".",
"io",
".",
"InputStream",
")",
"}",
".",
"In",
"any",
"case",
"this",
"method",
"never",
"throws",
"an",
"exception",
";",
"instead",
"if",
"the",
"image",
"data",
"is",
"unreadable",
"it",
"returns",
"a",
"dimension",
"object",
"with",
"zero",
"width",
"and",
"height",
"."
] | train | https://github.com/mike10004/common-helper/blob/744f82d9b0768a9ad9c63a57a37ab2c93bf408f4/imnetio-helper/src/main/java/com/github/mike10004/common/image/ImageInfos.java#L38-L63 |
teatrove/teatrove | tea/src/main/java/org/teatrove/tea/compiler/Compiler.java | Compiler.determineQualifiedName | private String determineQualifiedName(String name, CompilationUnit from) {
"""
Given a name, as requested by the given CompilationUnit, return a
fully qualified name or null if the name could not be found.
@param name requested name
@param from optional CompilationUnit
"""
if (from != null) {
// Determine qualified name as being relative to "from"
String fromName = from.getName();
int index = fromName.lastIndexOf('.');
if (index >= 0) {
String qual = fromName.substring(0, index + 1) + name;
if (sourceExists(qual)) {
return qual;
}
}
}
if (sourceExists(name)) {
return name;
}
return null;
} | java | private String determineQualifiedName(String name, CompilationUnit from) {
if (from != null) {
// Determine qualified name as being relative to "from"
String fromName = from.getName();
int index = fromName.lastIndexOf('.');
if (index >= 0) {
String qual = fromName.substring(0, index + 1) + name;
if (sourceExists(qual)) {
return qual;
}
}
}
if (sourceExists(name)) {
return name;
}
return null;
} | [
"private",
"String",
"determineQualifiedName",
"(",
"String",
"name",
",",
"CompilationUnit",
"from",
")",
"{",
"if",
"(",
"from",
"!=",
"null",
")",
"{",
"// Determine qualified name as being relative to \"from\"",
"String",
"fromName",
"=",
"from",
".",
"getName",
"(",
")",
";",
"int",
"index",
"=",
"fromName",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"index",
">=",
"0",
")",
"{",
"String",
"qual",
"=",
"fromName",
".",
"substring",
"(",
"0",
",",
"index",
"+",
"1",
")",
"+",
"name",
";",
"if",
"(",
"sourceExists",
"(",
"qual",
")",
")",
"{",
"return",
"qual",
";",
"}",
"}",
"}",
"if",
"(",
"sourceExists",
"(",
"name",
")",
")",
"{",
"return",
"name",
";",
"}",
"return",
"null",
";",
"}"
] | Given a name, as requested by the given CompilationUnit, return a
fully qualified name or null if the name could not be found.
@param name requested name
@param from optional CompilationUnit | [
"Given",
"a",
"name",
"as",
"requested",
"by",
"the",
"given",
"CompilationUnit",
"return",
"a",
"fully",
"qualified",
"name",
"or",
"null",
"if",
"the",
"name",
"could",
"not",
"be",
"found",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/tea/src/main/java/org/teatrove/tea/compiler/Compiler.java#L793-L812 |
prestodb/presto | presto-spi/src/main/java/com/facebook/presto/spi/type/UnscaledDecimal128Arithmetic.java | UnscaledDecimal128Arithmetic.addWithOverflow | public static long addWithOverflow(Slice left, Slice right, Slice result) {
"""
Instead of throwing overflow exception, this function returns:
0 when there was no overflow
+1 when there was overflow
-1 when there was underflow
"""
boolean leftNegative = isNegative(left);
boolean rightNegative = isNegative(right);
long overflow = 0;
if (leftNegative == rightNegative) {
// either both negative or both positive
overflow = addUnsignedReturnOverflow(left, right, result, leftNegative);
if (leftNegative) {
overflow = -overflow;
}
}
else {
int compare = compareAbsolute(left, right);
if (compare > 0) {
subtractUnsigned(left, right, result, leftNegative);
}
else if (compare < 0) {
subtractUnsigned(right, left, result, !leftNegative);
}
else {
setToZero(result);
}
}
return overflow;
} | java | public static long addWithOverflow(Slice left, Slice right, Slice result)
{
boolean leftNegative = isNegative(left);
boolean rightNegative = isNegative(right);
long overflow = 0;
if (leftNegative == rightNegative) {
// either both negative or both positive
overflow = addUnsignedReturnOverflow(left, right, result, leftNegative);
if (leftNegative) {
overflow = -overflow;
}
}
else {
int compare = compareAbsolute(left, right);
if (compare > 0) {
subtractUnsigned(left, right, result, leftNegative);
}
else if (compare < 0) {
subtractUnsigned(right, left, result, !leftNegative);
}
else {
setToZero(result);
}
}
return overflow;
} | [
"public",
"static",
"long",
"addWithOverflow",
"(",
"Slice",
"left",
",",
"Slice",
"right",
",",
"Slice",
"result",
")",
"{",
"boolean",
"leftNegative",
"=",
"isNegative",
"(",
"left",
")",
";",
"boolean",
"rightNegative",
"=",
"isNegative",
"(",
"right",
")",
";",
"long",
"overflow",
"=",
"0",
";",
"if",
"(",
"leftNegative",
"==",
"rightNegative",
")",
"{",
"// either both negative or both positive",
"overflow",
"=",
"addUnsignedReturnOverflow",
"(",
"left",
",",
"right",
",",
"result",
",",
"leftNegative",
")",
";",
"if",
"(",
"leftNegative",
")",
"{",
"overflow",
"=",
"-",
"overflow",
";",
"}",
"}",
"else",
"{",
"int",
"compare",
"=",
"compareAbsolute",
"(",
"left",
",",
"right",
")",
";",
"if",
"(",
"compare",
">",
"0",
")",
"{",
"subtractUnsigned",
"(",
"left",
",",
"right",
",",
"result",
",",
"leftNegative",
")",
";",
"}",
"else",
"if",
"(",
"compare",
"<",
"0",
")",
"{",
"subtractUnsigned",
"(",
"right",
",",
"left",
",",
"result",
",",
"!",
"leftNegative",
")",
";",
"}",
"else",
"{",
"setToZero",
"(",
"result",
")",
";",
"}",
"}",
"return",
"overflow",
";",
"}"
] | Instead of throwing overflow exception, this function returns:
0 when there was no overflow
+1 when there was overflow
-1 when there was underflow | [
"Instead",
"of",
"throwing",
"overflow",
"exception",
"this",
"function",
"returns",
":",
"0",
"when",
"there",
"was",
"no",
"overflow",
"+",
"1",
"when",
"there",
"was",
"overflow",
"-",
"1",
"when",
"there",
"was",
"underflow"
] | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-spi/src/main/java/com/facebook/presto/spi/type/UnscaledDecimal128Arithmetic.java#L312-L337 |
hawkular/hawkular-apm | client/opentracing/src/main/java/io/opentracing/impl/APMSpan.java | APMSpan.initChildOf | protected void initChildOf(APMSpanBuilder builder, Reference ref) {
"""
This method initialises the span based on a 'child-of' relationship.
@param builder The span builder
@param ref The 'child-of' relationship
"""
APMSpan parent = (APMSpan) ref.getReferredTo();
if (parent.getNodeBuilder() != null) {
nodeBuilder = new NodeBuilder(parent.getNodeBuilder());
traceContext = parent.traceContext;
// As it is not possible to know if a tag has been set after span
// creation, we use this situation to check if the parent span
// has the 'transaction.name' specified, to set on the trace
// context. This is required in case a child span is used to invoke
// another service (and needs to propagate the transaction
// name).
if (parent.getTags().containsKey(Constants.PROP_TRANSACTION_NAME)
&& traceContext.getTransaction() == null) {
traceContext.setTransaction(
parent.getTags().get(Constants.PROP_TRANSACTION_NAME).toString());
}
}
processRemainingReferences(builder, ref);
} | java | protected void initChildOf(APMSpanBuilder builder, Reference ref) {
APMSpan parent = (APMSpan) ref.getReferredTo();
if (parent.getNodeBuilder() != null) {
nodeBuilder = new NodeBuilder(parent.getNodeBuilder());
traceContext = parent.traceContext;
// As it is not possible to know if a tag has been set after span
// creation, we use this situation to check if the parent span
// has the 'transaction.name' specified, to set on the trace
// context. This is required in case a child span is used to invoke
// another service (and needs to propagate the transaction
// name).
if (parent.getTags().containsKey(Constants.PROP_TRANSACTION_NAME)
&& traceContext.getTransaction() == null) {
traceContext.setTransaction(
parent.getTags().get(Constants.PROP_TRANSACTION_NAME).toString());
}
}
processRemainingReferences(builder, ref);
} | [
"protected",
"void",
"initChildOf",
"(",
"APMSpanBuilder",
"builder",
",",
"Reference",
"ref",
")",
"{",
"APMSpan",
"parent",
"=",
"(",
"APMSpan",
")",
"ref",
".",
"getReferredTo",
"(",
")",
";",
"if",
"(",
"parent",
".",
"getNodeBuilder",
"(",
")",
"!=",
"null",
")",
"{",
"nodeBuilder",
"=",
"new",
"NodeBuilder",
"(",
"parent",
".",
"getNodeBuilder",
"(",
")",
")",
";",
"traceContext",
"=",
"parent",
".",
"traceContext",
";",
"// As it is not possible to know if a tag has been set after span",
"// creation, we use this situation to check if the parent span",
"// has the 'transaction.name' specified, to set on the trace",
"// context. This is required in case a child span is used to invoke",
"// another service (and needs to propagate the transaction",
"// name).",
"if",
"(",
"parent",
".",
"getTags",
"(",
")",
".",
"containsKey",
"(",
"Constants",
".",
"PROP_TRANSACTION_NAME",
")",
"&&",
"traceContext",
".",
"getTransaction",
"(",
")",
"==",
"null",
")",
"{",
"traceContext",
".",
"setTransaction",
"(",
"parent",
".",
"getTags",
"(",
")",
".",
"get",
"(",
"Constants",
".",
"PROP_TRANSACTION_NAME",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
"processRemainingReferences",
"(",
"builder",
",",
"ref",
")",
";",
"}"
] | This method initialises the span based on a 'child-of' relationship.
@param builder The span builder
@param ref The 'child-of' relationship | [
"This",
"method",
"initialises",
"the",
"span",
"based",
"on",
"a",
"child",
"-",
"of",
"relationship",
"."
] | train | https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/opentracing/src/main/java/io/opentracing/impl/APMSpan.java#L204-L225 |
stripe/stripe-android | stripe/src/main/java/com/stripe/android/model/AccountParams.java | AccountParams.createAccountParams | @NonNull
public static AccountParams createAccountParams(
boolean tosShownAndAccepted,
@NonNull BusinessType businessType,
@Nullable Map<String, Object> businessData) {
"""
Create an {@link AccountParams} instance for a {@link BusinessType#Individual} or
{@link BusinessType#Company}
Note: API version {@code 2019-02-19} [0] replaced {@code legal_entity} with
{@code individual} and {@code company}.
@param tosShownAndAccepted Whether the user described by the data in the token has been shown
the Stripe Connected Account Agreement [1]. When creating an
account token to create a new Connect account, this value must
be true.
@param businessType See {@link BusinessType}
@param businessData A map of company [2] or individual [3] params.
[0] <a href="https://stripe.com/docs/upgrades#2019-02-19">
https://stripe.com/docs/upgrades#2019-02-19</a>
[1] https://stripe.com/docs/api/tokens/create_account#create_account_token-account-tos_shown_and_accepted
[2] <a href="https://stripe.com/docs/api/accounts/create#create_account-company">
https://stripe.com/docs/api/accounts/create#create_account-company</a>
[3] <a href="https://stripe.com/docs/api/accounts/create#create_account-individual">
https://stripe.com/docs/api/accounts/create#create_account-individual</a>
@return {@link AccountParams}
"""
return new AccountParams(businessType, businessData, tosShownAndAccepted);
} | java | @NonNull
public static AccountParams createAccountParams(
boolean tosShownAndAccepted,
@NonNull BusinessType businessType,
@Nullable Map<String, Object> businessData) {
return new AccountParams(businessType, businessData, tosShownAndAccepted);
} | [
"@",
"NonNull",
"public",
"static",
"AccountParams",
"createAccountParams",
"(",
"boolean",
"tosShownAndAccepted",
",",
"@",
"NonNull",
"BusinessType",
"businessType",
",",
"@",
"Nullable",
"Map",
"<",
"String",
",",
"Object",
">",
"businessData",
")",
"{",
"return",
"new",
"AccountParams",
"(",
"businessType",
",",
"businessData",
",",
"tosShownAndAccepted",
")",
";",
"}"
] | Create an {@link AccountParams} instance for a {@link BusinessType#Individual} or
{@link BusinessType#Company}
Note: API version {@code 2019-02-19} [0] replaced {@code legal_entity} with
{@code individual} and {@code company}.
@param tosShownAndAccepted Whether the user described by the data in the token has been shown
the Stripe Connected Account Agreement [1]. When creating an
account token to create a new Connect account, this value must
be true.
@param businessType See {@link BusinessType}
@param businessData A map of company [2] or individual [3] params.
[0] <a href="https://stripe.com/docs/upgrades#2019-02-19">
https://stripe.com/docs/upgrades#2019-02-19</a>
[1] https://stripe.com/docs/api/tokens/create_account#create_account_token-account-tos_shown_and_accepted
[2] <a href="https://stripe.com/docs/api/accounts/create#create_account-company">
https://stripe.com/docs/api/accounts/create#create_account-company</a>
[3] <a href="https://stripe.com/docs/api/accounts/create#create_account-individual">
https://stripe.com/docs/api/accounts/create#create_account-individual</a>
@return {@link AccountParams} | [
"Create",
"an",
"{",
"@link",
"AccountParams",
"}",
"instance",
"for",
"a",
"{",
"@link",
"BusinessType#Individual",
"}",
"or",
"{",
"@link",
"BusinessType#Company",
"}"
] | train | https://github.com/stripe/stripe-android/blob/0f199255f3769a3b84583fe3ace47bfae8c3b1c8/stripe/src/main/java/com/stripe/android/model/AccountParams.java#L49-L55 |
mygreen/xlsmapper | src/main/java/com/gh/mygreen/xlsmapper/fieldprocessor/RecordMethodFacatory.java | RecordMethodFacatory.create | public RecordMethodCache create(final Class<?> recordClass, final ProcessCase processCase) {
"""
レコードクラスを元に、{@link RecordMethodCache}のインスタンスを組み立てる。
@param recordClass レコードクラス
@param processCase 現在の処理ケース
@return {@link RecordMethodCache}のインスタンス
@throws IllegalArgumentException {@literal recordClass == null}
"""
ArgUtils.notNull(recordClass, "recordClass");
final RecordMethodCache recordMethod = new RecordMethodCache();
setupIgnoreableMethod(recordMethod, recordClass, processCase);
setupListenerCallbackMethods(recordMethod, recordClass);
setupRecordCallbackMethods(recordMethod, recordClass);
return recordMethod;
} | java | public RecordMethodCache create(final Class<?> recordClass, final ProcessCase processCase) {
ArgUtils.notNull(recordClass, "recordClass");
final RecordMethodCache recordMethod = new RecordMethodCache();
setupIgnoreableMethod(recordMethod, recordClass, processCase);
setupListenerCallbackMethods(recordMethod, recordClass);
setupRecordCallbackMethods(recordMethod, recordClass);
return recordMethod;
} | [
"public",
"RecordMethodCache",
"create",
"(",
"final",
"Class",
"<",
"?",
">",
"recordClass",
",",
"final",
"ProcessCase",
"processCase",
")",
"{",
"ArgUtils",
".",
"notNull",
"(",
"recordClass",
",",
"\"recordClass\"",
")",
";",
"final",
"RecordMethodCache",
"recordMethod",
"=",
"new",
"RecordMethodCache",
"(",
")",
";",
"setupIgnoreableMethod",
"(",
"recordMethod",
",",
"recordClass",
",",
"processCase",
")",
";",
"setupListenerCallbackMethods",
"(",
"recordMethod",
",",
"recordClass",
")",
";",
"setupRecordCallbackMethods",
"(",
"recordMethod",
",",
"recordClass",
")",
";",
"return",
"recordMethod",
";",
"}"
] | レコードクラスを元に、{@link RecordMethodCache}のインスタンスを組み立てる。
@param recordClass レコードクラス
@param processCase 現在の処理ケース
@return {@link RecordMethodCache}のインスタンス
@throws IllegalArgumentException {@literal recordClass == null} | [
"レコードクラスを元に、",
"{",
"@link",
"RecordMethodCache",
"}",
"のインスタンスを組み立てる。"
] | train | https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/fieldprocessor/RecordMethodFacatory.java#L52-L63 |
liferay/com-liferay-commerce | commerce-user-segment-api/src/main/java/com/liferay/commerce/user/segment/model/CommerceUserSegmentEntryWrapper.java | CommerceUserSegmentEntryWrapper.getName | @Override
public String getName(String languageId, boolean useDefault) {
"""
Returns the localized name of this commerce user segment entry in the language, optionally using the default language if no localization exists for the requested language.
@param languageId the ID of the language
@param useDefault whether to use the default language if no localization exists for the requested language
@return the localized name of this commerce user segment entry
"""
return _commerceUserSegmentEntry.getName(languageId, useDefault);
} | java | @Override
public String getName(String languageId, boolean useDefault) {
return _commerceUserSegmentEntry.getName(languageId, useDefault);
} | [
"@",
"Override",
"public",
"String",
"getName",
"(",
"String",
"languageId",
",",
"boolean",
"useDefault",
")",
"{",
"return",
"_commerceUserSegmentEntry",
".",
"getName",
"(",
"languageId",
",",
"useDefault",
")",
";",
"}"
] | Returns the localized name of this commerce user segment entry in the language, optionally using the default language if no localization exists for the requested language.
@param languageId the ID of the language
@param useDefault whether to use the default language if no localization exists for the requested language
@return the localized name of this commerce user segment entry | [
"Returns",
"the",
"localized",
"name",
"of",
"this",
"commerce",
"user",
"segment",
"entry",
"in",
"the",
"language",
"optionally",
"using",
"the",
"default",
"language",
"if",
"no",
"localization",
"exists",
"for",
"the",
"requested",
"language",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-user-segment-api/src/main/java/com/liferay/commerce/user/segment/model/CommerceUserSegmentEntryWrapper.java#L306-L309 |
susom/database | src/main/java/com/github/susom/database/DatabaseProvider.java | DatabaseProvider.fromPropertyFileOrSystemProperties | public static Builder fromPropertyFileOrSystemProperties(String filename, String propertyPrefix) {
"""
Configure the database from up to five properties read from the specified
properties file, or from the system properties (system properties will take
precedence over the file):
<br/>
<pre>
database.url=... Database connect string (required)
database.user=... Authenticate as this user (optional if provided in url)
database.password=... User password (optional if user and password provided in
url; prompted on standard input if user is provided and
password is not)
database.flavor=... What kind of database it is (optional, will guess based
on the url if this is not provided)
database.driver=... The Java class of the JDBC driver to load (optional, will
guess based on the flavor if this is not provided)
</pre>
<p>This will use the JVM default character encoding to read the property file.</p>
@param filename path to the properties file we will attempt to read; if the file
cannot be read for any reason (e.g. does not exist) a debug level
log entry will be entered, but it will attempt to proceed using
solely the system properties
@param propertyPrefix if this is null or empty the properties above will be read;
if a value is provided it will be prefixed to each property
(exactly, so if you want to use "my.database.url" you must
pass "my." as the prefix)
"""
return fromPropertyFileOrSystemProperties(filename, propertyPrefix, Charset.defaultCharset().newDecoder());
} | java | public static Builder fromPropertyFileOrSystemProperties(String filename, String propertyPrefix) {
return fromPropertyFileOrSystemProperties(filename, propertyPrefix, Charset.defaultCharset().newDecoder());
} | [
"public",
"static",
"Builder",
"fromPropertyFileOrSystemProperties",
"(",
"String",
"filename",
",",
"String",
"propertyPrefix",
")",
"{",
"return",
"fromPropertyFileOrSystemProperties",
"(",
"filename",
",",
"propertyPrefix",
",",
"Charset",
".",
"defaultCharset",
"(",
")",
".",
"newDecoder",
"(",
")",
")",
";",
"}"
] | Configure the database from up to five properties read from the specified
properties file, or from the system properties (system properties will take
precedence over the file):
<br/>
<pre>
database.url=... Database connect string (required)
database.user=... Authenticate as this user (optional if provided in url)
database.password=... User password (optional if user and password provided in
url; prompted on standard input if user is provided and
password is not)
database.flavor=... What kind of database it is (optional, will guess based
on the url if this is not provided)
database.driver=... The Java class of the JDBC driver to load (optional, will
guess based on the flavor if this is not provided)
</pre>
<p>This will use the JVM default character encoding to read the property file.</p>
@param filename path to the properties file we will attempt to read; if the file
cannot be read for any reason (e.g. does not exist) a debug level
log entry will be entered, but it will attempt to proceed using
solely the system properties
@param propertyPrefix if this is null or empty the properties above will be read;
if a value is provided it will be prefixed to each property
(exactly, so if you want to use "my.database.url" you must
pass "my." as the prefix) | [
"Configure",
"the",
"database",
"from",
"up",
"to",
"five",
"properties",
"read",
"from",
"the",
"specified",
"properties",
"file",
"or",
"from",
"the",
"system",
"properties",
"(",
"system",
"properties",
"will",
"take",
"precedence",
"over",
"the",
"file",
")",
":",
"<br",
"/",
">",
"<pre",
">",
"database",
".",
"url",
"=",
"...",
"Database",
"connect",
"string",
"(",
"required",
")",
"database",
".",
"user",
"=",
"...",
"Authenticate",
"as",
"this",
"user",
"(",
"optional",
"if",
"provided",
"in",
"url",
")",
"database",
".",
"password",
"=",
"...",
"User",
"password",
"(",
"optional",
"if",
"user",
"and",
"password",
"provided",
"in",
"url",
";",
"prompted",
"on",
"standard",
"input",
"if",
"user",
"is",
"provided",
"and",
"password",
"is",
"not",
")",
"database",
".",
"flavor",
"=",
"...",
"What",
"kind",
"of",
"database",
"it",
"is",
"(",
"optional",
"will",
"guess",
"based",
"on",
"the",
"url",
"if",
"this",
"is",
"not",
"provided",
")",
"database",
".",
"driver",
"=",
"...",
"The",
"Java",
"class",
"of",
"the",
"JDBC",
"driver",
"to",
"load",
"(",
"optional",
"will",
"guess",
"based",
"on",
"the",
"flavor",
"if",
"this",
"is",
"not",
"provided",
")",
"<",
"/",
"pre",
">",
"<p",
">",
"This",
"will",
"use",
"the",
"JVM",
"default",
"character",
"encoding",
"to",
"read",
"the",
"property",
"file",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/susom/database/blob/25add9e08ad863712f9b5e319b6cb826f6f97640/src/main/java/com/github/susom/database/DatabaseProvider.java#L484-L486 |
wildfly/wildfly-core | logging/src/main/java/org/jboss/as/logging/deployments/resources/LoggingConfigurationReadStepHandler.java | LoggingConfigurationReadStepHandler.setModelValue | static void setModelValue(final ModelNode model, final Boolean value) {
"""
Sets the value of the model if the value is not {@code null}.
@param model the model to update
@param value the value for the model
"""
if (value != null) {
model.set(value);
}
} | java | static void setModelValue(final ModelNode model, final Boolean value) {
if (value != null) {
model.set(value);
}
} | [
"static",
"void",
"setModelValue",
"(",
"final",
"ModelNode",
"model",
",",
"final",
"Boolean",
"value",
")",
"{",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"model",
".",
"set",
"(",
"value",
")",
";",
"}",
"}"
] | Sets the value of the model if the value is not {@code null}.
@param model the model to update
@param value the value for the model | [
"Sets",
"the",
"value",
"of",
"the",
"model",
"if",
"the",
"value",
"is",
"not",
"{",
"@code",
"null",
"}",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/logging/src/main/java/org/jboss/as/logging/deployments/resources/LoggingConfigurationReadStepHandler.java#L101-L105 |
facebookarchive/hadoop-20 | src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNodeZkUtil.java | AvatarNodeZkUtil.writeSessionIdToZK | static long writeSessionIdToZK(Configuration conf) throws IOException {
"""
Generates a new session id for the cluster and writes it to zookeeper. Some
other data in zookeeper (like the last transaction id) is written to
zookeeper with the sessionId so that we can easily determine in which
session was this data written. The sessionId is unique since it uses the
current time.
@return the session id that it wrote to ZooKeeper
@throws IOException
"""
AvatarZooKeeperClient zk = null;
long ssid = -1;
int maxTries = conf.getInt("dfs.avatarnode.zk.retries", 3);
boolean mismatch = false;
Long ssIdInZk = -1L;
for (int i = 0; i < maxTries; i++) {
try {
zk = new AvatarZooKeeperClient(conf, null, false);
ssid = writeSessionIdToZK(conf, zk);
return ssid;
} catch (Exception e) {
LOG.error("Got Exception when writing session id to zk. Will retry...",
e);
} finally {
shutdownZkClient(zk);
}
}
if (mismatch)
throw new IOException("Session Id in the NameNode : " + ssid
+ " does not match the session Id in Zookeeper : " + ssIdInZk);
throw new IOException("Cannot connect to zk");
} | java | static long writeSessionIdToZK(Configuration conf) throws IOException {
AvatarZooKeeperClient zk = null;
long ssid = -1;
int maxTries = conf.getInt("dfs.avatarnode.zk.retries", 3);
boolean mismatch = false;
Long ssIdInZk = -1L;
for (int i = 0; i < maxTries; i++) {
try {
zk = new AvatarZooKeeperClient(conf, null, false);
ssid = writeSessionIdToZK(conf, zk);
return ssid;
} catch (Exception e) {
LOG.error("Got Exception when writing session id to zk. Will retry...",
e);
} finally {
shutdownZkClient(zk);
}
}
if (mismatch)
throw new IOException("Session Id in the NameNode : " + ssid
+ " does not match the session Id in Zookeeper : " + ssIdInZk);
throw new IOException("Cannot connect to zk");
} | [
"static",
"long",
"writeSessionIdToZK",
"(",
"Configuration",
"conf",
")",
"throws",
"IOException",
"{",
"AvatarZooKeeperClient",
"zk",
"=",
"null",
";",
"long",
"ssid",
"=",
"-",
"1",
";",
"int",
"maxTries",
"=",
"conf",
".",
"getInt",
"(",
"\"dfs.avatarnode.zk.retries\"",
",",
"3",
")",
";",
"boolean",
"mismatch",
"=",
"false",
";",
"Long",
"ssIdInZk",
"=",
"-",
"1L",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"maxTries",
";",
"i",
"++",
")",
"{",
"try",
"{",
"zk",
"=",
"new",
"AvatarZooKeeperClient",
"(",
"conf",
",",
"null",
",",
"false",
")",
";",
"ssid",
"=",
"writeSessionIdToZK",
"(",
"conf",
",",
"zk",
")",
";",
"return",
"ssid",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Got Exception when writing session id to zk. Will retry...\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"shutdownZkClient",
"(",
"zk",
")",
";",
"}",
"}",
"if",
"(",
"mismatch",
")",
"throw",
"new",
"IOException",
"(",
"\"Session Id in the NameNode : \"",
"+",
"ssid",
"+",
"\" does not match the session Id in Zookeeper : \"",
"+",
"ssIdInZk",
")",
";",
"throw",
"new",
"IOException",
"(",
"\"Cannot connect to zk\"",
")",
";",
"}"
] | Generates a new session id for the cluster and writes it to zookeeper. Some
other data in zookeeper (like the last transaction id) is written to
zookeeper with the sessionId so that we can easily determine in which
session was this data written. The sessionId is unique since it uses the
current time.
@return the session id that it wrote to ZooKeeper
@throws IOException | [
"Generates",
"a",
"new",
"session",
"id",
"for",
"the",
"cluster",
"and",
"writes",
"it",
"to",
"zookeeper",
".",
"Some",
"other",
"data",
"in",
"zookeeper",
"(",
"like",
"the",
"last",
"transaction",
"id",
")",
"is",
"written",
"to",
"zookeeper",
"with",
"the",
"sessionId",
"so",
"that",
"we",
"can",
"easily",
"determine",
"in",
"which",
"session",
"was",
"this",
"data",
"written",
".",
"The",
"sessionId",
"is",
"unique",
"since",
"it",
"uses",
"the",
"current",
"time",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNodeZkUtil.java#L189-L212 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/rpc/akka/AkkaRpcServiceUtils.java | AkkaRpcServiceUtils.createRpcService | public static RpcService createRpcService(
String hostname,
String portRangeDefinition,
Configuration configuration) throws Exception {
"""
Utility method to create RPC service from configuration and hostname, port.
@param hostname The hostname/address that describes the TaskManager's data location.
@param portRangeDefinition The port range to start TaskManager on.
@param configuration The configuration for the TaskManager.
@return The rpc service which is used to start and connect to the TaskManager RpcEndpoint .
@throws IOException Thrown, if the actor system can not bind to the address
@throws Exception Thrown is some other error occurs while creating akka actor system
"""
final ActorSystem actorSystem = BootstrapTools.startActorSystem(configuration, hostname, portRangeDefinition, LOG);
return instantiateAkkaRpcService(configuration, actorSystem);
} | java | public static RpcService createRpcService(
String hostname,
String portRangeDefinition,
Configuration configuration) throws Exception {
final ActorSystem actorSystem = BootstrapTools.startActorSystem(configuration, hostname, portRangeDefinition, LOG);
return instantiateAkkaRpcService(configuration, actorSystem);
} | [
"public",
"static",
"RpcService",
"createRpcService",
"(",
"String",
"hostname",
",",
"String",
"portRangeDefinition",
",",
"Configuration",
"configuration",
")",
"throws",
"Exception",
"{",
"final",
"ActorSystem",
"actorSystem",
"=",
"BootstrapTools",
".",
"startActorSystem",
"(",
"configuration",
",",
"hostname",
",",
"portRangeDefinition",
",",
"LOG",
")",
";",
"return",
"instantiateAkkaRpcService",
"(",
"configuration",
",",
"actorSystem",
")",
";",
"}"
] | Utility method to create RPC service from configuration and hostname, port.
@param hostname The hostname/address that describes the TaskManager's data location.
@param portRangeDefinition The port range to start TaskManager on.
@param configuration The configuration for the TaskManager.
@return The rpc service which is used to start and connect to the TaskManager RpcEndpoint .
@throws IOException Thrown, if the actor system can not bind to the address
@throws Exception Thrown is some other error occurs while creating akka actor system | [
"Utility",
"method",
"to",
"create",
"RPC",
"service",
"from",
"configuration",
"and",
"hostname",
"port",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/rpc/akka/AkkaRpcServiceUtils.java#L80-L86 |
onelogin/onelogin-java-sdk | src/main/java/com/onelogin/sdk/conn/Client.java | Client.getUsersBatch | private String getUsersBatch(List<User> users, URIBuilder url, OAuthClientRequest bearerRequest,
OneloginOAuthJSONResourceResponse oAuthResponse) {
"""
Get a batch of Users.
@param users
@param url
@param bearerRequest
@param oAuthResponse
@return The Batch reference
@see com.onelogin.sdk.model.User
@see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/users/get-users">Get Users documentation</a>
"""
if (oAuthResponse.getResponseCode() == 200) {
JSONObject[] dataArray = oAuthResponse.getDataArray();
if (dataArray != null && dataArray.length > 0) {
for (JSONObject data : dataArray) {
users.add(new User(data));
}
}
return collectAfterCursor(url, bearerRequest, oAuthResponse);
} else {
error = oAuthResponse.getError();
errorDescription = oAuthResponse.getErrorDescription();
}
return null;
} | java | private String getUsersBatch(List<User> users, URIBuilder url, OAuthClientRequest bearerRequest,
OneloginOAuthJSONResourceResponse oAuthResponse) {
if (oAuthResponse.getResponseCode() == 200) {
JSONObject[] dataArray = oAuthResponse.getDataArray();
if (dataArray != null && dataArray.length > 0) {
for (JSONObject data : dataArray) {
users.add(new User(data));
}
}
return collectAfterCursor(url, bearerRequest, oAuthResponse);
} else {
error = oAuthResponse.getError();
errorDescription = oAuthResponse.getErrorDescription();
}
return null;
} | [
"private",
"String",
"getUsersBatch",
"(",
"List",
"<",
"User",
">",
"users",
",",
"URIBuilder",
"url",
",",
"OAuthClientRequest",
"bearerRequest",
",",
"OneloginOAuthJSONResourceResponse",
"oAuthResponse",
")",
"{",
"if",
"(",
"oAuthResponse",
".",
"getResponseCode",
"(",
")",
"==",
"200",
")",
"{",
"JSONObject",
"[",
"]",
"dataArray",
"=",
"oAuthResponse",
".",
"getDataArray",
"(",
")",
";",
"if",
"(",
"dataArray",
"!=",
"null",
"&&",
"dataArray",
".",
"length",
">",
"0",
")",
"{",
"for",
"(",
"JSONObject",
"data",
":",
"dataArray",
")",
"{",
"users",
".",
"add",
"(",
"new",
"User",
"(",
"data",
")",
")",
";",
"}",
"}",
"return",
"collectAfterCursor",
"(",
"url",
",",
"bearerRequest",
",",
"oAuthResponse",
")",
";",
"}",
"else",
"{",
"error",
"=",
"oAuthResponse",
".",
"getError",
"(",
")",
";",
"errorDescription",
"=",
"oAuthResponse",
".",
"getErrorDescription",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Get a batch of Users.
@param users
@param url
@param bearerRequest
@param oAuthResponse
@return The Batch reference
@see com.onelogin.sdk.model.User
@see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/users/get-users">Get Users documentation</a> | [
"Get",
"a",
"batch",
"of",
"Users",
"."
] | train | https://github.com/onelogin/onelogin-java-sdk/blob/1570b78033dcc1c7387099e77fe41b6b0638df8c/src/main/java/com/onelogin/sdk/conn/Client.java#L418-L434 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java | AsynchronousRequest.getOutfitInfo | public void getOutfitInfo(int[] ids, Callback<List<Outfit>> callback) throws GuildWars2Exception, NullPointerException {
"""
For more info on Outfits API go <a href="https://wiki.guildwars2.com/wiki/API:2/outfits">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param ids list of outfit id
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception empty ID list
@throws NullPointerException if given {@link Callback} is empty
@see Outfit outfit info
"""
isParamValid(new ParamChecker(ids));
gw2API.getOutfitInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
} | java | public void getOutfitInfo(int[] ids, Callback<List<Outfit>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
gw2API.getOutfitInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
} | [
"public",
"void",
"getOutfitInfo",
"(",
"int",
"[",
"]",
"ids",
",",
"Callback",
"<",
"List",
"<",
"Outfit",
">",
">",
"callback",
")",
"throws",
"GuildWars2Exception",
",",
"NullPointerException",
"{",
"isParamValid",
"(",
"new",
"ParamChecker",
"(",
"ids",
")",
")",
";",
"gw2API",
".",
"getOutfitInfo",
"(",
"processIds",
"(",
"ids",
")",
",",
"GuildWars2",
".",
"lang",
".",
"getValue",
"(",
")",
")",
".",
"enqueue",
"(",
"callback",
")",
";",
"}"
] | For more info on Outfits API go <a href="https://wiki.guildwars2.com/wiki/API:2/outfits">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param ids list of outfit id
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception empty ID list
@throws NullPointerException if given {@link Callback} is empty
@see Outfit outfit info | [
"For",
"more",
"info",
"on",
"Outfits",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"outfits",
">",
"here<",
"/",
"a",
">",
"<br",
"/",
">",
"Give",
"user",
"the",
"access",
"to",
"{",
"@link",
"Callback#onResponse",
"(",
"Call",
"Response",
")",
"}",
"and",
"{",
"@link",
"Callback#onFailure",
"(",
"Call",
"Throwable",
")",
"}",
"methods",
"for",
"custom",
"interactions"
] | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L1934-L1937 |
wisdom-framework/wisdom | extensions/wisdom-raml/wisdom-raml-monitor-console/src/main/java/monitor/raml/console/RamlMonitorController.java | RamlMonitorController.index | @Route(method = HttpMethod.GET, uri = "")
public Result index(@PathParameter("name") String name) {
"""
Return the raml console api corresponding to the raml of given name.
@response.mime text/html
@param name Name of the raml api to display.
@return the raml console api or 404 if the file of given name doesn't exist in wisdom
"""
if(names.contains(name)){
return ok(render(template,"source",RAML_ASSET_DIR+name+RAML_EXT));
}
return notFound();
} | java | @Route(method = HttpMethod.GET, uri = "")
public Result index(@PathParameter("name") String name) {
if(names.contains(name)){
return ok(render(template,"source",RAML_ASSET_DIR+name+RAML_EXT));
}
return notFound();
} | [
"@",
"Route",
"(",
"method",
"=",
"HttpMethod",
".",
"GET",
",",
"uri",
"=",
"\"\"",
")",
"public",
"Result",
"index",
"(",
"@",
"PathParameter",
"(",
"\"name\"",
")",
"String",
"name",
")",
"{",
"if",
"(",
"names",
".",
"contains",
"(",
"name",
")",
")",
"{",
"return",
"ok",
"(",
"render",
"(",
"template",
",",
"\"source\"",
",",
"RAML_ASSET_DIR",
"+",
"name",
"+",
"RAML_EXT",
")",
")",
";",
"}",
"return",
"notFound",
"(",
")",
";",
"}"
] | Return the raml console api corresponding to the raml of given name.
@response.mime text/html
@param name Name of the raml api to display.
@return the raml console api or 404 if the file of given name doesn't exist in wisdom | [
"Return",
"the",
"raml",
"console",
"api",
"corresponding",
"to",
"the",
"raml",
"of",
"given",
"name",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/extensions/wisdom-raml/wisdom-raml-monitor-console/src/main/java/monitor/raml/console/RamlMonitorController.java#L92-L98 |
lucee/Lucee | core/src/main/java/lucee/runtime/security/SecurityManagerImpl.java | SecurityManagerImpl.toStringAccessValue | public static String toStringAccessValue(short accessValue) throws SecurityException {
"""
translate a short access value (all,local,none,no,yes) to String type
@param accessValue
@return return int access value (VALUE_ALL,VALUE_LOCAL,VALUE_NO,VALUE_NONE,VALUE_YES)
@throws SecurityException
"""
switch (accessValue) {
case VALUE_NONE:
return "none";
// case VALUE_NO: return "no";
case VALUE_YES:
return "yes";
// case VALUE_ALL: return "all";
case VALUE_LOCAL:
return "local";
case VALUE_1:
return "1";
case VALUE_2:
return "2";
case VALUE_3:
return "3";
case VALUE_4:
return "4";
case VALUE_5:
return "5";
case VALUE_6:
return "6";
case VALUE_7:
return "7";
case VALUE_8:
return "8";
case VALUE_9:
return "9";
case VALUE_10:
return "10";
}
throw new SecurityException("invalid access value", "valid access values are [all,local,no,none,yes,1,...,10]");
} | java | public static String toStringAccessValue(short accessValue) throws SecurityException {
switch (accessValue) {
case VALUE_NONE:
return "none";
// case VALUE_NO: return "no";
case VALUE_YES:
return "yes";
// case VALUE_ALL: return "all";
case VALUE_LOCAL:
return "local";
case VALUE_1:
return "1";
case VALUE_2:
return "2";
case VALUE_3:
return "3";
case VALUE_4:
return "4";
case VALUE_5:
return "5";
case VALUE_6:
return "6";
case VALUE_7:
return "7";
case VALUE_8:
return "8";
case VALUE_9:
return "9";
case VALUE_10:
return "10";
}
throw new SecurityException("invalid access value", "valid access values are [all,local,no,none,yes,1,...,10]");
} | [
"public",
"static",
"String",
"toStringAccessValue",
"(",
"short",
"accessValue",
")",
"throws",
"SecurityException",
"{",
"switch",
"(",
"accessValue",
")",
"{",
"case",
"VALUE_NONE",
":",
"return",
"\"none\"",
";",
"// case VALUE_NO: return \"no\";",
"case",
"VALUE_YES",
":",
"return",
"\"yes\"",
";",
"// case VALUE_ALL: return \"all\";",
"case",
"VALUE_LOCAL",
":",
"return",
"\"local\"",
";",
"case",
"VALUE_1",
":",
"return",
"\"1\"",
";",
"case",
"VALUE_2",
":",
"return",
"\"2\"",
";",
"case",
"VALUE_3",
":",
"return",
"\"3\"",
";",
"case",
"VALUE_4",
":",
"return",
"\"4\"",
";",
"case",
"VALUE_5",
":",
"return",
"\"5\"",
";",
"case",
"VALUE_6",
":",
"return",
"\"6\"",
";",
"case",
"VALUE_7",
":",
"return",
"\"7\"",
";",
"case",
"VALUE_8",
":",
"return",
"\"8\"",
";",
"case",
"VALUE_9",
":",
"return",
"\"9\"",
";",
"case",
"VALUE_10",
":",
"return",
"\"10\"",
";",
"}",
"throw",
"new",
"SecurityException",
"(",
"\"invalid access value\"",
",",
"\"valid access values are [all,local,no,none,yes,1,...,10]\"",
")",
";",
"}"
] | translate a short access value (all,local,none,no,yes) to String type
@param accessValue
@return return int access value (VALUE_ALL,VALUE_LOCAL,VALUE_NO,VALUE_NONE,VALUE_YES)
@throws SecurityException | [
"translate",
"a",
"short",
"access",
"value",
"(",
"all",
"local",
"none",
"no",
"yes",
")",
"to",
"String",
"type"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/security/SecurityManagerImpl.java#L263-L296 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpx/MPXWriter.java | MPXWriter.writeNotes | private void writeNotes(int recordNumber, String text) throws IOException {
"""
Write notes.
@param recordNumber record number
@param text note text
@throws IOException
"""
m_buffer.setLength(0);
m_buffer.append(recordNumber);
m_buffer.append(m_delimiter);
if (text != null)
{
String note = stripLineBreaks(text, MPXConstants.EOL_PLACEHOLDER_STRING);
boolean quote = (note.indexOf(m_delimiter) != -1 || note.indexOf('"') != -1);
int length = note.length();
char c;
if (quote == true)
{
m_buffer.append('"');
}
for (int loop = 0; loop < length; loop++)
{
c = note.charAt(loop);
switch (c)
{
case '"':
{
m_buffer.append("\"\"");
break;
}
default:
{
m_buffer.append(c);
break;
}
}
}
if (quote == true)
{
m_buffer.append('"');
}
}
m_buffer.append(MPXConstants.EOL);
m_writer.write(m_buffer.toString());
} | java | private void writeNotes(int recordNumber, String text) throws IOException
{
m_buffer.setLength(0);
m_buffer.append(recordNumber);
m_buffer.append(m_delimiter);
if (text != null)
{
String note = stripLineBreaks(text, MPXConstants.EOL_PLACEHOLDER_STRING);
boolean quote = (note.indexOf(m_delimiter) != -1 || note.indexOf('"') != -1);
int length = note.length();
char c;
if (quote == true)
{
m_buffer.append('"');
}
for (int loop = 0; loop < length; loop++)
{
c = note.charAt(loop);
switch (c)
{
case '"':
{
m_buffer.append("\"\"");
break;
}
default:
{
m_buffer.append(c);
break;
}
}
}
if (quote == true)
{
m_buffer.append('"');
}
}
m_buffer.append(MPXConstants.EOL);
m_writer.write(m_buffer.toString());
} | [
"private",
"void",
"writeNotes",
"(",
"int",
"recordNumber",
",",
"String",
"text",
")",
"throws",
"IOException",
"{",
"m_buffer",
".",
"setLength",
"(",
"0",
")",
";",
"m_buffer",
".",
"append",
"(",
"recordNumber",
")",
";",
"m_buffer",
".",
"append",
"(",
"m_delimiter",
")",
";",
"if",
"(",
"text",
"!=",
"null",
")",
"{",
"String",
"note",
"=",
"stripLineBreaks",
"(",
"text",
",",
"MPXConstants",
".",
"EOL_PLACEHOLDER_STRING",
")",
";",
"boolean",
"quote",
"=",
"(",
"note",
".",
"indexOf",
"(",
"m_delimiter",
")",
"!=",
"-",
"1",
"||",
"note",
".",
"indexOf",
"(",
"'",
"'",
")",
"!=",
"-",
"1",
")",
";",
"int",
"length",
"=",
"note",
".",
"length",
"(",
")",
";",
"char",
"c",
";",
"if",
"(",
"quote",
"==",
"true",
")",
"{",
"m_buffer",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
"for",
"(",
"int",
"loop",
"=",
"0",
";",
"loop",
"<",
"length",
";",
"loop",
"++",
")",
"{",
"c",
"=",
"note",
".",
"charAt",
"(",
"loop",
")",
";",
"switch",
"(",
"c",
")",
"{",
"case",
"'",
"'",
":",
"{",
"m_buffer",
".",
"append",
"(",
"\"\\\"\\\"\"",
")",
";",
"break",
";",
"}",
"default",
":",
"{",
"m_buffer",
".",
"append",
"(",
"c",
")",
";",
"break",
";",
"}",
"}",
"}",
"if",
"(",
"quote",
"==",
"true",
")",
"{",
"m_buffer",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
"}",
"m_buffer",
".",
"append",
"(",
"MPXConstants",
".",
"EOL",
")",
";",
"m_writer",
".",
"write",
"(",
"m_buffer",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Write notes.
@param recordNumber record number
@param text note text
@throws IOException | [
"Write",
"notes",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/MPXWriter.java#L554-L602 |
ironjacamar/ironjacamar | core/src/main/java/org/ironjacamar/core/workmanager/transport/remote/AbstractRemoteTransport.java | AbstractRemoteTransport.localUpdateLongRunningFree | public void localUpdateLongRunningFree(Address logicalAddress, Long freeCount) {
"""
localUpdateLongRunningFree
@param logicalAddress the logical address
@param freeCount the free count
"""
if (trace)
log.tracef("LOCAL_UPDATE_LONGRUNNING_FREE(%s, %d)", logicalAddress, freeCount);
DistributedWorkManager dwm = workManagerCoordinator.resolveDistributedWorkManager(logicalAddress);
if (dwm != null)
{
Collection<NotificationListener> copy =
new ArrayList<NotificationListener>(dwm.getNotificationListeners());
for (NotificationListener nl : copy)
{
nl.updateLongRunningFree(logicalAddress, freeCount);
}
}
else
{
WorkManagerEventQueue wmeq = WorkManagerEventQueue.getInstance();
wmeq.addEvent(new WorkManagerEvent(WorkManagerEvent.TYPE_UPDATE_LONG_RUNNING, logicalAddress, freeCount));
}
} | java | public void localUpdateLongRunningFree(Address logicalAddress, Long freeCount)
{
if (trace)
log.tracef("LOCAL_UPDATE_LONGRUNNING_FREE(%s, %d)", logicalAddress, freeCount);
DistributedWorkManager dwm = workManagerCoordinator.resolveDistributedWorkManager(logicalAddress);
if (dwm != null)
{
Collection<NotificationListener> copy =
new ArrayList<NotificationListener>(dwm.getNotificationListeners());
for (NotificationListener nl : copy)
{
nl.updateLongRunningFree(logicalAddress, freeCount);
}
}
else
{
WorkManagerEventQueue wmeq = WorkManagerEventQueue.getInstance();
wmeq.addEvent(new WorkManagerEvent(WorkManagerEvent.TYPE_UPDATE_LONG_RUNNING, logicalAddress, freeCount));
}
} | [
"public",
"void",
"localUpdateLongRunningFree",
"(",
"Address",
"logicalAddress",
",",
"Long",
"freeCount",
")",
"{",
"if",
"(",
"trace",
")",
"log",
".",
"tracef",
"(",
"\"LOCAL_UPDATE_LONGRUNNING_FREE(%s, %d)\"",
",",
"logicalAddress",
",",
"freeCount",
")",
";",
"DistributedWorkManager",
"dwm",
"=",
"workManagerCoordinator",
".",
"resolveDistributedWorkManager",
"(",
"logicalAddress",
")",
";",
"if",
"(",
"dwm",
"!=",
"null",
")",
"{",
"Collection",
"<",
"NotificationListener",
">",
"copy",
"=",
"new",
"ArrayList",
"<",
"NotificationListener",
">",
"(",
"dwm",
".",
"getNotificationListeners",
"(",
")",
")",
";",
"for",
"(",
"NotificationListener",
"nl",
":",
"copy",
")",
"{",
"nl",
".",
"updateLongRunningFree",
"(",
"logicalAddress",
",",
"freeCount",
")",
";",
"}",
"}",
"else",
"{",
"WorkManagerEventQueue",
"wmeq",
"=",
"WorkManagerEventQueue",
".",
"getInstance",
"(",
")",
";",
"wmeq",
".",
"addEvent",
"(",
"new",
"WorkManagerEvent",
"(",
"WorkManagerEvent",
".",
"TYPE_UPDATE_LONG_RUNNING",
",",
"logicalAddress",
",",
"freeCount",
")",
")",
";",
"}",
"}"
] | localUpdateLongRunningFree
@param logicalAddress the logical address
@param freeCount the free count | [
"localUpdateLongRunningFree"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/core/src/main/java/org/ironjacamar/core/workmanager/transport/remote/AbstractRemoteTransport.java#L942-L963 |
jamesagnew/hapi-fhir | hapi-fhir-converter/src/main/java/org/hl7/fhir/convertors/CDAUtilities.java | CDAUtilities.getById | public Element getById(Element id, String childName) throws Exception {
"""
This method looks up an object by it's id, and only returns it if has a child by the given name
(resolving identifier based cross references)
@param id
@param childName
@return
@throws Exception
"""
return getById(doc.getDocumentElement(), id, childName);
} | java | public Element getById(Element id, String childName) throws Exception {
return getById(doc.getDocumentElement(), id, childName);
} | [
"public",
"Element",
"getById",
"(",
"Element",
"id",
",",
"String",
"childName",
")",
"throws",
"Exception",
"{",
"return",
"getById",
"(",
"doc",
".",
"getDocumentElement",
"(",
")",
",",
"id",
",",
"childName",
")",
";",
"}"
] | This method looks up an object by it's id, and only returns it if has a child by the given name
(resolving identifier based cross references)
@param id
@param childName
@return
@throws Exception | [
"This",
"method",
"looks",
"up",
"an",
"object",
"by",
"it",
"s",
"id",
"and",
"only",
"returns",
"it",
"if",
"has",
"a",
"child",
"by",
"the",
"given",
"name",
"(",
"resolving",
"identifier",
"based",
"cross",
"references",
")"
] | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-converter/src/main/java/org/hl7/fhir/convertors/CDAUtilities.java#L238-L240 |
beihaifeiwu/dolphin | dolphin-common/src/main/java/com/freetmp/common/type/ResolvableType.java | ResolvableType.forConstructorParameter | public static ResolvableType forConstructorParameter(Constructor<?> constructor, int parameterIndex,
Class<?> implementationClass) {
"""
Return a {@link ResolvableType} for the specified {@link Constructor} parameter
with a given implementation. Use this variant when the class that declares the
constructor includes generic parameter variables that are satisfied by the
implementation class.
@param constructor the source constructor (must not be {@code null})
@param parameterIndex the parameter index
@param implementationClass the implementation class
@return a {@link ResolvableType} for the specified constructor parameter
@see #forConstructorParameter(Constructor, int)
"""
Assert.notNull(constructor, "Constructor must not be null");
MethodParameter methodParameter = new MethodParameter(constructor, parameterIndex);
methodParameter.setContainingClass(implementationClass);
return forMethodParameter(methodParameter);
} | java | public static ResolvableType forConstructorParameter(Constructor<?> constructor, int parameterIndex,
Class<?> implementationClass) {
Assert.notNull(constructor, "Constructor must not be null");
MethodParameter methodParameter = new MethodParameter(constructor, parameterIndex);
methodParameter.setContainingClass(implementationClass);
return forMethodParameter(methodParameter);
} | [
"public",
"static",
"ResolvableType",
"forConstructorParameter",
"(",
"Constructor",
"<",
"?",
">",
"constructor",
",",
"int",
"parameterIndex",
",",
"Class",
"<",
"?",
">",
"implementationClass",
")",
"{",
"Assert",
".",
"notNull",
"(",
"constructor",
",",
"\"Constructor must not be null\"",
")",
";",
"MethodParameter",
"methodParameter",
"=",
"new",
"MethodParameter",
"(",
"constructor",
",",
"parameterIndex",
")",
";",
"methodParameter",
".",
"setContainingClass",
"(",
"implementationClass",
")",
";",
"return",
"forMethodParameter",
"(",
"methodParameter",
")",
";",
"}"
] | Return a {@link ResolvableType} for the specified {@link Constructor} parameter
with a given implementation. Use this variant when the class that declares the
constructor includes generic parameter variables that are satisfied by the
implementation class.
@param constructor the source constructor (must not be {@code null})
@param parameterIndex the parameter index
@param implementationClass the implementation class
@return a {@link ResolvableType} for the specified constructor parameter
@see #forConstructorParameter(Constructor, int) | [
"Return",
"a",
"{"
] | train | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/type/ResolvableType.java#L1014-L1021 |
geomajas/geomajas-project-client-gwt | client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java | DomHelper.setController | public void setController(Object parent, String name, GraphicsController controller, int eventMask) {
"""
Set the controller on an element of this <code>GraphicsContext</code> so it can react to events.
@param parent
the parent of the element on which the controller should be set.
@param name
the name of the child element on which the controller should be set
@param controller
The new <code>GraphicsController</code>
@param eventMask
a bitmask to specify which events to listen for {@link com.google.gwt.user.client.Event}
"""
doSetController(getElement(parent, name), controller, eventMask);
} | java | public void setController(Object parent, String name, GraphicsController controller, int eventMask) {
doSetController(getElement(parent, name), controller, eventMask);
} | [
"public",
"void",
"setController",
"(",
"Object",
"parent",
",",
"String",
"name",
",",
"GraphicsController",
"controller",
",",
"int",
"eventMask",
")",
"{",
"doSetController",
"(",
"getElement",
"(",
"parent",
",",
"name",
")",
",",
"controller",
",",
"eventMask",
")",
";",
"}"
] | Set the controller on an element of this <code>GraphicsContext</code> so it can react to events.
@param parent
the parent of the element on which the controller should be set.
@param name
the name of the child element on which the controller should be set
@param controller
The new <code>GraphicsController</code>
@param eventMask
a bitmask to specify which events to listen for {@link com.google.gwt.user.client.Event} | [
"Set",
"the",
"controller",
"on",
"an",
"element",
"of",
"this",
"<code",
">",
"GraphicsContext<",
"/",
"code",
">",
"so",
"it",
"can",
"react",
"to",
"events",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java#L599-L601 |
mabe02/lanterna | src/main/java/com/googlecode/lanterna/TerminalSize.java | TerminalSize.withRows | public TerminalSize withRows(int rows) {
"""
Creates a new size based on this size, but with a different height
@param rows Height of the new size, in rows
@return New size based on this one, but with a new height
"""
if(this.rows == rows) {
return this;
}
if(rows == 0 && this.columns == 0) {
return ZERO;
}
return new TerminalSize(this.columns, rows);
} | java | public TerminalSize withRows(int rows) {
if(this.rows == rows) {
return this;
}
if(rows == 0 && this.columns == 0) {
return ZERO;
}
return new TerminalSize(this.columns, rows);
} | [
"public",
"TerminalSize",
"withRows",
"(",
"int",
"rows",
")",
"{",
"if",
"(",
"this",
".",
"rows",
"==",
"rows",
")",
"{",
"return",
"this",
";",
"}",
"if",
"(",
"rows",
"==",
"0",
"&&",
"this",
".",
"columns",
"==",
"0",
")",
"{",
"return",
"ZERO",
";",
"}",
"return",
"new",
"TerminalSize",
"(",
"this",
".",
"columns",
",",
"rows",
")",
";",
"}"
] | Creates a new size based on this size, but with a different height
@param rows Height of the new size, in rows
@return New size based on this one, but with a new height | [
"Creates",
"a",
"new",
"size",
"based",
"on",
"this",
"size",
"but",
"with",
"a",
"different",
"height"
] | train | https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/TerminalSize.java#L85-L93 |
michel-kraemer/citeproc-java | citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java | CSL.registerCitationItems | public void registerCitationItems(String... ids) {
"""
Introduces the given citation IDs to the processor. The processor will
call {@link ItemDataProvider#retrieveItem(String)} for each ID to get
the respective citation item. The retrieved items will be added to the
bibliography, so you don't have to call {@link #makeCitation(String...)}
for each of them anymore.
@param ids the IDs to register
@throws IllegalArgumentException if one of the given IDs refers to
citation item data that does not exist
"""
try {
runner.callMethod(engine, "updateItems", new Object[] { ids });
} catch (ScriptRunnerException e) {
throw new IllegalArgumentException("Could not update items", e);
}
} | java | public void registerCitationItems(String... ids) {
try {
runner.callMethod(engine, "updateItems", new Object[] { ids });
} catch (ScriptRunnerException e) {
throw new IllegalArgumentException("Could not update items", e);
}
} | [
"public",
"void",
"registerCitationItems",
"(",
"String",
"...",
"ids",
")",
"{",
"try",
"{",
"runner",
".",
"callMethod",
"(",
"engine",
",",
"\"updateItems\"",
",",
"new",
"Object",
"[",
"]",
"{",
"ids",
"}",
")",
";",
"}",
"catch",
"(",
"ScriptRunnerException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Could not update items\"",
",",
"e",
")",
";",
"}",
"}"
] | Introduces the given citation IDs to the processor. The processor will
call {@link ItemDataProvider#retrieveItem(String)} for each ID to get
the respective citation item. The retrieved items will be added to the
bibliography, so you don't have to call {@link #makeCitation(String...)}
for each of them anymore.
@param ids the IDs to register
@throws IllegalArgumentException if one of the given IDs refers to
citation item data that does not exist | [
"Introduces",
"the",
"given",
"citation",
"IDs",
"to",
"the",
"processor",
".",
"The",
"processor",
"will",
"call",
"{"
] | train | https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L611-L617 |
OpenTSDB/opentsdb | src/stats/StatsCollector.java | StatsCollector.addExtraTag | public final void addExtraTag(final String name, final String value) {
"""
Adds a tag to all the subsequent data points recorded.
<p>
All subsequent calls to one of the {@code record} methods will
associate the tag given to this method with the data point.
<p>
This method can be called multiple times to associate multiple tags
with all the subsequent data points.
@param name The name of the tag.
@param value The value of the tag.
@throws IllegalArgumentException if the name or the value are empty
or otherwise invalid.
@see #clearExtraTag
"""
if (name.length() <= 0) {
throw new IllegalArgumentException("empty tag name, value=" + value);
} else if (value.length() <= 0) {
throw new IllegalArgumentException("empty value, tag name=" + name);
} else if (name.indexOf('=') != -1) {
throw new IllegalArgumentException("tag name contains `=': " + name
+ " (value = " + value + ')');
} else if (value.indexOf('=') != -1) {
throw new IllegalArgumentException("tag value contains `=': " + value
+ " (name = " + name + ')');
}
if (extratags == null) {
extratags = new HashMap<String, String>();
}
extratags.put(name, value);
} | java | public final void addExtraTag(final String name, final String value) {
if (name.length() <= 0) {
throw new IllegalArgumentException("empty tag name, value=" + value);
} else if (value.length() <= 0) {
throw new IllegalArgumentException("empty value, tag name=" + name);
} else if (name.indexOf('=') != -1) {
throw new IllegalArgumentException("tag name contains `=': " + name
+ " (value = " + value + ')');
} else if (value.indexOf('=') != -1) {
throw new IllegalArgumentException("tag value contains `=': " + value
+ " (name = " + name + ')');
}
if (extratags == null) {
extratags = new HashMap<String, String>();
}
extratags.put(name, value);
} | [
"public",
"final",
"void",
"addExtraTag",
"(",
"final",
"String",
"name",
",",
"final",
"String",
"value",
")",
"{",
"if",
"(",
"name",
".",
"length",
"(",
")",
"<=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"empty tag name, value=\"",
"+",
"value",
")",
";",
"}",
"else",
"if",
"(",
"value",
".",
"length",
"(",
")",
"<=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"empty value, tag name=\"",
"+",
"name",
")",
";",
"}",
"else",
"if",
"(",
"name",
".",
"indexOf",
"(",
"'",
"'",
")",
"!=",
"-",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"tag name contains `=': \"",
"+",
"name",
"+",
"\" (value = \"",
"+",
"value",
"+",
"'",
"'",
")",
";",
"}",
"else",
"if",
"(",
"value",
".",
"indexOf",
"(",
"'",
"'",
")",
"!=",
"-",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"tag value contains `=': \"",
"+",
"value",
"+",
"\" (name = \"",
"+",
"name",
"+",
"'",
"'",
")",
";",
"}",
"if",
"(",
"extratags",
"==",
"null",
")",
"{",
"extratags",
"=",
"new",
"HashMap",
"<",
"String",
",",
"String",
">",
"(",
")",
";",
"}",
"extratags",
".",
"put",
"(",
"name",
",",
"value",
")",
";",
"}"
] | Adds a tag to all the subsequent data points recorded.
<p>
All subsequent calls to one of the {@code record} methods will
associate the tag given to this method with the data point.
<p>
This method can be called multiple times to associate multiple tags
with all the subsequent data points.
@param name The name of the tag.
@param value The value of the tag.
@throws IllegalArgumentException if the name or the value are empty
or otherwise invalid.
@see #clearExtraTag | [
"Adds",
"a",
"tag",
"to",
"all",
"the",
"subsequent",
"data",
"points",
"recorded",
".",
"<p",
">",
"All",
"subsequent",
"calls",
"to",
"one",
"of",
"the",
"{"
] | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/stats/StatsCollector.java#L182-L198 |
wonderpush/wonderpush-android-sdk | sdk/src/main/java/com/wonderpush/sdk/WonderPushFirebaseMessagingService.java | WonderPushFirebaseMessagingService.onMessageReceived | public static boolean onMessageReceived(Context context, RemoteMessage message) {
"""
Method to be called in your own {@link FirebaseMessagingService} to handle
WonderPush push notifications.
<b>Note:</b> This is only required if you use your own {@link FirebaseMessagingService}.
Implement your {@link FirebaseMessagingService#onMessageReceived(RemoteMessage)} method as follows:
<pre><code>@Override
public void onMessageReceived(RemoteMessage message) {
if (WonderPushFirebaseMessagingService.onMessageReceived(this, message)) {
return;
}
// Do your own handling here
}</code></pre>
@param context The current context
@param message The received message
@return Whether the notification has been handled by WonderPush
"""
try {
WonderPush.ensureInitialized(context);
WonderPush.logDebug("Received a push notification!");
NotificationModel notif;
try {
notif = NotificationModel.fromRemoteMessage(message);
} catch (NotificationModel.NotTargetedForThisInstallationException ex) {
WonderPush.logDebug(ex.getMessage());
return true;
}
if (notif == null) {
return false;
}
NotificationManager.onReceivedNotification(context, message.toIntent(), notif);
return true;
} catch (Exception e) {
Log.e(TAG, "Unexpected error while handling FCM message from:" + message.getFrom() + " bundle:" + message.getData(), e);
}
return false;
} | java | public static boolean onMessageReceived(Context context, RemoteMessage message) {
try {
WonderPush.ensureInitialized(context);
WonderPush.logDebug("Received a push notification!");
NotificationModel notif;
try {
notif = NotificationModel.fromRemoteMessage(message);
} catch (NotificationModel.NotTargetedForThisInstallationException ex) {
WonderPush.logDebug(ex.getMessage());
return true;
}
if (notif == null) {
return false;
}
NotificationManager.onReceivedNotification(context, message.toIntent(), notif);
return true;
} catch (Exception e) {
Log.e(TAG, "Unexpected error while handling FCM message from:" + message.getFrom() + " bundle:" + message.getData(), e);
}
return false;
} | [
"public",
"static",
"boolean",
"onMessageReceived",
"(",
"Context",
"context",
",",
"RemoteMessage",
"message",
")",
"{",
"try",
"{",
"WonderPush",
".",
"ensureInitialized",
"(",
"context",
")",
";",
"WonderPush",
".",
"logDebug",
"(",
"\"Received a push notification!\"",
")",
";",
"NotificationModel",
"notif",
";",
"try",
"{",
"notif",
"=",
"NotificationModel",
".",
"fromRemoteMessage",
"(",
"message",
")",
";",
"}",
"catch",
"(",
"NotificationModel",
".",
"NotTargetedForThisInstallationException",
"ex",
")",
"{",
"WonderPush",
".",
"logDebug",
"(",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"return",
"true",
";",
"}",
"if",
"(",
"notif",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"NotificationManager",
".",
"onReceivedNotification",
"(",
"context",
",",
"message",
".",
"toIntent",
"(",
")",
",",
"notif",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"Log",
".",
"e",
"(",
"TAG",
",",
"\"Unexpected error while handling FCM message from:\"",
"+",
"message",
".",
"getFrom",
"(",
")",
"+",
"\" bundle:\"",
"+",
"message",
".",
"getData",
"(",
")",
",",
"e",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Method to be called in your own {@link FirebaseMessagingService} to handle
WonderPush push notifications.
<b>Note:</b> This is only required if you use your own {@link FirebaseMessagingService}.
Implement your {@link FirebaseMessagingService#onMessageReceived(RemoteMessage)} method as follows:
<pre><code>@Override
public void onMessageReceived(RemoteMessage message) {
if (WonderPushFirebaseMessagingService.onMessageReceived(this, message)) {
return;
}
// Do your own handling here
}</code></pre>
@param context The current context
@param message The received message
@return Whether the notification has been handled by WonderPush | [
"Method",
"to",
"be",
"called",
"in",
"your",
"own",
"{",
"@link",
"FirebaseMessagingService",
"}",
"to",
"handle",
"WonderPush",
"push",
"notifications",
"."
] | train | https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushFirebaseMessagingService.java#L142-L164 |
petergeneric/stdlib | service-manager/configuration/src/main/java/com/peterphi/configuration/service/git/ConfigRepository.java | ConfigRepository.set | public void set(final String name,
final String email,
final Map<String, Map<String, ConfigPropertyValue>> data,
final ConfigChangeMode changeMode,
final String message) {
"""
Create a new commit reflecting the provided properties
@param name
@param email
@param data
@param erase
if true all existing properties will be erased
@param message
"""
try
{
RepoHelper.write(repo, name, email, data, changeMode, message);
}
catch (Exception e)
{
try
{
RepoHelper.reset(repo);
}
catch (Exception ee)
{
throw new RuntimeException("Error writing updated repository, then could not reset work tree", e);
}
throw new RuntimeException("Error writing updated repository, work tree reset", e);
}
// Push the changes to the remote
if (hasRemote)
{
try
{
RepoHelper.push(repo, "origin", credentials);
}
catch (Throwable t)
{
throw new RuntimeException("Saved changes to the local repository but push to remote failed!", t);
}
}
} | java | public void set(final String name,
final String email,
final Map<String, Map<String, ConfigPropertyValue>> data,
final ConfigChangeMode changeMode,
final String message)
{
try
{
RepoHelper.write(repo, name, email, data, changeMode, message);
}
catch (Exception e)
{
try
{
RepoHelper.reset(repo);
}
catch (Exception ee)
{
throw new RuntimeException("Error writing updated repository, then could not reset work tree", e);
}
throw new RuntimeException("Error writing updated repository, work tree reset", e);
}
// Push the changes to the remote
if (hasRemote)
{
try
{
RepoHelper.push(repo, "origin", credentials);
}
catch (Throwable t)
{
throw new RuntimeException("Saved changes to the local repository but push to remote failed!", t);
}
}
} | [
"public",
"void",
"set",
"(",
"final",
"String",
"name",
",",
"final",
"String",
"email",
",",
"final",
"Map",
"<",
"String",
",",
"Map",
"<",
"String",
",",
"ConfigPropertyValue",
">",
">",
"data",
",",
"final",
"ConfigChangeMode",
"changeMode",
",",
"final",
"String",
"message",
")",
"{",
"try",
"{",
"RepoHelper",
".",
"write",
"(",
"repo",
",",
"name",
",",
"email",
",",
"data",
",",
"changeMode",
",",
"message",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"try",
"{",
"RepoHelper",
".",
"reset",
"(",
"repo",
")",
";",
"}",
"catch",
"(",
"Exception",
"ee",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Error writing updated repository, then could not reset work tree\"",
",",
"e",
")",
";",
"}",
"throw",
"new",
"RuntimeException",
"(",
"\"Error writing updated repository, work tree reset\"",
",",
"e",
")",
";",
"}",
"// Push the changes to the remote",
"if",
"(",
"hasRemote",
")",
"{",
"try",
"{",
"RepoHelper",
".",
"push",
"(",
"repo",
",",
"\"origin\"",
",",
"credentials",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Saved changes to the local repository but push to remote failed!\"",
",",
"t",
")",
";",
"}",
"}",
"}"
] | Create a new commit reflecting the provided properties
@param name
@param email
@param data
@param erase
if true all existing properties will be erased
@param message | [
"Create",
"a",
"new",
"commit",
"reflecting",
"the",
"provided",
"properties"
] | train | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/service-manager/configuration/src/main/java/com/peterphi/configuration/service/git/ConfigRepository.java#L101-L137 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringHelper.java | StringHelper.iterateChars | public static void iterateChars (@Nullable final String sInputString, @Nonnull final ICharConsumer aConsumer) {
"""
Iterate all characters and pass them to the provided consumer.
@param sInputString
Input String to use. May be <code>null</code> or empty.
@param aConsumer
The consumer to be used. May not be <code>null</code>.
"""
ValueEnforcer.notNull (aConsumer, "Consumer");
if (sInputString != null)
{
final char [] aInput = sInputString.toCharArray ();
for (final char cInput : aInput)
aConsumer.accept (cInput);
}
} | java | public static void iterateChars (@Nullable final String sInputString, @Nonnull final ICharConsumer aConsumer)
{
ValueEnforcer.notNull (aConsumer, "Consumer");
if (sInputString != null)
{
final char [] aInput = sInputString.toCharArray ();
for (final char cInput : aInput)
aConsumer.accept (cInput);
}
} | [
"public",
"static",
"void",
"iterateChars",
"(",
"@",
"Nullable",
"final",
"String",
"sInputString",
",",
"@",
"Nonnull",
"final",
"ICharConsumer",
"aConsumer",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"aConsumer",
",",
"\"Consumer\"",
")",
";",
"if",
"(",
"sInputString",
"!=",
"null",
")",
"{",
"final",
"char",
"[",
"]",
"aInput",
"=",
"sInputString",
".",
"toCharArray",
"(",
")",
";",
"for",
"(",
"final",
"char",
"cInput",
":",
"aInput",
")",
"aConsumer",
".",
"accept",
"(",
"cInput",
")",
";",
"}",
"}"
] | Iterate all characters and pass them to the provided consumer.
@param sInputString
Input String to use. May be <code>null</code> or empty.
@param aConsumer
The consumer to be used. May not be <code>null</code>. | [
"Iterate",
"all",
"characters",
"and",
"pass",
"them",
"to",
"the",
"provided",
"consumer",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L5225-L5235 |
VoltDB/voltdb | src/frontend/org/voltcore/zk/CoreZK.java | CoreZK.removeJoinNodeIndicatorForHost | public static boolean removeJoinNodeIndicatorForHost(ZooKeeper zk, int hostId) {
"""
Removes the join indicator for the given host ID.
@return true if the indicator is removed successfully, false otherwise.
"""
try {
Stat stat = new Stat();
String path = ZKUtil.joinZKPath(readyjoininghosts, Integer.toString(hostId));
zk.getData(path, false, stat);
zk.delete(path, stat.getVersion());
return true;
} catch (KeeperException e) {
if (e.code() == KeeperException.Code.NONODE ||
e.code() == KeeperException.Code.BADVERSION) {
// Okay if the join indicator for the given hostId is already gone.
return true;
}
} catch (InterruptedException e) {
return false;
}
return false;
} | java | public static boolean removeJoinNodeIndicatorForHost(ZooKeeper zk, int hostId)
{
try {
Stat stat = new Stat();
String path = ZKUtil.joinZKPath(readyjoininghosts, Integer.toString(hostId));
zk.getData(path, false, stat);
zk.delete(path, stat.getVersion());
return true;
} catch (KeeperException e) {
if (e.code() == KeeperException.Code.NONODE ||
e.code() == KeeperException.Code.BADVERSION) {
// Okay if the join indicator for the given hostId is already gone.
return true;
}
} catch (InterruptedException e) {
return false;
}
return false;
} | [
"public",
"static",
"boolean",
"removeJoinNodeIndicatorForHost",
"(",
"ZooKeeper",
"zk",
",",
"int",
"hostId",
")",
"{",
"try",
"{",
"Stat",
"stat",
"=",
"new",
"Stat",
"(",
")",
";",
"String",
"path",
"=",
"ZKUtil",
".",
"joinZKPath",
"(",
"readyjoininghosts",
",",
"Integer",
".",
"toString",
"(",
"hostId",
")",
")",
";",
"zk",
".",
"getData",
"(",
"path",
",",
"false",
",",
"stat",
")",
";",
"zk",
".",
"delete",
"(",
"path",
",",
"stat",
".",
"getVersion",
"(",
")",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"KeeperException",
"e",
")",
"{",
"if",
"(",
"e",
".",
"code",
"(",
")",
"==",
"KeeperException",
".",
"Code",
".",
"NONODE",
"||",
"e",
".",
"code",
"(",
")",
"==",
"KeeperException",
".",
"Code",
".",
"BADVERSION",
")",
"{",
"// Okay if the join indicator for the given hostId is already gone.",
"return",
"true",
";",
"}",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"return",
"false",
";",
"}",
"return",
"false",
";",
"}"
] | Removes the join indicator for the given host ID.
@return true if the indicator is removed successfully, false otherwise. | [
"Removes",
"the",
"join",
"indicator",
"for",
"the",
"given",
"host",
"ID",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltcore/zk/CoreZK.java#L168-L186 |
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.updateCompositeEntityAsync | public Observable<OperationStatus> updateCompositeEntityAsync(UUID appId, String versionId, UUID cEntityId, CompositeEntityModel compositeModelUpdateObject) {
"""
Updates the composite entity extractor.
@param appId The application ID.
@param versionId The version ID.
@param cEntityId The composite entity extractor ID.
@param compositeModelUpdateObject A model object containing the new entity extractor name and children.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the OperationStatus object
"""
return updateCompositeEntityWithServiceResponseAsync(appId, versionId, cEntityId, compositeModelUpdateObject).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
} | java | public Observable<OperationStatus> updateCompositeEntityAsync(UUID appId, String versionId, UUID cEntityId, CompositeEntityModel compositeModelUpdateObject) {
return updateCompositeEntityWithServiceResponseAsync(appId, versionId, cEntityId, compositeModelUpdateObject).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"OperationStatus",
">",
"updateCompositeEntityAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"cEntityId",
",",
"CompositeEntityModel",
"compositeModelUpdateObject",
")",
"{",
"return",
"updateCompositeEntityWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"cEntityId",
",",
"compositeModelUpdateObject",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"OperationStatus",
">",
",",
"OperationStatus",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"OperationStatus",
"call",
"(",
"ServiceResponse",
"<",
"OperationStatus",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Updates the composite entity extractor.
@param appId The application ID.
@param versionId The version ID.
@param cEntityId The composite entity extractor ID.
@param compositeModelUpdateObject A model object containing the new entity extractor name and children.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the OperationStatus object | [
"Updates",
"the",
"composite",
"entity",
"extractor",
"."
] | 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#L4058-L4065 |
alkacon/opencms-core | src/org/opencms/widgets/CmsLocationPickerWidget.java | CmsLocationPickerWidget.getApiKey | private String getApiKey(CmsObject cms, String sitePath) throws CmsException {
"""
Get the correct google api key.
Tries to read a workplace key first.
@param cms CmsObject
@param sitePath site path
@return key value
@throws CmsException exception
"""
String res = cms.readPropertyObject(
sitePath,
CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY_WORKPLACE,
true).getValue();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(res)) {
res = cms.readPropertyObject(sitePath, CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY, true).getValue();
}
return res;
} | java | private String getApiKey(CmsObject cms, String sitePath) throws CmsException {
String res = cms.readPropertyObject(
sitePath,
CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY_WORKPLACE,
true).getValue();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(res)) {
res = cms.readPropertyObject(sitePath, CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY, true).getValue();
}
return res;
} | [
"private",
"String",
"getApiKey",
"(",
"CmsObject",
"cms",
",",
"String",
"sitePath",
")",
"throws",
"CmsException",
"{",
"String",
"res",
"=",
"cms",
".",
"readPropertyObject",
"(",
"sitePath",
",",
"CmsPropertyDefinition",
".",
"PROPERTY_GOOGLE_API_KEY_WORKPLACE",
",",
"true",
")",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"CmsStringUtil",
".",
"isEmptyOrWhitespaceOnly",
"(",
"res",
")",
")",
"{",
"res",
"=",
"cms",
".",
"readPropertyObject",
"(",
"sitePath",
",",
"CmsPropertyDefinition",
".",
"PROPERTY_GOOGLE_API_KEY",
",",
"true",
")",
".",
"getValue",
"(",
")",
";",
"}",
"return",
"res",
";",
"}"
] | Get the correct google api key.
Tries to read a workplace key first.
@param cms CmsObject
@param sitePath site path
@return key value
@throws CmsException exception | [
"Get",
"the",
"correct",
"google",
"api",
"key",
".",
"Tries",
"to",
"read",
"a",
"workplace",
"key",
"first",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/widgets/CmsLocationPickerWidget.java#L309-L321 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WMultiTextFieldRenderer.java | WMultiTextFieldRenderer.doRender | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
"""
Paints the given WMultiTextField.
@param component the WMultiTextField to paint.
@param renderContext the RenderContext to paint to.
"""
WMultiTextField textField = (WMultiTextField) component;
XmlStringBuilder xml = renderContext.getWriter();
boolean readOnly = textField.isReadOnly();
String[] values = textField.getTextInputs();
xml.appendTagOpen("ui:multitextfield");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
xml.appendOptionalAttribute("hidden", textField.isHidden(), "true");
if (readOnly) {
xml.appendAttribute("readOnly", "true");
} else {
int cols = textField.getColumns();
int minLength = textField.getMinLength();
int maxLength = textField.getMaxLength();
int maxInputs = textField.getMaxInputs();
String pattern = textField.getPattern();
xml.appendOptionalAttribute("disabled", textField.isDisabled(), "true");
xml.appendOptionalAttribute("required", textField.isMandatory(), "true");
xml.appendOptionalAttribute("toolTip", textField.getToolTip());
xml.appendOptionalAttribute("accessibleText", textField.getAccessibleText());
xml.appendOptionalAttribute("size", cols > 0, cols);
xml.appendOptionalAttribute("minLength", minLength > 0, minLength);
xml.appendOptionalAttribute("maxLength", maxLength > 0, maxLength);
xml.appendOptionalAttribute("max", maxInputs > 0, maxInputs);
xml.appendOptionalAttribute("pattern", !Util.empty(pattern), pattern);
// NOTE: do not use HtmlRenderUtil.getEffectivePlaceholder for placeholder - we do not want to echo "required" in every field.
String placeholder = textField.getPlaceholder();
xml.appendOptionalAttribute("placeholder", !Util.empty(placeholder), placeholder);
xml.appendOptionalAttribute("title", I18nUtilities.format(null, InternalMessages.DEFAULT_MULTITEXTFIELD_TIP));
}
xml.appendClose();
if (values != null) {
for (String value : values) {
xml.appendTag("ui:value");
xml.appendEscaped(value);
xml.appendEndTag("ui:value");
}
}
if (!readOnly) {
DiagnosticRenderUtil.renderDiagnostics(textField, renderContext);
}
xml.appendEndTag("ui:multitextfield");
} | java | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WMultiTextField textField = (WMultiTextField) component;
XmlStringBuilder xml = renderContext.getWriter();
boolean readOnly = textField.isReadOnly();
String[] values = textField.getTextInputs();
xml.appendTagOpen("ui:multitextfield");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
xml.appendOptionalAttribute("hidden", textField.isHidden(), "true");
if (readOnly) {
xml.appendAttribute("readOnly", "true");
} else {
int cols = textField.getColumns();
int minLength = textField.getMinLength();
int maxLength = textField.getMaxLength();
int maxInputs = textField.getMaxInputs();
String pattern = textField.getPattern();
xml.appendOptionalAttribute("disabled", textField.isDisabled(), "true");
xml.appendOptionalAttribute("required", textField.isMandatory(), "true");
xml.appendOptionalAttribute("toolTip", textField.getToolTip());
xml.appendOptionalAttribute("accessibleText", textField.getAccessibleText());
xml.appendOptionalAttribute("size", cols > 0, cols);
xml.appendOptionalAttribute("minLength", minLength > 0, minLength);
xml.appendOptionalAttribute("maxLength", maxLength > 0, maxLength);
xml.appendOptionalAttribute("max", maxInputs > 0, maxInputs);
xml.appendOptionalAttribute("pattern", !Util.empty(pattern), pattern);
// NOTE: do not use HtmlRenderUtil.getEffectivePlaceholder for placeholder - we do not want to echo "required" in every field.
String placeholder = textField.getPlaceholder();
xml.appendOptionalAttribute("placeholder", !Util.empty(placeholder), placeholder);
xml.appendOptionalAttribute("title", I18nUtilities.format(null, InternalMessages.DEFAULT_MULTITEXTFIELD_TIP));
}
xml.appendClose();
if (values != null) {
for (String value : values) {
xml.appendTag("ui:value");
xml.appendEscaped(value);
xml.appendEndTag("ui:value");
}
}
if (!readOnly) {
DiagnosticRenderUtil.renderDiagnostics(textField, renderContext);
}
xml.appendEndTag("ui:multitextfield");
} | [
"@",
"Override",
"public",
"void",
"doRender",
"(",
"final",
"WComponent",
"component",
",",
"final",
"WebXmlRenderContext",
"renderContext",
")",
"{",
"WMultiTextField",
"textField",
"=",
"(",
"WMultiTextField",
")",
"component",
";",
"XmlStringBuilder",
"xml",
"=",
"renderContext",
".",
"getWriter",
"(",
")",
";",
"boolean",
"readOnly",
"=",
"textField",
".",
"isReadOnly",
"(",
")",
";",
"String",
"[",
"]",
"values",
"=",
"textField",
".",
"getTextInputs",
"(",
")",
";",
"xml",
".",
"appendTagOpen",
"(",
"\"ui:multitextfield\"",
")",
";",
"xml",
".",
"appendAttribute",
"(",
"\"id\"",
",",
"component",
".",
"getId",
"(",
")",
")",
";",
"xml",
".",
"appendOptionalAttribute",
"(",
"\"class\"",
",",
"component",
".",
"getHtmlClass",
"(",
")",
")",
";",
"xml",
".",
"appendOptionalAttribute",
"(",
"\"track\"",
",",
"component",
".",
"isTracking",
"(",
")",
",",
"\"true\"",
")",
";",
"xml",
".",
"appendOptionalAttribute",
"(",
"\"hidden\"",
",",
"textField",
".",
"isHidden",
"(",
")",
",",
"\"true\"",
")",
";",
"if",
"(",
"readOnly",
")",
"{",
"xml",
".",
"appendAttribute",
"(",
"\"readOnly\"",
",",
"\"true\"",
")",
";",
"}",
"else",
"{",
"int",
"cols",
"=",
"textField",
".",
"getColumns",
"(",
")",
";",
"int",
"minLength",
"=",
"textField",
".",
"getMinLength",
"(",
")",
";",
"int",
"maxLength",
"=",
"textField",
".",
"getMaxLength",
"(",
")",
";",
"int",
"maxInputs",
"=",
"textField",
".",
"getMaxInputs",
"(",
")",
";",
"String",
"pattern",
"=",
"textField",
".",
"getPattern",
"(",
")",
";",
"xml",
".",
"appendOptionalAttribute",
"(",
"\"disabled\"",
",",
"textField",
".",
"isDisabled",
"(",
")",
",",
"\"true\"",
")",
";",
"xml",
".",
"appendOptionalAttribute",
"(",
"\"required\"",
",",
"textField",
".",
"isMandatory",
"(",
")",
",",
"\"true\"",
")",
";",
"xml",
".",
"appendOptionalAttribute",
"(",
"\"toolTip\"",
",",
"textField",
".",
"getToolTip",
"(",
")",
")",
";",
"xml",
".",
"appendOptionalAttribute",
"(",
"\"accessibleText\"",
",",
"textField",
".",
"getAccessibleText",
"(",
")",
")",
";",
"xml",
".",
"appendOptionalAttribute",
"(",
"\"size\"",
",",
"cols",
">",
"0",
",",
"cols",
")",
";",
"xml",
".",
"appendOptionalAttribute",
"(",
"\"minLength\"",
",",
"minLength",
">",
"0",
",",
"minLength",
")",
";",
"xml",
".",
"appendOptionalAttribute",
"(",
"\"maxLength\"",
",",
"maxLength",
">",
"0",
",",
"maxLength",
")",
";",
"xml",
".",
"appendOptionalAttribute",
"(",
"\"max\"",
",",
"maxInputs",
">",
"0",
",",
"maxInputs",
")",
";",
"xml",
".",
"appendOptionalAttribute",
"(",
"\"pattern\"",
",",
"!",
"Util",
".",
"empty",
"(",
"pattern",
")",
",",
"pattern",
")",
";",
"// NOTE: do not use HtmlRenderUtil.getEffectivePlaceholder for placeholder - we do not want to echo \"required\" in every field.",
"String",
"placeholder",
"=",
"textField",
".",
"getPlaceholder",
"(",
")",
";",
"xml",
".",
"appendOptionalAttribute",
"(",
"\"placeholder\"",
",",
"!",
"Util",
".",
"empty",
"(",
"placeholder",
")",
",",
"placeholder",
")",
";",
"xml",
".",
"appendOptionalAttribute",
"(",
"\"title\"",
",",
"I18nUtilities",
".",
"format",
"(",
"null",
",",
"InternalMessages",
".",
"DEFAULT_MULTITEXTFIELD_TIP",
")",
")",
";",
"}",
"xml",
".",
"appendClose",
"(",
")",
";",
"if",
"(",
"values",
"!=",
"null",
")",
"{",
"for",
"(",
"String",
"value",
":",
"values",
")",
"{",
"xml",
".",
"appendTag",
"(",
"\"ui:value\"",
")",
";",
"xml",
".",
"appendEscaped",
"(",
"value",
")",
";",
"xml",
".",
"appendEndTag",
"(",
"\"ui:value\"",
")",
";",
"}",
"}",
"if",
"(",
"!",
"readOnly",
")",
"{",
"DiagnosticRenderUtil",
".",
"renderDiagnostics",
"(",
"textField",
",",
"renderContext",
")",
";",
"}",
"xml",
".",
"appendEndTag",
"(",
"\"ui:multitextfield\"",
")",
";",
"}"
] | Paints the given WMultiTextField.
@param component the WMultiTextField to paint.
@param renderContext the RenderContext to paint to. | [
"Paints",
"the",
"given",
"WMultiTextField",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WMultiTextFieldRenderer.java#L27-L78 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/listeners/CollectScoresIterationListener.java | CollectScoresIterationListener.exportScores | public void exportScores(OutputStream outputStream, String delimiter) throws IOException {
"""
Export the scores in delimited (one per line) UTF-8 format with the specified delimiter
@param outputStream Stream to write to
@param delimiter Delimiter to use
"""
StringBuilder sb = new StringBuilder();
sb.append("Iteration").append(delimiter).append("Score");
for (Pair<Integer, Double> p : scoreVsIter) {
sb.append("\n").append(p.getFirst()).append(delimiter).append(p.getSecond());
}
outputStream.write(sb.toString().getBytes("UTF-8"));
} | java | public void exportScores(OutputStream outputStream, String delimiter) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("Iteration").append(delimiter).append("Score");
for (Pair<Integer, Double> p : scoreVsIter) {
sb.append("\n").append(p.getFirst()).append(delimiter).append(p.getSecond());
}
outputStream.write(sb.toString().getBytes("UTF-8"));
} | [
"public",
"void",
"exportScores",
"(",
"OutputStream",
"outputStream",
",",
"String",
"delimiter",
")",
"throws",
"IOException",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"\"Iteration\"",
")",
".",
"append",
"(",
"delimiter",
")",
".",
"append",
"(",
"\"Score\"",
")",
";",
"for",
"(",
"Pair",
"<",
"Integer",
",",
"Double",
">",
"p",
":",
"scoreVsIter",
")",
"{",
"sb",
".",
"append",
"(",
"\"\\n\"",
")",
".",
"append",
"(",
"p",
".",
"getFirst",
"(",
")",
")",
".",
"append",
"(",
"delimiter",
")",
".",
"append",
"(",
"p",
".",
"getSecond",
"(",
")",
")",
";",
"}",
"outputStream",
".",
"write",
"(",
"sb",
".",
"toString",
"(",
")",
".",
"getBytes",
"(",
"\"UTF-8\"",
")",
")",
";",
"}"
] | Export the scores in delimited (one per line) UTF-8 format with the specified delimiter
@param outputStream Stream to write to
@param delimiter Delimiter to use | [
"Export",
"the",
"scores",
"in",
"delimited",
"(",
"one",
"per",
"line",
")",
"UTF",
"-",
"8",
"format",
"with",
"the",
"specified",
"delimiter"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/listeners/CollectScoresIterationListener.java#L84-L91 |
groovy/groovy-core | src/main/org/codehaus/groovy/ast/ClassNode.java | ClassNode.hasPossibleMethod | public boolean hasPossibleMethod(String name, Expression arguments) {
"""
Returns true if the given method has a possibly matching instance method with the given name and arguments.
@param name the name of the method of interest
@param arguments the arguments to match against
@return true if a matching method was found
"""
int count = 0;
if (arguments instanceof TupleExpression) {
TupleExpression tuple = (TupleExpression) arguments;
// TODO this won't strictly be true when using list expansion in argument calls
count = tuple.getExpressions().size();
}
ClassNode node = this;
do {
for (MethodNode method : getMethods(name)) {
if (method.getParameters().length == count && !method.isStatic()) {
return true;
}
}
node = node.getSuperClass();
}
while (node != null);
return false;
} | java | public boolean hasPossibleMethod(String name, Expression arguments) {
int count = 0;
if (arguments instanceof TupleExpression) {
TupleExpression tuple = (TupleExpression) arguments;
// TODO this won't strictly be true when using list expansion in argument calls
count = tuple.getExpressions().size();
}
ClassNode node = this;
do {
for (MethodNode method : getMethods(name)) {
if (method.getParameters().length == count && !method.isStatic()) {
return true;
}
}
node = node.getSuperClass();
}
while (node != null);
return false;
} | [
"public",
"boolean",
"hasPossibleMethod",
"(",
"String",
"name",
",",
"Expression",
"arguments",
")",
"{",
"int",
"count",
"=",
"0",
";",
"if",
"(",
"arguments",
"instanceof",
"TupleExpression",
")",
"{",
"TupleExpression",
"tuple",
"=",
"(",
"TupleExpression",
")",
"arguments",
";",
"// TODO this won't strictly be true when using list expansion in argument calls",
"count",
"=",
"tuple",
".",
"getExpressions",
"(",
")",
".",
"size",
"(",
")",
";",
"}",
"ClassNode",
"node",
"=",
"this",
";",
"do",
"{",
"for",
"(",
"MethodNode",
"method",
":",
"getMethods",
"(",
"name",
")",
")",
"{",
"if",
"(",
"method",
".",
"getParameters",
"(",
")",
".",
"length",
"==",
"count",
"&&",
"!",
"method",
".",
"isStatic",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"node",
"=",
"node",
".",
"getSuperClass",
"(",
")",
";",
"}",
"while",
"(",
"node",
"!=",
"null",
")",
";",
"return",
"false",
";",
"}"
] | Returns true if the given method has a possibly matching instance method with the given name and arguments.
@param name the name of the method of interest
@param arguments the arguments to match against
@return true if a matching method was found | [
"Returns",
"true",
"if",
"the",
"given",
"method",
"has",
"a",
"possibly",
"matching",
"instance",
"method",
"with",
"the",
"given",
"name",
"and",
"arguments",
"."
] | train | https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/ast/ClassNode.java#L1221-L1240 |
pryzach/midao | midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/utils/CallableUtils.java | CallableUtils.updateDirectionsByName | public static QueryParameters updateDirectionsByName(QueryParameters original, QueryParameters source) {
"""
Same as @updateDirections but updates based not on position but on key
@param original QueryParameters which would be updated
@param source QueryParameters directions of which would be read
@return updated clone on @original with updated directions
"""
QueryParameters updatedParams = new QueryParameters(original);
if (source != null) {
for (String sourceKey : source.keySet()) {
if (updatedParams.containsKey(sourceKey) == true) {
updatedParams.updateDirection(sourceKey, source.getDirection(sourceKey));
}
}
}
return updatedParams;
} | java | public static QueryParameters updateDirectionsByName(QueryParameters original, QueryParameters source) {
QueryParameters updatedParams = new QueryParameters(original);
if (source != null) {
for (String sourceKey : source.keySet()) {
if (updatedParams.containsKey(sourceKey) == true) {
updatedParams.updateDirection(sourceKey, source.getDirection(sourceKey));
}
}
}
return updatedParams;
} | [
"public",
"static",
"QueryParameters",
"updateDirectionsByName",
"(",
"QueryParameters",
"original",
",",
"QueryParameters",
"source",
")",
"{",
"QueryParameters",
"updatedParams",
"=",
"new",
"QueryParameters",
"(",
"original",
")",
";",
"if",
"(",
"source",
"!=",
"null",
")",
"{",
"for",
"(",
"String",
"sourceKey",
":",
"source",
".",
"keySet",
"(",
")",
")",
"{",
"if",
"(",
"updatedParams",
".",
"containsKey",
"(",
"sourceKey",
")",
"==",
"true",
")",
"{",
"updatedParams",
".",
"updateDirection",
"(",
"sourceKey",
",",
"source",
".",
"getDirection",
"(",
"sourceKey",
")",
")",
";",
"}",
"}",
"}",
"return",
"updatedParams",
";",
"}"
] | Same as @updateDirections but updates based not on position but on key
@param original QueryParameters which would be updated
@param source QueryParameters directions of which would be read
@return updated clone on @original with updated directions | [
"Same",
"as",
"@updateDirections",
"but",
"updates",
"based",
"not",
"on",
"position",
"but",
"on",
"key"
] | train | https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/utils/CallableUtils.java#L168-L180 |
fozziethebeat/S-Space | src/main/java/edu/ucla/sspace/util/Properties.java | Properties.getProperty | @SuppressWarnings("unchecked")
public <T> T getProperty(String propName, T defaultValue) {
"""
Returns a class instance of the property associated with {@code propName},
or {@code defaultValue} if there is no property. This method assumes that
the class has a no argument constructor.
"""
String propValue = props.getProperty(propName);
if (propValue == null)
return defaultValue;
return ReflectionUtil.<T>getObjectInstance(propValue);
} | java | @SuppressWarnings("unchecked")
public <T> T getProperty(String propName, T defaultValue) {
String propValue = props.getProperty(propName);
if (propValue == null)
return defaultValue;
return ReflectionUtil.<T>getObjectInstance(propValue);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
">",
"T",
"getProperty",
"(",
"String",
"propName",
",",
"T",
"defaultValue",
")",
"{",
"String",
"propValue",
"=",
"props",
".",
"getProperty",
"(",
"propName",
")",
";",
"if",
"(",
"propValue",
"==",
"null",
")",
"return",
"defaultValue",
";",
"return",
"ReflectionUtil",
".",
"<",
"T",
">",
"getObjectInstance",
"(",
"propValue",
")",
";",
"}"
] | Returns a class instance of the property associated with {@code propName},
or {@code defaultValue} if there is no property. This method assumes that
the class has a no argument constructor. | [
"Returns",
"a",
"class",
"instance",
"of",
"the",
"property",
"associated",
"with",
"{"
] | train | https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/util/Properties.java#L92-L98 |
cdk/cdk | base/standard/src/main/java/org/openscience/cdk/tools/manipulator/ReactionSetManipulator.java | ReactionSetManipulator.getRelevantReactions | public static IReactionSet getRelevantReactions(IReactionSet reactSet, IAtomContainer molecule) {
"""
Get all Reactions object containing a Molecule from a set of Reactions.
@param reactSet The set of reaction to inspect
@param molecule The molecule to find
@return The IReactionSet
"""
IReactionSet newReactSet = reactSet.getBuilder().newInstance(IReactionSet.class);
IReactionSet reactSetProd = getRelevantReactionsAsProduct(reactSet, molecule);
for (IReaction reaction : reactSetProd.reactions())
newReactSet.addReaction(reaction);
IReactionSet reactSetReact = getRelevantReactionsAsReactant(reactSet, molecule);
for (IReaction reaction : reactSetReact.reactions())
newReactSet.addReaction(reaction);
return newReactSet;
} | java | public static IReactionSet getRelevantReactions(IReactionSet reactSet, IAtomContainer molecule) {
IReactionSet newReactSet = reactSet.getBuilder().newInstance(IReactionSet.class);
IReactionSet reactSetProd = getRelevantReactionsAsProduct(reactSet, molecule);
for (IReaction reaction : reactSetProd.reactions())
newReactSet.addReaction(reaction);
IReactionSet reactSetReact = getRelevantReactionsAsReactant(reactSet, molecule);
for (IReaction reaction : reactSetReact.reactions())
newReactSet.addReaction(reaction);
return newReactSet;
} | [
"public",
"static",
"IReactionSet",
"getRelevantReactions",
"(",
"IReactionSet",
"reactSet",
",",
"IAtomContainer",
"molecule",
")",
"{",
"IReactionSet",
"newReactSet",
"=",
"reactSet",
".",
"getBuilder",
"(",
")",
".",
"newInstance",
"(",
"IReactionSet",
".",
"class",
")",
";",
"IReactionSet",
"reactSetProd",
"=",
"getRelevantReactionsAsProduct",
"(",
"reactSet",
",",
"molecule",
")",
";",
"for",
"(",
"IReaction",
"reaction",
":",
"reactSetProd",
".",
"reactions",
"(",
")",
")",
"newReactSet",
".",
"addReaction",
"(",
"reaction",
")",
";",
"IReactionSet",
"reactSetReact",
"=",
"getRelevantReactionsAsReactant",
"(",
"reactSet",
",",
"molecule",
")",
";",
"for",
"(",
"IReaction",
"reaction",
":",
"reactSetReact",
".",
"reactions",
"(",
")",
")",
"newReactSet",
".",
"addReaction",
"(",
"reaction",
")",
";",
"return",
"newReactSet",
";",
"}"
] | Get all Reactions object containing a Molecule from a set of Reactions.
@param reactSet The set of reaction to inspect
@param molecule The molecule to find
@return The IReactionSet | [
"Get",
"all",
"Reactions",
"object",
"containing",
"a",
"Molecule",
"from",
"a",
"set",
"of",
"Reactions",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/tools/manipulator/ReactionSetManipulator.java#L144-L153 |
cvent/pangaea | src/main/java/com/cvent/pangaea/MultiEnvAware.java | MultiEnvAware.convert | public <R> MultiEnvAware<R> convert(BiFunction<String, T, R> func) {
"""
Utility method for MultiEnvAware config transformation
@param <R>
@param func - transformation function
@return new MultiEnvAware instance
"""
return convert(func, null);
} | java | public <R> MultiEnvAware<R> convert(BiFunction<String, T, R> func) {
return convert(func, null);
} | [
"public",
"<",
"R",
">",
"MultiEnvAware",
"<",
"R",
">",
"convert",
"(",
"BiFunction",
"<",
"String",
",",
"T",
",",
"R",
">",
"func",
")",
"{",
"return",
"convert",
"(",
"func",
",",
"null",
")",
";",
"}"
] | Utility method for MultiEnvAware config transformation
@param <R>
@param func - transformation function
@return new MultiEnvAware instance | [
"Utility",
"method",
"for",
"MultiEnvAware",
"config",
"transformation"
] | train | https://github.com/cvent/pangaea/blob/6cd213c370817905ae04a67db07347a4e29a708c/src/main/java/com/cvent/pangaea/MultiEnvAware.java#L45-L47 |
Netflix/spectator | spectator-ext-jvm/src/main/java/com/netflix/spectator/jvm/Jmx.java | Jmx.registerStandardMXBeans | public static void registerStandardMXBeans(Registry registry) {
"""
Add meters for the standard MXBeans provided by the jvm. This method will use
{@link java.lang.management.ManagementFactory#getPlatformMXBeans(Class)} to get the set of
mbeans from the local jvm.
"""
for (MemoryPoolMXBean mbean : ManagementFactory.getPlatformMXBeans(MemoryPoolMXBean.class)) {
registry.register(new MemoryPoolMeter(registry, mbean));
}
for (BufferPoolMXBean mbean : ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class)) {
registry.register(new BufferPoolMeter(registry, mbean));
}
} | java | public static void registerStandardMXBeans(Registry registry) {
for (MemoryPoolMXBean mbean : ManagementFactory.getPlatformMXBeans(MemoryPoolMXBean.class)) {
registry.register(new MemoryPoolMeter(registry, mbean));
}
for (BufferPoolMXBean mbean : ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class)) {
registry.register(new BufferPoolMeter(registry, mbean));
}
} | [
"public",
"static",
"void",
"registerStandardMXBeans",
"(",
"Registry",
"registry",
")",
"{",
"for",
"(",
"MemoryPoolMXBean",
"mbean",
":",
"ManagementFactory",
".",
"getPlatformMXBeans",
"(",
"MemoryPoolMXBean",
".",
"class",
")",
")",
"{",
"registry",
".",
"register",
"(",
"new",
"MemoryPoolMeter",
"(",
"registry",
",",
"mbean",
")",
")",
";",
"}",
"for",
"(",
"BufferPoolMXBean",
"mbean",
":",
"ManagementFactory",
".",
"getPlatformMXBeans",
"(",
"BufferPoolMXBean",
".",
"class",
")",
")",
"{",
"registry",
".",
"register",
"(",
"new",
"BufferPoolMeter",
"(",
"registry",
",",
"mbean",
")",
")",
";",
"}",
"}"
] | Add meters for the standard MXBeans provided by the jvm. This method will use
{@link java.lang.management.ManagementFactory#getPlatformMXBeans(Class)} to get the set of
mbeans from the local jvm. | [
"Add",
"meters",
"for",
"the",
"standard",
"MXBeans",
"provided",
"by",
"the",
"jvm",
".",
"This",
"method",
"will",
"use",
"{"
] | train | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-jvm/src/main/java/com/netflix/spectator/jvm/Jmx.java#L38-L46 |
smartsheet-platform/smartsheet-java-sdk | src/main/java/com/smartsheet/api/internal/http/DefaultHttpClient.java | DefaultHttpClient.shouldRetry | public boolean shouldRetry(int previousAttempts, long totalElapsedTimeMillis, HttpResponse response) {
"""
Called when an API request fails to determine if it can retry the request.
Calls calcBackoff to determine the time to wait in between retries.
@param previousAttempts number of attempts (including this one) to execute request
@param totalElapsedTimeMillis total time spent in millis for all previous (and this) attempt
@param response the failed HttpResponse
@return true if this request can be retried
"""
String contentType = response.getEntity().getContentType();
if (contentType != null && !contentType.startsWith(JSON_MIME_TYPE)) {
// it's not JSON; don't even try to parse it
return false;
}
Error error;
try {
error = jsonSerializer.deserialize(Error.class, response.getEntity().getContent());
}
catch (IOException e) {
return false;
}
switch(error.getErrorCode()) {
case 4001: /** Smartsheet.com is currently offline for system maintenance. Please check back again shortly. */
case 4002: /** Server timeout exceeded. Request has failed */
case 4003: /** Rate limit exceeded. */
case 4004: /** An unexpected error has occurred. Please retry your request.
* If you encounter this error repeatedly, please contact api@smartsheet.com for assistance. */
break;
default:
return false;
}
long backoffMillis = calcBackoff(previousAttempts, totalElapsedTimeMillis, error);
if(backoffMillis < 0)
return false;
logger.info("HttpError StatusCode=" + response.getStatusCode() + ": Retrying in " + backoffMillis + " milliseconds");
try {
Thread.sleep(backoffMillis);
}
catch (InterruptedException e) {
logger.warn("sleep interrupted", e);
return false;
}
return true;
} | java | public boolean shouldRetry(int previousAttempts, long totalElapsedTimeMillis, HttpResponse response) {
String contentType = response.getEntity().getContentType();
if (contentType != null && !contentType.startsWith(JSON_MIME_TYPE)) {
// it's not JSON; don't even try to parse it
return false;
}
Error error;
try {
error = jsonSerializer.deserialize(Error.class, response.getEntity().getContent());
}
catch (IOException e) {
return false;
}
switch(error.getErrorCode()) {
case 4001: /** Smartsheet.com is currently offline for system maintenance. Please check back again shortly. */
case 4002: /** Server timeout exceeded. Request has failed */
case 4003: /** Rate limit exceeded. */
case 4004: /** An unexpected error has occurred. Please retry your request.
* If you encounter this error repeatedly, please contact api@smartsheet.com for assistance. */
break;
default:
return false;
}
long backoffMillis = calcBackoff(previousAttempts, totalElapsedTimeMillis, error);
if(backoffMillis < 0)
return false;
logger.info("HttpError StatusCode=" + response.getStatusCode() + ": Retrying in " + backoffMillis + " milliseconds");
try {
Thread.sleep(backoffMillis);
}
catch (InterruptedException e) {
logger.warn("sleep interrupted", e);
return false;
}
return true;
} | [
"public",
"boolean",
"shouldRetry",
"(",
"int",
"previousAttempts",
",",
"long",
"totalElapsedTimeMillis",
",",
"HttpResponse",
"response",
")",
"{",
"String",
"contentType",
"=",
"response",
".",
"getEntity",
"(",
")",
".",
"getContentType",
"(",
")",
";",
"if",
"(",
"contentType",
"!=",
"null",
"&&",
"!",
"contentType",
".",
"startsWith",
"(",
"JSON_MIME_TYPE",
")",
")",
"{",
"// it's not JSON; don't even try to parse it",
"return",
"false",
";",
"}",
"Error",
"error",
";",
"try",
"{",
"error",
"=",
"jsonSerializer",
".",
"deserialize",
"(",
"Error",
".",
"class",
",",
"response",
".",
"getEntity",
"(",
")",
".",
"getContent",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"return",
"false",
";",
"}",
"switch",
"(",
"error",
".",
"getErrorCode",
"(",
")",
")",
"{",
"case",
"4001",
":",
"/** Smartsheet.com is currently offline for system maintenance. Please check back again shortly. */",
"case",
"4002",
":",
"/** Server timeout exceeded. Request has failed */",
"case",
"4003",
":",
"/** Rate limit exceeded. */",
"case",
"4004",
":",
"/** An unexpected error has occurred. Please retry your request.\n * If you encounter this error repeatedly, please contact api@smartsheet.com for assistance. */",
"break",
";",
"default",
":",
"return",
"false",
";",
"}",
"long",
"backoffMillis",
"=",
"calcBackoff",
"(",
"previousAttempts",
",",
"totalElapsedTimeMillis",
",",
"error",
")",
";",
"if",
"(",
"backoffMillis",
"<",
"0",
")",
"return",
"false",
";",
"logger",
".",
"info",
"(",
"\"HttpError StatusCode=\"",
"+",
"response",
".",
"getStatusCode",
"(",
")",
"+",
"\": Retrying in \"",
"+",
"backoffMillis",
"+",
"\" milliseconds\"",
")",
";",
"try",
"{",
"Thread",
".",
"sleep",
"(",
"backoffMillis",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"logger",
".",
"warn",
"(",
"\"sleep interrupted\"",
",",
"e",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Called when an API request fails to determine if it can retry the request.
Calls calcBackoff to determine the time to wait in between retries.
@param previousAttempts number of attempts (including this one) to execute request
@param totalElapsedTimeMillis total time spent in millis for all previous (and this) attempt
@param response the failed HttpResponse
@return true if this request can be retried | [
"Called",
"when",
"an",
"API",
"request",
"fails",
"to",
"determine",
"if",
"it",
"can",
"retry",
"the",
"request",
".",
"Calls",
"calcBackoff",
"to",
"determine",
"the",
"time",
"to",
"wait",
"in",
"between",
"retries",
"."
] | train | https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/http/DefaultHttpClient.java#L440-L477 |
gliga/ekstazi | org.ekstazi.core/src/main/java/org/ekstazi/maven/AbstractMojoInterceptor.java | AbstractMojoInterceptor.invokeAndGetString | protected static String invokeAndGetString(String methodName, Object mojo) throws Exception {
"""
Gets String field value from the given mojo based on the given method
name.
"""
return (String) invokeGetMethod(methodName, mojo);
} | java | protected static String invokeAndGetString(String methodName, Object mojo) throws Exception {
return (String) invokeGetMethod(methodName, mojo);
} | [
"protected",
"static",
"String",
"invokeAndGetString",
"(",
"String",
"methodName",
",",
"Object",
"mojo",
")",
"throws",
"Exception",
"{",
"return",
"(",
"String",
")",
"invokeGetMethod",
"(",
"methodName",
",",
"mojo",
")",
";",
"}"
] | Gets String field value from the given mojo based on the given method
name. | [
"Gets",
"String",
"field",
"value",
"from",
"the",
"given",
"mojo",
"based",
"on",
"the",
"given",
"method",
"name",
"."
] | train | https://github.com/gliga/ekstazi/blob/5bf4d39a13305afe62f8b8d2d7b4c573d37d42a1/org.ekstazi.core/src/main/java/org/ekstazi/maven/AbstractMojoInterceptor.java#L91-L93 |