repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
google/j2objc | jre_emul/android/platform/libcore/xml/src/main/java/org/kxml2/io/KXmlParser.java | KXmlParser.readQuotedId | private String readQuotedId(boolean returnText) throws IOException, XmlPullParserException {
int quote = peekCharacter();
char[] delimiter;
if (quote == '"') {
delimiter = DOUBLE_QUOTE;
} else if (quote == '\'') {
delimiter = SINGLE_QUOTE;
} else {
throw new XmlPullParserException("Expected a quoted string", this, null);
}
position++;
return readUntil(delimiter, returnText);
} | java | private String readQuotedId(boolean returnText) throws IOException, XmlPullParserException {
int quote = peekCharacter();
char[] delimiter;
if (quote == '"') {
delimiter = DOUBLE_QUOTE;
} else if (quote == '\'') {
delimiter = SINGLE_QUOTE;
} else {
throw new XmlPullParserException("Expected a quoted string", this, null);
}
position++;
return readUntil(delimiter, returnText);
} | [
"private",
"String",
"readQuotedId",
"(",
"boolean",
"returnText",
")",
"throws",
"IOException",
",",
"XmlPullParserException",
"{",
"int",
"quote",
"=",
"peekCharacter",
"(",
")",
";",
"char",
"[",
"]",
"delimiter",
";",
"if",
"(",
"quote",
"==",
"'",
"'",
... | Reads a quoted string, performing no entity escaping of the contents. | [
"Reads",
"a",
"quoted",
"string",
"performing",
"no",
"entity",
"escaping",
"of",
"the",
"contents",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/xml/src/main/java/org/kxml2/io/KXmlParser.java#L663-L675 |
liyiorg/weixin-popular | src/main/java/weixin/popular/api/CardAPI.java | CardAPI.codeDecrypt | public static CodeDecryptResult codeDecrypt(String accessToken, CodeDecrypt codeDecrypt) {
return codeDecrypt(accessToken, JsonUtil.toJSONString(codeDecrypt));
} | java | public static CodeDecryptResult codeDecrypt(String accessToken, CodeDecrypt codeDecrypt) {
return codeDecrypt(accessToken, JsonUtil.toJSONString(codeDecrypt));
} | [
"public",
"static",
"CodeDecryptResult",
"codeDecrypt",
"(",
"String",
"accessToken",
",",
"CodeDecrypt",
"codeDecrypt",
")",
"{",
"return",
"codeDecrypt",
"(",
"accessToken",
",",
"JsonUtil",
".",
"toJSONString",
"(",
"codeDecrypt",
")",
")",
";",
"}"
] | Code解码<br>
1.只能解码本公众号卡券获取的加密code。 <br>
2.开发者若从url上获取到加密code,请注意先进行urldecode,否则报错。<br>
3.encrypt_code是卡券的code码经过加密处理得到的加密code码,与code一一对应。<br>
4.开发者只能解密本公众号的加密code,否则报错。
@param accessToken accessToken
@param codeDecrypt codeDecrypt
@return result | [
"Code解码<br",
">",
"1",
".",
"只能解码本公众号卡券获取的加密code。",
"<br",
">",
"2",
".",
"开发者若从url上获取到加密code",
"请注意先进行urldecode,否则报错。<br",
">",
"3",
".",
"encrypt_code是卡券的code码经过加密处理得到的加密code码,与code一一对应。<br",
">",
"4",
".",
"开发者只能解密本公众号的加密code,否则报错。"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/CardAPI.java#L163-L165 |
aws/aws-sdk-java | aws-java-sdk-stepfunctions/src/main/java/com/amazonaws/services/stepfunctions/builder/StepFunctionBuilder.java | StepFunctionBuilder.lte | public static NumericLessThanOrEqualCondition.Builder lte(String variable, long expectedValue) {
return NumericLessThanOrEqualCondition.builder().variable(variable).expectedValue(expectedValue);
} | java | public static NumericLessThanOrEqualCondition.Builder lte(String variable, long expectedValue) {
return NumericLessThanOrEqualCondition.builder().variable(variable).expectedValue(expectedValue);
} | [
"public",
"static",
"NumericLessThanOrEqualCondition",
".",
"Builder",
"lte",
"(",
"String",
"variable",
",",
"long",
"expectedValue",
")",
"{",
"return",
"NumericLessThanOrEqualCondition",
".",
"builder",
"(",
")",
".",
"variable",
"(",
"variable",
")",
".",
"exp... | Binary condition for Numeric less than or equal to comparison. Supports both integral and floating point numeric types.
@param variable The JSONPath expression that determines which piece of the input document is used for the comparison.
@param expectedValue The expected value for this condition.
@see <a href="https://states-language.net/spec.html#choice-state">https://states-language.net/spec.html#choice-state</a>
@see com.amazonaws.services.stepfunctions.builder.states.Choice | [
"Binary",
"condition",
"for",
"Numeric",
"less",
"than",
"or",
"equal",
"to",
"comparison",
".",
"Supports",
"both",
"integral",
"and",
"floating",
"point",
"numeric",
"types",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-stepfunctions/src/main/java/com/amazonaws/services/stepfunctions/builder/StepFunctionBuilder.java#L428-L430 |
docusign/docusign-java-client | src/main/java/com/docusign/esign/api/TemplatesApi.java | TemplatesApi.getPages | public PageImages getPages(String accountId, String templateId, String documentId) throws ApiException {
return getPages(accountId, templateId, documentId, null);
} | java | public PageImages getPages(String accountId, String templateId, String documentId) throws ApiException {
return getPages(accountId, templateId, documentId, null);
} | [
"public",
"PageImages",
"getPages",
"(",
"String",
"accountId",
",",
"String",
"templateId",
",",
"String",
"documentId",
")",
"throws",
"ApiException",
"{",
"return",
"getPages",
"(",
"accountId",
",",
"templateId",
",",
"documentId",
",",
"null",
")",
";",
"... | Returns document page image(s) based on input.
@param accountId The external account number (int) or account ID Guid. (required)
@param templateId The ID of the template being accessed. (required)
@param documentId The ID of the document being accessed. (required)
@return PageImages | [
"Returns",
"document",
"page",
"image",
"(",
"s",
")",
"based",
"on",
"input",
"."
] | train | https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/TemplatesApi.java#L1787-L1789 |
liferay/com-liferay-commerce | commerce-product-type-virtual-service/src/main/java/com/liferay/commerce/product/type/virtual/service/persistence/impl/CPDefinitionVirtualSettingPersistenceImpl.java | CPDefinitionVirtualSettingPersistenceImpl.findByUUID_G | @Override
public CPDefinitionVirtualSetting findByUUID_G(String uuid, long groupId)
throws NoSuchCPDefinitionVirtualSettingException {
CPDefinitionVirtualSetting cpDefinitionVirtualSetting = fetchByUUID_G(uuid,
groupId);
if (cpDefinitionVirtualSetting == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", groupId=");
msg.append(groupId);
msg.append("}");
if (_log.isDebugEnabled()) {
_log.debug(msg.toString());
}
throw new NoSuchCPDefinitionVirtualSettingException(msg.toString());
}
return cpDefinitionVirtualSetting;
} | java | @Override
public CPDefinitionVirtualSetting findByUUID_G(String uuid, long groupId)
throws NoSuchCPDefinitionVirtualSettingException {
CPDefinitionVirtualSetting cpDefinitionVirtualSetting = fetchByUUID_G(uuid,
groupId);
if (cpDefinitionVirtualSetting == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", groupId=");
msg.append(groupId);
msg.append("}");
if (_log.isDebugEnabled()) {
_log.debug(msg.toString());
}
throw new NoSuchCPDefinitionVirtualSettingException(msg.toString());
}
return cpDefinitionVirtualSetting;
} | [
"@",
"Override",
"public",
"CPDefinitionVirtualSetting",
"findByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"throws",
"NoSuchCPDefinitionVirtualSettingException",
"{",
"CPDefinitionVirtualSetting",
"cpDefinitionVirtualSetting",
"=",
"fetchByUUID_G",
"(",
"uui... | Returns the cp definition virtual setting where uuid = ? and groupId = ? or throws a {@link NoSuchCPDefinitionVirtualSettingException} if it could not be found.
@param uuid the uuid
@param groupId the group ID
@return the matching cp definition virtual setting
@throws NoSuchCPDefinitionVirtualSettingException if a matching cp definition virtual setting could not be found | [
"Returns",
"the",
"cp",
"definition",
"virtual",
"setting",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"or",
"throws",
"a",
"{",
"@link",
"NoSuchCPDefinitionVirtualSettingException",
"}",
"if",
"it",
"could",
"not",
"be",
"found",
... | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-type-virtual-service/src/main/java/com/liferay/commerce/product/type/virtual/service/persistence/impl/CPDefinitionVirtualSettingPersistenceImpl.java#L675-L702 |
grails/grails-core | grails-web-common/src/main/groovy/org/grails/web/pages/GroovyPagesUriSupport.java | GroovyPagesUriSupport.getNoSuffixViewURI | public String getNoSuffixViewURI(String controllerName, String viewName) {
FastStringWriter buf = new FastStringWriter();
return getViewURIInternal(controllerName, viewName, buf, false);
} | java | public String getNoSuffixViewURI(String controllerName, String viewName) {
FastStringWriter buf = new FastStringWriter();
return getViewURIInternal(controllerName, viewName, buf, false);
} | [
"public",
"String",
"getNoSuffixViewURI",
"(",
"String",
"controllerName",
",",
"String",
"viewName",
")",
"{",
"FastStringWriter",
"buf",
"=",
"new",
"FastStringWriter",
"(",
")",
";",
"return",
"getViewURIInternal",
"(",
"controllerName",
",",
"viewName",
",",
"... | Obtains a view URI of the given controller name and view name without the suffix
@param controllerName The name of the controller
@param viewName The name of the view
@return The view URI | [
"Obtains",
"a",
"view",
"URI",
"of",
"the",
"given",
"controller",
"name",
"and",
"view",
"name",
"without",
"the",
"suffix"
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-web-common/src/main/groovy/org/grails/web/pages/GroovyPagesUriSupport.java#L209-L213 |
google/gson | gson/src/main/java/com/google/gson/Gson.java | Gson.toJson | public void toJson(Object src, Type typeOfSrc, Appendable writer) throws JsonIOException {
try {
JsonWriter jsonWriter = newJsonWriter(Streams.writerForAppendable(writer));
toJson(src, typeOfSrc, jsonWriter);
} catch (IOException e) {
throw new JsonIOException(e);
}
} | java | public void toJson(Object src, Type typeOfSrc, Appendable writer) throws JsonIOException {
try {
JsonWriter jsonWriter = newJsonWriter(Streams.writerForAppendable(writer));
toJson(src, typeOfSrc, jsonWriter);
} catch (IOException e) {
throw new JsonIOException(e);
}
} | [
"public",
"void",
"toJson",
"(",
"Object",
"src",
",",
"Type",
"typeOfSrc",
",",
"Appendable",
"writer",
")",
"throws",
"JsonIOException",
"{",
"try",
"{",
"JsonWriter",
"jsonWriter",
"=",
"newJsonWriter",
"(",
"Streams",
".",
"writerForAppendable",
"(",
"writer... | This method serializes the specified object, including those of generic types, into its
equivalent Json representation. This method must be used if the specified object is a generic
type. For non-generic objects, use {@link #toJson(Object, Appendable)} instead.
@param src the object for which JSON representation is to be created
@param typeOfSrc The specific genericized type of src. You can obtain
this type by using the {@link com.google.gson.reflect.TypeToken} class. For example,
to get the type for {@code Collection<Foo>}, you should use:
<pre>
Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
</pre>
@param writer Writer to which the Json representation of src needs to be written.
@throws JsonIOException if there was a problem writing to the writer
@since 1.2 | [
"This",
"method",
"serializes",
"the",
"specified",
"object",
"including",
"those",
"of",
"generic",
"types",
"into",
"its",
"equivalent",
"Json",
"representation",
".",
"This",
"method",
"must",
"be",
"used",
"if",
"the",
"specified",
"object",
"is",
"a",
"ge... | train | https://github.com/google/gson/blob/63ee47cb642c8018e5cddd639aa2be143220ad4b/gson/src/main/java/com/google/gson/Gson.java#L680-L687 |
ironjacamar/ironjacamar | codegenerator/src/main/java/org/ironjacamar/codegenerator/code/CfCodeGen.java | CfCodeGen.writeImport | @Override
public void writeImport(Definition def, Writer out) throws IOException
{
out.write("package " + def.getRaPackage() + ";");
writeEol(out);
writeEol(out);
importLogging(def, out);
out.write("import javax.naming.NamingException;\n");
out.write("import javax.naming.Reference;\n\n");
out.write("import javax.resource.ResourceException;\n");
out.write("import javax.resource.spi.ConnectionManager;\n\n");
} | java | @Override
public void writeImport(Definition def, Writer out) throws IOException
{
out.write("package " + def.getRaPackage() + ";");
writeEol(out);
writeEol(out);
importLogging(def, out);
out.write("import javax.naming.NamingException;\n");
out.write("import javax.naming.Reference;\n\n");
out.write("import javax.resource.ResourceException;\n");
out.write("import javax.resource.spi.ConnectionManager;\n\n");
} | [
"@",
"Override",
"public",
"void",
"writeImport",
"(",
"Definition",
"def",
",",
"Writer",
"out",
")",
"throws",
"IOException",
"{",
"out",
".",
"write",
"(",
"\"package \"",
"+",
"def",
".",
"getRaPackage",
"(",
")",
"+",
"\";\"",
")",
";",
"writeEol",
... | Output class import
@param def definition
@param out Writer
@throws IOException ioException | [
"Output",
"class",
"import"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/CfCodeGen.java#L97-L109 |
gliga/ekstazi | org.ekstazi.core/src/main/java/org/ekstazi/maven/AbstractMojoInterceptor.java | AbstractMojoInterceptor.invokeAndGetBoolean | protected static boolean invokeAndGetBoolean(String methodName, Object mojo) throws Exception {
return (Boolean) invokeGetMethod(methodName, mojo);
} | java | protected static boolean invokeAndGetBoolean(String methodName, Object mojo) throws Exception {
return (Boolean) invokeGetMethod(methodName, mojo);
} | [
"protected",
"static",
"boolean",
"invokeAndGetBoolean",
"(",
"String",
"methodName",
",",
"Object",
"mojo",
")",
"throws",
"Exception",
"{",
"return",
"(",
"Boolean",
")",
"invokeGetMethod",
"(",
"methodName",
",",
"mojo",
")",
";",
"}"
] | Gets boolean field value from the given mojo based on the given method
name.
@param methodName
Method name to be used to get the value
@param mojo
Mojo from which to extract the value
@return Boolean value by invoking method on Mojo
@throws Exception
If reflection invocation goes wrong | [
"Gets",
"boolean",
"field",
"value",
"from",
"the",
"given",
"mojo",
"based",
"on",
"the",
"given",
"method",
"name",
"."
] | train | https://github.com/gliga/ekstazi/blob/5bf4d39a13305afe62f8b8d2d7b4c573d37d42a1/org.ekstazi.core/src/main/java/org/ekstazi/maven/AbstractMojoInterceptor.java#L107-L109 |
js-lib-com/template.xhtml | src/main/java/js/template/xhtml/ConditionalExpression.java | ConditionalExpression.getProcessor | private static Processor getProcessor(Opcode opcode) {
switch (opcode) {
case NOT_EMPTY:
return NOT_EPMTY_PROCESSOR;
case EQUALS:
if (EQUALS_PROCESSOR == null) {
EQUALS_PROCESSOR = new EqualsProcessor();
}
return EQUALS_PROCESSOR;
case LESS_THAN:
if (LESS_THAN_PROCESSOR == null) {
LESS_THAN_PROCESSOR = new LessThanProcessor();
}
return LESS_THAN_PROCESSOR;
case GREATER_THAN:
if (GREATER_THAN_PROCESSOR == null) {
GREATER_THAN_PROCESSOR = new GreaterThanProcessor();
}
return GREATER_THAN_PROCESSOR;
default:
throw new BugError("Unsupported opcode |%s|.", opcode);
}
} | java | private static Processor getProcessor(Opcode opcode) {
switch (opcode) {
case NOT_EMPTY:
return NOT_EPMTY_PROCESSOR;
case EQUALS:
if (EQUALS_PROCESSOR == null) {
EQUALS_PROCESSOR = new EqualsProcessor();
}
return EQUALS_PROCESSOR;
case LESS_THAN:
if (LESS_THAN_PROCESSOR == null) {
LESS_THAN_PROCESSOR = new LessThanProcessor();
}
return LESS_THAN_PROCESSOR;
case GREATER_THAN:
if (GREATER_THAN_PROCESSOR == null) {
GREATER_THAN_PROCESSOR = new GreaterThanProcessor();
}
return GREATER_THAN_PROCESSOR;
default:
throw new BugError("Unsupported opcode |%s|.", opcode);
}
} | [
"private",
"static",
"Processor",
"getProcessor",
"(",
"Opcode",
"opcode",
")",
"{",
"switch",
"(",
"opcode",
")",
"{",
"case",
"NOT_EMPTY",
":",
"return",
"NOT_EPMTY_PROCESSOR",
";",
"case",
"EQUALS",
":",
"if",
"(",
"EQUALS_PROCESSOR",
"==",
"null",
")",
"... | Operator processor factory. Returned processor instance is a singleton, that is, reused on running virtual machine.
@param opcode return processor suitable for requested operator.
@return operator processor instance. | [
"Operator",
"processor",
"factory",
".",
"Returned",
"processor",
"instance",
"is",
"a",
"singleton",
"that",
"is",
"reused",
"on",
"running",
"virtual",
"machine",
"."
] | train | https://github.com/js-lib-com/template.xhtml/blob/d50cec08aca9ab9680baebe2a26a341c096564fb/src/main/java/js/template/xhtml/ConditionalExpression.java#L363-L389 |
square/dagger | core/src/main/java/dagger/internal/Keys.java | Keys.getLazyKey | static String getLazyKey(String key) {
int start = startOfType(key);
if (substringStartsWith(key, start, LAZY_PREFIX)) {
return extractKey(key, start, key.substring(0, start), LAZY_PREFIX);
} else {
return null;
}
} | java | static String getLazyKey(String key) {
int start = startOfType(key);
if (substringStartsWith(key, start, LAZY_PREFIX)) {
return extractKey(key, start, key.substring(0, start), LAZY_PREFIX);
} else {
return null;
}
} | [
"static",
"String",
"getLazyKey",
"(",
"String",
"key",
")",
"{",
"int",
"start",
"=",
"startOfType",
"(",
"key",
")",
";",
"if",
"(",
"substringStartsWith",
"(",
"key",
",",
"start",
",",
"LAZY_PREFIX",
")",
")",
"{",
"return",
"extractKey",
"(",
"key",... | Returns a key for the underlying binding of a Lazy<T> value. For example,
if this is a key for a {@code Lazy<Foo>}, this returns the key for
{@code Foo}. This retains annotations. | [
"Returns",
"a",
"key",
"for",
"the",
"underlying",
"binding",
"of",
"a",
"Lazy<T",
">",
"value",
".",
"For",
"example",
"if",
"this",
"is",
"a",
"key",
"for",
"a",
"{"
] | train | https://github.com/square/dagger/blob/572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde/core/src/main/java/dagger/internal/Keys.java#L196-L203 |
OpenLiberty/open-liberty | dev/com.ibm.ws.product.utility/src/com/ibm/ws/product/utility/extension/IFixCompareCommandTask.java | IFixCompareCommandTask.isIFixFileListValid | private boolean isIFixFileListValid(IFixInfo iFixInfo, File wlpInstallationDirectory) throws ParseException {
// First get the list of files to check
Updates updates = iFixInfo.getUpdates();
if (updates == null) {
return true;
}
Set<UpdatedFile> files = updates.getFiles();
// For each file work out if it is a feature JAR or not. Can do this based on the name as it will be in the format:
// <pathAndName>_1.0.0.v20120424-1111.jar
Pattern featureJarPattern = Pattern.compile(".*_([0-9]*\\.){3}v[0-9]{8}-[0-9]{4}\\.jar");
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
for (UpdatedFile file : files) {
String fileId = file.getId();
boolean isFeatureJar = featureJarPattern.matcher(fileId).matches();
if (isFeatureJar) {
// If it's a feature JAR we just need to see if it is present
File jarFile = new File(wlpInstallationDirectory, fileId);
if (!jarFile.exists()) {
return false;
}
} else {
// If its not a feature JAR then it means you don't get a unique JAR per iFix so see if the file that is there is the one for this iFix or newer
File fileOnDisk = new File(wlpInstallationDirectory, fileId);
String fileDate = file.getDate();
long metaDataDate = dateFormat.parse(fileDate).getTime();
if (metaDataDate > fileOnDisk.lastModified()) {
return false;
}
}
}
return true;
} | java | private boolean isIFixFileListValid(IFixInfo iFixInfo, File wlpInstallationDirectory) throws ParseException {
// First get the list of files to check
Updates updates = iFixInfo.getUpdates();
if (updates == null) {
return true;
}
Set<UpdatedFile> files = updates.getFiles();
// For each file work out if it is a feature JAR or not. Can do this based on the name as it will be in the format:
// <pathAndName>_1.0.0.v20120424-1111.jar
Pattern featureJarPattern = Pattern.compile(".*_([0-9]*\\.){3}v[0-9]{8}-[0-9]{4}\\.jar");
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
for (UpdatedFile file : files) {
String fileId = file.getId();
boolean isFeatureJar = featureJarPattern.matcher(fileId).matches();
if (isFeatureJar) {
// If it's a feature JAR we just need to see if it is present
File jarFile = new File(wlpInstallationDirectory, fileId);
if (!jarFile.exists()) {
return false;
}
} else {
// If its not a feature JAR then it means you don't get a unique JAR per iFix so see if the file that is there is the one for this iFix or newer
File fileOnDisk = new File(wlpInstallationDirectory, fileId);
String fileDate = file.getDate();
long metaDataDate = dateFormat.parse(fileDate).getTime();
if (metaDataDate > fileOnDisk.lastModified()) {
return false;
}
}
}
return true;
} | [
"private",
"boolean",
"isIFixFileListValid",
"(",
"IFixInfo",
"iFixInfo",
",",
"File",
"wlpInstallationDirectory",
")",
"throws",
"ParseException",
"{",
"// First get the list of files to check",
"Updates",
"updates",
"=",
"iFixInfo",
".",
"getUpdates",
"(",
")",
";",
"... | Returns <code>true</code> if the list of files in the IFixInfo are present (for non-platform JARs) or more recent than those listed (for platform JARs or static files).
@param iFixInfo
@param wlpInstallationDirectory
@return
@throws ParseException | [
"Returns",
"<code",
">",
"true<",
"/",
"code",
">",
"if",
"the",
"list",
"of",
"files",
"in",
"the",
"IFixInfo",
"are",
"present",
"(",
"for",
"non",
"-",
"platform",
"JARs",
")",
"or",
"more",
"recent",
"than",
"those",
"listed",
"(",
"for",
"platform... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.product.utility/src/com/ibm/ws/product/utility/extension/IFixCompareCommandTask.java#L430-L464 |
tomgibara/bits | src/main/java/com/tomgibara/bits/BitVector.java | BitVector.duplicateRange | public BitVector duplicateRange(int from, int to, boolean copy, boolean mutable) {
if (mutable && !copy && !this.mutable) throw new IllegalStateException("Cannot obtain mutable view of an immutable BitVector");
if (from < 0) throw new IllegalArgumentException();
if (to < from) throw new IllegalArgumentException();
from += start;
to += start;
if (to > finish) throw new IllegalArgumentException();
return duplicateAdj(from, to, copy, mutable);
} | java | public BitVector duplicateRange(int from, int to, boolean copy, boolean mutable) {
if (mutable && !copy && !this.mutable) throw new IllegalStateException("Cannot obtain mutable view of an immutable BitVector");
if (from < 0) throw new IllegalArgumentException();
if (to < from) throw new IllegalArgumentException();
from += start;
to += start;
if (to > finish) throw new IllegalArgumentException();
return duplicateAdj(from, to, copy, mutable);
} | [
"public",
"BitVector",
"duplicateRange",
"(",
"int",
"from",
",",
"int",
"to",
",",
"boolean",
"copy",
",",
"boolean",
"mutable",
")",
"{",
"if",
"(",
"mutable",
"&&",
"!",
"copy",
"&&",
"!",
"this",
".",
"mutable",
")",
"throw",
"new",
"IllegalStateExce... | Duplicates a range of the {@link BitVector}.
@param from
the (inclusive) position at which the range begins
@param to
the (exclusive) position at which the range ends
@param copy
true if the duplicated range should be a detached copy, false
if it should be a view, backed by the same bit data.
@param mutable
whether the duplicated range should be mutable
@return a duplicate of this BitVector
@see #duplicate(boolean, boolean) | [
"Duplicates",
"a",
"range",
"of",
"the",
"{",
"@link",
"BitVector",
"}",
"."
] | train | https://github.com/tomgibara/bits/blob/56c32c0a30efd3d7c4e7c6600a0ca39e51eecc97/src/main/java/com/tomgibara/bits/BitVector.java#L916-L924 |
smurn/jPLY | jply/src/main/java/org/smurn/jply/Element.java | Element.setDouble | public void setDouble(final String propertyName, final double value) {
if (propertyName == null) {
throw new NullPointerException("propertyName must not be null.");
}
Integer index = propertyMap.get(propertyName);
if (index == null) {
throw new IllegalArgumentException("non existent property: '"
+ propertyName + "'.");
}
this.data[index] = new double[]{value};
} | java | public void setDouble(final String propertyName, final double value) {
if (propertyName == null) {
throw new NullPointerException("propertyName must not be null.");
}
Integer index = propertyMap.get(propertyName);
if (index == null) {
throw new IllegalArgumentException("non existent property: '"
+ propertyName + "'.");
}
this.data[index] = new double[]{value};
} | [
"public",
"void",
"setDouble",
"(",
"final",
"String",
"propertyName",
",",
"final",
"double",
"value",
")",
"{",
"if",
"(",
"propertyName",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"propertyName must not be null.\"",
")",
";",
"}",... | Sets the value of a property-list.
If the property is a list, the list will be set to a single entry.
@param propertyName Name of the property to set.
@param value Value to set for that property.
@throws NullPointerException if {@code propertyName} is {@code null}.
@throws IllegalArgumentException if the element type does not have
a property with the given name. | [
"Sets",
"the",
"value",
"of",
"a",
"property",
"-",
"list",
".",
"If",
"the",
"property",
"is",
"a",
"list",
"the",
"list",
"will",
"be",
"set",
"to",
"a",
"single",
"entry",
"."
] | train | https://github.com/smurn/jPLY/blob/77cb8c47fff7549ae1da8d8568ad8bdf374fe89f/jply/src/main/java/org/smurn/jply/Element.java#L221-L231 |
geomajas/geomajas-project-client-gwt | client/src/main/java/org/geomajas/gwt/client/gfx/painter/RasterTilePainter.java | RasterTilePainter.deleteShape | public void deleteShape(Paintable paintable, Object group, MapContext context) {
RasterTile tile = (RasterTile) paintable;
context.getRasterContext().deleteElement(tile.getStore().getLayer(), tile.getCode().toString());
} | java | public void deleteShape(Paintable paintable, Object group, MapContext context) {
RasterTile tile = (RasterTile) paintable;
context.getRasterContext().deleteElement(tile.getStore().getLayer(), tile.getCode().toString());
} | [
"public",
"void",
"deleteShape",
"(",
"Paintable",
"paintable",
",",
"Object",
"group",
",",
"MapContext",
"context",
")",
"{",
"RasterTile",
"tile",
"=",
"(",
"RasterTile",
")",
"paintable",
";",
"context",
".",
"getRasterContext",
"(",
")",
".",
"deleteEleme... | Delete a {@link Paintable} object from the given {@link MapContext}. It the object does not exist, nothing
will be done.
@param paintable
The object to be painted.
@param group
The group where the object resides in (optional).
@param context
The context to paint on. | [
"Delete",
"a",
"{",
"@link",
"Paintable",
"}",
"object",
"from",
"the",
"given",
"{",
"@link",
"MapContext",
"}",
".",
"It",
"the",
"object",
"does",
"not",
"exist",
"nothing",
"will",
"be",
"done",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/painter/RasterTilePainter.java#L60-L63 |
OpenLiberty/open-liberty | dev/com.ibm.ws.repository/src/com/ibm/ws/repository/transport/model/FilterVersion.java | FilterVersion.getFilterRange | public static VersionRange getFilterRange(FilterVersion minVersion, FilterVersion maxVersion) {
VersionRange vr = null;
Version vmin = minVersion == null ? Version.emptyVersion : new Version(minVersion.getValue());
Version vmax = maxVersion == null ? null : new Version(maxVersion.getValue());
char leftType = (minVersion == null || minVersion.getInclusive()) ? VersionRange.LEFT_CLOSED : VersionRange.LEFT_OPEN;
char rightType = (maxVersion == null || maxVersion.getInclusive()) ? VersionRange.RIGHT_CLOSED : VersionRange.RIGHT_OPEN;
vr = new VersionRange(leftType, vmin, vmax, rightType);
return vr;
} | java | public static VersionRange getFilterRange(FilterVersion minVersion, FilterVersion maxVersion) {
VersionRange vr = null;
Version vmin = minVersion == null ? Version.emptyVersion : new Version(minVersion.getValue());
Version vmax = maxVersion == null ? null : new Version(maxVersion.getValue());
char leftType = (minVersion == null || minVersion.getInclusive()) ? VersionRange.LEFT_CLOSED : VersionRange.LEFT_OPEN;
char rightType = (maxVersion == null || maxVersion.getInclusive()) ? VersionRange.RIGHT_CLOSED : VersionRange.RIGHT_OPEN;
vr = new VersionRange(leftType, vmin, vmax, rightType);
return vr;
} | [
"public",
"static",
"VersionRange",
"getFilterRange",
"(",
"FilterVersion",
"minVersion",
",",
"FilterVersion",
"maxVersion",
")",
"{",
"VersionRange",
"vr",
"=",
"null",
";",
"Version",
"vmin",
"=",
"minVersion",
"==",
"null",
"?",
"Version",
".",
"emptyVersion",... | This method creates a version range from the supplied min and max FilterVersion
@param minVersion The min version in the range. Can be null, if so treated as {@link Version#emptyVersion}
@param maxVersion The max version. Can be null, null in a version range is treated as infinite
@return A version range object representing the min and max values supplied | [
"This",
"method",
"creates",
"a",
"version",
"range",
"from",
"the",
"supplied",
"min",
"and",
"max",
"FilterVersion"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository/src/com/ibm/ws/repository/transport/model/FilterVersion.java#L111-L119 |
ksclarke/freelib-utils | src/main/java/info/freelibrary/util/XMLResourceBundle.java | XMLResourceBundle.get | public String get(final String aMessage, final File... aFileArray) {
final String[] details = new String[aFileArray.length];
for (int index = 0; index < details.length; index++) {
details[index] = aFileArray[index].getAbsolutePath();
}
LOGGER.debug(MessageCodes.UTIL_026, aMessage, details);
return StringUtils.format(super.getString(aMessage), details);
} | java | public String get(final String aMessage, final File... aFileArray) {
final String[] details = new String[aFileArray.length];
for (int index = 0; index < details.length; index++) {
details[index] = aFileArray[index].getAbsolutePath();
}
LOGGER.debug(MessageCodes.UTIL_026, aMessage, details);
return StringUtils.format(super.getString(aMessage), details);
} | [
"public",
"String",
"get",
"(",
"final",
"String",
"aMessage",
",",
"final",
"File",
"...",
"aFileArray",
")",
"{",
"final",
"String",
"[",
"]",
"details",
"=",
"new",
"String",
"[",
"aFileArray",
".",
"length",
"]",
";",
"for",
"(",
"int",
"index",
"=... | Returns the string form of the requested message with the file values integrated into it.
@param aMessage A message key to use to return a message value
@param aFileArray An array of files, whose names should be integrated into the message value
@return The message value with the supplied file names integrated | [
"Returns",
"the",
"string",
"form",
"of",
"the",
"requested",
"message",
"with",
"the",
"file",
"values",
"integrated",
"into",
"it",
"."
] | train | https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/XMLResourceBundle.java#L123-L132 |
Bedework/bw-util | bw-util-directory/src/main/java/org/bedework/util/directory/common/DirRecord.java | DirRecord.setAttr | public void setAttr(String attr, Object val) throws NamingException {
getAttributes().put(attr, val);
} | java | public void setAttr(String attr, Object val) throws NamingException {
getAttributes().put(attr, val);
} | [
"public",
"void",
"setAttr",
"(",
"String",
"attr",
",",
"Object",
"val",
")",
"throws",
"NamingException",
"{",
"getAttributes",
"(",
")",
".",
"put",
"(",
"attr",
",",
"val",
")",
";",
"}"
] | Set the attribute value in the table. Replaces any existing value(s)
This does not write back to the directory
@param attr
@param val
@throws NamingException | [
"Set",
"the",
"attribute",
"value",
"in",
"the",
"table",
".",
"Replaces",
"any",
"existing",
"value",
"(",
"s",
")",
"This",
"does",
"not",
"write",
"back",
"to",
"the",
"directory"
] | train | https://github.com/Bedework/bw-util/blob/f51de4af3d7eb88fe63a0e22be8898a16c6cc3ad/bw-util-directory/src/main/java/org/bedework/util/directory/common/DirRecord.java#L82-L84 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java | MutateInBuilder.arrayPrependAll | @Deprecated
public <T> MutateInBuilder arrayPrependAll(String path, Collection<T> values, boolean createPath) {
asyncBuilder.arrayPrependAll(path, values, new SubdocOptionsBuilder().createPath(createPath));
return this;
} | java | @Deprecated
public <T> MutateInBuilder arrayPrependAll(String path, Collection<T> values, boolean createPath) {
asyncBuilder.arrayPrependAll(path, values, new SubdocOptionsBuilder().createPath(createPath));
return this;
} | [
"@",
"Deprecated",
"public",
"<",
"T",
">",
"MutateInBuilder",
"arrayPrependAll",
"(",
"String",
"path",
",",
"Collection",
"<",
"T",
">",
"values",
",",
"boolean",
"createPath",
")",
"{",
"asyncBuilder",
".",
"arrayPrependAll",
"(",
"path",
",",
"values",
"... | Prepend multiple values at once in an existing array, pushing all values in the collection's iteration order to
the front/start of the array.
First value becomes the first element of the array, second value the second, etc... All existing values
are shifted right in the array, by the number of inserted elements.
Each item in the collection is inserted as an individual element of the array, but a bit of overhead
is saved compared to individual {@link #arrayPrepend(String, Object, boolean)} (String, Object)} by grouping
mutations in a single packet.
For example given an array [ A, B, C ], prepending the values X and Y yields [ X, Y, A, B, C ]
and not [ [ X, Y ], A, B, C ].
@param path the path of the array.
@param values the collection of values to insert at the front of the array as individual elements.
@param createPath true to create missing intermediary nodes.
@param <T> the type of data in the collection (must be JSON serializable). | [
"Prepend",
"multiple",
"values",
"at",
"once",
"in",
"an",
"existing",
"array",
"pushing",
"all",
"values",
"in",
"the",
"collection",
"s",
"iteration",
"order",
"to",
"the",
"front",
"/",
"start",
"of",
"the",
"array",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java#L744-L748 |
livetribe/livetribe-slp | core/src/main/java/org/livetribe/slp/da/StandardDirectoryAgentServer.java | StandardDirectoryAgentServer.handleTCPSrvDeReg | protected void handleTCPSrvDeReg(SrvDeReg srvDeReg, Socket socket)
{
try
{
boolean update = srvDeReg.isUpdating();
ServiceInfo service = ServiceInfo.from(srvDeReg);
uncacheService(service, update);
tcpSrvAck.perform(socket, srvDeReg, SLPError.NO_ERROR);
}
catch (ServiceLocationException x)
{
tcpSrvAck.perform(socket, srvDeReg, x.getSLPError());
}
} | java | protected void handleTCPSrvDeReg(SrvDeReg srvDeReg, Socket socket)
{
try
{
boolean update = srvDeReg.isUpdating();
ServiceInfo service = ServiceInfo.from(srvDeReg);
uncacheService(service, update);
tcpSrvAck.perform(socket, srvDeReg, SLPError.NO_ERROR);
}
catch (ServiceLocationException x)
{
tcpSrvAck.perform(socket, srvDeReg, x.getSLPError());
}
} | [
"protected",
"void",
"handleTCPSrvDeReg",
"(",
"SrvDeReg",
"srvDeReg",
",",
"Socket",
"socket",
")",
"{",
"try",
"{",
"boolean",
"update",
"=",
"srvDeReg",
".",
"isUpdating",
"(",
")",
";",
"ServiceInfo",
"service",
"=",
"ServiceInfo",
".",
"from",
"(",
"srv... | Handles a unicast TCP SrvDeReg message arrived to this directory agent.
<br />
This directory agent will reply with an acknowledge containing the result of the deregistration.
@param srvDeReg the SrvDeReg message to handle
@param socket the socket connected to the client where to write the reply | [
"Handles",
"a",
"unicast",
"TCP",
"SrvDeReg",
"message",
"arrived",
"to",
"this",
"directory",
"agent",
".",
"<br",
"/",
">",
"This",
"directory",
"agent",
"will",
"reply",
"with",
"an",
"acknowledge",
"containing",
"the",
"result",
"of",
"the",
"deregistratio... | train | https://github.com/livetribe/livetribe-slp/blob/6cc13dbe81feab133fe3dd291ca081cbc6e1f591/core/src/main/java/org/livetribe/slp/da/StandardDirectoryAgentServer.java#L594-L607 |
elki-project/elki | elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/BitsUtil.java | BitsUtil.onesI | public static void onesI(long[] v, int bits) {
final int fillWords = bits >>> LONG_LOG2_SIZE;
final int fillBits = bits & LONG_LOG2_MASK;
Arrays.fill(v, 0, fillWords, LONG_ALL_BITS);
if(fillBits > 0) {
v[fillWords] = (1L << fillBits) - 1;
}
if(fillWords + 1 < v.length) {
Arrays.fill(v, fillWords + 1, v.length, 0L);
}
} | java | public static void onesI(long[] v, int bits) {
final int fillWords = bits >>> LONG_LOG2_SIZE;
final int fillBits = bits & LONG_LOG2_MASK;
Arrays.fill(v, 0, fillWords, LONG_ALL_BITS);
if(fillBits > 0) {
v[fillWords] = (1L << fillBits) - 1;
}
if(fillWords + 1 < v.length) {
Arrays.fill(v, fillWords + 1, v.length, 0L);
}
} | [
"public",
"static",
"void",
"onesI",
"(",
"long",
"[",
"]",
"v",
",",
"int",
"bits",
")",
"{",
"final",
"int",
"fillWords",
"=",
"bits",
">>>",
"LONG_LOG2_SIZE",
";",
"final",
"int",
"fillBits",
"=",
"bits",
"&",
"LONG_LOG2_MASK",
";",
"Arrays",
".",
"... | Fill a vector initialized with "bits" ones.
@param v Vector to fill.
@param bits Size | [
"Fill",
"a",
"vector",
"initialized",
"with",
"bits",
"ones",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/BitsUtil.java#L443-L453 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java | ImgUtil.toBufferedImage | public static BufferedImage toBufferedImage(Image image, String imageType) {
BufferedImage bufferedImage;
if (false == imageType.equalsIgnoreCase(IMAGE_TYPE_PNG)) {
// 当目标为非PNG类图片时,源图片统一转换为RGB格式
if (image instanceof BufferedImage) {
bufferedImage = (BufferedImage) image;
if (BufferedImage.TYPE_INT_RGB != bufferedImage.getType()) {
bufferedImage = copyImage(image, BufferedImage.TYPE_INT_RGB);
}
} else {
bufferedImage = copyImage(image, BufferedImage.TYPE_INT_RGB);
}
} else {
bufferedImage = toBufferedImage(image);
}
return bufferedImage;
} | java | public static BufferedImage toBufferedImage(Image image, String imageType) {
BufferedImage bufferedImage;
if (false == imageType.equalsIgnoreCase(IMAGE_TYPE_PNG)) {
// 当目标为非PNG类图片时,源图片统一转换为RGB格式
if (image instanceof BufferedImage) {
bufferedImage = (BufferedImage) image;
if (BufferedImage.TYPE_INT_RGB != bufferedImage.getType()) {
bufferedImage = copyImage(image, BufferedImage.TYPE_INT_RGB);
}
} else {
bufferedImage = copyImage(image, BufferedImage.TYPE_INT_RGB);
}
} else {
bufferedImage = toBufferedImage(image);
}
return bufferedImage;
} | [
"public",
"static",
"BufferedImage",
"toBufferedImage",
"(",
"Image",
"image",
",",
"String",
"imageType",
")",
"{",
"BufferedImage",
"bufferedImage",
";",
"if",
"(",
"false",
"==",
"imageType",
".",
"equalsIgnoreCase",
"(",
"IMAGE_TYPE_PNG",
")",
")",
"{",
"// ... | {@link Image} 转 {@link BufferedImage}<br>
如果源图片的RGB模式与目标模式一致,则直接转换,否则重新绘制
@param image {@link Image}
@param imageType 目标图片类型
@return {@link BufferedImage}
@since 4.3.2 | [
"{",
"@link",
"Image",
"}",
"转",
"{",
"@link",
"BufferedImage",
"}",
"<br",
">",
"如果源图片的RGB模式与目标模式一致,则直接转换,否则重新绘制"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L1175-L1191 |
googleads/googleads-java-lib | modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/utils/v201809/shopping/ProductPartitionTreeImpl.java | ProductPartitionTreeImpl.createAdGroupTree | static ProductPartitionTreeImpl createAdGroupTree(AdWordsServicesInterface services,
AdWordsSession session, Long adGroupId) throws ApiException, RemoteException {
// Get the AdGroupCriterionService.
AdGroupCriterionServiceInterface criterionService =
services.get(session, AdGroupCriterionServiceInterface.class);
SelectorBuilder selectorBuilder = new SelectorBuilder()
.fields(REQUIRED_SELECTOR_FIELD_ENUMS.toArray(
new AdGroupCriterionField[REQUIRED_SELECTOR_FIELD_ENUMS.size()]))
.equals(AdGroupCriterionField.AdGroupId, adGroupId.toString())
.equals(AdGroupCriterionField.CriteriaType, "PRODUCT_PARTITION")
.in(
AdGroupCriterionField.Status,
UserStatus.ENABLED.getValue(),
UserStatus.PAUSED.getValue())
.limit(PAGE_SIZE);
AdGroupCriterionPage adGroupCriterionPage;
// A multimap from each product partition ID to its direct children.
ListMultimap<Long, AdGroupCriterion> parentIdMap = LinkedListMultimap.create();
int offset = 0;
do {
// Get the next page of results.
adGroupCriterionPage = criterionService.get(selectorBuilder.build());
if (adGroupCriterionPage != null && adGroupCriterionPage.getEntries() != null) {
for (AdGroupCriterion adGroupCriterion : adGroupCriterionPage.getEntries()) {
ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion();
parentIdMap.put(partition.getParentCriterionId(), adGroupCriterion);
}
offset += adGroupCriterionPage.getEntries().length;
selectorBuilder.increaseOffsetBy(PAGE_SIZE);
}
} while (offset < adGroupCriterionPage.getTotalNumEntries());
// Construct the ProductPartitionTree from the parentIdMap.
if (!parentIdMap.containsKey(null)) {
Preconditions.checkState(parentIdMap.isEmpty(),
"No root criterion found in the tree but the tree is not empty");
return createEmptyAdGroupTree(adGroupId,
getAdGroupBiddingStrategyConfiguration(services, session, adGroupId));
}
return createNonEmptyAdGroupTree(adGroupId, parentIdMap);
} | java | static ProductPartitionTreeImpl createAdGroupTree(AdWordsServicesInterface services,
AdWordsSession session, Long adGroupId) throws ApiException, RemoteException {
// Get the AdGroupCriterionService.
AdGroupCriterionServiceInterface criterionService =
services.get(session, AdGroupCriterionServiceInterface.class);
SelectorBuilder selectorBuilder = new SelectorBuilder()
.fields(REQUIRED_SELECTOR_FIELD_ENUMS.toArray(
new AdGroupCriterionField[REQUIRED_SELECTOR_FIELD_ENUMS.size()]))
.equals(AdGroupCriterionField.AdGroupId, adGroupId.toString())
.equals(AdGroupCriterionField.CriteriaType, "PRODUCT_PARTITION")
.in(
AdGroupCriterionField.Status,
UserStatus.ENABLED.getValue(),
UserStatus.PAUSED.getValue())
.limit(PAGE_SIZE);
AdGroupCriterionPage adGroupCriterionPage;
// A multimap from each product partition ID to its direct children.
ListMultimap<Long, AdGroupCriterion> parentIdMap = LinkedListMultimap.create();
int offset = 0;
do {
// Get the next page of results.
adGroupCriterionPage = criterionService.get(selectorBuilder.build());
if (adGroupCriterionPage != null && adGroupCriterionPage.getEntries() != null) {
for (AdGroupCriterion adGroupCriterion : adGroupCriterionPage.getEntries()) {
ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion();
parentIdMap.put(partition.getParentCriterionId(), adGroupCriterion);
}
offset += adGroupCriterionPage.getEntries().length;
selectorBuilder.increaseOffsetBy(PAGE_SIZE);
}
} while (offset < adGroupCriterionPage.getTotalNumEntries());
// Construct the ProductPartitionTree from the parentIdMap.
if (!parentIdMap.containsKey(null)) {
Preconditions.checkState(parentIdMap.isEmpty(),
"No root criterion found in the tree but the tree is not empty");
return createEmptyAdGroupTree(adGroupId,
getAdGroupBiddingStrategyConfiguration(services, session, adGroupId));
}
return createNonEmptyAdGroupTree(adGroupId, parentIdMap);
} | [
"static",
"ProductPartitionTreeImpl",
"createAdGroupTree",
"(",
"AdWordsServicesInterface",
"services",
",",
"AdWordsSession",
"session",
",",
"Long",
"adGroupId",
")",
"throws",
"ApiException",
",",
"RemoteException",
"{",
"// Get the AdGroupCriterionService.",
"AdGroupCriteri... | Returns a new instance of this class by retrieving the product partitions of the
specified ad group. All parameters are required. | [
"Returns",
"a",
"new",
"instance",
"of",
"this",
"class",
"by",
"retrieving",
"the",
"product",
"partitions",
"of",
"the",
"specified",
"ad",
"group",
".",
"All",
"parameters",
"are",
"required",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/utils/v201809/shopping/ProductPartitionTreeImpl.java#L185-L230 |
aws/aws-sdk-java | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/ContentCryptoScheme.java | ContentCryptoScheme.createCipherLite | CipherLite createCipherLite(SecretKey cek, byte[] iv, int cipherMode,
Provider provider, boolean alwaysUseProvider) {
try {
Cipher cipher = createCipher(provider, alwaysUseProvider);
cipher.init(cipherMode, cek, new IvParameterSpec(iv));
return newCipherLite(cipher, cek, cipherMode);
} catch (Exception e) {
throw e instanceof RuntimeException
? (RuntimeException) e
: new SdkClientException(
"Unable to build cipher: "
+ e.getMessage()
+ "\nMake sure you have the JCE unlimited strength policy files installed and "
+ "configured for your JVM",
e);
}
} | java | CipherLite createCipherLite(SecretKey cek, byte[] iv, int cipherMode,
Provider provider, boolean alwaysUseProvider) {
try {
Cipher cipher = createCipher(provider, alwaysUseProvider);
cipher.init(cipherMode, cek, new IvParameterSpec(iv));
return newCipherLite(cipher, cek, cipherMode);
} catch (Exception e) {
throw e instanceof RuntimeException
? (RuntimeException) e
: new SdkClientException(
"Unable to build cipher: "
+ e.getMessage()
+ "\nMake sure you have the JCE unlimited strength policy files installed and "
+ "configured for your JVM",
e);
}
} | [
"CipherLite",
"createCipherLite",
"(",
"SecretKey",
"cek",
",",
"byte",
"[",
"]",
"iv",
",",
"int",
"cipherMode",
",",
"Provider",
"provider",
",",
"boolean",
"alwaysUseProvider",
")",
"{",
"try",
"{",
"Cipher",
"cipher",
"=",
"createCipher",
"(",
"provider",
... | Creates and initializes a {@link CipherLite} for content
encrypt/decryption.
@param cek
content encrypting key
@param iv
initialization vector
@param cipherMode
such as {@link Cipher#ENCRYPT_MODE}
@param provider
the security provider the user specified. For backwards
compatibility, if this scheme defines a preferred provider,
the user-specified provider is by default ignored.
@param alwaysUseProvider
if true, always use the user-specified provider above, even
if this scheme has a preferred provider.
@return the cipher lite created and initialized. | [
"Creates",
"and",
"initializes",
"a",
"{",
"@link",
"CipherLite",
"}",
"for",
"content",
"encrypt",
"/",
"decryption",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/ContentCryptoScheme.java#L182-L199 |
radkovo/CSSBox | src/main/java/org/fit/cssbox/demo/ImageRenderer.java | ImageRenderer.writeSVG | protected void writeSVG(Viewport vp, Writer out) throws IOException
{
//obtain the viewport bounds depending on whether we are clipping to viewport size or using the whole page
int w = vp.getClippedContentBounds().width;
int h = vp.getClippedContentBounds().height;
SVGRenderer render = new SVGRenderer(w, h, out);
vp.draw(render);
render.close();
} | java | protected void writeSVG(Viewport vp, Writer out) throws IOException
{
//obtain the viewport bounds depending on whether we are clipping to viewport size or using the whole page
int w = vp.getClippedContentBounds().width;
int h = vp.getClippedContentBounds().height;
SVGRenderer render = new SVGRenderer(w, h, out);
vp.draw(render);
render.close();
} | [
"protected",
"void",
"writeSVG",
"(",
"Viewport",
"vp",
",",
"Writer",
"out",
")",
"throws",
"IOException",
"{",
"//obtain the viewport bounds depending on whether we are clipping to viewport size or using the whole page",
"int",
"w",
"=",
"vp",
".",
"getClippedContentBounds",
... | Renders the viewport using an SVGRenderer to the given output writer.
@param vp
@param out
@throws IOException | [
"Renders",
"the",
"viewport",
"using",
"an",
"SVGRenderer",
"to",
"the",
"given",
"output",
"writer",
"."
] | train | https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/demo/ImageRenderer.java#L164-L173 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/TagsApi.java | TagsApi.getTag | public Tag getTag(Object projectIdOrPath, String tagName) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "repository", "tags", tagName);
return (response.readEntity(Tag.class));
} | java | public Tag getTag(Object projectIdOrPath, String tagName) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "repository", "tags", tagName);
return (response.readEntity(Tag.class));
} | [
"public",
"Tag",
"getTag",
"(",
"Object",
"projectIdOrPath",
",",
"String",
"tagName",
")",
"throws",
"GitLabApiException",
"{",
"Response",
"response",
"=",
"get",
"(",
"Response",
".",
"Status",
".",
"OK",
",",
"null",
",",
"\"projects\"",
",",
"getProjectId... | Get a specific repository tag determined by its name.
<pre><code>GitLab Endpoint: GET /projects/:id/repository/tags/:tagName</code></pre>
@param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path
@param tagName the name of the tag to fetch the info for
@return a Tag instance with info on the specified tag
@throws GitLabApiException if any exception occurs | [
"Get",
"a",
"specific",
"repository",
"tag",
"determined",
"by",
"its",
"name",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/TagsApi.java#L96-L99 |
actorapp/actor-platform | actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/encryption/SessionManagerActor.java | SessionManagerActor.pickSession | public Promise<PeerSession> pickSession(final int uid,
final int keyGroupId,
final long ownKeyId,
final long theirKeyId) {
return pickCachedSession(uid, keyGroupId, ownKeyId, theirKeyId)
.fallback(new Function<Exception, Promise<PeerSession>>() {
@Override
public Promise<PeerSession> apply(Exception e) {
return Promises.tuple(
keyManager.getOwnIdentity(),
keyManager.getOwnPreKey(ownKeyId),
keyManager.getUserKeyGroups(uid),
keyManager.getUserPreKey(uid, keyGroupId, theirKeyId))
.map(new FunctionTupled4<KeyManagerActor.OwnIdentity, PrivateKey, UserKeys, PublicKey, PeerSession>() {
@Override
public PeerSession apply(KeyManagerActor.OwnIdentity ownIdentity, PrivateKey ownPreKey, UserKeys userKeys, PublicKey theirPreKey) {
UserKeysGroup keysGroup = ManagedList.of(userKeys.getUserKeysGroups())
.filter(UserKeysGroup.BY_KEY_GROUP(keyGroupId))
.first();
return spawnSession(uid,
ownIdentity.getKeyGroup(),
keyGroupId,
ownIdentity.getIdentityKey(),
keysGroup.getIdentityKey(),
ownPreKey,
theirPreKey);
}
});
}
});
} | java | public Promise<PeerSession> pickSession(final int uid,
final int keyGroupId,
final long ownKeyId,
final long theirKeyId) {
return pickCachedSession(uid, keyGroupId, ownKeyId, theirKeyId)
.fallback(new Function<Exception, Promise<PeerSession>>() {
@Override
public Promise<PeerSession> apply(Exception e) {
return Promises.tuple(
keyManager.getOwnIdentity(),
keyManager.getOwnPreKey(ownKeyId),
keyManager.getUserKeyGroups(uid),
keyManager.getUserPreKey(uid, keyGroupId, theirKeyId))
.map(new FunctionTupled4<KeyManagerActor.OwnIdentity, PrivateKey, UserKeys, PublicKey, PeerSession>() {
@Override
public PeerSession apply(KeyManagerActor.OwnIdentity ownIdentity, PrivateKey ownPreKey, UserKeys userKeys, PublicKey theirPreKey) {
UserKeysGroup keysGroup = ManagedList.of(userKeys.getUserKeysGroups())
.filter(UserKeysGroup.BY_KEY_GROUP(keyGroupId))
.first();
return spawnSession(uid,
ownIdentity.getKeyGroup(),
keyGroupId,
ownIdentity.getIdentityKey(),
keysGroup.getIdentityKey(),
ownPreKey,
theirPreKey);
}
});
}
});
} | [
"public",
"Promise",
"<",
"PeerSession",
">",
"pickSession",
"(",
"final",
"int",
"uid",
",",
"final",
"int",
"keyGroupId",
",",
"final",
"long",
"ownKeyId",
",",
"final",
"long",
"theirKeyId",
")",
"{",
"return",
"pickCachedSession",
"(",
"uid",
",",
"keyGr... | Pick session for specific keys
@param uid User's id
@param keyGroupId User's key group
@param ownKeyId Own Pre Key id
@param theirKeyId Their Pre Key id | [
"Pick",
"session",
"for",
"specific",
"keys"
] | train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/encryption/SessionManagerActor.java#L126-L159 |
amplexus/java-flac-encoder | src/main/java/net/sourceforge/javaflacencoder/FLACStreamController.java | FLACStreamController.closeFLACStream | public void closeFLACStream(byte[] md5Hash, StreamConfiguration streamConfig)
throws IOException {
//reset position in output stream to beginning.
//re-write the updated stream info.
streamLock.lock();
try {
if(!flacStreamIsOpen)
throw new IllegalStateException("Error. Cannot close a non-opened stream");
StreamConfiguration tempSC = new StreamConfiguration(streamConfig);
tempSC.setMaxBlockSize(maxBlockSize);
tempSC.setMinBlockSize(minBlockSize);
EncodedElement streamInfo = MetadataBlockStreamInfo.getStreamInfo(
tempSC, minFrameSize, maxFrameSize, samplesInStream, md5Hash);
if(out.canSeek()) {
out.seek(streamHeaderPos);
this.writeDataToOutput(streamInfo);
}
flacStreamIsOpen = false;
out.close();
} finally {
streamLock.unlock();
}
} | java | public void closeFLACStream(byte[] md5Hash, StreamConfiguration streamConfig)
throws IOException {
//reset position in output stream to beginning.
//re-write the updated stream info.
streamLock.lock();
try {
if(!flacStreamIsOpen)
throw new IllegalStateException("Error. Cannot close a non-opened stream");
StreamConfiguration tempSC = new StreamConfiguration(streamConfig);
tempSC.setMaxBlockSize(maxBlockSize);
tempSC.setMinBlockSize(minBlockSize);
EncodedElement streamInfo = MetadataBlockStreamInfo.getStreamInfo(
tempSC, minFrameSize, maxFrameSize, samplesInStream, md5Hash);
if(out.canSeek()) {
out.seek(streamHeaderPos);
this.writeDataToOutput(streamInfo);
}
flacStreamIsOpen = false;
out.close();
} finally {
streamLock.unlock();
}
} | [
"public",
"void",
"closeFLACStream",
"(",
"byte",
"[",
"]",
"md5Hash",
",",
"StreamConfiguration",
"streamConfig",
")",
"throws",
"IOException",
"{",
"//reset position in output stream to beginning.",
"//re-write the updated stream info.",
"streamLock",
".",
"lock",
"(",
")... | Close the current FLAC stream. Updates the stream header information.
If called on a closed stream, operation is undefined. Do not do this. | [
"Close",
"the",
"current",
"FLAC",
"stream",
".",
"Updates",
"the",
"stream",
"header",
"information",
".",
"If",
"called",
"on",
"a",
"closed",
"stream",
"operation",
"is",
"undefined",
".",
"Do",
"not",
"do",
"this",
"."
] | train | https://github.com/amplexus/java-flac-encoder/blob/3d536b877dee2a3fd4ab2e0d9569e292cae93bc9/src/main/java/net/sourceforge/javaflacencoder/FLACStreamController.java#L94-L116 |
samskivert/samskivert | src/main/java/com/samskivert/swing/RadialLabelSausage.java | RadialLabelSausage.drawBase | @Override
protected void drawBase (Graphics2D gfx, int x, int y)
{
if (_active) {
// render the sausage
super.drawBase(gfx, x, y);
} else {
// render the circle
gfx.fillOval(x, y, closedBounds.width - 1, closedBounds.height - 1);
}
} | java | @Override
protected void drawBase (Graphics2D gfx, int x, int y)
{
if (_active) {
// render the sausage
super.drawBase(gfx, x, y);
} else {
// render the circle
gfx.fillOval(x, y, closedBounds.width - 1, closedBounds.height - 1);
}
} | [
"@",
"Override",
"protected",
"void",
"drawBase",
"(",
"Graphics2D",
"gfx",
",",
"int",
"x",
",",
"int",
"y",
")",
"{",
"if",
"(",
"_active",
")",
"{",
"// render the sausage",
"super",
".",
"drawBase",
"(",
"gfx",
",",
"x",
",",
"y",
")",
";",
"}",
... | Draw the base circle or sausage within which all the other
decorations are added. | [
"Draw",
"the",
"base",
"circle",
"or",
"sausage",
"within",
"which",
"all",
"the",
"other",
"decorations",
"are",
"added",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/RadialLabelSausage.java#L162-L173 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DiagnosticsInner.java | DiagnosticsInner.listSiteDetectorsAsync | public Observable<Page<DetectorDefinitionInner>> listSiteDetectorsAsync(final String resourceGroupName, final String siteName, final String diagnosticCategory) {
return listSiteDetectorsWithServiceResponseAsync(resourceGroupName, siteName, diagnosticCategory)
.map(new Func1<ServiceResponse<Page<DetectorDefinitionInner>>, Page<DetectorDefinitionInner>>() {
@Override
public Page<DetectorDefinitionInner> call(ServiceResponse<Page<DetectorDefinitionInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<DetectorDefinitionInner>> listSiteDetectorsAsync(final String resourceGroupName, final String siteName, final String diagnosticCategory) {
return listSiteDetectorsWithServiceResponseAsync(resourceGroupName, siteName, diagnosticCategory)
.map(new Func1<ServiceResponse<Page<DetectorDefinitionInner>>, Page<DetectorDefinitionInner>>() {
@Override
public Page<DetectorDefinitionInner> call(ServiceResponse<Page<DetectorDefinitionInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"DetectorDefinitionInner",
">",
">",
"listSiteDetectorsAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"siteName",
",",
"final",
"String",
"diagnosticCategory",
")",
"{",
"return",
"listSiteDetecto... | Get Detectors.
Get Detectors.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param siteName Site Name
@param diagnosticCategory Diagnostic Category
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<DetectorDefinitionInner> object | [
"Get",
"Detectors",
".",
"Get",
"Detectors",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DiagnosticsInner.java#L896-L904 |
OpenNTF/JavascriptAggregator | jaggr-core/src/main/java/com/ibm/jaggr/core/impl/modulebuilder/javascript/IdentitySourceMapGenerator.java | IdentitySourceMapGenerator.processNode | private void processNode(Node node) throws IOException {
for (Node cursor = node.getFirstChild(); cursor != null; cursor = cursor.getNext()) {
int lineno = cursor.getLineno()-1; // adjust for rhino line numbers being 1 based
int charno = cursor.getCharno();
if (lineno > currentLine || lineno == currentLine && charno > currentChar) {
currentLine = lineno;
currentChar = charno;
}
FilePosition endPosition = getEndPosition(cursor);
sgen.addMapping(name, null,
new FilePosition(currentLine, currentChar),
new FilePosition(currentLine, currentChar),
endPosition);
if (cursor.hasChildren()) {
processNode(cursor);
}
}
} | java | private void processNode(Node node) throws IOException {
for (Node cursor = node.getFirstChild(); cursor != null; cursor = cursor.getNext()) {
int lineno = cursor.getLineno()-1; // adjust for rhino line numbers being 1 based
int charno = cursor.getCharno();
if (lineno > currentLine || lineno == currentLine && charno > currentChar) {
currentLine = lineno;
currentChar = charno;
}
FilePosition endPosition = getEndPosition(cursor);
sgen.addMapping(name, null,
new FilePosition(currentLine, currentChar),
new FilePosition(currentLine, currentChar),
endPosition);
if (cursor.hasChildren()) {
processNode(cursor);
}
}
} | [
"private",
"void",
"processNode",
"(",
"Node",
"node",
")",
"throws",
"IOException",
"{",
"for",
"(",
"Node",
"cursor",
"=",
"node",
".",
"getFirstChild",
"(",
")",
";",
"cursor",
"!=",
"null",
";",
"cursor",
"=",
"cursor",
".",
"getNext",
"(",
")",
")... | Recursively processes the input node, adding a mapping for the node to the source map
generator.
@param node
the node to map
@throws IOException | [
"Recursively",
"processes",
"the",
"input",
"node",
"adding",
"a",
"mapping",
"for",
"the",
"node",
"to",
"the",
"source",
"map",
"generator",
"."
] | train | https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/modulebuilder/javascript/IdentitySourceMapGenerator.java#L106-L123 |
glyptodon/guacamole-client | guacamole-ext/src/main/java/org/apache/guacamole/net/auth/credentials/UserCredentials.java | UserCredentials.setValue | public String setValue(String name, String value) {
return values.put(name, value);
} | java | public String setValue(String name, String value) {
return values.put(name, value);
} | [
"public",
"String",
"setValue",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"return",
"values",
".",
"put",
"(",
"name",
",",
"value",
")",
";",
"}"
] | Sets the value of the field having the given name. Any existing value
for that field is replaced.
@param name
The name of the field whose value should be assigned.
@param value
The value to assign to the field having the given name.
@return
The previous value of the field, or null if the value of the field
was not previously defined. | [
"Sets",
"the",
"value",
"of",
"the",
"field",
"having",
"the",
"given",
"name",
".",
"Any",
"existing",
"value",
"for",
"that",
"field",
"is",
"replaced",
"."
] | train | https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/guacamole-ext/src/main/java/org/apache/guacamole/net/auth/credentials/UserCredentials.java#L164-L166 |
radkovo/CSSBox | src/main/java/org/fit/cssbox/layout/BoxFactory.java | BoxFactory.createAnonymousBox | protected ElementBox createAnonymousBox(ElementBox parent, Box child, boolean block)
{
ElementBox anbox;
if (block)
{
Element anelem = createAnonymousElement(child.getNode().getOwnerDocument(), "Xdiv", "block");
anbox = new BlockBox(anelem, (Graphics2D) child.getGraphics().create(), child.getVisualContext().create());
anbox.setViewport(viewport);
anbox.setStyle(createAnonymousStyle("block"));
((BlockBox) anbox).contblock = false;
anbox.isblock = true;
}
else
{
Element anelem = createAnonymousElement(child.getNode().getOwnerDocument(), "Xspan", "inline");
anbox = new InlineBox(anelem, (Graphics2D) child.getGraphics().create(), child.getVisualContext().create());
anbox.setViewport(viewport);
anbox.setStyle(createAnonymousStyle("inline"));
anbox.isblock = false;
}
if (parent != null)
{
computeInheritedStyle(anbox, parent);
anbox.setParent(parent);
}
anbox.setOrder(next_order++);
anbox.isempty = true;
anbox.setBase(child.getBase());
anbox.setContainingBlockBox(child.getContainingBlockBox());
anbox.setClipBlock(child.getClipBlock());
return anbox;
} | java | protected ElementBox createAnonymousBox(ElementBox parent, Box child, boolean block)
{
ElementBox anbox;
if (block)
{
Element anelem = createAnonymousElement(child.getNode().getOwnerDocument(), "Xdiv", "block");
anbox = new BlockBox(anelem, (Graphics2D) child.getGraphics().create(), child.getVisualContext().create());
anbox.setViewport(viewport);
anbox.setStyle(createAnonymousStyle("block"));
((BlockBox) anbox).contblock = false;
anbox.isblock = true;
}
else
{
Element anelem = createAnonymousElement(child.getNode().getOwnerDocument(), "Xspan", "inline");
anbox = new InlineBox(anelem, (Graphics2D) child.getGraphics().create(), child.getVisualContext().create());
anbox.setViewport(viewport);
anbox.setStyle(createAnonymousStyle("inline"));
anbox.isblock = false;
}
if (parent != null)
{
computeInheritedStyle(anbox, parent);
anbox.setParent(parent);
}
anbox.setOrder(next_order++);
anbox.isempty = true;
anbox.setBase(child.getBase());
anbox.setContainingBlockBox(child.getContainingBlockBox());
anbox.setClipBlock(child.getClipBlock());
return anbox;
} | [
"protected",
"ElementBox",
"createAnonymousBox",
"(",
"ElementBox",
"parent",
",",
"Box",
"child",
",",
"boolean",
"block",
")",
"{",
"ElementBox",
"anbox",
";",
"if",
"(",
"block",
")",
"{",
"Element",
"anelem",
"=",
"createAnonymousElement",
"(",
"child",
".... | Creates an empty anonymous block or inline box that can be placed between an optional parent and its child.
The corresponding properties of the box are taken from the child. The child is inserted NOT as the child box of the new box.
The new box is NOT inserted as a subbox of the parent.
@param parent an optional parent node. When used, the parent of the new box is set to this node and the style is inherited from the parent.
@param child the child node
@param block when set to <code>true</code>, a {@link BlockBox} is created. Otherwise, a {@link InlineBox} is created.
@return the new created block box | [
"Creates",
"an",
"empty",
"anonymous",
"block",
"or",
"inline",
"box",
"that",
"can",
"be",
"placed",
"between",
"an",
"optional",
"parent",
"and",
"its",
"child",
".",
"The",
"corresponding",
"properties",
"of",
"the",
"box",
"are",
"taken",
"from",
"the",
... | train | https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/layout/BoxFactory.java#L786-L817 |
GerdHolz/TOVAL | src/de/invation/code/toval/misc/ArrayUtils.java | ArrayUtils.arrayContainsEq | public static <T> boolean arrayContainsEq(T[] array, T value) {
for (int i = 0; i < array.length; i++) {
if (array[i].equals(value)) {
return true;
}
}
return false;
} | java | public static <T> boolean arrayContainsEq(T[] array, T value) {
for (int i = 0; i < array.length; i++) {
if (array[i].equals(value)) {
return true;
}
}
return false;
} | [
"public",
"static",
"<",
"T",
">",
"boolean",
"arrayContainsEq",
"(",
"T",
"[",
"]",
"array",
",",
"T",
"value",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"array",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"array",
... | Checks if the given array contains the specified value.<br>
This method works with the equals method.
@param <T>
Type of array elements and <code>value</code>
@param array
Array to examine
@param value
Value to search
@return <code>true</code> if <code>array</code> contains
<code>value</code>, <code>false</code> otherwise | [
"Checks",
"if",
"the",
"given",
"array",
"contains",
"the",
"specified",
"value",
".",
"<br",
">",
"This",
"method",
"works",
"with",
"the",
"equals",
"method",
"."
] | train | https://github.com/GerdHolz/TOVAL/blob/036922cdfd710fa53b18e5dbe1e07f226f731fde/src/de/invation/code/toval/misc/ArrayUtils.java#L256-L263 |
mabe02/lanterna | src/main/java/com/googlecode/lanterna/TextCharacter.java | TextCharacter.withCharacter | @SuppressWarnings("SameParameterValue")
public TextCharacter withCharacter(char character) {
if(this.character == character) {
return this;
}
return new TextCharacter(character, foregroundColor, backgroundColor, modifiers);
} | java | @SuppressWarnings("SameParameterValue")
public TextCharacter withCharacter(char character) {
if(this.character == character) {
return this;
}
return new TextCharacter(character, foregroundColor, backgroundColor, modifiers);
} | [
"@",
"SuppressWarnings",
"(",
"\"SameParameterValue\"",
")",
"public",
"TextCharacter",
"withCharacter",
"(",
"char",
"character",
")",
"{",
"if",
"(",
"this",
".",
"character",
"==",
"character",
")",
"{",
"return",
"this",
";",
"}",
"return",
"new",
"TextCha... | Returns a new TextCharacter with the same colors and modifiers but a different underlying character
@param character Character the copy should have
@return Copy of this TextCharacter with different underlying character | [
"Returns",
"a",
"new",
"TextCharacter",
"with",
"the",
"same",
"colors",
"and",
"modifiers",
"but",
"a",
"different",
"underlying",
"character"
] | train | https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/TextCharacter.java#L212-L218 |
chhh/MSFTBX | MSFileToolbox/src/main/java/umich/ms/util/ZlibInflater.java | ZlibInflater.zlibUncompressBuffer | public static ByteArrayHolder zlibUncompressBuffer(byte[] bytes, int length,
Integer uncompressedLen) throws
IOException, DataFormatException, FileParsingException {
Inflater inflater = new Inflater();
inflater.setInput(bytes, 0, length);
int bufSize = uncompressedLen == null ? length * 2 : uncompressedLen;
ByteArrayHolder bah = null;
try {
bah = pool.borrowObject();
} catch (Exception e) {
throw new FileParsingException("Could not borrow ByteArrayHolder from the pool.", e);
}
try {
// Decompress the data
int pos = 0;
// at the beginning we can afford to just allocate a new buffer, if the one we got was not enough
bah.ensureCapacity(bufSize, false);
while (!inflater.finished()) {
if (pos != 0) {
// when pos>0, it means we were not able to decompress the whole thing
// in one iteration, meaning there is something left in the input buffer
// but most likely not much, so we won't be overzealous about
// additional space allocation
//System.out.println("RAN OUT OF SPACE IN INFLATER!");
bah.ensureHasSpace(length / 2);
}
pos += inflater.inflate(bah.getUnderlyingBytes(), pos, bah.getCapacityLeft());
bah.setPosition(pos);
}
} finally {
inflater.end();
}
return bah;
} | java | public static ByteArrayHolder zlibUncompressBuffer(byte[] bytes, int length,
Integer uncompressedLen) throws
IOException, DataFormatException, FileParsingException {
Inflater inflater = new Inflater();
inflater.setInput(bytes, 0, length);
int bufSize = uncompressedLen == null ? length * 2 : uncompressedLen;
ByteArrayHolder bah = null;
try {
bah = pool.borrowObject();
} catch (Exception e) {
throw new FileParsingException("Could not borrow ByteArrayHolder from the pool.", e);
}
try {
// Decompress the data
int pos = 0;
// at the beginning we can afford to just allocate a new buffer, if the one we got was not enough
bah.ensureCapacity(bufSize, false);
while (!inflater.finished()) {
if (pos != 0) {
// when pos>0, it means we were not able to decompress the whole thing
// in one iteration, meaning there is something left in the input buffer
// but most likely not much, so we won't be overzealous about
// additional space allocation
//System.out.println("RAN OUT OF SPACE IN INFLATER!");
bah.ensureHasSpace(length / 2);
}
pos += inflater.inflate(bah.getUnderlyingBytes(), pos, bah.getCapacityLeft());
bah.setPosition(pos);
}
} finally {
inflater.end();
}
return bah;
} | [
"public",
"static",
"ByteArrayHolder",
"zlibUncompressBuffer",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"length",
",",
"Integer",
"uncompressedLen",
")",
"throws",
"IOException",
",",
"DataFormatException",
",",
"FileParsingException",
"{",
"Inflater",
"inflater",
... | Inflates zLib compressed byte[].
@param bytes zLib compressed bytes in a holder, with properly set position
@param length length of data in the input array to be used
@param uncompressedLen length of data in bytes when uncompressed. Optional.
@return inflated byte array, which is borrowed from pool ({@link #getPool() }). You MUST return
the byte holder back to the pool after usage.
@throws IOException should never happen, ByteArrayOutputStream is in-memory
@throws DataFormatException in case of malformed input byte array | [
"Inflates",
"zLib",
"compressed",
"byte",
"[]",
"."
] | train | https://github.com/chhh/MSFTBX/blob/e53ae6be982e2de3123292be7d5297715bec70bb/MSFileToolbox/src/main/java/umich/ms/util/ZlibInflater.java#L75-L112 |
daimajia/AndroidImageSlider | library/src/main/java/com/daimajia/slider/library/Transformers/BaseTransformer.java | BaseTransformer.onPostTransform | protected void onPostTransform(View view, float position) {
if(mCustomAnimationInterface != null){
if(position == -1 || position == 1){
mCustomAnimationInterface.onCurrentItemDisappear(view);
isApp = true;
}else if(position == 0){
mCustomAnimationInterface.onNextItemAppear(view);
isDis = true;
}
if(isApp && isDis){
h.clear();
isApp = false;
isDis = false;
}
}
} | java | protected void onPostTransform(View view, float position) {
if(mCustomAnimationInterface != null){
if(position == -1 || position == 1){
mCustomAnimationInterface.onCurrentItemDisappear(view);
isApp = true;
}else if(position == 0){
mCustomAnimationInterface.onNextItemAppear(view);
isDis = true;
}
if(isApp && isDis){
h.clear();
isApp = false;
isDis = false;
}
}
} | [
"protected",
"void",
"onPostTransform",
"(",
"View",
"view",
",",
"float",
"position",
")",
"{",
"if",
"(",
"mCustomAnimationInterface",
"!=",
"null",
")",
"{",
"if",
"(",
"position",
"==",
"-",
"1",
"||",
"position",
"==",
"1",
")",
"{",
"mCustomAnimation... | Called each {@link #transformPage(View, float)} call after {@link #onTransform(View, float)} is finished.
@param view
@param position | [
"Called",
"each",
"{",
"@link",
"#transformPage",
"(",
"View",
"float",
")",
"}",
"call",
"after",
"{",
"@link",
"#onTransform",
"(",
"View",
"float",
")",
"}",
"is",
"finished",
"."
] | train | https://github.com/daimajia/AndroidImageSlider/blob/e318cabdef668de985efdcc45ca304e2ac6f58b5/library/src/main/java/com/daimajia/slider/library/Transformers/BaseTransformer.java#L129-L144 |
lucee/Lucee | core/src/main/java/lucee/runtime/functions/decision/IsValid.java | IsValid.call | public static boolean call(PageContext pc, String type, Object value) throws ExpressionException {
type = type.trim();
if ("range".equalsIgnoreCase(type)) throw new FunctionException(pc, "isValid", 1, "type", "for [range] you have to define a min and max value");
if ("regex".equalsIgnoreCase(type) || "regular_expression".equalsIgnoreCase(type))
throw new FunctionException(pc, "isValid", 1, "type", "for [regex] you have to define a pattern");
return Decision.isValid(type, value);
} | java | public static boolean call(PageContext pc, String type, Object value) throws ExpressionException {
type = type.trim();
if ("range".equalsIgnoreCase(type)) throw new FunctionException(pc, "isValid", 1, "type", "for [range] you have to define a min and max value");
if ("regex".equalsIgnoreCase(type) || "regular_expression".equalsIgnoreCase(type))
throw new FunctionException(pc, "isValid", 1, "type", "for [regex] you have to define a pattern");
return Decision.isValid(type, value);
} | [
"public",
"static",
"boolean",
"call",
"(",
"PageContext",
"pc",
",",
"String",
"type",
",",
"Object",
"value",
")",
"throws",
"ExpressionException",
"{",
"type",
"=",
"type",
".",
"trim",
"(",
")",
";",
"if",
"(",
"\"range\"",
".",
"equalsIgnoreCase",
"("... | check for many diff types
@param pc
@param type
@param value
@return
@throws ExpressionException | [
"check",
"for",
"many",
"diff",
"types"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/functions/decision/IsValid.java#L46-L55 |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/SoyJsPluginUtils.java | SoyJsPluginUtils.genJsExprUsingSoySyntax | public static JsExpr genJsExprUsingSoySyntax(Operator op, List<JsExpr> operandJsExprs) {
List<Expression> operands =
Lists.transform(operandJsExprs, input -> fromExpr(input, ImmutableList.<GoogRequire>of()));
return Expression.operation(op, operands).assertExpr();
} | java | public static JsExpr genJsExprUsingSoySyntax(Operator op, List<JsExpr> operandJsExprs) {
List<Expression> operands =
Lists.transform(operandJsExprs, input -> fromExpr(input, ImmutableList.<GoogRequire>of()));
return Expression.operation(op, operands).assertExpr();
} | [
"public",
"static",
"JsExpr",
"genJsExprUsingSoySyntax",
"(",
"Operator",
"op",
",",
"List",
"<",
"JsExpr",
">",
"operandJsExprs",
")",
"{",
"List",
"<",
"Expression",
">",
"operands",
"=",
"Lists",
".",
"transform",
"(",
"operandJsExprs",
",",
"input",
"->",
... | Generates a JS expression for the given operator and operands. | [
"Generates",
"a",
"JS",
"expression",
"for",
"the",
"given",
"operator",
"and",
"operands",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/SoyJsPluginUtils.java#L57-L61 |
kaazing/gateway | resource.address/spi/src/main/java/org/kaazing/gateway/resource/address/uri/URIUtils.java | URIUtils.modifyURIAuthority | public static String modifyURIAuthority(String uri, String newAuthority) {
try {
URI uriObj = new URI(uri);
// code below modifies new authority considering also network interface syntax
Pattern pattern = Pattern.compile(NETWORK_INTERFACE_AUTHORITY);
Matcher matcher = pattern.matcher(newAuthority);
String matchedToken = MOCK_HOST;
// if newAuthority corresponds to NetworkInterfaceURI syntax
if (matcher.find()) {
matchedToken = matcher.group(0);
newAuthority = newAuthority.replace(matchedToken, MOCK_HOST);
}
URI modifiedURIAuthority = URLUtils.modifyURIAuthority(uriObj, newAuthority);
String uriWithModifiedAuthority = URIUtils.uriToString(modifiedURIAuthority).replace(MOCK_HOST, matchedToken);
return uriWithModifiedAuthority;
}
catch (URISyntaxException e) {
try {
return (new NetworkInterfaceURI(uri)).modifyURIAuthority(newAuthority);
}
catch (IllegalArgumentException ne) {
throw new IllegalArgumentException(ne.getMessage(), ne);
}
}
} | java | public static String modifyURIAuthority(String uri, String newAuthority) {
try {
URI uriObj = new URI(uri);
// code below modifies new authority considering also network interface syntax
Pattern pattern = Pattern.compile(NETWORK_INTERFACE_AUTHORITY);
Matcher matcher = pattern.matcher(newAuthority);
String matchedToken = MOCK_HOST;
// if newAuthority corresponds to NetworkInterfaceURI syntax
if (matcher.find()) {
matchedToken = matcher.group(0);
newAuthority = newAuthority.replace(matchedToken, MOCK_HOST);
}
URI modifiedURIAuthority = URLUtils.modifyURIAuthority(uriObj, newAuthority);
String uriWithModifiedAuthority = URIUtils.uriToString(modifiedURIAuthority).replace(MOCK_HOST, matchedToken);
return uriWithModifiedAuthority;
}
catch (URISyntaxException e) {
try {
return (new NetworkInterfaceURI(uri)).modifyURIAuthority(newAuthority);
}
catch (IllegalArgumentException ne) {
throw new IllegalArgumentException(ne.getMessage(), ne);
}
}
} | [
"public",
"static",
"String",
"modifyURIAuthority",
"(",
"String",
"uri",
",",
"String",
"newAuthority",
")",
"{",
"try",
"{",
"URI",
"uriObj",
"=",
"new",
"URI",
"(",
"uri",
")",
";",
"// code below modifies new authority considering also network interface syntax",
"... | Helper method for modifying URI authority
@param uri
@param newAuthority
@return | [
"Helper",
"method",
"for",
"modifying",
"URI",
"authority"
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/resource.address/spi/src/main/java/org/kaazing/gateway/resource/address/uri/URIUtils.java#L303-L327 |
Erudika/para | para-client/src/main/java/com/erudika/para/client/ParaClient.java | ParaClient.markdownToHtml | public String markdownToHtml(String markdownString) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("md", markdownString);
return getEntity(invokeGet("utils/md2html", params), String.class);
} | java | public String markdownToHtml(String markdownString) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("md", markdownString);
return getEntity(invokeGet("utils/md2html", params), String.class);
} | [
"public",
"String",
"markdownToHtml",
"(",
"String",
"markdownString",
")",
"{",
"MultivaluedMap",
"<",
"String",
",",
"String",
">",
"params",
"=",
"new",
"MultivaluedHashMap",
"<>",
"(",
")",
";",
"params",
".",
"putSingle",
"(",
"\"md\"",
",",
"markdownStri... | Converts Markdown to HTML.
@param markdownString Markdown
@return HTML | [
"Converts",
"Markdown",
"to",
"HTML",
"."
] | train | https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-client/src/main/java/com/erudika/para/client/ParaClient.java#L1232-L1236 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPInstancePersistenceImpl.java | CPInstancePersistenceImpl.countByC_C | @Override
public int countByC_C(long CPDefinitionId, String CPInstanceUuid) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_C_C;
Object[] finderArgs = new Object[] { CPDefinitionId, CPInstanceUuid };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_CPINSTANCE_WHERE);
query.append(_FINDER_COLUMN_C_C_CPDEFINITIONID_2);
boolean bindCPInstanceUuid = false;
if (CPInstanceUuid == null) {
query.append(_FINDER_COLUMN_C_C_CPINSTANCEUUID_1);
}
else if (CPInstanceUuid.equals("")) {
query.append(_FINDER_COLUMN_C_C_CPINSTANCEUUID_3);
}
else {
bindCPInstanceUuid = true;
query.append(_FINDER_COLUMN_C_C_CPINSTANCEUUID_2);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(CPDefinitionId);
if (bindCPInstanceUuid) {
qPos.add(CPInstanceUuid);
}
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
} | java | @Override
public int countByC_C(long CPDefinitionId, String CPInstanceUuid) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_C_C;
Object[] finderArgs = new Object[] { CPDefinitionId, CPInstanceUuid };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_CPINSTANCE_WHERE);
query.append(_FINDER_COLUMN_C_C_CPDEFINITIONID_2);
boolean bindCPInstanceUuid = false;
if (CPInstanceUuid == null) {
query.append(_FINDER_COLUMN_C_C_CPINSTANCEUUID_1);
}
else if (CPInstanceUuid.equals("")) {
query.append(_FINDER_COLUMN_C_C_CPINSTANCEUUID_3);
}
else {
bindCPInstanceUuid = true;
query.append(_FINDER_COLUMN_C_C_CPINSTANCEUUID_2);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(CPDefinitionId);
if (bindCPInstanceUuid) {
qPos.add(CPInstanceUuid);
}
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
} | [
"@",
"Override",
"public",
"int",
"countByC_C",
"(",
"long",
"CPDefinitionId",
",",
"String",
"CPInstanceUuid",
")",
"{",
"FinderPath",
"finderPath",
"=",
"FINDER_PATH_COUNT_BY_C_C",
";",
"Object",
"[",
"]",
"finderArgs",
"=",
"new",
"Object",
"[",
"]",
"{",
"... | Returns the number of cp instances where CPDefinitionId = ? and CPInstanceUuid = ?.
@param CPDefinitionId the cp definition ID
@param CPInstanceUuid the cp instance uuid
@return the number of matching cp instances | [
"Returns",
"the",
"number",
"of",
"cp",
"instances",
"where",
"CPDefinitionId",
"=",
"?",
";",
"and",
"CPInstanceUuid",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPInstancePersistenceImpl.java#L4248-L4309 |
apache/flink | flink-java/src/main/java/org/apache/flink/api/java/ExecutionEnvironment.java | ExecutionEnvironment.createRemoteEnvironment | public static ExecutionEnvironment createRemoteEnvironment(String host, int port, int parallelism, String... jarFiles) {
RemoteEnvironment rec = new RemoteEnvironment(host, port, jarFiles);
rec.setParallelism(parallelism);
return rec;
} | java | public static ExecutionEnvironment createRemoteEnvironment(String host, int port, int parallelism, String... jarFiles) {
RemoteEnvironment rec = new RemoteEnvironment(host, port, jarFiles);
rec.setParallelism(parallelism);
return rec;
} | [
"public",
"static",
"ExecutionEnvironment",
"createRemoteEnvironment",
"(",
"String",
"host",
",",
"int",
"port",
",",
"int",
"parallelism",
",",
"String",
"...",
"jarFiles",
")",
"{",
"RemoteEnvironment",
"rec",
"=",
"new",
"RemoteEnvironment",
"(",
"host",
",",
... | Creates a {@link RemoteEnvironment}. The remote environment sends (parts of) the program
to a cluster for execution. Note that all file paths used in the program must be accessible from the
cluster. The execution will use the specified parallelism.
@param host The host name or address of the master (JobManager), where the program should be executed.
@param port The port of the master (JobManager), where the program should be executed.
@param parallelism The parallelism to use during the execution.
@param jarFiles The JAR files with code that needs to be shipped to the cluster. If the program uses
user-defined functions, user-defined input formats, or any libraries, those must be
provided in the JAR files.
@return A remote environment that executes the program on a cluster. | [
"Creates",
"a",
"{",
"@link",
"RemoteEnvironment",
"}",
".",
"The",
"remote",
"environment",
"sends",
"(",
"parts",
"of",
")",
"the",
"program",
"to",
"a",
"cluster",
"for",
"execution",
".",
"Note",
"that",
"all",
"file",
"paths",
"used",
"in",
"the",
"... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-java/src/main/java/org/apache/flink/api/java/ExecutionEnvironment.java#L1210-L1214 |
DV8FromTheWorld/JDA | src/main/java/net/dv8tion/jda/core/requests/restaction/MessageAction.java | MessageAction.appendFormat | @CheckReturnValue
public MessageAction appendFormat(final String format, final Object... args)
{
return append(String.format(format, args));
} | java | @CheckReturnValue
public MessageAction appendFormat(final String format, final Object... args)
{
return append(String.format(format, args));
} | [
"@",
"CheckReturnValue",
"public",
"MessageAction",
"appendFormat",
"(",
"final",
"String",
"format",
",",
"final",
"Object",
"...",
"args",
")",
"{",
"return",
"append",
"(",
"String",
".",
"format",
"(",
"format",
",",
"args",
")",
")",
";",
"}"
] | Applies the result of {@link String#format(String, Object...) String.format(String, Object...)}
as content.
<p>For more information of formatting review the {@link java.util.Formatter Formatter} documentation!
@param format
The format String
@param args
The arguments that should be used for conversion
@throws java.lang.IllegalArgumentException
If the appended formatting is too big and will cause the content to
exceed the {@value net.dv8tion.jda.core.entities.Message#MAX_CONTENT_LENGTH} character limit
@throws java.util.IllegalFormatException
If a format string contains an illegal syntax,
a format specifier that is incompatible with the given arguments,
insufficient arguments given the format string, or other illegal conditions.
For specification of all possible formatting errors,
see the <a href="../util/Formatter.html#detail">Details</a>
section of the formatter class specification.
@return Updated MessageAction for chaining convenience | [
"Applies",
"the",
"result",
"of",
"{",
"@link",
"String#format",
"(",
"String",
"Object",
"...",
")",
"String",
".",
"format",
"(",
"String",
"Object",
"...",
")",
"}",
"as",
"content",
"."
] | train | https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/requests/restaction/MessageAction.java#L336-L340 |
modelmapper/modelmapper | core/src/main/java/org/modelmapper/internal/util/Iterables.java | Iterables.getElement | @SuppressWarnings("unchecked")
public static Object getElement(Object iterable, int index) {
if (iterable.getClass().isArray())
return getElementFromArrary(iterable, index);
if (iterable instanceof Collection)
return getElementFromCollection((Collection<Object>) iterable, index);
return null;
} | java | @SuppressWarnings("unchecked")
public static Object getElement(Object iterable, int index) {
if (iterable.getClass().isArray())
return getElementFromArrary(iterable, index);
if (iterable instanceof Collection)
return getElementFromCollection((Collection<Object>) iterable, index);
return null;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"Object",
"getElement",
"(",
"Object",
"iterable",
",",
"int",
"index",
")",
"{",
"if",
"(",
"iterable",
".",
"getClass",
"(",
")",
".",
"isArray",
"(",
")",
")",
"return",
"getElement... | Gets the element from an iterable with given index.
@param iterable the iterable
@param index the index
@return null if the iterable doesn't have the element at index, otherwise, return the element | [
"Gets",
"the",
"element",
"from",
"an",
"iterable",
"with",
"given",
"index",
"."
] | train | https://github.com/modelmapper/modelmapper/blob/491d165ded9dc9aba7ce8b56984249e1a1363204/core/src/main/java/org/modelmapper/internal/util/Iterables.java#L73-L81 |
alkacon/opencms-core | src/org/opencms/ui/editors/messagebundle/CmsMessageBundleEditorTypes.java | CmsMessageBundleEditorTypes.getDescriptor | public static CmsResource getDescriptor(CmsObject cms, String basename) {
CmsSolrQuery query = new CmsSolrQuery();
query.setResourceTypes(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR.toString());
query.setFilterQueries("filename:\"" + basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX + "\"");
query.add("fl", "path");
CmsSolrResultList results;
try {
boolean isOnlineProject = cms.getRequestContext().getCurrentProject().isOnlineProject();
String indexName = isOnlineProject
? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE
: CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE;
results = OpenCms.getSearchManager().getIndexSolr(indexName).search(cms, query, true, null, true, null);
} catch (CmsSearchException e) {
LOG.error(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_SEARCH_ERROR_0), e);
return null;
}
switch (results.size()) {
case 0:
return null;
case 1:
return results.get(0);
default:
String files = "";
for (CmsResource res : results) {
files += " " + res.getRootPath();
}
LOG.warn(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_NOT_UNIQUE_1, files));
return results.get(0);
}
} | java | public static CmsResource getDescriptor(CmsObject cms, String basename) {
CmsSolrQuery query = new CmsSolrQuery();
query.setResourceTypes(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR.toString());
query.setFilterQueries("filename:\"" + basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX + "\"");
query.add("fl", "path");
CmsSolrResultList results;
try {
boolean isOnlineProject = cms.getRequestContext().getCurrentProject().isOnlineProject();
String indexName = isOnlineProject
? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE
: CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE;
results = OpenCms.getSearchManager().getIndexSolr(indexName).search(cms, query, true, null, true, null);
} catch (CmsSearchException e) {
LOG.error(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_SEARCH_ERROR_0), e);
return null;
}
switch (results.size()) {
case 0:
return null;
case 1:
return results.get(0);
default:
String files = "";
for (CmsResource res : results) {
files += " " + res.getRootPath();
}
LOG.warn(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_NOT_UNIQUE_1, files));
return results.get(0);
}
} | [
"public",
"static",
"CmsResource",
"getDescriptor",
"(",
"CmsObject",
"cms",
",",
"String",
"basename",
")",
"{",
"CmsSolrQuery",
"query",
"=",
"new",
"CmsSolrQuery",
"(",
")",
";",
"query",
".",
"setResourceTypes",
"(",
"CmsMessageBundleEditorTypes",
".",
"Bundle... | Returns the bundle descriptor for the bundle with the provided base name.
@param cms {@link CmsObject} used for searching.
@param basename the bundle base name, for which the descriptor is searched.
@return the bundle descriptor, or <code>null</code> if it does not exist or searching fails. | [
"Returns",
"the",
"bundle",
"descriptor",
"for",
"the",
"bundle",
"with",
"the",
"provided",
"base",
"name",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/editors/messagebundle/CmsMessageBundleEditorTypes.java#L976-L1007 |
sai-pullabhotla/catatumbo | src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java | DefaultDatastoreReader.loadByName | public <E> List<E> loadByName(Class<E> entityClass, List<String> identifiers) {
Key[] nativeKeys = stringListToNativeKeys(entityClass, identifiers);
return fetch(entityClass, nativeKeys);
} | java | public <E> List<E> loadByName(Class<E> entityClass, List<String> identifiers) {
Key[] nativeKeys = stringListToNativeKeys(entityClass, identifiers);
return fetch(entityClass, nativeKeys);
} | [
"public",
"<",
"E",
">",
"List",
"<",
"E",
">",
"loadByName",
"(",
"Class",
"<",
"E",
">",
"entityClass",
",",
"List",
"<",
"String",
">",
"identifiers",
")",
"{",
"Key",
"[",
"]",
"nativeKeys",
"=",
"stringListToNativeKeys",
"(",
"entityClass",
",",
"... | Loads and returns the entities with the given <b>names (a.k.a String IDs)</b>. The entities are
assumed to be root entities (no parent). The entity kind is determined from the supplied class.
@param entityClass
the entity class
@param identifiers
the IDs of the entities
@return the list of entity objects in the same order as the given list of identifiers. If one
or more requested IDs do not exist in the Cloud Datastore, the corresponding item in
the returned list be <code>null</code>.
@throws EntityManagerException
if any error occurs while inserting. | [
"Loads",
"and",
"returns",
"the",
"entities",
"with",
"the",
"given",
"<b",
">",
"names",
"(",
"a",
".",
"k",
".",
"a",
"String",
"IDs",
")",
"<",
"/",
"b",
">",
".",
"The",
"entities",
"are",
"assumed",
"to",
"be",
"root",
"entities",
"(",
"no",
... | train | https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java#L228-L231 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/bob/BoBHash.java | BoBHash.fromSrc | public static BoBHash fromSrc(String src) {
String hashType = src.substring(src.lastIndexOf("cid:") + 4, src.indexOf("+"));
String hash = src.substring(src.indexOf("+") + 1, src.indexOf("@bob.xmpp.org"));
return new BoBHash(hash, hashType);
} | java | public static BoBHash fromSrc(String src) {
String hashType = src.substring(src.lastIndexOf("cid:") + 4, src.indexOf("+"));
String hash = src.substring(src.indexOf("+") + 1, src.indexOf("@bob.xmpp.org"));
return new BoBHash(hash, hashType);
} | [
"public",
"static",
"BoBHash",
"fromSrc",
"(",
"String",
"src",
")",
"{",
"String",
"hashType",
"=",
"src",
".",
"substring",
"(",
"src",
".",
"lastIndexOf",
"(",
"\"cid:\"",
")",
"+",
"4",
",",
"src",
".",
"indexOf",
"(",
"\"+\"",
")",
")",
";",
"St... | Get BoB hash from src attribute string.
@param src
@return the BoB hash | [
"Get",
"BoB",
"hash",
"from",
"src",
"attribute",
"string",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/bob/BoBHash.java#L103-L107 |
eclipse/hawkbit | hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java | HawkbitCommonUtil.formattingFinishedPercentage | public static String formattingFinishedPercentage(final RolloutGroup rolloutGroup, final float finishedPercentage) {
float tmpFinishedPercentage = 0;
switch (rolloutGroup.getStatus()) {
case READY:
case SCHEDULED:
case ERROR:
tmpFinishedPercentage = 0.0F;
break;
case FINISHED:
tmpFinishedPercentage = 100.0F;
break;
case RUNNING:
tmpFinishedPercentage = finishedPercentage;
break;
default:
break;
}
return String.format("%.1f", tmpFinishedPercentage);
} | java | public static String formattingFinishedPercentage(final RolloutGroup rolloutGroup, final float finishedPercentage) {
float tmpFinishedPercentage = 0;
switch (rolloutGroup.getStatus()) {
case READY:
case SCHEDULED:
case ERROR:
tmpFinishedPercentage = 0.0F;
break;
case FINISHED:
tmpFinishedPercentage = 100.0F;
break;
case RUNNING:
tmpFinishedPercentage = finishedPercentage;
break;
default:
break;
}
return String.format("%.1f", tmpFinishedPercentage);
} | [
"public",
"static",
"String",
"formattingFinishedPercentage",
"(",
"final",
"RolloutGroup",
"rolloutGroup",
",",
"final",
"float",
"finishedPercentage",
")",
"{",
"float",
"tmpFinishedPercentage",
"=",
"0",
";",
"switch",
"(",
"rolloutGroup",
".",
"getStatus",
"(",
... | Formats the finished percentage of a rollout group into a string with one
digit after comma.
@param rolloutGroup
the rollout group
@param finishedPercentage
the calculated finished percentage of the rolloutgroup
@return formatted String value | [
"Formats",
"the",
"finished",
"percentage",
"of",
"a",
"rollout",
"group",
"into",
"a",
"string",
"with",
"one",
"digit",
"after",
"comma",
"."
] | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java#L464-L482 |
rahulsom/genealogy | src/main/java/com/github/rahulsom/genealogy/NameDbUsa.java | NameDbUsa.getNameObject | private Name getNameObject(List<? extends Name> list, double probability) {
int index = Collections.binarySearch(list, new Name(null, probability), locateNameByCumulativeProbability);
if (index >= 0) {
return list.get(index);
} else if (-index > list.size()) {
throw new RuntimeException("Invalid probability provided - (" + probability +
"). Max allowed for this list is " + getMax(list));
} else {
return list.get((-index) - 1);
}
} | java | private Name getNameObject(List<? extends Name> list, double probability) {
int index = Collections.binarySearch(list, new Name(null, probability), locateNameByCumulativeProbability);
if (index >= 0) {
return list.get(index);
} else if (-index > list.size()) {
throw new RuntimeException("Invalid probability provided - (" + probability +
"). Max allowed for this list is " + getMax(list));
} else {
return list.get((-index) - 1);
}
} | [
"private",
"Name",
"getNameObject",
"(",
"List",
"<",
"?",
"extends",
"Name",
">",
"list",
",",
"double",
"probability",
")",
"{",
"int",
"index",
"=",
"Collections",
".",
"binarySearch",
"(",
"list",
",",
"new",
"Name",
"(",
"null",
",",
"probability",
... | Finds name at a given cumulative probability accounting for gaps.
@param list The list to look for name in
@param probability the cumulative probability to search for (between 0 and 1)
@return the name object | [
"Finds",
"name",
"at",
"a",
"given",
"cumulative",
"probability",
"accounting",
"for",
"gaps",
"."
] | train | https://github.com/rahulsom/genealogy/blob/2beb35ab9c6e03080328aa08b18f0a3c5d3f5c12/src/main/java/com/github/rahulsom/genealogy/NameDbUsa.java#L94-L104 |
codescape/bitvunit | bitvunit-core/src/main/java/de/codescape/bitvunit/util/html/HtmlElementUtil.java | HtmlElementUtil.hasNonEmptyAttribute | public static boolean hasNonEmptyAttribute(HtmlElement element, String attributeName) {
return hasAttribute(element, attributeName) && !element.getAttribute(attributeName).isEmpty();
} | java | public static boolean hasNonEmptyAttribute(HtmlElement element, String attributeName) {
return hasAttribute(element, attributeName) && !element.getAttribute(attributeName).isEmpty();
} | [
"public",
"static",
"boolean",
"hasNonEmptyAttribute",
"(",
"HtmlElement",
"element",
",",
"String",
"attributeName",
")",
"{",
"return",
"hasAttribute",
"(",
"element",
",",
"attributeName",
")",
"&&",
"!",
"element",
".",
"getAttribute",
"(",
"attributeName",
")... | Returns <code>true</code> when the given element contains a non empty attribute with the given attribute name.
@param element element to check for an attribute
@param attributeName name of the attribute
@return <code>true</code> if an attribute with the given name exists and is not empty, otherwise
<code>false</code> | [
"Returns",
"<code",
">",
"true<",
"/",
"code",
">",
"when",
"the",
"given",
"element",
"contains",
"a",
"non",
"empty",
"attribute",
"with",
"the",
"given",
"attribute",
"name",
"."
] | train | https://github.com/codescape/bitvunit/blob/cef6d9af60d684e41294981c10b6d92c8f063a4e/bitvunit-core/src/main/java/de/codescape/bitvunit/util/html/HtmlElementUtil.java#L24-L26 |
VoltDB/voltdb | src/frontend/org/voltcore/utils/CoreUtils.java | CoreUtils.printPortsInUse | public static synchronized void printPortsInUse(VoltLogger log) {
try {
/*
* Don't do DNS resolution, don't use names for port numbers
*/
ProcessBuilder pb = new ProcessBuilder("lsof", "-i", "-n", "-P");
pb.redirectErrorStream(true);
Process p = pb.start();
java.io.InputStreamReader reader = new java.io.InputStreamReader(p.getInputStream());
java.io.BufferedReader br = new java.io.BufferedReader(reader);
String str = br.readLine();
log.fatal("Logging ports that are bound for listening, " +
"this doesn't include ports bound by outgoing connections " +
"which can also cause a failure to bind");
log.fatal("The PID of this process is " + getPID());
if (str != null) {
log.fatal(str);
}
while((str = br.readLine()) != null) {
if (str.contains("LISTEN")) {
log.fatal(str);
}
}
}
catch (Exception e) {
log.fatal("Unable to list ports in use at this time.");
}
} | java | public static synchronized void printPortsInUse(VoltLogger log) {
try {
/*
* Don't do DNS resolution, don't use names for port numbers
*/
ProcessBuilder pb = new ProcessBuilder("lsof", "-i", "-n", "-P");
pb.redirectErrorStream(true);
Process p = pb.start();
java.io.InputStreamReader reader = new java.io.InputStreamReader(p.getInputStream());
java.io.BufferedReader br = new java.io.BufferedReader(reader);
String str = br.readLine();
log.fatal("Logging ports that are bound for listening, " +
"this doesn't include ports bound by outgoing connections " +
"which can also cause a failure to bind");
log.fatal("The PID of this process is " + getPID());
if (str != null) {
log.fatal(str);
}
while((str = br.readLine()) != null) {
if (str.contains("LISTEN")) {
log.fatal(str);
}
}
}
catch (Exception e) {
log.fatal("Unable to list ports in use at this time.");
}
} | [
"public",
"static",
"synchronized",
"void",
"printPortsInUse",
"(",
"VoltLogger",
"log",
")",
"{",
"try",
"{",
"/*\n * Don't do DNS resolution, don't use names for port numbers\n */",
"ProcessBuilder",
"pb",
"=",
"new",
"ProcessBuilder",
"(",
"\"lsof\"",... | Log (to the fatal logger) the list of ports in use.
Uses "lsof -i" internally.
@param log VoltLogger used to print output or warnings. | [
"Log",
"(",
"to",
"the",
"fatal",
"logger",
")",
"the",
"list",
"of",
"ports",
"in",
"use",
".",
"Uses",
"lsof",
"-",
"i",
"internally",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltcore/utils/CoreUtils.java#L1196-L1223 |
osglworks/java-mvc | src/main/java/org/osgl/mvc/result/NotAcceptable.java | NotAcceptable.of | public static NotAcceptable of(Throwable cause) {
if (_localizedErrorMsg()) {
return of(cause, defaultMessage(NOT_ACCEPTABLE));
} else {
touchPayload().cause(cause);
return _INSTANCE;
}
} | java | public static NotAcceptable of(Throwable cause) {
if (_localizedErrorMsg()) {
return of(cause, defaultMessage(NOT_ACCEPTABLE));
} else {
touchPayload().cause(cause);
return _INSTANCE;
}
} | [
"public",
"static",
"NotAcceptable",
"of",
"(",
"Throwable",
"cause",
")",
"{",
"if",
"(",
"_localizedErrorMsg",
"(",
")",
")",
"{",
"return",
"of",
"(",
"cause",
",",
"defaultMessage",
"(",
"NOT_ACCEPTABLE",
")",
")",
";",
"}",
"else",
"{",
"touchPayload"... | Returns a static NotAcceptable instance and set the {@link #payload} thread local
with cause specified.
When calling the instance on {@link #getMessage()} method, it will return whatever
stored in the {@link #payload} thread local
@param cause the cause
@return a static NotAcceptable instance as described above | [
"Returns",
"a",
"static",
"NotAcceptable",
"instance",
"and",
"set",
"the",
"{",
"@link",
"#payload",
"}",
"thread",
"local",
"with",
"cause",
"specified",
"."
] | train | https://github.com/osglworks/java-mvc/blob/4d2b2ec40498ac6ee7040c0424377cbeacab124b/src/main/java/org/osgl/mvc/result/NotAcceptable.java#L117-L124 |
ahome-it/lienzo-core | src/main/java/com/ait/lienzo/client/core/shape/Shape.java | Shape.setDashArray | public T setDashArray(final double dash, final double... dashes)
{
getAttributes().setDashArray(new DashArray(dash, dashes));
return cast();
} | java | public T setDashArray(final double dash, final double... dashes)
{
getAttributes().setDashArray(new DashArray(dash, dashes));
return cast();
} | [
"public",
"T",
"setDashArray",
"(",
"final",
"double",
"dash",
",",
"final",
"double",
"...",
"dashes",
")",
"{",
"getAttributes",
"(",
")",
".",
"setDashArray",
"(",
"new",
"DashArray",
"(",
"dash",
",",
"dashes",
")",
")",
";",
"return",
"cast",
"(",
... | Sets the dash array with individual dash lengths.
@param dash length of dash
@param dashes if specified, length of remaining dashes
@return this Line | [
"Sets",
"the",
"dash",
"array",
"with",
"individual",
"dash",
"lengths",
"."
] | train | https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/shape/Shape.java#L755-L760 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/mps/managed_device.java | managed_device.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
managed_device_responses result = (managed_device_responses) service.get_payload_formatter().string_to_resource(managed_device_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.managed_device_response_array);
}
managed_device[] result_managed_device = new managed_device[result.managed_device_response_array.length];
for(int i = 0; i < result.managed_device_response_array.length; i++)
{
result_managed_device[i] = result.managed_device_response_array[i].managed_device[0];
}
return result_managed_device;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
managed_device_responses result = (managed_device_responses) service.get_payload_formatter().string_to_resource(managed_device_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.managed_device_response_array);
}
managed_device[] result_managed_device = new managed_device[result.managed_device_response_array.length];
for(int i = 0; i < result.managed_device_response_array.length; i++)
{
result_managed_device[i] = result.managed_device_response_array[i].managed_device[0];
}
return result_managed_device;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"managed_device_responses",
"result",
"=",
"(",
"managed_device_responses",
")",
"service",
".",
"get_payload_... | <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/mps/managed_device.java#L573-L590 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-trace/src/main/java/com/google/cloud/trace/v1/TraceServiceClient.java | TraceServiceClient.patchTraces | public final void patchTraces(String projectId, Traces traces) {
PatchTracesRequest request =
PatchTracesRequest.newBuilder().setProjectId(projectId).setTraces(traces).build();
patchTraces(request);
} | java | public final void patchTraces(String projectId, Traces traces) {
PatchTracesRequest request =
PatchTracesRequest.newBuilder().setProjectId(projectId).setTraces(traces).build();
patchTraces(request);
} | [
"public",
"final",
"void",
"patchTraces",
"(",
"String",
"projectId",
",",
"Traces",
"traces",
")",
"{",
"PatchTracesRequest",
"request",
"=",
"PatchTracesRequest",
".",
"newBuilder",
"(",
")",
".",
"setProjectId",
"(",
"projectId",
")",
".",
"setTraces",
"(",
... | Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you
send matches that of an existing trace, any fields in the existing trace and its spans are
overwritten by the provided values, and any new fields provided are merged with the existing
trace data. If the ID does not match, a new trace is created.
<p>Sample code:
<pre><code>
try (TraceServiceClient traceServiceClient = TraceServiceClient.create()) {
String projectId = "";
Traces traces = Traces.newBuilder().build();
traceServiceClient.patchTraces(projectId, traces);
}
</code></pre>
@param projectId ID of the Cloud project where the trace data is stored.
@param traces The body of the message.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Sends",
"new",
"traces",
"to",
"Stackdriver",
"Trace",
"or",
"updates",
"existing",
"traces",
".",
"If",
"the",
"ID",
"of",
"a",
"trace",
"that",
"you",
"send",
"matches",
"that",
"of",
"an",
"existing",
"trace",
"any",
"fields",
"in",
"the",
"existing",
... | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-trace/src/main/java/com/google/cloud/trace/v1/TraceServiceClient.java#L187-L192 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/WSRdbManagedConnectionImpl.java | WSRdbManagedConnectionImpl.getSQLJConnectionContext | public final Object getSQLJConnectionContext(Class<?> DefaultContext, WSConnectionManager cm) throws SQLException {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(this, tc, "getSQLJConnectionContext");
if (sqljContext == null) {
// get the sqljContext if necessary. let the helper handle it
// the helper does the sqlex mapping
try {
sqljContext = helper.getSQLJContext(this, DefaultContext, cm);
} catch (SQLException se) {
// the helper already did the sqlj error mapping and ffdc..
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(this, tc, "getSQLJConnectionContext", se);
throw se;
}
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(this, tc, "getSQLJConnectionContext", sqljContext);
return sqljContext;
} | java | public final Object getSQLJConnectionContext(Class<?> DefaultContext, WSConnectionManager cm) throws SQLException {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(this, tc, "getSQLJConnectionContext");
if (sqljContext == null) {
// get the sqljContext if necessary. let the helper handle it
// the helper does the sqlex mapping
try {
sqljContext = helper.getSQLJContext(this, DefaultContext, cm);
} catch (SQLException se) {
// the helper already did the sqlj error mapping and ffdc..
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(this, tc, "getSQLJConnectionContext", se);
throw se;
}
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(this, tc, "getSQLJConnectionContext", sqljContext);
return sqljContext;
} | [
"public",
"final",
"Object",
"getSQLJConnectionContext",
"(",
"Class",
"<",
"?",
">",
"DefaultContext",
",",
"WSConnectionManager",
"cm",
")",
"throws",
"SQLException",
"{",
"final",
"boolean",
"isTraceOn",
"=",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")"... | This method returns the SQLJ ConnectionContext. This method is only called by
the WSJccConnection class. The ConnectionContext caches all the RTStatements
@param DefaultContext the sqlj.runtime.ref.DefaultContext class
@return sqlj.runtime.ref.DefaultContext
@exception SQLException - failed to create SQLJ Connection Context | [
"This",
"method",
"returns",
"the",
"SQLJ",
"ConnectionContext",
".",
"This",
"method",
"is",
"only",
"called",
"by",
"the",
"WSJccConnection",
"class",
".",
"The",
"ConnectionContext",
"caches",
"all",
"the",
"RTStatements"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/WSRdbManagedConnectionImpl.java#L4202-L4222 |
apache/reef | lang/java/reef-examples/src/main/java/org/apache/reef/examples/hello/HelloREEFStandalone.java | HelloREEFStandalone.main | public static void main(final String[] args) throws BindException, InjectionException {
final Tang tang = Tang.Factory.getTang();
final JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
try{
new CommandLine(cb)
.registerShortNameOfClass(NodeListFilePath.class)
.registerShortNameOfClass(SshPortNum.class)
.processCommandLine(args);
} catch(final IOException ex) {
LOG.log(Level.SEVERE, "Missing parameter 'nodelist' or wrong parameter input.");
throw new RuntimeException("Missing parameter 'nodelist' or wrong parameter input: ", ex);
}
final Injector injector = tang.newInjector(cb.build());
final String nodeListFilePath = injector.getNamedInstance(NodeListFilePath.class);
final int sshPortNum = injector.getNamedInstance(SshPortNum.class);
final Configuration runtimeConf = getRuntimeConfiguration(nodeListFilePath, sshPortNum);
final Configuration driverConf = getDriverConfiguration();
final LauncherStatus status = DriverLauncher
.getLauncher(runtimeConf)
.run(driverConf, JOB_TIMEOUT);
LOG.log(Level.INFO, "REEF job completed: {0}", status);
} | java | public static void main(final String[] args) throws BindException, InjectionException {
final Tang tang = Tang.Factory.getTang();
final JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
try{
new CommandLine(cb)
.registerShortNameOfClass(NodeListFilePath.class)
.registerShortNameOfClass(SshPortNum.class)
.processCommandLine(args);
} catch(final IOException ex) {
LOG.log(Level.SEVERE, "Missing parameter 'nodelist' or wrong parameter input.");
throw new RuntimeException("Missing parameter 'nodelist' or wrong parameter input: ", ex);
}
final Injector injector = tang.newInjector(cb.build());
final String nodeListFilePath = injector.getNamedInstance(NodeListFilePath.class);
final int sshPortNum = injector.getNamedInstance(SshPortNum.class);
final Configuration runtimeConf = getRuntimeConfiguration(nodeListFilePath, sshPortNum);
final Configuration driverConf = getDriverConfiguration();
final LauncherStatus status = DriverLauncher
.getLauncher(runtimeConf)
.run(driverConf, JOB_TIMEOUT);
LOG.log(Level.INFO, "REEF job completed: {0}", status);
} | [
"public",
"static",
"void",
"main",
"(",
"final",
"String",
"[",
"]",
"args",
")",
"throws",
"BindException",
",",
"InjectionException",
"{",
"final",
"Tang",
"tang",
"=",
"Tang",
".",
"Factory",
".",
"getTang",
"(",
")",
";",
"final",
"JavaConfigurationBuil... | Start Hello REEF job.
@param args command line parameters.
@throws BindException configuration error.
@throws InjectionException configuration error. | [
"Start",
"Hello",
"REEF",
"job",
"."
] | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-examples/src/main/java/org/apache/reef/examples/hello/HelloREEFStandalone.java#L87-L115 |
Mozu/mozu-java | mozu-java-core/src/main/java/com/mozu/api/urls/event/push/subscriptions/EventDeliverySummaryUrl.java | EventDeliverySummaryUrl.getDeliveryAttemptSummaryUrl | public static MozuUrl getDeliveryAttemptSummaryUrl(Integer processId, String responseFields, String subscriptionId)
{
UrlFormatter formatter = new UrlFormatter("/api/event/push/subscriptions/{subscriptionId}/deliveryattempts/{id}?responseFields={responseFields}");
formatter.formatUrl("processId", processId);
formatter.formatUrl("responseFields", responseFields);
formatter.formatUrl("subscriptionId", subscriptionId);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl getDeliveryAttemptSummaryUrl(Integer processId, String responseFields, String subscriptionId)
{
UrlFormatter formatter = new UrlFormatter("/api/event/push/subscriptions/{subscriptionId}/deliveryattempts/{id}?responseFields={responseFields}");
formatter.formatUrl("processId", processId);
formatter.formatUrl("responseFields", responseFields);
formatter.formatUrl("subscriptionId", subscriptionId);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"getDeliveryAttemptSummaryUrl",
"(",
"Integer",
"processId",
",",
"String",
"responseFields",
",",
"String",
"subscriptionId",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/event/push/subscriptions/{subscripti... | Get Resource Url for GetDeliveryAttemptSummary
@param processId
@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 subscriptionId Unique identifier for a subscription, such as subscribing tenants for an event or to receive a notification.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"GetDeliveryAttemptSummary"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/event/push/subscriptions/EventDeliverySummaryUrl.java#L23-L30 |
oasp/oasp4j | modules/rest/src/main/java/io/oasp/module/rest/service/impl/RestServiceExceptionFacade.java | RestServiceExceptionFacade.toResponse | protected Response toResponse(Throwable exception, Throwable catched) {
if (exception instanceof ValidationException) {
return handleValidationException(exception, catched);
} else if (exception instanceof ValidationErrorUserException) {
return createResponse(exception, (ValidationErrorUserException) exception, null);
} else {
Class<?> exceptionClass = exception.getClass();
for (Class<?> securityError : this.securityExceptions) {
if (securityError.isAssignableFrom(exceptionClass)) {
return handleSecurityError(exception, catched);
}
}
return handleGenericError(exception, catched);
}
} | java | protected Response toResponse(Throwable exception, Throwable catched) {
if (exception instanceof ValidationException) {
return handleValidationException(exception, catched);
} else if (exception instanceof ValidationErrorUserException) {
return createResponse(exception, (ValidationErrorUserException) exception, null);
} else {
Class<?> exceptionClass = exception.getClass();
for (Class<?> securityError : this.securityExceptions) {
if (securityError.isAssignableFrom(exceptionClass)) {
return handleSecurityError(exception, catched);
}
}
return handleGenericError(exception, catched);
}
} | [
"protected",
"Response",
"toResponse",
"(",
"Throwable",
"exception",
",",
"Throwable",
"catched",
")",
"{",
"if",
"(",
"exception",
"instanceof",
"ValidationException",
")",
"{",
"return",
"handleValidationException",
"(",
"exception",
",",
"catched",
")",
";",
"... | @see #toResponse(Throwable)
@param exception the exception to handle
@param catched the original exception that was cached. Either same as {@code error} or a (child-)
{@link Throwable#getCause() cause} of it.
@return the response build from the exception. | [
"@see",
"#toResponse",
"(",
"Throwable",
")"
] | train | https://github.com/oasp/oasp4j/blob/03f90132699fad95e52ec8efa54aa391f8d3c7e4/modules/rest/src/main/java/io/oasp/module/rest/service/impl/RestServiceExceptionFacade.java#L226-L241 |
Whiley/WhileyCompiler | src/main/java/wyil/type/util/ReadWriteTypeExtractor.java | ReadWriteTypeExtractor.unionHelper | @SuppressWarnings("unchecked")
protected static <T extends SemanticType> T unionHelper(T lhs, T rhs) {
if (lhs.equals(rhs)) {
return lhs;
} else if (lhs instanceof Type.Void) {
return rhs;
} else if (rhs instanceof Type.Void) {
return lhs;
} else if (lhs instanceof Type && rhs instanceof Type) {
return (T) new Type.Union(new Type[] { (Type) lhs, (Type) rhs });
} else {
return (T) new SemanticType.Union(new SemanticType[] { lhs, rhs });
}
} | java | @SuppressWarnings("unchecked")
protected static <T extends SemanticType> T unionHelper(T lhs, T rhs) {
if (lhs.equals(rhs)) {
return lhs;
} else if (lhs instanceof Type.Void) {
return rhs;
} else if (rhs instanceof Type.Void) {
return lhs;
} else if (lhs instanceof Type && rhs instanceof Type) {
return (T) new Type.Union(new Type[] { (Type) lhs, (Type) rhs });
} else {
return (T) new SemanticType.Union(new SemanticType[] { lhs, rhs });
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"static",
"<",
"T",
"extends",
"SemanticType",
">",
"T",
"unionHelper",
"(",
"T",
"lhs",
",",
"T",
"rhs",
")",
"{",
"if",
"(",
"lhs",
".",
"equals",
"(",
"rhs",
")",
")",
"{",
"return",
... | Provides a simplistic form of type union which, in some cases, does slightly
better than simply creating a new union. For example, unioning
<code>int</code> with <code>int</code> will return <code>int</code> rather
than <code>int|int</code>.
@param lhs
@param rhs
@return | [
"Provides",
"a",
"simplistic",
"form",
"of",
"type",
"union",
"which",
"in",
"some",
"cases",
"does",
"slightly",
"better",
"than",
"simply",
"creating",
"a",
"new",
"union",
".",
"For",
"example",
"unioning",
"<code",
">",
"int<",
"/",
"code",
">",
"with"... | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/type/util/ReadWriteTypeExtractor.java#L847-L860 |
contentful/contentful.java | src/main/java/com/contentful/java/cda/image/ImageOption.java | ImageOption.backgroundColorOf | public static ImageOption backgroundColorOf(int r, int g, int b) {
if (r > 255 || r < 0) {
throw new IllegalArgumentException("Red component out of range: " + r);
}
if (g > 255 || g < 0) {
throw new IllegalArgumentException("Green component out of range: " + g);
}
if (b > 255 || b < 0) {
throw new IllegalArgumentException("Blue component out of range: " + b);
}
return new ImageOption("bg", "rgb:" + format(Locale.getDefault(), "%02X%02X%02X", r, g, b));
} | java | public static ImageOption backgroundColorOf(int r, int g, int b) {
if (r > 255 || r < 0) {
throw new IllegalArgumentException("Red component out of range: " + r);
}
if (g > 255 || g < 0) {
throw new IllegalArgumentException("Green component out of range: " + g);
}
if (b > 255 || b < 0) {
throw new IllegalArgumentException("Blue component out of range: " + b);
}
return new ImageOption("bg", "rgb:" + format(Locale.getDefault(), "%02X%02X%02X", r, g, b));
} | [
"public",
"static",
"ImageOption",
"backgroundColorOf",
"(",
"int",
"r",
",",
"int",
"g",
",",
"int",
"b",
")",
"{",
"if",
"(",
"r",
">",
"255",
"||",
"r",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Red component out of range: ... | Define a background color by its components.
<p>
Each color component must be a hexadecimal in the range from 0 to 255 inclusively.
@param r the red color component in hex to be used.
@param g the green color component in hex to be used.
@param b the blue color component in hex to be used.
@return an image option for manipulating a given url.
@throws IllegalArgumentException if a component is less then zero or greater then 255. | [
"Define",
"a",
"background",
"color",
"by",
"its",
"components",
".",
"<p",
">",
"Each",
"color",
"component",
"must",
"be",
"a",
"hexadecimal",
"in",
"the",
"range",
"from",
"0",
"to",
"255",
"inclusively",
"."
] | train | https://github.com/contentful/contentful.java/blob/6ecc2ace454c674b218b99489dc50697b1dbffcb/src/main/java/com/contentful/java/cda/image/ImageOption.java#L262-L274 |
Jasig/uPortal | uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/layout/dlm/remoting/UpdatePreferencesServlet.java | UpdatePreferencesServlet.removeByFName | @RequestMapping(method = RequestMethod.POST, params = "action=removeByFName")
public ModelAndView removeByFName(
HttpServletRequest request,
HttpServletResponse response,
@RequestParam(value = "fname") String fname)
throws IOException {
IUserInstance ui = userInstanceManager.getUserInstance(request);
UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager();
IUserLayoutManager ulm = upm.getUserLayoutManager();
try {
String elementId =
ulm.getUserLayout().findNodeId(new PortletSubscribeIdResolver(fname));
if (elementId != null) {
// Delete the requested element node. This code is the same for
// all node types, so we can just have a generic action.
if (!ulm.deleteNode(elementId)) {
logger.info(
"Failed to remove element ID {} from layout root folder ID {}, delete node returned false",
elementId,
ulm.getRootFolderId());
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return new ModelAndView(
"jsonView",
Collections.singletonMap(
"error",
getMessage(
"error.element.update",
"Unable to update element",
RequestContextUtils.getLocale(request))));
}
} else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
ulm.saveUserLayout();
return new ModelAndView("jsonView", Collections.emptyMap());
} catch (PortalException e) {
return handlePersistError(request, response, e);
}
} | java | @RequestMapping(method = RequestMethod.POST, params = "action=removeByFName")
public ModelAndView removeByFName(
HttpServletRequest request,
HttpServletResponse response,
@RequestParam(value = "fname") String fname)
throws IOException {
IUserInstance ui = userInstanceManager.getUserInstance(request);
UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager();
IUserLayoutManager ulm = upm.getUserLayoutManager();
try {
String elementId =
ulm.getUserLayout().findNodeId(new PortletSubscribeIdResolver(fname));
if (elementId != null) {
// Delete the requested element node. This code is the same for
// all node types, so we can just have a generic action.
if (!ulm.deleteNode(elementId)) {
logger.info(
"Failed to remove element ID {} from layout root folder ID {}, delete node returned false",
elementId,
ulm.getRootFolderId());
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return new ModelAndView(
"jsonView",
Collections.singletonMap(
"error",
getMessage(
"error.element.update",
"Unable to update element",
RequestContextUtils.getLocale(request))));
}
} else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
ulm.saveUserLayout();
return new ModelAndView("jsonView", Collections.emptyMap());
} catch (PortalException e) {
return handlePersistError(request, response, e);
}
} | [
"@",
"RequestMapping",
"(",
"method",
"=",
"RequestMethod",
".",
"POST",
",",
"params",
"=",
"\"action=removeByFName\"",
")",
"public",
"ModelAndView",
"removeByFName",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"@",
"RequestPar... | Remove the first element with the provided fname from the layout.
@param request HttpServletRequest
@param response HttpServletResponse
@param fname fname of the portlet to remove from the layout
@return json response
@throws IOException if the person cannot be retrieved | [
"Remove",
"the",
"first",
"element",
"with",
"the",
"provided",
"fname",
"from",
"the",
"layout",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/layout/dlm/remoting/UpdatePreferencesServlet.java#L216-L261 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GJGeometryReader.java | GJGeometryReader.parseMultiPoint | private MultiPoint parseMultiPoint(JsonParser jp) throws IOException, SQLException {
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
jp.nextToken(); // START_ARRAY [ coordinates
MultiPoint mPoint = GF.createMultiPoint(parseCoordinates(jp));
jp.nextToken();//END_OBJECT } geometry
return mPoint;
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
} | java | private MultiPoint parseMultiPoint(JsonParser jp) throws IOException, SQLException {
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
jp.nextToken(); // START_ARRAY [ coordinates
MultiPoint mPoint = GF.createMultiPoint(parseCoordinates(jp));
jp.nextToken();//END_OBJECT } geometry
return mPoint;
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
} | [
"private",
"MultiPoint",
"parseMultiPoint",
"(",
"JsonParser",
"jp",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"jp",
".",
"nextToken",
"(",
")",
";",
"// FIELD_NAME coordinates ",
"String",
"coordinatesField",
"=",
"jp",
".",
"getText",
"(",
"... | Parses an array of positions
Syntax:
{ "type": "MultiPoint", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] }
@param jsParser
@throws IOException
@return MultiPoint | [
"Parses",
"an",
"array",
"of",
"positions"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GJGeometryReader.java#L115-L126 |
alkacon/opencms-core | src/org/opencms/ui/dialogs/availability/CmsAvailabilityDialog.java | CmsAvailabilityDialog.initResetCheckbox | private void initResetCheckbox(CheckBox box, final CmsDateField field) {
box.addValueChangeListener(new ValueChangeListener() {
private static final long serialVersionUID = 1L;
public void valueChange(ValueChangeEvent event) {
Boolean value = (Boolean)(event.getProperty().getValue());
if (value.booleanValue()) {
field.clear();
field.setEnabled(false);
} else {
field.setEnabled(true);
}
}
});
} | java | private void initResetCheckbox(CheckBox box, final CmsDateField field) {
box.addValueChangeListener(new ValueChangeListener() {
private static final long serialVersionUID = 1L;
public void valueChange(ValueChangeEvent event) {
Boolean value = (Boolean)(event.getProperty().getValue());
if (value.booleanValue()) {
field.clear();
field.setEnabled(false);
} else {
field.setEnabled(true);
}
}
});
} | [
"private",
"void",
"initResetCheckbox",
"(",
"CheckBox",
"box",
",",
"final",
"CmsDateField",
"field",
")",
"{",
"box",
".",
"addValueChangeListener",
"(",
"new",
"ValueChangeListener",
"(",
")",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
... | Creates a reset checkbox which can enable / disable a date field.<p>
@param box the check box
@param field the date field | [
"Creates",
"a",
"reset",
"checkbox",
"which",
"can",
"enable",
"/",
"disable",
"a",
"date",
"field",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/dialogs/availability/CmsAvailabilityDialog.java#L516-L533 |
minio/minio-java | api/src/main/java/io/minio/Signer.java | Signer.presignV4 | public static HttpUrl presignV4(Request request, String region, String accessKey, String secretKey, int expires)
throws NoSuchAlgorithmException, InvalidKeyException {
String contentSha256 = "UNSIGNED-PAYLOAD";
DateTime date = DateFormat.AMZ_DATE_FORMAT.parseDateTime(request.header("x-amz-date"));
Signer signer = new Signer(request, contentSha256, date, region, accessKey, secretKey, null);
signer.setScope();
signer.setPresignCanonicalRequest(expires);
signer.setStringToSign();
signer.setSigningKey();
signer.setSignature();
return signer.url.newBuilder()
.addEncodedQueryParameter(S3Escaper.encode("X-Amz-Signature"), S3Escaper.encode(signer.signature))
.build();
} | java | public static HttpUrl presignV4(Request request, String region, String accessKey, String secretKey, int expires)
throws NoSuchAlgorithmException, InvalidKeyException {
String contentSha256 = "UNSIGNED-PAYLOAD";
DateTime date = DateFormat.AMZ_DATE_FORMAT.parseDateTime(request.header("x-amz-date"));
Signer signer = new Signer(request, contentSha256, date, region, accessKey, secretKey, null);
signer.setScope();
signer.setPresignCanonicalRequest(expires);
signer.setStringToSign();
signer.setSigningKey();
signer.setSignature();
return signer.url.newBuilder()
.addEncodedQueryParameter(S3Escaper.encode("X-Amz-Signature"), S3Escaper.encode(signer.signature))
.build();
} | [
"public",
"static",
"HttpUrl",
"presignV4",
"(",
"Request",
"request",
",",
"String",
"region",
",",
"String",
"accessKey",
",",
"String",
"secretKey",
",",
"int",
"expires",
")",
"throws",
"NoSuchAlgorithmException",
",",
"InvalidKeyException",
"{",
"String",
"co... | Returns pre-signed HttpUrl object for given request, region, access key, secret key and expires time. | [
"Returns",
"pre",
"-",
"signed",
"HttpUrl",
"object",
"for",
"given",
"request",
"region",
"access",
"key",
"secret",
"key",
"and",
"expires",
"time",
"."
] | train | https://github.com/minio/minio-java/blob/b2028f56403c89ce2d5900ae813bc1314c87bc7f/api/src/main/java/io/minio/Signer.java#L328-L343 |
igniterealtime/Smack | smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/OmemoManager.java | OmemoManager.distrustOmemoIdentity | public void distrustOmemoIdentity(OmemoDevice device, OmemoFingerprint fingerprint) {
if (trustCallback == null) {
throw new IllegalStateException("No TrustCallback set.");
}
trustCallback.setTrust(device, fingerprint, TrustState.untrusted);
} | java | public void distrustOmemoIdentity(OmemoDevice device, OmemoFingerprint fingerprint) {
if (trustCallback == null) {
throw new IllegalStateException("No TrustCallback set.");
}
trustCallback.setTrust(device, fingerprint, TrustState.untrusted);
} | [
"public",
"void",
"distrustOmemoIdentity",
"(",
"OmemoDevice",
"device",
",",
"OmemoFingerprint",
"fingerprint",
")",
"{",
"if",
"(",
"trustCallback",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"No TrustCallback set.\"",
")",
";",
"}",
... | Distrust the fingerprint/OmemoDevice tuple.
The fingerprint must be the lowercase, hexadecimal fingerprint of the identityKey of the device and must
be of length 64.
@param device device
@param fingerprint fingerprint | [
"Distrust",
"the",
"fingerprint",
"/",
"OmemoDevice",
"tuple",
".",
"The",
"fingerprint",
"must",
"be",
"the",
"lowercase",
"hexadecimal",
"fingerprint",
"of",
"the",
"identityKey",
"of",
"the",
"device",
"and",
"must",
"be",
"of",
"length",
"64",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/OmemoManager.java#L435-L441 |
vigna/Sux4J | src/it/unimi/dsi/sux4j/mph/HypergraphSorter.java | HypergraphSorter.tripleToEdge | public static void tripleToEdge(final long[] triple, final long seed, final int numVertices, final int e[]) {
tripleToEdge(triple, seed, numVertices, (int)(numVertices * 0xAAAAAAABL >>> 33), e); // Fast division by 3
} | java | public static void tripleToEdge(final long[] triple, final long seed, final int numVertices, final int e[]) {
tripleToEdge(triple, seed, numVertices, (int)(numVertices * 0xAAAAAAABL >>> 33), e); // Fast division by 3
} | [
"public",
"static",
"void",
"tripleToEdge",
"(",
"final",
"long",
"[",
"]",
"triple",
",",
"final",
"long",
"seed",
",",
"final",
"int",
"numVertices",
",",
"final",
"int",
"e",
"[",
"]",
")",
"{",
"tripleToEdge",
"(",
"triple",
",",
"seed",
",",
"numV... | Turns a triple of longs into a 3-hyperedge.
@param triple a triple of intermediate hashes.
@param seed the seed for the hash function.
@param numVertices the number of vertices in the underlying hypergraph.
@param e an array to store the resulting edge.
@see #bitVectorToEdge(BitVector, long, int, int, int[]) | [
"Turns",
"a",
"triple",
"of",
"longs",
"into",
"a",
"3",
"-",
"hyperedge",
"."
] | train | https://github.com/vigna/Sux4J/blob/d57de8fa897c7d273e0e6dae7a3274174f175a5f/src/it/unimi/dsi/sux4j/mph/HypergraphSorter.java#L253-L255 |
JavaMoney/jsr354-api | src/main/java/javax/money/Monetary.java | Monetary.isRoundingAvailable | public static boolean isRoundingAvailable(RoundingQuery roundingQuery) {
return Optional.ofNullable(monetaryRoundingsSingletonSpi()).orElseThrow(
() -> new MonetaryException("No MonetaryRoundingsSpi loaded, query functionality is not available."))
.isRoundingAvailable(roundingQuery);
} | java | public static boolean isRoundingAvailable(RoundingQuery roundingQuery) {
return Optional.ofNullable(monetaryRoundingsSingletonSpi()).orElseThrow(
() -> new MonetaryException("No MonetaryRoundingsSpi loaded, query functionality is not available."))
.isRoundingAvailable(roundingQuery);
} | [
"public",
"static",
"boolean",
"isRoundingAvailable",
"(",
"RoundingQuery",
"roundingQuery",
")",
"{",
"return",
"Optional",
".",
"ofNullable",
"(",
"monetaryRoundingsSingletonSpi",
"(",
")",
")",
".",
"orElseThrow",
"(",
"(",
")",
"->",
"new",
"MonetaryException",
... | Checks if a {@link MonetaryRounding} matching the query is available.
@param roundingQuery The {@link javax.money.RoundingQuery} that may contains arbitrary parameters to be
evaluated.
@return true, if a corresponding {@link javax.money.MonetaryRounding} is available.
@throws IllegalArgumentException if no such rounding is registered using a
{@link javax.money.spi.RoundingProviderSpi} instance. | [
"Checks",
"if",
"a",
"{",
"@link",
"MonetaryRounding",
"}",
"matching",
"the",
"query",
"is",
"available",
"."
] | train | https://github.com/JavaMoney/jsr354-api/blob/49a7ae436eaf45cac1040879185531ef22de5525/src/main/java/javax/money/Monetary.java#L234-L238 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/jassimp/AiMaterial.java | AiMaterial.getProperty | public Property getProperty(String key, int semantic, int index) {
for (Property property : m_properties) {
if (property.getKey().equals(key) &&
property.m_semantic == semantic &&
property.m_index == index) {
return property;
}
}
return null;
} | java | public Property getProperty(String key, int semantic, int index) {
for (Property property : m_properties) {
if (property.getKey().equals(key) &&
property.m_semantic == semantic &&
property.m_index == index) {
return property;
}
}
return null;
} | [
"public",
"Property",
"getProperty",
"(",
"String",
"key",
",",
"int",
"semantic",
",",
"int",
"index",
")",
"{",
"for",
"(",
"Property",
"property",
":",
"m_properties",
")",
"{",
"if",
"(",
"property",
".",
"getKey",
"(",
")",
".",
"equals",
"(",
"ke... | Returns a single property based on its key.
@param key the key
@param semantic the semantic type (texture type)
@param index the index
@return the property or null if the property is not set | [
"Returns",
"a",
"single",
"property",
"based",
"on",
"its",
"key",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/jassimp/AiMaterial.java#L1194-L1205 |
Azure/azure-sdk-for-java | sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DataMaskingPoliciesInner.java | DataMaskingPoliciesInner.getAsync | public Observable<DataMaskingPolicyInner> getAsync(String resourceGroupName, String serverName, String databaseName) {
return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<DataMaskingPolicyInner>, DataMaskingPolicyInner>() {
@Override
public DataMaskingPolicyInner call(ServiceResponse<DataMaskingPolicyInner> response) {
return response.body();
}
});
} | java | public Observable<DataMaskingPolicyInner> getAsync(String resourceGroupName, String serverName, String databaseName) {
return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<DataMaskingPolicyInner>, DataMaskingPolicyInner>() {
@Override
public DataMaskingPolicyInner call(ServiceResponse<DataMaskingPolicyInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DataMaskingPolicyInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
... | Gets a database data masking policy.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DataMaskingPolicyInner object | [
"Gets",
"a",
"database",
"data",
"masking",
"policy",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DataMaskingPoliciesInner.java#L207-L214 |
Doctoror/ParticlesDrawable | opengl/src/main/java/com/doctoror/particlesdrawable/opengl/chooser/FailsafeEGLConfigChooserFactory.java | FailsafeEGLConfigChooserFactory.newFailsafeEGLConfigChooser | @NonNull
public static EGLConfigChooser newFailsafeEGLConfigChooser(
final int samples,
@Nullable final EGLConfigChooserCallback callback) {
if (samples < 0) {
throw new IllegalArgumentException("samples must not be negative");
}
if (samples == 0) {
return new FailsafeRGB888ConfigChooser(callback);
} else {
return new FailsafeMultisamplingConfigChooser(samples, callback);
}
} | java | @NonNull
public static EGLConfigChooser newFailsafeEGLConfigChooser(
final int samples,
@Nullable final EGLConfigChooserCallback callback) {
if (samples < 0) {
throw new IllegalArgumentException("samples must not be negative");
}
if (samples == 0) {
return new FailsafeRGB888ConfigChooser(callback);
} else {
return new FailsafeMultisamplingConfigChooser(samples, callback);
}
} | [
"@",
"NonNull",
"public",
"static",
"EGLConfigChooser",
"newFailsafeEGLConfigChooser",
"(",
"final",
"int",
"samples",
",",
"@",
"Nullable",
"final",
"EGLConfigChooserCallback",
"callback",
")",
"{",
"if",
"(",
"samples",
"<",
"0",
")",
"{",
"throw",
"new",
"Ill... | Creates an {@link EGLConfigChooser} for given multisampling value.
Will fallback to lower multisampling mode or no multisampling mode at all if unsupported.
@param samples multisampling mode. Must be a positive number and a power of two. May be 0 for
no multisampling.
@param callback the {@link EGLConfigChooserCallback} to notify with the chosen config
@return new {@link EGLConfigChooser} for the given parameters. | [
"Creates",
"an",
"{",
"@link",
"EGLConfigChooser",
"}",
"for",
"given",
"multisampling",
"value",
".",
"Will",
"fallback",
"to",
"lower",
"multisampling",
"mode",
"or",
"no",
"multisampling",
"mode",
"at",
"all",
"if",
"unsupported",
"."
] | train | https://github.com/Doctoror/ParticlesDrawable/blob/97ab510936692b5cf47822df78dd455f5e4b7ddf/opengl/src/main/java/com/doctoror/particlesdrawable/opengl/chooser/FailsafeEGLConfigChooserFactory.java#L41-L54 |
romannurik/muzei | muzei-api/src/main/java/com/google/android/apps/muzei/api/MuzeiArtSource.java | MuzeiArtSource.getSharedPreferences | protected static SharedPreferences getSharedPreferences(Context context, @NonNull String sourceName) {
return context.getSharedPreferences("muzeiartsource_" + sourceName, 0);
} | java | protected static SharedPreferences getSharedPreferences(Context context, @NonNull String sourceName) {
return context.getSharedPreferences("muzeiartsource_" + sourceName, 0);
} | [
"protected",
"static",
"SharedPreferences",
"getSharedPreferences",
"(",
"Context",
"context",
",",
"@",
"NonNull",
"String",
"sourceName",
")",
"{",
"return",
"context",
".",
"getSharedPreferences",
"(",
"\"muzeiartsource_\"",
"+",
"sourceName",
",",
"0",
")",
";",... | Convenience method for accessing preferences specific to the source (with the given name
within this package. The source name must be the one provided in the
{@link #MuzeiArtSource(String)} constructor. This static method is useful for exposing source
preferences to other application components such as the source settings activity.
@param context the context; can be an application context.
@param sourceName the source name, provided in the {@link #MuzeiArtSource(String)}
constructor.
@return the {@link SharedPreferences} where the MuzeiArtSource associated with the
sourceName stores its state. | [
"Convenience",
"method",
"for",
"accessing",
"preferences",
"specific",
"to",
"the",
"source",
"(",
"with",
"the",
"given",
"name",
"within",
"this",
"package",
".",
"The",
"source",
"name",
"must",
"be",
"the",
"one",
"provided",
"in",
"the",
"{",
"@link",
... | train | https://github.com/romannurik/muzei/blob/d00777a5fc59f34471be338c814ea85ddcbde304/muzei-api/src/main/java/com/google/android/apps/muzei/api/MuzeiArtSource.java#L649-L651 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/sql/DriverManager.java | DriverManager.getDriver | @CallerSensitive
public static Driver getDriver(String url)
throws SQLException {
println("DriverManager.getDriver(\"" + url + "\")");
ClassLoader callerClassLoader = ClassLoader.getSystemClassLoader();
// Walk through the loaded registeredDrivers attempting to locate someone
// who understands the given URL.
for (DriverInfo aDriver : registeredDrivers) {
// If the caller does not have permission to load the driver then
// skip it.
if(isDriverAllowed(aDriver.driver, callerClassLoader)) {
try {
if(aDriver.driver.acceptsURL(url)) {
// Success!
println("getDriver returning " + aDriver.driver.getClass().getName());
return (aDriver.driver);
}
} catch(SQLException sqe) {
// Drop through and try the next driver.
}
} else {
println(" skipping: " + aDriver.driver.getClass().getName());
}
}
println("getDriver: no suitable driver");
throw new SQLException("No suitable driver", "08001");
} | java | @CallerSensitive
public static Driver getDriver(String url)
throws SQLException {
println("DriverManager.getDriver(\"" + url + "\")");
ClassLoader callerClassLoader = ClassLoader.getSystemClassLoader();
// Walk through the loaded registeredDrivers attempting to locate someone
// who understands the given URL.
for (DriverInfo aDriver : registeredDrivers) {
// If the caller does not have permission to load the driver then
// skip it.
if(isDriverAllowed(aDriver.driver, callerClassLoader)) {
try {
if(aDriver.driver.acceptsURL(url)) {
// Success!
println("getDriver returning " + aDriver.driver.getClass().getName());
return (aDriver.driver);
}
} catch(SQLException sqe) {
// Drop through and try the next driver.
}
} else {
println(" skipping: " + aDriver.driver.getClass().getName());
}
}
println("getDriver: no suitable driver");
throw new SQLException("No suitable driver", "08001");
} | [
"@",
"CallerSensitive",
"public",
"static",
"Driver",
"getDriver",
"(",
"String",
"url",
")",
"throws",
"SQLException",
"{",
"println",
"(",
"\"DriverManager.getDriver(\\\"\"",
"+",
"url",
"+",
"\"\\\")\"",
")",
";",
"ClassLoader",
"callerClassLoader",
"=",
"ClassLo... | Attempts to locate a driver that understands the given URL.
The <code>DriverManager</code> attempts to select an appropriate driver from
the set of registered JDBC drivers.
@param url a database URL of the form
<code>jdbc:<em>subprotocol</em>:<em>subname</em></code>
@return a <code>Driver</code> object representing a driver
that can connect to the given URL
@exception SQLException if a database access error occurs | [
"Attempts",
"to",
"locate",
"a",
"driver",
"that",
"understands",
"the",
"given",
"URL",
".",
"The",
"<code",
">",
"DriverManager<",
"/",
"code",
">",
"attempts",
"to",
"select",
"an",
"appropriate",
"driver",
"from",
"the",
"set",
"of",
"registered",
"JDBC"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/sql/DriverManager.java#L244-L276 |
CrawlScript/WebCollector | src/main/java/cn/edu/hfut/dmic/webcollector/crawler/Crawler.java | Crawler.addSeed | public void addSeed(String url, String type, boolean force) {
addSeedAndReturn(url,force).type(type);
} | java | public void addSeed(String url, String type, boolean force) {
addSeedAndReturn(url,force).type(type);
} | [
"public",
"void",
"addSeed",
"(",
"String",
"url",
",",
"String",
"type",
",",
"boolean",
"force",
")",
"{",
"addSeedAndReturn",
"(",
"url",
",",
"force",
")",
".",
"type",
"(",
"type",
")",
";",
"}"
] | 与addSeed(CrawlDatum datum, boolean force)类似
@param url 种子URL
@param type 种子的type标识信息
@param force 是否强制注入 | [
"与addSeed",
"(",
"CrawlDatum",
"datum",
"boolean",
"force",
")",
"类似"
] | train | https://github.com/CrawlScript/WebCollector/blob/4ca71ec0e69d354feaf64319d76e64663159902d/src/main/java/cn/edu/hfut/dmic/webcollector/crawler/Crawler.java#L252-L254 |
teatrove/teatrove | trove/src/main/java/org/teatrove/trove/net/MultiPooledSocketFactory.java | MultiPooledSocketFactory.createSocketFactory | protected SocketFactory createSocketFactory(InetAddress address,
int port,
InetAddress localAddr,
int localPort,
long timeout)
{
SocketFactory factory;
factory = new PlainSocketFactory
(address, port, localAddr, localPort, timeout);
factory = new PooledSocketFactory(factory);
factory = new LazySocketFactory(factory);
return factory;
} | java | protected SocketFactory createSocketFactory(InetAddress address,
int port,
InetAddress localAddr,
int localPort,
long timeout)
{
SocketFactory factory;
factory = new PlainSocketFactory
(address, port, localAddr, localPort, timeout);
factory = new PooledSocketFactory(factory);
factory = new LazySocketFactory(factory);
return factory;
} | [
"protected",
"SocketFactory",
"createSocketFactory",
"(",
"InetAddress",
"address",
",",
"int",
"port",
",",
"InetAddress",
"localAddr",
",",
"int",
"localPort",
",",
"long",
"timeout",
")",
"{",
"SocketFactory",
"factory",
";",
"factory",
"=",
"new",
"PlainSocket... | Create socket factories for newly resolved addresses. Default
implementation returns a LazySocketFactory wrapping a
PooledSocketFactory wrapping a PlainSocketFactory. | [
"Create",
"socket",
"factories",
"for",
"newly",
"resolved",
"addresses",
".",
"Default",
"implementation",
"returns",
"a",
"LazySocketFactory",
"wrapping",
"a",
"PooledSocketFactory",
"wrapping",
"a",
"PlainSocketFactory",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/net/MultiPooledSocketFactory.java#L137-L149 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/GVRMesh.java | GVRMesh.setTexCoords | public void setTexCoords(float [] texCoords, int index)
{
String key = (index > 0) ? (KEY_TEXCOORD + index) : KEY_TEXCOORD;
mVertices.setFloatArray(key, texCoords);
} | java | public void setTexCoords(float [] texCoords, int index)
{
String key = (index > 0) ? (KEY_TEXCOORD + index) : KEY_TEXCOORD;
mVertices.setFloatArray(key, texCoords);
} | [
"public",
"void",
"setTexCoords",
"(",
"float",
"[",
"]",
"texCoords",
",",
"int",
"index",
")",
"{",
"String",
"key",
"=",
"(",
"index",
">",
"0",
")",
"?",
"(",
"KEY_TEXCOORD",
"+",
"index",
")",
":",
"KEY_TEXCOORD",
";",
"mVertices",
".",
"setFloatA... | Populates a set of texture coordinates for the mesh.
<p>
A mesh may have multiple sets of texture coordinates
Each texture coordinate is represented as a packed {@code float} pair:
<p>
<code>{ u0, v0, u1, v1, u2, v2, ...}</code>
This function updates the <i>a_texcoordN</i> vertex attribute where N is
the value of the <i>index</i> argument.
@param texCoords
Array containing the packed texture coordinate data.
@param index
0-based index indicating which set of texture coordinates to update.
@see #getTexCoords()
@see GVRVertexBuffer#setFloatArray(String, float[]) | [
"Populates",
"a",
"set",
"of",
"texture",
"coordinates",
"for",
"the",
"mesh",
".",
"<p",
">",
"A",
"mesh",
"may",
"have",
"multiple",
"sets",
"of",
"texture",
"coordinates",
"Each",
"texture",
"coordinate",
"is",
"represented",
"as",
"a",
"packed",
"{"
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRMesh.java#L321-L325 |
httl/httl | httl/src/main/java/httl/spi/codecs/json/JSONObject.java | JSONObject.getInt | public int getInt(String key, int def) {
Object tmp = objectMap.get(key);
return tmp != null && tmp instanceof Number ? ((Number) tmp).intValue()
: def;
} | java | public int getInt(String key, int def) {
Object tmp = objectMap.get(key);
return tmp != null && tmp instanceof Number ? ((Number) tmp).intValue()
: def;
} | [
"public",
"int",
"getInt",
"(",
"String",
"key",
",",
"int",
"def",
")",
"{",
"Object",
"tmp",
"=",
"objectMap",
".",
"get",
"(",
"key",
")",
";",
"return",
"tmp",
"!=",
"null",
"&&",
"tmp",
"instanceof",
"Number",
"?",
"(",
"(",
"Number",
")",
"tm... | get int value.
@param key key.
@param def default value.
@return value or default value. | [
"get",
"int",
"value",
"."
] | train | https://github.com/httl/httl/blob/e13e00f4ab41252a8f53d6dafd4a6610be9dcaad/httl/src/main/java/httl/spi/codecs/json/JSONObject.java#L63-L67 |
signit-wesign/java-sdk | src/main/java/cn/signit/sdk/util/HmacSignatureBuilder.java | HmacSignatureBuilder.isHashEqualsWithBase64 | public boolean isHashEqualsWithBase64(String expectedSignatureBase64, BuilderMode builderMode) {
try {
final byte[] signature = build(builderMode);
return MessageDigest.isEqual(signature, DatatypeConverter.parseBase64Binary(expectedSignatureBase64));
} catch (Throwable e) {
System.err.println(e.getMessage());
return false;
}
} | java | public boolean isHashEqualsWithBase64(String expectedSignatureBase64, BuilderMode builderMode) {
try {
final byte[] signature = build(builderMode);
return MessageDigest.isEqual(signature, DatatypeConverter.parseBase64Binary(expectedSignatureBase64));
} catch (Throwable e) {
System.err.println(e.getMessage());
return false;
}
} | [
"public",
"boolean",
"isHashEqualsWithBase64",
"(",
"String",
"expectedSignatureBase64",
",",
"BuilderMode",
"builderMode",
")",
"{",
"try",
"{",
"final",
"byte",
"[",
"]",
"signature",
"=",
"build",
"(",
"builderMode",
")",
";",
"return",
"MessageDigest",
".",
... | 判断期望摘要是否与已构建的摘要相等.
@param expectedSignatureBase64
传入的期望摘要base64编码表示的字符串
@param builderMode
采用的构建模式
@return <code>true</code> - 期望摘要与已构建的摘要相等; <code>false</code> -
期望摘要与已构建的摘要不相等
@author zhd
@since 1.0.0 | [
"判断期望摘要是否与已构建的摘要相等",
"."
] | train | https://github.com/signit-wesign/java-sdk/blob/6f3196c9d444818a953396fdaa8ffed9794d9530/src/main/java/cn/signit/sdk/util/HmacSignatureBuilder.java#L753-L761 |
GoogleCloudPlatform/bigdata-interop | gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageReadChannel.java | GoogleCloudStorageReadChannel.initMetadata | @VisibleForTesting
protected void initMetadata(
@Nullable String encoding, long sizeFromMetadata, @Nullable String generation)
throws IOException {
checkState(
!metadataInitialized,
"can not initialize metadata, it already initialized for '%s'", resourceIdString);
gzipEncoded = nullToEmpty(encoding).contains(GZIP_ENCODING);
if (gzipEncoded) {
size = Long.MAX_VALUE;
} else {
size = sizeFromMetadata;
}
randomAccess = !gzipEncoded && readOptions.getFadvise() == Fadvise.RANDOM;
checkEncodingAndAccess();
initGeneration(generation);
metadataInitialized = true;
logger.atFine().log(
"Initialized metadata (gzipEncoded=%s, size=%s, randomAccess=%s, generation=%s) for '%s'",
gzipEncoded, size, randomAccess, generation, resourceIdString);
} | java | @VisibleForTesting
protected void initMetadata(
@Nullable String encoding, long sizeFromMetadata, @Nullable String generation)
throws IOException {
checkState(
!metadataInitialized,
"can not initialize metadata, it already initialized for '%s'", resourceIdString);
gzipEncoded = nullToEmpty(encoding).contains(GZIP_ENCODING);
if (gzipEncoded) {
size = Long.MAX_VALUE;
} else {
size = sizeFromMetadata;
}
randomAccess = !gzipEncoded && readOptions.getFadvise() == Fadvise.RANDOM;
checkEncodingAndAccess();
initGeneration(generation);
metadataInitialized = true;
logger.atFine().log(
"Initialized metadata (gzipEncoded=%s, size=%s, randomAccess=%s, generation=%s) for '%s'",
gzipEncoded, size, randomAccess, generation, resourceIdString);
} | [
"@",
"VisibleForTesting",
"protected",
"void",
"initMetadata",
"(",
"@",
"Nullable",
"String",
"encoding",
",",
"long",
"sizeFromMetadata",
",",
"@",
"Nullable",
"String",
"generation",
")",
"throws",
"IOException",
"{",
"checkState",
"(",
"!",
"metadataInitialized"... | Initializes metadata (size, encoding, etc) from passed parameters. | [
"Initializes",
"metadata",
"(",
"size",
"encoding",
"etc",
")",
"from",
"passed",
"parameters",
"."
] | train | https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageReadChannel.java#L795-L818 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/solvers/accumulation/BasicGradientsAccumulator.java | BasicGradientsAccumulator.applyUpdate | @Override
public void applyUpdate(StepFunction function, INDArray params, INDArray grad, boolean isFinalStep) {
try {
updatesLock.readLock().lock();
firstOne.compareAndSet(-1L, Thread.currentThread().getId());
if (hasSomething.get())
function.step(params, updates);
barrier.await();
if (firstOne.get() == Thread.currentThread().getId()) {
// one thread just nullifies this array
updates.assign(0.0);
hasSomething.set(false);
firstOne.set(-1L);
}
updatesLock.readLock().unlock();
barrier.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
} | java | @Override
public void applyUpdate(StepFunction function, INDArray params, INDArray grad, boolean isFinalStep) {
try {
updatesLock.readLock().lock();
firstOne.compareAndSet(-1L, Thread.currentThread().getId());
if (hasSomething.get())
function.step(params, updates);
barrier.await();
if (firstOne.get() == Thread.currentThread().getId()) {
// one thread just nullifies this array
updates.assign(0.0);
hasSomething.set(false);
firstOne.set(-1L);
}
updatesLock.readLock().unlock();
barrier.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
} | [
"@",
"Override",
"public",
"void",
"applyUpdate",
"(",
"StepFunction",
"function",
",",
"INDArray",
"params",
",",
"INDArray",
"grad",
",",
"boolean",
"isFinalStep",
")",
"{",
"try",
"{",
"updatesLock",
".",
"readLock",
"(",
")",
".",
"lock",
"(",
")",
";"... | This method applies accumulated updates via given StepFunction
@param function
@param params | [
"This",
"method",
"applies",
"accumulated",
"updates",
"via",
"given",
"StepFunction"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/solvers/accumulation/BasicGradientsAccumulator.java#L105-L133 |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java | DeltaFIFO.queueActionLocked | private void queueActionLocked(DeltaType actionType, Object obj) {
String id = this.keyOf(obj);
// If object is supposed to be deleted (last event is Deleted),
// then we should ignore Sync events, because it would result in
// recreation of this object.
if (actionType == DeltaType.Sync && this.willObjectBeDeletedLocked(id)) {
return;
}
Deque<MutablePair<DeltaType, Object>> deltas = items.get(id);
if (deltas == null) {
Deque<MutablePair<DeltaType, Object>> deltaList = new LinkedList<>();
deltaList.add(new MutablePair(actionType, obj));
deltas = new LinkedList<>(deltaList);
} else {
deltas.add(new MutablePair<DeltaType, Object>(actionType, obj));
}
// TODO(yue9944882): Eliminate the force class casting here
Deque<MutablePair<DeltaType, Object>> combinedDeltaList =
combineDeltas((LinkedList<MutablePair<DeltaType, Object>>) deltas);
boolean exist = items.containsKey(id);
if (combinedDeltaList != null && combinedDeltaList.size() > 0) {
if (!exist) {
this.queue.add(id);
}
this.items.put(id, new LinkedList<>(combinedDeltaList));
notEmpty.signalAll();
} else {
this.items.remove(id);
}
} | java | private void queueActionLocked(DeltaType actionType, Object obj) {
String id = this.keyOf(obj);
// If object is supposed to be deleted (last event is Deleted),
// then we should ignore Sync events, because it would result in
// recreation of this object.
if (actionType == DeltaType.Sync && this.willObjectBeDeletedLocked(id)) {
return;
}
Deque<MutablePair<DeltaType, Object>> deltas = items.get(id);
if (deltas == null) {
Deque<MutablePair<DeltaType, Object>> deltaList = new LinkedList<>();
deltaList.add(new MutablePair(actionType, obj));
deltas = new LinkedList<>(deltaList);
} else {
deltas.add(new MutablePair<DeltaType, Object>(actionType, obj));
}
// TODO(yue9944882): Eliminate the force class casting here
Deque<MutablePair<DeltaType, Object>> combinedDeltaList =
combineDeltas((LinkedList<MutablePair<DeltaType, Object>>) deltas);
boolean exist = items.containsKey(id);
if (combinedDeltaList != null && combinedDeltaList.size() > 0) {
if (!exist) {
this.queue.add(id);
}
this.items.put(id, new LinkedList<>(combinedDeltaList));
notEmpty.signalAll();
} else {
this.items.remove(id);
}
} | [
"private",
"void",
"queueActionLocked",
"(",
"DeltaType",
"actionType",
",",
"Object",
"obj",
")",
"{",
"String",
"id",
"=",
"this",
".",
"keyOf",
"(",
"obj",
")",
";",
"// If object is supposed to be deleted (last event is Deleted),",
"// then we should ignore Sync event... | queueActionLocked appends to the delta list for the object. Caller must hold the lock. | [
"queueActionLocked",
"appends",
"to",
"the",
"delta",
"list",
"for",
"the",
"object",
".",
"Caller",
"must",
"hold",
"the",
"lock",
"."
] | train | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java#L337-L370 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/pca/weightfunctions/QuadraticStddevWeight.java | QuadraticStddevWeight.getWeight | @Override
public double getWeight(double distance, double max, double stddev) {
if(stddev <= 0) {
return 1;
}
double scaleddistance = distance / (scaling * stddev);
// After this, the result would be negative.
if(scaleddistance >= 1.0) {
return 0.0;
}
return 1.0 - scaleddistance * scaleddistance;
} | java | @Override
public double getWeight(double distance, double max, double stddev) {
if(stddev <= 0) {
return 1;
}
double scaleddistance = distance / (scaling * stddev);
// After this, the result would be negative.
if(scaleddistance >= 1.0) {
return 0.0;
}
return 1.0 - scaleddistance * scaleddistance;
} | [
"@",
"Override",
"public",
"double",
"getWeight",
"(",
"double",
"distance",
",",
"double",
"max",
",",
"double",
"stddev",
")",
"{",
"if",
"(",
"stddev",
"<=",
"0",
")",
"{",
"return",
"1",
";",
"}",
"double",
"scaleddistance",
"=",
"distance",
"/",
"... | Evaluate weight function at given parameters. max is ignored. | [
"Evaluate",
"weight",
"function",
"at",
"given",
"parameters",
".",
"max",
"is",
"ignored",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/pca/weightfunctions/QuadraticStddevWeight.java#L43-L54 |
lucee/Lucee | core/src/main/java/lucee/commons/lang/HTMLUtil.java | HTMLUtil.getURLS | public List<URL> getURLS(String html, URL url) {
List<URL> urls = new ArrayList<URL>();
SourceCode cfml = new SourceCode(html, false, CFMLEngine.DIALECT_CFML);
while (!cfml.isAfterLast()) {
if (cfml.forwardIfCurrent('<')) {
for (int i = 0; i < tags.length; i++) {
if (cfml.forwardIfCurrent(tags[i].tag + " ")) {
getSingleUrl(urls, cfml, tags[i], url);
}
}
}
else {
cfml.next();
}
}
return urls;
} | java | public List<URL> getURLS(String html, URL url) {
List<URL> urls = new ArrayList<URL>();
SourceCode cfml = new SourceCode(html, false, CFMLEngine.DIALECT_CFML);
while (!cfml.isAfterLast()) {
if (cfml.forwardIfCurrent('<')) {
for (int i = 0; i < tags.length; i++) {
if (cfml.forwardIfCurrent(tags[i].tag + " ")) {
getSingleUrl(urls, cfml, tags[i], url);
}
}
}
else {
cfml.next();
}
}
return urls;
} | [
"public",
"List",
"<",
"URL",
">",
"getURLS",
"(",
"String",
"html",
",",
"URL",
"url",
")",
"{",
"List",
"<",
"URL",
">",
"urls",
"=",
"new",
"ArrayList",
"<",
"URL",
">",
"(",
")",
";",
"SourceCode",
"cfml",
"=",
"new",
"SourceCode",
"(",
"html",... | returns all urls in a html String
@param html HTML String to search urls
@param url Absolute URL path to set
@return urls found in html String | [
"returns",
"all",
"urls",
"in",
"a",
"html",
"String"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/lang/HTMLUtil.java#L50-L67 |
roboconf/roboconf-platform | karaf/roboconf-karaf-commands-dm/src/main/java/net/roboconf/karaf/commands/dm/KarafDmCommandsUtils.java | KarafDmCommandsUtils.findInstances | public static RbcfInfo findInstances(
Manager manager,
String applicationName,
String scopedInstancePath,
PrintStream out ) {
ManagedApplication ma = null;
List<Instance> scopedInstances = new ArrayList<> ();
Instance scopedInstance;
if(( ma = manager.applicationMngr().findManagedApplicationByName( applicationName )) == null )
out.println( "Unknown application: " + applicationName + "." );
else if( scopedInstancePath == null )
scopedInstances.addAll( InstanceHelpers.findAllScopedInstances( ma.getApplication()));
else if(( scopedInstance = InstanceHelpers.findInstanceByPath( ma.getApplication(), scopedInstancePath )) == null )
out.println( "There is no " + scopedInstancePath + " instance in " + applicationName + "." );
else if( ! InstanceHelpers.isTarget( scopedInstance ))
out.println( "Instance " + scopedInstancePath + " is not a scoped instance in " + applicationName + "." );
else
scopedInstances.add( scopedInstance );
return new RbcfInfo( scopedInstances, ma );
} | java | public static RbcfInfo findInstances(
Manager manager,
String applicationName,
String scopedInstancePath,
PrintStream out ) {
ManagedApplication ma = null;
List<Instance> scopedInstances = new ArrayList<> ();
Instance scopedInstance;
if(( ma = manager.applicationMngr().findManagedApplicationByName( applicationName )) == null )
out.println( "Unknown application: " + applicationName + "." );
else if( scopedInstancePath == null )
scopedInstances.addAll( InstanceHelpers.findAllScopedInstances( ma.getApplication()));
else if(( scopedInstance = InstanceHelpers.findInstanceByPath( ma.getApplication(), scopedInstancePath )) == null )
out.println( "There is no " + scopedInstancePath + " instance in " + applicationName + "." );
else if( ! InstanceHelpers.isTarget( scopedInstance ))
out.println( "Instance " + scopedInstancePath + " is not a scoped instance in " + applicationName + "." );
else
scopedInstances.add( scopedInstance );
return new RbcfInfo( scopedInstances, ma );
} | [
"public",
"static",
"RbcfInfo",
"findInstances",
"(",
"Manager",
"manager",
",",
"String",
"applicationName",
",",
"String",
"scopedInstancePath",
",",
"PrintStream",
"out",
")",
"{",
"ManagedApplication",
"ma",
"=",
"null",
";",
"List",
"<",
"Instance",
">",
"s... | Finds instances for a given application.
@param manager
@param applicationName
@param scopedInstancePath
@param out
@return an object with non-null list of instances and a (nullable) managed application | [
"Finds",
"instances",
"for",
"a",
"given",
"application",
"."
] | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/karaf/roboconf-karaf-commands-dm/src/main/java/net/roboconf/karaf/commands/dm/KarafDmCommandsUtils.java#L59-L85 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderTransaction.java | SpiderTransaction.deleteShardedLinkValue | public void deleteShardedLinkValue(String objID, FieldDefinition linkDef, String targetObjID, int shardNo) {
assert linkDef.isSharded();
assert shardNo > 0;
deleteColumn(SpiderService.termsStoreName(linkDef.getTableDef()),
SpiderService.shardedLinkTermRowKey(linkDef, objID, shardNo),
targetObjID);
} | java | public void deleteShardedLinkValue(String objID, FieldDefinition linkDef, String targetObjID, int shardNo) {
assert linkDef.isSharded();
assert shardNo > 0;
deleteColumn(SpiderService.termsStoreName(linkDef.getTableDef()),
SpiderService.shardedLinkTermRowKey(linkDef, objID, shardNo),
targetObjID);
} | [
"public",
"void",
"deleteShardedLinkValue",
"(",
"String",
"objID",
",",
"FieldDefinition",
"linkDef",
",",
"String",
"targetObjID",
",",
"int",
"shardNo",
")",
"{",
"assert",
"linkDef",
".",
"isSharded",
"(",
")",
";",
"assert",
"shardNo",
">",
"0",
";",
"d... | Delete a link value column in the Terms store for a sharded link.
@param objID ID of object that owns the link field.
@param linkDef {@link FieldDefinition} of (sharded) link field.
@param targetObjID ID of referenced object.
@param shardNo Shard number. Must be > 0. | [
"Delete",
"a",
"link",
"value",
"column",
"in",
"the",
"Terms",
"store",
"for",
"a",
"sharded",
"link",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderTransaction.java#L464-L470 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java | SDBaseOps.fill | public SDVariable fill(SDVariable shape, org.nd4j.linalg.api.buffer.DataType dataType, double value) {
return fill(null, shape, dataType, value);
} | java | public SDVariable fill(SDVariable shape, org.nd4j.linalg.api.buffer.DataType dataType, double value) {
return fill(null, shape, dataType, value);
} | [
"public",
"SDVariable",
"fill",
"(",
"SDVariable",
"shape",
",",
"org",
".",
"nd4j",
".",
"linalg",
".",
"api",
".",
"buffer",
".",
"DataType",
"dataType",
",",
"double",
"value",
")",
"{",
"return",
"fill",
"(",
"null",
",",
"shape",
",",
"dataType",
... | Generate an output variable with the specified (dynamic) shape with all elements set to the specified value
@param shape Shape: must be a 1D array/variable
@param value Value to set all elements to
@return Output variable | [
"Generate",
"an",
"output",
"variable",
"with",
"the",
"specified",
"(",
"dynamic",
")",
"shape",
"with",
"all",
"elements",
"set",
"to",
"the",
"specified",
"value"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java#L526-L528 |
kevoree/kevoree-library | toys/src/main/java/com/rendion/util/WindowUtils.java | WindowUtils.createAncestorListener | private static AncestorListener createAncestorListener(JComponent component, final WindowFocusListener windowListener)
{
final WeakReference<JComponent> weakReference = new WeakReference<JComponent>(component);
return new AncestorListener()
{
public void ancestorAdded(AncestorEvent event)
{
// TODO if the WeakReference's object is null, remove the WeakReference
// as an
// TODO AncestorListener.
final Window window = weakReference.get() == null ? null : SwingUtilities
.getWindowAncestor(weakReference.get());
if (window != null)
{
window.removeWindowFocusListener(windowListener);
window.addWindowFocusListener(windowListener);
// notify the listener of the original focus state of the window,
// which ensures
// that the listener is in sync with the actual window state.
fireInitialFocusEvent(windowListener, window);
}
}
private void fireInitialFocusEvent(WindowFocusListener windowListener, Window window)
{
Window focusedWindow = FocusManager.getCurrentManager().getFocusedWindow();
// fire a fake event to the given listener indicating the actual focus
// state of the
// given window.
if (window == focusedWindow)
{
windowListener.windowGainedFocus(new WindowEvent(window, WindowEvent.WINDOW_GAINED_FOCUS));
}
else
{
windowListener.windowGainedFocus(new WindowEvent(window, WindowEvent.WINDOW_LOST_FOCUS));
}
}
public void ancestorRemoved(AncestorEvent event)
{
Window window = weakReference.get() == null ? null : SwingUtilities.getWindowAncestor(weakReference.get());
if (window != null)
{
window.removeWindowFocusListener(windowListener);
}
}
public void ancestorMoved(AncestorEvent event)
{
// no implementation.
}
};
} | java | private static AncestorListener createAncestorListener(JComponent component, final WindowFocusListener windowListener)
{
final WeakReference<JComponent> weakReference = new WeakReference<JComponent>(component);
return new AncestorListener()
{
public void ancestorAdded(AncestorEvent event)
{
// TODO if the WeakReference's object is null, remove the WeakReference
// as an
// TODO AncestorListener.
final Window window = weakReference.get() == null ? null : SwingUtilities
.getWindowAncestor(weakReference.get());
if (window != null)
{
window.removeWindowFocusListener(windowListener);
window.addWindowFocusListener(windowListener);
// notify the listener of the original focus state of the window,
// which ensures
// that the listener is in sync with the actual window state.
fireInitialFocusEvent(windowListener, window);
}
}
private void fireInitialFocusEvent(WindowFocusListener windowListener, Window window)
{
Window focusedWindow = FocusManager.getCurrentManager().getFocusedWindow();
// fire a fake event to the given listener indicating the actual focus
// state of the
// given window.
if (window == focusedWindow)
{
windowListener.windowGainedFocus(new WindowEvent(window, WindowEvent.WINDOW_GAINED_FOCUS));
}
else
{
windowListener.windowGainedFocus(new WindowEvent(window, WindowEvent.WINDOW_LOST_FOCUS));
}
}
public void ancestorRemoved(AncestorEvent event)
{
Window window = weakReference.get() == null ? null : SwingUtilities.getWindowAncestor(weakReference.get());
if (window != null)
{
window.removeWindowFocusListener(windowListener);
}
}
public void ancestorMoved(AncestorEvent event)
{
// no implementation.
}
};
} | [
"private",
"static",
"AncestorListener",
"createAncestorListener",
"(",
"JComponent",
"component",
",",
"final",
"WindowFocusListener",
"windowListener",
")",
"{",
"final",
"WeakReference",
"<",
"JComponent",
">",
"weakReference",
"=",
"new",
"WeakReference",
"<",
"JCom... | Creates an {@link AncestorListener} that installs a weakly referenced
version of the given {@link WindowFocusListener} when the given
{@link JComponent}'s parent changes. | [
"Creates",
"an",
"{"
] | train | https://github.com/kevoree/kevoree-library/blob/617460e6c5881902ebc488a31ecdea179024d8f1/toys/src/main/java/com/rendion/util/WindowUtils.java#L155-L208 |
nmorel/gwt-jackson | gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/AbstractCreator.java | AbstractCreator.methodCallCodeWithClassParameters | private CodeBlock methodCallCodeWithClassParameters( MapperInstance instance, ImmutableList<? extends JType> parameters ) {
CodeBlock.Builder builder = initMethodCallCode( instance );
return methodCallParametersCode( builder, Lists.transform( parameters, new Function<JType, CodeBlock>() {
@Override
public CodeBlock apply( JType jType ) {
return CodeBlock.builder().add( "$T.class", typeName( jType ) ).build();
}
} ) );
} | java | private CodeBlock methodCallCodeWithClassParameters( MapperInstance instance, ImmutableList<? extends JType> parameters ) {
CodeBlock.Builder builder = initMethodCallCode( instance );
return methodCallParametersCode( builder, Lists.transform( parameters, new Function<JType, CodeBlock>() {
@Override
public CodeBlock apply( JType jType ) {
return CodeBlock.builder().add( "$T.class", typeName( jType ) ).build();
}
} ) );
} | [
"private",
"CodeBlock",
"methodCallCodeWithClassParameters",
"(",
"MapperInstance",
"instance",
",",
"ImmutableList",
"<",
"?",
"extends",
"JType",
">",
"parameters",
")",
"{",
"CodeBlock",
".",
"Builder",
"builder",
"=",
"initMethodCallCode",
"(",
"instance",
")",
... | Build the code to create a mapper.
@param instance the class to call
@param parameters the parameters of the method
@return the code to create the mapper | [
"Build",
"the",
"code",
"to",
"create",
"a",
"mapper",
"."
] | train | https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/AbstractCreator.java#L898-L907 |
jMotif/SAX | src/main/java/net/seninp/jmotif/sax/TSProcessor.java | TSProcessor.num2char | public char num2char(double value, double[] cuts) {
int idx = 0;
if (value >= 0) {
idx = cuts.length;
while ((idx > 0) && (cuts[idx - 1] > value)) {
idx--;
}
}
else {
while ((idx < cuts.length) && (cuts[idx] <= value)) {
idx++;
}
}
return ALPHABET[idx];
} | java | public char num2char(double value, double[] cuts) {
int idx = 0;
if (value >= 0) {
idx = cuts.length;
while ((idx > 0) && (cuts[idx - 1] > value)) {
idx--;
}
}
else {
while ((idx < cuts.length) && (cuts[idx] <= value)) {
idx++;
}
}
return ALPHABET[idx];
} | [
"public",
"char",
"num2char",
"(",
"double",
"value",
",",
"double",
"[",
"]",
"cuts",
")",
"{",
"int",
"idx",
"=",
"0",
";",
"if",
"(",
"value",
">=",
"0",
")",
"{",
"idx",
"=",
"cuts",
".",
"length",
";",
"while",
"(",
"(",
"idx",
">",
"0",
... | Get mapping of a number to char.
@param value the value to map.
@param cuts the array of intervals.
@return character corresponding to numeric value. | [
"Get",
"mapping",
"of",
"a",
"number",
"to",
"char",
"."
] | train | https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/TSProcessor.java#L394-L408 |
foundation-runtime/service-directory | 1.1/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryLookupService.java | DirectoryLookupService.getModelServiceInstance | public ModelServiceInstance getModelServiceInstance(String serviceName, String instanceId){
ModelService service = getModelService(serviceName);
if(service != null && service.getServiceInstances() != null ){
for(ModelServiceInstance instance : service.getServiceInstances()){
if(instance.getInstanceId().equals(instanceId)){
return instance;
}
}
}
return null;
} | java | public ModelServiceInstance getModelServiceInstance(String serviceName, String instanceId){
ModelService service = getModelService(serviceName);
if(service != null && service.getServiceInstances() != null ){
for(ModelServiceInstance instance : service.getServiceInstances()){
if(instance.getInstanceId().equals(instanceId)){
return instance;
}
}
}
return null;
} | [
"public",
"ModelServiceInstance",
"getModelServiceInstance",
"(",
"String",
"serviceName",
",",
"String",
"instanceId",
")",
"{",
"ModelService",
"service",
"=",
"getModelService",
"(",
"serviceName",
")",
";",
"if",
"(",
"service",
"!=",
"null",
"&&",
"service",
... | Get the ModelServiceInstance by serviceName and instanceId.
@param serviceName
the service name.
@param instanceId
the instanceId.
@return
the ModelServiceInstance. | [
"Get",
"the",
"ModelServiceInstance",
"by",
"serviceName",
"and",
"instanceId",
"."
] | train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.1/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryLookupService.java#L102-L112 |
BBN-E/bue-common-open | common-core-open/src/main/java/com/bbn/bue/common/primitives/DoubleUtils.java | DoubleUtils.shiftTowardsZeroWithClipping | public static double shiftTowardsZeroWithClipping(double val, double shift) {
checkArgument(shift>=0.0);
if (val > shift) {
return val - shift;
} else if (val < -shift) {
return val + shift;
} else {
return 0.0;
}
} | java | public static double shiftTowardsZeroWithClipping(double val, double shift) {
checkArgument(shift>=0.0);
if (val > shift) {
return val - shift;
} else if (val < -shift) {
return val + shift;
} else {
return 0.0;
}
} | [
"public",
"static",
"double",
"shiftTowardsZeroWithClipping",
"(",
"double",
"val",
",",
"double",
"shift",
")",
"{",
"checkArgument",
"(",
"shift",
">=",
"0.0",
")",
";",
"if",
"(",
"val",
">",
"shift",
")",
"{",
"return",
"val",
"-",
"shift",
";",
"}",... | Shifts the provided {@code val} towards but not past zero. If the absolute value of
{@code val} is less than or equal to shift, zero will be returned. Otherwise, negative {@code val}s
will have {@code shift} added and positive vals will have {@code shift} subtracted.
{@code shift} must be non-negative
Inspired by AdaGradRDA.ISTAHelper from FACTORIE. | [
"Shifts",
"the",
"provided",
"{",
"@code",
"val",
"}",
"towards",
"but",
"not",
"past",
"zero",
".",
"If",
"the",
"absolute",
"value",
"of",
"{",
"@code",
"val",
"}",
"is",
"less",
"than",
"or",
"equal",
"to",
"shift",
"zero",
"will",
"be",
"returned",... | train | https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/primitives/DoubleUtils.java#L246-L255 |
interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/SuffixTree.java | SuffixTree.setSuffixLink | void setSuffixLink(Node<I, S> node) {
if (isNotFirstInsert()) {
lastNodeInserted.setSuffixLink(node);
}
lastNodeInserted = node;
} | java | void setSuffixLink(Node<I, S> node) {
if (isNotFirstInsert()) {
lastNodeInserted.setSuffixLink(node);
}
lastNodeInserted = node;
} | [
"void",
"setSuffixLink",
"(",
"Node",
"<",
"I",
",",
"S",
">",
"node",
")",
"{",
"if",
"(",
"isNotFirstInsert",
"(",
")",
")",
"{",
"lastNodeInserted",
".",
"setSuffixLink",
"(",
"node",
")",
";",
"}",
"lastNodeInserted",
"=",
"node",
";",
"}"
] | Sets the suffix link of the last inserted node to point to the supplied
node. This method checks the state of the step and only applies the
suffix link if there is a previous node inserted during this step. This
method also set the last node inserted to the supplied node after
applying any suffix linking.
@param node The node to which the last node inserted's suffix link should
point to. | [
"Sets",
"the",
"suffix",
"link",
"of",
"the",
"last",
"inserted",
"node",
"to",
"point",
"to",
"the",
"supplied",
"node",
".",
"This",
"method",
"checks",
"the",
"state",
"of",
"the",
"step",
"and",
"only",
"applies",
"the",
"suffix",
"link",
"if",
"ther... | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/SuffixTree.java#L150-L155 |
graphql-java/graphql-java | src/main/java/graphql/schema/GraphQLTypeCollectingVisitor.java | GraphQLTypeCollectingVisitor.assertTypeUniqueness | private void assertTypeUniqueness(GraphQLType type, Map<String, GraphQLType> result) {
GraphQLType existingType = result.get(type.getName());
// do we have an existing definition
if (existingType != null) {
// type references are ok
if (!(existingType instanceof GraphQLTypeReference || type instanceof GraphQLTypeReference))
// object comparison here is deliberate
if (existingType != type) {
throw new AssertException(format("All types within a GraphQL schema must have unique names. No two provided types may have the same name.\n" +
"No provided type may have a name which conflicts with any built in types (including Scalar and Introspection types).\n" +
"You have redefined the type '%s' from being a '%s' to a '%s'",
type.getName(), existingType.getClass().getSimpleName(), type.getClass().getSimpleName()));
}
}
} | java | private void assertTypeUniqueness(GraphQLType type, Map<String, GraphQLType> result) {
GraphQLType existingType = result.get(type.getName());
// do we have an existing definition
if (existingType != null) {
// type references are ok
if (!(existingType instanceof GraphQLTypeReference || type instanceof GraphQLTypeReference))
// object comparison here is deliberate
if (existingType != type) {
throw new AssertException(format("All types within a GraphQL schema must have unique names. No two provided types may have the same name.\n" +
"No provided type may have a name which conflicts with any built in types (including Scalar and Introspection types).\n" +
"You have redefined the type '%s' from being a '%s' to a '%s'",
type.getName(), existingType.getClass().getSimpleName(), type.getClass().getSimpleName()));
}
}
} | [
"private",
"void",
"assertTypeUniqueness",
"(",
"GraphQLType",
"type",
",",
"Map",
"<",
"String",
",",
"GraphQLType",
">",
"result",
")",
"{",
"GraphQLType",
"existingType",
"=",
"result",
".",
"get",
"(",
"type",
".",
"getName",
"(",
")",
")",
";",
"// do... | /*
From http://facebook.github.io/graphql/#sec-Type-System
All types within a GraphQL schema must have unique names. No two provided types may have the same name.
No provided type may have a name which conflicts with any built in types (including Scalar and Introspection types).
Enforcing this helps avoid problems later down the track fo example https://github.com/graphql-java/graphql-java/issues/373 | [
"/",
"*",
"From",
"http",
":",
"//",
"facebook",
".",
"github",
".",
"io",
"/",
"graphql",
"/",
"#sec",
"-",
"Type",
"-",
"System"
] | train | https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/schema/GraphQLTypeCollectingVisitor.java#L97-L111 |
jboss/jboss-jsf-api_spec | src/main/java/javax/faces/component/UIViewRoot.java | UIViewRoot.removeComponentResource | public void removeComponentResource(FacesContext context, UIComponent componentResource, String target) {
final Map<String,Object> attributes = componentResource.getAttributes();
// look for a target in the component attribute set if arg is not set.
if (target == null) {
target = (String) attributes.get("target");
}
if (target == null) {
target = "head";
}
List<UIComponent> facetChildren = getComponentResources(context,
target,
false);
if (facetChildren != null) {
facetChildren.remove(componentResource);
}
} | java | public void removeComponentResource(FacesContext context, UIComponent componentResource, String target) {
final Map<String,Object> attributes = componentResource.getAttributes();
// look for a target in the component attribute set if arg is not set.
if (target == null) {
target = (String) attributes.get("target");
}
if (target == null) {
target = "head";
}
List<UIComponent> facetChildren = getComponentResources(context,
target,
false);
if (facetChildren != null) {
facetChildren.remove(componentResource);
}
} | [
"public",
"void",
"removeComponentResource",
"(",
"FacesContext",
"context",
",",
"UIComponent",
"componentResource",
",",
"String",
"target",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"attributes",
"=",
"componentResource",
".",
"getAttributes",
... | <p class="changed_added_2_0">Remove argument <code>component</code>,
which is assumed to represent a resource instance, as a resource
to this view. A resource instance is rendered by a resource
<code>Renderer</code>, as described in the Standard HTML
RenderKit. </p>
<div class="changed_added_2_0">
<p>
The <code>component</code> must be removed using the following algorithm:
<ul>
<li>If the <code>target</code> argument is <code>null</code>, look for a <code>target</code>
attribute on the <code>component</code>.<br>
If there is no <code>target</code> attribute, set <code>target</code> to be the default value <code>head</code></li>
<li>Call {@link #getComponentResources} to obtain the child list for the
given target.</li>
<li>Remove the <code>component</code> resource from the child list.</li>
</ul>
</p>
</div>
@param context {@link FacesContext} for the current request
@param componentResource The {@link UIComponent} representing a
{@link javax.faces.application.Resource} instance
@param target The name of the facet for which the {@link UIComponent} will be added
@since 2.0 | [
"<p",
"class",
"=",
"changed_added_2_0",
">",
"Remove",
"argument",
"<code",
">",
"component<",
"/",
"code",
">",
"which",
"is",
"assumed",
"to",
"represent",
"a",
"resource",
"instance",
"as",
"a",
"resource",
"to",
"this",
"view",
".",
"A",
"resource",
"... | train | https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/component/UIViewRoot.java#L647-L664 |
upwork/java-upwork | src/com/Upwork/api/UpworkRestClient.java | UpworkRestClient.getJSONObject | public static JSONObject getJSONObject(HttpGet request, Integer method) throws JSONException {
return UpworkRestClient.getJSONObject(request, method, new HashMap<String, String>());
} | java | public static JSONObject getJSONObject(HttpGet request, Integer method) throws JSONException {
return UpworkRestClient.getJSONObject(request, method, new HashMap<String, String>());
} | [
"public",
"static",
"JSONObject",
"getJSONObject",
"(",
"HttpGet",
"request",
",",
"Integer",
"method",
")",
"throws",
"JSONException",
"{",
"return",
"UpworkRestClient",
".",
"getJSONObject",
"(",
"request",
",",
"method",
",",
"new",
"HashMap",
"<",
"String",
... | Get JSON response for GET
@param request Request object for GET
@param method HTTP Method
@throws JSONException
@return {@link JSONObject} | [
"Get",
"JSON",
"response",
"for",
"GET"
] | train | https://github.com/upwork/java-upwork/blob/342297161503a74e9e0bddbd381ab5eebf4dc454/src/com/Upwork/api/UpworkRestClient.java#L74-L76 |
Impetus/Kundera | src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/query/CassQuery.java | CassQuery.onQueryOverCQL3 | public String onQueryOverCQL3(EntityMetadata m, Client client, MetamodelImpl metaModel, List<String> relations) {
// select column will always be of entity field only!
// where clause ordering
Class compoundKeyClass = m.getIdAttribute().getBindableJavaType();
EmbeddableType compoundKey = null;
String idColumn;
if (metaModel.isEmbeddable(compoundKeyClass)) {
compoundKey = metaModel.embeddable(compoundKeyClass);
idColumn = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();
} else {
idColumn = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();
}
StringBuilder builder = new StringBuilder();
boolean isPresent = false;
List<String> columns = getColumnList(m, metaModel, getKunderaQuery().getResult(), compoundKey);
String selectQuery = setSelectQuery(columns);
CQLTranslator translator = new CQLTranslator();
selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMN_FAMILY,
translator.ensureCase(new StringBuilder(), m.getTableName(), false).toString());
builder = CassandraUtilities.appendColumns(builder, columns, selectQuery, translator);
addWhereClause(builder);
onCondition(m, metaModel, compoundKey, idColumn, builder, isPresent, translator, true);
return builder.toString();
} | java | public String onQueryOverCQL3(EntityMetadata m, Client client, MetamodelImpl metaModel, List<String> relations) {
// select column will always be of entity field only!
// where clause ordering
Class compoundKeyClass = m.getIdAttribute().getBindableJavaType();
EmbeddableType compoundKey = null;
String idColumn;
if (metaModel.isEmbeddable(compoundKeyClass)) {
compoundKey = metaModel.embeddable(compoundKeyClass);
idColumn = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();
} else {
idColumn = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();
}
StringBuilder builder = new StringBuilder();
boolean isPresent = false;
List<String> columns = getColumnList(m, metaModel, getKunderaQuery().getResult(), compoundKey);
String selectQuery = setSelectQuery(columns);
CQLTranslator translator = new CQLTranslator();
selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMN_FAMILY,
translator.ensureCase(new StringBuilder(), m.getTableName(), false).toString());
builder = CassandraUtilities.appendColumns(builder, columns, selectQuery, translator);
addWhereClause(builder);
onCondition(m, metaModel, compoundKey, idColumn, builder, isPresent, translator, true);
return builder.toString();
} | [
"public",
"String",
"onQueryOverCQL3",
"(",
"EntityMetadata",
"m",
",",
"Client",
"client",
",",
"MetamodelImpl",
"metaModel",
",",
"List",
"<",
"String",
">",
"relations",
")",
"{",
"// select column will always be of entity field only!",
"// where clause ordering",
"Cla... | On query over composite columns.
@param m
the m
@param client
the client
@param metaModel
the meta model
@param relations
the relations
@return the list | [
"On",
"query",
"over",
"composite",
"columns",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/query/CassQuery.java#L613-L644 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/packet/Privacy.java | Privacy.getItem | public PrivacyItem getItem(String listName, int order) {
// CHECKSTYLE:OFF
Iterator<PrivacyItem> values = getPrivacyList(listName).iterator();
PrivacyItem itemFound = null;
while (itemFound == null && values.hasNext()) {
PrivacyItem element = values.next();
if (element.getOrder() == order) {
itemFound = element;
}
}
return itemFound;
// CHECKSTYLE:ON
} | java | public PrivacyItem getItem(String listName, int order) {
// CHECKSTYLE:OFF
Iterator<PrivacyItem> values = getPrivacyList(listName).iterator();
PrivacyItem itemFound = null;
while (itemFound == null && values.hasNext()) {
PrivacyItem element = values.next();
if (element.getOrder() == order) {
itemFound = element;
}
}
return itemFound;
// CHECKSTYLE:ON
} | [
"public",
"PrivacyItem",
"getItem",
"(",
"String",
"listName",
",",
"int",
"order",
")",
"{",
"// CHECKSTYLE:OFF",
"Iterator",
"<",
"PrivacyItem",
">",
"values",
"=",
"getPrivacyList",
"(",
"listName",
")",
".",
"iterator",
"(",
")",
";",
"PrivacyItem",
"itemF... | Returns the privacy item in the specified order.
@param listName the name of the privacy list.
@param order the order of the element.
@return a List with {@link PrivacyItem} | [
"Returns",
"the",
"privacy",
"item",
"in",
"the",
"specified",
"order",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/packet/Privacy.java#L157-L169 |
sevensource/html-email-service | src/main/java/org/sevensource/commons/email/model/DefaultEmailModel.java | DefaultEmailModel.addBcc | public void addBcc(String address, String personal) throws AddressException {
if(bcc == null) {
bcc = new ArrayList<>();
}
bcc.add( toInternetAddress(address, personal) );
} | java | public void addBcc(String address, String personal) throws AddressException {
if(bcc == null) {
bcc = new ArrayList<>();
}
bcc.add( toInternetAddress(address, personal) );
} | [
"public",
"void",
"addBcc",
"(",
"String",
"address",
",",
"String",
"personal",
")",
"throws",
"AddressException",
"{",
"if",
"(",
"bcc",
"==",
"null",
")",
"{",
"bcc",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"}",
"bcc",
".",
"add",
"(",
"toIn... | adds a BCC recipient
@param address a valid email address
@param personal the real world name of the sender (can be null)
@throws AddressException in case of an invalid email address | [
"adds",
"a",
"BCC",
"recipient"
] | train | https://github.com/sevensource/html-email-service/blob/a55d9ef1a2173917cb5f870854bc24e5aaebd182/src/main/java/org/sevensource/commons/email/model/DefaultEmailModel.java#L121-L126 |
ironjacamar/ironjacamar | tracer/src/main/java/org/ironjacamar/tracer/TraceEventHelper.java | TraceEventHelper.hasMoreApplicationEvents | static boolean hasMoreApplicationEvents(List<TraceEvent> events, int index)
{
if (index < 0 || index >= events.size())
return false;
for (int j = index; j < events.size(); j++)
{
TraceEvent te = events.get(j);
if (te.getType() == TraceEvent.GET_CONNECTION ||
te.getType() == TraceEvent.RETURN_CONNECTION)
return true;
}
return false;
} | java | static boolean hasMoreApplicationEvents(List<TraceEvent> events, int index)
{
if (index < 0 || index >= events.size())
return false;
for (int j = index; j < events.size(); j++)
{
TraceEvent te = events.get(j);
if (te.getType() == TraceEvent.GET_CONNECTION ||
te.getType() == TraceEvent.RETURN_CONNECTION)
return true;
}
return false;
} | [
"static",
"boolean",
"hasMoreApplicationEvents",
"(",
"List",
"<",
"TraceEvent",
">",
"events",
",",
"int",
"index",
")",
"{",
"if",
"(",
"index",
"<",
"0",
"||",
"index",
">=",
"events",
".",
"size",
"(",
")",
")",
"return",
"false",
";",
"for",
"(",
... | Has more application events
@param events The events
@param index The index
@return True if more application events after the index | [
"Has",
"more",
"application",
"events"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/tracer/src/main/java/org/ironjacamar/tracer/TraceEventHelper.java#L1056-L1070 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.