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
listlengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
listlengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
alkacon/opencms-core | src/org/opencms/search/documents/CmsDocumentXmlPage.java | CmsDocumentXmlPage.extractContent | public I_CmsExtractionResult extractContent(CmsObject cms, CmsResource resource, I_CmsSearchIndex index)
throws CmsException {
"""
Returns the raw text content of a given vfs resource of type <code>CmsResourceTypeXmlPage</code>.<p>
@see org.opencms.search.documents.I_CmsSearchExtractor#extractContent(CmsObject, CmsResource, I_CmsSearchIndex)
"""
logContentExtraction(resource, index);
try {
CmsFile file = readFile(cms, resource);
CmsXmlPage page = CmsXmlPageFactory.unmarshal(cms, file);
Locale locale = index.getLocaleForResource(cms, resource, page.getLocales());
List<String> elements = page.getNames(locale);
StringBuffer content = new StringBuffer();
LinkedHashMap<String, String> items = new LinkedHashMap<String, String>();
for (Iterator<String> i = elements.iterator(); i.hasNext();) {
String elementName = i.next();
String value = page.getStringValue(cms, elementName, locale);
String extracted = CmsHtmlExtractor.extractText(value, page.getEncoding());
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(extracted)) {
items.put(elementName, extracted);
content.append(extracted);
content.append('\n');
}
}
return new CmsExtractionResult(content.toString(), items);
} catch (Exception e) {
throw new CmsIndexException(
Messages.get().container(Messages.ERR_TEXT_EXTRACTION_1, resource.getRootPath()),
e);
}
} | java | public I_CmsExtractionResult extractContent(CmsObject cms, CmsResource resource, I_CmsSearchIndex index)
throws CmsException {
logContentExtraction(resource, index);
try {
CmsFile file = readFile(cms, resource);
CmsXmlPage page = CmsXmlPageFactory.unmarshal(cms, file);
Locale locale = index.getLocaleForResource(cms, resource, page.getLocales());
List<String> elements = page.getNames(locale);
StringBuffer content = new StringBuffer();
LinkedHashMap<String, String> items = new LinkedHashMap<String, String>();
for (Iterator<String> i = elements.iterator(); i.hasNext();) {
String elementName = i.next();
String value = page.getStringValue(cms, elementName, locale);
String extracted = CmsHtmlExtractor.extractText(value, page.getEncoding());
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(extracted)) {
items.put(elementName, extracted);
content.append(extracted);
content.append('\n');
}
}
return new CmsExtractionResult(content.toString(), items);
} catch (Exception e) {
throw new CmsIndexException(
Messages.get().container(Messages.ERR_TEXT_EXTRACTION_1, resource.getRootPath()),
e);
}
} | [
"public",
"I_CmsExtractionResult",
"extractContent",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"resource",
",",
"I_CmsSearchIndex",
"index",
")",
"throws",
"CmsException",
"{",
"logContentExtraction",
"(",
"resource",
",",
"index",
")",
";",
"try",
"{",
"CmsFile",
"file",
"=",
"readFile",
"(",
"cms",
",",
"resource",
")",
";",
"CmsXmlPage",
"page",
"=",
"CmsXmlPageFactory",
".",
"unmarshal",
"(",
"cms",
",",
"file",
")",
";",
"Locale",
"locale",
"=",
"index",
".",
"getLocaleForResource",
"(",
"cms",
",",
"resource",
",",
"page",
".",
"getLocales",
"(",
")",
")",
";",
"List",
"<",
"String",
">",
"elements",
"=",
"page",
".",
"getNames",
"(",
"locale",
")",
";",
"StringBuffer",
"content",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"LinkedHashMap",
"<",
"String",
",",
"String",
">",
"items",
"=",
"new",
"LinkedHashMap",
"<",
"String",
",",
"String",
">",
"(",
")",
";",
"for",
"(",
"Iterator",
"<",
"String",
">",
"i",
"=",
"elements",
".",
"iterator",
"(",
")",
";",
"i",
".",
"hasNext",
"(",
")",
";",
")",
"{",
"String",
"elementName",
"=",
"i",
".",
"next",
"(",
")",
";",
"String",
"value",
"=",
"page",
".",
"getStringValue",
"(",
"cms",
",",
"elementName",
",",
"locale",
")",
";",
"String",
"extracted",
"=",
"CmsHtmlExtractor",
".",
"extractText",
"(",
"value",
",",
"page",
".",
"getEncoding",
"(",
")",
")",
";",
"if",
"(",
"CmsStringUtil",
".",
"isNotEmptyOrWhitespaceOnly",
"(",
"extracted",
")",
")",
"{",
"items",
".",
"put",
"(",
"elementName",
",",
"extracted",
")",
";",
"content",
".",
"append",
"(",
"extracted",
")",
";",
"content",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
"}",
"return",
"new",
"CmsExtractionResult",
"(",
"content",
".",
"toString",
"(",
")",
",",
"items",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"CmsIndexException",
"(",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"Messages",
".",
"ERR_TEXT_EXTRACTION_1",
",",
"resource",
".",
"getRootPath",
"(",
")",
")",
",",
"e",
")",
";",
"}",
"}"
]
| Returns the raw text content of a given vfs resource of type <code>CmsResourceTypeXmlPage</code>.<p>
@see org.opencms.search.documents.I_CmsSearchExtractor#extractContent(CmsObject, CmsResource, I_CmsSearchIndex) | [
"Returns",
"the",
"raw",
"text",
"content",
"of",
"a",
"given",
"vfs",
"resource",
"of",
"type",
"<code",
">",
"CmsResourceTypeXmlPage<",
"/",
"code",
">",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/documents/CmsDocumentXmlPage.java#L71-L101 |
toddfast/typeconverter | src/main/java/com/toddfast/util/convert/TypeConverter.java | TypeConverter.asByte | public static byte asByte(Object value, byte nullValue) {
"""
Return the value converted to a byte
or the specified alternate value if the original value is null. Note,
this method still throws {@link IllegalArgumentException} if the value
is not null and could not be converted.
@param value
The value to be converted
@param nullValue
The value to be returned if {@link value} is null. Note, this
value will not be returned if the conversion fails otherwise.
@throws IllegalArgumentException
If the value cannot be converted
"""
value=convert(Byte.class,value);
if (value!=null) {
return ((Byte)value).byteValue();
}
else {
return nullValue;
}
} | java | public static byte asByte(Object value, byte nullValue) {
value=convert(Byte.class,value);
if (value!=null) {
return ((Byte)value).byteValue();
}
else {
return nullValue;
}
} | [
"public",
"static",
"byte",
"asByte",
"(",
"Object",
"value",
",",
"byte",
"nullValue",
")",
"{",
"value",
"=",
"convert",
"(",
"Byte",
".",
"class",
",",
"value",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"return",
"(",
"(",
"Byte",
")",
"value",
")",
".",
"byteValue",
"(",
")",
";",
"}",
"else",
"{",
"return",
"nullValue",
";",
"}",
"}"
]
| Return the value converted to a byte
or the specified alternate value if the original value is null. Note,
this method still throws {@link IllegalArgumentException} if the value
is not null and could not be converted.
@param value
The value to be converted
@param nullValue
The value to be returned if {@link value} is null. Note, this
value will not be returned if the conversion fails otherwise.
@throws IllegalArgumentException
If the value cannot be converted | [
"Return",
"the",
"value",
"converted",
"to",
"a",
"byte",
"or",
"the",
"specified",
"alternate",
"value",
"if",
"the",
"original",
"value",
"is",
"null",
".",
"Note",
"this",
"method",
"still",
"throws",
"{",
"@link",
"IllegalArgumentException",
"}",
"if",
"the",
"value",
"is",
"not",
"null",
"and",
"could",
"not",
"be",
"converted",
"."
]
| train | https://github.com/toddfast/typeconverter/blob/44efa352254faa49edaba5c5935389705aa12b90/src/main/java/com/toddfast/util/convert/TypeConverter.java#L453-L461 |
looly/hutool | hutool-crypto/src/main/java/cn/hutool/crypto/KeyUtil.java | KeyUtil.generateKey | public static SecretKey generateKey(String algorithm, int keySize) {
"""
生成 {@link SecretKey},仅用于对称加密和摘要算法密钥生成
@param algorithm 算法,支持PBE算法
@param keySize 密钥长度
@return {@link SecretKey}
@since 3.1.2
"""
algorithm = getMainAlgorithm(algorithm);
final KeyGenerator keyGenerator = getKeyGenerator(algorithm);
if (keySize > 0) {
keyGenerator.init(keySize);
} else if (SymmetricAlgorithm.AES.getValue().equals(algorithm)) {
// 对于AES的密钥,除非指定,否则强制使用128位
keyGenerator.init(128);
}
return keyGenerator.generateKey();
} | java | public static SecretKey generateKey(String algorithm, int keySize) {
algorithm = getMainAlgorithm(algorithm);
final KeyGenerator keyGenerator = getKeyGenerator(algorithm);
if (keySize > 0) {
keyGenerator.init(keySize);
} else if (SymmetricAlgorithm.AES.getValue().equals(algorithm)) {
// 对于AES的密钥,除非指定,否则强制使用128位
keyGenerator.init(128);
}
return keyGenerator.generateKey();
} | [
"public",
"static",
"SecretKey",
"generateKey",
"(",
"String",
"algorithm",
",",
"int",
"keySize",
")",
"{",
"algorithm",
"=",
"getMainAlgorithm",
"(",
"algorithm",
")",
";",
"final",
"KeyGenerator",
"keyGenerator",
"=",
"getKeyGenerator",
"(",
"algorithm",
")",
";",
"if",
"(",
"keySize",
">",
"0",
")",
"{",
"keyGenerator",
".",
"init",
"(",
"keySize",
")",
";",
"}",
"else",
"if",
"(",
"SymmetricAlgorithm",
".",
"AES",
".",
"getValue",
"(",
")",
".",
"equals",
"(",
"algorithm",
")",
")",
"{",
"// 对于AES的密钥,除非指定,否则强制使用128位\r",
"keyGenerator",
".",
"init",
"(",
"128",
")",
";",
"}",
"return",
"keyGenerator",
".",
"generateKey",
"(",
")",
";",
"}"
]
| 生成 {@link SecretKey},仅用于对称加密和摘要算法密钥生成
@param algorithm 算法,支持PBE算法
@param keySize 密钥长度
@return {@link SecretKey}
@since 3.1.2 | [
"生成",
"{",
"@link",
"SecretKey",
"}",
",仅用于对称加密和摘要算法密钥生成"
]
| train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-crypto/src/main/java/cn/hutool/crypto/KeyUtil.java#L94-L105 |
twilio/twilio-java | src/main/java/com/twilio/rest/fax/v1/fax/FaxMediaReader.java | FaxMediaReader.nextPage | @Override
public Page<FaxMedia> nextPage(final Page<FaxMedia> page,
final TwilioRestClient client) {
"""
Retrieve the next page from the Twilio API.
@param page current page
@param client TwilioRestClient with which to make the request
@return Next Page
"""
Request request = new Request(
HttpMethod.GET,
page.getNextPageUrl(
Domains.FAX.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | java | @Override
public Page<FaxMedia> nextPage(final Page<FaxMedia> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getNextPageUrl(
Domains.FAX.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | [
"@",
"Override",
"public",
"Page",
"<",
"FaxMedia",
">",
"nextPage",
"(",
"final",
"Page",
"<",
"FaxMedia",
">",
"page",
",",
"final",
"TwilioRestClient",
"client",
")",
"{",
"Request",
"request",
"=",
"new",
"Request",
"(",
"HttpMethod",
".",
"GET",
",",
"page",
".",
"getNextPageUrl",
"(",
"Domains",
".",
"FAX",
".",
"toString",
"(",
")",
",",
"client",
".",
"getRegion",
"(",
")",
")",
")",
";",
"return",
"pageForRequest",
"(",
"client",
",",
"request",
")",
";",
"}"
]
| Retrieve the next page from the Twilio API.
@param page current page
@param client TwilioRestClient with which to make the request
@return Next Page | [
"Retrieve",
"the",
"next",
"page",
"from",
"the",
"Twilio",
"API",
"."
]
| train | https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/fax/v1/fax/FaxMediaReader.java#L94-L105 |
liferay/com-liferay-commerce | commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPOptionCategoryWrapper.java | CPOptionCategoryWrapper.getTitle | @Override
public String getTitle(String languageId, boolean useDefault) {
"""
Returns the localized title of this cp option category 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 title of this cp option category
"""
return _cpOptionCategory.getTitle(languageId, useDefault);
} | java | @Override
public String getTitle(String languageId, boolean useDefault) {
return _cpOptionCategory.getTitle(languageId, useDefault);
} | [
"@",
"Override",
"public",
"String",
"getTitle",
"(",
"String",
"languageId",
",",
"boolean",
"useDefault",
")",
"{",
"return",
"_cpOptionCategory",
".",
"getTitle",
"(",
"languageId",
",",
"useDefault",
")",
";",
"}"
]
| Returns the localized title of this cp option category 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 title of this cp option category | [
"Returns",
"the",
"localized",
"title",
"of",
"this",
"cp",
"option",
"category",
"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-product-api/src/main/java/com/liferay/commerce/product/model/CPOptionCategoryWrapper.java#L408-L411 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.jwtsso_fat/fat/src/com/ibm/ws/security/jwtsso/fat/utils/CommonExpectations.java | CommonExpectations.jwtCookieExists | public static Expectations jwtCookieExists(String testAction, WebClient webClient, String jwtCookieName) {
"""
Sets expectations that will check:
<ol>
<li>The provided WebClient contains a cookie with the default JWT SSO cookie name, its value is a JWT, is NOT marked secure, and is marked HttpOnly
</ol>
"""
Expectations expectations = new Expectations();
expectations.addExpectation(new CookieExpectation(testAction, webClient, jwtCookieName, JwtFatConstants.JWT_REGEX, JwtFatConstants.NOT_SECURE, JwtFatConstants.HTTPONLY));
return expectations;
} | java | public static Expectations jwtCookieExists(String testAction, WebClient webClient, String jwtCookieName) {
Expectations expectations = new Expectations();
expectations.addExpectation(new CookieExpectation(testAction, webClient, jwtCookieName, JwtFatConstants.JWT_REGEX, JwtFatConstants.NOT_SECURE, JwtFatConstants.HTTPONLY));
return expectations;
} | [
"public",
"static",
"Expectations",
"jwtCookieExists",
"(",
"String",
"testAction",
",",
"WebClient",
"webClient",
",",
"String",
"jwtCookieName",
")",
"{",
"Expectations",
"expectations",
"=",
"new",
"Expectations",
"(",
")",
";",
"expectations",
".",
"addExpectation",
"(",
"new",
"CookieExpectation",
"(",
"testAction",
",",
"webClient",
",",
"jwtCookieName",
",",
"JwtFatConstants",
".",
"JWT_REGEX",
",",
"JwtFatConstants",
".",
"NOT_SECURE",
",",
"JwtFatConstants",
".",
"HTTPONLY",
")",
")",
";",
"return",
"expectations",
";",
"}"
]
| Sets expectations that will check:
<ol>
<li>The provided WebClient contains a cookie with the default JWT SSO cookie name, its value is a JWT, is NOT marked secure, and is marked HttpOnly
</ol> | [
"Sets",
"expectations",
"that",
"will",
"check",
":",
"<ol",
">",
"<li",
">",
"The",
"provided",
"WebClient",
"contains",
"a",
"cookie",
"with",
"the",
"default",
"JWT",
"SSO",
"cookie",
"name",
"its",
"value",
"is",
"a",
"JWT",
"is",
"NOT",
"marked",
"secure",
"and",
"is",
"marked",
"HttpOnly",
"<",
"/",
"ol",
">"
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.jwtsso_fat/fat/src/com/ibm/ws/security/jwtsso/fat/utils/CommonExpectations.java#L70-L74 |
amzn/ion-java | src/com/amazon/ion/impl/bin/IonRawBinaryWriter.java | IonRawBinaryWriter.writeTypedBytes | private void writeTypedBytes(final int type, final byte[] data, final int offset, final int length) {
"""
Write a raw byte array as some type. Note that this does not do {@link #prepareValue()}.
"""
int totalLength = 1 + length;
if (length < 14)
{
buffer.writeUInt8(type | length);
}
else
{
// need to specify length explicitly
buffer.writeUInt8(type | 0xE);
final int sizeLength = buffer.writeVarUInt(length);
totalLength += sizeLength;
}
updateLength(totalLength);
buffer.writeBytes(data, offset, length);
} | java | private void writeTypedBytes(final int type, final byte[] data, final int offset, final int length)
{
int totalLength = 1 + length;
if (length < 14)
{
buffer.writeUInt8(type | length);
}
else
{
// need to specify length explicitly
buffer.writeUInt8(type | 0xE);
final int sizeLength = buffer.writeVarUInt(length);
totalLength += sizeLength;
}
updateLength(totalLength);
buffer.writeBytes(data, offset, length);
} | [
"private",
"void",
"writeTypedBytes",
"(",
"final",
"int",
"type",
",",
"final",
"byte",
"[",
"]",
"data",
",",
"final",
"int",
"offset",
",",
"final",
"int",
"length",
")",
"{",
"int",
"totalLength",
"=",
"1",
"+",
"length",
";",
"if",
"(",
"length",
"<",
"14",
")",
"{",
"buffer",
".",
"writeUInt8",
"(",
"type",
"|",
"length",
")",
";",
"}",
"else",
"{",
"// need to specify length explicitly",
"buffer",
".",
"writeUInt8",
"(",
"type",
"|",
"0xE",
")",
";",
"final",
"int",
"sizeLength",
"=",
"buffer",
".",
"writeVarUInt",
"(",
"length",
")",
";",
"totalLength",
"+=",
"sizeLength",
";",
"}",
"updateLength",
"(",
"totalLength",
")",
";",
"buffer",
".",
"writeBytes",
"(",
"data",
",",
"offset",
",",
"length",
")",
";",
"}"
]
| Write a raw byte array as some type. Note that this does not do {@link #prepareValue()}. | [
"Write",
"a",
"raw",
"byte",
"array",
"as",
"some",
"type",
".",
"Note",
"that",
"this",
"does",
"not",
"do",
"{"
]
| train | https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/impl/bin/IonRawBinaryWriter.java#L1021-L1037 |
drinkjava2/jBeanBox | jbeanbox/src/main/java/com/github/drinkjava2/asm5_0_3/util/CheckClassAdapter.java | CheckClassAdapter.checkAccess | static void checkAccess(final int access, final int possibleAccess) {
"""
Checks that the given access flags do not contain invalid flags. This
method also checks that mutually incompatible flags are not set
simultaneously.
@param access
the access flags to be checked
@param possibleAccess
the valid access flags.
"""
if ((access & ~possibleAccess) != 0) {
throw new IllegalArgumentException("Invalid access flags: "
+ access);
}
int pub = (access & Opcodes.ACC_PUBLIC) == 0 ? 0 : 1;
int pri = (access & Opcodes.ACC_PRIVATE) == 0 ? 0 : 1;
int pro = (access & Opcodes.ACC_PROTECTED) == 0 ? 0 : 1;
if (pub + pri + pro > 1) {
throw new IllegalArgumentException(
"public private and protected are mutually exclusive: "
+ access);
}
int fin = (access & Opcodes.ACC_FINAL) == 0 ? 0 : 1;
int abs = (access & Opcodes.ACC_ABSTRACT) == 0 ? 0 : 1;
if (fin + abs > 1) {
throw new IllegalArgumentException(
"final and abstract are mutually exclusive: " + access);
}
} | java | static void checkAccess(final int access, final int possibleAccess) {
if ((access & ~possibleAccess) != 0) {
throw new IllegalArgumentException("Invalid access flags: "
+ access);
}
int pub = (access & Opcodes.ACC_PUBLIC) == 0 ? 0 : 1;
int pri = (access & Opcodes.ACC_PRIVATE) == 0 ? 0 : 1;
int pro = (access & Opcodes.ACC_PROTECTED) == 0 ? 0 : 1;
if (pub + pri + pro > 1) {
throw new IllegalArgumentException(
"public private and protected are mutually exclusive: "
+ access);
}
int fin = (access & Opcodes.ACC_FINAL) == 0 ? 0 : 1;
int abs = (access & Opcodes.ACC_ABSTRACT) == 0 ? 0 : 1;
if (fin + abs > 1) {
throw new IllegalArgumentException(
"final and abstract are mutually exclusive: " + access);
}
} | [
"static",
"void",
"checkAccess",
"(",
"final",
"int",
"access",
",",
"final",
"int",
"possibleAccess",
")",
"{",
"if",
"(",
"(",
"access",
"&",
"~",
"possibleAccess",
")",
"!=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid access flags: \"",
"+",
"access",
")",
";",
"}",
"int",
"pub",
"=",
"(",
"access",
"&",
"Opcodes",
".",
"ACC_PUBLIC",
")",
"==",
"0",
"?",
"0",
":",
"1",
";",
"int",
"pri",
"=",
"(",
"access",
"&",
"Opcodes",
".",
"ACC_PRIVATE",
")",
"==",
"0",
"?",
"0",
":",
"1",
";",
"int",
"pro",
"=",
"(",
"access",
"&",
"Opcodes",
".",
"ACC_PROTECTED",
")",
"==",
"0",
"?",
"0",
":",
"1",
";",
"if",
"(",
"pub",
"+",
"pri",
"+",
"pro",
">",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"public private and protected are mutually exclusive: \"",
"+",
"access",
")",
";",
"}",
"int",
"fin",
"=",
"(",
"access",
"&",
"Opcodes",
".",
"ACC_FINAL",
")",
"==",
"0",
"?",
"0",
":",
"1",
";",
"int",
"abs",
"=",
"(",
"access",
"&",
"Opcodes",
".",
"ACC_ABSTRACT",
")",
"==",
"0",
"?",
"0",
":",
"1",
";",
"if",
"(",
"fin",
"+",
"abs",
">",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"final and abstract are mutually exclusive: \"",
"+",
"access",
")",
";",
"}",
"}"
]
| Checks that the given access flags do not contain invalid flags. This
method also checks that mutually incompatible flags are not set
simultaneously.
@param access
the access flags to be checked
@param possibleAccess
the valid access flags. | [
"Checks",
"that",
"the",
"given",
"access",
"flags",
"do",
"not",
"contain",
"invalid",
"flags",
".",
"This",
"method",
"also",
"checks",
"that",
"mutually",
"incompatible",
"flags",
"are",
"not",
"set",
"simultaneously",
"."
]
| train | https://github.com/drinkjava2/jBeanBox/blob/01c216599ffa2e5f2d9c01df2adaad0f45567c04/jbeanbox/src/main/java/com/github/drinkjava2/asm5_0_3/util/CheckClassAdapter.java#L597-L616 |
LGoodDatePicker/LGoodDatePicker | Project/src/main/java/com/privatejgoodies/forms/layout/RowSpec.java | RowSpec.createGap | public static RowSpec createGap(ConstantSize gapHeight) {
"""
Creates and returns a {@link RowSpec} that represents a gap with the specified
{@link ConstantSize}.
@param gapHeight specifies the gap height
@return a RowSpec that describes a vertical gap with the given height
@throws NullPointerException if {@code gapHeight} is {@code null}
@since 1.2
"""
return new RowSpec(RowSpec.DEFAULT, gapHeight, FormSpec.NO_GROW);
} | java | public static RowSpec createGap(ConstantSize gapHeight) {
return new RowSpec(RowSpec.DEFAULT, gapHeight, FormSpec.NO_GROW);
} | [
"public",
"static",
"RowSpec",
"createGap",
"(",
"ConstantSize",
"gapHeight",
")",
"{",
"return",
"new",
"RowSpec",
"(",
"RowSpec",
".",
"DEFAULT",
",",
"gapHeight",
",",
"FormSpec",
".",
"NO_GROW",
")",
";",
"}"
]
| Creates and returns a {@link RowSpec} that represents a gap with the specified
{@link ConstantSize}.
@param gapHeight specifies the gap height
@return a RowSpec that describes a vertical gap with the given height
@throws NullPointerException if {@code gapHeight} is {@code null}
@since 1.2 | [
"Creates",
"and",
"returns",
"a",
"{",
"@link",
"RowSpec",
"}",
"that",
"represents",
"a",
"gap",
"with",
"the",
"specified",
"{",
"@link",
"ConstantSize",
"}",
"."
]
| train | https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/privatejgoodies/forms/layout/RowSpec.java#L149-L151 |
sd4324530/fastweixin | src/main/java/com/github/sd4324530/fastweixin/api/JsAPI.java | JsAPI.getSignature | public GetSignatureResponse getSignature(String nonceStr, long timestame, String url) {
"""
获取js-sdk所需的签名,给调用者最大的自由度,控制生成签名的参数
@param nonceStr 随机字符串
@param timestame 时间戳
@param url 当前网页的URL,不包含#及其后面部分
@return 签名以及相关参数
"""
BeanUtil.requireNonNull(url, "请传入当前网页的URL,不包含#及其后面部分");
GetSignatureResponse response = new GetSignatureResponse();
String jsApiTicket = this.config.getJsApiTicket();
String sign;
try {
sign = JsApiUtil.sign(jsApiTicket, nonceStr, timestame, url);
} catch (Exception e) {
LOG.error("获取签名异常:", e);
response.setErrcode(ResultType.OTHER_ERROR.getCode().toString());
response.setErrmsg("获取签名异常");
return response;
}
response.setNoncestr(nonceStr);
response.setSignature(sign);
response.setTimestamp(timestame);
response.setUrl(url);
response.setErrcode(ResultType.SUCCESS.getCode().toString());
return response;
} | java | public GetSignatureResponse getSignature(String nonceStr, long timestame, String url) {
BeanUtil.requireNonNull(url, "请传入当前网页的URL,不包含#及其后面部分");
GetSignatureResponse response = new GetSignatureResponse();
String jsApiTicket = this.config.getJsApiTicket();
String sign;
try {
sign = JsApiUtil.sign(jsApiTicket, nonceStr, timestame, url);
} catch (Exception e) {
LOG.error("获取签名异常:", e);
response.setErrcode(ResultType.OTHER_ERROR.getCode().toString());
response.setErrmsg("获取签名异常");
return response;
}
response.setNoncestr(nonceStr);
response.setSignature(sign);
response.setTimestamp(timestame);
response.setUrl(url);
response.setErrcode(ResultType.SUCCESS.getCode().toString());
return response;
} | [
"public",
"GetSignatureResponse",
"getSignature",
"(",
"String",
"nonceStr",
",",
"long",
"timestame",
",",
"String",
"url",
")",
"{",
"BeanUtil",
".",
"requireNonNull",
"(",
"url",
",",
"\"请传入当前网页的URL,不包含#及其后面部分\");",
"",
"",
"GetSignatureResponse",
"response",
"=",
"new",
"GetSignatureResponse",
"(",
")",
";",
"String",
"jsApiTicket",
"=",
"this",
".",
"config",
".",
"getJsApiTicket",
"(",
")",
";",
"String",
"sign",
";",
"try",
"{",
"sign",
"=",
"JsApiUtil",
".",
"sign",
"(",
"jsApiTicket",
",",
"nonceStr",
",",
"timestame",
",",
"url",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"获取签名异常:\", e);",
"",
"",
"",
"",
"response",
".",
"setErrcode",
"(",
"ResultType",
".",
"OTHER_ERROR",
".",
"getCode",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"response",
".",
"setErrmsg",
"(",
"\"获取签名异常\");",
"",
"",
"return",
"response",
";",
"}",
"response",
".",
"setNoncestr",
"(",
"nonceStr",
")",
";",
"response",
".",
"setSignature",
"(",
"sign",
")",
";",
"response",
".",
"setTimestamp",
"(",
"timestame",
")",
";",
"response",
".",
"setUrl",
"(",
"url",
")",
";",
"response",
".",
"setErrcode",
"(",
"ResultType",
".",
"SUCCESS",
".",
"getCode",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"return",
"response",
";",
"}"
]
| 获取js-sdk所需的签名,给调用者最大的自由度,控制生成签名的参数
@param nonceStr 随机字符串
@param timestame 时间戳
@param url 当前网页的URL,不包含#及其后面部分
@return 签名以及相关参数 | [
"获取js",
"-",
"sdk所需的签名,给调用者最大的自由度,控制生成签名的参数"
]
| train | https://github.com/sd4324530/fastweixin/blob/6bc0a7abfa23aad0dbad4c3123a47a7fb53f3447/src/main/java/com/github/sd4324530/fastweixin/api/JsAPI.java#L47-L66 |
eirbjo/jetty-console | jetty-console-core/src/main/java/org/simplericity/jettyconsole/JettyConsoleBootstrapMainClass.java | JettyConsoleBootstrapMainClass.unpackFile | private static void unpackFile(InputStream in, File file) {
"""
Write the contents of an InputStream to a file
@param in the input stream to read
@param file the File to write to
"""
byte[] buffer = new byte[4096];
try {
OutputStream out = new FileOutputStream(file);
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
} | java | private static void unpackFile(InputStream in, File file) {
byte[] buffer = new byte[4096];
try {
OutputStream out = new FileOutputStream(file);
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
} | [
"private",
"static",
"void",
"unpackFile",
"(",
"InputStream",
"in",
",",
"File",
"file",
")",
"{",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"4096",
"]",
";",
"try",
"{",
"OutputStream",
"out",
"=",
"new",
"FileOutputStream",
"(",
"file",
")",
";",
"int",
"read",
";",
"while",
"(",
"(",
"read",
"=",
"in",
".",
"read",
"(",
"buffer",
")",
")",
"!=",
"-",
"1",
")",
"{",
"out",
".",
"write",
"(",
"buffer",
",",
"0",
",",
"read",
")",
";",
"}",
"out",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
]
| Write the contents of an InputStream to a file
@param in the input stream to read
@param file the File to write to | [
"Write",
"the",
"contents",
"of",
"an",
"InputStream",
"to",
"a",
"file"
]
| train | https://github.com/eirbjo/jetty-console/blob/5bd32ecab12837394dd45fd15c51c3934afcd76b/jetty-console-core/src/main/java/org/simplericity/jettyconsole/JettyConsoleBootstrapMainClass.java#L319-L332 |
OpenLiberty/open-liberty | dev/com.ibm.ws.channelfw/src/com/ibm/wsspi/bytebuffer/WsByteBufferUtils.java | WsByteBufferUtils.asInt | public static final int asInt(WsByteBuffer[] list, int[] positions, int[] limits) {
"""
Convert a list of buffers to an int using the starting positions and ending
limits.
@param list
@param positions
@param limits
@return int
"""
return asInt(asByteArray(list, positions, limits));
} | java | public static final int asInt(WsByteBuffer[] list, int[] positions, int[] limits) {
return asInt(asByteArray(list, positions, limits));
} | [
"public",
"static",
"final",
"int",
"asInt",
"(",
"WsByteBuffer",
"[",
"]",
"list",
",",
"int",
"[",
"]",
"positions",
",",
"int",
"[",
"]",
"limits",
")",
"{",
"return",
"asInt",
"(",
"asByteArray",
"(",
"list",
",",
"positions",
",",
"limits",
")",
")",
";",
"}"
]
| Convert a list of buffers to an int using the starting positions and ending
limits.
@param list
@param positions
@param limits
@return int | [
"Convert",
"a",
"list",
"of",
"buffers",
"to",
"an",
"int",
"using",
"the",
"starting",
"positions",
"and",
"ending",
"limits",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/wsspi/bytebuffer/WsByteBufferUtils.java#L257-L259 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/query/dsl/functions/Collections.java | Collections.arrayWithin | public static WhenBuilder arrayWithin(Expression arrayExpression, String variable, Expression expression) {
"""
Create an ARRAY comprehension with a first WITHIN range.
The ARRAY operator lets you map and filter the elements or attributes of a collection, object, or objects.
It evaluates to an array of the operand expression, that satisfies the WHEN clause, if provided.
For elements, IN ranges in the direct elements of its array expression, WITHIN also ranges in its descendants.
"""
return new WhenBuilder(x("ARRAY " + arrayExpression.toString() + " FOR"),
variable, expression, false);
} | java | public static WhenBuilder arrayWithin(Expression arrayExpression, String variable, Expression expression) {
return new WhenBuilder(x("ARRAY " + arrayExpression.toString() + " FOR"),
variable, expression, false);
} | [
"public",
"static",
"WhenBuilder",
"arrayWithin",
"(",
"Expression",
"arrayExpression",
",",
"String",
"variable",
",",
"Expression",
"expression",
")",
"{",
"return",
"new",
"WhenBuilder",
"(",
"x",
"(",
"\"ARRAY \"",
"+",
"arrayExpression",
".",
"toString",
"(",
")",
"+",
"\" FOR\"",
")",
",",
"variable",
",",
"expression",
",",
"false",
")",
";",
"}"
]
| Create an ARRAY comprehension with a first WITHIN range.
The ARRAY operator lets you map and filter the elements or attributes of a collection, object, or objects.
It evaluates to an array of the operand expression, that satisfies the WHEN clause, if provided.
For elements, IN ranges in the direct elements of its array expression, WITHIN also ranges in its descendants. | [
"Create",
"an",
"ARRAY",
"comprehension",
"with",
"a",
"first",
"WITHIN",
"range",
"."
]
| train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/Collections.java#L239-L242 |
versionone/VersionOne.SDK.Java.ObjectModel | src/main/java/com/versionone/om/V1Instance.java | V1Instance.executeOperation | <T extends Entity> T executeOperation(Class<T> clazz, Entity subject,
String operationName) throws UnsupportedOperationException {
"""
Executes an Operation on an Entity, assuming it is safe to do so.
@param clazz Class of expected Entity to return.
@param subject asset will be found for.
@param operationName operator name.
@return object identifier.
@throws UnsupportedOperationException in case invalid state for the
Operation.
"""
Oid operationResult = executeOperation(subject, operationName);
AssetID id = new AssetID(operationResult.getToken());
return createWrapper(clazz, id, false);
} | java | <T extends Entity> T executeOperation(Class<T> clazz, Entity subject,
String operationName) throws UnsupportedOperationException {
Oid operationResult = executeOperation(subject, operationName);
AssetID id = new AssetID(operationResult.getToken());
return createWrapper(clazz, id, false);
} | [
"<",
"T",
"extends",
"Entity",
">",
"T",
"executeOperation",
"(",
"Class",
"<",
"T",
">",
"clazz",
",",
"Entity",
"subject",
",",
"String",
"operationName",
")",
"throws",
"UnsupportedOperationException",
"{",
"Oid",
"operationResult",
"=",
"executeOperation",
"(",
"subject",
",",
"operationName",
")",
";",
"AssetID",
"id",
"=",
"new",
"AssetID",
"(",
"operationResult",
".",
"getToken",
"(",
")",
")",
";",
"return",
"createWrapper",
"(",
"clazz",
",",
"id",
",",
"false",
")",
";",
"}"
]
| Executes an Operation on an Entity, assuming it is safe to do so.
@param clazz Class of expected Entity to return.
@param subject asset will be found for.
@param operationName operator name.
@return object identifier.
@throws UnsupportedOperationException in case invalid state for the
Operation. | [
"Executes",
"an",
"Operation",
"on",
"an",
"Entity",
"assuming",
"it",
"is",
"safe",
"to",
"do",
"so",
"."
]
| train | https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/om/V1Instance.java#L486-L492 |
facebookarchive/hadoop-20 | src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNode.java | AvatarNode.stopRPC | protected void stopRPC(boolean interruptClientHandlers) throws IOException {
"""
Stops all RPC threads and ensures that all RPC handlers have exited.
Stops all communication to the namenode.
"""
try {
// stop avatardatanode server
stopRPCInternal(server, "avatardatanode", interruptClientHandlers);
// stop namenode rpc (client, datanode)
super.stopRPC(interruptClientHandlers);
// wait for avatardatanode rpc
stopWaitRPCInternal(server, "avatardatanode");
} catch (InterruptedException ex) {
throw new IOException("stopRPC() interrupted", ex);
}
} | java | protected void stopRPC(boolean interruptClientHandlers) throws IOException {
try {
// stop avatardatanode server
stopRPCInternal(server, "avatardatanode", interruptClientHandlers);
// stop namenode rpc (client, datanode)
super.stopRPC(interruptClientHandlers);
// wait for avatardatanode rpc
stopWaitRPCInternal(server, "avatardatanode");
} catch (InterruptedException ex) {
throw new IOException("stopRPC() interrupted", ex);
}
} | [
"protected",
"void",
"stopRPC",
"(",
"boolean",
"interruptClientHandlers",
")",
"throws",
"IOException",
"{",
"try",
"{",
"// stop avatardatanode server",
"stopRPCInternal",
"(",
"server",
",",
"\"avatardatanode\"",
",",
"interruptClientHandlers",
")",
";",
"// stop namenode rpc (client, datanode)",
"super",
".",
"stopRPC",
"(",
"interruptClientHandlers",
")",
";",
"// wait for avatardatanode rpc",
"stopWaitRPCInternal",
"(",
"server",
",",
"\"avatardatanode\"",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"ex",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"stopRPC() interrupted\"",
",",
"ex",
")",
";",
"}",
"}"
]
| Stops all RPC threads and ensures that all RPC handlers have exited.
Stops all communication to the namenode. | [
"Stops",
"all",
"RPC",
"threads",
"and",
"ensures",
"that",
"all",
"RPC",
"handlers",
"have",
"exited",
".",
"Stops",
"all",
"communication",
"to",
"the",
"namenode",
"."
]
| train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNode.java#L651-L664 |
uaihebert/uaiMockServer | src/main/java/com/uaihebert/uaimockserver/validator/body/XmlUnitWrapper.java | XmlUnitWrapper.isSimilar | public static boolean isSimilar(final String expected, final String actual) {
"""
This method will compare both XMLs and WILL NOT validate its attribute order.
@param expected what are we expecting
@param actual what we receive
@return if they have same value
"""
final Diff diff = createDiffResult(expected, actual, true);
return diff.similar();
} | java | public static boolean isSimilar(final String expected, final String actual) {
final Diff diff = createDiffResult(expected, actual, true);
return diff.similar();
} | [
"public",
"static",
"boolean",
"isSimilar",
"(",
"final",
"String",
"expected",
",",
"final",
"String",
"actual",
")",
"{",
"final",
"Diff",
"diff",
"=",
"createDiffResult",
"(",
"expected",
",",
"actual",
",",
"true",
")",
";",
"return",
"diff",
".",
"similar",
"(",
")",
";",
"}"
]
| This method will compare both XMLs and WILL NOT validate its attribute order.
@param expected what are we expecting
@param actual what we receive
@return if they have same value | [
"This",
"method",
"will",
"compare",
"both",
"XMLs",
"and",
"WILL",
"NOT",
"validate",
"its",
"attribute",
"order",
"."
]
| train | https://github.com/uaihebert/uaiMockServer/blob/8b0090d4018c2f430cfbbb3ae249347652802f2b/src/main/java/com/uaihebert/uaimockserver/validator/body/XmlUnitWrapper.java#L46-L50 |
mygreen/xlsmapper | src/main/java/com/gh/mygreen/xlsmapper/LoadingWorkObject.java | LoadingWorkObject.addTypeBindError | public void addTypeBindError(final TypeBindException bindException, final CellPosition address, final String fieldName, final String label) {
"""
型変換エラーを追加します。
@param bindException 型変換エラー
@param address マッピング元となったセルのアドレス
@param fieldName マッピング先のフィールド名
@param label ラベル。省略する場合は、nullを指定します。
"""
this.errors.createFieldConversionError(fieldName, bindException.getBindClass(), bindException.getTargetValue())
.variables(bindException.getMessageVars())
.variables("validatedValue", bindException.getTargetValue())
.address(address)
.label(label)
.buildAndAddError();
} | java | public void addTypeBindError(final TypeBindException bindException, final CellPosition address, final String fieldName, final String label) {
this.errors.createFieldConversionError(fieldName, bindException.getBindClass(), bindException.getTargetValue())
.variables(bindException.getMessageVars())
.variables("validatedValue", bindException.getTargetValue())
.address(address)
.label(label)
.buildAndAddError();
} | [
"public",
"void",
"addTypeBindError",
"(",
"final",
"TypeBindException",
"bindException",
",",
"final",
"CellPosition",
"address",
",",
"final",
"String",
"fieldName",
",",
"final",
"String",
"label",
")",
"{",
"this",
".",
"errors",
".",
"createFieldConversionError",
"(",
"fieldName",
",",
"bindException",
".",
"getBindClass",
"(",
")",
",",
"bindException",
".",
"getTargetValue",
"(",
")",
")",
".",
"variables",
"(",
"bindException",
".",
"getMessageVars",
"(",
")",
")",
".",
"variables",
"(",
"\"validatedValue\"",
",",
"bindException",
".",
"getTargetValue",
"(",
")",
")",
".",
"address",
"(",
"address",
")",
".",
"label",
"(",
"label",
")",
".",
"buildAndAddError",
"(",
")",
";",
"}"
]
| 型変換エラーを追加します。
@param bindException 型変換エラー
@param address マッピング元となったセルのアドレス
@param fieldName マッピング先のフィールド名
@param label ラベル。省略する場合は、nullを指定します。 | [
"型変換エラーを追加します。"
]
| train | https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/LoadingWorkObject.java#L68-L77 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/JobScheduleOperations.java | JobScheduleOperations.deleteJobSchedule | public void deleteJobSchedule(String jobScheduleId, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException {
"""
Deletes the specified job schedule.
@param jobScheduleId The ID of the job schedule.
@param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request.
@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.
"""
JobScheduleDeleteOptions options = new JobScheduleDeleteOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
this.parentBatchClient.protocolLayer().jobSchedules().delete(jobScheduleId, options);
} | java | public void deleteJobSchedule(String jobScheduleId, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException {
JobScheduleDeleteOptions options = new JobScheduleDeleteOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
this.parentBatchClient.protocolLayer().jobSchedules().delete(jobScheduleId, options);
} | [
"public",
"void",
"deleteJobSchedule",
"(",
"String",
"jobScheduleId",
",",
"Iterable",
"<",
"BatchClientBehavior",
">",
"additionalBehaviors",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"JobScheduleDeleteOptions",
"options",
"=",
"new",
"JobScheduleDeleteOptions",
"(",
")",
";",
"BehaviorManager",
"bhMgr",
"=",
"new",
"BehaviorManager",
"(",
"this",
".",
"customBehaviors",
"(",
")",
",",
"additionalBehaviors",
")",
";",
"bhMgr",
".",
"applyRequestBehaviors",
"(",
"options",
")",
";",
"this",
".",
"parentBatchClient",
".",
"protocolLayer",
"(",
")",
".",
"jobSchedules",
"(",
")",
".",
"delete",
"(",
"jobScheduleId",
",",
"options",
")",
";",
"}"
]
| Deletes the specified job schedule.
@param jobScheduleId The ID of the job schedule.
@param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request.
@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. | [
"Deletes",
"the",
"specified",
"job",
"schedule",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/JobScheduleOperations.java#L116-L122 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-crypto/xwiki-commons-crypto-pkix/src/main/java/org/xwiki/crypto/pkix/internal/BcUtils.java | BcUtils.getX509CertificateHolder | public static X509CertificateHolder getX509CertificateHolder(TBSCertificate tbsCert, byte[] signature) {
"""
Build the structure of an X.509 certificate.
@param tbsCert the to be signed structure
@param signature the signature
@return a X.509 certificate holder.
"""
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(tbsCert);
v.add(tbsCert.getSignature());
v.add(new DERBitString(signature));
return new X509CertificateHolder(Certificate.getInstance(new DERSequence(v)));
} | java | public static X509CertificateHolder getX509CertificateHolder(TBSCertificate tbsCert, byte[] signature)
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(tbsCert);
v.add(tbsCert.getSignature());
v.add(new DERBitString(signature));
return new X509CertificateHolder(Certificate.getInstance(new DERSequence(v)));
} | [
"public",
"static",
"X509CertificateHolder",
"getX509CertificateHolder",
"(",
"TBSCertificate",
"tbsCert",
",",
"byte",
"[",
"]",
"signature",
")",
"{",
"ASN1EncodableVector",
"v",
"=",
"new",
"ASN1EncodableVector",
"(",
")",
";",
"v",
".",
"add",
"(",
"tbsCert",
")",
";",
"v",
".",
"add",
"(",
"tbsCert",
".",
"getSignature",
"(",
")",
")",
";",
"v",
".",
"add",
"(",
"new",
"DERBitString",
"(",
"signature",
")",
")",
";",
"return",
"new",
"X509CertificateHolder",
"(",
"Certificate",
".",
"getInstance",
"(",
"new",
"DERSequence",
"(",
"v",
")",
")",
")",
";",
"}"
]
| Build the structure of an X.509 certificate.
@param tbsCert the to be signed structure
@param signature the signature
@return a X.509 certificate holder. | [
"Build",
"the",
"structure",
"of",
"an",
"X",
".",
"509",
"certificate",
"."
]
| train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-crypto/xwiki-commons-crypto-pkix/src/main/java/org/xwiki/crypto/pkix/internal/BcUtils.java#L131-L140 |
ocelotds/ocelot | ocelot-web/src/main/java/org/ocelotds/topic/TopicManagerImpl.java | TopicManagerImpl.removeSessionToSessions | int removeSessionToSessions(Session session, Collection<Session> sessions) {
"""
Remove session in sessions
@param session
@param sessions
@return 1 if session removed else 0
"""
if (sessions != null) {
if (sessions.remove(session)) {
return 1;
}
}
return 0;
} | java | int removeSessionToSessions(Session session, Collection<Session> sessions) {
if (sessions != null) {
if (sessions.remove(session)) {
return 1;
}
}
return 0;
} | [
"int",
"removeSessionToSessions",
"(",
"Session",
"session",
",",
"Collection",
"<",
"Session",
">",
"sessions",
")",
"{",
"if",
"(",
"sessions",
"!=",
"null",
")",
"{",
"if",
"(",
"sessions",
".",
"remove",
"(",
"session",
")",
")",
"{",
"return",
"1",
";",
"}",
"}",
"return",
"0",
";",
"}"
]
| Remove session in sessions
@param session
@param sessions
@return 1 if session removed else 0 | [
"Remove",
"session",
"in",
"sessions"
]
| train | https://github.com/ocelotds/ocelot/blob/5f0ac37afd8fa4dc9f7234a2aac8abbb522128e7/ocelot-web/src/main/java/org/ocelotds/topic/TopicManagerImpl.java#L130-L137 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/TypeAdapterHelper.java | TypeAdapterHelper.detectSourceType | public static String detectSourceType(Element element, String adapterClazz) {
"""
Detect source type.
@param element the element
@param adapterClazz the adapter clazz
@return the string
"""
TypeElement a = BaseProcessor.elementUtils.getTypeElement(adapterClazz);
for (Element i : BaseProcessor.elementUtils.getAllMembers(a)) {
if (i.getKind() == ElementKind.METHOD && "toJava".equals(i.getSimpleName().toString())) {
ExecutableElement method = (ExecutableElement) i;
return TypeUtility.typeName(method.getReturnType()).toString();
}
}
AssertKripton.fail("In '%s', class '%s' can not be used as type adapter", element, adapterClazz);
return null;
} | java | public static String detectSourceType(Element element, String adapterClazz) {
TypeElement a = BaseProcessor.elementUtils.getTypeElement(adapterClazz);
for (Element i : BaseProcessor.elementUtils.getAllMembers(a)) {
if (i.getKind() == ElementKind.METHOD && "toJava".equals(i.getSimpleName().toString())) {
ExecutableElement method = (ExecutableElement) i;
return TypeUtility.typeName(method.getReturnType()).toString();
}
}
AssertKripton.fail("In '%s', class '%s' can not be used as type adapter", element, adapterClazz);
return null;
} | [
"public",
"static",
"String",
"detectSourceType",
"(",
"Element",
"element",
",",
"String",
"adapterClazz",
")",
"{",
"TypeElement",
"a",
"=",
"BaseProcessor",
".",
"elementUtils",
".",
"getTypeElement",
"(",
"adapterClazz",
")",
";",
"for",
"(",
"Element",
"i",
":",
"BaseProcessor",
".",
"elementUtils",
".",
"getAllMembers",
"(",
"a",
")",
")",
"{",
"if",
"(",
"i",
".",
"getKind",
"(",
")",
"==",
"ElementKind",
".",
"METHOD",
"&&",
"\"toJava\"",
".",
"equals",
"(",
"i",
".",
"getSimpleName",
"(",
")",
".",
"toString",
"(",
")",
")",
")",
"{",
"ExecutableElement",
"method",
"=",
"(",
"ExecutableElement",
")",
"i",
";",
"return",
"TypeUtility",
".",
"typeName",
"(",
"method",
".",
"getReturnType",
"(",
")",
")",
".",
"toString",
"(",
")",
";",
"}",
"}",
"AssertKripton",
".",
"fail",
"(",
"\"In '%s', class '%s' can not be used as type adapter\"",
",",
"element",
",",
"adapterClazz",
")",
";",
"return",
"null",
";",
"}"
]
| Detect source type.
@param element the element
@param adapterClazz the adapter clazz
@return the string | [
"Detect",
"source",
"type",
"."
]
| train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/TypeAdapterHelper.java#L51-L62 |
Mozu/mozu-java | mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/catalog/storefront/ProductUrl.java | ProductUrl.validateProductUrl | public static MozuUrl validateProductUrl(String productCode, String purchaseLocation, Integer quantity, String responseFields, Boolean skipDefaults, Boolean skipInventoryCheck) {
"""
Get Resource Url for ValidateProduct
@param productCode The unique, user-defined product code of a product, used throughout to reference and associate to a product.
@param purchaseLocation The location where the order item(s) was purchased.
@param quantity The number of cart items in the shopper's active cart.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@param skipDefaults Normally, product validation applies default extras to products that do not have options specified. If , product validation does not apply default extras to products.
@param skipInventoryCheck If true, skip the process to validate inventory when creating this product reservation.
@return String Resource Url
"""
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/storefront/products/{productCode}/validate?skipInventoryCheck={skipInventoryCheck}&quantity={quantity}&skipDefaults={skipDefaults}&purchaseLocation={purchaseLocation}&responseFields={responseFields}");
formatter.formatUrl("productCode", productCode);
formatter.formatUrl("purchaseLocation", purchaseLocation);
formatter.formatUrl("quantity", quantity);
formatter.formatUrl("responseFields", responseFields);
formatter.formatUrl("skipDefaults", skipDefaults);
formatter.formatUrl("skipInventoryCheck", skipInventoryCheck);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl validateProductUrl(String productCode, String purchaseLocation, Integer quantity, String responseFields, Boolean skipDefaults, Boolean skipInventoryCheck)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/storefront/products/{productCode}/validate?skipInventoryCheck={skipInventoryCheck}&quantity={quantity}&skipDefaults={skipDefaults}&purchaseLocation={purchaseLocation}&responseFields={responseFields}");
formatter.formatUrl("productCode", productCode);
formatter.formatUrl("purchaseLocation", purchaseLocation);
formatter.formatUrl("quantity", quantity);
formatter.formatUrl("responseFields", responseFields);
formatter.formatUrl("skipDefaults", skipDefaults);
formatter.formatUrl("skipInventoryCheck", skipInventoryCheck);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"validateProductUrl",
"(",
"String",
"productCode",
",",
"String",
"purchaseLocation",
",",
"Integer",
"quantity",
",",
"String",
"responseFields",
",",
"Boolean",
"skipDefaults",
",",
"Boolean",
"skipInventoryCheck",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/catalog/storefront/products/{productCode}/validate?skipInventoryCheck={skipInventoryCheck}&quantity={quantity}&skipDefaults={skipDefaults}&purchaseLocation={purchaseLocation}&responseFields={responseFields}\"",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"productCode\"",
",",
"productCode",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"purchaseLocation\"",
",",
"purchaseLocation",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"quantity\"",
",",
"quantity",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"responseFields\"",
",",
"responseFields",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"skipDefaults\"",
",",
"skipDefaults",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"skipInventoryCheck\"",
",",
"skipInventoryCheck",
")",
";",
"return",
"new",
"MozuUrl",
"(",
"formatter",
".",
"getResourceUrl",
"(",
")",
",",
"MozuUrl",
".",
"UrlLocation",
".",
"TENANT_POD",
")",
";",
"}"
]
| Get Resource Url for ValidateProduct
@param productCode The unique, user-defined product code of a product, used throughout to reference and associate to a product.
@param purchaseLocation The location where the order item(s) was purchased.
@param quantity The number of cart items in the shopper's active cart.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@param skipDefaults Normally, product validation applies default extras to products that do not have options specified. If , product validation does not apply default extras to products.
@param skipInventoryCheck If true, skip the process to validate inventory when creating this product reservation.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"ValidateProduct"
]
| train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/catalog/storefront/ProductUrl.java#L140-L150 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/optimisation/CQJDBCStorageConnection.java | CQJDBCStorageConnection.readACLOwner | protected String readACLOwner(String cid, Map<String, SortedSet<TempPropertyData>> properties)
throws IllegalACLException, IOException {
"""
Read ACL owner.
@param cid - node id (used only in exception message)
@param properties - Property name and property values
@return ACL owner
@throws IllegalACLException
@throws IOException
"""
SortedSet<TempPropertyData> ownerValues = properties.get(Constants.EXO_OWNER.getAsString());
if (ownerValues != null)
{
try
{
return ValueDataUtil.getString(ownerValues.first().getValueData());
}
catch (RepositoryException e)
{
throw new IOException(e.getMessage(), e);
}
}
else
{
throw new IllegalACLException("Property exo:owner is not found for node with id: " + getIdentifier(cid));
}
} | java | protected String readACLOwner(String cid, Map<String, SortedSet<TempPropertyData>> properties)
throws IllegalACLException, IOException
{
SortedSet<TempPropertyData> ownerValues = properties.get(Constants.EXO_OWNER.getAsString());
if (ownerValues != null)
{
try
{
return ValueDataUtil.getString(ownerValues.first().getValueData());
}
catch (RepositoryException e)
{
throw new IOException(e.getMessage(), e);
}
}
else
{
throw new IllegalACLException("Property exo:owner is not found for node with id: " + getIdentifier(cid));
}
} | [
"protected",
"String",
"readACLOwner",
"(",
"String",
"cid",
",",
"Map",
"<",
"String",
",",
"SortedSet",
"<",
"TempPropertyData",
">",
">",
"properties",
")",
"throws",
"IllegalACLException",
",",
"IOException",
"{",
"SortedSet",
"<",
"TempPropertyData",
">",
"ownerValues",
"=",
"properties",
".",
"get",
"(",
"Constants",
".",
"EXO_OWNER",
".",
"getAsString",
"(",
")",
")",
";",
"if",
"(",
"ownerValues",
"!=",
"null",
")",
"{",
"try",
"{",
"return",
"ValueDataUtil",
".",
"getString",
"(",
"ownerValues",
".",
"first",
"(",
")",
".",
"getValueData",
"(",
")",
")",
";",
"}",
"catch",
"(",
"RepositoryException",
"e",
")",
"{",
"throw",
"new",
"IOException",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"IllegalACLException",
"(",
"\"Property exo:owner is not found for node with id: \"",
"+",
"getIdentifier",
"(",
"cid",
")",
")",
";",
"}",
"}"
]
| Read ACL owner.
@param cid - node id (used only in exception message)
@param properties - Property name and property values
@return ACL owner
@throws IllegalACLException
@throws IOException | [
"Read",
"ACL",
"owner",
"."
]
| train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/optimisation/CQJDBCStorageConnection.java#L1288-L1307 |
igniterealtime/Smack | smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/OmemoService.java | OmemoService.buildFreshSessionWithDevice | void buildFreshSessionWithDevice(XMPPConnection connection, OmemoDevice userDevice, OmemoDevice contactsDevice)
throws CannotEstablishOmemoSessionException, SmackException.NotConnectedException, InterruptedException,
SmackException.NoResponseException, CorruptedOmemoKeyException {
"""
Fetch the bundle of a contact and build a fresh OMEMO session with the contacts device.
Note that this builds a fresh session, regardless if we have had a session before or not.
@param connection authenticated XMPP connection
@param userDevice our OmemoDevice
@param contactsDevice OmemoDevice of a contact.
@throws CannotEstablishOmemoSessionException if we cannot establish a session (because of missing bundle etc.)
@throws SmackException.NotConnectedException
@throws InterruptedException
@throws SmackException.NoResponseException
@throws CorruptedOmemoKeyException if our IdentityKeyPair is corrupted.
"""
if (contactsDevice.equals(userDevice)) {
// Do not build a session with yourself.
return;
}
OmemoBundleElement bundleElement;
try {
bundleElement = fetchBundle(connection, contactsDevice);
} catch (XMPPException.XMPPErrorException | PubSubException.NotALeafNodeException |
PubSubException.NotAPubSubNodeException e) {
throw new CannotEstablishOmemoSessionException(contactsDevice, e);
}
// Select random Bundle
HashMap<Integer, T_Bundle> bundlesList = getOmemoStoreBackend().keyUtil().BUNDLE.bundles(bundleElement, contactsDevice);
int randomIndex = new Random().nextInt(bundlesList.size());
T_Bundle randomPreKeyBundle = new ArrayList<>(bundlesList.values()).get(randomIndex);
// build the session
OmemoManager omemoManager = OmemoManager.getInstanceFor(connection, userDevice.getDeviceId());
processBundle(omemoManager, randomPreKeyBundle, contactsDevice);
} | java | void buildFreshSessionWithDevice(XMPPConnection connection, OmemoDevice userDevice, OmemoDevice contactsDevice)
throws CannotEstablishOmemoSessionException, SmackException.NotConnectedException, InterruptedException,
SmackException.NoResponseException, CorruptedOmemoKeyException {
if (contactsDevice.equals(userDevice)) {
// Do not build a session with yourself.
return;
}
OmemoBundleElement bundleElement;
try {
bundleElement = fetchBundle(connection, contactsDevice);
} catch (XMPPException.XMPPErrorException | PubSubException.NotALeafNodeException |
PubSubException.NotAPubSubNodeException e) {
throw new CannotEstablishOmemoSessionException(contactsDevice, e);
}
// Select random Bundle
HashMap<Integer, T_Bundle> bundlesList = getOmemoStoreBackend().keyUtil().BUNDLE.bundles(bundleElement, contactsDevice);
int randomIndex = new Random().nextInt(bundlesList.size());
T_Bundle randomPreKeyBundle = new ArrayList<>(bundlesList.values()).get(randomIndex);
// build the session
OmemoManager omemoManager = OmemoManager.getInstanceFor(connection, userDevice.getDeviceId());
processBundle(omemoManager, randomPreKeyBundle, contactsDevice);
} | [
"void",
"buildFreshSessionWithDevice",
"(",
"XMPPConnection",
"connection",
",",
"OmemoDevice",
"userDevice",
",",
"OmemoDevice",
"contactsDevice",
")",
"throws",
"CannotEstablishOmemoSessionException",
",",
"SmackException",
".",
"NotConnectedException",
",",
"InterruptedException",
",",
"SmackException",
".",
"NoResponseException",
",",
"CorruptedOmemoKeyException",
"{",
"if",
"(",
"contactsDevice",
".",
"equals",
"(",
"userDevice",
")",
")",
"{",
"// Do not build a session with yourself.",
"return",
";",
"}",
"OmemoBundleElement",
"bundleElement",
";",
"try",
"{",
"bundleElement",
"=",
"fetchBundle",
"(",
"connection",
",",
"contactsDevice",
")",
";",
"}",
"catch",
"(",
"XMPPException",
".",
"XMPPErrorException",
"|",
"PubSubException",
".",
"NotALeafNodeException",
"|",
"PubSubException",
".",
"NotAPubSubNodeException",
"e",
")",
"{",
"throw",
"new",
"CannotEstablishOmemoSessionException",
"(",
"contactsDevice",
",",
"e",
")",
";",
"}",
"// Select random Bundle",
"HashMap",
"<",
"Integer",
",",
"T_Bundle",
">",
"bundlesList",
"=",
"getOmemoStoreBackend",
"(",
")",
".",
"keyUtil",
"(",
")",
".",
"BUNDLE",
".",
"bundles",
"(",
"bundleElement",
",",
"contactsDevice",
")",
";",
"int",
"randomIndex",
"=",
"new",
"Random",
"(",
")",
".",
"nextInt",
"(",
"bundlesList",
".",
"size",
"(",
")",
")",
";",
"T_Bundle",
"randomPreKeyBundle",
"=",
"new",
"ArrayList",
"<>",
"(",
"bundlesList",
".",
"values",
"(",
")",
")",
".",
"get",
"(",
"randomIndex",
")",
";",
"// build the session",
"OmemoManager",
"omemoManager",
"=",
"OmemoManager",
".",
"getInstanceFor",
"(",
"connection",
",",
"userDevice",
".",
"getDeviceId",
"(",
")",
")",
";",
"processBundle",
"(",
"omemoManager",
",",
"randomPreKeyBundle",
",",
"contactsDevice",
")",
";",
"}"
]
| Fetch the bundle of a contact and build a fresh OMEMO session with the contacts device.
Note that this builds a fresh session, regardless if we have had a session before or not.
@param connection authenticated XMPP connection
@param userDevice our OmemoDevice
@param contactsDevice OmemoDevice of a contact.
@throws CannotEstablishOmemoSessionException if we cannot establish a session (because of missing bundle etc.)
@throws SmackException.NotConnectedException
@throws InterruptedException
@throws SmackException.NoResponseException
@throws CorruptedOmemoKeyException if our IdentityKeyPair is corrupted. | [
"Fetch",
"the",
"bundle",
"of",
"a",
"contact",
"and",
"build",
"a",
"fresh",
"OMEMO",
"session",
"with",
"the",
"contacts",
"device",
".",
"Note",
"that",
"this",
"builds",
"a",
"fresh",
"session",
"regardless",
"if",
"we",
"have",
"had",
"a",
"session",
"before",
"or",
"not",
"."
]
| train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/OmemoService.java#L761-L786 |
tango-controls/JTango | server/src/main/java/org/tango/server/attribute/AttributeImpl.java | AttributeImpl.setValue | private void setValue(final AttributeValue value, boolean fromMemorizedValue) throws DevFailed {
"""
Write value
@param value
@param fromMemorizedValue true is value comes from tangodb
@throws DevFailed
"""
if (!config.getWritable().equals(AttrWriteType.READ)) {
// final Profiler profilerPeriod = new Profiler("write attribute " + name);
// profilerPeriod.start("check");
checkSetErrors(value);
// profilerPeriod.start("clone");
// copy value for safety and transform it to 2D array if necessary
try {
writeValue = (AttributeValue) value.clone();
} catch (final CloneNotSupportedException e) {
throw DevFailedUtils.newDevFailed(e);
}
// profilerPeriod.start("after clone");
checkMinMaxValue();
writtenTimestamp = writeValue.getTime();
int dimY = writeValue.getYDim();
if (config.getFormat().equals(AttrDataFormat.IMAGE) && dimY == 0) {
// force at least 1 to obtain a real 2D array with [][]
dimY = 1;
}
// profilerPeriod.start("convert image");
value.setValue(ArrayUtils.fromArrayTo2DArray(writeValue.getValue(), writeValue.getXDim(), dimY),
writtenTimestamp);
behavior.setValue(value);
if (isMemorized() && getFormat().equals(AttrDataFormat.SCALAR) && !fromMemorizedValue) {
// TODO: refactoring to manage performance issues for spectrum and
// images
attributePropertiesManager.setAttributePropertyInDB(getName(), Constants.MEMORIZED_VALUE,
getValueAsString()[0]);
// if (getFormat().equals(AttrDataFormat.IMAGE)) {
// deviceImpl.setAttributePropertyInDB(att.getName(),
// Constants.MEMORIZED_VALUE_DIM,
// Integer.toString(value4.w_dim.dim_x),
// Integer.toString(value4.w_dim.dim_y));
// }
}
// profilerPeriod.stop().print();
} else {
throw DevFailedUtils.newDevFailed(ExceptionMessages.ATTR_NOT_WRITABLE, name + " is not writable");
}
} | java | private void setValue(final AttributeValue value, boolean fromMemorizedValue) throws DevFailed {
if (!config.getWritable().equals(AttrWriteType.READ)) {
// final Profiler profilerPeriod = new Profiler("write attribute " + name);
// profilerPeriod.start("check");
checkSetErrors(value);
// profilerPeriod.start("clone");
// copy value for safety and transform it to 2D array if necessary
try {
writeValue = (AttributeValue) value.clone();
} catch (final CloneNotSupportedException e) {
throw DevFailedUtils.newDevFailed(e);
}
// profilerPeriod.start("after clone");
checkMinMaxValue();
writtenTimestamp = writeValue.getTime();
int dimY = writeValue.getYDim();
if (config.getFormat().equals(AttrDataFormat.IMAGE) && dimY == 0) {
// force at least 1 to obtain a real 2D array with [][]
dimY = 1;
}
// profilerPeriod.start("convert image");
value.setValue(ArrayUtils.fromArrayTo2DArray(writeValue.getValue(), writeValue.getXDim(), dimY),
writtenTimestamp);
behavior.setValue(value);
if (isMemorized() && getFormat().equals(AttrDataFormat.SCALAR) && !fromMemorizedValue) {
// TODO: refactoring to manage performance issues for spectrum and
// images
attributePropertiesManager.setAttributePropertyInDB(getName(), Constants.MEMORIZED_VALUE,
getValueAsString()[0]);
// if (getFormat().equals(AttrDataFormat.IMAGE)) {
// deviceImpl.setAttributePropertyInDB(att.getName(),
// Constants.MEMORIZED_VALUE_DIM,
// Integer.toString(value4.w_dim.dim_x),
// Integer.toString(value4.w_dim.dim_y));
// }
}
// profilerPeriod.stop().print();
} else {
throw DevFailedUtils.newDevFailed(ExceptionMessages.ATTR_NOT_WRITABLE, name + " is not writable");
}
} | [
"private",
"void",
"setValue",
"(",
"final",
"AttributeValue",
"value",
",",
"boolean",
"fromMemorizedValue",
")",
"throws",
"DevFailed",
"{",
"if",
"(",
"!",
"config",
".",
"getWritable",
"(",
")",
".",
"equals",
"(",
"AttrWriteType",
".",
"READ",
")",
")",
"{",
"// final Profiler profilerPeriod = new Profiler(\"write attribute \" + name);",
"// profilerPeriod.start(\"check\");",
"checkSetErrors",
"(",
"value",
")",
";",
"// profilerPeriod.start(\"clone\");",
"// copy value for safety and transform it to 2D array if necessary",
"try",
"{",
"writeValue",
"=",
"(",
"AttributeValue",
")",
"value",
".",
"clone",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"CloneNotSupportedException",
"e",
")",
"{",
"throw",
"DevFailedUtils",
".",
"newDevFailed",
"(",
"e",
")",
";",
"}",
"// profilerPeriod.start(\"after clone\");",
"checkMinMaxValue",
"(",
")",
";",
"writtenTimestamp",
"=",
"writeValue",
".",
"getTime",
"(",
")",
";",
"int",
"dimY",
"=",
"writeValue",
".",
"getYDim",
"(",
")",
";",
"if",
"(",
"config",
".",
"getFormat",
"(",
")",
".",
"equals",
"(",
"AttrDataFormat",
".",
"IMAGE",
")",
"&&",
"dimY",
"==",
"0",
")",
"{",
"// force at least 1 to obtain a real 2D array with [][]",
"dimY",
"=",
"1",
";",
"}",
"// profilerPeriod.start(\"convert image\");",
"value",
".",
"setValue",
"(",
"ArrayUtils",
".",
"fromArrayTo2DArray",
"(",
"writeValue",
".",
"getValue",
"(",
")",
",",
"writeValue",
".",
"getXDim",
"(",
")",
",",
"dimY",
")",
",",
"writtenTimestamp",
")",
";",
"behavior",
".",
"setValue",
"(",
"value",
")",
";",
"if",
"(",
"isMemorized",
"(",
")",
"&&",
"getFormat",
"(",
")",
".",
"equals",
"(",
"AttrDataFormat",
".",
"SCALAR",
")",
"&&",
"!",
"fromMemorizedValue",
")",
"{",
"// TODO: refactoring to manage performance issues for spectrum and",
"// images",
"attributePropertiesManager",
".",
"setAttributePropertyInDB",
"(",
"getName",
"(",
")",
",",
"Constants",
".",
"MEMORIZED_VALUE",
",",
"getValueAsString",
"(",
")",
"[",
"0",
"]",
")",
";",
"// if (getFormat().equals(AttrDataFormat.IMAGE)) {",
"// deviceImpl.setAttributePropertyInDB(att.getName(),",
"// Constants.MEMORIZED_VALUE_DIM,",
"// Integer.toString(value4.w_dim.dim_x),",
"// Integer.toString(value4.w_dim.dim_y));",
"// }",
"}",
"// profilerPeriod.stop().print();",
"}",
"else",
"{",
"throw",
"DevFailedUtils",
".",
"newDevFailed",
"(",
"ExceptionMessages",
".",
"ATTR_NOT_WRITABLE",
",",
"name",
"+",
"\" is not writable\"",
")",
";",
"}",
"}"
]
| Write value
@param value
@param fromMemorizedValue true is value comes from tangodb
@throws DevFailed | [
"Write",
"value"
]
| train | https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/attribute/AttributeImpl.java#L458-L500 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/LevelRipConverter.java | LevelRipConverter.checkPixel | private static boolean checkPixel(MapTile map, ImageBuffer tileRef, int progressTileX, int progressTileY) {
"""
Check the pixel by searching tile on sheet.
@param map The destination map reference.
@param tileRef The tile sheet.
@param progressTileX The progress on horizontal tiles.
@param progressTileY The progress on vertical tiles.
@return <code>true</code> if tile found, <code>false</code> else.
"""
final int x = progressTileX * map.getTileWidth();
final int y = progressTileY * map.getTileHeight();
final int pixel = tileRef.getRgb(x, y);
// Skip blank tile of image map
if (TilesExtractor.IGNORED_COLOR_VALUE != pixel)
{
// Search if tile is on sheet and get it
final Tile tile = searchForTile(map, tileRef, progressTileX, progressTileY);
if (tile == null)
{
return false;
}
map.setTile(tile);
}
return true;
} | java | private static boolean checkPixel(MapTile map, ImageBuffer tileRef, int progressTileX, int progressTileY)
{
final int x = progressTileX * map.getTileWidth();
final int y = progressTileY * map.getTileHeight();
final int pixel = tileRef.getRgb(x, y);
// Skip blank tile of image map
if (TilesExtractor.IGNORED_COLOR_VALUE != pixel)
{
// Search if tile is on sheet and get it
final Tile tile = searchForTile(map, tileRef, progressTileX, progressTileY);
if (tile == null)
{
return false;
}
map.setTile(tile);
}
return true;
} | [
"private",
"static",
"boolean",
"checkPixel",
"(",
"MapTile",
"map",
",",
"ImageBuffer",
"tileRef",
",",
"int",
"progressTileX",
",",
"int",
"progressTileY",
")",
"{",
"final",
"int",
"x",
"=",
"progressTileX",
"*",
"map",
".",
"getTileWidth",
"(",
")",
";",
"final",
"int",
"y",
"=",
"progressTileY",
"*",
"map",
".",
"getTileHeight",
"(",
")",
";",
"final",
"int",
"pixel",
"=",
"tileRef",
".",
"getRgb",
"(",
"x",
",",
"y",
")",
";",
"// Skip blank tile of image map",
"if",
"(",
"TilesExtractor",
".",
"IGNORED_COLOR_VALUE",
"!=",
"pixel",
")",
"{",
"// Search if tile is on sheet and get it",
"final",
"Tile",
"tile",
"=",
"searchForTile",
"(",
"map",
",",
"tileRef",
",",
"progressTileX",
",",
"progressTileY",
")",
";",
"if",
"(",
"tile",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"map",
".",
"setTile",
"(",
"tile",
")",
";",
"}",
"return",
"true",
";",
"}"
]
| Check the pixel by searching tile on sheet.
@param map The destination map reference.
@param tileRef The tile sheet.
@param progressTileX The progress on horizontal tiles.
@param progressTileY The progress on vertical tiles.
@return <code>true</code> if tile found, <code>false</code> else. | [
"Check",
"the",
"pixel",
"by",
"searching",
"tile",
"on",
"sheet",
"."
]
| train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/LevelRipConverter.java#L127-L145 |
aws/aws-sdk-java | aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/ListDevEndpointsRequest.java | ListDevEndpointsRequest.withTags | public ListDevEndpointsRequest withTags(java.util.Map<String, String> tags) {
"""
<p>
Specifies to return only these tagged resources.
</p>
@param tags
Specifies to return only these tagged resources.
@return Returns a reference to this object so that method calls can be chained together.
"""
setTags(tags);
return this;
} | java | public ListDevEndpointsRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"ListDevEndpointsRequest",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
]
| <p>
Specifies to return only these tagged resources.
</p>
@param tags
Specifies to return only these tagged resources.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"Specifies",
"to",
"return",
"only",
"these",
"tagged",
"resources",
".",
"<",
"/",
"p",
">"
]
| train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/ListDevEndpointsRequest.java#L162-L165 |
Azure/azure-sdk-for-java | notificationhubs/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2016_03_01/implementation/NamespacesInner.java | NamespacesInner.regenerateKeysAsync | public Observable<ResourceListKeysInner> regenerateKeysAsync(String resourceGroupName, String namespaceName, String authorizationRuleName) {
"""
Regenerates the Primary/Secondary Keys to the Namespace Authorization Rule.
@param resourceGroupName The name of the resource group.
@param namespaceName The namespace name.
@param authorizationRuleName The connection string of the namespace for the specified authorizationRule.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ResourceListKeysInner object
"""
return regenerateKeysWithServiceResponseAsync(resourceGroupName, namespaceName, authorizationRuleName).map(new Func1<ServiceResponse<ResourceListKeysInner>, ResourceListKeysInner>() {
@Override
public ResourceListKeysInner call(ServiceResponse<ResourceListKeysInner> response) {
return response.body();
}
});
} | java | public Observable<ResourceListKeysInner> regenerateKeysAsync(String resourceGroupName, String namespaceName, String authorizationRuleName) {
return regenerateKeysWithServiceResponseAsync(resourceGroupName, namespaceName, authorizationRuleName).map(new Func1<ServiceResponse<ResourceListKeysInner>, ResourceListKeysInner>() {
@Override
public ResourceListKeysInner call(ServiceResponse<ResourceListKeysInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ResourceListKeysInner",
">",
"regenerateKeysAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"namespaceName",
",",
"String",
"authorizationRuleName",
")",
"{",
"return",
"regenerateKeysWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"namespaceName",
",",
"authorizationRuleName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ResourceListKeysInner",
">",
",",
"ResourceListKeysInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ResourceListKeysInner",
"call",
"(",
"ServiceResponse",
"<",
"ResourceListKeysInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Regenerates the Primary/Secondary Keys to the Namespace Authorization Rule.
@param resourceGroupName The name of the resource group.
@param namespaceName The namespace name.
@param authorizationRuleName The connection string of the namespace for the specified authorizationRule.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ResourceListKeysInner object | [
"Regenerates",
"the",
"Primary",
"/",
"Secondary",
"Keys",
"to",
"the",
"Namespace",
"Authorization",
"Rule",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/notificationhubs/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2016_03_01/implementation/NamespacesInner.java#L1417-L1424 |
aol/cyclops | cyclops/src/main/java/cyclops/companion/Functions.java | Functions.skipDoubles | public static Function<? super ReactiveSeq<Double>, ? extends ReactiveSeq<Double>> skipDoubles(long skip) {
"""
/*
Fluent limit operation using primitive types
e.g.
<pre>
{@code
import static cyclops.ReactiveSeq.skipDoubles;
ReactiveSeq.ofDoubles(1d,2d,3d)
.to(limitDoubles(1));
//[1d]
}
</pre>
"""
return a->a.doubles(i->i,s->s.skip(skip));
} | java | public static Function<? super ReactiveSeq<Double>, ? extends ReactiveSeq<Double>> skipDoubles(long skip){
return a->a.doubles(i->i,s->s.skip(skip));
} | [
"public",
"static",
"Function",
"<",
"?",
"super",
"ReactiveSeq",
"<",
"Double",
">",
",",
"?",
"extends",
"ReactiveSeq",
"<",
"Double",
">",
">",
"skipDoubles",
"(",
"long",
"skip",
")",
"{",
"return",
"a",
"->",
"a",
".",
"doubles",
"(",
"i",
"->",
"i",
",",
"s",
"->",
"s",
".",
"skip",
"(",
"skip",
")",
")",
";",
"}"
]
| /*
Fluent limit operation using primitive types
e.g.
<pre>
{@code
import static cyclops.ReactiveSeq.skipDoubles;
ReactiveSeq.ofDoubles(1d,2d,3d)
.to(limitDoubles(1));
//[1d]
}
</pre> | [
"/",
"*",
"Fluent",
"limit",
"operation",
"using",
"primitive",
"types",
"e",
".",
"g",
".",
"<pre",
">",
"{",
"@code",
"import",
"static",
"cyclops",
".",
"ReactiveSeq",
".",
"skipDoubles",
";"
]
| train | https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/cyclops/companion/Functions.java#L480-L483 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCrossConnectionsInner.java | ExpressRouteCrossConnectionsInner.beginCreateOrUpdate | public ExpressRouteCrossConnectionInner beginCreateOrUpdate(String resourceGroupName, String crossConnectionName, ExpressRouteCrossConnectionInner parameters) {
"""
Update the specified ExpressRouteCrossConnection.
@param resourceGroupName The name of the resource group.
@param crossConnectionName The name of the ExpressRouteCrossConnection.
@param parameters Parameters supplied to the update express route crossConnection operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ExpressRouteCrossConnectionInner object if successful.
"""
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, crossConnectionName, parameters).toBlocking().single().body();
} | java | public ExpressRouteCrossConnectionInner beginCreateOrUpdate(String resourceGroupName, String crossConnectionName, ExpressRouteCrossConnectionInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, crossConnectionName, parameters).toBlocking().single().body();
} | [
"public",
"ExpressRouteCrossConnectionInner",
"beginCreateOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"crossConnectionName",
",",
"ExpressRouteCrossConnectionInner",
"parameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"crossConnectionName",
",",
"parameters",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
]
| Update the specified ExpressRouteCrossConnection.
@param resourceGroupName The name of the resource group.
@param crossConnectionName The name of the ExpressRouteCrossConnection.
@param parameters Parameters supplied to the update express route crossConnection operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ExpressRouteCrossConnectionInner object if successful. | [
"Update",
"the",
"specified",
"ExpressRouteCrossConnection",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCrossConnectionsInner.java#L519-L521 |
webmetrics/browsermob-proxy | src/main/java/cz/mallat/uasparser/UASparser.java | UASparser.copyType | private void copyType(UserAgentInfo retObj, Long idBrowser) {
"""
Sets the source type, if possible
@param retObj
@param idBrowser
"""
try {
lock.lock();
BrowserEntry be = browserMap.get(idBrowser);
if (be != null) {
Long type = be.getType();
if (type != null) {
String typeString = browserTypeMap.get(type);
if (typeString != null) {
retObj.setTyp(typeString);
}
}
}
} finally {
lock.unlock();
}
} | java | private void copyType(UserAgentInfo retObj, Long idBrowser) {
try {
lock.lock();
BrowserEntry be = browserMap.get(idBrowser);
if (be != null) {
Long type = be.getType();
if (type != null) {
String typeString = browserTypeMap.get(type);
if (typeString != null) {
retObj.setTyp(typeString);
}
}
}
} finally {
lock.unlock();
}
} | [
"private",
"void",
"copyType",
"(",
"UserAgentInfo",
"retObj",
",",
"Long",
"idBrowser",
")",
"{",
"try",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"BrowserEntry",
"be",
"=",
"browserMap",
".",
"get",
"(",
"idBrowser",
")",
";",
"if",
"(",
"be",
"!=",
"null",
")",
"{",
"Long",
"type",
"=",
"be",
".",
"getType",
"(",
")",
";",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
"String",
"typeString",
"=",
"browserTypeMap",
".",
"get",
"(",
"type",
")",
";",
"if",
"(",
"typeString",
"!=",
"null",
")",
"{",
"retObj",
".",
"setTyp",
"(",
"typeString",
")",
";",
"}",
"}",
"}",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
]
| Sets the source type, if possible
@param retObj
@param idBrowser | [
"Sets",
"the",
"source",
"type",
"if",
"possible"
]
| train | https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/cz/mallat/uasparser/UASparser.java#L182-L199 |
ineunetOS/knife-commons | knife-commons-utils/src/main/java/com/ineunet/knife/util/validation/WebValidator.java | WebValidator.notBlankSpace | public IValidator notBlankSpace(String propertyTitle, String propertyValue) {
"""
验证不能为纯空格. Validate not all spaces.
@param propertyTitle
@param propertyValue
@since 2.0.1
"""
return this.appendError(WebValidatorRestrictor.notBlankSpace(propertyTitle, propertyValue));
} | java | public IValidator notBlankSpace(String propertyTitle, String propertyValue) {
return this.appendError(WebValidatorRestrictor.notBlankSpace(propertyTitle, propertyValue));
} | [
"public",
"IValidator",
"notBlankSpace",
"(",
"String",
"propertyTitle",
",",
"String",
"propertyValue",
")",
"{",
"return",
"this",
".",
"appendError",
"(",
"WebValidatorRestrictor",
".",
"notBlankSpace",
"(",
"propertyTitle",
",",
"propertyValue",
")",
")",
";",
"}"
]
| 验证不能为纯空格. Validate not all spaces.
@param propertyTitle
@param propertyValue
@since 2.0.1 | [
"验证不能为纯空格",
".",
"Validate",
"not",
"all",
"spaces",
"."
]
| train | https://github.com/ineunetOS/knife-commons/blob/eae9e59afa020a00ae8977c10d43ac8ae46ae236/knife-commons-utils/src/main/java/com/ineunet/knife/util/validation/WebValidator.java#L92-L94 |
apache/incubator-heron | heron/common/src/java/org/apache/heron/common/utils/logging/ErrorReportLoggingHandler.java | ErrorReportLoggingHandler.publish | @Override
public void publish(LogRecord record) {
"""
will flush the exception to metrics manager during getValueAndReset call.
"""
// Convert Log
Throwable throwable = record.getThrown();
if (throwable != null) {
synchronized (ExceptionRepositoryAsMetrics.INSTANCE) {
// We would not include the message if already exceeded the exceptions limit
if (ExceptionRepositoryAsMetrics.INSTANCE.getExceptionsCount() >= exceptionsLimit) {
droppedExceptionsCount.incr();
return;
}
// Convert the record
StringWriter sink = new StringWriter();
throwable.printStackTrace(new PrintWriter(sink, true));
String trace = sink.toString();
Metrics.ExceptionData.Builder exceptionDataBuilder =
ExceptionRepositoryAsMetrics.INSTANCE.getExceptionInfo(trace);
exceptionDataBuilder.setCount(exceptionDataBuilder.getCount() + 1);
exceptionDataBuilder.setLasttime(new Date().toString());
exceptionDataBuilder.setStacktrace(trace);
// Can cause NPE and crash HI
//exceptionDataBuilder.setLogging(record.getMessage());
if (record.getMessage() == null) {
exceptionDataBuilder.setLogging("");
} else {
exceptionDataBuilder.setLogging(record.getMessage());
}
}
}
} | java | @Override
public void publish(LogRecord record) {
// Convert Log
Throwable throwable = record.getThrown();
if (throwable != null) {
synchronized (ExceptionRepositoryAsMetrics.INSTANCE) {
// We would not include the message if already exceeded the exceptions limit
if (ExceptionRepositoryAsMetrics.INSTANCE.getExceptionsCount() >= exceptionsLimit) {
droppedExceptionsCount.incr();
return;
}
// Convert the record
StringWriter sink = new StringWriter();
throwable.printStackTrace(new PrintWriter(sink, true));
String trace = sink.toString();
Metrics.ExceptionData.Builder exceptionDataBuilder =
ExceptionRepositoryAsMetrics.INSTANCE.getExceptionInfo(trace);
exceptionDataBuilder.setCount(exceptionDataBuilder.getCount() + 1);
exceptionDataBuilder.setLasttime(new Date().toString());
exceptionDataBuilder.setStacktrace(trace);
// Can cause NPE and crash HI
//exceptionDataBuilder.setLogging(record.getMessage());
if (record.getMessage() == null) {
exceptionDataBuilder.setLogging("");
} else {
exceptionDataBuilder.setLogging(record.getMessage());
}
}
}
} | [
"@",
"Override",
"public",
"void",
"publish",
"(",
"LogRecord",
"record",
")",
"{",
"// Convert Log",
"Throwable",
"throwable",
"=",
"record",
".",
"getThrown",
"(",
")",
";",
"if",
"(",
"throwable",
"!=",
"null",
")",
"{",
"synchronized",
"(",
"ExceptionRepositoryAsMetrics",
".",
"INSTANCE",
")",
"{",
"// We would not include the message if already exceeded the exceptions limit",
"if",
"(",
"ExceptionRepositoryAsMetrics",
".",
"INSTANCE",
".",
"getExceptionsCount",
"(",
")",
">=",
"exceptionsLimit",
")",
"{",
"droppedExceptionsCount",
".",
"incr",
"(",
")",
";",
"return",
";",
"}",
"// Convert the record",
"StringWriter",
"sink",
"=",
"new",
"StringWriter",
"(",
")",
";",
"throwable",
".",
"printStackTrace",
"(",
"new",
"PrintWriter",
"(",
"sink",
",",
"true",
")",
")",
";",
"String",
"trace",
"=",
"sink",
".",
"toString",
"(",
")",
";",
"Metrics",
".",
"ExceptionData",
".",
"Builder",
"exceptionDataBuilder",
"=",
"ExceptionRepositoryAsMetrics",
".",
"INSTANCE",
".",
"getExceptionInfo",
"(",
"trace",
")",
";",
"exceptionDataBuilder",
".",
"setCount",
"(",
"exceptionDataBuilder",
".",
"getCount",
"(",
")",
"+",
"1",
")",
";",
"exceptionDataBuilder",
".",
"setLasttime",
"(",
"new",
"Date",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"exceptionDataBuilder",
".",
"setStacktrace",
"(",
"trace",
")",
";",
"// Can cause NPE and crash HI",
"//exceptionDataBuilder.setLogging(record.getMessage());",
"if",
"(",
"record",
".",
"getMessage",
"(",
")",
"==",
"null",
")",
"{",
"exceptionDataBuilder",
".",
"setLogging",
"(",
"\"\"",
")",
";",
"}",
"else",
"{",
"exceptionDataBuilder",
".",
"setLogging",
"(",
"record",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"}",
"}"
]
| will flush the exception to metrics manager during getValueAndReset call. | [
"will",
"flush",
"the",
"exception",
"to",
"metrics",
"manager",
"during",
"getValueAndReset",
"call",
"."
]
| train | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/utils/logging/ErrorReportLoggingHandler.java#L90-L123 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/utils/SIMPUtils.java | SIMPUtils.getRemoteGetKey | public static String getRemoteGetKey(SIBUuid8 remoteUuid, SIBUuid12 gatheringTargetDestUuid) {
"""
The key we use to lookup/insert a streamInfo object is based off the remoteMEuuid +
the gatheringTargetDestUuid. This second value is null for standard consumer and set
to a destinationUuid (which could be an alias) for gathering consumers. In this way
we have seperate streams per consumer type.
"""
String key = null;
if (gatheringTargetDestUuid!=null)
key = remoteUuid.toString()+gatheringTargetDestUuid.toString();
else
key = remoteUuid.toString()+SIMPConstants.DEFAULT_CONSUMER_SET;
return key;
} | java | public static String getRemoteGetKey(SIBUuid8 remoteUuid, SIBUuid12 gatheringTargetDestUuid)
{
String key = null;
if (gatheringTargetDestUuid!=null)
key = remoteUuid.toString()+gatheringTargetDestUuid.toString();
else
key = remoteUuid.toString()+SIMPConstants.DEFAULT_CONSUMER_SET;
return key;
} | [
"public",
"static",
"String",
"getRemoteGetKey",
"(",
"SIBUuid8",
"remoteUuid",
",",
"SIBUuid12",
"gatheringTargetDestUuid",
")",
"{",
"String",
"key",
"=",
"null",
";",
"if",
"(",
"gatheringTargetDestUuid",
"!=",
"null",
")",
"key",
"=",
"remoteUuid",
".",
"toString",
"(",
")",
"+",
"gatheringTargetDestUuid",
".",
"toString",
"(",
")",
";",
"else",
"key",
"=",
"remoteUuid",
".",
"toString",
"(",
")",
"+",
"SIMPConstants",
".",
"DEFAULT_CONSUMER_SET",
";",
"return",
"key",
";",
"}"
]
| The key we use to lookup/insert a streamInfo object is based off the remoteMEuuid +
the gatheringTargetDestUuid. This second value is null for standard consumer and set
to a destinationUuid (which could be an alias) for gathering consumers. In this way
we have seperate streams per consumer type. | [
"The",
"key",
"we",
"use",
"to",
"lookup",
"/",
"insert",
"a",
"streamInfo",
"object",
"is",
"based",
"off",
"the",
"remoteMEuuid",
"+",
"the",
"gatheringTargetDestUuid",
".",
"This",
"second",
"value",
"is",
"null",
"for",
"standard",
"consumer",
"and",
"set",
"to",
"a",
"destinationUuid",
"(",
"which",
"could",
"be",
"an",
"alias",
")",
"for",
"gathering",
"consumers",
".",
"In",
"this",
"way",
"we",
"have",
"seperate",
"streams",
"per",
"consumer",
"type",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/utils/SIMPUtils.java#L317-L325 |
apache/groovy | src/main/java/org/apache/groovy/plugin/GroovyRunnerRegistry.java | GroovyRunnerRegistry.putAll | @Override
public void putAll(Map<? extends String, ? extends GroovyRunner> m) {
"""
Adds all entries from the given Map to the registry.
Any entries in the provided Map that contain a {@code null}
key or value will be ignored.
@param m entries to add to the registry
@throws NullPointerException if the given Map is {@code null}
"""
Map<String, GroovyRunner> map = getMap();
writeLock.lock();
try {
cachedValues = null;
for (Map.Entry<? extends String, ? extends GroovyRunner> entry : m.entrySet()) {
if (entry.getKey() != null && entry.getValue() != null) {
map.put(entry.getKey(), entry.getValue());
}
}
} finally {
writeLock.unlock();
}
} | java | @Override
public void putAll(Map<? extends String, ? extends GroovyRunner> m) {
Map<String, GroovyRunner> map = getMap();
writeLock.lock();
try {
cachedValues = null;
for (Map.Entry<? extends String, ? extends GroovyRunner> entry : m.entrySet()) {
if (entry.getKey() != null && entry.getValue() != null) {
map.put(entry.getKey(), entry.getValue());
}
}
} finally {
writeLock.unlock();
}
} | [
"@",
"Override",
"public",
"void",
"putAll",
"(",
"Map",
"<",
"?",
"extends",
"String",
",",
"?",
"extends",
"GroovyRunner",
">",
"m",
")",
"{",
"Map",
"<",
"String",
",",
"GroovyRunner",
">",
"map",
"=",
"getMap",
"(",
")",
";",
"writeLock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"cachedValues",
"=",
"null",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"?",
"extends",
"String",
",",
"?",
"extends",
"GroovyRunner",
">",
"entry",
":",
"m",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"entry",
".",
"getKey",
"(",
")",
"!=",
"null",
"&&",
"entry",
".",
"getValue",
"(",
")",
"!=",
"null",
")",
"{",
"map",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"}",
"finally",
"{",
"writeLock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
]
| Adds all entries from the given Map to the registry.
Any entries in the provided Map that contain a {@code null}
key or value will be ignored.
@param m entries to add to the registry
@throws NullPointerException if the given Map is {@code null} | [
"Adds",
"all",
"entries",
"from",
"the",
"given",
"Map",
"to",
"the",
"registry",
".",
"Any",
"entries",
"in",
"the",
"provided",
"Map",
"that",
"contain",
"a",
"{",
"@code",
"null",
"}",
"key",
"or",
"value",
"will",
"be",
"ignored",
"."
]
| train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/apache/groovy/plugin/GroovyRunnerRegistry.java#L356-L370 |
feedzai/pdb | src/main/java/com/feedzai/commons/sql/abstraction/dml/dialect/SqlBuilder.java | SqlBuilder.caseWhen | public static Case caseWhen(final Expression condition, final Expression trueAction) {
"""
Creates a case expression.
@param condition The name of the view.
@param trueAction The name of the view.
@return The case when representation.
"""
return Case.caseWhen(condition, trueAction);
} | java | public static Case caseWhen(final Expression condition, final Expression trueAction) {
return Case.caseWhen(condition, trueAction);
} | [
"public",
"static",
"Case",
"caseWhen",
"(",
"final",
"Expression",
"condition",
",",
"final",
"Expression",
"trueAction",
")",
"{",
"return",
"Case",
".",
"caseWhen",
"(",
"condition",
",",
"trueAction",
")",
";",
"}"
]
| Creates a case expression.
@param condition The name of the view.
@param trueAction The name of the view.
@return The case when representation. | [
"Creates",
"a",
"case",
"expression",
"."
]
| train | https://github.com/feedzai/pdb/blob/fe07ca08417e0ddcd620a36aa1fdbca7f338be98/src/main/java/com/feedzai/commons/sql/abstraction/dml/dialect/SqlBuilder.java#L592-L594 |
aNNiMON/Lightweight-Stream-API | stream/src/main/java/com/annimon/stream/Collectors.java | Collectors.toMap | @NotNull
public static <T, K, V, M extends Map<K, V>> Collector<T, ?, M> toMap(
@NotNull final Function<? super T, ? extends K> keyMapper,
@NotNull final Function<? super T, ? extends V> valueMapper,
@NotNull final Supplier<M> mapFactory) {
"""
Returns a {@code Collector} that fills new {@code Map} with input elements.
If the mapped keys contain duplicates, an {@code IllegalStateException} is thrown.
Use {@link #toMap(Function, Function, BinaryOperator, Supplier)} to handle merging of the values.
@param <T> the type of the input elements
@param <K> the result type of key mapping function
@param <V> the result type of value mapping function
@param <M> the type of the resulting {@code Map}
@param keyMapper a mapping function to produce keys
@param valueMapper a mapping function to produce values
@param mapFactory a supplier function that provides new {@code Map}
@return a {@code Collector}
@see #toMap(Function, Function, BinaryOperator, Supplier)
"""
return new CollectorsImpl<T, M, M>(
mapFactory,
new BiConsumer<M, T>() {
@Override
public void accept(M map, T t) {
final K key = keyMapper.apply(t);
final V value = Objects.requireNonNull(valueMapper.apply(t));
// To avoid calling map.get to determine duplicate keys
// we check the result of map.put
final V oldValue = map.put(key, value);
if (oldValue != null) {
// If there is duplicate key, rollback previous put operation
map.put(key, oldValue);
throw duplicateKeyException(key, oldValue, value);
}
}
}
);
} | java | @NotNull
public static <T, K, V, M extends Map<K, V>> Collector<T, ?, M> toMap(
@NotNull final Function<? super T, ? extends K> keyMapper,
@NotNull final Function<? super T, ? extends V> valueMapper,
@NotNull final Supplier<M> mapFactory) {
return new CollectorsImpl<T, M, M>(
mapFactory,
new BiConsumer<M, T>() {
@Override
public void accept(M map, T t) {
final K key = keyMapper.apply(t);
final V value = Objects.requireNonNull(valueMapper.apply(t));
// To avoid calling map.get to determine duplicate keys
// we check the result of map.put
final V oldValue = map.put(key, value);
if (oldValue != null) {
// If there is duplicate key, rollback previous put operation
map.put(key, oldValue);
throw duplicateKeyException(key, oldValue, value);
}
}
}
);
} | [
"@",
"NotNull",
"public",
"static",
"<",
"T",
",",
"K",
",",
"V",
",",
"M",
"extends",
"Map",
"<",
"K",
",",
"V",
">",
">",
"Collector",
"<",
"T",
",",
"?",
",",
"M",
">",
"toMap",
"(",
"@",
"NotNull",
"final",
"Function",
"<",
"?",
"super",
"T",
",",
"?",
"extends",
"K",
">",
"keyMapper",
",",
"@",
"NotNull",
"final",
"Function",
"<",
"?",
"super",
"T",
",",
"?",
"extends",
"V",
">",
"valueMapper",
",",
"@",
"NotNull",
"final",
"Supplier",
"<",
"M",
">",
"mapFactory",
")",
"{",
"return",
"new",
"CollectorsImpl",
"<",
"T",
",",
"M",
",",
"M",
">",
"(",
"mapFactory",
",",
"new",
"BiConsumer",
"<",
"M",
",",
"T",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"accept",
"(",
"M",
"map",
",",
"T",
"t",
")",
"{",
"final",
"K",
"key",
"=",
"keyMapper",
".",
"apply",
"(",
"t",
")",
";",
"final",
"V",
"value",
"=",
"Objects",
".",
"requireNonNull",
"(",
"valueMapper",
".",
"apply",
"(",
"t",
")",
")",
";",
"// To avoid calling map.get to determine duplicate keys",
"// we check the result of map.put",
"final",
"V",
"oldValue",
"=",
"map",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"if",
"(",
"oldValue",
"!=",
"null",
")",
"{",
"// If there is duplicate key, rollback previous put operation",
"map",
".",
"put",
"(",
"key",
",",
"oldValue",
")",
";",
"throw",
"duplicateKeyException",
"(",
"key",
",",
"oldValue",
",",
"value",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
]
| Returns a {@code Collector} that fills new {@code Map} with input elements.
If the mapped keys contain duplicates, an {@code IllegalStateException} is thrown.
Use {@link #toMap(Function, Function, BinaryOperator, Supplier)} to handle merging of the values.
@param <T> the type of the input elements
@param <K> the result type of key mapping function
@param <V> the result type of value mapping function
@param <M> the type of the resulting {@code Map}
@param keyMapper a mapping function to produce keys
@param valueMapper a mapping function to produce values
@param mapFactory a supplier function that provides new {@code Map}
@return a {@code Collector}
@see #toMap(Function, Function, BinaryOperator, Supplier) | [
"Returns",
"a",
"{",
"@code",
"Collector",
"}",
"that",
"fills",
"new",
"{",
"@code",
"Map",
"}",
"with",
"input",
"elements",
"."
]
| train | https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Collectors.java#L224-L250 |
nextreports/nextreports-server | src/ro/nextreports/server/dao/JcrSecurityDao.java | JcrSecurityDao.grantRawAclEntry | private void grantRawAclEntry(String entityPath, String rawAclEntry, boolean recursive) throws NotFoundException {
"""
/*
private void grantRecursiveRawAclEntryById(String entityId, String rawAclEntry) throws NotFoundException {
Entity[] children = storageDao.getEntityChildrenById(entityId);
if (children.length == 0) {
return;
}
for (Entity child : children) {
grantNodeRawAclEntryById(child.getId(), rawAclEntry, false);
grantRecursiveRawAclEntryById(child.getId(), rawAclEntry);
}
}
"""
grantNodeRawAclEntry(entityPath, rawAclEntry, false);
int permissions = 0;
permissions = PermissionUtil.setRead(permissions);
AclEntry aclEntry = new AclEntry(AclUtil.getType(rawAclEntry), AclUtil.getName(rawAclEntry), permissions);
// grant read to all parent nodes
String pPath = entityPath;
while(true) {
String parentPath = StorageUtil.getParentPath(pPath);
if (StorageUtil.isSystemPath(parentPath)) {
break;
}
grantNodeRawAclEntry(parentPath, AclUtil.encodeAclEntry(aclEntry), true);
pPath = parentPath;
}
// recursive grant to all children
if (recursive) {
grantRecursiveRawAclEntry(entityPath, rawAclEntry);
}
getTemplate().save();
} | java | private void grantRawAclEntry(String entityPath, String rawAclEntry, boolean recursive) throws NotFoundException {
grantNodeRawAclEntry(entityPath, rawAclEntry, false);
int permissions = 0;
permissions = PermissionUtil.setRead(permissions);
AclEntry aclEntry = new AclEntry(AclUtil.getType(rawAclEntry), AclUtil.getName(rawAclEntry), permissions);
// grant read to all parent nodes
String pPath = entityPath;
while(true) {
String parentPath = StorageUtil.getParentPath(pPath);
if (StorageUtil.isSystemPath(parentPath)) {
break;
}
grantNodeRawAclEntry(parentPath, AclUtil.encodeAclEntry(aclEntry), true);
pPath = parentPath;
}
// recursive grant to all children
if (recursive) {
grantRecursiveRawAclEntry(entityPath, rawAclEntry);
}
getTemplate().save();
} | [
"private",
"void",
"grantRawAclEntry",
"(",
"String",
"entityPath",
",",
"String",
"rawAclEntry",
",",
"boolean",
"recursive",
")",
"throws",
"NotFoundException",
"{",
"grantNodeRawAclEntry",
"(",
"entityPath",
",",
"rawAclEntry",
",",
"false",
")",
";",
"int",
"permissions",
"=",
"0",
";",
"permissions",
"=",
"PermissionUtil",
".",
"setRead",
"(",
"permissions",
")",
";",
"AclEntry",
"aclEntry",
"=",
"new",
"AclEntry",
"(",
"AclUtil",
".",
"getType",
"(",
"rawAclEntry",
")",
",",
"AclUtil",
".",
"getName",
"(",
"rawAclEntry",
")",
",",
"permissions",
")",
";",
"// grant read to all parent nodes",
"String",
"pPath",
"=",
"entityPath",
";",
"while",
"(",
"true",
")",
"{",
"String",
"parentPath",
"=",
"StorageUtil",
".",
"getParentPath",
"(",
"pPath",
")",
";",
"if",
"(",
"StorageUtil",
".",
"isSystemPath",
"(",
"parentPath",
")",
")",
"{",
"break",
";",
"}",
"grantNodeRawAclEntry",
"(",
"parentPath",
",",
"AclUtil",
".",
"encodeAclEntry",
"(",
"aclEntry",
")",
",",
"true",
")",
";",
"pPath",
"=",
"parentPath",
";",
"}",
"// recursive grant to all children",
"if",
"(",
"recursive",
")",
"{",
"grantRecursiveRawAclEntry",
"(",
"entityPath",
",",
"rawAclEntry",
")",
";",
"}",
"getTemplate",
"(",
")",
".",
"save",
"(",
")",
";",
"}"
]
| /*
private void grantRecursiveRawAclEntryById(String entityId, String rawAclEntry) throws NotFoundException {
Entity[] children = storageDao.getEntityChildrenById(entityId);
if (children.length == 0) {
return;
}
for (Entity child : children) {
grantNodeRawAclEntryById(child.getId(), rawAclEntry, false);
grantRecursiveRawAclEntryById(child.getId(), rawAclEntry);
}
} | [
"/",
"*",
"private",
"void",
"grantRecursiveRawAclEntryById",
"(",
"String",
"entityId",
"String",
"rawAclEntry",
")",
"throws",
"NotFoundException",
"{",
"Entity",
"[]",
"children",
"=",
"storageDao",
".",
"getEntityChildrenById",
"(",
"entityId",
")",
";",
"if",
"(",
"children",
".",
"length",
"==",
"0",
")",
"{",
"return",
";",
"}"
]
| train | https://github.com/nextreports/nextreports-server/blob/cfce12f5c6d52cb6a739388d50142c6e2e07c55e/src/ro/nextreports/server/dao/JcrSecurityDao.java#L331-L355 |
apereo/cas | support/cas-server-support-wsfederation/src/main/java/org/apereo/cas/support/wsfederation/authentication/principal/WsFederationCredentialsToPrincipalResolver.java | WsFederationCredentialsToPrincipalResolver.extractPrincipalId | @Override
protected String extractPrincipalId(final Credential credentials, final Optional<Principal> currentPrincipal) {
"""
Extracts the principalId.
@param credentials the credentials
@return the principal id
"""
val wsFedCredentials = (WsFederationCredential) credentials;
val attributes = wsFedCredentials.getAttributes();
LOGGER.debug("Credential attributes provided are: [{}]", attributes);
val idAttribute = this.configuration.getIdentityAttribute();
if (attributes.containsKey(idAttribute)) {
LOGGER.debug("Extracting principal id from attribute [{}]", this.configuration.getIdentityAttribute());
val idAttributeAsList = CollectionUtils.toCollection(attributes.get(this.configuration.getIdentityAttribute()));
if (idAttributeAsList.size() > 1) {
LOGGER.warn("Found multiple values for id attribute [{}].", idAttribute);
} else {
LOGGER.debug("Found principal id attribute as [{}]", idAttributeAsList);
}
val result = CollectionUtils.firstElement(idAttributeAsList);
if (result.isPresent()) {
val principalId = result.get().toString();
LOGGER.debug("Principal Id extracted from credentials: [{}]", principalId);
return principalId;
}
}
LOGGER.warn("Credential attributes do not include an attribute for [{}]. "
+ "This will prohibit CAS to construct a meaningful authenticated principal. "
+ "Examine the released claims and ensure [{}] is allowed", idAttribute, idAttribute);
return null;
} | java | @Override
protected String extractPrincipalId(final Credential credentials, final Optional<Principal> currentPrincipal) {
val wsFedCredentials = (WsFederationCredential) credentials;
val attributes = wsFedCredentials.getAttributes();
LOGGER.debug("Credential attributes provided are: [{}]", attributes);
val idAttribute = this.configuration.getIdentityAttribute();
if (attributes.containsKey(idAttribute)) {
LOGGER.debug("Extracting principal id from attribute [{}]", this.configuration.getIdentityAttribute());
val idAttributeAsList = CollectionUtils.toCollection(attributes.get(this.configuration.getIdentityAttribute()));
if (idAttributeAsList.size() > 1) {
LOGGER.warn("Found multiple values for id attribute [{}].", idAttribute);
} else {
LOGGER.debug("Found principal id attribute as [{}]", idAttributeAsList);
}
val result = CollectionUtils.firstElement(idAttributeAsList);
if (result.isPresent()) {
val principalId = result.get().toString();
LOGGER.debug("Principal Id extracted from credentials: [{}]", principalId);
return principalId;
}
}
LOGGER.warn("Credential attributes do not include an attribute for [{}]. "
+ "This will prohibit CAS to construct a meaningful authenticated principal. "
+ "Examine the released claims and ensure [{}] is allowed", idAttribute, idAttribute);
return null;
} | [
"@",
"Override",
"protected",
"String",
"extractPrincipalId",
"(",
"final",
"Credential",
"credentials",
",",
"final",
"Optional",
"<",
"Principal",
">",
"currentPrincipal",
")",
"{",
"val",
"wsFedCredentials",
"=",
"(",
"WsFederationCredential",
")",
"credentials",
";",
"val",
"attributes",
"=",
"wsFedCredentials",
".",
"getAttributes",
"(",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"Credential attributes provided are: [{}]\"",
",",
"attributes",
")",
";",
"val",
"idAttribute",
"=",
"this",
".",
"configuration",
".",
"getIdentityAttribute",
"(",
")",
";",
"if",
"(",
"attributes",
".",
"containsKey",
"(",
"idAttribute",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Extracting principal id from attribute [{}]\"",
",",
"this",
".",
"configuration",
".",
"getIdentityAttribute",
"(",
")",
")",
";",
"val",
"idAttributeAsList",
"=",
"CollectionUtils",
".",
"toCollection",
"(",
"attributes",
".",
"get",
"(",
"this",
".",
"configuration",
".",
"getIdentityAttribute",
"(",
")",
")",
")",
";",
"if",
"(",
"idAttributeAsList",
".",
"size",
"(",
")",
">",
"1",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Found multiple values for id attribute [{}].\"",
",",
"idAttribute",
")",
";",
"}",
"else",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Found principal id attribute as [{}]\"",
",",
"idAttributeAsList",
")",
";",
"}",
"val",
"result",
"=",
"CollectionUtils",
".",
"firstElement",
"(",
"idAttributeAsList",
")",
";",
"if",
"(",
"result",
".",
"isPresent",
"(",
")",
")",
"{",
"val",
"principalId",
"=",
"result",
".",
"get",
"(",
")",
".",
"toString",
"(",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"Principal Id extracted from credentials: [{}]\"",
",",
"principalId",
")",
";",
"return",
"principalId",
";",
"}",
"}",
"LOGGER",
".",
"warn",
"(",
"\"Credential attributes do not include an attribute for [{}]. \"",
"+",
"\"This will prohibit CAS to construct a meaningful authenticated principal. \"",
"+",
"\"Examine the released claims and ensure [{}] is allowed\"",
",",
"idAttribute",
",",
"idAttribute",
")",
";",
"return",
"null",
";",
"}"
]
| Extracts the principalId.
@param credentials the credentials
@return the principal id | [
"Extracts",
"the",
"principalId",
"."
]
| train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-wsfederation/src/main/java/org/apereo/cas/support/wsfederation/authentication/principal/WsFederationCredentialsToPrincipalResolver.java#L53-L79 |
landawn/AbacusUtil | src/com/landawn/abacus/logging/JDKLogger.java | JDKLogger.fillCallerData | final private void fillCallerData(String callerFQCN, LogRecord record) {
"""
Fill in caller data if possible.
@param record
The record to update
"""
StackTraceElement[] steArray = new Throwable().getStackTrace();
int selfIndex = -1;
for (int i = 0; i < steArray.length; i++) {
final String className = steArray[i].getClassName();
if (className.equals(callerFQCN) || className.equals(SUPER)) {
selfIndex = i;
break;
}
}
int found = -1;
for (int i = selfIndex + 1; i < steArray.length; i++) {
final String className = steArray[i].getClassName();
if (!(className.equals(callerFQCN) || className.equals(SUPER))) {
found = i;
break;
}
}
if (found != -1) {
StackTraceElement ste = steArray[found];
// setting the class name has the side effect of setting
// the needToInferCaller variable to false.
record.setSourceClassName(ste.getClassName());
record.setSourceMethodName(ste.getMethodName());
}
} | java | final private void fillCallerData(String callerFQCN, LogRecord record) {
StackTraceElement[] steArray = new Throwable().getStackTrace();
int selfIndex = -1;
for (int i = 0; i < steArray.length; i++) {
final String className = steArray[i].getClassName();
if (className.equals(callerFQCN) || className.equals(SUPER)) {
selfIndex = i;
break;
}
}
int found = -1;
for (int i = selfIndex + 1; i < steArray.length; i++) {
final String className = steArray[i].getClassName();
if (!(className.equals(callerFQCN) || className.equals(SUPER))) {
found = i;
break;
}
}
if (found != -1) {
StackTraceElement ste = steArray[found];
// setting the class name has the side effect of setting
// the needToInferCaller variable to false.
record.setSourceClassName(ste.getClassName());
record.setSourceMethodName(ste.getMethodName());
}
} | [
"final",
"private",
"void",
"fillCallerData",
"(",
"String",
"callerFQCN",
",",
"LogRecord",
"record",
")",
"{",
"StackTraceElement",
"[",
"]",
"steArray",
"=",
"new",
"Throwable",
"(",
")",
".",
"getStackTrace",
"(",
")",
";",
"int",
"selfIndex",
"=",
"-",
"1",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"steArray",
".",
"length",
";",
"i",
"++",
")",
"{",
"final",
"String",
"className",
"=",
"steArray",
"[",
"i",
"]",
".",
"getClassName",
"(",
")",
";",
"if",
"(",
"className",
".",
"equals",
"(",
"callerFQCN",
")",
"||",
"className",
".",
"equals",
"(",
"SUPER",
")",
")",
"{",
"selfIndex",
"=",
"i",
";",
"break",
";",
"}",
"}",
"int",
"found",
"=",
"-",
"1",
";",
"for",
"(",
"int",
"i",
"=",
"selfIndex",
"+",
"1",
";",
"i",
"<",
"steArray",
".",
"length",
";",
"i",
"++",
")",
"{",
"final",
"String",
"className",
"=",
"steArray",
"[",
"i",
"]",
".",
"getClassName",
"(",
")",
";",
"if",
"(",
"!",
"(",
"className",
".",
"equals",
"(",
"callerFQCN",
")",
"||",
"className",
".",
"equals",
"(",
"SUPER",
")",
")",
")",
"{",
"found",
"=",
"i",
";",
"break",
";",
"}",
"}",
"if",
"(",
"found",
"!=",
"-",
"1",
")",
"{",
"StackTraceElement",
"ste",
"=",
"steArray",
"[",
"found",
"]",
";",
"// setting the class name has the side effect of setting\r",
"// the needToInferCaller variable to false.\r",
"record",
".",
"setSourceClassName",
"(",
"ste",
".",
"getClassName",
"(",
")",
")",
";",
"record",
".",
"setSourceMethodName",
"(",
"ste",
".",
"getMethodName",
"(",
")",
")",
";",
"}",
"}"
]
| Fill in caller data if possible.
@param record
The record to update | [
"Fill",
"in",
"caller",
"data",
"if",
"possible",
"."
]
| train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/logging/JDKLogger.java#L148-L176 |
elvishew/xLog | library/src/main/java/com/elvishew/xlog/Logger.java | Logger.println | private void println(int logLevel, String msg, Throwable tr) {
"""
Print a log in a new line.
@param logLevel the log level of the printing log
@param msg the message you would like to log
@param tr a throwable object to log
"""
if (logLevel < logConfiguration.logLevel) {
return;
}
printlnInternal(logLevel, ((msg == null || msg.length() == 0)
? "" : (msg + SystemCompat.lineSeparator))
+ logConfiguration.throwableFormatter.format(tr));
} | java | private void println(int logLevel, String msg, Throwable tr) {
if (logLevel < logConfiguration.logLevel) {
return;
}
printlnInternal(logLevel, ((msg == null || msg.length() == 0)
? "" : (msg + SystemCompat.lineSeparator))
+ logConfiguration.throwableFormatter.format(tr));
} | [
"private",
"void",
"println",
"(",
"int",
"logLevel",
",",
"String",
"msg",
",",
"Throwable",
"tr",
")",
"{",
"if",
"(",
"logLevel",
"<",
"logConfiguration",
".",
"logLevel",
")",
"{",
"return",
";",
"}",
"printlnInternal",
"(",
"logLevel",
",",
"(",
"(",
"msg",
"==",
"null",
"||",
"msg",
".",
"length",
"(",
")",
"==",
"0",
")",
"?",
"\"\"",
":",
"(",
"msg",
"+",
"SystemCompat",
".",
"lineSeparator",
")",
")",
"+",
"logConfiguration",
".",
"throwableFormatter",
".",
"format",
"(",
"tr",
")",
")",
";",
"}"
]
| Print a log in a new line.
@param logLevel the log level of the printing log
@param msg the message you would like to log
@param tr a throwable object to log | [
"Print",
"a",
"log",
"in",
"a",
"new",
"line",
"."
]
| train | https://github.com/elvishew/xLog/blob/c6fb95555ce619d3e527f5ba6c45d4d247c5a838/library/src/main/java/com/elvishew/xlog/Logger.java#L542-L549 |
stapler/stapler | core/src/main/java/org/kohsuke/stapler/export/Model.java | Model.writeTo | @Deprecated
public void writeTo(T object, int baseVisibility, DataWriter writer) throws IOException {
"""
Writes the property values of the given object to the writer.
@param baseVisibility
This parameters controls how much data we'd be writing,
by adding bias to the sub tree cutting.
A property with {@link Exported#visibility() visibility} X will be written
if the current depth Y and baseVisibility Z satisfies {@code X + Z > Y}.
0 is the normal value. Positive value means writing bigger tree,
and negative value means writing smaller trees.
@deprecated as of 1.139
"""
writeTo(object,new ByDepth(1-baseVisibility),writer);
} | java | @Deprecated
public void writeTo(T object, int baseVisibility, DataWriter writer) throws IOException {
writeTo(object,new ByDepth(1-baseVisibility),writer);
} | [
"@",
"Deprecated",
"public",
"void",
"writeTo",
"(",
"T",
"object",
",",
"int",
"baseVisibility",
",",
"DataWriter",
"writer",
")",
"throws",
"IOException",
"{",
"writeTo",
"(",
"object",
",",
"new",
"ByDepth",
"(",
"1",
"-",
"baseVisibility",
")",
",",
"writer",
")",
";",
"}"
]
| Writes the property values of the given object to the writer.
@param baseVisibility
This parameters controls how much data we'd be writing,
by adding bias to the sub tree cutting.
A property with {@link Exported#visibility() visibility} X will be written
if the current depth Y and baseVisibility Z satisfies {@code X + Z > Y}.
0 is the normal value. Positive value means writing bigger tree,
and negative value means writing smaller trees.
@deprecated as of 1.139 | [
"Writes",
"the",
"property",
"values",
"of",
"the",
"given",
"object",
"to",
"the",
"writer",
"."
]
| train | https://github.com/stapler/stapler/blob/11ad5af185e062fb46e01bf9fbed66f3ebf2a8f7/core/src/main/java/org/kohsuke/stapler/export/Model.java#L212-L215 |
jayantk/jklol | src/com/jayantkrish/jklol/ccg/SyntacticCategory.java | SyntacticCategory.isUnifiableWith | public boolean isUnifiableWith(SyntacticCategory other) {
"""
Returns {@code true} if this category is unifiable with
{@code other}. Two categories are unifiable if there exist
assignments to the feature variables of each category which make
both categories equal.
@param other
@return
"""
Map<Integer, String> myAssignedVariables = Maps.newHashMap();
Map<Integer, String> otherAssignedVariables = Maps.newHashMap();
Map<Integer, Integer> variableRelabeling = Maps.newHashMap();
// System.err.println("unifying: " + this + " " + other);
return isUnifiableWith(other, myAssignedVariables, otherAssignedVariables, variableRelabeling);
} | java | public boolean isUnifiableWith(SyntacticCategory other) {
Map<Integer, String> myAssignedVariables = Maps.newHashMap();
Map<Integer, String> otherAssignedVariables = Maps.newHashMap();
Map<Integer, Integer> variableRelabeling = Maps.newHashMap();
// System.err.println("unifying: " + this + " " + other);
return isUnifiableWith(other, myAssignedVariables, otherAssignedVariables, variableRelabeling);
} | [
"public",
"boolean",
"isUnifiableWith",
"(",
"SyntacticCategory",
"other",
")",
"{",
"Map",
"<",
"Integer",
",",
"String",
">",
"myAssignedVariables",
"=",
"Maps",
".",
"newHashMap",
"(",
")",
";",
"Map",
"<",
"Integer",
",",
"String",
">",
"otherAssignedVariables",
"=",
"Maps",
".",
"newHashMap",
"(",
")",
";",
"Map",
"<",
"Integer",
",",
"Integer",
">",
"variableRelabeling",
"=",
"Maps",
".",
"newHashMap",
"(",
")",
";",
"// System.err.println(\"unifying: \" + this + \" \" + other);",
"return",
"isUnifiableWith",
"(",
"other",
",",
"myAssignedVariables",
",",
"otherAssignedVariables",
",",
"variableRelabeling",
")",
";",
"}"
]
| Returns {@code true} if this category is unifiable with
{@code other}. Two categories are unifiable if there exist
assignments to the feature variables of each category which make
both categories equal.
@param other
@return | [
"Returns",
"{",
"@code",
"true",
"}",
"if",
"this",
"category",
"is",
"unifiable",
"with",
"{",
"@code",
"other",
"}",
".",
"Two",
"categories",
"are",
"unifiable",
"if",
"there",
"exist",
"assignments",
"to",
"the",
"feature",
"variables",
"of",
"each",
"category",
"which",
"make",
"both",
"categories",
"equal",
"."
]
| train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/SyntacticCategory.java#L477-L484 |
groupon/odo | proxylib/src/main/java/com/groupon/odo/proxylib/BackupService.java | BackupService.getConnectorStrings | private ArrayList<String> getConnectorStrings(String name) {
"""
Get a list of strings(scheme + host + port) that the specified connector is running on
@param name
@return
"""
ArrayList<String> connectorStrings = new ArrayList<String>();
try {
MBeanServer mbeanServer = getServerForName(name);
Set<ObjectName> objs = mbeanServer.queryNames(new ObjectName("*:type=Connector,*"), null);
String hostname = InetAddress.getLocalHost().getHostName();
InetAddress[] addresses = InetAddress.getAllByName(hostname);
for (Iterator<ObjectName> i = objs.iterator(); i.hasNext(); ) {
ObjectName obj = i.next();
String scheme = mbeanServer.getAttribute(obj, "scheme").toString();
String port = obj.getKeyProperty("port");
connectorStrings.add(scheme + "://localhost:" + port);
logger.info("Adding: {}", scheme + "://localhost:" + port);
}
} catch (Exception e) {
}
return connectorStrings;
} | java | private ArrayList<String> getConnectorStrings(String name) {
ArrayList<String> connectorStrings = new ArrayList<String>();
try {
MBeanServer mbeanServer = getServerForName(name);
Set<ObjectName> objs = mbeanServer.queryNames(new ObjectName("*:type=Connector,*"), null);
String hostname = InetAddress.getLocalHost().getHostName();
InetAddress[] addresses = InetAddress.getAllByName(hostname);
for (Iterator<ObjectName> i = objs.iterator(); i.hasNext(); ) {
ObjectName obj = i.next();
String scheme = mbeanServer.getAttribute(obj, "scheme").toString();
String port = obj.getKeyProperty("port");
connectorStrings.add(scheme + "://localhost:" + port);
logger.info("Adding: {}", scheme + "://localhost:" + port);
}
} catch (Exception e) {
}
return connectorStrings;
} | [
"private",
"ArrayList",
"<",
"String",
">",
"getConnectorStrings",
"(",
"String",
"name",
")",
"{",
"ArrayList",
"<",
"String",
">",
"connectorStrings",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"try",
"{",
"MBeanServer",
"mbeanServer",
"=",
"getServerForName",
"(",
"name",
")",
";",
"Set",
"<",
"ObjectName",
">",
"objs",
"=",
"mbeanServer",
".",
"queryNames",
"(",
"new",
"ObjectName",
"(",
"\"*:type=Connector,*\"",
")",
",",
"null",
")",
";",
"String",
"hostname",
"=",
"InetAddress",
".",
"getLocalHost",
"(",
")",
".",
"getHostName",
"(",
")",
";",
"InetAddress",
"[",
"]",
"addresses",
"=",
"InetAddress",
".",
"getAllByName",
"(",
"hostname",
")",
";",
"for",
"(",
"Iterator",
"<",
"ObjectName",
">",
"i",
"=",
"objs",
".",
"iterator",
"(",
")",
";",
"i",
".",
"hasNext",
"(",
")",
";",
")",
"{",
"ObjectName",
"obj",
"=",
"i",
".",
"next",
"(",
")",
";",
"String",
"scheme",
"=",
"mbeanServer",
".",
"getAttribute",
"(",
"obj",
",",
"\"scheme\"",
")",
".",
"toString",
"(",
")",
";",
"String",
"port",
"=",
"obj",
".",
"getKeyProperty",
"(",
"\"port\"",
")",
";",
"connectorStrings",
".",
"add",
"(",
"scheme",
"+",
"\"://localhost:\"",
"+",
"port",
")",
";",
"logger",
".",
"info",
"(",
"\"Adding: {}\"",
",",
"scheme",
"+",
"\"://localhost:\"",
"+",
"port",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
"return",
"connectorStrings",
";",
"}"
]
| Get a list of strings(scheme + host + port) that the specified connector is running on
@param name
@return | [
"Get",
"a",
"list",
"of",
"strings",
"(",
"scheme",
"+",
"host",
"+",
"port",
")",
"that",
"the",
"specified",
"connector",
"is",
"running",
"on"
]
| train | https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxylib/src/main/java/com/groupon/odo/proxylib/BackupService.java#L422-L442 |
vdurmont/semver4j | src/main/java/com/vdurmont/semver4j/Requirement.java | Requirement.buildNPM | public static Requirement buildNPM(String requirement) {
"""
Builds a requirement following the rules of NPM.
@param requirement the requirement as a string
@return the generated requirement
"""
if (requirement.isEmpty()) {
requirement = "*";
}
return buildWithTokenizer(requirement, Semver.SemverType.NPM);
} | java | public static Requirement buildNPM(String requirement) {
if (requirement.isEmpty()) {
requirement = "*";
}
return buildWithTokenizer(requirement, Semver.SemverType.NPM);
} | [
"public",
"static",
"Requirement",
"buildNPM",
"(",
"String",
"requirement",
")",
"{",
"if",
"(",
"requirement",
".",
"isEmpty",
"(",
")",
")",
"{",
"requirement",
"=",
"\"*\"",
";",
"}",
"return",
"buildWithTokenizer",
"(",
"requirement",
",",
"Semver",
".",
"SemverType",
".",
"NPM",
")",
";",
"}"
]
| Builds a requirement following the rules of NPM.
@param requirement the requirement as a string
@return the generated requirement | [
"Builds",
"a",
"requirement",
"following",
"the",
"rules",
"of",
"NPM",
"."
]
| train | https://github.com/vdurmont/semver4j/blob/3f0266e4985ac29e9da482e04001ed15fad6c3e2/src/main/java/com/vdurmont/semver4j/Requirement.java#L96-L101 |
gallandarakhneorg/afc | advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d3/dfx/Segment3dfx.java | Segment3dfx.z1Property | @Pure
public DoubleProperty z1Property() {
"""
Replies the property that is the z coordinate of the first segment point.
@return the z1 property.
"""
if (this.p1.z == null) {
this.p1.z = new SimpleDoubleProperty(this, MathFXAttributeNames.Z1);
}
return this.p1.z;
} | java | @Pure
public DoubleProperty z1Property() {
if (this.p1.z == null) {
this.p1.z = new SimpleDoubleProperty(this, MathFXAttributeNames.Z1);
}
return this.p1.z;
} | [
"@",
"Pure",
"public",
"DoubleProperty",
"z1Property",
"(",
")",
"{",
"if",
"(",
"this",
".",
"p1",
".",
"z",
"==",
"null",
")",
"{",
"this",
".",
"p1",
".",
"z",
"=",
"new",
"SimpleDoubleProperty",
"(",
"this",
",",
"MathFXAttributeNames",
".",
"Z1",
")",
";",
"}",
"return",
"this",
".",
"p1",
".",
"z",
";",
"}"
]
| Replies the property that is the z coordinate of the first segment point.
@return the z1 property. | [
"Replies",
"the",
"property",
"that",
"is",
"the",
"z",
"coordinate",
"of",
"the",
"first",
"segment",
"point",
"."
]
| train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d3/dfx/Segment3dfx.java#L241-L247 |
dbracewell/mango | src/main/java/com/davidbracewell/DynamicEnum.java | DynamicEnum.valueOf | public static <T extends EnumValue> T valueOf(@NonNull Class<T> enumClass, @NonNull String name) {
"""
<p>Returns the constant of the given {@link EnumValue} class with the specified name.The normalized version of
the specified name will be matched allowing for case and space variations.</p>
@param <T> Specific type of EnumValue being looked up
@param enumClass Class information for the EnumValue that we will check.
@param name the name of the specified value
@return The constant of enumClass with the specified name
@throws IllegalArgumentException if the specified name is not a member of enumClass.
@throws NullPointerException if either the enumClass or name are null
"""
String key = toKey(enumClass, name);
T toReturn = Cast.as(GLOBAL_REPOSITORY.get(key));
if (toReturn == null) {
throw new IllegalArgumentException("No enum constant " + key);
}
return toReturn;
} | java | public static <T extends EnumValue> T valueOf(@NonNull Class<T> enumClass, @NonNull String name) {
String key = toKey(enumClass, name);
T toReturn = Cast.as(GLOBAL_REPOSITORY.get(key));
if (toReturn == null) {
throw new IllegalArgumentException("No enum constant " + key);
}
return toReturn;
} | [
"public",
"static",
"<",
"T",
"extends",
"EnumValue",
">",
"T",
"valueOf",
"(",
"@",
"NonNull",
"Class",
"<",
"T",
">",
"enumClass",
",",
"@",
"NonNull",
"String",
"name",
")",
"{",
"String",
"key",
"=",
"toKey",
"(",
"enumClass",
",",
"name",
")",
";",
"T",
"toReturn",
"=",
"Cast",
".",
"as",
"(",
"GLOBAL_REPOSITORY",
".",
"get",
"(",
"key",
")",
")",
";",
"if",
"(",
"toReturn",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"No enum constant \"",
"+",
"key",
")",
";",
"}",
"return",
"toReturn",
";",
"}"
]
| <p>Returns the constant of the given {@link EnumValue} class with the specified name.The normalized version of
the specified name will be matched allowing for case and space variations.</p>
@param <T> Specific type of EnumValue being looked up
@param enumClass Class information for the EnumValue that we will check.
@param name the name of the specified value
@return The constant of enumClass with the specified name
@throws IllegalArgumentException if the specified name is not a member of enumClass.
@throws NullPointerException if either the enumClass or name are null | [
"<p",
">",
"Returns",
"the",
"constant",
"of",
"the",
"given",
"{",
"@link",
"EnumValue",
"}",
"class",
"with",
"the",
"specified",
"name",
".",
"The",
"normalized",
"version",
"of",
"the",
"specified",
"name",
"will",
"be",
"matched",
"allowing",
"for",
"case",
"and",
"space",
"variations",
".",
"<",
"/",
"p",
">"
]
| train | https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/DynamicEnum.java#L97-L104 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/xen/ftw_events.java | ftw_events.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception {
"""
<pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre>
"""
ftw_events_responses result = (ftw_events_responses) service.get_payload_formatter().string_to_resource(ftw_events_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ftw_events_response_array);
}
ftw_events[] result_ftw_events = new ftw_events[result.ftw_events_response_array.length];
for(int i = 0; i < result.ftw_events_response_array.length; i++)
{
result_ftw_events[i] = result.ftw_events_response_array[i].ftw_events[0];
}
return result_ftw_events;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
ftw_events_responses result = (ftw_events_responses) service.get_payload_formatter().string_to_resource(ftw_events_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ftw_events_response_array);
}
ftw_events[] result_ftw_events = new ftw_events[result.ftw_events_response_array.length];
for(int i = 0; i < result.ftw_events_response_array.length; i++)
{
result_ftw_events[i] = result.ftw_events_response_array[i].ftw_events[0];
}
return result_ftw_events;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"ftw_events_responses",
"result",
"=",
"(",
"ftw_events_responses",
")",
"service",
".",
"get_payload_formatter",
"(",
")",
".",
"string_to_resource",
"(",
"ftw_events_responses",
".",
"class",
",",
"response",
")",
";",
"if",
"(",
"result",
".",
"errorcode",
"!=",
"0",
")",
"{",
"if",
"(",
"result",
".",
"errorcode",
"==",
"SESSION_NOT_EXISTS",
")",
"service",
".",
"clear_session",
"(",
")",
";",
"throw",
"new",
"nitro_exception",
"(",
"result",
".",
"message",
",",
"result",
".",
"errorcode",
",",
"(",
"base_response",
"[",
"]",
")",
"result",
".",
"ftw_events_response_array",
")",
";",
"}",
"ftw_events",
"[",
"]",
"result_ftw_events",
"=",
"new",
"ftw_events",
"[",
"result",
".",
"ftw_events_response_array",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"result",
".",
"ftw_events_response_array",
".",
"length",
";",
"i",
"++",
")",
"{",
"result_ftw_events",
"[",
"i",
"]",
"=",
"result",
".",
"ftw_events_response_array",
"[",
"i",
"]",
".",
"ftw_events",
"[",
"0",
"]",
";",
"}",
"return",
"result_ftw_events",
";",
"}"
]
| <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
]
| train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/xen/ftw_events.java#L184-L201 |
Azure/azure-sdk-for-java | containerregistry/resource-manager/v2016_06_27_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2016_06_27_preview/implementation/RegistriesInner.java | RegistriesInner.regenerateCredentialsAsync | public Observable<RegistryCredentialsInner> regenerateCredentialsAsync(String resourceGroupName, String registryName) {
"""
Regenerates the administrator login credentials for the specified container registry.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RegistryCredentialsInner object
"""
return regenerateCredentialsWithServiceResponseAsync(resourceGroupName, registryName).map(new Func1<ServiceResponse<RegistryCredentialsInner>, RegistryCredentialsInner>() {
@Override
public RegistryCredentialsInner call(ServiceResponse<RegistryCredentialsInner> response) {
return response.body();
}
});
} | java | public Observable<RegistryCredentialsInner> regenerateCredentialsAsync(String resourceGroupName, String registryName) {
return regenerateCredentialsWithServiceResponseAsync(resourceGroupName, registryName).map(new Func1<ServiceResponse<RegistryCredentialsInner>, RegistryCredentialsInner>() {
@Override
public RegistryCredentialsInner call(ServiceResponse<RegistryCredentialsInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"RegistryCredentialsInner",
">",
"regenerateCredentialsAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"registryName",
")",
"{",
"return",
"regenerateCredentialsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"registryName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"RegistryCredentialsInner",
">",
",",
"RegistryCredentialsInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"RegistryCredentialsInner",
"call",
"(",
"ServiceResponse",
"<",
"RegistryCredentialsInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Regenerates the administrator login credentials for the specified container registry.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RegistryCredentialsInner object | [
"Regenerates",
"the",
"administrator",
"login",
"credentials",
"for",
"the",
"specified",
"container",
"registry",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2016_06_27_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2016_06_27_preview/implementation/RegistriesInner.java#L902-L909 |
copper-engine/copper-engine | projects/copper-coreengine/src/main/java/org/copperengine/core/persistent/PostgreSQLDialect.java | PostgreSQLDialect.doLock | @Override
protected void doLock(Connection con, final String lockContext) throws SQLException {
"""
ref: https://www.postgresql.org/docs/9.5/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
pg_advisory_lock locks an application-defined resource, which can be identified either by a single 64-bit key
value or two 32-bit key values (note that these two key spaces do not overlap). If another session already holds
a lock on the same resource identifier, this function will wait until the resource becomes available. The lock is
exclusive. Multiple lock requests stack, so that if the same resource is locked three times it must then be
unlocked three times to be released for other sessions' use.
DO NOT USE IT WITHOUT finally { release_lock(lockContext)} or it will be deadlocked!!
"""
logger.debug("Trying to acquire db lock for '{}'", lockContext);
final int lockId = computeLockId(lockContext);
PreparedStatement stmt = con.prepareStatement("SELECT pg_advisory_xact_lock (?)");
stmt.setInt(1, lockId);
try {
stmt.executeQuery();
} finally {
JdbcUtils.closeStatement(stmt);
}
} | java | @Override
protected void doLock(Connection con, final String lockContext) throws SQLException {
logger.debug("Trying to acquire db lock for '{}'", lockContext);
final int lockId = computeLockId(lockContext);
PreparedStatement stmt = con.prepareStatement("SELECT pg_advisory_xact_lock (?)");
stmt.setInt(1, lockId);
try {
stmt.executeQuery();
} finally {
JdbcUtils.closeStatement(stmt);
}
} | [
"@",
"Override",
"protected",
"void",
"doLock",
"(",
"Connection",
"con",
",",
"final",
"String",
"lockContext",
")",
"throws",
"SQLException",
"{",
"logger",
".",
"debug",
"(",
"\"Trying to acquire db lock for '{}'\"",
",",
"lockContext",
")",
";",
"final",
"int",
"lockId",
"=",
"computeLockId",
"(",
"lockContext",
")",
";",
"PreparedStatement",
"stmt",
"=",
"con",
".",
"prepareStatement",
"(",
"\"SELECT pg_advisory_xact_lock (?)\"",
")",
";",
"stmt",
".",
"setInt",
"(",
"1",
",",
"lockId",
")",
";",
"try",
"{",
"stmt",
".",
"executeQuery",
"(",
")",
";",
"}",
"finally",
"{",
"JdbcUtils",
".",
"closeStatement",
"(",
"stmt",
")",
";",
"}",
"}"
]
| ref: https://www.postgresql.org/docs/9.5/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
pg_advisory_lock locks an application-defined resource, which can be identified either by a single 64-bit key
value or two 32-bit key values (note that these two key spaces do not overlap). If another session already holds
a lock on the same resource identifier, this function will wait until the resource becomes available. The lock is
exclusive. Multiple lock requests stack, so that if the same resource is locked three times it must then be
unlocked three times to be released for other sessions' use.
DO NOT USE IT WITHOUT finally { release_lock(lockContext)} or it will be deadlocked!! | [
"ref",
":",
"https",
":",
"//",
"www",
".",
"postgresql",
".",
"org",
"/",
"docs",
"/",
"9",
".",
"5",
"/",
"static",
"/",
"functions",
"-",
"admin",
".",
"html#FUNCTIONS",
"-",
"ADVISORY",
"-",
"LOCKS",
"pg_advisory_lock",
"locks",
"an",
"application",
"-",
"defined",
"resource",
"which",
"can",
"be",
"identified",
"either",
"by",
"a",
"single",
"64",
"-",
"bit",
"key",
"value",
"or",
"two",
"32",
"-",
"bit",
"key",
"values",
"(",
"note",
"that",
"these",
"two",
"key",
"spaces",
"do",
"not",
"overlap",
")",
".",
"If",
"another",
"session",
"already",
"holds",
"a",
"lock",
"on",
"the",
"same",
"resource",
"identifier",
"this",
"function",
"will",
"wait",
"until",
"the",
"resource",
"becomes",
"available",
".",
"The",
"lock",
"is",
"exclusive",
".",
"Multiple",
"lock",
"requests",
"stack",
"so",
"that",
"if",
"the",
"same",
"resource",
"is",
"locked",
"three",
"times",
"it",
"must",
"then",
"be",
"unlocked",
"three",
"times",
"to",
"be",
"released",
"for",
"other",
"sessions",
"use",
".",
"DO",
"NOT",
"USE",
"IT",
"WITHOUT",
"finally",
"{",
"release_lock",
"(",
"lockContext",
")",
"}",
"or",
"it",
"will",
"be",
"deadlocked!!"
]
| train | https://github.com/copper-engine/copper-engine/blob/92acf748a1be3d2d49e86b04e180bd19b1745c15/projects/copper-coreengine/src/main/java/org/copperengine/core/persistent/PostgreSQLDialect.java#L122-L133 |
buschmais/extended-objects | neo4j/remote/src/main/java/com/buschmais/xo/neo4j/remote/impl/datastore/RemoteDatastoreEntityManager.java | RemoteDatastoreEntityManager.initializeEntity | private void initializeEntity(Collection<? extends TypeMetadata> types, NodeState nodeState) {
"""
Initializes all relation properties of the given node state with empty
collections.
@param types
The types.
@param nodeState
The state of the entity.
"""
for (TypeMetadata type : types) {
Collection<TypeMetadata> superTypes = type.getSuperTypes();
initializeEntity(superTypes, nodeState);
for (MethodMetadata<?, ?> methodMetadata : type.getProperties()) {
if (methodMetadata instanceof AbstractRelationPropertyMethodMetadata) {
AbstractRelationPropertyMethodMetadata<?> relationPropertyMethodMetadata = (AbstractRelationPropertyMethodMetadata) methodMetadata;
RelationTypeMetadata<RelationshipMetadata<RemoteRelationshipType>> relationshipMetadata = relationPropertyMethodMetadata
.getRelationshipMetadata();
RemoteRelationshipType relationshipType = relationshipMetadata.getDatastoreMetadata().getDiscriminator();
RelationTypeMetadata.Direction direction = relationPropertyMethodMetadata.getDirection();
RemoteDirection remoteDirection;
switch (direction) {
case FROM:
remoteDirection = RemoteDirection.OUTGOING;
break;
case TO:
remoteDirection = RemoteDirection.INCOMING;
break;
default:
throw new XOException("Unsupported direction: " + direction);
}
if (nodeState.getRelationships(remoteDirection, relationshipType) == null) {
nodeState.setRelationships(remoteDirection, relationshipType, new StateTracker<>(new LinkedHashSet<>()));
}
}
}
}
} | java | private void initializeEntity(Collection<? extends TypeMetadata> types, NodeState nodeState) {
for (TypeMetadata type : types) {
Collection<TypeMetadata> superTypes = type.getSuperTypes();
initializeEntity(superTypes, nodeState);
for (MethodMetadata<?, ?> methodMetadata : type.getProperties()) {
if (methodMetadata instanceof AbstractRelationPropertyMethodMetadata) {
AbstractRelationPropertyMethodMetadata<?> relationPropertyMethodMetadata = (AbstractRelationPropertyMethodMetadata) methodMetadata;
RelationTypeMetadata<RelationshipMetadata<RemoteRelationshipType>> relationshipMetadata = relationPropertyMethodMetadata
.getRelationshipMetadata();
RemoteRelationshipType relationshipType = relationshipMetadata.getDatastoreMetadata().getDiscriminator();
RelationTypeMetadata.Direction direction = relationPropertyMethodMetadata.getDirection();
RemoteDirection remoteDirection;
switch (direction) {
case FROM:
remoteDirection = RemoteDirection.OUTGOING;
break;
case TO:
remoteDirection = RemoteDirection.INCOMING;
break;
default:
throw new XOException("Unsupported direction: " + direction);
}
if (nodeState.getRelationships(remoteDirection, relationshipType) == null) {
nodeState.setRelationships(remoteDirection, relationshipType, new StateTracker<>(new LinkedHashSet<>()));
}
}
}
}
} | [
"private",
"void",
"initializeEntity",
"(",
"Collection",
"<",
"?",
"extends",
"TypeMetadata",
">",
"types",
",",
"NodeState",
"nodeState",
")",
"{",
"for",
"(",
"TypeMetadata",
"type",
":",
"types",
")",
"{",
"Collection",
"<",
"TypeMetadata",
">",
"superTypes",
"=",
"type",
".",
"getSuperTypes",
"(",
")",
";",
"initializeEntity",
"(",
"superTypes",
",",
"nodeState",
")",
";",
"for",
"(",
"MethodMetadata",
"<",
"?",
",",
"?",
">",
"methodMetadata",
":",
"type",
".",
"getProperties",
"(",
")",
")",
"{",
"if",
"(",
"methodMetadata",
"instanceof",
"AbstractRelationPropertyMethodMetadata",
")",
"{",
"AbstractRelationPropertyMethodMetadata",
"<",
"?",
">",
"relationPropertyMethodMetadata",
"=",
"(",
"AbstractRelationPropertyMethodMetadata",
")",
"methodMetadata",
";",
"RelationTypeMetadata",
"<",
"RelationshipMetadata",
"<",
"RemoteRelationshipType",
">",
">",
"relationshipMetadata",
"=",
"relationPropertyMethodMetadata",
".",
"getRelationshipMetadata",
"(",
")",
";",
"RemoteRelationshipType",
"relationshipType",
"=",
"relationshipMetadata",
".",
"getDatastoreMetadata",
"(",
")",
".",
"getDiscriminator",
"(",
")",
";",
"RelationTypeMetadata",
".",
"Direction",
"direction",
"=",
"relationPropertyMethodMetadata",
".",
"getDirection",
"(",
")",
";",
"RemoteDirection",
"remoteDirection",
";",
"switch",
"(",
"direction",
")",
"{",
"case",
"FROM",
":",
"remoteDirection",
"=",
"RemoteDirection",
".",
"OUTGOING",
";",
"break",
";",
"case",
"TO",
":",
"remoteDirection",
"=",
"RemoteDirection",
".",
"INCOMING",
";",
"break",
";",
"default",
":",
"throw",
"new",
"XOException",
"(",
"\"Unsupported direction: \"",
"+",
"direction",
")",
";",
"}",
"if",
"(",
"nodeState",
".",
"getRelationships",
"(",
"remoteDirection",
",",
"relationshipType",
")",
"==",
"null",
")",
"{",
"nodeState",
".",
"setRelationships",
"(",
"remoteDirection",
",",
"relationshipType",
",",
"new",
"StateTracker",
"<>",
"(",
"new",
"LinkedHashSet",
"<>",
"(",
")",
")",
")",
";",
"}",
"}",
"}",
"}",
"}"
]
| Initializes all relation properties of the given node state with empty
collections.
@param types
The types.
@param nodeState
The state of the entity. | [
"Initializes",
"all",
"relation",
"properties",
"of",
"the",
"given",
"node",
"state",
"with",
"empty",
"collections",
"."
]
| train | https://github.com/buschmais/extended-objects/blob/186431e81f3d8d26c511cfe1143dee59b03c2e7a/neo4j/remote/src/main/java/com/buschmais/xo/neo4j/remote/impl/datastore/RemoteDatastoreEntityManager.java#L106-L134 |
OpenLiberty/open-liberty | dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/internal/UnifiedClassLoader.java | UnifiedClassLoader.getThrowawayClassLoader | @Override
public ClassLoader getThrowawayClassLoader() {
"""
Special method used by Spring to obtain a throwaway class loader for this ClassLoader
"""
ClassLoader newParent = getThrowawayVersion(getParent());
ClassLoader[] newFollowOns = new ClassLoader[followOnClassLoaders.size()];
for (int i = 0; i < newFollowOns.length; i++) {
newFollowOns[i] = getThrowawayVersion(followOnClassLoaders.get(i));
}
return new UnifiedClassLoader(newParent, newFollowOns);
} | java | @Override
public ClassLoader getThrowawayClassLoader() {
ClassLoader newParent = getThrowawayVersion(getParent());
ClassLoader[] newFollowOns = new ClassLoader[followOnClassLoaders.size()];
for (int i = 0; i < newFollowOns.length; i++) {
newFollowOns[i] = getThrowawayVersion(followOnClassLoaders.get(i));
}
return new UnifiedClassLoader(newParent, newFollowOns);
} | [
"@",
"Override",
"public",
"ClassLoader",
"getThrowawayClassLoader",
"(",
")",
"{",
"ClassLoader",
"newParent",
"=",
"getThrowawayVersion",
"(",
"getParent",
"(",
")",
")",
";",
"ClassLoader",
"[",
"]",
"newFollowOns",
"=",
"new",
"ClassLoader",
"[",
"followOnClassLoaders",
".",
"size",
"(",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"newFollowOns",
".",
"length",
";",
"i",
"++",
")",
"{",
"newFollowOns",
"[",
"i",
"]",
"=",
"getThrowawayVersion",
"(",
"followOnClassLoaders",
".",
"get",
"(",
"i",
")",
")",
";",
"}",
"return",
"new",
"UnifiedClassLoader",
"(",
"newParent",
",",
"newFollowOns",
")",
";",
"}"
]
| Special method used by Spring to obtain a throwaway class loader for this ClassLoader | [
"Special",
"method",
"used",
"by",
"Spring",
"to",
"obtain",
"a",
"throwaway",
"class",
"loader",
"for",
"this",
"ClassLoader"
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/internal/UnifiedClassLoader.java#L59-L67 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/GitlabAPI.java | GitlabAPI.editProjectBadge | public GitlabBadge editProjectBadge(Serializable projectId, Integer badgeId, String linkUrl, String imageUrl) throws IOException {
"""
Edit project badge
@param projectId The id of the project for which the badge should be edited
@param badgeId The id of the badge that should be edited
@param linkUrl The URL that the badge should link to
@param imageUrl The URL to the badge image
@return The updated badge
@throws IOException on GitLab API call error
"""
String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBadge.URL
+ "/" + badgeId;
GitlabHTTPRequestor requestor = retrieve().method(PUT);
requestor.with("link_url", linkUrl)
.with("image_url", imageUrl);
return requestor.to(tailUrl, GitlabBadge.class);
} | java | public GitlabBadge editProjectBadge(Serializable projectId, Integer badgeId, String linkUrl, String imageUrl) throws IOException {
String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBadge.URL
+ "/" + badgeId;
GitlabHTTPRequestor requestor = retrieve().method(PUT);
requestor.with("link_url", linkUrl)
.with("image_url", imageUrl);
return requestor.to(tailUrl, GitlabBadge.class);
} | [
"public",
"GitlabBadge",
"editProjectBadge",
"(",
"Serializable",
"projectId",
",",
"Integer",
"badgeId",
",",
"String",
"linkUrl",
",",
"String",
"imageUrl",
")",
"throws",
"IOException",
"{",
"String",
"tailUrl",
"=",
"GitlabProject",
".",
"URL",
"+",
"\"/\"",
"+",
"sanitizeProjectId",
"(",
"projectId",
")",
"+",
"GitlabBadge",
".",
"URL",
"+",
"\"/\"",
"+",
"badgeId",
";",
"GitlabHTTPRequestor",
"requestor",
"=",
"retrieve",
"(",
")",
".",
"method",
"(",
"PUT",
")",
";",
"requestor",
".",
"with",
"(",
"\"link_url\"",
",",
"linkUrl",
")",
".",
"with",
"(",
"\"image_url\"",
",",
"imageUrl",
")",
";",
"return",
"requestor",
".",
"to",
"(",
"tailUrl",
",",
"GitlabBadge",
".",
"class",
")",
";",
"}"
]
| Edit project badge
@param projectId The id of the project for which the badge should be edited
@param badgeId The id of the badge that should be edited
@param linkUrl The URL that the badge should link to
@param imageUrl The URL to the badge image
@return The updated badge
@throws IOException on GitLab API call error | [
"Edit",
"project",
"badge"
]
| train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L2651-L2658 |
NoraUi/NoraUi | src/main/java/com/github/noraui/application/steps/Step.java | Step.selectCheckbox | protected void selectCheckbox(PageElement element, String valueKeyOrKey, Map<String, Boolean> values) throws TechnicalException, FailureException {
"""
Checks a checkbox type element (value corresponding to key "valueKey").
@param element
Target page element
@param valueKeyOrKey
is valueKey (valueKey or key in context (after a save)) to match in values map
@param values
Values map
@throws TechnicalException
is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi.
Failure with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_CHECK_ELEMENT} message (with screenshot)
@throws FailureException
if the scenario encounters a functional error
"""
final String valueKey = Context.getValue(valueKeyOrKey) != null ? Context.getValue(valueKeyOrKey) : valueKeyOrKey;
try {
final WebElement webElement = Context.waitUntil(ExpectedConditions.elementToBeClickable(Utilities.getLocator(element)));
Boolean checkboxValue = values.get(valueKey);
if (checkboxValue == null) {
checkboxValue = values.get("Default");
}
if (webElement.isSelected() != checkboxValue.booleanValue()) {
webElement.click();
}
} catch (final Exception e) {
new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_CHECK_ELEMENT), element, element.getPage().getApplication()), true,
element.getPage().getCallBack());
}
} | java | protected void selectCheckbox(PageElement element, String valueKeyOrKey, Map<String, Boolean> values) throws TechnicalException, FailureException {
final String valueKey = Context.getValue(valueKeyOrKey) != null ? Context.getValue(valueKeyOrKey) : valueKeyOrKey;
try {
final WebElement webElement = Context.waitUntil(ExpectedConditions.elementToBeClickable(Utilities.getLocator(element)));
Boolean checkboxValue = values.get(valueKey);
if (checkboxValue == null) {
checkboxValue = values.get("Default");
}
if (webElement.isSelected() != checkboxValue.booleanValue()) {
webElement.click();
}
} catch (final Exception e) {
new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_CHECK_ELEMENT), element, element.getPage().getApplication()), true,
element.getPage().getCallBack());
}
} | [
"protected",
"void",
"selectCheckbox",
"(",
"PageElement",
"element",
",",
"String",
"valueKeyOrKey",
",",
"Map",
"<",
"String",
",",
"Boolean",
">",
"values",
")",
"throws",
"TechnicalException",
",",
"FailureException",
"{",
"final",
"String",
"valueKey",
"=",
"Context",
".",
"getValue",
"(",
"valueKeyOrKey",
")",
"!=",
"null",
"?",
"Context",
".",
"getValue",
"(",
"valueKeyOrKey",
")",
":",
"valueKeyOrKey",
";",
"try",
"{",
"final",
"WebElement",
"webElement",
"=",
"Context",
".",
"waitUntil",
"(",
"ExpectedConditions",
".",
"elementToBeClickable",
"(",
"Utilities",
".",
"getLocator",
"(",
"element",
")",
")",
")",
";",
"Boolean",
"checkboxValue",
"=",
"values",
".",
"get",
"(",
"valueKey",
")",
";",
"if",
"(",
"checkboxValue",
"==",
"null",
")",
"{",
"checkboxValue",
"=",
"values",
".",
"get",
"(",
"\"Default\"",
")",
";",
"}",
"if",
"(",
"webElement",
".",
"isSelected",
"(",
")",
"!=",
"checkboxValue",
".",
"booleanValue",
"(",
")",
")",
"{",
"webElement",
".",
"click",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"new",
"Result",
".",
"Failure",
"<>",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"Messages",
".",
"format",
"(",
"Messages",
".",
"getMessage",
"(",
"Messages",
".",
"FAIL_MESSAGE_UNABLE_TO_CHECK_ELEMENT",
")",
",",
"element",
",",
"element",
".",
"getPage",
"(",
")",
".",
"getApplication",
"(",
")",
")",
",",
"true",
",",
"element",
".",
"getPage",
"(",
")",
".",
"getCallBack",
"(",
")",
")",
";",
"}",
"}"
]
| Checks a checkbox type element (value corresponding to key "valueKey").
@param element
Target page element
@param valueKeyOrKey
is valueKey (valueKey or key in context (after a save)) to match in values map
@param values
Values map
@throws TechnicalException
is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi.
Failure with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_CHECK_ELEMENT} message (with screenshot)
@throws FailureException
if the scenario encounters a functional error | [
"Checks",
"a",
"checkbox",
"type",
"element",
"(",
"value",
"corresponding",
"to",
"key",
"valueKey",
")",
"."
]
| train | https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/Step.java#L739-L754 |
JoeKerouac/utils | src/main/java/com/joe/utils/reflect/asm/AsmByteCodeUtils.java | AsmByteCodeUtils.invokeMethod | public static void invokeMethod(MethodVisitor mv, Method method, Runnable load) {
"""
byte code执行指定方法
@param mv MethodVisitor
@param method 要执行的方法
@param load 加载方法需要的数据
"""
// 先加载数据
load.run();
// 执行方法
if (method.getDeclaringClass().isInterface()) {
mv.visitMethodInsn(INVOKEINTERFACE, convert(method.getDeclaringClass()),
method.getName(), getMethodDesc(method), true);
} else {
mv.visitMethodInsn(INVOKEVIRTUAL, convert(method.getDeclaringClass()), method.getName(),
getMethodDesc(method), false);
}
if (method.getReturnType() == void.class) {
mv.visitInsn(ACONST_NULL);
mv.visitInsn(ARETURN);
} else {
// 返回结果
mv.visitInsn(ARETURN);
}
} | java | public static void invokeMethod(MethodVisitor mv, Method method, Runnable load) {
// 先加载数据
load.run();
// 执行方法
if (method.getDeclaringClass().isInterface()) {
mv.visitMethodInsn(INVOKEINTERFACE, convert(method.getDeclaringClass()),
method.getName(), getMethodDesc(method), true);
} else {
mv.visitMethodInsn(INVOKEVIRTUAL, convert(method.getDeclaringClass()), method.getName(),
getMethodDesc(method), false);
}
if (method.getReturnType() == void.class) {
mv.visitInsn(ACONST_NULL);
mv.visitInsn(ARETURN);
} else {
// 返回结果
mv.visitInsn(ARETURN);
}
} | [
"public",
"static",
"void",
"invokeMethod",
"(",
"MethodVisitor",
"mv",
",",
"Method",
"method",
",",
"Runnable",
"load",
")",
"{",
"// 先加载数据",
"load",
".",
"run",
"(",
")",
";",
"// 执行方法",
"if",
"(",
"method",
".",
"getDeclaringClass",
"(",
")",
".",
"isInterface",
"(",
")",
")",
"{",
"mv",
".",
"visitMethodInsn",
"(",
"INVOKEINTERFACE",
",",
"convert",
"(",
"method",
".",
"getDeclaringClass",
"(",
")",
")",
",",
"method",
".",
"getName",
"(",
")",
",",
"getMethodDesc",
"(",
"method",
")",
",",
"true",
")",
";",
"}",
"else",
"{",
"mv",
".",
"visitMethodInsn",
"(",
"INVOKEVIRTUAL",
",",
"convert",
"(",
"method",
".",
"getDeclaringClass",
"(",
")",
")",
",",
"method",
".",
"getName",
"(",
")",
",",
"getMethodDesc",
"(",
"method",
")",
",",
"false",
")",
";",
"}",
"if",
"(",
"method",
".",
"getReturnType",
"(",
")",
"==",
"void",
".",
"class",
")",
"{",
"mv",
".",
"visitInsn",
"(",
"ACONST_NULL",
")",
";",
"mv",
".",
"visitInsn",
"(",
"ARETURN",
")",
";",
"}",
"else",
"{",
"// 返回结果",
"mv",
".",
"visitInsn",
"(",
"ARETURN",
")",
";",
"}",
"}"
]
| byte code执行指定方法
@param mv MethodVisitor
@param method 要执行的方法
@param load 加载方法需要的数据 | [
"byte",
"code执行指定方法"
]
| train | https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/reflect/asm/AsmByteCodeUtils.java#L48-L66 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java | JDBCResultSet.updateByte | public void updateByte(int columnIndex, byte x) throws SQLException {
"""
<!-- start generic documentation -->
Updates the designated column with a <code>byte</code> value.
The updater methods are used to update column values in the
current row or the insert row. The updater methods do not
update the underlying database; instead the <code>updateRow</code> or
<code>insertRow</code> methods are called to update the database.
<!-- end generic documentation -->
<!-- start release-specific documentation -->
<div class="ReleaseSpecificDocumentation">
<h3>HSQLDB-Specific Information:</h3> <p>
HSQLDB supports this feature. <p>
</div>
<!-- end release-specific documentation -->
@param columnIndex the first column is 1, the second is 2, ...
@param x the new column value
@exception SQLException if a database access error occurs,
the result set concurrency is <code>CONCUR_READ_ONLY</code>
or this method is called on a closed result set
@exception SQLFeatureNotSupportedException if the JDBC driver does not support
this method
@since JDK 1.2 (JDK 1.1.x developers: read the overview for
JDBCResultSet)
"""
startUpdate(columnIndex);
preparedStatement.setIntParameter(columnIndex, x);
} | java | public void updateByte(int columnIndex, byte x) throws SQLException {
startUpdate(columnIndex);
preparedStatement.setIntParameter(columnIndex, x);
} | [
"public",
"void",
"updateByte",
"(",
"int",
"columnIndex",
",",
"byte",
"x",
")",
"throws",
"SQLException",
"{",
"startUpdate",
"(",
"columnIndex",
")",
";",
"preparedStatement",
".",
"setIntParameter",
"(",
"columnIndex",
",",
"x",
")",
";",
"}"
]
| <!-- start generic documentation -->
Updates the designated column with a <code>byte</code> value.
The updater methods are used to update column values in the
current row or the insert row. The updater methods do not
update the underlying database; instead the <code>updateRow</code> or
<code>insertRow</code> methods are called to update the database.
<!-- end generic documentation -->
<!-- start release-specific documentation -->
<div class="ReleaseSpecificDocumentation">
<h3>HSQLDB-Specific Information:</h3> <p>
HSQLDB supports this feature. <p>
</div>
<!-- end release-specific documentation -->
@param columnIndex the first column is 1, the second is 2, ...
@param x the new column value
@exception SQLException if a database access error occurs,
the result set concurrency is <code>CONCUR_READ_ONLY</code>
or this method is called on a closed result set
@exception SQLFeatureNotSupportedException if the JDBC driver does not support
this method
@since JDK 1.2 (JDK 1.1.x developers: read the overview for
JDBCResultSet) | [
"<!",
"--",
"start",
"generic",
"documentation",
"--",
">",
"Updates",
"the",
"designated",
"column",
"with",
"a",
"<code",
">",
"byte<",
"/",
"code",
">",
"value",
".",
"The",
"updater",
"methods",
"are",
"used",
"to",
"update",
"column",
"values",
"in",
"the",
"current",
"row",
"or",
"the",
"insert",
"row",
".",
"The",
"updater",
"methods",
"do",
"not",
"update",
"the",
"underlying",
"database",
";",
"instead",
"the",
"<code",
">",
"updateRow<",
"/",
"code",
">",
"or",
"<code",
">",
"insertRow<",
"/",
"code",
">",
"methods",
"are",
"called",
"to",
"update",
"the",
"database",
".",
"<!",
"--",
"end",
"generic",
"documentation",
"--",
">"
]
| train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java#L2685-L2688 |
gallandarakhneorg/afc | advanced/dbasefile/src/main/java/org/arakhne/afc/io/dbase/DBaseFileReader.java | DBaseFileReader.readBooleanRecordValue | @SuppressWarnings("checkstyle:magicnumber")
private static int readBooleanRecordValue(DBaseFileField field, int nrecord, int nfield, byte[] rawData,
int rawOffset, OutputParameter<Boolean> value) throws IOException {
"""
Read a BOOLEAN record value.
@param field is the current parsed field.
@param nrecord is the number of the record
@param nfield is the number of the field
@param rawData raw data
@param rawOffset is the index at which the data could be obtained
@param value will be set with the value extracted from the dBASE file
@return the count of consumed bytes
@throws IOException in case of error.
"""
final int byteCode = rawData[rawOffset] & 0xFF;
if (TRUE_CHARS.indexOf(byteCode) != -1) {
value.set(true);
return 1;
}
if (FALSE_CHARS.indexOf(byteCode) != -1) {
value.set(false);
return 1;
}
throw new InvalidRawDataFormatException(nrecord, nfield, Integer.toString(byteCode));
} | java | @SuppressWarnings("checkstyle:magicnumber")
private static int readBooleanRecordValue(DBaseFileField field, int nrecord, int nfield, byte[] rawData,
int rawOffset, OutputParameter<Boolean> value) throws IOException {
final int byteCode = rawData[rawOffset] & 0xFF;
if (TRUE_CHARS.indexOf(byteCode) != -1) {
value.set(true);
return 1;
}
if (FALSE_CHARS.indexOf(byteCode) != -1) {
value.set(false);
return 1;
}
throw new InvalidRawDataFormatException(nrecord, nfield, Integer.toString(byteCode));
} | [
"@",
"SuppressWarnings",
"(",
"\"checkstyle:magicnumber\"",
")",
"private",
"static",
"int",
"readBooleanRecordValue",
"(",
"DBaseFileField",
"field",
",",
"int",
"nrecord",
",",
"int",
"nfield",
",",
"byte",
"[",
"]",
"rawData",
",",
"int",
"rawOffset",
",",
"OutputParameter",
"<",
"Boolean",
">",
"value",
")",
"throws",
"IOException",
"{",
"final",
"int",
"byteCode",
"=",
"rawData",
"[",
"rawOffset",
"]",
"&",
"0xFF",
";",
"if",
"(",
"TRUE_CHARS",
".",
"indexOf",
"(",
"byteCode",
")",
"!=",
"-",
"1",
")",
"{",
"value",
".",
"set",
"(",
"true",
")",
";",
"return",
"1",
";",
"}",
"if",
"(",
"FALSE_CHARS",
".",
"indexOf",
"(",
"byteCode",
")",
"!=",
"-",
"1",
")",
"{",
"value",
".",
"set",
"(",
"false",
")",
";",
"return",
"1",
";",
"}",
"throw",
"new",
"InvalidRawDataFormatException",
"(",
"nrecord",
",",
"nfield",
",",
"Integer",
".",
"toString",
"(",
"byteCode",
")",
")",
";",
"}"
]
| Read a BOOLEAN record value.
@param field is the current parsed field.
@param nrecord is the number of the record
@param nfield is the number of the field
@param rawData raw data
@param rawOffset is the index at which the data could be obtained
@param value will be set with the value extracted from the dBASE file
@return the count of consumed bytes
@throws IOException in case of error. | [
"Read",
"a",
"BOOLEAN",
"record",
"value",
"."
]
| train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/dbasefile/src/main/java/org/arakhne/afc/io/dbase/DBaseFileReader.java#L1148-L1164 |
apache/groovy | src/main/java/org/codehaus/groovy/vmplugin/v7/IndyGuardsFiltersAndSignatures.java | IndyGuardsFiltersAndSignatures.setBeanProperties | public static Object setBeanProperties(MetaClass mc, Object bean, Map properties) {
"""
This method is called by he handle to realize the bean constructor
with property map.
"""
for (Iterator iter = properties.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String key = entry.getKey().toString();
Object value = entry.getValue();
mc.setProperty(bean, key, value);
}
return bean;
} | java | public static Object setBeanProperties(MetaClass mc, Object bean, Map properties) {
for (Iterator iter = properties.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String key = entry.getKey().toString();
Object value = entry.getValue();
mc.setProperty(bean, key, value);
}
return bean;
} | [
"public",
"static",
"Object",
"setBeanProperties",
"(",
"MetaClass",
"mc",
",",
"Object",
"bean",
",",
"Map",
"properties",
")",
"{",
"for",
"(",
"Iterator",
"iter",
"=",
"properties",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"iter",
".",
"hasNext",
"(",
")",
";",
")",
"{",
"Map",
".",
"Entry",
"entry",
"=",
"(",
"Map",
".",
"Entry",
")",
"iter",
".",
"next",
"(",
")",
";",
"String",
"key",
"=",
"entry",
".",
"getKey",
"(",
")",
".",
"toString",
"(",
")",
";",
"Object",
"value",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"mc",
".",
"setProperty",
"(",
"bean",
",",
"key",
",",
"value",
")",
";",
"}",
"return",
"bean",
";",
"}"
]
| This method is called by he handle to realize the bean constructor
with property map. | [
"This",
"method",
"is",
"called",
"by",
"he",
"handle",
"to",
"realize",
"the",
"bean",
"constructor",
"with",
"property",
"map",
"."
]
| train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/vmplugin/v7/IndyGuardsFiltersAndSignatures.java#L133-L142 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/proxyhandler/MultiMEProxyHandler.java | MultiMEProxyHandler.getNeighbour | public final Neighbour getNeighbour(SIBUuid8 neighbourUUID, boolean includeRecovered) {
"""
Returns the neighbour for the given UUID
@param neighbourUUID The uuid to find
@param includeRecovered Also look for the neighbour in the recovered list
@return The neighbour object
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getNeighbour", new Object[] { neighbourUUID, Boolean.valueOf(includeRecovered)});
Neighbour neighbour = _neighbours.getNeighbour(neighbourUUID);
if((neighbour == null) && includeRecovered)
neighbour = _neighbours.getRecoveredNeighbour(neighbourUUID);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "getNeighbour", neighbour);
return neighbour;
} | java | public final Neighbour getNeighbour(SIBUuid8 neighbourUUID, boolean includeRecovered)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getNeighbour", new Object[] { neighbourUUID, Boolean.valueOf(includeRecovered)});
Neighbour neighbour = _neighbours.getNeighbour(neighbourUUID);
if((neighbour == null) && includeRecovered)
neighbour = _neighbours.getRecoveredNeighbour(neighbourUUID);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "getNeighbour", neighbour);
return neighbour;
} | [
"public",
"final",
"Neighbour",
"getNeighbour",
"(",
"SIBUuid8",
"neighbourUUID",
",",
"boolean",
"includeRecovered",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
"tc",
",",
"\"getNeighbour\"",
",",
"new",
"Object",
"[",
"]",
"{",
"neighbourUUID",
",",
"Boolean",
".",
"valueOf",
"(",
"includeRecovered",
")",
"}",
")",
";",
"Neighbour",
"neighbour",
"=",
"_neighbours",
".",
"getNeighbour",
"(",
"neighbourUUID",
")",
";",
"if",
"(",
"(",
"neighbour",
"==",
"null",
")",
"&&",
"includeRecovered",
")",
"neighbour",
"=",
"_neighbours",
".",
"getRecoveredNeighbour",
"(",
"neighbourUUID",
")",
";",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"exit",
"(",
"tc",
",",
"\"getNeighbour\"",
",",
"neighbour",
")",
";",
"return",
"neighbour",
";",
"}"
]
| Returns the neighbour for the given UUID
@param neighbourUUID The uuid to find
@param includeRecovered Also look for the neighbour in the recovered list
@return The neighbour object | [
"Returns",
"the",
"neighbour",
"for",
"the",
"given",
"UUID"
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/proxyhandler/MultiMEProxyHandler.java#L1297-L1311 |
CycloneDX/cyclonedx-core-java | src/main/java/org/cyclonedx/BomGenerator11.java | BomGenerator11.generate | public Document generate() throws ParserConfigurationException {
"""
Creates a CycloneDX BoM from a set of Components.
@return an XML Document representing a CycloneDX BoM
@since 2.0.0
"""
final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(true);
final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
this.doc = docBuilder.newDocument();
doc.setXmlStandalone(true);
// Create root <bom> node
final Element bomNode = createRootElement("bom", null,
new Attribute("xmlns", NS_BOM_11),
new Attribute("version", String.valueOf(bom.getVersion())));
if (bom.getSerialNumber() != null) {
bomNode.setAttribute("serialNumber", bom.getSerialNumber());
}
final Element componentsNode = createElement(bomNode, "components");
createComponentsNode(componentsNode, bom.getComponents());
createExternalReferencesNode(bomNode, bom.getExternalReferences());
return doc;
} | java | public Document generate() throws ParserConfigurationException {
final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(true);
final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
this.doc = docBuilder.newDocument();
doc.setXmlStandalone(true);
// Create root <bom> node
final Element bomNode = createRootElement("bom", null,
new Attribute("xmlns", NS_BOM_11),
new Attribute("version", String.valueOf(bom.getVersion())));
if (bom.getSerialNumber() != null) {
bomNode.setAttribute("serialNumber", bom.getSerialNumber());
}
final Element componentsNode = createElement(bomNode, "components");
createComponentsNode(componentsNode, bom.getComponents());
createExternalReferencesNode(bomNode, bom.getExternalReferences());
return doc;
} | [
"public",
"Document",
"generate",
"(",
")",
"throws",
"ParserConfigurationException",
"{",
"final",
"DocumentBuilderFactory",
"docFactory",
"=",
"DocumentBuilderFactory",
".",
"newInstance",
"(",
")",
";",
"docFactory",
".",
"setNamespaceAware",
"(",
"true",
")",
";",
"final",
"DocumentBuilder",
"docBuilder",
"=",
"docFactory",
".",
"newDocumentBuilder",
"(",
")",
";",
"this",
".",
"doc",
"=",
"docBuilder",
".",
"newDocument",
"(",
")",
";",
"doc",
".",
"setXmlStandalone",
"(",
"true",
")",
";",
"// Create root <bom> node",
"final",
"Element",
"bomNode",
"=",
"createRootElement",
"(",
"\"bom\"",
",",
"null",
",",
"new",
"Attribute",
"(",
"\"xmlns\"",
",",
"NS_BOM_11",
")",
",",
"new",
"Attribute",
"(",
"\"version\"",
",",
"String",
".",
"valueOf",
"(",
"bom",
".",
"getVersion",
"(",
")",
")",
")",
")",
";",
"if",
"(",
"bom",
".",
"getSerialNumber",
"(",
")",
"!=",
"null",
")",
"{",
"bomNode",
".",
"setAttribute",
"(",
"\"serialNumber\"",
",",
"bom",
".",
"getSerialNumber",
"(",
")",
")",
";",
"}",
"final",
"Element",
"componentsNode",
"=",
"createElement",
"(",
"bomNode",
",",
"\"components\"",
")",
";",
"createComponentsNode",
"(",
"componentsNode",
",",
"bom",
".",
"getComponents",
"(",
")",
")",
";",
"createExternalReferencesNode",
"(",
"bomNode",
",",
"bom",
".",
"getExternalReferences",
"(",
")",
")",
";",
"return",
"doc",
";",
"}"
]
| Creates a CycloneDX BoM from a set of Components.
@return an XML Document representing a CycloneDX BoM
@since 2.0.0 | [
"Creates",
"a",
"CycloneDX",
"BoM",
"from",
"a",
"set",
"of",
"Components",
"."
]
| train | https://github.com/CycloneDX/cyclonedx-core-java/blob/45f8f55a7f308f41280b834f179b48ea852b8c20/src/main/java/org/cyclonedx/BomGenerator11.java#L70-L89 |
foundation-runtime/service-directory | 2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java | DirectoryServiceClient.updateServiceInstanceStatus | public void updateServiceInstanceStatus(String serviceName, String instanceId, OperationalStatus status) {
"""
Update ServiceInstance status.
@param serviceName
the service name.
@param instanceId
the instanceId.
@param status
the OeperationalStatus.
"""
ProtocolHeader header = new ProtocolHeader();
header.setType(ProtocolType.UpdateServiceInstanceStatus);
UpdateServiceInstanceStatusProtocol p = new UpdateServiceInstanceStatusProtocol(serviceName, instanceId, status);
connection.submitRequest(header, p, null);
} | java | public void updateServiceInstanceStatus(String serviceName, String instanceId, OperationalStatus status){
ProtocolHeader header = new ProtocolHeader();
header.setType(ProtocolType.UpdateServiceInstanceStatus);
UpdateServiceInstanceStatusProtocol p = new UpdateServiceInstanceStatusProtocol(serviceName, instanceId, status);
connection.submitRequest(header, p, null);
} | [
"public",
"void",
"updateServiceInstanceStatus",
"(",
"String",
"serviceName",
",",
"String",
"instanceId",
",",
"OperationalStatus",
"status",
")",
"{",
"ProtocolHeader",
"header",
"=",
"new",
"ProtocolHeader",
"(",
")",
";",
"header",
".",
"setType",
"(",
"ProtocolType",
".",
"UpdateServiceInstanceStatus",
")",
";",
"UpdateServiceInstanceStatusProtocol",
"p",
"=",
"new",
"UpdateServiceInstanceStatusProtocol",
"(",
"serviceName",
",",
"instanceId",
",",
"status",
")",
";",
"connection",
".",
"submitRequest",
"(",
"header",
",",
"p",
",",
"null",
")",
";",
"}"
]
| Update ServiceInstance status.
@param serviceName
the service name.
@param instanceId
the instanceId.
@param status
the OeperationalStatus. | [
"Update",
"ServiceInstance",
"status",
"."
]
| train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java#L401-L407 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.setUsersOrganizationalUnit | public void setUsersOrganizationalUnit(CmsRequestContext context, CmsOrganizationalUnit orgUnit, CmsUser user)
throws CmsException {
"""
Moves an user to the given organizational unit.<p>
@param context the current request context
@param orgUnit the organizational unit to add the principal to
@param user the user that is to be move to the organizational unit
@throws CmsException if something goes wrong
@see org.opencms.security.CmsOrgUnitManager#setUsersOrganizationalUnit(CmsObject, String, String)
"""
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
checkRole(dbc, CmsRole.ADMINISTRATOR.forOrgUnit(orgUnit.getName()));
checkOfflineProject(dbc);
m_driverManager.setUsersOrganizationalUnit(dbc, orgUnit, user);
} catch (Exception e) {
dbc.report(
null,
Messages.get().container(Messages.ERR_SET_USERS_ORGUNIT_2, orgUnit.getName(), user.getName()),
e);
} finally {
dbc.clear();
}
} | java | public void setUsersOrganizationalUnit(CmsRequestContext context, CmsOrganizationalUnit orgUnit, CmsUser user)
throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
checkRole(dbc, CmsRole.ADMINISTRATOR.forOrgUnit(orgUnit.getName()));
checkOfflineProject(dbc);
m_driverManager.setUsersOrganizationalUnit(dbc, orgUnit, user);
} catch (Exception e) {
dbc.report(
null,
Messages.get().container(Messages.ERR_SET_USERS_ORGUNIT_2, orgUnit.getName(), user.getName()),
e);
} finally {
dbc.clear();
}
} | [
"public",
"void",
"setUsersOrganizationalUnit",
"(",
"CmsRequestContext",
"context",
",",
"CmsOrganizationalUnit",
"orgUnit",
",",
"CmsUser",
"user",
")",
"throws",
"CmsException",
"{",
"CmsDbContext",
"dbc",
"=",
"m_dbContextFactory",
".",
"getDbContext",
"(",
"context",
")",
";",
"try",
"{",
"checkRole",
"(",
"dbc",
",",
"CmsRole",
".",
"ADMINISTRATOR",
".",
"forOrgUnit",
"(",
"orgUnit",
".",
"getName",
"(",
")",
")",
")",
";",
"checkOfflineProject",
"(",
"dbc",
")",
";",
"m_driverManager",
".",
"setUsersOrganizationalUnit",
"(",
"dbc",
",",
"orgUnit",
",",
"user",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"dbc",
".",
"report",
"(",
"null",
",",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"Messages",
".",
"ERR_SET_USERS_ORGUNIT_2",
",",
"orgUnit",
".",
"getName",
"(",
")",
",",
"user",
".",
"getName",
"(",
")",
")",
",",
"e",
")",
";",
"}",
"finally",
"{",
"dbc",
".",
"clear",
"(",
")",
";",
"}",
"}"
]
| Moves an user to the given organizational unit.<p>
@param context the current request context
@param orgUnit the organizational unit to add the principal to
@param user the user that is to be move to the organizational unit
@throws CmsException if something goes wrong
@see org.opencms.security.CmsOrgUnitManager#setUsersOrganizationalUnit(CmsObject, String, String) | [
"Moves",
"an",
"user",
"to",
"the",
"given",
"organizational",
"unit",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L6135-L6151 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/GVRApplication.java | GVRApplication.enableGestureDetector | public synchronized void enableGestureDetector() {
"""
Enables the Android GestureDetector which in turn fires the appropriate {@link GVRMain} callbacks.
By default it is not.
@see GVRMain#onSwipe(GVRTouchPadGestureListener.Action, float)
@see GVRMain#onSingleTapUp(MotionEvent)
@see GVRTouchPadGestureListener
"""
final GVRTouchPadGestureListener gestureListener = new GVRTouchPadGestureListener() {
@Override
public boolean onSwipe(MotionEvent e, Action action, float vx, float vy) {
if (null != mGVRMain) {
mGVRMain.onSwipe(action, vx);
}
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
if (null != mGVRMain) {
mGVRMain.onSingleTapUp(e);
}
return true;
}
};
mGestureDetector = new GestureDetector(mActivity.getApplicationContext(), gestureListener);
getEventReceiver().addListener(new GVREventListeners.ActivityEvents() {
@Override
public void dispatchTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
}
});
} | java | public synchronized void enableGestureDetector() {
final GVRTouchPadGestureListener gestureListener = new GVRTouchPadGestureListener() {
@Override
public boolean onSwipe(MotionEvent e, Action action, float vx, float vy) {
if (null != mGVRMain) {
mGVRMain.onSwipe(action, vx);
}
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
if (null != mGVRMain) {
mGVRMain.onSingleTapUp(e);
}
return true;
}
};
mGestureDetector = new GestureDetector(mActivity.getApplicationContext(), gestureListener);
getEventReceiver().addListener(new GVREventListeners.ActivityEvents() {
@Override
public void dispatchTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
}
});
} | [
"public",
"synchronized",
"void",
"enableGestureDetector",
"(",
")",
"{",
"final",
"GVRTouchPadGestureListener",
"gestureListener",
"=",
"new",
"GVRTouchPadGestureListener",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"onSwipe",
"(",
"MotionEvent",
"e",
",",
"Action",
"action",
",",
"float",
"vx",
",",
"float",
"vy",
")",
"{",
"if",
"(",
"null",
"!=",
"mGVRMain",
")",
"{",
"mGVRMain",
".",
"onSwipe",
"(",
"action",
",",
"vx",
")",
";",
"}",
"return",
"true",
";",
"}",
"@",
"Override",
"public",
"boolean",
"onSingleTapUp",
"(",
"MotionEvent",
"e",
")",
"{",
"if",
"(",
"null",
"!=",
"mGVRMain",
")",
"{",
"mGVRMain",
".",
"onSingleTapUp",
"(",
"e",
")",
";",
"}",
"return",
"true",
";",
"}",
"}",
";",
"mGestureDetector",
"=",
"new",
"GestureDetector",
"(",
"mActivity",
".",
"getApplicationContext",
"(",
")",
",",
"gestureListener",
")",
";",
"getEventReceiver",
"(",
")",
".",
"addListener",
"(",
"new",
"GVREventListeners",
".",
"ActivityEvents",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"dispatchTouchEvent",
"(",
"MotionEvent",
"event",
")",
"{",
"mGestureDetector",
".",
"onTouchEvent",
"(",
"event",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Enables the Android GestureDetector which in turn fires the appropriate {@link GVRMain} callbacks.
By default it is not.
@see GVRMain#onSwipe(GVRTouchPadGestureListener.Action, float)
@see GVRMain#onSingleTapUp(MotionEvent)
@see GVRTouchPadGestureListener | [
"Enables",
"the",
"Android",
"GestureDetector",
"which",
"in",
"turn",
"fires",
"the",
"appropriate",
"{"
]
| train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRApplication.java#L710-L735 |
Stratio/cassandra-lucene-index | plugin/src/main/java/com/stratio/cassandra/lucene/common/GeospatialUtils.java | GeospatialUtils.checkLatitude | public static Double checkLatitude(String name, Double latitude) {
"""
Checks if the specified latitude is correct.
@param name the name of the latitude field
@param latitude the value of the latitude field
@return the latitude
"""
if (latitude == null) {
throw new IndexException("{} required", name);
} else if (latitude < MIN_LATITUDE || latitude > MAX_LATITUDE) {
throw new IndexException("{} must be in range [{}, {}], but found {}",
name,
MIN_LATITUDE,
MAX_LATITUDE,
latitude);
}
return latitude;
} | java | public static Double checkLatitude(String name, Double latitude) {
if (latitude == null) {
throw new IndexException("{} required", name);
} else if (latitude < MIN_LATITUDE || latitude > MAX_LATITUDE) {
throw new IndexException("{} must be in range [{}, {}], but found {}",
name,
MIN_LATITUDE,
MAX_LATITUDE,
latitude);
}
return latitude;
} | [
"public",
"static",
"Double",
"checkLatitude",
"(",
"String",
"name",
",",
"Double",
"latitude",
")",
"{",
"if",
"(",
"latitude",
"==",
"null",
")",
"{",
"throw",
"new",
"IndexException",
"(",
"\"{} required\"",
",",
"name",
")",
";",
"}",
"else",
"if",
"(",
"latitude",
"<",
"MIN_LATITUDE",
"||",
"latitude",
">",
"MAX_LATITUDE",
")",
"{",
"throw",
"new",
"IndexException",
"(",
"\"{} must be in range [{}, {}], but found {}\"",
",",
"name",
",",
"MIN_LATITUDE",
",",
"MAX_LATITUDE",
",",
"latitude",
")",
";",
"}",
"return",
"latitude",
";",
"}"
]
| Checks if the specified latitude is correct.
@param name the name of the latitude field
@param latitude the value of the latitude field
@return the latitude | [
"Checks",
"if",
"the",
"specified",
"latitude",
"is",
"correct",
"."
]
| train | https://github.com/Stratio/cassandra-lucene-index/blob/a94a4d9af6c25d40e1108729974c35c27c54441c/plugin/src/main/java/com/stratio/cassandra/lucene/common/GeospatialUtils.java#L68-L79 |
alkacon/opencms-core | src/org/opencms/jsp/util/CmsStringTemplateRenderer.java | CmsStringTemplateRenderer.renderTemplate | public static String renderTemplate(
CmsObject cms,
String template,
CmsResource content,
Map<String, Object> contextObjects) {
"""
Renders the given string template.<p>
@param cms the cms context
@param template the template
@param content the content
@param contextObjects additional context objects made available to the template
@return the rendering result
"""
return renderTemplate(cms, template, new CmsJspContentAccessBean(cms, content), contextObjects);
} | java | public static String renderTemplate(
CmsObject cms,
String template,
CmsResource content,
Map<String, Object> contextObjects) {
return renderTemplate(cms, template, new CmsJspContentAccessBean(cms, content), contextObjects);
} | [
"public",
"static",
"String",
"renderTemplate",
"(",
"CmsObject",
"cms",
",",
"String",
"template",
",",
"CmsResource",
"content",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"contextObjects",
")",
"{",
"return",
"renderTemplate",
"(",
"cms",
",",
"template",
",",
"new",
"CmsJspContentAccessBean",
"(",
"cms",
",",
"content",
")",
",",
"contextObjects",
")",
";",
"}"
]
| Renders the given string template.<p>
@param cms the cms context
@param template the template
@param content the content
@param contextObjects additional context objects made available to the template
@return the rendering result | [
"Renders",
"the",
"given",
"string",
"template",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/util/CmsStringTemplateRenderer.java#L170-L177 |
sriharshachilakapati/WebGL4J | webgl4j/src/main/java/com/shc/webgl4j/client/WebGL10.java | WebGL10.glClearColor | public static void glClearColor(float r, float g, float b, float a) {
"""
{@code glClearColor} specifies the red, green, blue, and alpha values used by {@link #glClear(int)} to clear the
color buffers. Values specified by {@code glClearColor} are clamped to the range [0,1].
@param r Specifies the red value used when the color buffers are cleared.
@param g Specifies the green value used when the color buffers are cleared.
@param b Specifies the blue value used when the color buffers are cleared.
@param a Specifies the alpha value used when the color buffers are cleared.
"""
checkContextCompatibility();
nglClearColor(r, g, b, a);
} | java | public static void glClearColor(float r, float g, float b, float a)
{
checkContextCompatibility();
nglClearColor(r, g, b, a);
} | [
"public",
"static",
"void",
"glClearColor",
"(",
"float",
"r",
",",
"float",
"g",
",",
"float",
"b",
",",
"float",
"a",
")",
"{",
"checkContextCompatibility",
"(",
")",
";",
"nglClearColor",
"(",
"r",
",",
"g",
",",
"b",
",",
"a",
")",
";",
"}"
]
| {@code glClearColor} specifies the red, green, blue, and alpha values used by {@link #glClear(int)} to clear the
color buffers. Values specified by {@code glClearColor} are clamped to the range [0,1].
@param r Specifies the red value used when the color buffers are cleared.
@param g Specifies the green value used when the color buffers are cleared.
@param b Specifies the blue value used when the color buffers are cleared.
@param a Specifies the alpha value used when the color buffers are cleared. | [
"{",
"@code",
"glClearColor",
"}",
"specifies",
"the",
"red",
"green",
"blue",
"and",
"alpha",
"values",
"used",
"by",
"{",
"@link",
"#glClear",
"(",
"int",
")",
"}",
"to",
"clear",
"the",
"color",
"buffers",
".",
"Values",
"specified",
"by",
"{",
"@code",
"glClearColor",
"}",
"are",
"clamped",
"to",
"the",
"range",
"[",
"0",
"1",
"]",
"."
]
| train | https://github.com/sriharshachilakapati/WebGL4J/blob/7daa425300b08b338b50cef2935289849c92d415/webgl4j/src/main/java/com/shc/webgl4j/client/WebGL10.java#L1209-L1213 |
SonarSource/sonarqube | server/sonar-db-dao/src/main/java/org/sonar/db/ce/CeQueueDao.java | CeQueueDao.resetToPendingForWorker | public int resetToPendingForWorker(DbSession session, String workerUuid) {
"""
Update all tasks for the specified worker uuid which are not PENDING to:
STATUS='PENDING', STARTED_AT=NULL, UPDATED_AT={now}.
"""
return mapper(session).resetToPendingForWorker(workerUuid, system2.now());
} | java | public int resetToPendingForWorker(DbSession session, String workerUuid) {
return mapper(session).resetToPendingForWorker(workerUuid, system2.now());
} | [
"public",
"int",
"resetToPendingForWorker",
"(",
"DbSession",
"session",
",",
"String",
"workerUuid",
")",
"{",
"return",
"mapper",
"(",
"session",
")",
".",
"resetToPendingForWorker",
"(",
"workerUuid",
",",
"system2",
".",
"now",
"(",
")",
")",
";",
"}"
]
| Update all tasks for the specified worker uuid which are not PENDING to:
STATUS='PENDING', STARTED_AT=NULL, UPDATED_AT={now}. | [
"Update",
"all",
"tasks",
"for",
"the",
"specified",
"worker",
"uuid",
"which",
"are",
"not",
"PENDING",
"to",
":",
"STATUS",
"=",
"PENDING",
"STARTED_AT",
"=",
"NULL",
"UPDATED_AT",
"=",
"{",
"now",
"}",
"."
]
| train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-db-dao/src/main/java/org/sonar/db/ce/CeQueueDao.java#L133-L135 |
dkpro/dkpro-jwpl | de.tudarmstadt.ukp.wikipedia.parser/src/main/java/de/tudarmstadt/ukp/wikipedia/parser/mediawiki/ModularParser.java | ModularParser.parseBoldAndItalicSpans | private void parseBoldAndItalicSpans(SpanManager sm, Span line,
List<Span> boldSpans, List<Span> italicSpans) {
"""
Searches a line for Bold and Italic quotations, this has to be done
linewhise.
"""
// Das suchen nach BOLD und ITALIC muss in den Jeweiligen
// Zeilen geschenhen, da ein LineSeparator immer BOLD und
// Italic Tags schliesst.
// Bold Spans
parseQuotedSpans(sm, line, boldSpans, "'''");
// Italic Spans
parseQuotedSpans(sm, line, italicSpans, "''");
// Maybe there is ONE SINGLE OPEN TAG left... handel these...
int openTag = sm.indexOf("''", line);
if (openTag != -1)
{
// build a Span from this Tag.
Span qs = new Span(openTag, line.getEnd());
// calculate the original src positions.
if (calculateSrcSpans)
{
qs.setSrcSpan(new SrcSpan(sm.getSrcPos(openTag), sm
.getSrcPos(line.getEnd())));
}
// is it a Bold or an Italic tag ?
if (sm.indexOf("'''", openTag, openTag + 3) != -1)
{
// --> BOLD
boldSpans.add(qs);
sm.delete(openTag, openTag + 3);
}
else
{
// --> ITALIC
italicSpans.add(qs);
sm.delete(openTag, openTag + 2);
}
}
} | java | private void parseBoldAndItalicSpans(SpanManager sm, Span line,
List<Span> boldSpans, List<Span> italicSpans)
{
// Das suchen nach BOLD und ITALIC muss in den Jeweiligen
// Zeilen geschenhen, da ein LineSeparator immer BOLD und
// Italic Tags schliesst.
// Bold Spans
parseQuotedSpans(sm, line, boldSpans, "'''");
// Italic Spans
parseQuotedSpans(sm, line, italicSpans, "''");
// Maybe there is ONE SINGLE OPEN TAG left... handel these...
int openTag = sm.indexOf("''", line);
if (openTag != -1)
{
// build a Span from this Tag.
Span qs = new Span(openTag, line.getEnd());
// calculate the original src positions.
if (calculateSrcSpans)
{
qs.setSrcSpan(new SrcSpan(sm.getSrcPos(openTag), sm
.getSrcPos(line.getEnd())));
}
// is it a Bold or an Italic tag ?
if (sm.indexOf("'''", openTag, openTag + 3) != -1)
{
// --> BOLD
boldSpans.add(qs);
sm.delete(openTag, openTag + 3);
}
else
{
// --> ITALIC
italicSpans.add(qs);
sm.delete(openTag, openTag + 2);
}
}
} | [
"private",
"void",
"parseBoldAndItalicSpans",
"(",
"SpanManager",
"sm",
",",
"Span",
"line",
",",
"List",
"<",
"Span",
">",
"boldSpans",
",",
"List",
"<",
"Span",
">",
"italicSpans",
")",
"{",
"// Das suchen nach BOLD und ITALIC muss in den Jeweiligen",
"// Zeilen geschenhen, da ein LineSeparator immer BOLD und",
"// Italic Tags schliesst.",
"// Bold Spans",
"parseQuotedSpans",
"(",
"sm",
",",
"line",
",",
"boldSpans",
",",
"\"'''\"",
")",
";",
"// Italic Spans",
"parseQuotedSpans",
"(",
"sm",
",",
"line",
",",
"italicSpans",
",",
"\"''\"",
")",
";",
"// Maybe there is ONE SINGLE OPEN TAG left... handel these...",
"int",
"openTag",
"=",
"sm",
".",
"indexOf",
"(",
"\"''\"",
",",
"line",
")",
";",
"if",
"(",
"openTag",
"!=",
"-",
"1",
")",
"{",
"// build a Span from this Tag.",
"Span",
"qs",
"=",
"new",
"Span",
"(",
"openTag",
",",
"line",
".",
"getEnd",
"(",
")",
")",
";",
"// calculate the original src positions.",
"if",
"(",
"calculateSrcSpans",
")",
"{",
"qs",
".",
"setSrcSpan",
"(",
"new",
"SrcSpan",
"(",
"sm",
".",
"getSrcPos",
"(",
"openTag",
")",
",",
"sm",
".",
"getSrcPos",
"(",
"line",
".",
"getEnd",
"(",
")",
")",
")",
")",
";",
"}",
"// is it a Bold or an Italic tag ?",
"if",
"(",
"sm",
".",
"indexOf",
"(",
"\"'''\"",
",",
"openTag",
",",
"openTag",
"+",
"3",
")",
"!=",
"-",
"1",
")",
"{",
"// --> BOLD",
"boldSpans",
".",
"add",
"(",
"qs",
")",
";",
"sm",
".",
"delete",
"(",
"openTag",
",",
"openTag",
"+",
"3",
")",
";",
"}",
"else",
"{",
"// --> ITALIC",
"italicSpans",
".",
"add",
"(",
"qs",
")",
";",
"sm",
".",
"delete",
"(",
"openTag",
",",
"openTag",
"+",
"2",
")",
";",
"}",
"}",
"}"
]
| Searches a line for Bold and Italic quotations, this has to be done
linewhise. | [
"Searches",
"a",
"line",
"for",
"Bold",
"and",
"Italic",
"quotations",
"this",
"has",
"to",
"be",
"done",
"linewhise",
"."
]
| train | https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.parser/src/main/java/de/tudarmstadt/ukp/wikipedia/parser/mediawiki/ModularParser.java#L1712-L1753 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/net/MessagingService.java | MessagingService.maybeAddLatency | public void maybeAddLatency(IAsyncCallback cb, InetAddress address, long latency) {
"""
Track latency information for the dynamic snitch
@param cb the callback associated with this message -- this lets us know if it's a message type we're interested in
@param address the host that replied to the message
@param latency
"""
if (cb.isLatencyForSnitch())
addLatency(address, latency);
} | java | public void maybeAddLatency(IAsyncCallback cb, InetAddress address, long latency)
{
if (cb.isLatencyForSnitch())
addLatency(address, latency);
} | [
"public",
"void",
"maybeAddLatency",
"(",
"IAsyncCallback",
"cb",
",",
"InetAddress",
"address",
",",
"long",
"latency",
")",
"{",
"if",
"(",
"cb",
".",
"isLatencyForSnitch",
"(",
")",
")",
"addLatency",
"(",
"address",
",",
"latency",
")",
";",
"}"
]
| Track latency information for the dynamic snitch
@param cb the callback associated with this message -- this lets us know if it's a message type we're interested in
@param address the host that replied to the message
@param latency | [
"Track",
"latency",
"information",
"for",
"the",
"dynamic",
"snitch"
]
| train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/net/MessagingService.java#L385-L389 |
Azure/azure-sdk-for-java | notificationhubs/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2016_03_01/implementation/NamespacesInner.java | NamespacesInner.createOrUpdateAuthorizationRule | public SharedAccessAuthorizationRuleResourceInner createOrUpdateAuthorizationRule(String resourceGroupName, String namespaceName, String authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters) {
"""
Creates an authorization rule for a namespace.
@param resourceGroupName The name of the resource group.
@param namespaceName The namespace name.
@param authorizationRuleName Aauthorization Rule Name.
@param parameters The shared access authorization rule.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the SharedAccessAuthorizationRuleResourceInner object if successful.
"""
return createOrUpdateAuthorizationRuleWithServiceResponseAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters).toBlocking().single().body();
} | java | public SharedAccessAuthorizationRuleResourceInner createOrUpdateAuthorizationRule(String resourceGroupName, String namespaceName, String authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters) {
return createOrUpdateAuthorizationRuleWithServiceResponseAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters).toBlocking().single().body();
} | [
"public",
"SharedAccessAuthorizationRuleResourceInner",
"createOrUpdateAuthorizationRule",
"(",
"String",
"resourceGroupName",
",",
"String",
"namespaceName",
",",
"String",
"authorizationRuleName",
",",
"SharedAccessAuthorizationRuleCreateOrUpdateParameters",
"parameters",
")",
"{",
"return",
"createOrUpdateAuthorizationRuleWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"namespaceName",
",",
"authorizationRuleName",
",",
"parameters",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
]
| Creates an authorization rule for a namespace.
@param resourceGroupName The name of the resource group.
@param namespaceName The namespace name.
@param authorizationRuleName Aauthorization Rule Name.
@param parameters The shared access authorization rule.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the SharedAccessAuthorizationRuleResourceInner object if successful. | [
"Creates",
"an",
"authorization",
"rule",
"for",
"a",
"namespace",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/notificationhubs/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2016_03_01/implementation/NamespacesInner.java#L666-L668 |
dashorst/wicket-stuff-markup-validator | jing/src/main/java/com/thaiopensource/validate/nvdl/SchemaImpl.java | SchemaImpl.lookupCreateMode | private Mode lookupCreateMode(String name) {
"""
Gets a mode with the given name from the mode map.
If not present then it creates a new mode extending the default base mode.
@param name The mode to look for or create if it does not exist.
@return Always a not null mode.
"""
if (name == null)
return null;
name = name.trim();
Mode mode = (Mode)modeMap.get(name);
if (mode == null) {
mode = new Mode(name, defaultBaseMode);
modeMap.put(name, mode);
}
return mode;
} | java | private Mode lookupCreateMode(String name) {
if (name == null)
return null;
name = name.trim();
Mode mode = (Mode)modeMap.get(name);
if (mode == null) {
mode = new Mode(name, defaultBaseMode);
modeMap.put(name, mode);
}
return mode;
} | [
"private",
"Mode",
"lookupCreateMode",
"(",
"String",
"name",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"return",
"null",
";",
"name",
"=",
"name",
".",
"trim",
"(",
")",
";",
"Mode",
"mode",
"=",
"(",
"Mode",
")",
"modeMap",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"mode",
"==",
"null",
")",
"{",
"mode",
"=",
"new",
"Mode",
"(",
"name",
",",
"defaultBaseMode",
")",
";",
"modeMap",
".",
"put",
"(",
"name",
",",
"mode",
")",
";",
"}",
"return",
"mode",
";",
"}"
]
| Gets a mode with the given name from the mode map.
If not present then it creates a new mode extending the default base mode.
@param name The mode to look for or create if it does not exist.
@return Always a not null mode. | [
"Gets",
"a",
"mode",
"with",
"the",
"given",
"name",
"from",
"the",
"mode",
"map",
".",
"If",
"not",
"present",
"then",
"it",
"creates",
"a",
"new",
"mode",
"extending",
"the",
"default",
"base",
"mode",
"."
]
| train | https://github.com/dashorst/wicket-stuff-markup-validator/blob/9e529a4dc8bfdbbe4c794f3132ef400a006560a1/jing/src/main/java/com/thaiopensource/validate/nvdl/SchemaImpl.java#L1244-L1254 |
Axway/Grapes | utils/src/main/java/org/axway/grapes/utils/client/GrapesClient.java | GrapesClient.getArtifacts | public List<Artifact> getArtifacts(final Boolean hasLicense) throws GrapesCommunicationException {
"""
Send a get artifacts request
@param hasLicense
@return list of artifact
@throws GrapesCommunicationException
"""
final Client client = getClient();
final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactsPath());
final ClientResponse response = resource.queryParam(ServerAPI.HAS_LICENSE_PARAM, hasLicense.toString())
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = "Failed to get artifacts";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
return response.getEntity(ArtifactList.class);
} | java | public List<Artifact> getArtifacts(final Boolean hasLicense) throws GrapesCommunicationException {
final Client client = getClient();
final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactsPath());
final ClientResponse response = resource.queryParam(ServerAPI.HAS_LICENSE_PARAM, hasLicense.toString())
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = "Failed to get artifacts";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
return response.getEntity(ArtifactList.class);
} | [
"public",
"List",
"<",
"Artifact",
">",
"getArtifacts",
"(",
"final",
"Boolean",
"hasLicense",
")",
"throws",
"GrapesCommunicationException",
"{",
"final",
"Client",
"client",
"=",
"getClient",
"(",
")",
";",
"final",
"WebResource",
"resource",
"=",
"client",
".",
"resource",
"(",
"serverURL",
")",
".",
"path",
"(",
"RequestUtils",
".",
"getArtifactsPath",
"(",
")",
")",
";",
"final",
"ClientResponse",
"response",
"=",
"resource",
".",
"queryParam",
"(",
"ServerAPI",
".",
"HAS_LICENSE_PARAM",
",",
"hasLicense",
".",
"toString",
"(",
")",
")",
".",
"accept",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
".",
"get",
"(",
"ClientResponse",
".",
"class",
")",
";",
"client",
".",
"destroy",
"(",
")",
";",
"if",
"(",
"ClientResponse",
".",
"Status",
".",
"OK",
".",
"getStatusCode",
"(",
")",
"!=",
"response",
".",
"getStatus",
"(",
")",
")",
"{",
"final",
"String",
"message",
"=",
"\"Failed to get artifacts\"",
";",
"if",
"(",
"LOG",
".",
"isErrorEnabled",
"(",
")",
")",
"{",
"LOG",
".",
"error",
"(",
"String",
".",
"format",
"(",
"HTTP_STATUS_TEMPLATE_MSG",
",",
"message",
",",
"response",
".",
"getStatus",
"(",
")",
")",
")",
";",
"}",
"throw",
"new",
"GrapesCommunicationException",
"(",
"message",
",",
"response",
".",
"getStatus",
"(",
")",
")",
";",
"}",
"return",
"response",
".",
"getEntity",
"(",
"ArtifactList",
".",
"class",
")",
";",
"}"
]
| Send a get artifacts request
@param hasLicense
@return list of artifact
@throws GrapesCommunicationException | [
"Send",
"a",
"get",
"artifacts",
"request"
]
| train | https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/utils/src/main/java/org/axway/grapes/utils/client/GrapesClient.java#L486-L502 |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java | WaitPageInterceptor.copyErrors | protected void copyErrors(ActionBeanContext source, ActionBeanContext destination) {
"""
Copy errors from a context to another context.
@param source source containing errors to copy
@param destination where errors will be copied
"""
destination.getValidationErrors().putAll(source.getValidationErrors());
} | java | protected void copyErrors(ActionBeanContext source, ActionBeanContext destination) {
destination.getValidationErrors().putAll(source.getValidationErrors());
} | [
"protected",
"void",
"copyErrors",
"(",
"ActionBeanContext",
"source",
",",
"ActionBeanContext",
"destination",
")",
"{",
"destination",
".",
"getValidationErrors",
"(",
")",
".",
"putAll",
"(",
"source",
".",
"getValidationErrors",
"(",
")",
")",
";",
"}"
]
| Copy errors from a context to another context.
@param source source containing errors to copy
@param destination where errors will be copied | [
"Copy",
"errors",
"from",
"a",
"context",
"to",
"another",
"context",
"."
]
| train | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java#L350-L352 |
Coveros/selenified | src/main/java/com/coveros/selenified/application/WaitFor.java | WaitFor.popupMatches | private double popupMatches(double seconds, String expectedPopupPattern) {
"""
Wait for a popup to have the expected text, and then returns the
amount of time that was waited
@param seconds - maximum amount of time to wait in seconds
@param expectedPopupPattern - the expected pattern to wait for
@return double: the total time waited
"""
double end = System.currentTimeMillis() + (seconds * 1000);
while (!app.get().alert().matches(expectedPopupPattern) && System.currentTimeMillis() < end) ;
return Math.min((seconds * 1000) - (end - System.currentTimeMillis()), seconds * 1000) / 1000;
} | java | private double popupMatches(double seconds, String expectedPopupPattern) {
double end = System.currentTimeMillis() + (seconds * 1000);
while (!app.get().alert().matches(expectedPopupPattern) && System.currentTimeMillis() < end) ;
return Math.min((seconds * 1000) - (end - System.currentTimeMillis()), seconds * 1000) / 1000;
} | [
"private",
"double",
"popupMatches",
"(",
"double",
"seconds",
",",
"String",
"expectedPopupPattern",
")",
"{",
"double",
"end",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"(",
"seconds",
"*",
"1000",
")",
";",
"while",
"(",
"!",
"app",
".",
"get",
"(",
")",
".",
"alert",
"(",
")",
".",
"matches",
"(",
"expectedPopupPattern",
")",
"&&",
"System",
".",
"currentTimeMillis",
"(",
")",
"<",
"end",
")",
";",
"return",
"Math",
".",
"min",
"(",
"(",
"seconds",
"*",
"1000",
")",
"-",
"(",
"end",
"-",
"System",
".",
"currentTimeMillis",
"(",
")",
")",
",",
"seconds",
"*",
"1000",
")",
"/",
"1000",
";",
"}"
]
| Wait for a popup to have the expected text, and then returns the
amount of time that was waited
@param seconds - maximum amount of time to wait in seconds
@param expectedPopupPattern - the expected pattern to wait for
@return double: the total time waited | [
"Wait",
"for",
"a",
"popup",
"to",
"have",
"the",
"expected",
"text",
"and",
"then",
"returns",
"the",
"amount",
"of",
"time",
"that",
"was",
"waited"
]
| train | https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/application/WaitFor.java#L432-L436 |
VueGWT/vue-gwt | processors/src/main/java/com/axellience/vuegwt/processors/component/template/parser/VForDefinition.java | VForDefinition.vForVariable | private boolean vForVariable(String loopVariablesDefinition, TemplateParserContext context) {
"""
v-for on an array with just a loop variable: "Item item in myArray"
@param loopVariablesDefinition The variable definition ("Item item" above)
@param context The context of the parser
@return true if we managed the case, false otherwise
"""
Matcher matcher = VFOR_VARIABLE.matcher(loopVariablesDefinition);
if (matcher.matches()) {
initLoopVariable(matcher.group(1), matcher.group(2), context);
indexVariableInfo = null;
return true;
}
return false;
} | java | private boolean vForVariable(String loopVariablesDefinition, TemplateParserContext context) {
Matcher matcher = VFOR_VARIABLE.matcher(loopVariablesDefinition);
if (matcher.matches()) {
initLoopVariable(matcher.group(1), matcher.group(2), context);
indexVariableInfo = null;
return true;
}
return false;
} | [
"private",
"boolean",
"vForVariable",
"(",
"String",
"loopVariablesDefinition",
",",
"TemplateParserContext",
"context",
")",
"{",
"Matcher",
"matcher",
"=",
"VFOR_VARIABLE",
".",
"matcher",
"(",
"loopVariablesDefinition",
")",
";",
"if",
"(",
"matcher",
".",
"matches",
"(",
")",
")",
"{",
"initLoopVariable",
"(",
"matcher",
".",
"group",
"(",
"1",
")",
",",
"matcher",
".",
"group",
"(",
"2",
")",
",",
"context",
")",
";",
"indexVariableInfo",
"=",
"null",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| v-for on an array with just a loop variable: "Item item in myArray"
@param loopVariablesDefinition The variable definition ("Item item" above)
@param context The context of the parser
@return true if we managed the case, false otherwise | [
"v",
"-",
"for",
"on",
"an",
"array",
"with",
"just",
"a",
"loop",
"variable",
":",
"Item",
"item",
"in",
"myArray"
]
| train | https://github.com/VueGWT/vue-gwt/blob/961cd83aed6fe8e2dd80c279847f1b3f62918a1f/processors/src/main/java/com/axellience/vuegwt/processors/component/template/parser/VForDefinition.java#L80-L89 |
E7du/jfinal-ext3 | src/main/java/com/jfinal/ext/kit/SqlpKit.java | SqlpKit.select | public static SqlPara select(ModelExt<?> model, String... columns) {
"""
make SqlPara use the model with attr datas.
@param model
@columns fetch columns
"""
return SqlpKit.select(model, FLAG.ALL, columns);
} | java | public static SqlPara select(ModelExt<?> model, String... columns) {
return SqlpKit.select(model, FLAG.ALL, columns);
} | [
"public",
"static",
"SqlPara",
"select",
"(",
"ModelExt",
"<",
"?",
">",
"model",
",",
"String",
"...",
"columns",
")",
"{",
"return",
"SqlpKit",
".",
"select",
"(",
"model",
",",
"FLAG",
".",
"ALL",
",",
"columns",
")",
";",
"}"
]
| make SqlPara use the model with attr datas.
@param model
@columns fetch columns | [
"make",
"SqlPara",
"use",
"the",
"model",
"with",
"attr",
"datas",
"."
]
| train | https://github.com/E7du/jfinal-ext3/blob/8ffcbd150fd50c72852bb778bd427b5eb19254dc/src/main/java/com/jfinal/ext/kit/SqlpKit.java#L107-L109 |
alkacon/opencms-core | src/org/opencms/importexport/A_CmsImport.java | A_CmsImport.importAccessControlEntries | protected void importAccessControlEntries(CmsResource resource, List<CmsAccessControlEntry> aceList) {
"""
Writes already imported access control entries for a given resource.<p>
@param resource the resource assigned to the access control entries
@param aceList the access control entries to create
"""
if (aceList.size() == 0) {
// no ACE in the list
return;
}
try {
m_cms.importAccessControlEntries(resource, aceList);
} catch (CmsException exc) {
m_report.println(
Messages.get().container(Messages.RPT_IMPORT_ACL_DATA_FAILED_0),
I_CmsReport.FORMAT_WARNING);
}
} | java | protected void importAccessControlEntries(CmsResource resource, List<CmsAccessControlEntry> aceList) {
if (aceList.size() == 0) {
// no ACE in the list
return;
}
try {
m_cms.importAccessControlEntries(resource, aceList);
} catch (CmsException exc) {
m_report.println(
Messages.get().container(Messages.RPT_IMPORT_ACL_DATA_FAILED_0),
I_CmsReport.FORMAT_WARNING);
}
} | [
"protected",
"void",
"importAccessControlEntries",
"(",
"CmsResource",
"resource",
",",
"List",
"<",
"CmsAccessControlEntry",
">",
"aceList",
")",
"{",
"if",
"(",
"aceList",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"// no ACE in the list",
"return",
";",
"}",
"try",
"{",
"m_cms",
".",
"importAccessControlEntries",
"(",
"resource",
",",
"aceList",
")",
";",
"}",
"catch",
"(",
"CmsException",
"exc",
")",
"{",
"m_report",
".",
"println",
"(",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"Messages",
".",
"RPT_IMPORT_ACL_DATA_FAILED_0",
")",
",",
"I_CmsReport",
".",
"FORMAT_WARNING",
")",
";",
"}",
"}"
]
| Writes already imported access control entries for a given resource.<p>
@param resource the resource assigned to the access control entries
@param aceList the access control entries to create | [
"Writes",
"already",
"imported",
"access",
"control",
"entries",
"for",
"a",
"given",
"resource",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/A_CmsImport.java#L647-L660 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/misc/ProfileOperation.java | ProfileOperation.profile | public static void profile( Performer performer , int num ) {
"""
See how long it takes to run the process 'num' times and print the results
to standard out
"""
long deltaTime = measureTime(performer,num);
System.out.printf("%30s time = %8d ms per frame = %8.3f\n",
performer.getName(),deltaTime,(deltaTime/(double)num));
// System.out.println(performer.getClass().getSimpleName()+
// " time = "+deltaTime+" ms per frame "+(deltaTime/(double)num));
} | java | public static void profile( Performer performer , int num ) {
long deltaTime = measureTime(performer,num);
System.out.printf("%30s time = %8d ms per frame = %8.3f\n",
performer.getName(),deltaTime,(deltaTime/(double)num));
// System.out.println(performer.getClass().getSimpleName()+
// " time = "+deltaTime+" ms per frame "+(deltaTime/(double)num));
} | [
"public",
"static",
"void",
"profile",
"(",
"Performer",
"performer",
",",
"int",
"num",
")",
"{",
"long",
"deltaTime",
"=",
"measureTime",
"(",
"performer",
",",
"num",
")",
";",
"System",
".",
"out",
".",
"printf",
"(",
"\"%30s time = %8d ms per frame = %8.3f\\n\"",
",",
"performer",
".",
"getName",
"(",
")",
",",
"deltaTime",
",",
"(",
"deltaTime",
"/",
"(",
"double",
")",
"num",
")",
")",
";",
"// System.out.println(performer.getClass().getSimpleName()+",
"// \" time = \"+deltaTime+\" ms per frame \"+(deltaTime/(double)num));",
"}"
]
| See how long it takes to run the process 'num' times and print the results
to standard out | [
"See",
"how",
"long",
"it",
"takes",
"to",
"run",
"the",
"process",
"num",
"times",
"and",
"print",
"the",
"results",
"to",
"standard",
"out"
]
| train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/misc/ProfileOperation.java#L31-L39 |
weld/core | impl/src/main/java/org/jboss/weld/util/Interceptors.java | Interceptors.mergeBeanInterceptorBindings | public static Multimap<Class<? extends Annotation>, Annotation> mergeBeanInterceptorBindings(BeanManagerImpl beanManager, EnhancedAnnotatedType<?> clazz, Collection<Class<? extends Annotation>> stereotypes) {
"""
Merge class-level interceptor bindings with interceptor bindings inherited from interceptor bindings and stereotypes.
"""
Set<Annotation> rawBindings = clazz.getMetaAnnotations(InterceptorBinding.class);
Set<Annotation> classBindingAnnotations = flattenInterceptorBindings(clazz, beanManager, filterInterceptorBindings(beanManager, rawBindings), true, false);
Set<Annotation> inheritedBindingAnnotations = new HashSet<Annotation>();
inheritedBindingAnnotations.addAll(flattenInterceptorBindings(clazz, beanManager, filterInterceptorBindings(beanManager, rawBindings), false, true));
for (Class<? extends Annotation> annotation : stereotypes) {
inheritedBindingAnnotations.addAll(flattenInterceptorBindings(clazz, beanManager, filterInterceptorBindings(beanManager, beanManager.getStereotypeDefinition(annotation)), true, true));
}
try {
return mergeBeanInterceptorBindings(beanManager, clazz, classBindingAnnotations, inheritedBindingAnnotations);
} catch (DeploymentException e) {
throw new DefinitionException(BeanLogger.LOG.conflictingInterceptorBindings(clazz.getJavaClass()));
}
} | java | public static Multimap<Class<? extends Annotation>, Annotation> mergeBeanInterceptorBindings(BeanManagerImpl beanManager, EnhancedAnnotatedType<?> clazz, Collection<Class<? extends Annotation>> stereotypes) {
Set<Annotation> rawBindings = clazz.getMetaAnnotations(InterceptorBinding.class);
Set<Annotation> classBindingAnnotations = flattenInterceptorBindings(clazz, beanManager, filterInterceptorBindings(beanManager, rawBindings), true, false);
Set<Annotation> inheritedBindingAnnotations = new HashSet<Annotation>();
inheritedBindingAnnotations.addAll(flattenInterceptorBindings(clazz, beanManager, filterInterceptorBindings(beanManager, rawBindings), false, true));
for (Class<? extends Annotation> annotation : stereotypes) {
inheritedBindingAnnotations.addAll(flattenInterceptorBindings(clazz, beanManager, filterInterceptorBindings(beanManager, beanManager.getStereotypeDefinition(annotation)), true, true));
}
try {
return mergeBeanInterceptorBindings(beanManager, clazz, classBindingAnnotations, inheritedBindingAnnotations);
} catch (DeploymentException e) {
throw new DefinitionException(BeanLogger.LOG.conflictingInterceptorBindings(clazz.getJavaClass()));
}
} | [
"public",
"static",
"Multimap",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
",",
"Annotation",
">",
"mergeBeanInterceptorBindings",
"(",
"BeanManagerImpl",
"beanManager",
",",
"EnhancedAnnotatedType",
"<",
"?",
">",
"clazz",
",",
"Collection",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
">",
"stereotypes",
")",
"{",
"Set",
"<",
"Annotation",
">",
"rawBindings",
"=",
"clazz",
".",
"getMetaAnnotations",
"(",
"InterceptorBinding",
".",
"class",
")",
";",
"Set",
"<",
"Annotation",
">",
"classBindingAnnotations",
"=",
"flattenInterceptorBindings",
"(",
"clazz",
",",
"beanManager",
",",
"filterInterceptorBindings",
"(",
"beanManager",
",",
"rawBindings",
")",
",",
"true",
",",
"false",
")",
";",
"Set",
"<",
"Annotation",
">",
"inheritedBindingAnnotations",
"=",
"new",
"HashSet",
"<",
"Annotation",
">",
"(",
")",
";",
"inheritedBindingAnnotations",
".",
"addAll",
"(",
"flattenInterceptorBindings",
"(",
"clazz",
",",
"beanManager",
",",
"filterInterceptorBindings",
"(",
"beanManager",
",",
"rawBindings",
")",
",",
"false",
",",
"true",
")",
")",
";",
"for",
"(",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotation",
":",
"stereotypes",
")",
"{",
"inheritedBindingAnnotations",
".",
"addAll",
"(",
"flattenInterceptorBindings",
"(",
"clazz",
",",
"beanManager",
",",
"filterInterceptorBindings",
"(",
"beanManager",
",",
"beanManager",
".",
"getStereotypeDefinition",
"(",
"annotation",
")",
")",
",",
"true",
",",
"true",
")",
")",
";",
"}",
"try",
"{",
"return",
"mergeBeanInterceptorBindings",
"(",
"beanManager",
",",
"clazz",
",",
"classBindingAnnotations",
",",
"inheritedBindingAnnotations",
")",
";",
"}",
"catch",
"(",
"DeploymentException",
"e",
")",
"{",
"throw",
"new",
"DefinitionException",
"(",
"BeanLogger",
".",
"LOG",
".",
"conflictingInterceptorBindings",
"(",
"clazz",
".",
"getJavaClass",
"(",
")",
")",
")",
";",
"}",
"}"
]
| Merge class-level interceptor bindings with interceptor bindings inherited from interceptor bindings and stereotypes. | [
"Merge",
"class",
"-",
"level",
"interceptor",
"bindings",
"with",
"interceptor",
"bindings",
"inherited",
"from",
"interceptor",
"bindings",
"and",
"stereotypes",
"."
]
| train | https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/impl/src/main/java/org/jboss/weld/util/Interceptors.java#L119-L132 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/property/CmsPropertySubmitHandler.java | CmsPropertySubmitHandler.getPropertyChanges | protected List<CmsPropertyModification> getPropertyChanges(Map<String, String> fieldValues) {
"""
Converts a map of field values to a list of property changes.<p>
@param fieldValues the field values
@return the property changes
"""
List<CmsPropertyModification> result = new ArrayList<CmsPropertyModification>();
for (Map.Entry<String, String> entry : fieldValues.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key.contains("/")) {
CmsPropertyModification propChange = new CmsPropertyModification(key, value);
result.add(propChange);
}
}
return result;
} | java | protected List<CmsPropertyModification> getPropertyChanges(Map<String, String> fieldValues) {
List<CmsPropertyModification> result = new ArrayList<CmsPropertyModification>();
for (Map.Entry<String, String> entry : fieldValues.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key.contains("/")) {
CmsPropertyModification propChange = new CmsPropertyModification(key, value);
result.add(propChange);
}
}
return result;
} | [
"protected",
"List",
"<",
"CmsPropertyModification",
">",
"getPropertyChanges",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"fieldValues",
")",
"{",
"List",
"<",
"CmsPropertyModification",
">",
"result",
"=",
"new",
"ArrayList",
"<",
"CmsPropertyModification",
">",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"entry",
":",
"fieldValues",
".",
"entrySet",
"(",
")",
")",
"{",
"String",
"key",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"String",
"value",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"key",
".",
"contains",
"(",
"\"/\"",
")",
")",
"{",
"CmsPropertyModification",
"propChange",
"=",
"new",
"CmsPropertyModification",
"(",
"key",
",",
"value",
")",
";",
"result",
".",
"add",
"(",
"propChange",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
]
| Converts a map of field values to a list of property changes.<p>
@param fieldValues the field values
@return the property changes | [
"Converts",
"a",
"map",
"of",
"field",
"values",
"to",
"a",
"list",
"of",
"property",
"changes",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/property/CmsPropertySubmitHandler.java#L114-L126 |
wcm-io/wcm-io-handler | commons/src/main/java/io/wcm/handler/commons/dom/AbstractHtmlElementFactory.java | AbstractHtmlElementFactory.createImage | public Image createImage(String src, String alt) {
"""
Creates and adds imgage (img) element.
@param src Html "src" attribute.
@param alt Html "alt" attribute.
@return Html element.
"""
return this.add(new Image(src, alt));
} | java | public Image createImage(String src, String alt) {
return this.add(new Image(src, alt));
} | [
"public",
"Image",
"createImage",
"(",
"String",
"src",
",",
"String",
"alt",
")",
"{",
"return",
"this",
".",
"add",
"(",
"new",
"Image",
"(",
"src",
",",
"alt",
")",
")",
";",
"}"
]
| Creates and adds imgage (img) element.
@param src Html "src" attribute.
@param alt Html "alt" attribute.
@return Html element. | [
"Creates",
"and",
"adds",
"imgage",
"(",
"img",
")",
"element",
"."
]
| train | https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/commons/src/main/java/io/wcm/handler/commons/dom/AbstractHtmlElementFactory.java#L137-L139 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/NotesApi.java | NotesApi.createIssueNote | public Note createIssueNote(Object projectIdOrPath, Integer issueIid, String body, Date createdAt) throws GitLabApiException {
"""
Create a issues's note.
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param issueIid the issue IID to create the notes for
@param body the content of note
@param createdAt the created time of note
@return the created Note instance
@throws GitLabApiException if any exception occurs
"""
GitLabApiForm formData = new GitLabApiForm()
.withParam("body", body, true)
.withParam("created_at", createdAt);
Response response = post(Response.Status.CREATED, formData,
"projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "notes");
return (response.readEntity(Note.class));
} | java | public Note createIssueNote(Object projectIdOrPath, Integer issueIid, String body, Date createdAt) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("body", body, true)
.withParam("created_at", createdAt);
Response response = post(Response.Status.CREATED, formData,
"projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "notes");
return (response.readEntity(Note.class));
} | [
"public",
"Note",
"createIssueNote",
"(",
"Object",
"projectIdOrPath",
",",
"Integer",
"issueIid",
",",
"String",
"body",
",",
"Date",
"createdAt",
")",
"throws",
"GitLabApiException",
"{",
"GitLabApiForm",
"formData",
"=",
"new",
"GitLabApiForm",
"(",
")",
".",
"withParam",
"(",
"\"body\"",
",",
"body",
",",
"true",
")",
".",
"withParam",
"(",
"\"created_at\"",
",",
"createdAt",
")",
";",
"Response",
"response",
"=",
"post",
"(",
"Response",
".",
"Status",
".",
"CREATED",
",",
"formData",
",",
"\"projects\"",
",",
"getProjectIdOrPath",
"(",
"projectIdOrPath",
")",
",",
"\"issues\"",
",",
"issueIid",
",",
"\"notes\"",
")",
";",
"return",
"(",
"response",
".",
"readEntity",
"(",
"Note",
".",
"class",
")",
")",
";",
"}"
]
| Create a issues's note.
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param issueIid the issue IID to create the notes for
@param body the content of note
@param createdAt the created time of note
@return the created Note instance
@throws GitLabApiException if any exception occurs | [
"Create",
"a",
"issues",
"s",
"note",
"."
]
| train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/NotesApi.java#L168-L176 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/misc/PixelMath.java | PixelMath.diffAbs | public static void diffAbs( GrayU8 imgA , GrayU8 imgB , GrayU8 output ) {
"""
<p>
Computes the absolute value of the difference between each pixel in the two images.<br>
d(x,y) = |img1(x,y) - img2(x,y)|
</p>
@param imgA Input image. Not modified.
@param imgB Input image. Not modified.
@param output Absolute value of difference image. Can be either input. Modified.
"""
InputSanityCheck.checkSameShape(imgA,imgB);
output.reshape(imgA.width,imgA.height);
if( BoofConcurrency.USE_CONCURRENT ) {
ImplPixelMath_MT.diffAbs(imgA, imgB, output);
} else {
ImplPixelMath.diffAbs(imgA, imgB, output);
}
} | java | public static void diffAbs( GrayU8 imgA , GrayU8 imgB , GrayU8 output ) {
InputSanityCheck.checkSameShape(imgA,imgB);
output.reshape(imgA.width,imgA.height);
if( BoofConcurrency.USE_CONCURRENT ) {
ImplPixelMath_MT.diffAbs(imgA, imgB, output);
} else {
ImplPixelMath.diffAbs(imgA, imgB, output);
}
} | [
"public",
"static",
"void",
"diffAbs",
"(",
"GrayU8",
"imgA",
",",
"GrayU8",
"imgB",
",",
"GrayU8",
"output",
")",
"{",
"InputSanityCheck",
".",
"checkSameShape",
"(",
"imgA",
",",
"imgB",
")",
";",
"output",
".",
"reshape",
"(",
"imgA",
".",
"width",
",",
"imgA",
".",
"height",
")",
";",
"if",
"(",
"BoofConcurrency",
".",
"USE_CONCURRENT",
")",
"{",
"ImplPixelMath_MT",
".",
"diffAbs",
"(",
"imgA",
",",
"imgB",
",",
"output",
")",
";",
"}",
"else",
"{",
"ImplPixelMath",
".",
"diffAbs",
"(",
"imgA",
",",
"imgB",
",",
"output",
")",
";",
"}",
"}"
]
| <p>
Computes the absolute value of the difference between each pixel in the two images.<br>
d(x,y) = |img1(x,y) - img2(x,y)|
</p>
@param imgA Input image. Not modified.
@param imgB Input image. Not modified.
@param output Absolute value of difference image. Can be either input. Modified. | [
"<p",
">",
"Computes",
"the",
"absolute",
"value",
"of",
"the",
"difference",
"between",
"each",
"pixel",
"in",
"the",
"two",
"images",
".",
"<br",
">",
"d",
"(",
"x",
"y",
")",
"=",
"|img1",
"(",
"x",
"y",
")",
"-",
"img2",
"(",
"x",
"y",
")",
"|",
"<",
"/",
"p",
">"
]
| train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/misc/PixelMath.java#L4311-L4320 |
TheHortonMachine/hortonmachine | dbs/src/main/java/org/hortonmachine/dbs/utils/SerializationUtilities.java | SerializationUtilities.serializeToDisk | public static void serializeToDisk( File file, Object obj ) throws IOException {
"""
Serialize an object to disk.
@param file
the file to write to.
@param obj
the object to write.
@throws IOException
"""
byte[] serializedObj = serialize(obj);
try (RandomAccessFile raFile = new RandomAccessFile(file, "rw")) {
raFile.write(serializedObj);
}
} | java | public static void serializeToDisk( File file, Object obj ) throws IOException {
byte[] serializedObj = serialize(obj);
try (RandomAccessFile raFile = new RandomAccessFile(file, "rw")) {
raFile.write(serializedObj);
}
} | [
"public",
"static",
"void",
"serializeToDisk",
"(",
"File",
"file",
",",
"Object",
"obj",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"serializedObj",
"=",
"serialize",
"(",
"obj",
")",
";",
"try",
"(",
"RandomAccessFile",
"raFile",
"=",
"new",
"RandomAccessFile",
"(",
"file",
",",
"\"rw\"",
")",
")",
"{",
"raFile",
".",
"write",
"(",
"serializedObj",
")",
";",
"}",
"}"
]
| Serialize an object to disk.
@param file
the file to write to.
@param obj
the object to write.
@throws IOException | [
"Serialize",
"an",
"object",
"to",
"disk",
"."
]
| train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/org/hortonmachine/dbs/utils/SerializationUtilities.java#L58-L63 |
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.listEntities | public List<EntityExtractor> listEntities(UUID appId, String versionId, ListEntitiesOptionalParameter listEntitiesOptionalParameter) {
"""
Gets information about the entity models.
@param appId The application ID.
@param versionId The version ID.
@param listEntitiesOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the List<EntityExtractor> object if successful.
"""
return listEntitiesWithServiceResponseAsync(appId, versionId, listEntitiesOptionalParameter).toBlocking().single().body();
} | java | public List<EntityExtractor> listEntities(UUID appId, String versionId, ListEntitiesOptionalParameter listEntitiesOptionalParameter) {
return listEntitiesWithServiceResponseAsync(appId, versionId, listEntitiesOptionalParameter).toBlocking().single().body();
} | [
"public",
"List",
"<",
"EntityExtractor",
">",
"listEntities",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"ListEntitiesOptionalParameter",
"listEntitiesOptionalParameter",
")",
"{",
"return",
"listEntitiesWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"listEntitiesOptionalParameter",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
]
| Gets information about the entity models.
@param appId The application ID.
@param versionId The version ID.
@param listEntitiesOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the List<EntityExtractor> object if successful. | [
"Gets",
"information",
"about",
"the",
"entity",
"models",
"."
]
| 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#L1103-L1105 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/httpsessions/HttpSessionsSite.java | HttpSessionsSite.createEmptySessionAndSetAsActive | private void createEmptySessionAndSetAsActive(final String name) {
"""
Creates an empty session with the given {@code name} and sets it as the active session.
<p>
<strong>Note:</strong> It's responsibility of the caller to ensure that no session with the
given {@code name} already exists.
@param name the name of the session that will be created and set as the active session
@throws IllegalArgumentException if the {@code name} is {@code null} or an empty string
@see #addHttpSession(HttpSession)
@see #setActiveSession(HttpSession)
@see #isSessionNameUnique(String)
"""
validateSessionName(name);
final HttpSession session = new HttpSession(name, extension.getHttpSessionTokensSet(getSite()));
addHttpSession(session);
setActiveSession(session);
} | java | private void createEmptySessionAndSetAsActive(final String name) {
validateSessionName(name);
final HttpSession session = new HttpSession(name, extension.getHttpSessionTokensSet(getSite()));
addHttpSession(session);
setActiveSession(session);
} | [
"private",
"void",
"createEmptySessionAndSetAsActive",
"(",
"final",
"String",
"name",
")",
"{",
"validateSessionName",
"(",
"name",
")",
";",
"final",
"HttpSession",
"session",
"=",
"new",
"HttpSession",
"(",
"name",
",",
"extension",
".",
"getHttpSessionTokensSet",
"(",
"getSite",
"(",
")",
")",
")",
";",
"addHttpSession",
"(",
"session",
")",
";",
"setActiveSession",
"(",
"session",
")",
";",
"}"
]
| Creates an empty session with the given {@code name} and sets it as the active session.
<p>
<strong>Note:</strong> It's responsibility of the caller to ensure that no session with the
given {@code name} already exists.
@param name the name of the session that will be created and set as the active session
@throws IllegalArgumentException if the {@code name} is {@code null} or an empty string
@see #addHttpSession(HttpSession)
@see #setActiveSession(HttpSession)
@see #isSessionNameUnique(String) | [
"Creates",
"an",
"empty",
"session",
"with",
"the",
"given",
"{",
"@code",
"name",
"}",
"and",
"sets",
"it",
"as",
"the",
"active",
"session",
".",
"<p",
">",
"<strong",
">",
"Note",
":",
"<",
"/",
"strong",
">",
"It",
"s",
"responsibility",
"of",
"the",
"caller",
"to",
"ensure",
"that",
"no",
"session",
"with",
"the",
"given",
"{",
"@code",
"name",
"}",
"already",
"exists",
"."
]
| train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/httpsessions/HttpSessionsSite.java#L278-L284 |
BlueBrain/bluima | modules/bluima_pdf/src/main/java/ch/epfl/bbp/uima/pdf/grobid/diff_match_patch.java | diff_match_patch.patch_make | public LinkedList<Patch> patch_make(String text1, String text2) {
"""
Compute a list of patches to turn text1 into text2. A set of diffs will
be computed.
@param text1
Old text.
@param text2
New text.
@return LinkedList of Patch objects.
"""
if (text1 == null || text2 == null) {
throw new IllegalArgumentException("Null inputs. (patch_make)");
}
// No diffs provided, compute our own.
LinkedList<Diff> diffs = diff_main(text1, text2, true);
if (diffs.size() > 2) {
diff_cleanupSemantic(diffs);
diff_cleanupEfficiency(diffs);
}
return patch_make(text1, diffs);
} | java | public LinkedList<Patch> patch_make(String text1, String text2) {
if (text1 == null || text2 == null) {
throw new IllegalArgumentException("Null inputs. (patch_make)");
}
// No diffs provided, compute our own.
LinkedList<Diff> diffs = diff_main(text1, text2, true);
if (diffs.size() > 2) {
diff_cleanupSemantic(diffs);
diff_cleanupEfficiency(diffs);
}
return patch_make(text1, diffs);
} | [
"public",
"LinkedList",
"<",
"Patch",
">",
"patch_make",
"(",
"String",
"text1",
",",
"String",
"text2",
")",
"{",
"if",
"(",
"text1",
"==",
"null",
"||",
"text2",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Null inputs. (patch_make)\"",
")",
";",
"}",
"// No diffs provided, compute our own.",
"LinkedList",
"<",
"Diff",
">",
"diffs",
"=",
"diff_main",
"(",
"text1",
",",
"text2",
",",
"true",
")",
";",
"if",
"(",
"diffs",
".",
"size",
"(",
")",
">",
"2",
")",
"{",
"diff_cleanupSemantic",
"(",
"diffs",
")",
";",
"diff_cleanupEfficiency",
"(",
"diffs",
")",
";",
"}",
"return",
"patch_make",
"(",
"text1",
",",
"diffs",
")",
";",
"}"
]
| Compute a list of patches to turn text1 into text2. A set of diffs will
be computed.
@param text1
Old text.
@param text2
New text.
@return LinkedList of Patch objects. | [
"Compute",
"a",
"list",
"of",
"patches",
"to",
"turn",
"text1",
"into",
"text2",
".",
"A",
"set",
"of",
"diffs",
"will",
"be",
"computed",
"."
]
| train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_pdf/src/main/java/ch/epfl/bbp/uima/pdf/grobid/diff_match_patch.java#L1932-L1943 |
spring-projects/spring-boot | spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java | InfoPropertiesInfoContributor.copyIfSet | protected void copyIfSet(Properties target, String key) {
"""
Copy the specified key to the target {@link Properties} if it is set.
@param target the target properties to update
@param key the key
"""
String value = this.properties.get(key);
if (StringUtils.hasText(value)) {
target.put(key, value);
}
} | java | protected void copyIfSet(Properties target, String key) {
String value = this.properties.get(key);
if (StringUtils.hasText(value)) {
target.put(key, value);
}
} | [
"protected",
"void",
"copyIfSet",
"(",
"Properties",
"target",
",",
"String",
"key",
")",
"{",
"String",
"value",
"=",
"this",
".",
"properties",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"StringUtils",
".",
"hasText",
"(",
"value",
")",
")",
"{",
"target",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}",
"}"
]
| Copy the specified key to the target {@link Properties} if it is set.
@param target the target properties to update
@param key the key | [
"Copy",
"the",
"specified",
"key",
"to",
"the",
"target",
"{"
]
| train | https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java#L123-L128 |
pravega/pravega | common/src/main/java/io/pravega/common/LoggerHelpers.java | LoggerHelpers.exceptionSummary | public static Object exceptionSummary(Logger log, Throwable e) {
"""
Returns either the given {@link Throwable} or its message, depending on the current logging context.
@param log The {@link Logger} to query.
@param e The {@link Throwable} to return or process.
@return The given {@link Throwable}, if {@link Logger#isDebugEnabled()} is true for log, or {@link Throwable#toString()}
otherwise (which should output only the name of the exception).
"""
if (log.isDebugEnabled()) {
return e;
} else {
return e.toString();
}
} | java | public static Object exceptionSummary(Logger log, Throwable e) {
if (log.isDebugEnabled()) {
return e;
} else {
return e.toString();
}
} | [
"public",
"static",
"Object",
"exceptionSummary",
"(",
"Logger",
"log",
",",
"Throwable",
"e",
")",
"{",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"return",
"e",
";",
"}",
"else",
"{",
"return",
"e",
".",
"toString",
"(",
")",
";",
"}",
"}"
]
| Returns either the given {@link Throwable} or its message, depending on the current logging context.
@param log The {@link Logger} to query.
@param e The {@link Throwable} to return or process.
@return The given {@link Throwable}, if {@link Logger#isDebugEnabled()} is true for log, or {@link Throwable#toString()}
otherwise (which should output only the name of the exception). | [
"Returns",
"either",
"the",
"given",
"{",
"@link",
"Throwable",
"}",
"or",
"its",
"message",
"depending",
"on",
"the",
"current",
"logging",
"context",
"."
]
| train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/LoggerHelpers.java#L122-L128 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheUnitImpl.java | CacheUnitImpl.setEntry | public void setEntry(String cacheName, CacheEntry cacheEntry) {
"""
This implements the method in the CacheUnit interface.
This is called by DRSNotificationService and DRSMessageListener.
@param cacheName The cache name
@param cacheEntry The entry to be set.
"""
if (tc.isEntryEnabled())
Tr.entry(tc, "setEntry: {0}", cacheEntry.id);
cacheEntry = invalidationAuditDaemon.filterEntry(cacheName, cacheEntry);
if (cacheEntry != null) {
DCache cache = ServerCache.getCache(cacheName);
cache.setEntry(cacheEntry,CachePerf.REMOTE);
}
if (tc.isEntryEnabled())
Tr.exit(tc, "setEntry: {0}", cacheEntry==null?"null":cacheEntry.id );
} | java | public void setEntry(String cacheName, CacheEntry cacheEntry) {
if (tc.isEntryEnabled())
Tr.entry(tc, "setEntry: {0}", cacheEntry.id);
cacheEntry = invalidationAuditDaemon.filterEntry(cacheName, cacheEntry);
if (cacheEntry != null) {
DCache cache = ServerCache.getCache(cacheName);
cache.setEntry(cacheEntry,CachePerf.REMOTE);
}
if (tc.isEntryEnabled())
Tr.exit(tc, "setEntry: {0}", cacheEntry==null?"null":cacheEntry.id );
} | [
"public",
"void",
"setEntry",
"(",
"String",
"cacheName",
",",
"CacheEntry",
"cacheEntry",
")",
"{",
"if",
"(",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"entry",
"(",
"tc",
",",
"\"setEntry: {0}\"",
",",
"cacheEntry",
".",
"id",
")",
";",
"cacheEntry",
"=",
"invalidationAuditDaemon",
".",
"filterEntry",
"(",
"cacheName",
",",
"cacheEntry",
")",
";",
"if",
"(",
"cacheEntry",
"!=",
"null",
")",
"{",
"DCache",
"cache",
"=",
"ServerCache",
".",
"getCache",
"(",
"cacheName",
")",
";",
"cache",
".",
"setEntry",
"(",
"cacheEntry",
",",
"CachePerf",
".",
"REMOTE",
")",
";",
"}",
"if",
"(",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"exit",
"(",
"tc",
",",
"\"setEntry: {0}\"",
",",
"cacheEntry",
"==",
"null",
"?",
"\"null\"",
":",
"cacheEntry",
".",
"id",
")",
";",
"}"
]
| This implements the method in the CacheUnit interface.
This is called by DRSNotificationService and DRSMessageListener.
@param cacheName The cache name
@param cacheEntry The entry to be set. | [
"This",
"implements",
"the",
"method",
"in",
"the",
"CacheUnit",
"interface",
".",
"This",
"is",
"called",
"by",
"DRSNotificationService",
"and",
"DRSMessageListener",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheUnitImpl.java#L175-L186 |
aws/aws-sdk-java | aws-java-sdk-discovery/src/main/java/com/amazonaws/services/applicationdiscovery/model/ContinuousExportDescription.java | ContinuousExportDescription.withSchemaStorageConfig | public ContinuousExportDescription withSchemaStorageConfig(java.util.Map<String, String> schemaStorageConfig) {
"""
<p>
An object which describes how the data is stored.
</p>
<ul>
<li>
<p>
<code>databaseName</code> - the name of the Glue database used to store the schema.
</p>
</li>
</ul>
@param schemaStorageConfig
An object which describes how the data is stored.</p>
<ul>
<li>
<p>
<code>databaseName</code> - the name of the Glue database used to store the schema.
</p>
</li>
@return Returns a reference to this object so that method calls can be chained together.
"""
setSchemaStorageConfig(schemaStorageConfig);
return this;
} | java | public ContinuousExportDescription withSchemaStorageConfig(java.util.Map<String, String> schemaStorageConfig) {
setSchemaStorageConfig(schemaStorageConfig);
return this;
} | [
"public",
"ContinuousExportDescription",
"withSchemaStorageConfig",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"schemaStorageConfig",
")",
"{",
"setSchemaStorageConfig",
"(",
"schemaStorageConfig",
")",
";",
"return",
"this",
";",
"}"
]
| <p>
An object which describes how the data is stored.
</p>
<ul>
<li>
<p>
<code>databaseName</code> - the name of the Glue database used to store the schema.
</p>
</li>
</ul>
@param schemaStorageConfig
An object which describes how the data is stored.</p>
<ul>
<li>
<p>
<code>databaseName</code> - the name of the Glue database used to store the schema.
</p>
</li>
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"An",
"object",
"which",
"describes",
"how",
"the",
"data",
"is",
"stored",
".",
"<",
"/",
"p",
">",
"<ul",
">",
"<li",
">",
"<p",
">",
"<code",
">",
"databaseName<",
"/",
"code",
">",
"-",
"the",
"name",
"of",
"the",
"Glue",
"database",
"used",
"to",
"store",
"the",
"schema",
".",
"<",
"/",
"p",
">",
"<",
"/",
"li",
">",
"<",
"/",
"ul",
">"
]
| train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-discovery/src/main/java/com/amazonaws/services/applicationdiscovery/model/ContinuousExportDescription.java#L1207-L1210 |
gallandarakhneorg/afc | core/maths/mathgraph/src/main/java/org/arakhne/afc/math/graph/GraphPath.java | GraphPath.removeAfterLast | public boolean removeAfterLast(ST obj, PT pt) {
"""
Remove the path's elements after the
specified one which is starting
at the specified point. The specified element will
not be removed.
<p>This function removes after the <i>last occurence</i>
of the given object.
@param obj is the segment to remove
@param pt is the point on which the segment was connected
as its first point.
@return <code>true</code> on success, otherwise <code>false</code>
"""
return removeAfter(lastIndexOf(obj, pt), false);
} | java | public boolean removeAfterLast(ST obj, PT pt) {
return removeAfter(lastIndexOf(obj, pt), false);
} | [
"public",
"boolean",
"removeAfterLast",
"(",
"ST",
"obj",
",",
"PT",
"pt",
")",
"{",
"return",
"removeAfter",
"(",
"lastIndexOf",
"(",
"obj",
",",
"pt",
")",
",",
"false",
")",
";",
"}"
]
| Remove the path's elements after the
specified one which is starting
at the specified point. The specified element will
not be removed.
<p>This function removes after the <i>last occurence</i>
of the given object.
@param obj is the segment to remove
@param pt is the point on which the segment was connected
as its first point.
@return <code>true</code> on success, otherwise <code>false</code> | [
"Remove",
"the",
"path",
"s",
"elements",
"after",
"the",
"specified",
"one",
"which",
"is",
"starting",
"at",
"the",
"specified",
"point",
".",
"The",
"specified",
"element",
"will",
"not",
"be",
"removed",
"."
]
| train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgraph/src/main/java/org/arakhne/afc/math/graph/GraphPath.java#L823-L825 |
sebastiangraf/jSCSI | bundles/commons/src/main/java/org/jscsi/parser/ProtocolDataUnit.java | ProtocolDataUnit.serializeAdditionalHeaderSegments | private final int serializeAdditionalHeaderSegments (final ByteBuffer dst, final int offset) throws InternetSCSIException {
"""
Serialize all the contained additional header segments to the destination array starting from the given offset.
@param dst The destination array to write in.
@param offset The offset to start to write in <code>dst</code>.
@return The written length.
@throws InternetSCSIException If any violation of the iSCSI-Standard emerge.
"""
int off = offset;
for (AdditionalHeaderSegment ahs : additionalHeaderSegments) {
off += ahs.serialize(dst, off);
}
return off - offset;
} | java | private final int serializeAdditionalHeaderSegments (final ByteBuffer dst, final int offset) throws InternetSCSIException {
int off = offset;
for (AdditionalHeaderSegment ahs : additionalHeaderSegments) {
off += ahs.serialize(dst, off);
}
return off - offset;
} | [
"private",
"final",
"int",
"serializeAdditionalHeaderSegments",
"(",
"final",
"ByteBuffer",
"dst",
",",
"final",
"int",
"offset",
")",
"throws",
"InternetSCSIException",
"{",
"int",
"off",
"=",
"offset",
";",
"for",
"(",
"AdditionalHeaderSegment",
"ahs",
":",
"additionalHeaderSegments",
")",
"{",
"off",
"+=",
"ahs",
".",
"serialize",
"(",
"dst",
",",
"off",
")",
";",
"}",
"return",
"off",
"-",
"offset",
";",
"}"
]
| Serialize all the contained additional header segments to the destination array starting from the given offset.
@param dst The destination array to write in.
@param offset The offset to start to write in <code>dst</code>.
@return The written length.
@throws InternetSCSIException If any violation of the iSCSI-Standard emerge. | [
"Serialize",
"all",
"the",
"contained",
"additional",
"header",
"segments",
"to",
"the",
"destination",
"array",
"starting",
"from",
"the",
"given",
"offset",
"."
]
| train | https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/commons/src/main/java/org/jscsi/parser/ProtocolDataUnit.java#L250-L258 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ReflectUtil.java | ReflectUtil.invoke | @SuppressWarnings("unchecked")
public static <T> T invoke(Object obj, Method method, Object... args) throws UtilException {
"""
执行方法
@param <T> 返回对象类型
@param obj 对象,如果执行静态方法,此值为<code>null</code>
@param method 方法(对象方法或static方法都可)
@param args 参数对象
@return 结果
@throws UtilException 一些列异常的包装
"""
if (false == method.isAccessible()) {
method.setAccessible(true);
}
try {
return (T) method.invoke(ClassUtil.isStatic(method) ? null : obj, args);
} catch (Exception e) {
throw new UtilException(e);
}
} | java | @SuppressWarnings("unchecked")
public static <T> T invoke(Object obj, Method method, Object... args) throws UtilException {
if (false == method.isAccessible()) {
method.setAccessible(true);
}
try {
return (T) method.invoke(ClassUtil.isStatic(method) ? null : obj, args);
} catch (Exception e) {
throw new UtilException(e);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"T",
"invoke",
"(",
"Object",
"obj",
",",
"Method",
"method",
",",
"Object",
"...",
"args",
")",
"throws",
"UtilException",
"{",
"if",
"(",
"false",
"==",
"method",
".",
"isAccessible",
"(",
")",
")",
"{",
"method",
".",
"setAccessible",
"(",
"true",
")",
";",
"}",
"try",
"{",
"return",
"(",
"T",
")",
"method",
".",
"invoke",
"(",
"ClassUtil",
".",
"isStatic",
"(",
"method",
")",
"?",
"null",
":",
"obj",
",",
"args",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"UtilException",
"(",
"e",
")",
";",
"}",
"}"
]
| 执行方法
@param <T> 返回对象类型
@param obj 对象,如果执行静态方法,此值为<code>null</code>
@param method 方法(对象方法或static方法都可)
@param args 参数对象
@return 结果
@throws UtilException 一些列异常的包装 | [
"执行方法"
]
| train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ReflectUtil.java#L782-L793 |
actorapp/actor-platform | actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/util/images/ops/ImageLoading.java | ImageLoading.saveJpeg | public static void saveJpeg(Bitmap src, String fileName, int quality) throws ImageSaveException {
"""
Saving image in jpeg to file with better quality 90
@param src source image
@param fileName destination file name
@throws ImageSaveException if it is unable to save image
"""
save(src, fileName, Bitmap.CompressFormat.JPEG, quality);
} | java | public static void saveJpeg(Bitmap src, String fileName, int quality) throws ImageSaveException {
save(src, fileName, Bitmap.CompressFormat.JPEG, quality);
} | [
"public",
"static",
"void",
"saveJpeg",
"(",
"Bitmap",
"src",
",",
"String",
"fileName",
",",
"int",
"quality",
")",
"throws",
"ImageSaveException",
"{",
"save",
"(",
"src",
",",
"fileName",
",",
"Bitmap",
".",
"CompressFormat",
".",
"JPEG",
",",
"quality",
")",
";",
"}"
]
| Saving image in jpeg to file with better quality 90
@param src source image
@param fileName destination file name
@throws ImageSaveException if it is unable to save image | [
"Saving",
"image",
"in",
"jpeg",
"to",
"file",
"with",
"better",
"quality",
"90"
]
| train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/util/images/ops/ImageLoading.java#L321-L323 |
jparsec/jparsec | jparsec/src/main/java/org/jparsec/SourceLocator.java | SourceLocator.lookup | @Private Location lookup(int index) {
"""
Looks up the location identified by {@code ind} using the cached indices of line break
characters. This assumes that all line-break characters before {@code ind} are already scanned.
"""
int size = lineBreakIndices.size();
if (size == 0) return location(0, index);
int lineNumber = binarySearch(lineBreakIndices, index);
if (lineNumber == 0) return location(0, index);
int previousBreak = lineBreakIndices.get(lineNumber - 1);
return location(lineNumber, index - previousBreak - 1);
} | java | @Private Location lookup(int index) {
int size = lineBreakIndices.size();
if (size == 0) return location(0, index);
int lineNumber = binarySearch(lineBreakIndices, index);
if (lineNumber == 0) return location(0, index);
int previousBreak = lineBreakIndices.get(lineNumber - 1);
return location(lineNumber, index - previousBreak - 1);
} | [
"@",
"Private",
"Location",
"lookup",
"(",
"int",
"index",
")",
"{",
"int",
"size",
"=",
"lineBreakIndices",
".",
"size",
"(",
")",
";",
"if",
"(",
"size",
"==",
"0",
")",
"return",
"location",
"(",
"0",
",",
"index",
")",
";",
"int",
"lineNumber",
"=",
"binarySearch",
"(",
"lineBreakIndices",
",",
"index",
")",
";",
"if",
"(",
"lineNumber",
"==",
"0",
")",
"return",
"location",
"(",
"0",
",",
"index",
")",
";",
"int",
"previousBreak",
"=",
"lineBreakIndices",
".",
"get",
"(",
"lineNumber",
"-",
"1",
")",
";",
"return",
"location",
"(",
"lineNumber",
",",
"index",
"-",
"previousBreak",
"-",
"1",
")",
";",
"}"
]
| Looks up the location identified by {@code ind} using the cached indices of line break
characters. This assumes that all line-break characters before {@code ind} are already scanned. | [
"Looks",
"up",
"the",
"location",
"identified",
"by",
"{"
]
| train | https://github.com/jparsec/jparsec/blob/df1280259f5da9eb5ffc537437569dddba66cb94/jparsec/src/main/java/org/jparsec/SourceLocator.java#L85-L92 |
wisdom-framework/wisdom-jdbc | wisdom-openjpa-enhancer-plugin/src/main/java/org/wisdom/openjpa/enhancer/OpenJPAEnhancerMojo.java | OpenJPAEnhancerMojo.fileCreated | @Override
public boolean fileCreated(File file) throws WatchingException {
"""
Notifies the watcher that a new file is created.
@param file is the file.
@return {@literal false} if the pipeline processing must be interrupted for this event. Most watchers should
return {@literal true} to let other watchers be notified.
@throws org.wisdom.maven.WatchingException if the watcher failed to process the given file.
"""
try {
List<File> entities = findEntityClassFiles();
enhance(entities);
return true;
} catch (MojoExecutionException e) {
throw new WatchingException("OpenJPA Enhancer", "Error while enhancing JPA entities", file, e);
}
} | java | @Override
public boolean fileCreated(File file) throws WatchingException {
try {
List<File> entities = findEntityClassFiles();
enhance(entities);
return true;
} catch (MojoExecutionException e) {
throw new WatchingException("OpenJPA Enhancer", "Error while enhancing JPA entities", file, e);
}
} | [
"@",
"Override",
"public",
"boolean",
"fileCreated",
"(",
"File",
"file",
")",
"throws",
"WatchingException",
"{",
"try",
"{",
"List",
"<",
"File",
">",
"entities",
"=",
"findEntityClassFiles",
"(",
")",
";",
"enhance",
"(",
"entities",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"MojoExecutionException",
"e",
")",
"{",
"throw",
"new",
"WatchingException",
"(",
"\"OpenJPA Enhancer\"",
",",
"\"Error while enhancing JPA entities\"",
",",
"file",
",",
"e",
")",
";",
"}",
"}"
]
| Notifies the watcher that a new file is created.
@param file is the file.
@return {@literal false} if the pipeline processing must be interrupted for this event. Most watchers should
return {@literal true} to let other watchers be notified.
@throws org.wisdom.maven.WatchingException if the watcher failed to process the given file. | [
"Notifies",
"the",
"watcher",
"that",
"a",
"new",
"file",
"is",
"created",
"."
]
| train | https://github.com/wisdom-framework/wisdom-jdbc/blob/931f5acf0b2bcb0a8f3b683d60d326caafd09a72/wisdom-openjpa-enhancer-plugin/src/main/java/org/wisdom/openjpa/enhancer/OpenJPAEnhancerMojo.java#L259-L268 |
drinkjava2/jBeanBox | jbeanbox/src/main/java/com/github/drinkjava2/asm5_0_3/commons/JSRInlinerAdapter.java | JSRInlinerAdapter.emitCode | private void emitCode() {
"""
Creates the new instructions, inlining each instantiation of each
subroutine until the code is fully elaborated.
"""
LinkedList<Instantiation> worklist = new LinkedList<Instantiation>();
// Create an instantiation of the "root" subroutine, which is just the
// main routine
worklist.add(new Instantiation(null, mainSubroutine));
// Emit instantiations of each subroutine we encounter, including the
// main subroutine
InsnList newInstructions = new InsnList();
List<TryCatchBlockNode> newTryCatchBlocks = new ArrayList<TryCatchBlockNode>();
List<LocalVariableNode> newLocalVariables = new ArrayList<LocalVariableNode>();
while (!worklist.isEmpty()) {
Instantiation inst = worklist.removeFirst();
emitSubroutine(inst, worklist, newInstructions, newTryCatchBlocks,
newLocalVariables);
}
instructions = newInstructions;
tryCatchBlocks = newTryCatchBlocks;
localVariables = newLocalVariables;
} | java | private void emitCode() {
LinkedList<Instantiation> worklist = new LinkedList<Instantiation>();
// Create an instantiation of the "root" subroutine, which is just the
// main routine
worklist.add(new Instantiation(null, mainSubroutine));
// Emit instantiations of each subroutine we encounter, including the
// main subroutine
InsnList newInstructions = new InsnList();
List<TryCatchBlockNode> newTryCatchBlocks = new ArrayList<TryCatchBlockNode>();
List<LocalVariableNode> newLocalVariables = new ArrayList<LocalVariableNode>();
while (!worklist.isEmpty()) {
Instantiation inst = worklist.removeFirst();
emitSubroutine(inst, worklist, newInstructions, newTryCatchBlocks,
newLocalVariables);
}
instructions = newInstructions;
tryCatchBlocks = newTryCatchBlocks;
localVariables = newLocalVariables;
} | [
"private",
"void",
"emitCode",
"(",
")",
"{",
"LinkedList",
"<",
"Instantiation",
">",
"worklist",
"=",
"new",
"LinkedList",
"<",
"Instantiation",
">",
"(",
")",
";",
"// Create an instantiation of the \"root\" subroutine, which is just the",
"// main routine",
"worklist",
".",
"add",
"(",
"new",
"Instantiation",
"(",
"null",
",",
"mainSubroutine",
")",
")",
";",
"// Emit instantiations of each subroutine we encounter, including the",
"// main subroutine",
"InsnList",
"newInstructions",
"=",
"new",
"InsnList",
"(",
")",
";",
"List",
"<",
"TryCatchBlockNode",
">",
"newTryCatchBlocks",
"=",
"new",
"ArrayList",
"<",
"TryCatchBlockNode",
">",
"(",
")",
";",
"List",
"<",
"LocalVariableNode",
">",
"newLocalVariables",
"=",
"new",
"ArrayList",
"<",
"LocalVariableNode",
">",
"(",
")",
";",
"while",
"(",
"!",
"worklist",
".",
"isEmpty",
"(",
")",
")",
"{",
"Instantiation",
"inst",
"=",
"worklist",
".",
"removeFirst",
"(",
")",
";",
"emitSubroutine",
"(",
"inst",
",",
"worklist",
",",
"newInstructions",
",",
"newTryCatchBlocks",
",",
"newLocalVariables",
")",
";",
"}",
"instructions",
"=",
"newInstructions",
";",
"tryCatchBlocks",
"=",
"newTryCatchBlocks",
";",
"localVariables",
"=",
"newLocalVariables",
";",
"}"
]
| Creates the new instructions, inlining each instantiation of each
subroutine until the code is fully elaborated. | [
"Creates",
"the",
"new",
"instructions",
"inlining",
"each",
"instantiation",
"of",
"each",
"subroutine",
"until",
"the",
"code",
"is",
"fully",
"elaborated",
"."
]
| train | https://github.com/drinkjava2/jBeanBox/blob/01c216599ffa2e5f2d9c01df2adaad0f45567c04/jbeanbox/src/main/java/com/github/drinkjava2/asm5_0_3/commons/JSRInlinerAdapter.java#L378-L397 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/DoublesPmfCdfImpl.java | DoublesPmfCdfImpl.internalBuildHistogram | private static double[] internalBuildHistogram(final DoublesSketch sketch, final double[] splitPoints) {
"""
Shared algorithm for both PMF and CDF functions. The splitPoints must be unique, monotonically
increasing values.
@param sketch the given quantiles DoublesSketch
@param splitPoints an array of <i>m</i> unique, monotonically increasing doubles
that divide the real number line into <i>m+1</i> consecutive disjoint intervals.
@return the unnormalized, accumulated counts of <i>m + 1</i> intervals.
"""
final DoublesSketchAccessor sketchAccessor = DoublesSketchAccessor.wrap(sketch);
Util.checkSplitPointsOrder(splitPoints);
final int numSplitPoints = splitPoints.length;
final int numCounters = numSplitPoints + 1;
final double[] counters = new double[numCounters];
long weight = 1;
sketchAccessor.setLevel(DoublesSketchAccessor.BB_LVL_IDX);
if (numSplitPoints < 50) { // empirically determined crossover
// sort not worth it when few split points
DoublesPmfCdfImpl.bilinearTimeIncrementHistogramCounters(
sketchAccessor, weight, splitPoints, counters);
} else {
sketchAccessor.sort();
// sort is worth it when many split points
DoublesPmfCdfImpl.linearTimeIncrementHistogramCounters(
sketchAccessor, weight, splitPoints, counters);
}
long myBitPattern = sketch.getBitPattern();
final int k = sketch.getK();
assert myBitPattern == sketch.getN() / (2L * k); // internal consistency check
for (int lvl = 0; myBitPattern != 0L; lvl++, myBitPattern >>>= 1) {
weight <<= 1; // double the weight
if ((myBitPattern & 1L) > 0L) { //valid level exists
// the levels are already sorted so we can use the fast version
sketchAccessor.setLevel(lvl);
DoublesPmfCdfImpl.linearTimeIncrementHistogramCounters(
sketchAccessor, weight, splitPoints, counters);
}
}
return counters;
} | java | private static double[] internalBuildHistogram(final DoublesSketch sketch, final double[] splitPoints) {
final DoublesSketchAccessor sketchAccessor = DoublesSketchAccessor.wrap(sketch);
Util.checkSplitPointsOrder(splitPoints);
final int numSplitPoints = splitPoints.length;
final int numCounters = numSplitPoints + 1;
final double[] counters = new double[numCounters];
long weight = 1;
sketchAccessor.setLevel(DoublesSketchAccessor.BB_LVL_IDX);
if (numSplitPoints < 50) { // empirically determined crossover
// sort not worth it when few split points
DoublesPmfCdfImpl.bilinearTimeIncrementHistogramCounters(
sketchAccessor, weight, splitPoints, counters);
} else {
sketchAccessor.sort();
// sort is worth it when many split points
DoublesPmfCdfImpl.linearTimeIncrementHistogramCounters(
sketchAccessor, weight, splitPoints, counters);
}
long myBitPattern = sketch.getBitPattern();
final int k = sketch.getK();
assert myBitPattern == sketch.getN() / (2L * k); // internal consistency check
for (int lvl = 0; myBitPattern != 0L; lvl++, myBitPattern >>>= 1) {
weight <<= 1; // double the weight
if ((myBitPattern & 1L) > 0L) { //valid level exists
// the levels are already sorted so we can use the fast version
sketchAccessor.setLevel(lvl);
DoublesPmfCdfImpl.linearTimeIncrementHistogramCounters(
sketchAccessor, weight, splitPoints, counters);
}
}
return counters;
} | [
"private",
"static",
"double",
"[",
"]",
"internalBuildHistogram",
"(",
"final",
"DoublesSketch",
"sketch",
",",
"final",
"double",
"[",
"]",
"splitPoints",
")",
"{",
"final",
"DoublesSketchAccessor",
"sketchAccessor",
"=",
"DoublesSketchAccessor",
".",
"wrap",
"(",
"sketch",
")",
";",
"Util",
".",
"checkSplitPointsOrder",
"(",
"splitPoints",
")",
";",
"final",
"int",
"numSplitPoints",
"=",
"splitPoints",
".",
"length",
";",
"final",
"int",
"numCounters",
"=",
"numSplitPoints",
"+",
"1",
";",
"final",
"double",
"[",
"]",
"counters",
"=",
"new",
"double",
"[",
"numCounters",
"]",
";",
"long",
"weight",
"=",
"1",
";",
"sketchAccessor",
".",
"setLevel",
"(",
"DoublesSketchAccessor",
".",
"BB_LVL_IDX",
")",
";",
"if",
"(",
"numSplitPoints",
"<",
"50",
")",
"{",
"// empirically determined crossover",
"// sort not worth it when few split points",
"DoublesPmfCdfImpl",
".",
"bilinearTimeIncrementHistogramCounters",
"(",
"sketchAccessor",
",",
"weight",
",",
"splitPoints",
",",
"counters",
")",
";",
"}",
"else",
"{",
"sketchAccessor",
".",
"sort",
"(",
")",
";",
"// sort is worth it when many split points",
"DoublesPmfCdfImpl",
".",
"linearTimeIncrementHistogramCounters",
"(",
"sketchAccessor",
",",
"weight",
",",
"splitPoints",
",",
"counters",
")",
";",
"}",
"long",
"myBitPattern",
"=",
"sketch",
".",
"getBitPattern",
"(",
")",
";",
"final",
"int",
"k",
"=",
"sketch",
".",
"getK",
"(",
")",
";",
"assert",
"myBitPattern",
"==",
"sketch",
".",
"getN",
"(",
")",
"/",
"(",
"2L",
"*",
"k",
")",
";",
"// internal consistency check",
"for",
"(",
"int",
"lvl",
"=",
"0",
";",
"myBitPattern",
"!=",
"0L",
";",
"lvl",
"++",
",",
"myBitPattern",
">>>=",
"1",
")",
"{",
"weight",
"<<=",
"1",
";",
"// double the weight",
"if",
"(",
"(",
"myBitPattern",
"&",
"1L",
")",
">",
"0L",
")",
"{",
"//valid level exists",
"// the levels are already sorted so we can use the fast version",
"sketchAccessor",
".",
"setLevel",
"(",
"lvl",
")",
";",
"DoublesPmfCdfImpl",
".",
"linearTimeIncrementHistogramCounters",
"(",
"sketchAccessor",
",",
"weight",
",",
"splitPoints",
",",
"counters",
")",
";",
"}",
"}",
"return",
"counters",
";",
"}"
]
| Shared algorithm for both PMF and CDF functions. The splitPoints must be unique, monotonically
increasing values.
@param sketch the given quantiles DoublesSketch
@param splitPoints an array of <i>m</i> unique, monotonically increasing doubles
that divide the real number line into <i>m+1</i> consecutive disjoint intervals.
@return the unnormalized, accumulated counts of <i>m + 1</i> intervals. | [
"Shared",
"algorithm",
"for",
"both",
"PMF",
"and",
"CDF",
"functions",
".",
"The",
"splitPoints",
"must",
"be",
"unique",
"monotonically",
"increasing",
"values",
"."
]
| train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/DoublesPmfCdfImpl.java#L41-L76 |
GerdHolz/TOVAL | src/de/invation/code/toval/graphic/diagrams/panels/ScatterChartPanel.java | ScatterChartPanel.paintTick | protected void paintTick(Graphics g, ValueDimension dim, Number tickValue, int tickLength) {
"""
Paints a tick with the specified length and value with respect to the given dimension.
@param g Graphics context
@param dim Reference dimension for tick painting
@param tickValue Value for the tick
@param tickLength Length of the tick
"""
String str = String.format(getTickInfo(dim).getFormat(), tickValue.doubleValue());
int xPosition;
int yPosition;
Point descPos;
switch (dim) {
case X:
xPosition = getXFor(tickValue);
yPosition = getPaintingRegion().getBottomLeft().y;
g.drawLine(xPosition, yPosition, xPosition, yPosition+tickLength);
descPos = getPaintingRegion().getDescriptionPos(dim, str, xPosition);
g.drawString(str, descPos.x, descPos.y+tickLength);
break;
case Y:
xPosition = getPaintingRegion().getBottomLeft().x;
yPosition = getYFor(tickValue);
g.drawLine(xPosition, yPosition, xPosition-tickLength, yPosition);
descPos = getPaintingRegion().getDescriptionPos(dim, str, yPosition);
g.drawString(str, descPos.x-tickLength, descPos.y+tickLength);
break;
}
} | java | protected void paintTick(Graphics g, ValueDimension dim, Number tickValue, int tickLength) {
String str = String.format(getTickInfo(dim).getFormat(), tickValue.doubleValue());
int xPosition;
int yPosition;
Point descPos;
switch (dim) {
case X:
xPosition = getXFor(tickValue);
yPosition = getPaintingRegion().getBottomLeft().y;
g.drawLine(xPosition, yPosition, xPosition, yPosition+tickLength);
descPos = getPaintingRegion().getDescriptionPos(dim, str, xPosition);
g.drawString(str, descPos.x, descPos.y+tickLength);
break;
case Y:
xPosition = getPaintingRegion().getBottomLeft().x;
yPosition = getYFor(tickValue);
g.drawLine(xPosition, yPosition, xPosition-tickLength, yPosition);
descPos = getPaintingRegion().getDescriptionPos(dim, str, yPosition);
g.drawString(str, descPos.x-tickLength, descPos.y+tickLength);
break;
}
} | [
"protected",
"void",
"paintTick",
"(",
"Graphics",
"g",
",",
"ValueDimension",
"dim",
",",
"Number",
"tickValue",
",",
"int",
"tickLength",
")",
"{",
"String",
"str",
"=",
"String",
".",
"format",
"(",
"getTickInfo",
"(",
"dim",
")",
".",
"getFormat",
"(",
")",
",",
"tickValue",
".",
"doubleValue",
"(",
")",
")",
";",
"int",
"xPosition",
";",
"int",
"yPosition",
";",
"Point",
"descPos",
";",
"switch",
"(",
"dim",
")",
"{",
"case",
"X",
":",
"xPosition",
"=",
"getXFor",
"(",
"tickValue",
")",
";",
"yPosition",
"=",
"getPaintingRegion",
"(",
")",
".",
"getBottomLeft",
"(",
")",
".",
"y",
";",
"g",
".",
"drawLine",
"(",
"xPosition",
",",
"yPosition",
",",
"xPosition",
",",
"yPosition",
"+",
"tickLength",
")",
";",
"descPos",
"=",
"getPaintingRegion",
"(",
")",
".",
"getDescriptionPos",
"(",
"dim",
",",
"str",
",",
"xPosition",
")",
";",
"g",
".",
"drawString",
"(",
"str",
",",
"descPos",
".",
"x",
",",
"descPos",
".",
"y",
"+",
"tickLength",
")",
";",
"break",
";",
"case",
"Y",
":",
"xPosition",
"=",
"getPaintingRegion",
"(",
")",
".",
"getBottomLeft",
"(",
")",
".",
"x",
";",
"yPosition",
"=",
"getYFor",
"(",
"tickValue",
")",
";",
"g",
".",
"drawLine",
"(",
"xPosition",
",",
"yPosition",
",",
"xPosition",
"-",
"tickLength",
",",
"yPosition",
")",
";",
"descPos",
"=",
"getPaintingRegion",
"(",
")",
".",
"getDescriptionPos",
"(",
"dim",
",",
"str",
",",
"yPosition",
")",
";",
"g",
".",
"drawString",
"(",
"str",
",",
"descPos",
".",
"x",
"-",
"tickLength",
",",
"descPos",
".",
"y",
"+",
"tickLength",
")",
";",
"break",
";",
"}",
"}"
]
| Paints a tick with the specified length and value with respect to the given dimension.
@param g Graphics context
@param dim Reference dimension for tick painting
@param tickValue Value for the tick
@param tickLength Length of the tick | [
"Paints",
"a",
"tick",
"with",
"the",
"specified",
"length",
"and",
"value",
"with",
"respect",
"to",
"the",
"given",
"dimension",
"."
]
| train | https://github.com/GerdHolz/TOVAL/blob/036922cdfd710fa53b18e5dbe1e07f226f731fde/src/de/invation/code/toval/graphic/diagrams/panels/ScatterChartPanel.java#L339-L360 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.