repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 218 | func_name stringlengths 4 140 | whole_func_string stringlengths 153 5.32k | language stringclasses 1
value | func_code_string stringlengths 72 4k | func_code_tokens listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
fabric8io/docker-maven-plugin | src/main/java/io/fabric8/maven/docker/util/EnvUtil.java | EnvUtil.greaterOrEqualsVersion | public static boolean greaterOrEqualsVersion(String versionA, String versionB) {
"""
Check whether the first given API version is larger or equals the second given version
@param versionA first version to check against
@param versionB the second version
@return true if versionA is greater or equals versionB, false otherwise
"""
String largerVersion = extractLargerVersion(versionA, versionB);
return largerVersion != null && largerVersion.equals(versionA);
} | java | public static boolean greaterOrEqualsVersion(String versionA, String versionB) {
String largerVersion = extractLargerVersion(versionA, versionB);
return largerVersion != null && largerVersion.equals(versionA);
} | [
"public",
"static",
"boolean",
"greaterOrEqualsVersion",
"(",
"String",
"versionA",
",",
"String",
"versionB",
")",
"{",
"String",
"largerVersion",
"=",
"extractLargerVersion",
"(",
"versionA",
",",
"versionB",
")",
";",
"return",
"largerVersion",
"!=",
"null",
"&... | Check whether the first given API version is larger or equals the second given version
@param versionA first version to check against
@param versionB the second version
@return true if versionA is greater or equals versionB, false otherwise | [
"Check",
"whether",
"the",
"first",
"given",
"API",
"version",
"is",
"larger",
"or",
"equals",
"the",
"second",
"given",
"version"
] | train | https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/EnvUtil.java#L85-L88 |
Alluxio/alluxio | shell/src/main/java/alluxio/cli/GetConf.java | GetConf.getConf | public static int getConf(ClientContext ctx, String... args) {
"""
Implements get configuration.
@param ctx Alluxio client configuration
@param args list of arguments
@return 0 on success, 1 on failures
"""
return getConfImpl(
() -> new RetryHandlingMetaMasterConfigClient(MasterClientContext.newBuilder(ctx).build()),
ctx.getConf(), args);
} | java | public static int getConf(ClientContext ctx, String... args) {
return getConfImpl(
() -> new RetryHandlingMetaMasterConfigClient(MasterClientContext.newBuilder(ctx).build()),
ctx.getConf(), args);
} | [
"public",
"static",
"int",
"getConf",
"(",
"ClientContext",
"ctx",
",",
"String",
"...",
"args",
")",
"{",
"return",
"getConfImpl",
"(",
"(",
")",
"->",
"new",
"RetryHandlingMetaMasterConfigClient",
"(",
"MasterClientContext",
".",
"newBuilder",
"(",
"ctx",
")",... | Implements get configuration.
@param ctx Alluxio client configuration
@param args list of arguments
@return 0 on success, 1 on failures | [
"Implements",
"get",
"configuration",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/GetConf.java#L143-L147 |
3pillarlabs/spring-data-simpledb | spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/reflection/ReflectionUtils.java | ReflectionUtils.getDeclaredFieldInHierarchy | public static Field getDeclaredFieldInHierarchy(Class<?> clazz, String fieldName) throws NoSuchFieldException {
"""
Finds a declared field in given <tt>clazz</tt> and continues to search
up the superclass until no more super class is present.
@param clazz
@param fieldName
@return
@throws NoSuchFieldException
"""
Field field = null;
for (Class<?> acls = clazz; acls != null; acls = acls.getSuperclass()) {
try {
field = acls.getDeclaredField(fieldName);
break;
} catch (NoSuchFieldException e) {
// ignore
}
}
if (field == null) {
throw new NoSuchFieldException("Could not find field '" + fieldName + "' in class '" + clazz.getName() + "' or its super classes");
}
return field;
} | java | public static Field getDeclaredFieldInHierarchy(Class<?> clazz, String fieldName) throws NoSuchFieldException {
Field field = null;
for (Class<?> acls = clazz; acls != null; acls = acls.getSuperclass()) {
try {
field = acls.getDeclaredField(fieldName);
break;
} catch (NoSuchFieldException e) {
// ignore
}
}
if (field == null) {
throw new NoSuchFieldException("Could not find field '" + fieldName + "' in class '" + clazz.getName() + "' or its super classes");
}
return field;
} | [
"public",
"static",
"Field",
"getDeclaredFieldInHierarchy",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"fieldName",
")",
"throws",
"NoSuchFieldException",
"{",
"Field",
"field",
"=",
"null",
";",
"for",
"(",
"Class",
"<",
"?",
">",
"acls",
"=",
"... | Finds a declared field in given <tt>clazz</tt> and continues to search
up the superclass until no more super class is present.
@param clazz
@param fieldName
@return
@throws NoSuchFieldException | [
"Finds",
"a",
"declared",
"field",
"in",
"given",
"<tt",
">",
"clazz<",
"/",
"tt",
">",
"and",
"continues",
"to",
"search",
"up",
"the",
"superclass",
"until",
"no",
"more",
"super",
"class",
"is",
"present",
"."
] | train | https://github.com/3pillarlabs/spring-data-simpledb/blob/f1e0eb4e48ec4674d3966e8f5bc04c95031f93ae/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/reflection/ReflectionUtils.java#L300-L316 |
OpenNTF/JavascriptAggregator | jaggr-core/src/main/java/com/ibm/jaggr/core/impl/deps/DepTreeNode.java | DepTreeNode.toStringTree | private void toStringTree(String indent, StringBuffer sb) {
"""
Prints the string representaton of the tree rooted at this node to the
specified {@link StringBuffer}.
@param indent
String for indenting nodes
@param sb
The StringBuffer to output to
"""
sb.append(toString());
if (children != null) {
for (Entry<String, DepTreeNode> entry : children.entrySet()) {
entry.getValue().toStringTree(indent + "\t", sb); //$NON-NLS-1$
}
}
} | java | private void toStringTree(String indent, StringBuffer sb) {
sb.append(toString());
if (children != null) {
for (Entry<String, DepTreeNode> entry : children.entrySet()) {
entry.getValue().toStringTree(indent + "\t", sb); //$NON-NLS-1$
}
}
} | [
"private",
"void",
"toStringTree",
"(",
"String",
"indent",
",",
"StringBuffer",
"sb",
")",
"{",
"sb",
".",
"append",
"(",
"toString",
"(",
")",
")",
";",
"if",
"(",
"children",
"!=",
"null",
")",
"{",
"for",
"(",
"Entry",
"<",
"String",
",",
"DepTre... | Prints the string representaton of the tree rooted at this node to the
specified {@link StringBuffer}.
@param indent
String for indenting nodes
@param sb
The StringBuffer to output to | [
"Prints",
"the",
"string",
"representaton",
"of",
"the",
"tree",
"rooted",
"at",
"this",
"node",
"to",
"the",
"specified",
"{",
"@link",
"StringBuffer",
"}",
"."
] | train | https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/deps/DepTreeNode.java#L569-L576 |
lucee/Lucee | core/src/main/java/lucee/runtime/db/QoQ.java | QoQ.executeAnd | private Object executeAnd(PageContext pc, SQL sql, Query qr, Operation2 expression, int row) throws PageException {
"""
/*
*
@param expression / private void print(ZExpression expression) {
print.ln("Operator:"+expression.getOperator().toLowerCase()); int len=expression.nbOperands();
for(int i=0;i<len;i++) { print.ln(" ["+i+"]= "+expression.getOperand(i)); } }/*
/**
execute a and operation
@param qr QueryResult to execute on it
@param expression
@param row row of resultset to execute
@return
@throws PageException
"""
// print.out("("+expression.getLeft().toString(true)+" AND
// "+expression.getRight().toString(true)+")");
boolean rtn = Caster.toBooleanValue(executeExp(pc, sql, qr, expression.getLeft(), row));
if (!rtn) return Boolean.FALSE;
return Caster.toBoolean(executeExp(pc, sql, qr, expression.getRight(), row));
} | java | private Object executeAnd(PageContext pc, SQL sql, Query qr, Operation2 expression, int row) throws PageException {
// print.out("("+expression.getLeft().toString(true)+" AND
// "+expression.getRight().toString(true)+")");
boolean rtn = Caster.toBooleanValue(executeExp(pc, sql, qr, expression.getLeft(), row));
if (!rtn) return Boolean.FALSE;
return Caster.toBoolean(executeExp(pc, sql, qr, expression.getRight(), row));
} | [
"private",
"Object",
"executeAnd",
"(",
"PageContext",
"pc",
",",
"SQL",
"sql",
",",
"Query",
"qr",
",",
"Operation2",
"expression",
",",
"int",
"row",
")",
"throws",
"PageException",
"{",
"// print.out(\"(\"+expression.getLeft().toString(true)+\" AND",
"// \"+expressio... | /*
*
@param expression / private void print(ZExpression expression) {
print.ln("Operator:"+expression.getOperator().toLowerCase()); int len=expression.nbOperands();
for(int i=0;i<len;i++) { print.ln(" ["+i+"]= "+expression.getOperand(i)); } }/*
/**
execute a and operation
@param qr QueryResult to execute on it
@param expression
@param row row of resultset to execute
@return
@throws PageException | [
"/",
"*",
"*"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/db/QoQ.java#L548-L554 |
GoogleCloudPlatform/google-cloud-datastore | java/datastore/src/main/java/com/google/datastore/v1/client/DatastoreHelper.java | DatastoreHelper.getServiceAccountCredential | public static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes)
throws GeneralSecurityException, IOException {
"""
Constructs credentials for the given account and key.
@param serviceAccountId service account ID (typically an e-mail address).
@param privateKey the private key for the given account.
@param serviceAccountScopes Collection of OAuth scopes to use with the the service
account flow or {@code null} if not.
@return valid credentials or {@code null}
"""
return getCredentialBuilderWithoutPrivateKey(serviceAccountId, serviceAccountScopes)
.setServiceAccountPrivateKey(privateKey)
.build();
} | java | public static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes)
throws GeneralSecurityException, IOException {
return getCredentialBuilderWithoutPrivateKey(serviceAccountId, serviceAccountScopes)
.setServiceAccountPrivateKey(privateKey)
.build();
} | [
"public",
"static",
"Credential",
"getServiceAccountCredential",
"(",
"String",
"serviceAccountId",
",",
"PrivateKey",
"privateKey",
",",
"Collection",
"<",
"String",
">",
"serviceAccountScopes",
")",
"throws",
"GeneralSecurityException",
",",
"IOException",
"{",
"return"... | Constructs credentials for the given account and key.
@param serviceAccountId service account ID (typically an e-mail address).
@param privateKey the private key for the given account.
@param serviceAccountScopes Collection of OAuth scopes to use with the the service
account flow or {@code null} if not.
@return valid credentials or {@code null} | [
"Constructs",
"credentials",
"for",
"the",
"given",
"account",
"and",
"key",
"."
] | train | https://github.com/GoogleCloudPlatform/google-cloud-datastore/blob/a23940d0634d7f537faf01ad9e60598046bcb40a/java/datastore/src/main/java/com/google/datastore/v1/client/DatastoreHelper.java#L194-L200 |
svenkubiak/mangooio | mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java | Validator.expectEmail | public void expectEmail(String name, String message) {
"""
Validates a field to be a valid email address
@param name The field to check
@param message A custom error message instead of the default one
"""
String value = Optional.ofNullable(get(name)).orElse("");
if (!EmailValidator.getInstance().isValid(value)) {
addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.EMAIL_KEY.name(), name)));
}
} | java | public void expectEmail(String name, String message) {
String value = Optional.ofNullable(get(name)).orElse("");
if (!EmailValidator.getInstance().isValid(value)) {
addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.EMAIL_KEY.name(), name)));
}
} | [
"public",
"void",
"expectEmail",
"(",
"String",
"name",
",",
"String",
"message",
")",
"{",
"String",
"value",
"=",
"Optional",
".",
"ofNullable",
"(",
"get",
"(",
"name",
")",
")",
".",
"orElse",
"(",
"\"\"",
")",
";",
"if",
"(",
"!",
"EmailValidator"... | Validates a field to be a valid email address
@param name The field to check
@param message A custom error message instead of the default one | [
"Validates",
"a",
"field",
"to",
"be",
"a",
"valid",
"email",
"address"
] | train | https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java#L257-L263 |
validator/validator | src/nu/validator/xml/AttributesImpl.java | AttributesImpl.addAttribute | public void addAttribute(String localName, String value) {
"""
Adds an attribute that is not in a namespace. The infoset type
of the attribute will be ID if the <code>localName</code> is
"id" and CDATA otherwise.
@param localName the local name of the attribute
@param value the value of the attribute
"""
if ("id".equals(localName)) {
super.addAttribute("", localName, localName, "ID", value);
} else {
super.addAttribute("", localName, localName, "CDATA", value);
}
} | java | public void addAttribute(String localName, String value) {
if ("id".equals(localName)) {
super.addAttribute("", localName, localName, "ID", value);
} else {
super.addAttribute("", localName, localName, "CDATA", value);
}
} | [
"public",
"void",
"addAttribute",
"(",
"String",
"localName",
",",
"String",
"value",
")",
"{",
"if",
"(",
"\"id\"",
".",
"equals",
"(",
"localName",
")",
")",
"{",
"super",
".",
"addAttribute",
"(",
"\"\"",
",",
"localName",
",",
"localName",
",",
"\"ID... | Adds an attribute that is not in a namespace. The infoset type
of the attribute will be ID if the <code>localName</code> is
"id" and CDATA otherwise.
@param localName the local name of the attribute
@param value the value of the attribute | [
"Adds",
"an",
"attribute",
"that",
"is",
"not",
"in",
"a",
"namespace",
".",
"The",
"infoset",
"type",
"of",
"the",
"attribute",
"will",
"be",
"ID",
"if",
"the",
"<code",
">",
"localName<",
"/",
"code",
">",
"is",
"id",
"and",
"CDATA",
"otherwise",
"."... | train | https://github.com/validator/validator/blob/c7b7f85b3a364df7d9944753fb5b2cd0ce642889/src/nu/validator/xml/AttributesImpl.java#L55-L61 |
Impetus/Kundera | src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/index/Neo4JIndexManager.java | Neo4JIndexManager.deleteNodeIndex | public void deleteNodeIndex(EntityMetadata entityMetadata, GraphDatabaseService graphDb, Node node) {
"""
Deletes a {@link Node} from manually created index if auto-indexing is
disabled
@param entityMetadata
@param graphDb
@param node
"""
if (!isNodeAutoIndexingEnabled(graphDb) && entityMetadata.isIndexable())
{
Index<Node> nodeIndex = graphDb.index().forNodes(entityMetadata.getIndexName());
nodeIndex.remove(node);
}
} | java | public void deleteNodeIndex(EntityMetadata entityMetadata, GraphDatabaseService graphDb, Node node)
{
if (!isNodeAutoIndexingEnabled(graphDb) && entityMetadata.isIndexable())
{
Index<Node> nodeIndex = graphDb.index().forNodes(entityMetadata.getIndexName());
nodeIndex.remove(node);
}
} | [
"public",
"void",
"deleteNodeIndex",
"(",
"EntityMetadata",
"entityMetadata",
",",
"GraphDatabaseService",
"graphDb",
",",
"Node",
"node",
")",
"{",
"if",
"(",
"!",
"isNodeAutoIndexingEnabled",
"(",
"graphDb",
")",
"&&",
"entityMetadata",
".",
"isIndexable",
"(",
... | Deletes a {@link Node} from manually created index if auto-indexing is
disabled
@param entityMetadata
@param graphDb
@param node | [
"Deletes",
"a",
"{",
"@link",
"Node",
"}",
"from",
"manually",
"created",
"index",
"if",
"auto",
"-",
"indexing",
"is",
"disabled"
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/index/Neo4JIndexManager.java#L208-L215 |
jwtk/jjwt | api/src/main/java/io/jsonwebtoken/lang/Strings.java | Strings.delimitedListToStringArray | public static String[] delimitedListToStringArray(String str, String delimiter) {
"""
Take a String which is a delimited list and convert it to a String array.
<p>A single delimiter can consists of more than one character: It will still
be considered as single delimiter string, rather than as bunch of potential
delimiter characters - in contrast to <code>tokenizeToStringArray</code>.
@param str the input String
@param delimiter the delimiter between elements (this is a single delimiter,
rather than a bunch individual delimiter characters)
@return an array of the tokens in the list
@see #tokenizeToStringArray
"""
return delimitedListToStringArray(str, delimiter, null);
} | java | public static String[] delimitedListToStringArray(String str, String delimiter) {
return delimitedListToStringArray(str, delimiter, null);
} | [
"public",
"static",
"String",
"[",
"]",
"delimitedListToStringArray",
"(",
"String",
"str",
",",
"String",
"delimiter",
")",
"{",
"return",
"delimitedListToStringArray",
"(",
"str",
",",
"delimiter",
",",
"null",
")",
";",
"}"
] | Take a String which is a delimited list and convert it to a String array.
<p>A single delimiter can consists of more than one character: It will still
be considered as single delimiter string, rather than as bunch of potential
delimiter characters - in contrast to <code>tokenizeToStringArray</code>.
@param str the input String
@param delimiter the delimiter between elements (this is a single delimiter,
rather than a bunch individual delimiter characters)
@return an array of the tokens in the list
@see #tokenizeToStringArray | [
"Take",
"a",
"String",
"which",
"is",
"a",
"delimited",
"list",
"and",
"convert",
"it",
"to",
"a",
"String",
"array",
".",
"<p",
">",
"A",
"single",
"delimiter",
"can",
"consists",
"of",
"more",
"than",
"one",
"character",
":",
"It",
"will",
"still",
"... | train | https://github.com/jwtk/jjwt/blob/86b6096946752cffcfbc9b0a5503f1ea195cc140/api/src/main/java/io/jsonwebtoken/lang/Strings.java#L998-L1000 |
raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/utility/visitor/MetadataAwareClassVisitor.java | MetadataAwareClassVisitor.onVisitMethod | protected MethodVisitor onVisitMethod(int modifiers, String internalName, String descriptor, String signature, String[] exception) {
"""
An order-sensitive invocation of {@link ClassVisitor#visitMethod(int, String, String, String, String[])}.
@param modifiers The method's modifiers.
@param internalName The method's internal name.
@param descriptor The field type's descriptor.
@param signature The method's generic signature or {@code null} if the method is not generic.
@param exception The method's declared exceptions or {@code null} if no exceptions are declared.
@return A method visitor to visit the method or {@code null} to ignore it.
"""
return super.visitMethod(modifiers, internalName, descriptor, signature, exception);
} | java | protected MethodVisitor onVisitMethod(int modifiers, String internalName, String descriptor, String signature, String[] exception) {
return super.visitMethod(modifiers, internalName, descriptor, signature, exception);
} | [
"protected",
"MethodVisitor",
"onVisitMethod",
"(",
"int",
"modifiers",
",",
"String",
"internalName",
",",
"String",
"descriptor",
",",
"String",
"signature",
",",
"String",
"[",
"]",
"exception",
")",
"{",
"return",
"super",
".",
"visitMethod",
"(",
"modifiers... | An order-sensitive invocation of {@link ClassVisitor#visitMethod(int, String, String, String, String[])}.
@param modifiers The method's modifiers.
@param internalName The method's internal name.
@param descriptor The field type's descriptor.
@param signature The method's generic signature or {@code null} if the method is not generic.
@param exception The method's declared exceptions or {@code null} if no exceptions are declared.
@return A method visitor to visit the method or {@code null} to ignore it. | [
"An",
"order",
"-",
"sensitive",
"invocation",
"of",
"{",
"@link",
"ClassVisitor#visitMethod",
"(",
"int",
"String",
"String",
"String",
"String",
"[]",
")",
"}",
"."
] | train | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/utility/visitor/MetadataAwareClassVisitor.java#L262-L264 |
strator-dev/greenpepper | greenpepper-open/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/velocity/ConfluenceGreenPepper.java | ConfluenceGreenPepper.setPageProperty | public void setPageProperty(String key, String value, String identifier) {
"""
<p>setPageProperty.</p>
@param key a {@link java.lang.String} object.
@param value a {@link java.lang.String} object.
@param identifier a {@link java.lang.String} object.
"""
Space space = getSpaceManager().getSpace(identifier);
ContentEntityObject entityObject = getContentEntityManager().getById(space.getHomePage().getId());
getContentPropertyManager().setStringProperty(entityObject, ServerPropertiesManager.SEQUENCE + key, value);
} | java | public void setPageProperty(String key, String value, String identifier) {
Space space = getSpaceManager().getSpace(identifier);
ContentEntityObject entityObject = getContentEntityManager().getById(space.getHomePage().getId());
getContentPropertyManager().setStringProperty(entityObject, ServerPropertiesManager.SEQUENCE + key, value);
} | [
"public",
"void",
"setPageProperty",
"(",
"String",
"key",
",",
"String",
"value",
",",
"String",
"identifier",
")",
"{",
"Space",
"space",
"=",
"getSpaceManager",
"(",
")",
".",
"getSpace",
"(",
"identifier",
")",
";",
"ContentEntityObject",
"entityObject",
"... | <p>setPageProperty.</p>
@param key a {@link java.lang.String} object.
@param value a {@link java.lang.String} object.
@param identifier a {@link java.lang.String} object. | [
"<p",
">",
"setPageProperty",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper-open/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/velocity/ConfluenceGreenPepper.java#L853-L857 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ManagedDatabasesInner.java | ManagedDatabasesInner.updateAsync | public Observable<ManagedDatabaseInner> updateAsync(String resourceGroupName, String managedInstanceName, String databaseName, ManagedDatabaseUpdate parameters) {
"""
Updates an existing database.
@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 managedInstanceName The name of the managed instance.
@param databaseName The name of the database.
@param parameters The requested database resource state.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return updateWithServiceResponseAsync(resourceGroupName, managedInstanceName, databaseName, parameters).map(new Func1<ServiceResponse<ManagedDatabaseInner>, ManagedDatabaseInner>() {
@Override
public ManagedDatabaseInner call(ServiceResponse<ManagedDatabaseInner> response) {
return response.body();
}
});
} | java | public Observable<ManagedDatabaseInner> updateAsync(String resourceGroupName, String managedInstanceName, String databaseName, ManagedDatabaseUpdate parameters) {
return updateWithServiceResponseAsync(resourceGroupName, managedInstanceName, databaseName, parameters).map(new Func1<ServiceResponse<ManagedDatabaseInner>, ManagedDatabaseInner>() {
@Override
public ManagedDatabaseInner call(ServiceResponse<ManagedDatabaseInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ManagedDatabaseInner",
">",
"updateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"managedInstanceName",
",",
"String",
"databaseName",
",",
"ManagedDatabaseUpdate",
"parameters",
")",
"{",
"return",
"updateWithServiceResponseAsync"... | Updates an existing database.
@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 managedInstanceName The name of the managed instance.
@param databaseName The name of the database.
@param parameters The requested database resource state.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Updates",
"an",
"existing",
"database",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ManagedDatabasesInner.java#L900-L907 |
IBM-Cloud/gp-java-client | src/main/java/com/ibm/g11n/pipeline/iam/TokenLifeCycleManager.java | TokenLifeCycleManager.getInstance | static TokenLifeCycleManager getInstance(final String jsonCredentials) {
"""
Get an instance of TokenLifeCylceManager. Single instance is maintained
for each unique pair of iamEndpoint and apiKey. The method and the returned instance is thread
safe.
@param jsonCredentials
Credentials in JSON format. The credentials should at minimum
have these <key>:<value> pairs in the credentials json:
{
"apikey":"<IAM_API_KEY>",
"iam_endpoint":"<IAM_ENDPOINT>"
}
@return Instance of TokenLifeCylceManager.
"""
final JsonObject credentials = new JsonParser().parse(jsonCredentials)
.getAsJsonObject();
if(credentials.get("apikey")==null || credentials.get("apikey").isJsonNull()||credentials.get("apikey").getAsString().isEmpty()) {
throw new IllegalArgumentException(
"IAM API Key value is either not available, or null or is empty in credentials JSON.");
}
if(credentials.get("iam_endpoint")==null || credentials.get("iam_endpoint").isJsonNull()||credentials.get("iam_endpoint").getAsString().isEmpty()) {
throw new IllegalArgumentException(
"IAM endpoint Key value is either not available, or null or is empty in credentials JSON.");
}
final String apiKey = credentials.get("apikey").getAsString();
final String iamEndpoint = credentials.get("iam_endpoint").getAsString();
return getInstanceUnchecked(iamEndpoint, apiKey);
} | java | static TokenLifeCycleManager getInstance(final String jsonCredentials) {
final JsonObject credentials = new JsonParser().parse(jsonCredentials)
.getAsJsonObject();
if(credentials.get("apikey")==null || credentials.get("apikey").isJsonNull()||credentials.get("apikey").getAsString().isEmpty()) {
throw new IllegalArgumentException(
"IAM API Key value is either not available, or null or is empty in credentials JSON.");
}
if(credentials.get("iam_endpoint")==null || credentials.get("iam_endpoint").isJsonNull()||credentials.get("iam_endpoint").getAsString().isEmpty()) {
throw new IllegalArgumentException(
"IAM endpoint Key value is either not available, or null or is empty in credentials JSON.");
}
final String apiKey = credentials.get("apikey").getAsString();
final String iamEndpoint = credentials.get("iam_endpoint").getAsString();
return getInstanceUnchecked(iamEndpoint, apiKey);
} | [
"static",
"TokenLifeCycleManager",
"getInstance",
"(",
"final",
"String",
"jsonCredentials",
")",
"{",
"final",
"JsonObject",
"credentials",
"=",
"new",
"JsonParser",
"(",
")",
".",
"parse",
"(",
"jsonCredentials",
")",
".",
"getAsJsonObject",
"(",
")",
";",
"if... | Get an instance of TokenLifeCylceManager. Single instance is maintained
for each unique pair of iamEndpoint and apiKey. The method and the returned instance is thread
safe.
@param jsonCredentials
Credentials in JSON format. The credentials should at minimum
have these <key>:<value> pairs in the credentials json:
{
"apikey":"<IAM_API_KEY>",
"iam_endpoint":"<IAM_ENDPOINT>"
}
@return Instance of TokenLifeCylceManager. | [
"Get",
"an",
"instance",
"of",
"TokenLifeCylceManager",
".",
"Single",
"instance",
"is",
"maintained",
"for",
"each",
"unique",
"pair",
"of",
"iamEndpoint",
"and",
"apiKey",
".",
"The",
"method",
"and",
"the",
"returned",
"instance",
"is",
"thread",
"safe",
".... | train | https://github.com/IBM-Cloud/gp-java-client/blob/b015a081d7a7313bc48c448087fbc07bce860427/src/main/java/com/ibm/g11n/pipeline/iam/TokenLifeCycleManager.java#L222-L237 |
erlang/otp | lib/jinterface/java_src/com/ericsson/otp/erlang/OtpOutputStream.java | OtpOutputStream.write_ref | public void write_ref(final String node, final int id, final int creation) {
"""
Write an old style Erlang ref to the stream.
@param node
the nodename.
@param id
an arbitrary number. Only the low order 18 bits will be used.
@param creation
another arbitrary number.
"""
/* Always encode as an extended reference; all
participating parties are now expected to be
able to decode extended references. */
int ids[] = new int[1];
ids[0] = id;
write_ref(node, ids, creation);
} | java | public void write_ref(final String node, final int id, final int creation) {
/* Always encode as an extended reference; all
participating parties are now expected to be
able to decode extended references. */
int ids[] = new int[1];
ids[0] = id;
write_ref(node, ids, creation);
} | [
"public",
"void",
"write_ref",
"(",
"final",
"String",
"node",
",",
"final",
"int",
"id",
",",
"final",
"int",
"creation",
")",
"{",
"/* Always encode as an extended reference; all\n\t participating parties are now expected to be\n\t able to decode extended references. */",
"... | Write an old style Erlang ref to the stream.
@param node
the nodename.
@param id
an arbitrary number. Only the low order 18 bits will be used.
@param creation
another arbitrary number. | [
"Write",
"an",
"old",
"style",
"Erlang",
"ref",
"to",
"the",
"stream",
"."
] | train | https://github.com/erlang/otp/blob/ac6084fd83240355f72e94adbf303e57832d1fab/lib/jinterface/java_src/com/ericsson/otp/erlang/OtpOutputStream.java#L802-L809 |
jferard/fastods | fastods/src/main/java/com/github/jferard/fastods/TextBuilder.java | TextBuilder.styledLink | public TextBuilder styledLink(final String text, final TextStyle ts, final String ref) {
"""
Create a styled link in the current paragraph.
@param text the text
@param ts the style
@param ref the destination
@return this for fluent style
"""
this.curParagraphBuilder.styledLink(text, ts, ref);
return this;
} | java | public TextBuilder styledLink(final String text, final TextStyle ts, final String ref) {
this.curParagraphBuilder.styledLink(text, ts, ref);
return this;
} | [
"public",
"TextBuilder",
"styledLink",
"(",
"final",
"String",
"text",
",",
"final",
"TextStyle",
"ts",
",",
"final",
"String",
"ref",
")",
"{",
"this",
".",
"curParagraphBuilder",
".",
"styledLink",
"(",
"text",
",",
"ts",
",",
"ref",
")",
";",
"return",
... | Create a styled link in the current paragraph.
@param text the text
@param ts the style
@param ref the destination
@return this for fluent style | [
"Create",
"a",
"styled",
"link",
"in",
"the",
"current",
"paragraph",
"."
] | train | https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/TextBuilder.java#L199-L202 |
stackify/stackify-api-java | src/main/java/com/stackify/api/common/log/direct/Logger.java | Logger.queueMessage | public static void queueMessage(final String level, final String message) {
"""
Queues a log message to be sent to Stackify
@param level The log level
@param message The log message
"""
try {
LogAppender<LogEvent> appender = LogManager.getAppender();
if (appender != null) {
LogEvent.Builder builder = LogEvent.newBuilder();
builder.level(level);
builder.message(message);
if ((level != null) && ("ERROR".equals(level.toUpperCase()))) {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
if ((stackTrace != null) && (1 < stackTrace.length)) {
StackTraceElement caller = stackTrace[1];
builder.className(caller.getClassName());
builder.methodName(caller.getMethodName());
builder.lineNumber(caller.getLineNumber());
}
}
appender.append(builder.build());
}
} catch (Throwable t) {
LOGGER.info("Unable to queue message to Stackify Log API service: {} {}", level, message, t);
}
} | java | public static void queueMessage(final String level, final String message) {
try {
LogAppender<LogEvent> appender = LogManager.getAppender();
if (appender != null) {
LogEvent.Builder builder = LogEvent.newBuilder();
builder.level(level);
builder.message(message);
if ((level != null) && ("ERROR".equals(level.toUpperCase()))) {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
if ((stackTrace != null) && (1 < stackTrace.length)) {
StackTraceElement caller = stackTrace[1];
builder.className(caller.getClassName());
builder.methodName(caller.getMethodName());
builder.lineNumber(caller.getLineNumber());
}
}
appender.append(builder.build());
}
} catch (Throwable t) {
LOGGER.info("Unable to queue message to Stackify Log API service: {} {}", level, message, t);
}
} | [
"public",
"static",
"void",
"queueMessage",
"(",
"final",
"String",
"level",
",",
"final",
"String",
"message",
")",
"{",
"try",
"{",
"LogAppender",
"<",
"LogEvent",
">",
"appender",
"=",
"LogManager",
".",
"getAppender",
"(",
")",
";",
"if",
"(",
"appende... | Queues a log message to be sent to Stackify
@param level The log level
@param message The log message | [
"Queues",
"a",
"log",
"message",
"to",
"be",
"sent",
"to",
"Stackify"
] | train | https://github.com/stackify/stackify-api-java/blob/d3000b7c87ed53a88b302939b0c88405d63d7b67/src/main/java/com/stackify/api/common/log/direct/Logger.java#L38-L63 |
http-builder-ng/http-builder-ng | http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java | HttpBuilder.headAsync | public CompletableFuture<Object> headAsync(@DelegatesTo(HttpConfig.class) final Closure closure) {
"""
Executes an asynchronous HEAD request on the configured URI (asynchronous alias to the `head(Closure)` method), with additional configuration
provided by the configuration closure.
[source,groovy]
----
def http = HttpBuilder.configure {
request.uri = 'http://localhost:10101'
}
http.headAsync(){
request.uri.path = '/something'
}
----
The configuration `closure` allows additional configuration for this request based on the {@link HttpConfig} interface.
The response will not contain content unless the `response.when()` method closure provides it based on the response headers.
@param closure the additional configuration closure (delegated to {@link HttpConfig})
@return the resulting content
"""
return CompletableFuture.supplyAsync(() -> head(closure), getExecutor());
} | java | public CompletableFuture<Object> headAsync(@DelegatesTo(HttpConfig.class) final Closure closure) {
return CompletableFuture.supplyAsync(() -> head(closure), getExecutor());
} | [
"public",
"CompletableFuture",
"<",
"Object",
">",
"headAsync",
"(",
"@",
"DelegatesTo",
"(",
"HttpConfig",
".",
"class",
")",
"final",
"Closure",
"closure",
")",
"{",
"return",
"CompletableFuture",
".",
"supplyAsync",
"(",
"(",
")",
"->",
"head",
"(",
"clos... | Executes an asynchronous HEAD request on the configured URI (asynchronous alias to the `head(Closure)` method), with additional configuration
provided by the configuration closure.
[source,groovy]
----
def http = HttpBuilder.configure {
request.uri = 'http://localhost:10101'
}
http.headAsync(){
request.uri.path = '/something'
}
----
The configuration `closure` allows additional configuration for this request based on the {@link HttpConfig} interface.
The response will not contain content unless the `response.when()` method closure provides it based on the response headers.
@param closure the additional configuration closure (delegated to {@link HttpConfig})
@return the resulting content | [
"Executes",
"an",
"asynchronous",
"HEAD",
"request",
"on",
"the",
"configured",
"URI",
"(",
"asynchronous",
"alias",
"to",
"the",
"head",
"(",
"Closure",
")",
"method",
")",
"with",
"additional",
"configuration",
"provided",
"by",
"the",
"configuration",
"closur... | train | https://github.com/http-builder-ng/http-builder-ng/blob/865f37732c102c748d3db8b905199dac9222a525/http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java#L605-L607 |
googlegenomics/dataflow-java | src/main/java/com/google/cloud/genomics/dataflow/utils/GCSHelper.java | GCSHelper.getAsFile | public File getAsFile(String bucket, String fname) throws IOException {
"""
Retrieve the whole file (to a temporary file on disk).
@throws IOException
"""
Storage.Objects.Get request = storage.objects().get(bucket, fname);
File file = File.createTempFile("gcsdownload", "obj");
try (OutputStream out = new FileOutputStream(file)) {
request.executeMediaAndDownloadTo(out);
}
return file;
} | java | public File getAsFile(String bucket, String fname) throws IOException {
Storage.Objects.Get request = storage.objects().get(bucket, fname);
File file = File.createTempFile("gcsdownload", "obj");
try (OutputStream out = new FileOutputStream(file)) {
request.executeMediaAndDownloadTo(out);
}
return file;
} | [
"public",
"File",
"getAsFile",
"(",
"String",
"bucket",
",",
"String",
"fname",
")",
"throws",
"IOException",
"{",
"Storage",
".",
"Objects",
".",
"Get",
"request",
"=",
"storage",
".",
"objects",
"(",
")",
".",
"get",
"(",
"bucket",
",",
"fname",
")",
... | Retrieve the whole file (to a temporary file on disk).
@throws IOException | [
"Retrieve",
"the",
"whole",
"file",
"(",
"to",
"a",
"temporary",
"file",
"on",
"disk",
")",
"."
] | train | https://github.com/googlegenomics/dataflow-java/blob/ef2c56ed1a6397843c55102748b8c2b12aaa4772/src/main/java/com/google/cloud/genomics/dataflow/utils/GCSHelper.java#L197-L204 |
netty/netty | resolver-dns/src/main/java/io/netty/resolver/dns/DnsResolveContext.java | DnsResolveContext.extractAuthoritativeNameServers | private static AuthoritativeNameServerList extractAuthoritativeNameServers(String questionName, DnsResponse res) {
"""
Returns the {@code {@link AuthoritativeNameServerList} which were included in {@link DnsSection#AUTHORITY}
or {@code null} if non are found.
"""
int authorityCount = res.count(DnsSection.AUTHORITY);
if (authorityCount == 0) {
return null;
}
AuthoritativeNameServerList serverNames = new AuthoritativeNameServerList(questionName);
for (int i = 0; i < authorityCount; i++) {
serverNames.add(res.recordAt(DnsSection.AUTHORITY, i));
}
return serverNames.isEmpty() ? null : serverNames;
} | java | private static AuthoritativeNameServerList extractAuthoritativeNameServers(String questionName, DnsResponse res) {
int authorityCount = res.count(DnsSection.AUTHORITY);
if (authorityCount == 0) {
return null;
}
AuthoritativeNameServerList serverNames = new AuthoritativeNameServerList(questionName);
for (int i = 0; i < authorityCount; i++) {
serverNames.add(res.recordAt(DnsSection.AUTHORITY, i));
}
return serverNames.isEmpty() ? null : serverNames;
} | [
"private",
"static",
"AuthoritativeNameServerList",
"extractAuthoritativeNameServers",
"(",
"String",
"questionName",
",",
"DnsResponse",
"res",
")",
"{",
"int",
"authorityCount",
"=",
"res",
".",
"count",
"(",
"DnsSection",
".",
"AUTHORITY",
")",
";",
"if",
"(",
... | Returns the {@code {@link AuthoritativeNameServerList} which were included in {@link DnsSection#AUTHORITY}
or {@code null} if non are found. | [
"Returns",
"the",
"{"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/resolver-dns/src/main/java/io/netty/resolver/dns/DnsResolveContext.java#L630-L641 |
hexagonframework/spring-data-ebean | src/main/java/org/springframework/data/ebean/repository/query/StringQuery.java | StringQuery.getBindingFor | public ParameterBinding getBindingFor(String name) {
"""
Returns the {@link ParameterBinding} for the given name.
@param name must not be {@literal null} or empty.
@return
"""
Assert.hasText(name, PARAMETER_NAME_MISSING);
for (ParameterBinding binding : bindings) {
if (binding.hasName(name)) {
return binding;
}
}
throw new IllegalArgumentException(String.format("No parameter binding found for name %s!", name));
} | java | public ParameterBinding getBindingFor(String name) {
Assert.hasText(name, PARAMETER_NAME_MISSING);
for (ParameterBinding binding : bindings) {
if (binding.hasName(name)) {
return binding;
}
}
throw new IllegalArgumentException(String.format("No parameter binding found for name %s!", name));
} | [
"public",
"ParameterBinding",
"getBindingFor",
"(",
"String",
"name",
")",
"{",
"Assert",
".",
"hasText",
"(",
"name",
",",
"PARAMETER_NAME_MISSING",
")",
";",
"for",
"(",
"ParameterBinding",
"binding",
":",
"bindings",
")",
"{",
"if",
"(",
"binding",
".",
"... | Returns the {@link ParameterBinding} for the given name.
@param name must not be {@literal null} or empty.
@return | [
"Returns",
"the",
"{",
"@link",
"ParameterBinding",
"}",
"for",
"the",
"given",
"name",
"."
] | train | https://github.com/hexagonframework/spring-data-ebean/blob/dd11b97654982403b50dd1d5369cadad71fce410/src/main/java/org/springframework/data/ebean/repository/query/StringQuery.java#L95-L106 |
goldmansachs/gs-collections | collections/src/main/java/com/gs/collections/impl/utility/MapIterate.java | MapIterate.collectIf | public static <K1, V1, K2, V2> MutableMap<K2, V2> collectIf(
Map<K1, V1> map,
final Function2<? super K1, ? super V1, Pair<K2, V2>> function,
final Predicate2<? super K1, ? super V1> predicate,
Map<K2, V2> target) {
"""
For each value of the map, the Predicate2 is evaluated with the key and value as the parameter,
and if true, then {@code function} is applied.
The results of these evaluations are collected into the target map.
"""
final MutableMap<K2, V2> result = MapAdapter.adapt(target);
MapIterate.forEachKeyValue(map, new Procedure2<K1, V1>()
{
public void value(K1 key, V1 value)
{
if (predicate.accept(key, value))
{
Pair<K2, V2> pair = function.value(key, value);
result.put(pair.getOne(), pair.getTwo());
}
}
});
return result;
} | java | public static <K1, V1, K2, V2> MutableMap<K2, V2> collectIf(
Map<K1, V1> map,
final Function2<? super K1, ? super V1, Pair<K2, V2>> function,
final Predicate2<? super K1, ? super V1> predicate,
Map<K2, V2> target)
{
final MutableMap<K2, V2> result = MapAdapter.adapt(target);
MapIterate.forEachKeyValue(map, new Procedure2<K1, V1>()
{
public void value(K1 key, V1 value)
{
if (predicate.accept(key, value))
{
Pair<K2, V2> pair = function.value(key, value);
result.put(pair.getOne(), pair.getTwo());
}
}
});
return result;
} | [
"public",
"static",
"<",
"K1",
",",
"V1",
",",
"K2",
",",
"V2",
">",
"MutableMap",
"<",
"K2",
",",
"V2",
">",
"collectIf",
"(",
"Map",
"<",
"K1",
",",
"V1",
">",
"map",
",",
"final",
"Function2",
"<",
"?",
"super",
"K1",
",",
"?",
"super",
"V1"... | For each value of the map, the Predicate2 is evaluated with the key and value as the parameter,
and if true, then {@code function} is applied.
The results of these evaluations are collected into the target map. | [
"For",
"each",
"value",
"of",
"the",
"map",
"the",
"Predicate2",
"is",
"evaluated",
"with",
"the",
"key",
"and",
"value",
"as",
"the",
"parameter",
"and",
"if",
"true",
"then",
"{"
] | train | https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/MapIterate.java#L702-L723 |
FlyingHe/UtilsMaven | src/main/java/com/github/flyinghe/tools/CommonUtils.java | CommonUtils.imgToBase64Str | public static String imgToBase64Str(BufferedImage image, String formatName) {
"""
将一张图片转换成指定格式的Base64字符串编码
@param image 指定一张图片
@param formatName 图片格式名,如gif,png,jpg,jpeg等,默认为jpeg
@return 返回编码好的字符串, 失败返回null
"""
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String base64Str = null;
try {
ImageIO.write(image, formatName == null ? "jpeg" : formatName, baos);
byte[] bytes = baos.toByteArray();
base64Str = CommonUtils.bytesToBase64Str(bytes);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
CommonUtils.closeIOStream(null, baos);
}
return base64Str;
} | java | public static String imgToBase64Str(BufferedImage image, String formatName) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String base64Str = null;
try {
ImageIO.write(image, formatName == null ? "jpeg" : formatName, baos);
byte[] bytes = baos.toByteArray();
base64Str = CommonUtils.bytesToBase64Str(bytes);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
CommonUtils.closeIOStream(null, baos);
}
return base64Str;
} | [
"public",
"static",
"String",
"imgToBase64Str",
"(",
"BufferedImage",
"image",
",",
"String",
"formatName",
")",
"{",
"ByteArrayOutputStream",
"baos",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"String",
"base64Str",
"=",
"null",
";",
"try",
"{",
"Image... | 将一张图片转换成指定格式的Base64字符串编码
@param image 指定一张图片
@param formatName 图片格式名,如gif,png,jpg,jpeg等,默认为jpeg
@return 返回编码好的字符串, 失败返回null | [
"将一张图片转换成指定格式的Base64字符串编码"
] | train | https://github.com/FlyingHe/UtilsMaven/blob/d9605b7bfe0c28a05289252e12d163e114080b4a/src/main/java/com/github/flyinghe/tools/CommonUtils.java#L181-L194 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/SeaGlassLookAndFeel.java | SeaGlassLookAndFeel.updateSubregion | public static void updateSubregion(SynthContext state, Graphics g, Rectangle bounds) {
"""
A convenience method that handles painting of the background for
subregions. All SynthUI's that have subregions should invoke this method,
than paint the foreground.
@param state the SynthContext describing the component, region, and
state.
@param g the Graphics context used to paint the subregion.
@param bounds the bounds to paint in.
"""
paintRegion(state, g, bounds);
} | java | public static void updateSubregion(SynthContext state, Graphics g, Rectangle bounds) {
paintRegion(state, g, bounds);
} | [
"public",
"static",
"void",
"updateSubregion",
"(",
"SynthContext",
"state",
",",
"Graphics",
"g",
",",
"Rectangle",
"bounds",
")",
"{",
"paintRegion",
"(",
"state",
",",
"g",
",",
"bounds",
")",
";",
"}"
] | A convenience method that handles painting of the background for
subregions. All SynthUI's that have subregions should invoke this method,
than paint the foreground.
@param state the SynthContext describing the component, region, and
state.
@param g the Graphics context used to paint the subregion.
@param bounds the bounds to paint in. | [
"A",
"convenience",
"method",
"that",
"handles",
"painting",
"of",
"the",
"background",
"for",
"subregions",
".",
"All",
"SynthUI",
"s",
"that",
"have",
"subregions",
"should",
"invoke",
"this",
"method",
"than",
"paint",
"the",
"foreground",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/SeaGlassLookAndFeel.java#L2792-L2794 |
salesforce/Argus | ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/ChartResources.java | ChartResources.getCharts | @GET
@Produces(MediaType.APPLICATION_JSON)
@Description("Return a list of charts owned by a user. Optionally, provide an entityId to filter charts associated "
+ "with a given entity. ")
public List<ChartDto> getCharts(@Context HttpServletRequest req,
@QueryParam("ownerName") String ownerName,
@QueryParam("entityId") BigInteger entityId) {
"""
Return a list of charts owned by a user. Optionally, provide an entityId to filter charts associated
with a given entity.
@param req The HttpServlet request object. Cannot be null.
@param ownerName Optional. The username for which to retrieve charts. For non-privileged this must be null
or equal to the logged in user.
@param entityId Optional. The entity id associated with these charts.
@return A list of charts filtered using the provided parameters.
@throws WebApplicationException An exception with 404 NOT_FOUND will be thrown if the user does not exist.
"""
PrincipalUser remoteUser = getRemoteUser(req);
PrincipalUser owner;
owner = validateAndGetOwner(req,ownerName);
List<Chart> result = new ArrayList<>();
if(entityId == null) {
result.addAll(_chartService.getChartsByOwner(owner));
} else {
Dashboard dashboard = _dService.findDashboardByPrimaryKey(entityId);
if(dashboard==null)
{
throw new WebApplicationException(entityId + ": Dashboard does not exist.", Status.NOT_FOUND);
}
else if(dashboard.isShared() || remoteUser.isPrivileged())
{
result.addAll(_chartService.getChartsForEntity(entityId));
}
else {
result.addAll(_chartService.getChartsByOwnerForEntity(owner, entityId));
}
}
return ChartDto.transformToDto(result);
} | java | @GET
@Produces(MediaType.APPLICATION_JSON)
@Description("Return a list of charts owned by a user. Optionally, provide an entityId to filter charts associated "
+ "with a given entity. ")
public List<ChartDto> getCharts(@Context HttpServletRequest req,
@QueryParam("ownerName") String ownerName,
@QueryParam("entityId") BigInteger entityId) {
PrincipalUser remoteUser = getRemoteUser(req);
PrincipalUser owner;
owner = validateAndGetOwner(req,ownerName);
List<Chart> result = new ArrayList<>();
if(entityId == null) {
result.addAll(_chartService.getChartsByOwner(owner));
} else {
Dashboard dashboard = _dService.findDashboardByPrimaryKey(entityId);
if(dashboard==null)
{
throw new WebApplicationException(entityId + ": Dashboard does not exist.", Status.NOT_FOUND);
}
else if(dashboard.isShared() || remoteUser.isPrivileged())
{
result.addAll(_chartService.getChartsForEntity(entityId));
}
else {
result.addAll(_chartService.getChartsByOwnerForEntity(owner, entityId));
}
}
return ChartDto.transformToDto(result);
} | [
"@",
"GET",
"@",
"Produces",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Description",
"(",
"\"Return a list of charts owned by a user. Optionally, provide an entityId to filter charts associated \"",
"+",
"\"",
"with",
"given",
"entity",
".",
"\"",
")",
"public",... | Return a list of charts owned by a user. Optionally, provide an entityId to filter charts associated
with a given entity.
@param req The HttpServlet request object. Cannot be null.
@param ownerName Optional. The username for which to retrieve charts. For non-privileged this must be null
or equal to the logged in user.
@param entityId Optional. The entity id associated with these charts.
@return A list of charts filtered using the provided parameters.
@throws WebApplicationException An exception with 404 NOT_FOUND will be thrown if the user does not exist. | [
"Return",
"a",
"list",
"of",
"charts",
"owned",
"by",
"a",
"user",
".",
"Optionally",
"provide",
"an",
"entityId",
"to",
"filter",
"charts",
"associated",
"with",
"a",
"given",
"entity",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/ChartResources.java#L264-L294 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java | MapUtil.of | public static <K, V> HashMap<K, V> of(K key, V value) {
"""
将单一键值对转换为Map
@param <K> 键类型
@param <V> 值类型
@param key 键
@param value 值
@return {@link HashMap}
"""
return of(key, value, false);
} | java | public static <K, V> HashMap<K, V> of(K key, V value) {
return of(key, value, false);
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"HashMap",
"<",
"K",
",",
"V",
">",
"of",
"(",
"K",
"key",
",",
"V",
"value",
")",
"{",
"return",
"of",
"(",
"key",
",",
"value",
",",
"false",
")",
";",
"}"
] | 将单一键值对转换为Map
@param <K> 键类型
@param <V> 值类型
@param key 键
@param value 值
@return {@link HashMap} | [
"将单一键值对转换为Map"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java#L175-L177 |
apache/flink | flink-connectors/flink-hbase/src/main/java/org/apache/flink/addons/hbase/TableInputFormat.java | TableInputFormat.createTable | private HTable createTable() {
"""
Create an {@link HTable} instance and set it into this format.
"""
LOG.info("Initializing HBaseConfiguration");
//use files found in the classpath
org.apache.hadoop.conf.Configuration hConf = HBaseConfiguration.create();
try {
return new HTable(hConf, getTableName());
} catch (Exception e) {
LOG.error("Error instantiating a new HTable instance", e);
}
return null;
} | java | private HTable createTable() {
LOG.info("Initializing HBaseConfiguration");
//use files found in the classpath
org.apache.hadoop.conf.Configuration hConf = HBaseConfiguration.create();
try {
return new HTable(hConf, getTableName());
} catch (Exception e) {
LOG.error("Error instantiating a new HTable instance", e);
}
return null;
} | [
"private",
"HTable",
"createTable",
"(",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Initializing HBaseConfiguration\"",
")",
";",
"//use files found in the classpath",
"org",
".",
"apache",
".",
"hadoop",
".",
"conf",
".",
"Configuration",
"hConf",
"=",
"HBaseConfigurati... | Create an {@link HTable} instance and set it into this format. | [
"Create",
"an",
"{"
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-hbase/src/main/java/org/apache/flink/addons/hbase/TableInputFormat.java#L78-L89 |
kaazing/gateway | util/src/main/java/org/kaazing/gateway/util/Utils.java | Utils.getLong | public static long getLong(ByteBuffer buf, int index) {
"""
Reads an long value from the buffer starting at the given index relative to the current
position() of the buffer, without mutating the buffer in any way (so it's thread safe).
"""
return buf.order() == BIG_ENDIAN ? getLongB(buf, index) : getLongL(buf, index);
} | java | public static long getLong(ByteBuffer buf, int index) {
return buf.order() == BIG_ENDIAN ? getLongB(buf, index) : getLongL(buf, index);
} | [
"public",
"static",
"long",
"getLong",
"(",
"ByteBuffer",
"buf",
",",
"int",
"index",
")",
"{",
"return",
"buf",
".",
"order",
"(",
")",
"==",
"BIG_ENDIAN",
"?",
"getLongB",
"(",
"buf",
",",
"index",
")",
":",
"getLongL",
"(",
"buf",
",",
"index",
")... | Reads an long value from the buffer starting at the given index relative to the current
position() of the buffer, without mutating the buffer in any way (so it's thread safe). | [
"Reads",
"an",
"long",
"value",
"from",
"the",
"buffer",
"starting",
"at",
"the",
"given",
"index",
"relative",
"to",
"the",
"current",
"position",
"()",
"of",
"the",
"buffer",
"without",
"mutating",
"the",
"buffer",
"in",
"any",
"way",
"(",
"so",
"it",
... | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/util/src/main/java/org/kaazing/gateway/util/Utils.java#L442-L444 |
oehf/ipf-oht-atna | nodeauth/src/main/java/org/openhealthtools/ihe/atna/nodeauth/SecurityDomainManager.java | SecurityDomainManager.formatKey | public String formatKey(URI uri) throws URISyntaxException {
"""
Converts a well-formed URI containing a hostname and port into
string which allows for lookups in the Security Domain table
@param uri URI to convert
@return A string with "host:port" concatenated
@throws URISyntaxException
"""
if (uri == null) {
throw new URISyntaxException("","URI specified is null");
}
return formatKey(uri.getHost(), uri.getPort());
} | java | public String formatKey(URI uri) throws URISyntaxException
{
if (uri == null) {
throw new URISyntaxException("","URI specified is null");
}
return formatKey(uri.getHost(), uri.getPort());
} | [
"public",
"String",
"formatKey",
"(",
"URI",
"uri",
")",
"throws",
"URISyntaxException",
"{",
"if",
"(",
"uri",
"==",
"null",
")",
"{",
"throw",
"new",
"URISyntaxException",
"(",
"\"\"",
",",
"\"URI specified is null\"",
")",
";",
"}",
"return",
"formatKey",
... | Converts a well-formed URI containing a hostname and port into
string which allows for lookups in the Security Domain table
@param uri URI to convert
@return A string with "host:port" concatenated
@throws URISyntaxException | [
"Converts",
"a",
"well",
"-",
"formed",
"URI",
"containing",
"a",
"hostname",
"and",
"port",
"into",
"string",
"which",
"allows",
"for",
"lookups",
"in",
"the",
"Security",
"Domain",
"table"
] | train | https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/nodeauth/src/main/java/org/openhealthtools/ihe/atna/nodeauth/SecurityDomainManager.java#L240-L246 |
OrienteerBAP/wicket-orientdb | wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/OSchemaUtils.java | OSchemaUtils.probeOClass | public static OClass probeOClass(Iterator<ODocument> it, int probeLimit) {
"""
Check first several items to resolve common {@link OClass}
@param it {@link Iterable} over {@link ODocument}s
@param probeLimit limit over iterable
@return common {@link OClass} or null
"""
return getCommonOClass(Iterators.limit(it, probeLimit));
} | java | public static OClass probeOClass(Iterator<ODocument> it, int probeLimit) {
return getCommonOClass(Iterators.limit(it, probeLimit));
} | [
"public",
"static",
"OClass",
"probeOClass",
"(",
"Iterator",
"<",
"ODocument",
">",
"it",
",",
"int",
"probeLimit",
")",
"{",
"return",
"getCommonOClass",
"(",
"Iterators",
".",
"limit",
"(",
"it",
",",
"probeLimit",
")",
")",
";",
"}"
] | Check first several items to resolve common {@link OClass}
@param it {@link Iterable} over {@link ODocument}s
@param probeLimit limit over iterable
@return common {@link OClass} or null | [
"Check",
"first",
"several",
"items",
"to",
"resolve",
"common",
"{"
] | train | https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/OSchemaUtils.java#L39-L41 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/lss/LssClient.java | LssClient.createSession | public CreateSessionResponse createSession(CreateSessionRequest request) {
"""
Create a live session in the live stream service.
@param request The request object containing all options for creating live session.
@return the response
"""
checkNotNull(request, "The parameter request should NOT be null.");
if (request.getPreset() == null && request.getPresets() == null) {
throw new IllegalArgumentException("The parameter preset and presets should NOT both be null or empty.");
}
InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, LIVE_SESSION);
return invokeHttpClient(internalRequest, CreateSessionResponse.class);
} | java | public CreateSessionResponse createSession(CreateSessionRequest request) {
checkNotNull(request, "The parameter request should NOT be null.");
if (request.getPreset() == null && request.getPresets() == null) {
throw new IllegalArgumentException("The parameter preset and presets should NOT both be null or empty.");
}
InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, LIVE_SESSION);
return invokeHttpClient(internalRequest, CreateSessionResponse.class);
} | [
"public",
"CreateSessionResponse",
"createSession",
"(",
"CreateSessionRequest",
"request",
")",
"{",
"checkNotNull",
"(",
"request",
",",
"\"The parameter request should NOT be null.\"",
")",
";",
"if",
"(",
"request",
".",
"getPreset",
"(",
")",
"==",
"null",
"&&",
... | Create a live session in the live stream service.
@param request The request object containing all options for creating live session.
@return the response | [
"Create",
"a",
"live",
"session",
"in",
"the",
"live",
"stream",
"service",
"."
] | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/lss/LssClient.java#L528-L537 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java | TrainingsImpl.getIteration | public Iteration getIteration(UUID projectId, UUID iterationId) {
"""
Get a specific iteration.
@param projectId The id of the project the iteration belongs to
@param iterationId The id of the iteration to get
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the Iteration object if successful.
"""
return getIterationWithServiceResponseAsync(projectId, iterationId).toBlocking().single().body();
} | java | public Iteration getIteration(UUID projectId, UUID iterationId) {
return getIterationWithServiceResponseAsync(projectId, iterationId).toBlocking().single().body();
} | [
"public",
"Iteration",
"getIteration",
"(",
"UUID",
"projectId",
",",
"UUID",
"iterationId",
")",
"{",
"return",
"getIterationWithServiceResponseAsync",
"(",
"projectId",
",",
"iterationId",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",... | Get a specific iteration.
@param projectId The id of the project the iteration belongs to
@param iterationId The id of the iteration to get
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the Iteration object if successful. | [
"Get",
"a",
"specific",
"iteration",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L1964-L1966 |
VoltDB/voltdb | src/frontend/org/voltdb/utils/PersistentBinaryDeque.java | PersistentBinaryDeque.quarantineSegment | private void quarantineSegment(Map.Entry<Long, PBDSegment> prevEntry) throws IOException {
"""
Quarantine a segment which was already added to {@link #m_segments}
@param prevEntry {@link Map.Entry} from {@link #m_segments} to quarantine
@throws IOException
"""
quarantineSegment(prevEntry, prevEntry.getValue(), prevEntry.getValue().getNumEntries());
} | java | private void quarantineSegment(Map.Entry<Long, PBDSegment> prevEntry) throws IOException {
quarantineSegment(prevEntry, prevEntry.getValue(), prevEntry.getValue().getNumEntries());
} | [
"private",
"void",
"quarantineSegment",
"(",
"Map",
".",
"Entry",
"<",
"Long",
",",
"PBDSegment",
">",
"prevEntry",
")",
"throws",
"IOException",
"{",
"quarantineSegment",
"(",
"prevEntry",
",",
"prevEntry",
".",
"getValue",
"(",
")",
",",
"prevEntry",
".",
... | Quarantine a segment which was already added to {@link #m_segments}
@param prevEntry {@link Map.Entry} from {@link #m_segments} to quarantine
@throws IOException | [
"Quarantine",
"a",
"segment",
"which",
"was",
"already",
"added",
"to",
"{",
"@link",
"#m_segments",
"}"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/utils/PersistentBinaryDeque.java#L618-L620 |
SUSE/salt-netapi-client | src/main/java/com/suse/salt/netapi/calls/modules/File.java | File.mkdir | public static LocalCall<String> mkdir(String path) {
"""
Ensures that a directory is available
@param path Path to directory
@return The {@link LocalCall} object to make the call
"""
return mkdir(path, Optional.empty(), Optional.empty(), Optional.empty());
} | java | public static LocalCall<String> mkdir(String path) {
return mkdir(path, Optional.empty(), Optional.empty(), Optional.empty());
} | [
"public",
"static",
"LocalCall",
"<",
"String",
">",
"mkdir",
"(",
"String",
"path",
")",
"{",
"return",
"mkdir",
"(",
"path",
",",
"Optional",
".",
"empty",
"(",
")",
",",
"Optional",
".",
"empty",
"(",
")",
",",
"Optional",
".",
"empty",
"(",
")",
... | Ensures that a directory is available
@param path Path to directory
@return The {@link LocalCall} object to make the call | [
"Ensures",
"that",
"a",
"directory",
"is",
"available"
] | train | https://github.com/SUSE/salt-netapi-client/blob/a0bdf643c8e34fa4def4b915366594c1491fdad5/src/main/java/com/suse/salt/netapi/calls/modules/File.java#L240-L242 |
deeplearning4j/deeplearning4j | datavec/datavec-api/src/main/java/org/datavec/api/io/WritableUtils.java | WritableUtils.writeStringArray | public static void writeStringArray(DataOutput out, String[] s) throws IOException {
"""
/*
Write a String array as a Nework Int N, followed by Int N Byte Array Strings.
Could be generalised using introspection.
"""
out.writeInt(s.length);
for (int i = 0; i < s.length; i++) {
writeString(out, s[i]);
}
} | java | public static void writeStringArray(DataOutput out, String[] s) throws IOException {
out.writeInt(s.length);
for (int i = 0; i < s.length; i++) {
writeString(out, s[i]);
}
} | [
"public",
"static",
"void",
"writeStringArray",
"(",
"DataOutput",
"out",
",",
"String",
"[",
"]",
"s",
")",
"throws",
"IOException",
"{",
"out",
".",
"writeInt",
"(",
"s",
".",
"length",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"... | /*
Write a String array as a Nework Int N, followed by Int N Byte Array Strings.
Could be generalised using introspection. | [
"/",
"*",
"Write",
"a",
"String",
"array",
"as",
"a",
"Nework",
"Int",
"N",
"followed",
"by",
"Int",
"N",
"Byte",
"Array",
"Strings",
".",
"Could",
"be",
"generalised",
"using",
"introspection",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-api/src/main/java/org/datavec/api/io/WritableUtils.java#L129-L134 |
apache/incubator-atlas | repository/src/main/java/org/apache/atlas/gremlin/GremlinExpressionFactory.java | GremlinExpressionFactory.generateUnaryHasExpression | public GroovyExpression generateUnaryHasExpression(GroovyExpression parent, String fieldName) {
"""
Generates an expression which checks whether the vertices in the query have
a field with the given name.
@param parent
@param fieldName
@return
"""
return new FunctionCallExpression(TraversalStepType.FILTER, parent, HAS_METHOD, new LiteralExpression(fieldName));
} | java | public GroovyExpression generateUnaryHasExpression(GroovyExpression parent, String fieldName) {
return new FunctionCallExpression(TraversalStepType.FILTER, parent, HAS_METHOD, new LiteralExpression(fieldName));
} | [
"public",
"GroovyExpression",
"generateUnaryHasExpression",
"(",
"GroovyExpression",
"parent",
",",
"String",
"fieldName",
")",
"{",
"return",
"new",
"FunctionCallExpression",
"(",
"TraversalStepType",
".",
"FILTER",
",",
"parent",
",",
"HAS_METHOD",
",",
"new",
"Lite... | Generates an expression which checks whether the vertices in the query have
a field with the given name.
@param parent
@param fieldName
@return | [
"Generates",
"an",
"expression",
"which",
"checks",
"whether",
"the",
"vertices",
"in",
"the",
"query",
"have",
"a",
"field",
"with",
"the",
"given",
"name",
"."
] | train | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/repository/src/main/java/org/apache/atlas/gremlin/GremlinExpressionFactory.java#L421-L423 |
astrapi69/mystic-crypt | crypt-data/src/main/java/de/alpharogroup/crypto/factories/SecretKeyFactoryExtensions.java | SecretKeyFactoryExtensions.newSecretKey | public static SecretKey newSecretKey(final char[] password, final String algorithm)
throws NoSuchAlgorithmException, InvalidKeySpecException {
"""
Factory method for creating a new {@link SecretKey} from the given password and algorithm.
@param password
the password
@param algorithm
the algorithm
@return the new {@link SecretKey} from the given password and algorithm.
@throws NoSuchAlgorithmException
is thrown if instantiation of the SecretKeyFactory object fails.
@throws InvalidKeySpecException
is thrown if generation of the SecretKey object fails.
"""
final PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
final SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
return secretKey;
} | java | public static SecretKey newSecretKey(final char[] password, final String algorithm)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
final PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
final SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
return secretKey;
} | [
"public",
"static",
"SecretKey",
"newSecretKey",
"(",
"final",
"char",
"[",
"]",
"password",
",",
"final",
"String",
"algorithm",
")",
"throws",
"NoSuchAlgorithmException",
",",
"InvalidKeySpecException",
"{",
"final",
"PBEKeySpec",
"pbeKeySpec",
"=",
"new",
"PBEKey... | Factory method for creating a new {@link SecretKey} from the given password and algorithm.
@param password
the password
@param algorithm
the algorithm
@return the new {@link SecretKey} from the given password and algorithm.
@throws NoSuchAlgorithmException
is thrown if instantiation of the SecretKeyFactory object fails.
@throws InvalidKeySpecException
is thrown if generation of the SecretKey object fails. | [
"Factory",
"method",
"for",
"creating",
"a",
"new",
"{",
"@link",
"SecretKey",
"}",
"from",
"the",
"given",
"password",
"and",
"algorithm",
"."
] | train | https://github.com/astrapi69/mystic-crypt/blob/7f51ef5e4457e24de7ff391f10bfc5609e6f1a34/crypt-data/src/main/java/de/alpharogroup/crypto/factories/SecretKeyFactoryExtensions.java#L116-L123 |
dlemmermann/CalendarFX | CalendarFXRecurrence/src/main/java/com/google/ical/compat/jodatime/LocalDateIteratorFactory.java | LocalDateIteratorFactory.createLocalDateIterator | public static LocalDateIterator createLocalDateIterator(
String rdata, LocalDate start, boolean strict)
throws ParseException {
"""
given a block of RRULE, EXRULE, RDATE, and EXDATE content lines, parse
them into a single local date iterator.
@param rdata RRULE, EXRULE, RDATE, and EXDATE lines.
@param start the first occurrence of the series.
@param strict true if any failure to parse should result in a
ParseException. false causes bad content lines to be logged and ignored.
"""
return createLocalDateIterator(rdata, start, DateTimeZone.UTC, strict);
} | java | public static LocalDateIterator createLocalDateIterator(
String rdata, LocalDate start, boolean strict)
throws ParseException {
return createLocalDateIterator(rdata, start, DateTimeZone.UTC, strict);
} | [
"public",
"static",
"LocalDateIterator",
"createLocalDateIterator",
"(",
"String",
"rdata",
",",
"LocalDate",
"start",
",",
"boolean",
"strict",
")",
"throws",
"ParseException",
"{",
"return",
"createLocalDateIterator",
"(",
"rdata",
",",
"start",
",",
"DateTimeZone",... | given a block of RRULE, EXRULE, RDATE, and EXDATE content lines, parse
them into a single local date iterator.
@param rdata RRULE, EXRULE, RDATE, and EXDATE lines.
@param start the first occurrence of the series.
@param strict true if any failure to parse should result in a
ParseException. false causes bad content lines to be logged and ignored. | [
"given",
"a",
"block",
"of",
"RRULE",
"EXRULE",
"RDATE",
"and",
"EXDATE",
"content",
"lines",
"parse",
"them",
"into",
"a",
"single",
"local",
"date",
"iterator",
"."
] | train | https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXRecurrence/src/main/java/com/google/ical/compat/jodatime/LocalDateIteratorFactory.java#L71-L75 |
astrapi69/jaulp-wicket | jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/labeled/textfield/LabeledDateTextFieldPanel.java | LabeledDateTextFieldPanel.newDateTextField | protected DateTextField newDateTextField(final String id, final IModel<M> model) {
"""
Factory method for create the new {@link DateTextField}. This method is invoked in the
constructor from the derived classes and can be overridden so users can provide their own
version of a new {@link DateTextField}.
@param id
the id
@param model
the model
@return the new {@link DateTextField}
"""
final IModel<Date> textFieldModel = new PropertyModel<>(model.getObject(), getId());
final DateTextField dateTextField = new DateTextField(id, textFieldModel,
new StyleDateConverter("S-", true))
{
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
public Locale getLocale()
{
return getSession().getLocale();
}
};
final DatePicker datePicker = new DatePicker()
{
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
protected boolean enableMonthYearSelection()
{
return true;
}
};
datePicker.setShowOnFieldClick(true);
dateTextField.add(datePicker);
dateTextField.setOutputMarkupId(true);
return dateTextField;
} | java | protected DateTextField newDateTextField(final String id, final IModel<M> model)
{
final IModel<Date> textFieldModel = new PropertyModel<>(model.getObject(), getId());
final DateTextField dateTextField = new DateTextField(id, textFieldModel,
new StyleDateConverter("S-", true))
{
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
public Locale getLocale()
{
return getSession().getLocale();
}
};
final DatePicker datePicker = new DatePicker()
{
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
protected boolean enableMonthYearSelection()
{
return true;
}
};
datePicker.setShowOnFieldClick(true);
dateTextField.add(datePicker);
dateTextField.setOutputMarkupId(true);
return dateTextField;
} | [
"protected",
"DateTextField",
"newDateTextField",
"(",
"final",
"String",
"id",
",",
"final",
"IModel",
"<",
"M",
">",
"model",
")",
"{",
"final",
"IModel",
"<",
"Date",
">",
"textFieldModel",
"=",
"new",
"PropertyModel",
"<>",
"(",
"model",
".",
"getObject"... | Factory method for create the new {@link DateTextField}. This method is invoked in the
constructor from the derived classes and can be overridden so users can provide their own
version of a new {@link DateTextField}.
@param id
the id
@param model
the model
@return the new {@link DateTextField} | [
"Factory",
"method",
"for",
"create",
"the",
"new",
"{",
"@link",
"DateTextField",
"}",
".",
"This",
"method",
"is",
"invoked",
"in",
"the",
"constructor",
"from",
"the",
"derived",
"classes",
"and",
"can",
"be",
"overridden",
"so",
"users",
"can",
"provide"... | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/labeled/textfield/LabeledDateTextFieldPanel.java#L95-L136 |
before/uadetector | modules/uadetector-core/src/main/java/net/sf/uadetector/datastore/CachingXmlDataStore.java | CachingXmlDataStore.readCacheFileAsFallback | private static DataStore readCacheFileAsFallback(@Nonnull final DataReader reader, @Nonnull final File cacheFile,
@Nonnull final Charset charset, @Nonnull final DataStore fallback) {
"""
Tries to read the content of specified cache file and returns them as fallback data store. If the cache file
contains unexpected data the given fallback data store will be returned instead.
@param reader
data reader to read the given {@code dataUrl}
@param cacheFile
file with cached <em>UAS data</em> in XML format or empty file
@param versionUrl
URL to version information about the given <em>UAS data</em>
@param charset
the character set in which the data should be read
@param fallback
<em>UAS data</em> as fallback in case the data on the specified resource can not be read correctly
@return a fallback data store
"""
DataStore fallbackDataStore;
if (!isEmpty(cacheFile, charset)) {
final URL cacheFileUrl = UrlUtil.toUrl(cacheFile);
try {
fallbackDataStore = new CacheFileDataStore(reader.read(cacheFileUrl, charset), reader, cacheFileUrl, charset);
LOG.debug(MSG_CACHE_FILE_IS_FILLED);
} catch (final RuntimeException e) {
fallbackDataStore = fallback;
deleteCacheFile(cacheFile);
}
} else {
fallbackDataStore = fallback;
LOG.debug(MSG_CACHE_FILE_IS_EMPTY);
}
return fallbackDataStore;
} | java | private static DataStore readCacheFileAsFallback(@Nonnull final DataReader reader, @Nonnull final File cacheFile,
@Nonnull final Charset charset, @Nonnull final DataStore fallback) {
DataStore fallbackDataStore;
if (!isEmpty(cacheFile, charset)) {
final URL cacheFileUrl = UrlUtil.toUrl(cacheFile);
try {
fallbackDataStore = new CacheFileDataStore(reader.read(cacheFileUrl, charset), reader, cacheFileUrl, charset);
LOG.debug(MSG_CACHE_FILE_IS_FILLED);
} catch (final RuntimeException e) {
fallbackDataStore = fallback;
deleteCacheFile(cacheFile);
}
} else {
fallbackDataStore = fallback;
LOG.debug(MSG_CACHE_FILE_IS_EMPTY);
}
return fallbackDataStore;
} | [
"private",
"static",
"DataStore",
"readCacheFileAsFallback",
"(",
"@",
"Nonnull",
"final",
"DataReader",
"reader",
",",
"@",
"Nonnull",
"final",
"File",
"cacheFile",
",",
"@",
"Nonnull",
"final",
"Charset",
"charset",
",",
"@",
"Nonnull",
"final",
"DataStore",
"... | Tries to read the content of specified cache file and returns them as fallback data store. If the cache file
contains unexpected data the given fallback data store will be returned instead.
@param reader
data reader to read the given {@code dataUrl}
@param cacheFile
file with cached <em>UAS data</em> in XML format or empty file
@param versionUrl
URL to version information about the given <em>UAS data</em>
@param charset
the character set in which the data should be read
@param fallback
<em>UAS data</em> as fallback in case the data on the specified resource can not be read correctly
@return a fallback data store | [
"Tries",
"to",
"read",
"the",
"content",
"of",
"specified",
"cache",
"file",
"and",
"returns",
"them",
"as",
"fallback",
"data",
"store",
".",
"If",
"the",
"cache",
"file",
"contains",
"unexpected",
"data",
"the",
"given",
"fallback",
"data",
"store",
"will"... | train | https://github.com/before/uadetector/blob/215fb652723c52866572cff885f52a3fe67b9db5/modules/uadetector-core/src/main/java/net/sf/uadetector/datastore/CachingXmlDataStore.java#L286-L303 |
opendatatrentino/s-match | src/main/java/it/unitn/disi/smatch/filters/SPSMMappingFilter.java | SPSMMappingFilter.comparePrecedence | private int comparePrecedence(char sourceRelation, char targetRelation) {
"""
Compares the semantic relation of the source and target in the order of precedence
= > < ! ?. Returning -1 if sourceRelation is less precedent than targetRelation,
0 if sourceRelation is equally precedent than targetRelation,
1 if sourceRelation is more precedent than targetRelation.
@param sourceRelation source relation from IMappingElement.
@param targetRelation target relation from IMappingElement.
@return -1 if sourceRelation is less precedent than targetRelation,
0 if sourceRelation is equally precedent than targetRelation,
1 if sourceRelation is more precedent than targetRelation.
"""
int result = -1;
int sourcePrecedence = getPrecedenceNumber(sourceRelation);
int targetPrecedence = getPrecedenceNumber(targetRelation);
if (sourcePrecedence < targetPrecedence) {
result = 1;
} else if (sourcePrecedence == targetPrecedence) {
result = 0;
} else {
result = -1;
}
return result;
} | java | private int comparePrecedence(char sourceRelation, char targetRelation) {
int result = -1;
int sourcePrecedence = getPrecedenceNumber(sourceRelation);
int targetPrecedence = getPrecedenceNumber(targetRelation);
if (sourcePrecedence < targetPrecedence) {
result = 1;
} else if (sourcePrecedence == targetPrecedence) {
result = 0;
} else {
result = -1;
}
return result;
} | [
"private",
"int",
"comparePrecedence",
"(",
"char",
"sourceRelation",
",",
"char",
"targetRelation",
")",
"{",
"int",
"result",
"=",
"-",
"1",
";",
"int",
"sourcePrecedence",
"=",
"getPrecedenceNumber",
"(",
"sourceRelation",
")",
";",
"int",
"targetPrecedence",
... | Compares the semantic relation of the source and target in the order of precedence
= > < ! ?. Returning -1 if sourceRelation is less precedent than targetRelation,
0 if sourceRelation is equally precedent than targetRelation,
1 if sourceRelation is more precedent than targetRelation.
@param sourceRelation source relation from IMappingElement.
@param targetRelation target relation from IMappingElement.
@return -1 if sourceRelation is less precedent than targetRelation,
0 if sourceRelation is equally precedent than targetRelation,
1 if sourceRelation is more precedent than targetRelation. | [
"Compares",
"the",
"semantic",
"relation",
"of",
"the",
"source",
"and",
"target",
"in",
"the",
"order",
"of",
"precedence",
"=",
">",
"<",
"!",
"?",
".",
"Returning",
"-",
"1",
"if",
"sourceRelation",
"is",
"less",
"precedent",
"than",
"targetRelation",
"... | train | https://github.com/opendatatrentino/s-match/blob/ba5982ef406b7010c2f92592e43887a485935aa1/src/main/java/it/unitn/disi/smatch/filters/SPSMMappingFilter.java#L512-L526 |
OpenLiberty/open-liberty | dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/java2sec/PermissionManager.java | PermissionManager.addPermissionsXMLPermission | public void addPermissionsXMLPermission(CodeSource codeSource, Permission permission) {
"""
Adds a permission from the permissions.xml file for the given CodeSource.
@param codeSource - The CodeSource of the code the specified permission was granted to.
@param permissions - The permissions granted in the permissions.xml of the application.
@return the effective granted permissions
"""
ArrayList<Permission> permissions = null;
String codeBase = codeSource.getLocation().getPath();
if (!isRestricted(permission)) {
if (permissionXMLPermissionMap.containsKey(codeBase)) {
permissions = permissionXMLPermissionMap.get(codeBase);
permissions.add(permission);
} else {
permissions = new ArrayList<Permission>();
permissions.add(permission);
permissionXMLPermissionMap.put(codeBase, permissions);
}
}
} | java | public void addPermissionsXMLPermission(CodeSource codeSource, Permission permission) {
ArrayList<Permission> permissions = null;
String codeBase = codeSource.getLocation().getPath();
if (!isRestricted(permission)) {
if (permissionXMLPermissionMap.containsKey(codeBase)) {
permissions = permissionXMLPermissionMap.get(codeBase);
permissions.add(permission);
} else {
permissions = new ArrayList<Permission>();
permissions.add(permission);
permissionXMLPermissionMap.put(codeBase, permissions);
}
}
} | [
"public",
"void",
"addPermissionsXMLPermission",
"(",
"CodeSource",
"codeSource",
",",
"Permission",
"permission",
")",
"{",
"ArrayList",
"<",
"Permission",
">",
"permissions",
"=",
"null",
";",
"String",
"codeBase",
"=",
"codeSource",
".",
"getLocation",
"(",
")"... | Adds a permission from the permissions.xml file for the given CodeSource.
@param codeSource - The CodeSource of the code the specified permission was granted to.
@param permissions - The permissions granted in the permissions.xml of the application.
@return the effective granted permissions | [
"Adds",
"a",
"permission",
"from",
"the",
"permissions",
".",
"xml",
"file",
"for",
"the",
"given",
"CodeSource",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/java2sec/PermissionManager.java#L618-L632 |
datasalt/pangool | core/src/main/java/com/datasalt/pangool/utils/InstancesDistributor.java | InstancesDistributor.loadInstance | public static <T> T loadInstance(Configuration conf, Class<T> objClass, String fileName, boolean callSetConf)
throws IOException {
"""
Given a Hadoop Configuration property and an Class, this method can
re-instantiate an Object instance that was previously distributed using *
{@link InstancesDistributor#distribute(Object, String, Configuration)}.
@param <T>
The object type.
@param conf
The Hadoop Configuration.
@param objClass
The object type class.
@param fileName
The file name to locate the instance
@param callSetConf
If true, will call setConf() if deserialized instance is
{@link Configurable}
@throws IOException
"""
Path path = InstancesDistributor.locateFileInCache(conf, fileName);
T obj;
ObjectInput in;
if (path == null) {
throw new IOException("Path is null");
}
in = new ObjectInputStream(FileSystem.get(conf).open(path));
try {
obj = objClass.cast(in.readObject());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
in.close();
if (obj instanceof Configurable && callSetConf) {
((Configurable) obj).setConf(conf);
}
return obj;
} | java | public static <T> T loadInstance(Configuration conf, Class<T> objClass, String fileName, boolean callSetConf)
throws IOException {
Path path = InstancesDistributor.locateFileInCache(conf, fileName);
T obj;
ObjectInput in;
if (path == null) {
throw new IOException("Path is null");
}
in = new ObjectInputStream(FileSystem.get(conf).open(path));
try {
obj = objClass.cast(in.readObject());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
in.close();
if (obj instanceof Configurable && callSetConf) {
((Configurable) obj).setConf(conf);
}
return obj;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"loadInstance",
"(",
"Configuration",
"conf",
",",
"Class",
"<",
"T",
">",
"objClass",
",",
"String",
"fileName",
",",
"boolean",
"callSetConf",
")",
"throws",
"IOException",
"{",
"Path",
"path",
"=",
"InstancesDistrib... | Given a Hadoop Configuration property and an Class, this method can
re-instantiate an Object instance that was previously distributed using *
{@link InstancesDistributor#distribute(Object, String, Configuration)}.
@param <T>
The object type.
@param conf
The Hadoop Configuration.
@param objClass
The object type class.
@param fileName
The file name to locate the instance
@param callSetConf
If true, will call setConf() if deserialized instance is
{@link Configurable}
@throws IOException | [
"Given",
"a",
"Hadoop",
"Configuration",
"property",
"and",
"an",
"Class",
"this",
"method",
"can",
"re",
"-",
"instantiate",
"an",
"Object",
"instance",
"that",
"was",
"previously",
"distributed",
"using",
"*",
"{",
"@link",
"InstancesDistributor#distribute",
"("... | train | https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/utils/InstancesDistributor.java#L117-L138 |
ngageoint/geopackage-core-java | src/main/java/mil/nga/geopackage/extension/coverage/CoverageDataCore.java | CoverageDataCore.getCubicInterpolationValue | protected Double getCubicInterpolationValue(Double[] values, double offset) {
"""
Interpolate 4 values using the offset between value1 and value2
@param values
coverage data values
@param offset
offset between the middle two pixels
@return value coverage data value
"""
Double value = null;
if (values != null) {
value = getCubicInterpolationValue(values[0], values[1], values[2],
values[3], offset);
}
return value;
} | java | protected Double getCubicInterpolationValue(Double[] values, double offset) {
Double value = null;
if (values != null) {
value = getCubicInterpolationValue(values[0], values[1], values[2],
values[3], offset);
}
return value;
} | [
"protected",
"Double",
"getCubicInterpolationValue",
"(",
"Double",
"[",
"]",
"values",
",",
"double",
"offset",
")",
"{",
"Double",
"value",
"=",
"null",
";",
"if",
"(",
"values",
"!=",
"null",
")",
"{",
"value",
"=",
"getCubicInterpolationValue",
"(",
"val... | Interpolate 4 values using the offset between value1 and value2
@param values
coverage data values
@param offset
offset between the middle two pixels
@return value coverage data value | [
"Interpolate",
"4",
"values",
"using",
"the",
"offset",
"between",
"value1",
"and",
"value2"
] | train | https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/extension/coverage/CoverageDataCore.java#L1243-L1250 |
joniles/mpxj | src/main/java/net/sf/mpxj/asta/AstaReader.java | AstaReader.processTasks | public void processTasks(List<Row> bars, List<Row> expandedTasks, List<Row> tasks, List<Row> milestones) {
"""
Organises the data from Asta into a hierarchy and converts this into tasks.
@param bars bar data
@param expandedTasks expanded task data
@param tasks task data
@param milestones milestone data
"""
List<Row> parentBars = buildRowHierarchy(bars, expandedTasks, tasks, milestones);
createTasks(m_project, "", parentBars);
deriveProjectCalendar();
updateStructure();
} | java | public void processTasks(List<Row> bars, List<Row> expandedTasks, List<Row> tasks, List<Row> milestones)
{
List<Row> parentBars = buildRowHierarchy(bars, expandedTasks, tasks, milestones);
createTasks(m_project, "", parentBars);
deriveProjectCalendar();
updateStructure();
} | [
"public",
"void",
"processTasks",
"(",
"List",
"<",
"Row",
">",
"bars",
",",
"List",
"<",
"Row",
">",
"expandedTasks",
",",
"List",
"<",
"Row",
">",
"tasks",
",",
"List",
"<",
"Row",
">",
"milestones",
")",
"{",
"List",
"<",
"Row",
">",
"parentBars",... | Organises the data from Asta into a hierarchy and converts this into tasks.
@param bars bar data
@param expandedTasks expanded task data
@param tasks task data
@param milestones milestone data | [
"Organises",
"the",
"data",
"from",
"Asta",
"into",
"a",
"hierarchy",
"and",
"converts",
"this",
"into",
"tasks",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/asta/AstaReader.java#L198-L204 |
google/closure-compiler | src/com/google/javascript/jscomp/DotFormatter.java | DotFormatter.toDot | static String toDot(Node n, ControlFlowGraph<Node> inCFG)
throws IOException {
"""
Converts an AST to dot representation.
@param n the root of the AST described in the dot formatted string
@param inCFG Control Flow Graph.
@return the dot representation of the AST
"""
StringBuilder builder = new StringBuilder();
new DotFormatter(n, inCFG, builder, false);
return builder.toString();
} | java | static String toDot(Node n, ControlFlowGraph<Node> inCFG)
throws IOException {
StringBuilder builder = new StringBuilder();
new DotFormatter(n, inCFG, builder, false);
return builder.toString();
} | [
"static",
"String",
"toDot",
"(",
"Node",
"n",
",",
"ControlFlowGraph",
"<",
"Node",
">",
"inCFG",
")",
"throws",
"IOException",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"new",
"DotFormatter",
"(",
"n",
",",
"inCFG",
","... | Converts an AST to dot representation.
@param n the root of the AST described in the dot formatted string
@param inCFG Control Flow Graph.
@return the dot representation of the AST | [
"Converts",
"an",
"AST",
"to",
"dot",
"representation",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DotFormatter.java#L93-L98 |
whitesource/agents | wss-agent-hash-calculator/src/main/java/org/whitesource/agent/parser/JavaScriptParser.java | JavaScriptParser.removeHeaderComments | private String removeHeaderComments(String fileContent, SortedSet<Comment> comments) {
"""
Go over each comment and remove from content until reaching the beginning of the actual code.
"""
String headerlessFileContent = fileContent;
for (Comment comment : comments) {
String commentValue = comment.getValue();
if (headerlessFileContent.startsWith(commentValue)) {
headerlessFileContent = headerlessFileContent.replace(commentValue, EMPTY_STRING);
// remove all leading white spaces and new line characters
while (StringUtils.isNotBlank(headerlessFileContent) && Character.isWhitespace(headerlessFileContent.charAt(0))) {
headerlessFileContent = headerlessFileContent.substring(1);
}
} else {
// finished removing all header comments
break;
}
}
return headerlessFileContent;
} | java | private String removeHeaderComments(String fileContent, SortedSet<Comment> comments) {
String headerlessFileContent = fileContent;
for (Comment comment : comments) {
String commentValue = comment.getValue();
if (headerlessFileContent.startsWith(commentValue)) {
headerlessFileContent = headerlessFileContent.replace(commentValue, EMPTY_STRING);
// remove all leading white spaces and new line characters
while (StringUtils.isNotBlank(headerlessFileContent) && Character.isWhitespace(headerlessFileContent.charAt(0))) {
headerlessFileContent = headerlessFileContent.substring(1);
}
} else {
// finished removing all header comments
break;
}
}
return headerlessFileContent;
} | [
"private",
"String",
"removeHeaderComments",
"(",
"String",
"fileContent",
",",
"SortedSet",
"<",
"Comment",
">",
"comments",
")",
"{",
"String",
"headerlessFileContent",
"=",
"fileContent",
";",
"for",
"(",
"Comment",
"comment",
":",
"comments",
")",
"{",
"Stri... | Go over each comment and remove from content until reaching the beginning of the actual code. | [
"Go",
"over",
"each",
"comment",
"and",
"remove",
"from",
"content",
"until",
"reaching",
"the",
"beginning",
"of",
"the",
"actual",
"code",
"."
] | train | https://github.com/whitesource/agents/blob/8a947a3dbad257aff70f23f79fb3a55ca90b765f/wss-agent-hash-calculator/src/main/java/org/whitesource/agent/parser/JavaScriptParser.java#L73-L89 |
nohana/Amalgam | amalgam/src/main/java/com/amalgam/app/ProgressDialogFragment.java | ProgressDialogFragment.newInstance | public static ProgressDialogFragment newInstance(Context context, int title, int message, boolean indeterminate) {
"""
Create a new instance of the {@link com.amalgam.app.ProgressDialogFragment}.
@param context the context.
@param title the title text resource.
@param message the message text resource.
@param indeterminate indeterminate progress or not.
@return the instance of the {@link com.amalgam.app.ProgressDialogFragment}.
"""
return newInstance(context.getString(title), context.getString(message), indeterminate);
} | java | public static ProgressDialogFragment newInstance(Context context, int title, int message, boolean indeterminate) {
return newInstance(context.getString(title), context.getString(message), indeterminate);
} | [
"public",
"static",
"ProgressDialogFragment",
"newInstance",
"(",
"Context",
"context",
",",
"int",
"title",
",",
"int",
"message",
",",
"boolean",
"indeterminate",
")",
"{",
"return",
"newInstance",
"(",
"context",
".",
"getString",
"(",
"title",
")",
",",
"c... | Create a new instance of the {@link com.amalgam.app.ProgressDialogFragment}.
@param context the context.
@param title the title text resource.
@param message the message text resource.
@param indeterminate indeterminate progress or not.
@return the instance of the {@link com.amalgam.app.ProgressDialogFragment}. | [
"Create",
"a",
"new",
"instance",
"of",
"the",
"{",
"@link",
"com",
".",
"amalgam",
".",
"app",
".",
"ProgressDialogFragment",
"}",
"."
] | train | https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/app/ProgressDialogFragment.java#L56-L58 |
EdwardRaff/JSAT | JSAT/src/jsat/regression/BaseUpdateableRegressor.java | BaseUpdateableRegressor.trainEpochs | public static void trainEpochs(RegressionDataSet dataSet, UpdateableRegressor toTrain, int epochs) {
"""
Performs training on an updateable classifier by going over the whole
data set in random order one observation at a time, multiple times.
@param dataSet the data set to train from
@param toTrain the classifier to train
@param epochs the number of passes through the data set
"""
if(epochs < 1)
throw new IllegalArgumentException("epochs must be positive");
toTrain.setUp(dataSet.getCategories(), dataSet.getNumNumericalVars());
IntList randomOrder = new IntList(dataSet.size());
ListUtils.addRange(randomOrder, 0, dataSet.size(), 1);
for (int epoch = 0; epoch < epochs; epoch++)
{
Collections.shuffle(randomOrder);
for (int i : randomOrder)
toTrain.update(dataSet.getDataPoint(i), dataSet.getWeight(i), dataSet.getTargetValue(i));
}
} | java | public static void trainEpochs(RegressionDataSet dataSet, UpdateableRegressor toTrain, int epochs)
{
if(epochs < 1)
throw new IllegalArgumentException("epochs must be positive");
toTrain.setUp(dataSet.getCategories(), dataSet.getNumNumericalVars());
IntList randomOrder = new IntList(dataSet.size());
ListUtils.addRange(randomOrder, 0, dataSet.size(), 1);
for (int epoch = 0; epoch < epochs; epoch++)
{
Collections.shuffle(randomOrder);
for (int i : randomOrder)
toTrain.update(dataSet.getDataPoint(i), dataSet.getWeight(i), dataSet.getTargetValue(i));
}
} | [
"public",
"static",
"void",
"trainEpochs",
"(",
"RegressionDataSet",
"dataSet",
",",
"UpdateableRegressor",
"toTrain",
",",
"int",
"epochs",
")",
"{",
"if",
"(",
"epochs",
"<",
"1",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"epochs must be positive\"",... | Performs training on an updateable classifier by going over the whole
data set in random order one observation at a time, multiple times.
@param dataSet the data set to train from
@param toTrain the classifier to train
@param epochs the number of passes through the data set | [
"Performs",
"training",
"on",
"an",
"updateable",
"classifier",
"by",
"going",
"over",
"the",
"whole",
"data",
"set",
"in",
"random",
"order",
"one",
"observation",
"at",
"a",
"time",
"multiple",
"times",
"."
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/regression/BaseUpdateableRegressor.java#L66-L79 |
mlhartme/sushi | src/main/java/net/oneandone/sushi/util/IntBitSet.java | IntBitSet.addRange | public void addRange(int first, int last) {
"""
Add all elements in the indicated range. Nothing is set for first > last.
@param first first element to add
@param last last element to add
"""
int ele;
for (ele = first; ele <= last; ele++) {
add(ele);
}
} | java | public void addRange(int first, int last) {
int ele;
for (ele = first; ele <= last; ele++) {
add(ele);
}
} | [
"public",
"void",
"addRange",
"(",
"int",
"first",
",",
"int",
"last",
")",
"{",
"int",
"ele",
";",
"for",
"(",
"ele",
"=",
"first",
";",
"ele",
"<=",
"last",
";",
"ele",
"++",
")",
"{",
"add",
"(",
"ele",
")",
";",
"}",
"}"
] | Add all elements in the indicated range. Nothing is set for first > last.
@param first first element to add
@param last last element to add | [
"Add",
"all",
"elements",
"in",
"the",
"indicated",
"range",
".",
"Nothing",
"is",
"set",
"for",
"first",
">",
";",
"last",
"."
] | train | https://github.com/mlhartme/sushi/blob/4af33414b04bd58584d4febe5cc63ef6c7346a75/src/main/java/net/oneandone/sushi/util/IntBitSet.java#L221-L227 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/GitLabApiForm.java | GitLabApiForm.withParam | public <T> GitLabApiForm withParam(String name, List<T> values) {
"""
Fluent method for adding a List type query and form parameters to a get() or post() call.
@param <T> the type contained by the List
@param name the name of the field/attribute to add
@param values a List containing the values of the field/attribute to add
@return this GitLabAPiForm instance
"""
return (withParam(name, values, false));
} | java | public <T> GitLabApiForm withParam(String name, List<T> values) {
return (withParam(name, values, false));
} | [
"public",
"<",
"T",
">",
"GitLabApiForm",
"withParam",
"(",
"String",
"name",
",",
"List",
"<",
"T",
">",
"values",
")",
"{",
"return",
"(",
"withParam",
"(",
"name",
",",
"values",
",",
"false",
")",
")",
";",
"}"
] | Fluent method for adding a List type query and form parameters to a get() or post() call.
@param <T> the type contained by the List
@param name the name of the field/attribute to add
@param values a List containing the values of the field/attribute to add
@return this GitLabAPiForm instance | [
"Fluent",
"method",
"for",
"adding",
"a",
"List",
"type",
"query",
"and",
"form",
"parameters",
"to",
"a",
"get",
"()",
"or",
"post",
"()",
"call",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/GitLabApiForm.java#L106-L108 |
cesarferreira/AndroidQuickUtils | library/src/main/java/quickutils/core/categories/sdcard.java | sdcard.writeToFile | public void writeToFile(File file, String fileContent) {
"""
Writes a file to Disk.
This is an I/O operation and this method executes in the main thread, so it is recommended to
perform this operation using another thread.
@param file The file to write to Disk.
"""
if (!file.exists()) {
try {
FileWriter writer = new FileWriter(file);
writer.write(fileContent);
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
} | java | public void writeToFile(File file, String fileContent) {
if (!file.exists()) {
try {
FileWriter writer = new FileWriter(file);
writer.write(fileContent);
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
} | [
"public",
"void",
"writeToFile",
"(",
"File",
"file",
",",
"String",
"fileContent",
")",
"{",
"if",
"(",
"!",
"file",
".",
"exists",
"(",
")",
")",
"{",
"try",
"{",
"FileWriter",
"writer",
"=",
"new",
"FileWriter",
"(",
"file",
")",
";",
"writer",
".... | Writes a file to Disk.
This is an I/O operation and this method executes in the main thread, so it is recommended to
perform this operation using another thread.
@param file The file to write to Disk. | [
"Writes",
"a",
"file",
"to",
"Disk",
".",
"This",
"is",
"an",
"I",
"/",
"O",
"operation",
"and",
"this",
"method",
"executes",
"in",
"the",
"main",
"thread",
"so",
"it",
"is",
"recommended",
"to",
"perform",
"this",
"operation",
"using",
"another",
"thre... | train | https://github.com/cesarferreira/AndroidQuickUtils/blob/73a91daedbb9f7be7986ea786fbc441c9e5a881c/library/src/main/java/quickutils/core/categories/sdcard.java#L270-L284 |
LearnLib/learnlib | algorithms/active/ttt/src/main/java/de/learnlib/algorithms/ttt/base/AbstractTTTLearner.java | AbstractTTTLearner.link | protected static <I, D> void link(AbstractBaseDTNode<I, D> dtNode, TTTState<I, D> state) {
"""
Establish the connection between a node in the discrimination tree and a state of the hypothesis.
@param dtNode
the node in the discrimination tree
@param state
the state in the hypothesis
"""
assert dtNode.isLeaf();
dtNode.setData(state);
state.dtLeaf = dtNode;
} | java | protected static <I, D> void link(AbstractBaseDTNode<I, D> dtNode, TTTState<I, D> state) {
assert dtNode.isLeaf();
dtNode.setData(state);
state.dtLeaf = dtNode;
} | [
"protected",
"static",
"<",
"I",
",",
"D",
">",
"void",
"link",
"(",
"AbstractBaseDTNode",
"<",
"I",
",",
"D",
">",
"dtNode",
",",
"TTTState",
"<",
"I",
",",
"D",
">",
"state",
")",
"{",
"assert",
"dtNode",
".",
"isLeaf",
"(",
")",
";",
"dtNode",
... | Establish the connection between a node in the discrimination tree and a state of the hypothesis.
@param dtNode
the node in the discrimination tree
@param state
the state in the hypothesis | [
"Establish",
"the",
"connection",
"between",
"a",
"node",
"in",
"the",
"discrimination",
"tree",
"and",
"a",
"state",
"of",
"the",
"hypothesis",
"."
] | train | https://github.com/LearnLib/learnlib/blob/fa38a14adcc0664099f180d671ffa42480318d7b/algorithms/active/ttt/src/main/java/de/learnlib/algorithms/ttt/base/AbstractTTTLearner.java#L135-L140 |
igniterealtime/Smack | smack-im/src/main/java/org/jivesoftware/smack/chat/ChatManager.java | ChatManager.createChat | public Chat createChat(EntityJid userJID, ChatMessageListener listener) {
"""
Creates a new chat and returns it.
@param userJID the user this chat is with.
@param listener the optional listener which will listen for new messages from this chat.
@return the created chat.
"""
return createChat(userJID, null, listener);
} | java | public Chat createChat(EntityJid userJID, ChatMessageListener listener) {
return createChat(userJID, null, listener);
} | [
"public",
"Chat",
"createChat",
"(",
"EntityJid",
"userJID",
",",
"ChatMessageListener",
"listener",
")",
"{",
"return",
"createChat",
"(",
"userJID",
",",
"null",
",",
"listener",
")",
";",
"}"
] | Creates a new chat and returns it.
@param userJID the user this chat is with.
@param listener the optional listener which will listen for new messages from this chat.
@return the created chat. | [
"Creates",
"a",
"new",
"chat",
"and",
"returns",
"it",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-im/src/main/java/org/jivesoftware/smack/chat/ChatManager.java#L235-L237 |
looly/hutool | hutool-extra/src/main/java/cn/hutool/extra/qrcode/QrCodeUtil.java | QrCodeUtil.toImage | public static BufferedImage toImage(BitMatrix matrix, int foreColor, int backColor) {
"""
BitMatrix转BufferedImage
@param matrix BitMatrix
@param foreColor 前景色
@param backColor 背景色
@return BufferedImage
@since 4.1.2
"""
final int width = matrix.getWidth();
final int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? foreColor : backColor);
}
}
return image;
} | java | public static BufferedImage toImage(BitMatrix matrix, int foreColor, int backColor) {
final int width = matrix.getWidth();
final int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? foreColor : backColor);
}
}
return image;
} | [
"public",
"static",
"BufferedImage",
"toImage",
"(",
"BitMatrix",
"matrix",
",",
"int",
"foreColor",
",",
"int",
"backColor",
")",
"{",
"final",
"int",
"width",
"=",
"matrix",
".",
"getWidth",
"(",
")",
";",
"final",
"int",
"height",
"=",
"matrix",
".",
... | BitMatrix转BufferedImage
@param matrix BitMatrix
@param foreColor 前景色
@param backColor 背景色
@return BufferedImage
@since 4.1.2 | [
"BitMatrix转BufferedImage"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/qrcode/QrCodeUtil.java#L341-L351 |
Impetus/Kundera | src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/ReflectUtils.java | ReflectUtils.hasSuperClass | public static boolean hasSuperClass(Class<?> has, Class<?> in) {
"""
Checks for super "has" in class "in".
@param has
the has
@param in
the in
@return true, if exists?
"""
if (in.equals(has))
{
return true;
}
boolean match = false;
// stop if the superclass is Object
if (in.getSuperclass() != null && in.getSuperclass().equals(Object.class))
{
return match;
}
match = in.getSuperclass() != null ? hasSuperClass(has, in.getSuperclass()): false;
return match;
} | java | public static boolean hasSuperClass(Class<?> has, Class<?> in)
{
if (in.equals(has))
{
return true;
}
boolean match = false;
// stop if the superclass is Object
if (in.getSuperclass() != null && in.getSuperclass().equals(Object.class))
{
return match;
}
match = in.getSuperclass() != null ? hasSuperClass(has, in.getSuperclass()): false;
return match;
} | [
"public",
"static",
"boolean",
"hasSuperClass",
"(",
"Class",
"<",
"?",
">",
"has",
",",
"Class",
"<",
"?",
">",
"in",
")",
"{",
"if",
"(",
"in",
".",
"equals",
"(",
"has",
")",
")",
"{",
"return",
"true",
";",
"}",
"boolean",
"match",
"=",
"fals... | Checks for super "has" in class "in".
@param has
the has
@param in
the in
@return true, if exists? | [
"Checks",
"for",
"super",
"has",
"in",
"class",
"in",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/ReflectUtils.java#L108-L122 |
snowflakedb/snowflake-jdbc | src/main/java/net/snowflake/client/core/SessionUtil.java | SessionUtil.federatedFlowStep3 | private static String federatedFlowStep3(LoginInput loginInput, String tokenUrl)
throws SnowflakeSQLException {
"""
Query IDP token url to authenticate and retrieve access token
@param loginInput
@param tokenUrl
@return
@throws SnowflakeSQLException
"""
String oneTimeToken = "";
try
{
URL url = new URL(tokenUrl);
URI tokenUri = url.toURI();
final HttpPost postRequest = new HttpPost(tokenUri);
StringEntity params = new StringEntity("{\"username\":\"" +
loginInput.getUserName() + "\",\"password\":\"" +
loginInput.getPassword() + "\"}");
postRequest.setEntity(params);
HeaderGroup headers = new HeaderGroup();
headers.addHeader(new BasicHeader(HttpHeaders.ACCEPT, "application/json"));
headers.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
postRequest.setHeaders(headers.getAllHeaders());
final String idpResponse = HttpUtil.executeRequestWithoutCookies(postRequest,
loginInput.getLoginTimeout(), 0, null);
logger.debug("user is authenticated against {}.",
loginInput.getAuthenticator());
// session token is in the data field of the returned json response
final JsonNode jsonNode = mapper.readTree(idpResponse);
oneTimeToken = jsonNode.get("cookieToken").asText();
}
catch (IOException | URISyntaxException ex)
{
handleFederatedFlowError(loginInput, ex);
}
return oneTimeToken;
} | java | private static String federatedFlowStep3(LoginInput loginInput, String tokenUrl)
throws SnowflakeSQLException
{
String oneTimeToken = "";
try
{
URL url = new URL(tokenUrl);
URI tokenUri = url.toURI();
final HttpPost postRequest = new HttpPost(tokenUri);
StringEntity params = new StringEntity("{\"username\":\"" +
loginInput.getUserName() + "\",\"password\":\"" +
loginInput.getPassword() + "\"}");
postRequest.setEntity(params);
HeaderGroup headers = new HeaderGroup();
headers.addHeader(new BasicHeader(HttpHeaders.ACCEPT, "application/json"));
headers.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
postRequest.setHeaders(headers.getAllHeaders());
final String idpResponse = HttpUtil.executeRequestWithoutCookies(postRequest,
loginInput.getLoginTimeout(), 0, null);
logger.debug("user is authenticated against {}.",
loginInput.getAuthenticator());
// session token is in the data field of the returned json response
final JsonNode jsonNode = mapper.readTree(idpResponse);
oneTimeToken = jsonNode.get("cookieToken").asText();
}
catch (IOException | URISyntaxException ex)
{
handleFederatedFlowError(loginInput, ex);
}
return oneTimeToken;
} | [
"private",
"static",
"String",
"federatedFlowStep3",
"(",
"LoginInput",
"loginInput",
",",
"String",
"tokenUrl",
")",
"throws",
"SnowflakeSQLException",
"{",
"String",
"oneTimeToken",
"=",
"\"\"",
";",
"try",
"{",
"URL",
"url",
"=",
"new",
"URL",
"(",
"tokenUrl"... | Query IDP token url to authenticate and retrieve access token
@param loginInput
@param tokenUrl
@return
@throws SnowflakeSQLException | [
"Query",
"IDP",
"token",
"url",
"to",
"authenticate",
"and",
"retrieve",
"access",
"token"
] | train | https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtil.java#L1206-L1242 |
eclipse/xtext-core | org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/server/occurrences/DefaultDocumentHighlightService.java | DefaultDocumentHighlightService.isDocumentHighlightAvailableFor | protected boolean isDocumentHighlightAvailableFor(final EObject selectedElement, final XtextResource resource,
final int offset) {
"""
Returns with {@code true} if the AST element selected from the resource
can provide document highlights, otherwise returns with {@code false}.
<p>
Clients may override this method to change the default behavior.
@param selectedElement
the selected element resolved via the offset from the
resource. Can be {@code null}.
@param resource
the resource for the document.
@param offset
the offset of the selection.
@return {@code true} if the document highlight is available for the
selected element, otherwise {@code false}.
"""
if (selectedElement == null || !getSelectedElementFilter().apply(selectedElement)) {
return false;
}
// This code handles the special case where your language has constructs that can refer to
// themselves. For example "function MyFunction begin ... end MyFunction" defines the function "MyFunction" and
// terminates its implementation block with an additional repetition of the word "MyFunction". Normally, when
// you are positioned on a selected element, you only want to highlight that selected element when you are
// positioned directly on top of the name of the selected element. However, when the selected element can refer
// to itself then there are references inside the element that must trigger highlighting. In the example,
// we also want to highlight "MyFunction" when we are positioned on the "end MyFunction".
INode crossReferenceNode = offsetHelper.getCrossReferenceNode(resource, new TextRegion(offset, 0));
if (crossReferenceNode != null) {
EObject crossReferencedElement = offsetHelper.getCrossReferencedElement(crossReferenceNode);
if (crossReferencedElement != null && crossReferencedElement == selectedElement) {
return true;
}
}
final EObject containedElement = offsetHelper.resolveContainedElementAt(resource, offset);
// When the cursor is positioned in the selected element, then we only want to highlight the selected element
// when we are directly on top of the name (the significant text region) of that element.
if (selectedElement == containedElement) {
final ITextRegion region = locationInFileProvider.getSignificantTextRegion(containedElement);
return !isNullOrEmpty(region)
// Region is comparable to a selection in an editor,
// therefore the end position is exclusive.
&& (region.contains(offset) || (region.getOffset() + region.getLength()) == offset);
}
return true;
} | java | protected boolean isDocumentHighlightAvailableFor(final EObject selectedElement, final XtextResource resource,
final int offset) {
if (selectedElement == null || !getSelectedElementFilter().apply(selectedElement)) {
return false;
}
// This code handles the special case where your language has constructs that can refer to
// themselves. For example "function MyFunction begin ... end MyFunction" defines the function "MyFunction" and
// terminates its implementation block with an additional repetition of the word "MyFunction". Normally, when
// you are positioned on a selected element, you only want to highlight that selected element when you are
// positioned directly on top of the name of the selected element. However, when the selected element can refer
// to itself then there are references inside the element that must trigger highlighting. In the example,
// we also want to highlight "MyFunction" when we are positioned on the "end MyFunction".
INode crossReferenceNode = offsetHelper.getCrossReferenceNode(resource, new TextRegion(offset, 0));
if (crossReferenceNode != null) {
EObject crossReferencedElement = offsetHelper.getCrossReferencedElement(crossReferenceNode);
if (crossReferencedElement != null && crossReferencedElement == selectedElement) {
return true;
}
}
final EObject containedElement = offsetHelper.resolveContainedElementAt(resource, offset);
// When the cursor is positioned in the selected element, then we only want to highlight the selected element
// when we are directly on top of the name (the significant text region) of that element.
if (selectedElement == containedElement) {
final ITextRegion region = locationInFileProvider.getSignificantTextRegion(containedElement);
return !isNullOrEmpty(region)
// Region is comparable to a selection in an editor,
// therefore the end position is exclusive.
&& (region.contains(offset) || (region.getOffset() + region.getLength()) == offset);
}
return true;
} | [
"protected",
"boolean",
"isDocumentHighlightAvailableFor",
"(",
"final",
"EObject",
"selectedElement",
",",
"final",
"XtextResource",
"resource",
",",
"final",
"int",
"offset",
")",
"{",
"if",
"(",
"selectedElement",
"==",
"null",
"||",
"!",
"getSelectedElementFilter"... | Returns with {@code true} if the AST element selected from the resource
can provide document highlights, otherwise returns with {@code false}.
<p>
Clients may override this method to change the default behavior.
@param selectedElement
the selected element resolved via the offset from the
resource. Can be {@code null}.
@param resource
the resource for the document.
@param offset
the offset of the selection.
@return {@code true} if the document highlight is available for the
selected element, otherwise {@code false}. | [
"Returns",
"with",
"{",
"@code",
"true",
"}",
"if",
"the",
"AST",
"element",
"selected",
"from",
"the",
"resource",
"can",
"provide",
"document",
"highlights",
"otherwise",
"returns",
"with",
"{",
"@code",
"false",
"}",
"."
] | train | https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/server/occurrences/DefaultDocumentHighlightService.java#L186-L223 |
alkacon/opencms-core | src/org/opencms/db/CmsDriverManager.java | CmsDriverManager.createProject | public CmsProject createProject(
CmsDbContext dbc,
String name,
String description,
String groupname,
String managergroupname,
CmsProject.CmsProjectType projecttype)
throws CmsIllegalArgumentException, CmsException {
"""
Creates a project.<p>
@param dbc the current database context
@param name the name of the project to create
@param description the description of the project
@param groupname the project user group to be set
@param managergroupname the project manager group to be set
@param projecttype the type of the project
@return the created project
@throws CmsIllegalArgumentException if the chosen <code>name</code> is already used
by the online project, or if the name is not valid
@throws CmsException if something goes wrong
"""
if (CmsProject.ONLINE_PROJECT_NAME.equals(name)) {
throw new CmsIllegalArgumentException(
Messages.get().container(
Messages.ERR_CREATE_PROJECT_ONLINE_PROJECT_NAME_1,
CmsProject.ONLINE_PROJECT_NAME));
}
// check the name
CmsProject.checkProjectName(CmsOrganizationalUnit.getSimpleName(name));
// check the ou
readOrganizationalUnit(dbc, CmsOrganizationalUnit.getParentFqn(name));
// read the needed groups from the cms
CmsGroup group = readGroup(dbc, groupname);
CmsGroup managergroup = readGroup(dbc, managergroupname);
return getProjectDriver(dbc).createProject(
dbc,
new CmsUUID(),
dbc.currentUser(),
group,
managergroup,
name,
description,
projecttype.getDefaultFlags(),
projecttype);
} | java | public CmsProject createProject(
CmsDbContext dbc,
String name,
String description,
String groupname,
String managergroupname,
CmsProject.CmsProjectType projecttype)
throws CmsIllegalArgumentException, CmsException {
if (CmsProject.ONLINE_PROJECT_NAME.equals(name)) {
throw new CmsIllegalArgumentException(
Messages.get().container(
Messages.ERR_CREATE_PROJECT_ONLINE_PROJECT_NAME_1,
CmsProject.ONLINE_PROJECT_NAME));
}
// check the name
CmsProject.checkProjectName(CmsOrganizationalUnit.getSimpleName(name));
// check the ou
readOrganizationalUnit(dbc, CmsOrganizationalUnit.getParentFqn(name));
// read the needed groups from the cms
CmsGroup group = readGroup(dbc, groupname);
CmsGroup managergroup = readGroup(dbc, managergroupname);
return getProjectDriver(dbc).createProject(
dbc,
new CmsUUID(),
dbc.currentUser(),
group,
managergroup,
name,
description,
projecttype.getDefaultFlags(),
projecttype);
} | [
"public",
"CmsProject",
"createProject",
"(",
"CmsDbContext",
"dbc",
",",
"String",
"name",
",",
"String",
"description",
",",
"String",
"groupname",
",",
"String",
"managergroupname",
",",
"CmsProject",
".",
"CmsProjectType",
"projecttype",
")",
"throws",
"CmsIlleg... | Creates a project.<p>
@param dbc the current database context
@param name the name of the project to create
@param description the description of the project
@param groupname the project user group to be set
@param managergroupname the project manager group to be set
@param projecttype the type of the project
@return the created project
@throws CmsIllegalArgumentException if the chosen <code>name</code> is already used
by the online project, or if the name is not valid
@throws CmsException if something goes wrong | [
"Creates",
"a",
"project",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L1483-L1516 |
ops4j/org.ops4j.pax.exam2 | core/pax-exam-spi/src/main/java/org/ops4j/pax/exam/spi/war/JarBuilder.java | JarBuilder.buildJar | public URI buildJar() {
"""
Builds a JAR from the given option.
@return file URI referencing the JAR in a temporary directory
"""
if (option.getName() == null) {
option.name(UUID.randomUUID().toString());
}
try {
File explodedJarDir = getExplodedJarDir();
File probeJar = new File(tempDir, option.getName() + ".jar");
ZipBuilder builder = new ZipBuilder(probeJar);
builder.addDirectory(explodedJarDir, "");
builder.close();
URI warUri = probeJar.toURI();
LOG.info("JAR probe = {}", warUri);
return warUri;
}
catch (IOException exc) {
throw new TestContainerException(exc);
}
} | java | public URI buildJar() {
if (option.getName() == null) {
option.name(UUID.randomUUID().toString());
}
try {
File explodedJarDir = getExplodedJarDir();
File probeJar = new File(tempDir, option.getName() + ".jar");
ZipBuilder builder = new ZipBuilder(probeJar);
builder.addDirectory(explodedJarDir, "");
builder.close();
URI warUri = probeJar.toURI();
LOG.info("JAR probe = {}", warUri);
return warUri;
}
catch (IOException exc) {
throw new TestContainerException(exc);
}
} | [
"public",
"URI",
"buildJar",
"(",
")",
"{",
"if",
"(",
"option",
".",
"getName",
"(",
")",
"==",
"null",
")",
"{",
"option",
".",
"name",
"(",
"UUID",
".",
"randomUUID",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"try",
"{",
"File",
"e... | Builds a JAR from the given option.
@return file URI referencing the JAR in a temporary directory | [
"Builds",
"a",
"JAR",
"from",
"the",
"given",
"option",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.exam2/blob/7f83796cbbb857123d8fc7fe817a7637218d5d77/core/pax-exam-spi/src/main/java/org/ops4j/pax/exam/spi/war/JarBuilder.java#L71-L88 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java | ApiOvhEmailexchange.organizationName_service_exchangeService_publicFolder_path_permission_allowedAccountId_PUT | public void organizationName_service_exchangeService_publicFolder_path_permission_allowedAccountId_PUT(String organizationName, String exchangeService, String path, Long allowedAccountId, OvhExchangePublicFolderPermission body) throws IOException {
"""
Alter this object properties
REST: PUT /email/exchange/{organizationName}/service/{exchangeService}/publicFolder/{path}/permission/{allowedAccountId}
@param body [required] New object properties
@param organizationName [required] The internal name of your exchange organization
@param exchangeService [required] The internal name of your exchange service
@param path [required] Path for public folder
@param allowedAccountId [required] Account id
"""
String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/publicFolder/{path}/permission/{allowedAccountId}";
StringBuilder sb = path(qPath, organizationName, exchangeService, path, allowedAccountId);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void organizationName_service_exchangeService_publicFolder_path_permission_allowedAccountId_PUT(String organizationName, String exchangeService, String path, Long allowedAccountId, OvhExchangePublicFolderPermission body) throws IOException {
String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/publicFolder/{path}/permission/{allowedAccountId}";
StringBuilder sb = path(qPath, organizationName, exchangeService, path, allowedAccountId);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"organizationName_service_exchangeService_publicFolder_path_permission_allowedAccountId_PUT",
"(",
"String",
"organizationName",
",",
"String",
"exchangeService",
",",
"String",
"path",
",",
"Long",
"allowedAccountId",
",",
"OvhExchangePublicFolderPermission",
"bo... | Alter this object properties
REST: PUT /email/exchange/{organizationName}/service/{exchangeService}/publicFolder/{path}/permission/{allowedAccountId}
@param body [required] New object properties
@param organizationName [required] The internal name of your exchange organization
@param exchangeService [required] The internal name of your exchange service
@param path [required] Path for public folder
@param allowedAccountId [required] Account id | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L265-L269 |
stephenc/redmine-java-api | src/main/java/org/redmine/ta/RedmineManager.java | RedmineManager.createIssue | public Issue createIssue(String projectKey, Issue issue) throws RedmineException {
"""
Sample usage:
<p/>
<p/>
<pre>
{@code
Issue issueToCreate = new Issue();
issueToCreate.setSubject("This is the summary line 123");
Issue newIssue = mgr.createIssue(PROJECT_KEY, issueToCreate);
}
@param projectKey The project "identifier". This is a string key like "project-ABC", NOT a database numeric ID.
@param issue the Issue object to create on the server.
@return the newly created Issue.
@throws RedmineAuthenticationException invalid or no API access key is used with the server, which
requires authorization. Check the constructor arguments.
@throws NotFoundException the project with the given projectKey is not found
@throws RedmineException
"""
final Project oldProject = issue.getProject();
final Project newProject = new Project();
newProject.setIdentifier(projectKey);
issue.setProject(newProject);
try {
return transport.addObject(issue, new BasicNameValuePair("include",
INCLUDE.attachments.toString()));
} finally {
issue.setProject(oldProject);
}
} | java | public Issue createIssue(String projectKey, Issue issue) throws RedmineException {
final Project oldProject = issue.getProject();
final Project newProject = new Project();
newProject.setIdentifier(projectKey);
issue.setProject(newProject);
try {
return transport.addObject(issue, new BasicNameValuePair("include",
INCLUDE.attachments.toString()));
} finally {
issue.setProject(oldProject);
}
} | [
"public",
"Issue",
"createIssue",
"(",
"String",
"projectKey",
",",
"Issue",
"issue",
")",
"throws",
"RedmineException",
"{",
"final",
"Project",
"oldProject",
"=",
"issue",
".",
"getProject",
"(",
")",
";",
"final",
"Project",
"newProject",
"=",
"new",
"Proje... | Sample usage:
<p/>
<p/>
<pre>
{@code
Issue issueToCreate = new Issue();
issueToCreate.setSubject("This is the summary line 123");
Issue newIssue = mgr.createIssue(PROJECT_KEY, issueToCreate);
}
@param projectKey The project "identifier". This is a string key like "project-ABC", NOT a database numeric ID.
@param issue the Issue object to create on the server.
@return the newly created Issue.
@throws RedmineAuthenticationException invalid or no API access key is used with the server, which
requires authorization. Check the constructor arguments.
@throws NotFoundException the project with the given projectKey is not found
@throws RedmineException | [
"Sample",
"usage",
":",
"<p",
"/",
">",
"<p",
"/",
">",
"<pre",
">",
"{",
"@code",
"Issue",
"issueToCreate",
"=",
"new",
"Issue",
"()",
";",
"issueToCreate",
".",
"setSubject",
"(",
"This",
"is",
"the",
"summary",
"line",
"123",
")",
";",
"Issue",
"n... | train | https://github.com/stephenc/redmine-java-api/blob/7e5270c84aba32d74a506260ec47ff86ab6c9d84/src/main/java/org/redmine/ta/RedmineManager.java#L133-L144 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jaxrs.2.0.common/src/org/apache/cxf/jaxrs/utils/ThreadLocalProxyCopyOnWriteArrayList.java | ThreadLocalProxyCopyOnWriteArrayList.addAll | @Override
public boolean addAll(int index, Collection<? extends E> c) {
"""
Inserts all of the elements in the specified collection into this
list, starting at the specified position. Shifts the element
currently at that position (if any) and any subsequent elements to
the right (increases their indices). The new elements will appear
in this list in the order that they are returned by the
specified collection's iterator.
@param index index at which to insert the first element
from the specified collection
@param c collection containing elements to be added to this list
@return <tt>true</tt> if this list changed as a result of the call
@throws IndexOutOfBoundsException {@inheritDoc}
@throws NullPointerException if the specified collection is null
@see #add(int,Object)
"""
Object[] cs = c.toArray();
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
if (index > len || index < 0)
throw new IndexOutOfBoundsException("Index: " + index +
", Size: " + len);
if (cs.length == 0)
return false;
int numMoved = len - index;
Object[] newElements;
if (numMoved == 0)
newElements = Arrays.copyOf(elements, len + cs.length);
else {
newElements = new Object[len + cs.length];
System.arraycopy(elements, 0, newElements, 0, index);
System.arraycopy(elements, index,
newElements, index + cs.length,
numMoved);
}
System.arraycopy(cs, 0, newElements, index, cs.length);
setArray(newElements);
return true;
} finally {
lock.unlock();
}
} | java | @Override
public boolean addAll(int index, Collection<? extends E> c) {
Object[] cs = c.toArray();
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
if (index > len || index < 0)
throw new IndexOutOfBoundsException("Index: " + index +
", Size: " + len);
if (cs.length == 0)
return false;
int numMoved = len - index;
Object[] newElements;
if (numMoved == 0)
newElements = Arrays.copyOf(elements, len + cs.length);
else {
newElements = new Object[len + cs.length];
System.arraycopy(elements, 0, newElements, 0, index);
System.arraycopy(elements, index,
newElements, index + cs.length,
numMoved);
}
System.arraycopy(cs, 0, newElements, index, cs.length);
setArray(newElements);
return true;
} finally {
lock.unlock();
}
} | [
"@",
"Override",
"public",
"boolean",
"addAll",
"(",
"int",
"index",
",",
"Collection",
"<",
"?",
"extends",
"E",
">",
"c",
")",
"{",
"Object",
"[",
"]",
"cs",
"=",
"c",
".",
"toArray",
"(",
")",
";",
"final",
"ReentrantLock",
"lock",
"=",
"this",
... | Inserts all of the elements in the specified collection into this
list, starting at the specified position. Shifts the element
currently at that position (if any) and any subsequent elements to
the right (increases their indices). The new elements will appear
in this list in the order that they are returned by the
specified collection's iterator.
@param index index at which to insert the first element
from the specified collection
@param c collection containing elements to be added to this list
@return <tt>true</tt> if this list changed as a result of the call
@throws IndexOutOfBoundsException {@inheritDoc}
@throws NullPointerException if the specified collection is null
@see #add(int,Object) | [
"Inserts",
"all",
"of",
"the",
"elements",
"in",
"the",
"specified",
"collection",
"into",
"this",
"list",
"starting",
"at",
"the",
"specified",
"position",
".",
"Shifts",
"the",
"element",
"currently",
"at",
"that",
"position",
"(",
"if",
"any",
")",
"and",... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxrs.2.0.common/src/org/apache/cxf/jaxrs/utils/ThreadLocalProxyCopyOnWriteArrayList.java#L756-L786 |
alkacon/opencms-core | src/org/opencms/ui/dialogs/permissions/CmsPermissionView.java | CmsPermissionView.isAllowed | protected Boolean isAllowed(CmsPermissionSet p, int value) {
"""
Checks if a certain permission of a permission set is allowed.<p>
@param p the current CmsPermissionSet
@param value the int value of the permission to check
@return true if the permission is allowed, otherwise false
"""
if ((p.getAllowedPermissions() & value) > 0) {
return Boolean.TRUE;
}
return Boolean.FALSE;
} | java | protected Boolean isAllowed(CmsPermissionSet p, int value) {
if ((p.getAllowedPermissions() & value) > 0) {
return Boolean.TRUE;
}
return Boolean.FALSE;
} | [
"protected",
"Boolean",
"isAllowed",
"(",
"CmsPermissionSet",
"p",
",",
"int",
"value",
")",
"{",
"if",
"(",
"(",
"p",
".",
"getAllowedPermissions",
"(",
")",
"&",
"value",
")",
">",
"0",
")",
"{",
"return",
"Boolean",
".",
"TRUE",
";",
"}",
"return",
... | Checks if a certain permission of a permission set is allowed.<p>
@param p the current CmsPermissionSet
@param value the int value of the permission to check
@return true if the permission is allowed, otherwise false | [
"Checks",
"if",
"a",
"certain",
"permission",
"of",
"a",
"permission",
"set",
"is",
"allowed",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/dialogs/permissions/CmsPermissionView.java#L414-L420 |
m-m-m/util | xml/src/main/java/net/sf/mmm/util/xml/base/DomUtilImpl.java | DomUtilImpl.isEqual | protected boolean isEqual(CharIterator charIterator1, CharIterator charIterator2, XmlCompareMode mode) {
"""
This method determines if the given {@link CharSequence}s are equal.
@see #isEqual(Node, Node, XmlCompareMode)
@param charIterator1 is the first {@link CharIterator}.
@param charIterator2 is the second {@link CharIterator}.
@param mode is the mode of comparison.
@return {@code true} if equal, {@code false} otherwise.
"""
CharIterator c1, c2;
if (mode.isNormalizeSpaces()) {
c1 = new SpaceNormalizingCharIterator(charIterator1);
c2 = new SpaceNormalizingCharIterator(charIterator2);
} else {
c1 = charIterator1;
c2 = charIterator2;
}
return compare(c1, c2);
} | java | protected boolean isEqual(CharIterator charIterator1, CharIterator charIterator2, XmlCompareMode mode) {
CharIterator c1, c2;
if (mode.isNormalizeSpaces()) {
c1 = new SpaceNormalizingCharIterator(charIterator1);
c2 = new SpaceNormalizingCharIterator(charIterator2);
} else {
c1 = charIterator1;
c2 = charIterator2;
}
return compare(c1, c2);
} | [
"protected",
"boolean",
"isEqual",
"(",
"CharIterator",
"charIterator1",
",",
"CharIterator",
"charIterator2",
",",
"XmlCompareMode",
"mode",
")",
"{",
"CharIterator",
"c1",
",",
"c2",
";",
"if",
"(",
"mode",
".",
"isNormalizeSpaces",
"(",
")",
")",
"{",
"c1",... | This method determines if the given {@link CharSequence}s are equal.
@see #isEqual(Node, Node, XmlCompareMode)
@param charIterator1 is the first {@link CharIterator}.
@param charIterator2 is the second {@link CharIterator}.
@param mode is the mode of comparison.
@return {@code true} if equal, {@code false} otherwise. | [
"This",
"method",
"determines",
"if",
"the",
"given",
"{",
"@link",
"CharSequence",
"}",
"s",
"are",
"equal",
"."
] | train | https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/xml/src/main/java/net/sf/mmm/util/xml/base/DomUtilImpl.java#L462-L473 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.token.ltpa/src/com/ibm/ws/security/token/ltpa/internal/LTPAToken2.java | LTPAToken2.toUTF8String | private static final String toUTF8String(byte[] b) {
"""
Convert the byte representation to the UTF-8 String form.
@param b The byte representation
@return The UTF-8 String form
"""
String ns = null;
try {
ns = new String(b, "UTF8");
} catch (UnsupportedEncodingException e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Error converting to string; " + e);
}
}
return ns;
} | java | private static final String toUTF8String(byte[] b) {
String ns = null;
try {
ns = new String(b, "UTF8");
} catch (UnsupportedEncodingException e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Error converting to string; " + e);
}
}
return ns;
} | [
"private",
"static",
"final",
"String",
"toUTF8String",
"(",
"byte",
"[",
"]",
"b",
")",
"{",
"String",
"ns",
"=",
"null",
";",
"try",
"{",
"ns",
"=",
"new",
"String",
"(",
"b",
",",
"\"UTF8\"",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingExceptio... | Convert the byte representation to the UTF-8 String form.
@param b The byte representation
@return The UTF-8 String form | [
"Convert",
"the",
"byte",
"representation",
"to",
"the",
"UTF",
"-",
"8",
"String",
"form",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.token.ltpa/src/com/ibm/ws/security/token/ltpa/internal/LTPAToken2.java#L431-L441 |
alkacon/opencms-core | src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java | CmsContainerpageHandler.openModelResourceSelect | public void openModelResourceSelect(
final CmsContainerPageElementPanel element,
List<CmsModelResourceInfo> modelResources) {
"""
Opens the model select dialog for the given new element.<p>
@param element the element widget
@param modelResources the available resource models
"""
I_CmsModelSelectHandler handler = new I_CmsModelSelectHandler() {
public void onModelSelect(CmsUUID modelStructureId) {
m_controller.createAndEditNewElement(element, modelStructureId);
}
};
String title = org.opencms.gwt.client.Messages.get().key(
org.opencms.gwt.client.Messages.GUI_MODEL_SELECT_TITLE_0);
String message = org.opencms.gwt.client.Messages.get().key(
org.opencms.gwt.client.Messages.GUI_MODEL_SELECT_MESSAGE_0);
CmsModelSelectDialog dialog = new CmsModelSelectDialog(handler, modelResources, title, message);
dialog.center();
} | java | public void openModelResourceSelect(
final CmsContainerPageElementPanel element,
List<CmsModelResourceInfo> modelResources) {
I_CmsModelSelectHandler handler = new I_CmsModelSelectHandler() {
public void onModelSelect(CmsUUID modelStructureId) {
m_controller.createAndEditNewElement(element, modelStructureId);
}
};
String title = org.opencms.gwt.client.Messages.get().key(
org.opencms.gwt.client.Messages.GUI_MODEL_SELECT_TITLE_0);
String message = org.opencms.gwt.client.Messages.get().key(
org.opencms.gwt.client.Messages.GUI_MODEL_SELECT_MESSAGE_0);
CmsModelSelectDialog dialog = new CmsModelSelectDialog(handler, modelResources, title, message);
dialog.center();
} | [
"public",
"void",
"openModelResourceSelect",
"(",
"final",
"CmsContainerPageElementPanel",
"element",
",",
"List",
"<",
"CmsModelResourceInfo",
">",
"modelResources",
")",
"{",
"I_CmsModelSelectHandler",
"handler",
"=",
"new",
"I_CmsModelSelectHandler",
"(",
")",
"{",
"... | Opens the model select dialog for the given new element.<p>
@param element the element widget
@param modelResources the available resource models | [
"Opens",
"the",
"model",
"select",
"dialog",
"for",
"the",
"given",
"new",
"element",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java#L833-L850 |
webmetrics/browsermob-proxy | src/main/java/org/browsermob/proxy/jetty/http/HttpFields.java | HttpFields.formatDate | public static void formatDate(StringBuffer buf,Calendar calendar, boolean cookie) {
"""
Format HTTP date
"EEE, dd MMM yyyy HH:mm:ss 'GMT'" or
"EEE, dd-MMM-yy HH:mm:ss 'GMT'"for cookies
"""
// "EEE, dd MMM yyyy HH:mm:ss 'GMT'"
// "EEE, dd-MMM-yy HH:mm:ss 'GMT'", cookie
int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
int day_of_month = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
int century = year/100;
year=year%100;
long tm = (calendar instanceof HttpCal)?(((HttpCal)calendar).getTimeInMillis()):calendar.getTime().getTime();
int epoch=(int)((tm/1000) % (60*60*24));
int seconds=epoch%60;
epoch=epoch/60;
int minutes=epoch%60;
int hours=epoch/60;
buf.append(DAYS[day_of_week]);
buf.append(',');
buf.append(' ');
StringUtil.append2digits(buf,day_of_month);
if (cookie)
{
buf.append('-');
buf.append(MONTHS[month]);
buf.append('-');
StringUtil.append2digits(buf,year);
}
else
{
buf.append(' ');
buf.append(MONTHS[month]);
buf.append(' ');
StringUtil.append2digits(buf,century);
StringUtil.append2digits(buf,year);
}
buf.append(' ');
StringUtil.append2digits(buf,hours);
buf.append(':');
StringUtil.append2digits(buf,minutes);
buf.append(':');
StringUtil.append2digits(buf,seconds);
buf.append(" GMT");
} | java | public static void formatDate(StringBuffer buf,Calendar calendar, boolean cookie)
{
// "EEE, dd MMM yyyy HH:mm:ss 'GMT'"
// "EEE, dd-MMM-yy HH:mm:ss 'GMT'", cookie
int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
int day_of_month = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
int century = year/100;
year=year%100;
long tm = (calendar instanceof HttpCal)?(((HttpCal)calendar).getTimeInMillis()):calendar.getTime().getTime();
int epoch=(int)((tm/1000) % (60*60*24));
int seconds=epoch%60;
epoch=epoch/60;
int minutes=epoch%60;
int hours=epoch/60;
buf.append(DAYS[day_of_week]);
buf.append(',');
buf.append(' ');
StringUtil.append2digits(buf,day_of_month);
if (cookie)
{
buf.append('-');
buf.append(MONTHS[month]);
buf.append('-');
StringUtil.append2digits(buf,year);
}
else
{
buf.append(' ');
buf.append(MONTHS[month]);
buf.append(' ');
StringUtil.append2digits(buf,century);
StringUtil.append2digits(buf,year);
}
buf.append(' ');
StringUtil.append2digits(buf,hours);
buf.append(':');
StringUtil.append2digits(buf,minutes);
buf.append(':');
StringUtil.append2digits(buf,seconds);
buf.append(" GMT");
} | [
"public",
"static",
"void",
"formatDate",
"(",
"StringBuffer",
"buf",
",",
"Calendar",
"calendar",
",",
"boolean",
"cookie",
")",
"{",
"// \"EEE, dd MMM yyyy HH:mm:ss 'GMT'\"",
"// \"EEE, dd-MMM-yy HH:mm:ss 'GMT'\", cookie",
"int",
"day_of_week",
"=",
"calendar",
".",
... | Format HTTP date
"EEE, dd MMM yyyy HH:mm:ss 'GMT'" or
"EEE, dd-MMM-yy HH:mm:ss 'GMT'"for cookies | [
"Format",
"HTTP",
"date",
"EEE",
"dd",
"MMM",
"yyyy",
"HH",
":",
"mm",
":",
"ss",
"GMT",
"or",
"EEE",
"dd",
"-",
"MMM",
"-",
"yy",
"HH",
":",
"mm",
":",
"ss",
"GMT",
"for",
"cookies"
] | train | https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/http/HttpFields.java#L356-L402 |
aequologica/geppaequo | geppaequo-core/src/main/java/net/aequologica/neo/geppaequo/auth/MethodUtils.java | MethodUtils.invokeMethod | public static Object invokeMethod(
Object object,
String methodName,
Object[] args)
throws
NoSuchMethodException,
IllegalAccessException,
InvocationTargetException {
"""
<p>Invoke a named method whose parameter type matches the object type.</p>
<p>The behaviour of this method is less deterministic
than {@link #invokeExactMethod(Object object,String methodName,Object [] args)}.
It loops through all methods with names that match
and then executes the first it finds with compatible parameters.</p>
<p>This method supports calls to methods taking primitive parameters
via passing in wrapping classes. So, for example, a <code>Boolean</code> class
would match a <code>boolean</code> primitive.</p>
<p> This is a convenient wrapper for
{@link #invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}.
</p>
@param object invoke method on this object
@param methodName get method with this name
@param args use these arguments - treat null as empty array (passing null will
result in calling the parameterless method with name {@code methodName}).
@return The value returned by the invoked method
@throws NoSuchMethodException if there is no such accessible method
@throws InvocationTargetException wraps an exception thrown by the
method invoked
@throws IllegalAccessException if the requested method is not accessible
via reflection
"""
if (args == null) {
args = EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
Class<?>[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
return invokeMethod(object, methodName, args, parameterTypes);
} | java | public static Object invokeMethod(
Object object,
String methodName,
Object[] args)
throws
NoSuchMethodException,
IllegalAccessException,
InvocationTargetException {
if (args == null) {
args = EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
Class<?>[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
return invokeMethod(object, methodName, args, parameterTypes);
} | [
"public",
"static",
"Object",
"invokeMethod",
"(",
"Object",
"object",
",",
"String",
"methodName",
",",
"Object",
"[",
"]",
"args",
")",
"throws",
"NoSuchMethodException",
",",
"IllegalAccessException",
",",
"InvocationTargetException",
"{",
"if",
"(",
"args",
"=... | <p>Invoke a named method whose parameter type matches the object type.</p>
<p>The behaviour of this method is less deterministic
than {@link #invokeExactMethod(Object object,String methodName,Object [] args)}.
It loops through all methods with names that match
and then executes the first it finds with compatible parameters.</p>
<p>This method supports calls to methods taking primitive parameters
via passing in wrapping classes. So, for example, a <code>Boolean</code> class
would match a <code>boolean</code> primitive.</p>
<p> This is a convenient wrapper for
{@link #invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}.
</p>
@param object invoke method on this object
@param methodName get method with this name
@param args use these arguments - treat null as empty array (passing null will
result in calling the parameterless method with name {@code methodName}).
@return The value returned by the invoked method
@throws NoSuchMethodException if there is no such accessible method
@throws InvocationTargetException wraps an exception thrown by the
method invoked
@throws IllegalAccessException if the requested method is not accessible
via reflection | [
"<p",
">",
"Invoke",
"a",
"named",
"method",
"whose",
"parameter",
"type",
"matches",
"the",
"object",
"type",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aequologica/geppaequo/blob/b72e5f6356535fd045a931f8c544d4a8ea6e35a2/geppaequo-core/src/main/java/net/aequologica/neo/geppaequo/auth/MethodUtils.java#L210-L228 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/blas/impl/BaseLevel1.java | BaseLevel1.rotg | @Override
public void rotg(INDArray a, INDArray b, INDArray c, INDArray s) {
"""
computes parameters for a Givens rotation.
@param a
@param b
@param c
@param s
"""
throw new UnsupportedOperationException();
} | java | @Override
public void rotg(INDArray a, INDArray b, INDArray c, INDArray s) {
throw new UnsupportedOperationException();
} | [
"@",
"Override",
"public",
"void",
"rotg",
"(",
"INDArray",
"a",
",",
"INDArray",
"b",
",",
"INDArray",
"c",
",",
"INDArray",
"s",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
")",
";",
"}"
] | computes parameters for a Givens rotation.
@param a
@param b
@param c
@param s | [
"computes",
"parameters",
"for",
"a",
"Givens",
"rotation",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/blas/impl/BaseLevel1.java#L367-L370 |
line/armeria | core/src/main/java/com/linecorp/armeria/server/docs/TypeSignature.java | TypeSignature.ofUnresolved | public static TypeSignature ofUnresolved(String unresolvedTypeName) {
"""
Creates a new unresolved type signature with the specified type name.
"""
requireNonNull(unresolvedTypeName, "unresolvedTypeName");
return new TypeSignature('?' + unresolvedTypeName, ImmutableList.of());
} | java | public static TypeSignature ofUnresolved(String unresolvedTypeName) {
requireNonNull(unresolvedTypeName, "unresolvedTypeName");
return new TypeSignature('?' + unresolvedTypeName, ImmutableList.of());
} | [
"public",
"static",
"TypeSignature",
"ofUnresolved",
"(",
"String",
"unresolvedTypeName",
")",
"{",
"requireNonNull",
"(",
"unresolvedTypeName",
",",
"\"unresolvedTypeName\"",
")",
";",
"return",
"new",
"TypeSignature",
"(",
"'",
"'",
"+",
"unresolvedTypeName",
",",
... | Creates a new unresolved type signature with the specified type name. | [
"Creates",
"a",
"new",
"unresolved",
"type",
"signature",
"with",
"the",
"specified",
"type",
"name",
"."
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/docs/TypeSignature.java#L204-L207 |
CycloneDX/cyclonedx-core-java | src/main/java/org/cyclonedx/BomParser.java | BomParser.isValid | public boolean isValid(File file, CycloneDxSchema.Version schemaVersion) {
"""
Verifies a CycloneDX BoM conforms to the specification through XML validation.
@param file the CycloneDX BoM file to validate
@param schemaVersion the schema version to validate against
@return true is the file is a valid BoM, false if not
@since 2.0.0
"""
return validate(file, schemaVersion).isEmpty();
} | java | public boolean isValid(File file, CycloneDxSchema.Version schemaVersion) {
return validate(file, schemaVersion).isEmpty();
} | [
"public",
"boolean",
"isValid",
"(",
"File",
"file",
",",
"CycloneDxSchema",
".",
"Version",
"schemaVersion",
")",
"{",
"return",
"validate",
"(",
"file",
",",
"schemaVersion",
")",
".",
"isEmpty",
"(",
")",
";",
"}"
] | Verifies a CycloneDX BoM conforms to the specification through XML validation.
@param file the CycloneDX BoM file to validate
@param schemaVersion the schema version to validate against
@return true is the file is a valid BoM, false if not
@since 2.0.0 | [
"Verifies",
"a",
"CycloneDX",
"BoM",
"conforms",
"to",
"the",
"specification",
"through",
"XML",
"validation",
"."
] | train | https://github.com/CycloneDX/cyclonedx-core-java/blob/45f8f55a7f308f41280b834f179b48ea852b8c20/src/main/java/org/cyclonedx/BomParser.java#L159-L161 |
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.executeSiteDetectorSlot | public DiagnosticDetectorResponseInner executeSiteDetectorSlot(String resourceGroupName, String siteName, String detectorName, String diagnosticCategory, String slot, DateTime startTime, DateTime endTime, String timeGrain) {
"""
Execute Detector.
Execute Detector.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param siteName Site Name
@param detectorName Detector Resource Name
@param diagnosticCategory Category Name
@param slot Slot Name
@param startTime Start Time
@param endTime End Time
@param timeGrain Time Grain
@throws IllegalArgumentException thrown if parameters fail the validation
@throws DefaultErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DiagnosticDetectorResponseInner object if successful.
"""
return executeSiteDetectorSlotWithServiceResponseAsync(resourceGroupName, siteName, detectorName, diagnosticCategory, slot, startTime, endTime, timeGrain).toBlocking().single().body();
} | java | public DiagnosticDetectorResponseInner executeSiteDetectorSlot(String resourceGroupName, String siteName, String detectorName, String diagnosticCategory, String slot, DateTime startTime, DateTime endTime, String timeGrain) {
return executeSiteDetectorSlotWithServiceResponseAsync(resourceGroupName, siteName, detectorName, diagnosticCategory, slot, startTime, endTime, timeGrain).toBlocking().single().body();
} | [
"public",
"DiagnosticDetectorResponseInner",
"executeSiteDetectorSlot",
"(",
"String",
"resourceGroupName",
",",
"String",
"siteName",
",",
"String",
"detectorName",
",",
"String",
"diagnosticCategory",
",",
"String",
"slot",
",",
"DateTime",
"startTime",
",",
"DateTime",... | Execute Detector.
Execute Detector.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param siteName Site Name
@param detectorName Detector Resource Name
@param diagnosticCategory Category Name
@param slot Slot Name
@param startTime Start Time
@param endTime End Time
@param timeGrain Time Grain
@throws IllegalArgumentException thrown if parameters fail the validation
@throws DefaultErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DiagnosticDetectorResponseInner object if successful. | [
"Execute",
"Detector",
".",
"Execute",
"Detector",
"."
] | 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#L2482-L2484 |
glyptodon/guacamole-client | extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/user/ModeledUser.java | ModeledUser.asCalendar | private Calendar asCalendar(Calendar base, Time time) {
"""
Converts a SQL Time to a Calendar, independently of time zone, using the
given Calendar as a base. The time components will be copied to the
given Calendar verbatim, leaving the date and time zone components of
the given Calendar otherwise intact.
@param base
The Calendar object to use as a base for the conversion.
@param time
The SQL Time object containing the time components to be applied to
the given Calendar.
@return
The given Calendar, now modified to represent the given time.
"""
// Get calendar from given SQL time
Calendar timeCalendar = Calendar.getInstance();
timeCalendar.setTime(time);
// Apply given time to base calendar
base.set(Calendar.HOUR_OF_DAY, timeCalendar.get(Calendar.HOUR_OF_DAY));
base.set(Calendar.MINUTE, timeCalendar.get(Calendar.MINUTE));
base.set(Calendar.SECOND, timeCalendar.get(Calendar.SECOND));
base.set(Calendar.MILLISECOND, timeCalendar.get(Calendar.MILLISECOND));
return base;
} | java | private Calendar asCalendar(Calendar base, Time time) {
// Get calendar from given SQL time
Calendar timeCalendar = Calendar.getInstance();
timeCalendar.setTime(time);
// Apply given time to base calendar
base.set(Calendar.HOUR_OF_DAY, timeCalendar.get(Calendar.HOUR_OF_DAY));
base.set(Calendar.MINUTE, timeCalendar.get(Calendar.MINUTE));
base.set(Calendar.SECOND, timeCalendar.get(Calendar.SECOND));
base.set(Calendar.MILLISECOND, timeCalendar.get(Calendar.MILLISECOND));
return base;
} | [
"private",
"Calendar",
"asCalendar",
"(",
"Calendar",
"base",
",",
"Time",
"time",
")",
"{",
"// Get calendar from given SQL time",
"Calendar",
"timeCalendar",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"timeCalendar",
".",
"setTime",
"(",
"time",
")",
... | Converts a SQL Time to a Calendar, independently of time zone, using the
given Calendar as a base. The time components will be copied to the
given Calendar verbatim, leaving the date and time zone components of
the given Calendar otherwise intact.
@param base
The Calendar object to use as a base for the conversion.
@param time
The SQL Time object containing the time components to be applied to
the given Calendar.
@return
The given Calendar, now modified to represent the given time. | [
"Converts",
"a",
"SQL",
"Time",
"to",
"a",
"Calendar",
"independently",
"of",
"time",
"zone",
"using",
"the",
"given",
"Calendar",
"as",
"a",
"base",
".",
"The",
"time",
"components",
"will",
"be",
"copied",
"to",
"the",
"given",
"Calendar",
"verbatim",
"l... | train | https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/user/ModeledUser.java#L554-L568 |
paylogic/java-fogbugz | src/main/java/org/paylogic/fogbugz/FogbugzManager.java | FogbugzManager.getFogbugzDocument | private Document getFogbugzDocument(Map<String, String> parameters) throws IOException, ParserConfigurationException, SAXException {
"""
Fetches the XML from the Fogbugz API and returns a Document object
with the response XML in it, so we can use that.
"""
URL uri = new URL(this.mapToFogbugzUrl(parameters));
HttpURLConnection con = (HttpURLConnection) uri.openConnection();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
return dBuilder.parse(con.getInputStream());
} | java | private Document getFogbugzDocument(Map<String, String> parameters) throws IOException, ParserConfigurationException, SAXException {
URL uri = new URL(this.mapToFogbugzUrl(parameters));
HttpURLConnection con = (HttpURLConnection) uri.openConnection();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
return dBuilder.parse(con.getInputStream());
} | [
"private",
"Document",
"getFogbugzDocument",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
")",
"throws",
"IOException",
",",
"ParserConfigurationException",
",",
"SAXException",
"{",
"URL",
"uri",
"=",
"new",
"URL",
"(",
"this",
".",
"mapToFogbug... | Fetches the XML from the Fogbugz API and returns a Document object
with the response XML in it, so we can use that. | [
"Fetches",
"the",
"XML",
"from",
"the",
"Fogbugz",
"API",
"and",
"returns",
"a",
"Document",
"object",
"with",
"the",
"response",
"XML",
"in",
"it",
"so",
"we",
"can",
"use",
"that",
"."
] | train | https://github.com/paylogic/java-fogbugz/blob/75651d82b2476e9ba2a0805311e18ee36882c2df/src/main/java/org/paylogic/fogbugz/FogbugzManager.java#L108-L114 |
zaproxy/zaproxy | src/org/zaproxy/zap/view/StandardFieldsDialog.java | StandardFieldsDialog.addNodeSelectField | public void addNodeSelectField(final String fieldLabel, final SiteNode value,
final boolean editable, final boolean allowRoot) {
"""
/*
Add a 'node select' field which provides a button for showing a Node Select Dialog and a
non editable field for showing the node selected
"""
validateNotTabbed();
final ZapTextField text = new ZapTextField();
text.setEditable(editable);
if (value != null) {
text.setText(getNodeText(value));
}
JButton selectButton = new JButton(Constant.messages.getString("all.button.select"));
selectButton.setIcon(new ImageIcon(View.class.getResource("/resource/icon/16/094.png"))); // Globe icon
selectButton.addActionListener(new java.awt.event.ActionListener() {
// Keep a local copy so that we can always select the last node chosen
SiteNode node = value;
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
NodeSelectDialog nsd = new NodeSelectDialog(StandardFieldsDialog.this);
nsd.setAllowRoot(allowRoot);
SiteNode node = nsd.showDialog(this.node);
if (node != null) {
text.setText(getNodeText(node));
this.node = node;
siteNodeSelected(fieldLabel, node);
}
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.add(text, LayoutHelper.getGBC(0, 0, 1, 1.0D, 0.0D, GridBagConstraints.BOTH, new Insets(4,4,4,4)));
panel.add(selectButton, LayoutHelper.getGBC(1, 0, 1, 0.0D, 0.0D, GridBagConstraints.BOTH, new Insets(4,4,4,4)));
this.addField(fieldLabel, text, panel, 0.0D);
} | java | public void addNodeSelectField(final String fieldLabel, final SiteNode value,
final boolean editable, final boolean allowRoot) {
validateNotTabbed();
final ZapTextField text = new ZapTextField();
text.setEditable(editable);
if (value != null) {
text.setText(getNodeText(value));
}
JButton selectButton = new JButton(Constant.messages.getString("all.button.select"));
selectButton.setIcon(new ImageIcon(View.class.getResource("/resource/icon/16/094.png"))); // Globe icon
selectButton.addActionListener(new java.awt.event.ActionListener() {
// Keep a local copy so that we can always select the last node chosen
SiteNode node = value;
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
NodeSelectDialog nsd = new NodeSelectDialog(StandardFieldsDialog.this);
nsd.setAllowRoot(allowRoot);
SiteNode node = nsd.showDialog(this.node);
if (node != null) {
text.setText(getNodeText(node));
this.node = node;
siteNodeSelected(fieldLabel, node);
}
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.add(text, LayoutHelper.getGBC(0, 0, 1, 1.0D, 0.0D, GridBagConstraints.BOTH, new Insets(4,4,4,4)));
panel.add(selectButton, LayoutHelper.getGBC(1, 0, 1, 0.0D, 0.0D, GridBagConstraints.BOTH, new Insets(4,4,4,4)));
this.addField(fieldLabel, text, panel, 0.0D);
} | [
"public",
"void",
"addNodeSelectField",
"(",
"final",
"String",
"fieldLabel",
",",
"final",
"SiteNode",
"value",
",",
"final",
"boolean",
"editable",
",",
"final",
"boolean",
"allowRoot",
")",
"{",
"validateNotTabbed",
"(",
")",
";",
"final",
"ZapTextField",
"te... | /*
Add a 'node select' field which provides a button for showing a Node Select Dialog and a
non editable field for showing the node selected | [
"/",
"*",
"Add",
"a",
"node",
"select",
"field",
"which",
"provides",
"a",
"button",
"for",
"showing",
"a",
"Node",
"Select",
"Dialog",
"and",
"a",
"non",
"editable",
"field",
"for",
"showing",
"the",
"node",
"selected"
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/view/StandardFieldsDialog.java#L1101-L1132 |
liferay/com-liferay-commerce | commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommerceTierPriceEntryPersistenceImpl.java | CommerceTierPriceEntryPersistenceImpl.fetchByC_ERC | @Override
public CommerceTierPriceEntry fetchByC_ERC(long companyId,
String externalReferenceCode) {
"""
Returns the commerce tier price entry where companyId = ? and externalReferenceCode = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
@param companyId the company ID
@param externalReferenceCode the external reference code
@return the matching commerce tier price entry, or <code>null</code> if a matching commerce tier price entry could not be found
"""
return fetchByC_ERC(companyId, externalReferenceCode, true);
} | java | @Override
public CommerceTierPriceEntry fetchByC_ERC(long companyId,
String externalReferenceCode) {
return fetchByC_ERC(companyId, externalReferenceCode, true);
} | [
"@",
"Override",
"public",
"CommerceTierPriceEntry",
"fetchByC_ERC",
"(",
"long",
"companyId",
",",
"String",
"externalReferenceCode",
")",
"{",
"return",
"fetchByC_ERC",
"(",
"companyId",
",",
"externalReferenceCode",
",",
"true",
")",
";",
"}"
] | Returns the commerce tier price entry where companyId = ? and externalReferenceCode = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
@param companyId the company ID
@param externalReferenceCode the external reference code
@return the matching commerce tier price entry, or <code>null</code> if a matching commerce tier price entry could not be found | [
"Returns",
"the",
"commerce",
"tier",
"price",
"entry",
"where",
"companyId",
"=",
"?",
";",
"and",
"externalReferenceCode",
"=",
"?",
";",
"or",
"returns",
"<code",
">",
"null<",
"/",
"code",
">",
"if",
"it",
"could",
"not",
"be",
"found",
".",
"U... | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommerceTierPriceEntryPersistenceImpl.java#L3867-L3871 |
google/auto | value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java | AutoAnnotationProcessor.compatibleTypes | private boolean compatibleTypes(TypeMirror parameterType, TypeMirror memberType) {
"""
Returns true if {@code parameterType} can be used to provide the value of an annotation member
of type {@code memberType}. They must either be the same type, or the member type must be an
array and the parameter type must be a collection of a compatible type.
"""
if (typeUtils.isAssignable(parameterType, memberType)) {
// parameterType assignable to memberType, which in the restricted world of annotations
// means they are the same type, or maybe memberType is an annotation type and parameterType
// is a subtype of that annotation interface (why would you do that?).
return true;
}
// They're not the same, but we could still consider them compatible if for example
// parameterType is List<Integer> and memberType is int[]. We accept any type that is assignable
// to Collection<Integer> (in this example).
if (memberType.getKind() != TypeKind.ARRAY) {
return false;
}
TypeMirror arrayElementType = ((ArrayType) memberType).getComponentType();
TypeMirror wrappedArrayElementType =
arrayElementType.getKind().isPrimitive()
? typeUtils.boxedClass((PrimitiveType) arrayElementType).asType()
: arrayElementType;
TypeElement javaUtilCollection =
elementUtils.getTypeElement(Collection.class.getCanonicalName());
DeclaredType collectionOfElement =
typeUtils.getDeclaredType(javaUtilCollection, wrappedArrayElementType);
return typeUtils.isAssignable(parameterType, collectionOfElement);
} | java | private boolean compatibleTypes(TypeMirror parameterType, TypeMirror memberType) {
if (typeUtils.isAssignable(parameterType, memberType)) {
// parameterType assignable to memberType, which in the restricted world of annotations
// means they are the same type, or maybe memberType is an annotation type and parameterType
// is a subtype of that annotation interface (why would you do that?).
return true;
}
// They're not the same, but we could still consider them compatible if for example
// parameterType is List<Integer> and memberType is int[]. We accept any type that is assignable
// to Collection<Integer> (in this example).
if (memberType.getKind() != TypeKind.ARRAY) {
return false;
}
TypeMirror arrayElementType = ((ArrayType) memberType).getComponentType();
TypeMirror wrappedArrayElementType =
arrayElementType.getKind().isPrimitive()
? typeUtils.boxedClass((PrimitiveType) arrayElementType).asType()
: arrayElementType;
TypeElement javaUtilCollection =
elementUtils.getTypeElement(Collection.class.getCanonicalName());
DeclaredType collectionOfElement =
typeUtils.getDeclaredType(javaUtilCollection, wrappedArrayElementType);
return typeUtils.isAssignable(parameterType, collectionOfElement);
} | [
"private",
"boolean",
"compatibleTypes",
"(",
"TypeMirror",
"parameterType",
",",
"TypeMirror",
"memberType",
")",
"{",
"if",
"(",
"typeUtils",
".",
"isAssignable",
"(",
"parameterType",
",",
"memberType",
")",
")",
"{",
"// parameterType assignable to memberType, which... | Returns true if {@code parameterType} can be used to provide the value of an annotation member
of type {@code memberType}. They must either be the same type, or the member type must be an
array and the parameter type must be a collection of a compatible type. | [
"Returns",
"true",
"if",
"{"
] | train | https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java#L385-L408 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/tag/jsf/ComponentSupport.java | ComponentSupport.findChild | public static UIComponent findChild(UIComponent parent, String id) {
"""
A lighter-weight version of UIComponent's findChild.
@param parent
parent to start searching from
@param id
to match to
@return UIComponent found or null
"""
int childCount = parent.getChildCount();
if (childCount > 0)
{
for (int i = 0; i < childCount; i++)
{
UIComponent child = parent.getChildren().get(i);
if (id.equals(child.getId()))
{
return child;
}
}
}
return null;
} | java | public static UIComponent findChild(UIComponent parent, String id)
{
int childCount = parent.getChildCount();
if (childCount > 0)
{
for (int i = 0; i < childCount; i++)
{
UIComponent child = parent.getChildren().get(i);
if (id.equals(child.getId()))
{
return child;
}
}
}
return null;
} | [
"public",
"static",
"UIComponent",
"findChild",
"(",
"UIComponent",
"parent",
",",
"String",
"id",
")",
"{",
"int",
"childCount",
"=",
"parent",
".",
"getChildCount",
"(",
")",
";",
"if",
"(",
"childCount",
">",
"0",
")",
"{",
"for",
"(",
"int",
"i",
"... | A lighter-weight version of UIComponent's findChild.
@param parent
parent to start searching from
@param id
to match to
@return UIComponent found or null | [
"A",
"lighter",
"-",
"weight",
"version",
"of",
"UIComponent",
"s",
"findChild",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/tag/jsf/ComponentSupport.java#L152-L167 |
threerings/nenya | core/src/main/java/com/threerings/media/image/ImageUtil.java | ImageUtil.tileImageAcross | public static void tileImageAcross (Graphics2D gfx, Mirage image, int x, int y, int width) {
"""
Paints multiple copies of the supplied image using the supplied graphics context such that
the requested width is filled with the image.
"""
tileImage(gfx, image, x, y, width, image.getHeight());
} | java | public static void tileImageAcross (Graphics2D gfx, Mirage image, int x, int y, int width)
{
tileImage(gfx, image, x, y, width, image.getHeight());
} | [
"public",
"static",
"void",
"tileImageAcross",
"(",
"Graphics2D",
"gfx",
",",
"Mirage",
"image",
",",
"int",
"x",
",",
"int",
"y",
",",
"int",
"width",
")",
"{",
"tileImage",
"(",
"gfx",
",",
"image",
",",
"x",
",",
"y",
",",
"width",
",",
"image",
... | Paints multiple copies of the supplied image using the supplied graphics context such that
the requested width is filled with the image. | [
"Paints",
"multiple",
"copies",
"of",
"the",
"supplied",
"image",
"using",
"the",
"supplied",
"graphics",
"context",
"such",
"that",
"the",
"requested",
"width",
"is",
"filled",
"with",
"the",
"image",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/image/ImageUtil.java#L216-L219 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/network/channel_binding.java | channel_binding.get | public static channel_binding get(nitro_service service, String id) throws Exception {
"""
Use this API to fetch channel_binding resource of given name .
"""
channel_binding obj = new channel_binding();
obj.set_id(id);
channel_binding response = (channel_binding) obj.get_resource(service);
return response;
} | java | public static channel_binding get(nitro_service service, String id) throws Exception{
channel_binding obj = new channel_binding();
obj.set_id(id);
channel_binding response = (channel_binding) obj.get_resource(service);
return response;
} | [
"public",
"static",
"channel_binding",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"id",
")",
"throws",
"Exception",
"{",
"channel_binding",
"obj",
"=",
"new",
"channel_binding",
"(",
")",
";",
"obj",
".",
"set_id",
"(",
"id",
")",
";",
"channel_b... | Use this API to fetch channel_binding resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"channel_binding",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/network/channel_binding.java#L105-L110 |
apache/spark | core/src/main/java/org/apache/spark/util/collection/TimSort.java | TimSort.binarySort | @SuppressWarnings("fallthrough")
private void binarySort(Buffer a, int lo, int hi, int start, Comparator<? super K> c) {
"""
Sorts the specified portion of the specified array using a binary
insertion sort. This is the best method for sorting small numbers
of elements. It requires O(n log n) compares, but O(n^2) data
movement (worst case).
If the initial part of the specified range is already sorted,
this method can take advantage of it: the method assumes that the
elements from index {@code lo}, inclusive, to {@code start},
exclusive are already sorted.
@param a the array in which a range is to be sorted
@param lo the index of the first element in the range to be sorted
@param hi the index after the last element in the range to be sorted
@param start the index of the first element in the range that is
not already known to be sorted ({@code lo <= start <= hi})
@param c comparator to used for the sort
"""
assert lo <= start && start <= hi;
if (start == lo)
start++;
K key0 = s.newKey();
K key1 = s.newKey();
Buffer pivotStore = s.allocate(1);
for ( ; start < hi; start++) {
s.copyElement(a, start, pivotStore, 0);
K pivot = s.getKey(pivotStore, 0, key0);
// Set left (and right) to the index where a[start] (pivot) belongs
int left = lo;
int right = start;
assert left <= right;
/*
* Invariants:
* pivot >= all in [lo, left).
* pivot < all in [right, start).
*/
while (left < right) {
int mid = (left + right) >>> 1;
if (c.compare(pivot, s.getKey(a, mid, key1)) < 0)
right = mid;
else
left = mid + 1;
}
assert left == right;
/*
* The invariants still hold: pivot >= all in [lo, left) and
* pivot < all in [left, start), so pivot belongs at left. Note
* that if there are elements equal to pivot, left points to the
* first slot after them -- that's why this sort is stable.
* Slide elements over to make room for pivot.
*/
int n = start - left; // The number of elements to move
// Switch is just an optimization for arraycopy in default case
switch (n) {
case 2: s.copyElement(a, left + 1, a, left + 2);
case 1: s.copyElement(a, left, a, left + 1);
break;
default: s.copyRange(a, left, a, left + 1, n);
}
s.copyElement(pivotStore, 0, a, left);
}
} | java | @SuppressWarnings("fallthrough")
private void binarySort(Buffer a, int lo, int hi, int start, Comparator<? super K> c) {
assert lo <= start && start <= hi;
if (start == lo)
start++;
K key0 = s.newKey();
K key1 = s.newKey();
Buffer pivotStore = s.allocate(1);
for ( ; start < hi; start++) {
s.copyElement(a, start, pivotStore, 0);
K pivot = s.getKey(pivotStore, 0, key0);
// Set left (and right) to the index where a[start] (pivot) belongs
int left = lo;
int right = start;
assert left <= right;
/*
* Invariants:
* pivot >= all in [lo, left).
* pivot < all in [right, start).
*/
while (left < right) {
int mid = (left + right) >>> 1;
if (c.compare(pivot, s.getKey(a, mid, key1)) < 0)
right = mid;
else
left = mid + 1;
}
assert left == right;
/*
* The invariants still hold: pivot >= all in [lo, left) and
* pivot < all in [left, start), so pivot belongs at left. Note
* that if there are elements equal to pivot, left points to the
* first slot after them -- that's why this sort is stable.
* Slide elements over to make room for pivot.
*/
int n = start - left; // The number of elements to move
// Switch is just an optimization for arraycopy in default case
switch (n) {
case 2: s.copyElement(a, left + 1, a, left + 2);
case 1: s.copyElement(a, left, a, left + 1);
break;
default: s.copyRange(a, left, a, left + 1, n);
}
s.copyElement(pivotStore, 0, a, left);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"fallthrough\"",
")",
"private",
"void",
"binarySort",
"(",
"Buffer",
"a",
",",
"int",
"lo",
",",
"int",
"hi",
",",
"int",
"start",
",",
"Comparator",
"<",
"?",
"super",
"K",
">",
"c",
")",
"{",
"assert",
"lo",
"<=",
"... | Sorts the specified portion of the specified array using a binary
insertion sort. This is the best method for sorting small numbers
of elements. It requires O(n log n) compares, but O(n^2) data
movement (worst case).
If the initial part of the specified range is already sorted,
this method can take advantage of it: the method assumes that the
elements from index {@code lo}, inclusive, to {@code start},
exclusive are already sorted.
@param a the array in which a range is to be sorted
@param lo the index of the first element in the range to be sorted
@param hi the index after the last element in the range to be sorted
@param start the index of the first element in the range that is
not already known to be sorted ({@code lo <= start <= hi})
@param c comparator to used for the sort | [
"Sorts",
"the",
"specified",
"portion",
"of",
"the",
"specified",
"array",
"using",
"a",
"binary",
"insertion",
"sort",
".",
"This",
"is",
"the",
"best",
"method",
"for",
"sorting",
"small",
"numbers",
"of",
"elements",
".",
"It",
"requires",
"O",
"(",
"n"... | train | https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/core/src/main/java/org/apache/spark/util/collection/TimSort.java#L184-L233 |
goldmansachs/reladomo | reladomo/src/main/java/com/gs/fw/common/mithra/connectionmanager/AbstractConnectionManager.java | AbstractConnectionManager.initialisePool | public void initialisePool() {
"""
This method must be called after all the connection pool properties have been set.
"""
Properties loginProperties = createLoginProperties();
if (logger.isDebugEnabled())
{
logger.debug("about to create pool with user-id : " + this.getJdbcUser());
}
ConnectionFactory connectionFactory = createConnectionFactory(loginProperties);
PoolableObjectFactory objectFactoryForConnectionPool = getObjectFactoryForConnectionPool(connectionFactory, connectionPool);
connectionPool = new ObjectPoolWithThreadAffinity(objectFactoryForConnectionPool, this.getPoolSize(),
this.getMaxWait(), this.getPoolSize(), this.getInitialSize(), true, false, this.timeBetweenEvictionRunsMillis,
this.minEvictableIdleTimeMillis, this.softMinEvictableIdleTimeMillis);
dataSource = createPoolingDataSource(connectionPool);
if (this.getInitialSize() > 0)
{
try // test connection
{
this.getConnection().close();
}
catch (Exception e)
{
logger.error("Error initializing pool " + this, e);
}
}
} | java | public void initialisePool()
{
Properties loginProperties = createLoginProperties();
if (logger.isDebugEnabled())
{
logger.debug("about to create pool with user-id : " + this.getJdbcUser());
}
ConnectionFactory connectionFactory = createConnectionFactory(loginProperties);
PoolableObjectFactory objectFactoryForConnectionPool = getObjectFactoryForConnectionPool(connectionFactory, connectionPool);
connectionPool = new ObjectPoolWithThreadAffinity(objectFactoryForConnectionPool, this.getPoolSize(),
this.getMaxWait(), this.getPoolSize(), this.getInitialSize(), true, false, this.timeBetweenEvictionRunsMillis,
this.minEvictableIdleTimeMillis, this.softMinEvictableIdleTimeMillis);
dataSource = createPoolingDataSource(connectionPool);
if (this.getInitialSize() > 0)
{
try // test connection
{
this.getConnection().close();
}
catch (Exception e)
{
logger.error("Error initializing pool " + this, e);
}
}
} | [
"public",
"void",
"initialisePool",
"(",
")",
"{",
"Properties",
"loginProperties",
"=",
"createLoginProperties",
"(",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"about to create pool with user-id : \""... | This method must be called after all the connection pool properties have been set. | [
"This",
"method",
"must",
"be",
"called",
"after",
"all",
"the",
"connection",
"pool",
"properties",
"have",
"been",
"set",
"."
] | train | https://github.com/goldmansachs/reladomo/blob/e9a069452eece7a6ef9551caf81a69d3d9a3d990/reladomo/src/main/java/com/gs/fw/common/mithra/connectionmanager/AbstractConnectionManager.java#L107-L136 |
TheHortonMachine/hortonmachine | dbs/src/main/java/jsqlite/Database.java | Database.get_table | public TableResult get_table( String sql, String args[] ) throws jsqlite.Exception {
"""
Convenience method to retrieve an entire result
set into memory.
@param sql the SQL statement to be executed
@param args arguments for the SQL statement, '%q' substitution
@return result set
"""
return get_table(sql, 0, args);
} | java | public TableResult get_table( String sql, String args[] ) throws jsqlite.Exception {
return get_table(sql, 0, args);
} | [
"public",
"TableResult",
"get_table",
"(",
"String",
"sql",
",",
"String",
"args",
"[",
"]",
")",
"throws",
"jsqlite",
".",
"Exception",
"{",
"return",
"get_table",
"(",
"sql",
",",
"0",
",",
"args",
")",
";",
"}"
] | Convenience method to retrieve an entire result
set into memory.
@param sql the SQL statement to be executed
@param args arguments for the SQL statement, '%q' substitution
@return result set | [
"Convenience",
"method",
"to",
"retrieve",
"an",
"entire",
"result",
"set",
"into",
"memory",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/jsqlite/Database.java#L375-L377 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/util/ConcurrentReferenceHashMap.java | ConcurrentReferenceHashMap.applyIfAbsent | @Override
public V applyIfAbsent(K key, IFunction<? super K, ? extends V> mappingFunction) {
"""
*
{@inheritDoc}
@throws UnsupportedOperationException {@inheritDoc}
@throws ClassCastException {@inheritDoc}
@throws NullPointerException {@inheritDoc}
@implSpec The default implementation is equivalent to the following steps for this
{@code map}, then returning the current value or {@code null} if now
absent:
<p>
<pre> {@code
if (map.get(key) == null) {
V newValue = mappingFunction.apply(key);
if (newValue != null)
return map.putIfAbsent(key, newValue);
}
}</pre>
<p>
The default implementation may retry these steps when multiple
threads attempt updates including potentially calling the mapping
function multiple times.
<p>
<p>This implementation assumes that the ConcurrentMap cannot contain null
values and {@code get()} returning null unambiguously means the key is
absent. Implementations which support null values <strong>must</strong>
override this default implementation.
"""
checkNotNull(key);
checkNotNull(mappingFunction);
int hash = hashOf(key);
Segment<K, V> segment = segmentFor(hash);
V v = segment.get(key, hash);
return v == null ? segment.put(key, hash, null, mappingFunction, true) : v;
} | java | @Override
public V applyIfAbsent(K key, IFunction<? super K, ? extends V> mappingFunction) {
checkNotNull(key);
checkNotNull(mappingFunction);
int hash = hashOf(key);
Segment<K, V> segment = segmentFor(hash);
V v = segment.get(key, hash);
return v == null ? segment.put(key, hash, null, mappingFunction, true) : v;
} | [
"@",
"Override",
"public",
"V",
"applyIfAbsent",
"(",
"K",
"key",
",",
"IFunction",
"<",
"?",
"super",
"K",
",",
"?",
"extends",
"V",
">",
"mappingFunction",
")",
"{",
"checkNotNull",
"(",
"key",
")",
";",
"checkNotNull",
"(",
"mappingFunction",
")",
";"... | *
{@inheritDoc}
@throws UnsupportedOperationException {@inheritDoc}
@throws ClassCastException {@inheritDoc}
@throws NullPointerException {@inheritDoc}
@implSpec The default implementation is equivalent to the following steps for this
{@code map}, then returning the current value or {@code null} if now
absent:
<p>
<pre> {@code
if (map.get(key) == null) {
V newValue = mappingFunction.apply(key);
if (newValue != null)
return map.putIfAbsent(key, newValue);
}
}</pre>
<p>
The default implementation may retry these steps when multiple
threads attempt updates including potentially calling the mapping
function multiple times.
<p>
<p>This implementation assumes that the ConcurrentMap cannot contain null
values and {@code get()} returning null unambiguously means the key is
absent. Implementations which support null values <strong>must</strong>
override this default implementation. | [
"*",
"{",
"@inheritDoc",
"}"
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/ConcurrentReferenceHashMap.java#L1424-L1433 |
spotify/styx | styx-common/src/main/java/com/spotify/styx/util/TimeUtil.java | TimeUtil.addOffset | public static ZonedDateTime addOffset(ZonedDateTime time, String offset) {
"""
Applies an ISO 8601 Duration to a {@link ZonedDateTime}.
<p>Since the JDK defined different types for the different parts of a Duration
specification, this utility method is needed when a full Duration is to be applied to a
{@link ZonedDateTime}. See {@link Period} and {@link Duration}.
<p>All date-based parts of a Duration specification (Year, Month, Day or Week) are parsed
using {@link Period#parse(CharSequence)} and added to the time. The remaining parts (Hour,
Minute, Second) are parsed using {@link Duration#parse(CharSequence)} and added to the time.
@param time A zoned date time to apply the offset to
@param offset The offset in ISO 8601 Duration format
@return A zoned date time with the offset applied
"""
final Matcher matcher = OFFSET_PATTERN.matcher(offset);
if (!matcher.matches()) {
throw new DateTimeParseException("Unable to parse offset period", offset, 0);
}
final String sign = matcher.group(1);
final String periodOffset = sign + "P" + Optional.ofNullable(matcher.group(2)).orElse("0D");
final String durationOffset = sign + "PT" + Optional.ofNullable(matcher.group(4)).orElse("0S");
final TemporalAmount dateAmount = Period.parse(periodOffset);
final TemporalAmount timeAmount = Duration.parse(durationOffset);
return time.plus(dateAmount).plus(timeAmount);
} | java | public static ZonedDateTime addOffset(ZonedDateTime time, String offset) {
final Matcher matcher = OFFSET_PATTERN.matcher(offset);
if (!matcher.matches()) {
throw new DateTimeParseException("Unable to parse offset period", offset, 0);
}
final String sign = matcher.group(1);
final String periodOffset = sign + "P" + Optional.ofNullable(matcher.group(2)).orElse("0D");
final String durationOffset = sign + "PT" + Optional.ofNullable(matcher.group(4)).orElse("0S");
final TemporalAmount dateAmount = Period.parse(periodOffset);
final TemporalAmount timeAmount = Duration.parse(durationOffset);
return time.plus(dateAmount).plus(timeAmount);
} | [
"public",
"static",
"ZonedDateTime",
"addOffset",
"(",
"ZonedDateTime",
"time",
",",
"String",
"offset",
")",
"{",
"final",
"Matcher",
"matcher",
"=",
"OFFSET_PATTERN",
".",
"matcher",
"(",
"offset",
")",
";",
"if",
"(",
"!",
"matcher",
".",
"matches",
"(",
... | Applies an ISO 8601 Duration to a {@link ZonedDateTime}.
<p>Since the JDK defined different types for the different parts of a Duration
specification, this utility method is needed when a full Duration is to be applied to a
{@link ZonedDateTime}. See {@link Period} and {@link Duration}.
<p>All date-based parts of a Duration specification (Year, Month, Day or Week) are parsed
using {@link Period#parse(CharSequence)} and added to the time. The remaining parts (Hour,
Minute, Second) are parsed using {@link Duration#parse(CharSequence)} and added to the time.
@param time A zoned date time to apply the offset to
@param offset The offset in ISO 8601 Duration format
@return A zoned date time with the offset applied | [
"Applies",
"an",
"ISO",
"8601",
"Duration",
"to",
"a",
"{",
"@link",
"ZonedDateTime",
"}",
"."
] | train | https://github.com/spotify/styx/blob/0d63999beeb93a17447e3bbccaa62175b74cf6e4/styx-common/src/main/java/com/spotify/styx/util/TimeUtil.java#L217-L232 |
jbundle/jbundle | base/screen/model/src/main/java/org/jbundle/base/screen/model/BaseScreen.java | BaseScreen.checkContactSecurity | public int checkContactSecurity(String strContactType, String strContactID) {
"""
Special security check for screens that only allow access to users that are contacts (such as vendors, profiles, employees).
If this contact type and ID match the user contact and ID, allow access, otherwise deny access.
NOTE: Special case if this user is not a contact or is a different type of contact (such as an administrator), allow access.
@param strContactType
@param strContactID
@return
"""
int iErrorCode = DBConstants.NORMAL_RETURN;
if (Utility.isNumeric(strContactType))
{
ContactTypeModel recContactType = (ContactTypeModel)Record.makeRecordFromClassName(ContactTypeModel.THICK_CLASS, this);
strContactType = recContactType.getContactTypeFromID(strContactType);
recContactType.free();
}
String strUserContactType = this.getProperty(TrxMessageHeader.CONTACT_TYPE);
String strUserContactID = this.getProperty(TrxMessageHeader.CONTACT_ID);
if ((strUserContactType == null) || (strUserContactType.length() == 0) || (strUserContactType.equalsIgnoreCase(strContactType)))
iErrorCode = DBConstants.NORMAL_RETURN; // No contact or different contact, okay
else if ((strUserContactID != null) && (strUserContactID.equalsIgnoreCase(strContactID)))
iErrorCode = DBConstants.NORMAL_RETURN; // Matching contact, okay
else
iErrorCode = DBConstants.ACCESS_DENIED; // Non-matching contact, NO
return iErrorCode;
} | java | public int checkContactSecurity(String strContactType, String strContactID)
{
int iErrorCode = DBConstants.NORMAL_RETURN;
if (Utility.isNumeric(strContactType))
{
ContactTypeModel recContactType = (ContactTypeModel)Record.makeRecordFromClassName(ContactTypeModel.THICK_CLASS, this);
strContactType = recContactType.getContactTypeFromID(strContactType);
recContactType.free();
}
String strUserContactType = this.getProperty(TrxMessageHeader.CONTACT_TYPE);
String strUserContactID = this.getProperty(TrxMessageHeader.CONTACT_ID);
if ((strUserContactType == null) || (strUserContactType.length() == 0) || (strUserContactType.equalsIgnoreCase(strContactType)))
iErrorCode = DBConstants.NORMAL_RETURN; // No contact or different contact, okay
else if ((strUserContactID != null) && (strUserContactID.equalsIgnoreCase(strContactID)))
iErrorCode = DBConstants.NORMAL_RETURN; // Matching contact, okay
else
iErrorCode = DBConstants.ACCESS_DENIED; // Non-matching contact, NO
return iErrorCode;
} | [
"public",
"int",
"checkContactSecurity",
"(",
"String",
"strContactType",
",",
"String",
"strContactID",
")",
"{",
"int",
"iErrorCode",
"=",
"DBConstants",
".",
"NORMAL_RETURN",
";",
"if",
"(",
"Utility",
".",
"isNumeric",
"(",
"strContactType",
")",
")",
"{",
... | Special security check for screens that only allow access to users that are contacts (such as vendors, profiles, employees).
If this contact type and ID match the user contact and ID, allow access, otherwise deny access.
NOTE: Special case if this user is not a contact or is a different type of contact (such as an administrator), allow access.
@param strContactType
@param strContactID
@return | [
"Special",
"security",
"check",
"for",
"screens",
"that",
"only",
"allow",
"access",
"to",
"users",
"that",
"are",
"contacts",
"(",
"such",
"as",
"vendors",
"profiles",
"employees",
")",
".",
"If",
"this",
"contact",
"type",
"and",
"ID",
"match",
"the",
"u... | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/BaseScreen.java#L284-L306 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WListOptionsExample.java | WListOptionsExample.applySettings | private void applySettings() {
"""
Apply settings is responsible for building the list to be displayed and adding it to the container.
"""
container.reset();
WList list = new WList((com.github.bordertech.wcomponents.WList.Type) ddType.getSelected());
List<String> selected = (List<String>) cgBeanFields.getSelected();
SimpleListRenderer renderer = new SimpleListRenderer(selected, cbRenderUsingFieldLayout.
isSelected());
list.setRepeatedComponent(renderer);
list.setSeparator((Separator) ddSeparator.getSelected());
list.setRenderBorder(cbRenderBorder.isSelected());
container.add(list);
List<SimpleTableBean> items = new ArrayList<>();
items.add(new SimpleTableBean("A", "none", "thing"));
items.add(new SimpleTableBean("B", "some", "thing2"));
items.add(new SimpleTableBean("C", "little", "thing3"));
items.add(new SimpleTableBean("D", "lots", "thing4"));
list.setData(items);
list.setVisible(cbVisible.isSelected());
} | java | private void applySettings() {
container.reset();
WList list = new WList((com.github.bordertech.wcomponents.WList.Type) ddType.getSelected());
List<String> selected = (List<String>) cgBeanFields.getSelected();
SimpleListRenderer renderer = new SimpleListRenderer(selected, cbRenderUsingFieldLayout.
isSelected());
list.setRepeatedComponent(renderer);
list.setSeparator((Separator) ddSeparator.getSelected());
list.setRenderBorder(cbRenderBorder.isSelected());
container.add(list);
List<SimpleTableBean> items = new ArrayList<>();
items.add(new SimpleTableBean("A", "none", "thing"));
items.add(new SimpleTableBean("B", "some", "thing2"));
items.add(new SimpleTableBean("C", "little", "thing3"));
items.add(new SimpleTableBean("D", "lots", "thing4"));
list.setData(items);
list.setVisible(cbVisible.isSelected());
} | [
"private",
"void",
"applySettings",
"(",
")",
"{",
"container",
".",
"reset",
"(",
")",
";",
"WList",
"list",
"=",
"new",
"WList",
"(",
"(",
"com",
".",
"github",
".",
"bordertech",
".",
"wcomponents",
".",
"WList",
".",
"Type",
")",
"ddType",
".",
"... | Apply settings is responsible for building the list to be displayed and adding it to the container. | [
"Apply",
"settings",
"is",
"responsible",
"for",
"building",
"the",
"list",
"to",
"be",
"displayed",
"and",
"adding",
"it",
"to",
"the",
"container",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WListOptionsExample.java#L142-L164 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/gd/GuaranteedTargetStream.java | GuaranteedTargetStream.handleNewGap | private void handleNewGap(long startstamp, long endstamp) {
"""
all methods calling this are already synchronized
@exception GDException thrown from the writeRange method
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"handleNewGap",
new Object[] { Long.valueOf(startstamp), Long.valueOf(endstamp) });
TickRange tr = new TickRange(TickRange.Requested, startstamp, endstamp);
oststream.writeRange(tr);
// SIB0115
// Update Health State due to detected gap
getControlAdapter().getHealthState().updateHealth(HealthStateListener.GAP_DETECTED_STATE,
HealthState.AMBER);
NRTExpiryHandle nexphandle = new NRTExpiryHandle(tr, this);
nexphandle.timer =
am.create(mp.getCustomProperties().getGapCuriosityThreshold(), nexphandle);
addAlarm(this, nexphandle);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleNewGap");
} | java | private void handleNewGap(long startstamp, long endstamp)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"handleNewGap",
new Object[] { Long.valueOf(startstamp), Long.valueOf(endstamp) });
TickRange tr = new TickRange(TickRange.Requested, startstamp, endstamp);
oststream.writeRange(tr);
// SIB0115
// Update Health State due to detected gap
getControlAdapter().getHealthState().updateHealth(HealthStateListener.GAP_DETECTED_STATE,
HealthState.AMBER);
NRTExpiryHandle nexphandle = new NRTExpiryHandle(tr, this);
nexphandle.timer =
am.create(mp.getCustomProperties().getGapCuriosityThreshold(), nexphandle);
addAlarm(this, nexphandle);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleNewGap");
} | [
"private",
"void",
"handleNewGap",
"(",
"long",
"startstamp",
",",
"long",
"endstamp",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
"tc",
",",
"... | all methods calling this are already synchronized
@exception GDException thrown from the writeRange method | [
"all",
"methods",
"calling",
"this",
"are",
"already",
"synchronized"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/gd/GuaranteedTargetStream.java#L1285-L1309 |
datacleaner/AnalyzerBeans | core/src/main/java/org/eobjects/analyzer/util/SystemProperties.java | SystemProperties.getBoolean | public static boolean getBoolean(String key, boolean valueIfNull) {
"""
Gets a system property boolean, or a replacement value if the property is
null or blank or not parseable as a boolean.
@param key
@param valueIfNull
@return
"""
String value = System.getProperty(key);
if (Strings.isNullOrEmpty(value)) {
return valueIfNull;
}
value = value.trim().toLowerCase();
if ("true".equals(value)) {
return true;
} else if ("false".equals(value)) {
return false;
}
return valueIfNull;
} | java | public static boolean getBoolean(String key, boolean valueIfNull) {
String value = System.getProperty(key);
if (Strings.isNullOrEmpty(value)) {
return valueIfNull;
}
value = value.trim().toLowerCase();
if ("true".equals(value)) {
return true;
} else if ("false".equals(value)) {
return false;
}
return valueIfNull;
} | [
"public",
"static",
"boolean",
"getBoolean",
"(",
"String",
"key",
",",
"boolean",
"valueIfNull",
")",
"{",
"String",
"value",
"=",
"System",
".",
"getProperty",
"(",
"key",
")",
";",
"if",
"(",
"Strings",
".",
"isNullOrEmpty",
"(",
"value",
")",
")",
"{... | Gets a system property boolean, or a replacement value if the property is
null or blank or not parseable as a boolean.
@param key
@param valueIfNull
@return | [
"Gets",
"a",
"system",
"property",
"boolean",
"or",
"a",
"replacement",
"value",
"if",
"the",
"property",
"is",
"null",
"or",
"blank",
"or",
"not",
"parseable",
"as",
"a",
"boolean",
"."
] | train | https://github.com/datacleaner/AnalyzerBeans/blob/f82dae080d80d2a647b706a5fb22b3ea250613b3/core/src/main/java/org/eobjects/analyzer/util/SystemProperties.java#L103-L118 |
VoltDB/voltdb | third_party/java/src/org/apache/commons_voltpatches/cli/DefaultParser.java | DefaultParser.handleLongOptionWithEqual | private void handleLongOptionWithEqual(String token) throws ParseException {
"""
Handles the following tokens:
--L=V
-L=V
--l=V
-l=V
@param token the command line token to handle
"""
int pos = token.indexOf('=');
String value = token.substring(pos + 1);
String opt = token.substring(0, pos);
List<String> matchingOpts = options.getMatchingOptions(opt);
if (matchingOpts.isEmpty())
{
handleUnknownToken(currentToken);
}
else if (matchingOpts.size() > 1)
{
throw new AmbiguousOptionException(opt, matchingOpts);
}
else
{
Option option = options.getOption(matchingOpts.get(0));
if (option.acceptsArg())
{
handleOption(option);
currentOption.addValueForProcessing(value);
currentOption = null;
}
else
{
handleUnknownToken(currentToken);
}
}
} | java | private void handleLongOptionWithEqual(String token) throws ParseException
{
int pos = token.indexOf('=');
String value = token.substring(pos + 1);
String opt = token.substring(0, pos);
List<String> matchingOpts = options.getMatchingOptions(opt);
if (matchingOpts.isEmpty())
{
handleUnknownToken(currentToken);
}
else if (matchingOpts.size() > 1)
{
throw new AmbiguousOptionException(opt, matchingOpts);
}
else
{
Option option = options.getOption(matchingOpts.get(0));
if (option.acceptsArg())
{
handleOption(option);
currentOption.addValueForProcessing(value);
currentOption = null;
}
else
{
handleUnknownToken(currentToken);
}
}
} | [
"private",
"void",
"handleLongOptionWithEqual",
"(",
"String",
"token",
")",
"throws",
"ParseException",
"{",
"int",
"pos",
"=",
"token",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"String",
"value",
"=",
"token",
".",
"substring",
"(",
"pos",
"+",
"1",
")... | Handles the following tokens:
--L=V
-L=V
--l=V
-l=V
@param token the command line token to handle | [
"Handles",
"the",
"following",
"tokens",
":"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/commons_voltpatches/cli/DefaultParser.java#L416-L448 |
ngageoint/geopackage-android-map | geopackage-map/src/main/java/mil/nga/geopackage/map/geom/GoogleMapShapeConverter.java | GoogleMapShapeConverter.toMultiLineStringFromList | public MultiLineString toMultiLineStringFromList(
List<List<LatLng>> polylineList, boolean hasZ, boolean hasM) {
"""
Convert a list of List<LatLng> to a {@link MultiLineString}
@param polylineList polyline list
@param hasZ has z flag
@param hasM has m flag
@return multi line string
"""
MultiLineString multiLineString = new MultiLineString(hasZ, hasM);
for (List<LatLng> polyline : polylineList) {
LineString lineString = toLineString(polyline);
multiLineString.addLineString(lineString);
}
return multiLineString;
} | java | public MultiLineString toMultiLineStringFromList(
List<List<LatLng>> polylineList, boolean hasZ, boolean hasM) {
MultiLineString multiLineString = new MultiLineString(hasZ, hasM);
for (List<LatLng> polyline : polylineList) {
LineString lineString = toLineString(polyline);
multiLineString.addLineString(lineString);
}
return multiLineString;
} | [
"public",
"MultiLineString",
"toMultiLineStringFromList",
"(",
"List",
"<",
"List",
"<",
"LatLng",
">",
">",
"polylineList",
",",
"boolean",
"hasZ",
",",
"boolean",
"hasM",
")",
"{",
"MultiLineString",
"multiLineString",
"=",
"new",
"MultiLineString",
"(",
"hasZ",... | Convert a list of List<LatLng> to a {@link MultiLineString}
@param polylineList polyline list
@param hasZ has z flag
@param hasM has m flag
@return multi line string | [
"Convert",
"a",
"list",
"of",
"List<LatLng",
">",
"to",
"a",
"{",
"@link",
"MultiLineString",
"}"
] | train | https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/geom/GoogleMapShapeConverter.java#L872-L883 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/util/JavacMessages.java | JavacMessages.getLocalizedString | public String getLocalizedString(String key, Object... args) {
"""
Gets the localized string corresponding to a key, formatted with a set of args.
"""
return getLocalizedString(currentLocale, key, args);
} | java | public String getLocalizedString(String key, Object... args) {
return getLocalizedString(currentLocale, key, args);
} | [
"public",
"String",
"getLocalizedString",
"(",
"String",
"key",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"getLocalizedString",
"(",
"currentLocale",
",",
"key",
",",
"args",
")",
";",
"}"
] | Gets the localized string corresponding to a key, formatted with a set of args. | [
"Gets",
"the",
"localized",
"string",
"corresponding",
"to",
"a",
"key",
"formatted",
"with",
"a",
"set",
"of",
"args",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/util/JavacMessages.java#L139-L141 |
weld/core | environments/servlet/core/src/main/java/org/jboss/weld/environment/servlet/Listener.java | Listener.using | public static Listener using(BeanManager manager) {
"""
Creates a new Listener that uses the given {@link BeanManager} instead of initializing a new Weld container instance.
@param manager the bean manager to be used
@return a new Listener instance
"""
return new Listener(Collections.singletonList(initAction(WeldServletLifecycle.BEAN_MANAGER_ATTRIBUTE_NAME, manager)));
} | java | public static Listener using(BeanManager manager) {
return new Listener(Collections.singletonList(initAction(WeldServletLifecycle.BEAN_MANAGER_ATTRIBUTE_NAME, manager)));
} | [
"public",
"static",
"Listener",
"using",
"(",
"BeanManager",
"manager",
")",
"{",
"return",
"new",
"Listener",
"(",
"Collections",
".",
"singletonList",
"(",
"initAction",
"(",
"WeldServletLifecycle",
".",
"BEAN_MANAGER_ATTRIBUTE_NAME",
",",
"manager",
")",
")",
"... | Creates a new Listener that uses the given {@link BeanManager} instead of initializing a new Weld container instance.
@param manager the bean manager to be used
@return a new Listener instance | [
"Creates",
"a",
"new",
"Listener",
"that",
"uses",
"the",
"given",
"{",
"@link",
"BeanManager",
"}",
"instead",
"of",
"initializing",
"a",
"new",
"Weld",
"container",
"instance",
"."
] | train | https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/environments/servlet/core/src/main/java/org/jboss/weld/environment/servlet/Listener.java#L61-L63 |
geomajas/geomajas-project-client-gwt | client/src/main/java/org/geomajas/gwt/client/gfx/painter/RectanglePainter.java | RectanglePainter.deleteShape | public void deleteShape(Paintable paintable, Object group, MapContext context) {
"""
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 graphics
The context to paint on.
"""
Rectangle rectangle = (Rectangle) paintable;
context.getVectorContext().deleteElement(group, rectangle.getId());
} | java | public void deleteShape(Paintable paintable, Object group, MapContext context) {
Rectangle rectangle = (Rectangle) paintable;
context.getVectorContext().deleteElement(group, rectangle.getId());
} | [
"public",
"void",
"deleteShape",
"(",
"Paintable",
"paintable",
",",
"Object",
"group",
",",
"MapContext",
"context",
")",
"{",
"Rectangle",
"rectangle",
"=",
"(",
"Rectangle",
")",
"paintable",
";",
"context",
".",
"getVectorContext",
"(",
")",
".",
"deleteEl... | 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 graphics
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/RectanglePainter.java#L64-L67 |
WiQuery/wiquery | wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/button/ButtonBehavior.java | ButtonBehavior.setIcons | public ButtonBehavior setIcons(UiIcon primary, UiIcon secondary) {
"""
* Icons to display, with or without text (see text option). The primary icon is
displayed on the left of the label text, the secondary on the right. Value for the
primary and secondary properties must be a classname (String), eg. "ui-icon-gear".
For using only a primary icon: icons: {primary:'ui-icon-locked'}. For using both
primary and secondary icon: icons:
{primary:'ui-icon-gear',secondary:'ui-icon-triangle-1-s'}
@param primary
The primary icon (should be non-null)
@param secondary
The secondary icon (might be null).
@return
"""
options.put("icons", new ButtonIcon(primary, secondary));
return this;
} | java | public ButtonBehavior setIcons(UiIcon primary, UiIcon secondary)
{
options.put("icons", new ButtonIcon(primary, secondary));
return this;
} | [
"public",
"ButtonBehavior",
"setIcons",
"(",
"UiIcon",
"primary",
",",
"UiIcon",
"secondary",
")",
"{",
"options",
".",
"put",
"(",
"\"icons\"",
",",
"new",
"ButtonIcon",
"(",
"primary",
",",
"secondary",
")",
")",
";",
"return",
"this",
";",
"}"
] | * Icons to display, with or without text (see text option). The primary icon is
displayed on the left of the label text, the secondary on the right. Value for the
primary and secondary properties must be a classname (String), eg. "ui-icon-gear".
For using only a primary icon: icons: {primary:'ui-icon-locked'}. For using both
primary and secondary icon: icons:
{primary:'ui-icon-gear',secondary:'ui-icon-triangle-1-s'}
@param primary
The primary icon (should be non-null)
@param secondary
The secondary icon (might be null).
@return | [
"*",
"Icons",
"to",
"display",
"with",
"or",
"without",
"text",
"(",
"see",
"text",
"option",
")",
".",
"The",
"primary",
"icon",
"is",
"displayed",
"on",
"the",
"left",
"of",
"the",
"label",
"text",
"the",
"secondary",
"on",
"the",
"right",
".",
"Valu... | train | https://github.com/WiQuery/wiquery/blob/1b8d60c7a3c37b90fd68c9cd0ff97178fcbcbb08/wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/button/ButtonBehavior.java#L189-L193 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/RegionDiskClient.java | RegionDiskClient.createSnapshotRegionDisk | @BetaApi
public final Operation createSnapshotRegionDisk(String disk, Snapshot snapshotResource) {
"""
Creates a snapshot of this regional disk.
<p>Sample code:
<pre><code>
try (RegionDiskClient regionDiskClient = RegionDiskClient.create()) {
ProjectRegionDiskName disk = ProjectRegionDiskName.of("[PROJECT]", "[REGION]", "[DISK]");
Snapshot snapshotResource = Snapshot.newBuilder().build();
Operation response = regionDiskClient.createSnapshotRegionDisk(disk.toString(), snapshotResource);
}
</code></pre>
@param disk Name of the regional persistent disk to snapshot.
@param snapshotResource A persistent disk snapshot resource. (== resource_for beta.snapshots
==) (== resource_for v1.snapshots ==)
@throws com.google.api.gax.rpc.ApiException if the remote call fails
"""
CreateSnapshotRegionDiskHttpRequest request =
CreateSnapshotRegionDiskHttpRequest.newBuilder()
.setDisk(disk)
.setSnapshotResource(snapshotResource)
.build();
return createSnapshotRegionDisk(request);
} | java | @BetaApi
public final Operation createSnapshotRegionDisk(String disk, Snapshot snapshotResource) {
CreateSnapshotRegionDiskHttpRequest request =
CreateSnapshotRegionDiskHttpRequest.newBuilder()
.setDisk(disk)
.setSnapshotResource(snapshotResource)
.build();
return createSnapshotRegionDisk(request);
} | [
"@",
"BetaApi",
"public",
"final",
"Operation",
"createSnapshotRegionDisk",
"(",
"String",
"disk",
",",
"Snapshot",
"snapshotResource",
")",
"{",
"CreateSnapshotRegionDiskHttpRequest",
"request",
"=",
"CreateSnapshotRegionDiskHttpRequest",
".",
"newBuilder",
"(",
")",
"."... | Creates a snapshot of this regional disk.
<p>Sample code:
<pre><code>
try (RegionDiskClient regionDiskClient = RegionDiskClient.create()) {
ProjectRegionDiskName disk = ProjectRegionDiskName.of("[PROJECT]", "[REGION]", "[DISK]");
Snapshot snapshotResource = Snapshot.newBuilder().build();
Operation response = regionDiskClient.createSnapshotRegionDisk(disk.toString(), snapshotResource);
}
</code></pre>
@param disk Name of the regional persistent disk to snapshot.
@param snapshotResource A persistent disk snapshot resource. (== resource_for beta.snapshots
==) (== resource_for v1.snapshots ==)
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"a",
"snapshot",
"of",
"this",
"regional",
"disk",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/RegionDiskClient.java#L205-L214 |
spring-cloud/spring-cloud-contract | spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ContractProjectUpdater.java | ContractProjectUpdater.updateContractProject | public void updateContractProject(String projectName, Path rootStubsFolder) {
"""
Merges the folder with stubs with the project containing contracts.
@param projectName name of the project
@param rootStubsFolder root folder of the stubs
"""
File clonedRepo = this.gitContractsRepo
.clonedRepo(this.stubRunnerOptions.stubRepositoryRoot);
GitStubDownloaderProperties properties = new GitStubDownloaderProperties(
this.stubRunnerOptions.stubRepositoryRoot, this.stubRunnerOptions);
copyStubs(projectName, rootStubsFolder, clonedRepo);
GitRepo gitRepo = new GitRepo(clonedRepo, properties);
String msg = StubRunnerPropertyUtils
.getProperty(this.stubRunnerOptions.getProperties(), GIT_COMMIT_MESSAGE);
GitRepo.CommitResult commit = gitRepo.commit(clonedRepo,
commitMessage(projectName, msg));
if (commit == GitRepo.CommitResult.EMPTY) {
log.info("There were no changes to commit. Won't push the changes");
return;
}
String attempts = StubRunnerPropertyUtils.getProperty(
this.stubRunnerOptions.getProperties(), GIT_ATTEMPTS_NO_PROP);
int intAttempts = StringUtils.hasText(attempts) ? Integer.parseInt(attempts)
: DEFAULT_ATTEMPTS_NO;
String wait = StubRunnerPropertyUtils.getProperty(
this.stubRunnerOptions.getProperties(), GIT_WAIT_BETWEEN_ATTEMPTS);
long longWait = StringUtils.hasText(wait) ? Long.parseLong(wait)
: DEFAULT_WAIT_BETWEEN_ATTEMPTS;
tryToPushCurrentBranch(clonedRepo, gitRepo, intAttempts, longWait);
} | java | public void updateContractProject(String projectName, Path rootStubsFolder) {
File clonedRepo = this.gitContractsRepo
.clonedRepo(this.stubRunnerOptions.stubRepositoryRoot);
GitStubDownloaderProperties properties = new GitStubDownloaderProperties(
this.stubRunnerOptions.stubRepositoryRoot, this.stubRunnerOptions);
copyStubs(projectName, rootStubsFolder, clonedRepo);
GitRepo gitRepo = new GitRepo(clonedRepo, properties);
String msg = StubRunnerPropertyUtils
.getProperty(this.stubRunnerOptions.getProperties(), GIT_COMMIT_MESSAGE);
GitRepo.CommitResult commit = gitRepo.commit(clonedRepo,
commitMessage(projectName, msg));
if (commit == GitRepo.CommitResult.EMPTY) {
log.info("There were no changes to commit. Won't push the changes");
return;
}
String attempts = StubRunnerPropertyUtils.getProperty(
this.stubRunnerOptions.getProperties(), GIT_ATTEMPTS_NO_PROP);
int intAttempts = StringUtils.hasText(attempts) ? Integer.parseInt(attempts)
: DEFAULT_ATTEMPTS_NO;
String wait = StubRunnerPropertyUtils.getProperty(
this.stubRunnerOptions.getProperties(), GIT_WAIT_BETWEEN_ATTEMPTS);
long longWait = StringUtils.hasText(wait) ? Long.parseLong(wait)
: DEFAULT_WAIT_BETWEEN_ATTEMPTS;
tryToPushCurrentBranch(clonedRepo, gitRepo, intAttempts, longWait);
} | [
"public",
"void",
"updateContractProject",
"(",
"String",
"projectName",
",",
"Path",
"rootStubsFolder",
")",
"{",
"File",
"clonedRepo",
"=",
"this",
".",
"gitContractsRepo",
".",
"clonedRepo",
"(",
"this",
".",
"stubRunnerOptions",
".",
"stubRepositoryRoot",
")",
... | Merges the folder with stubs with the project containing contracts.
@param projectName name of the project
@param rootStubsFolder root folder of the stubs | [
"Merges",
"the",
"folder",
"with",
"stubs",
"with",
"the",
"project",
"containing",
"contracts",
"."
] | train | https://github.com/spring-cloud/spring-cloud-contract/blob/857da51950a87b393286e3bb1b2208c420c01087/spring-cloud-contract-stub-runner/src/main/java/org/springframework/cloud/contract/stubrunner/ContractProjectUpdater.java#L74-L98 |
jbundle/jbundle | thin/base/thread/src/main/java/org/jbundle/thin/base/thread/AutoTask.java | AutoTask.initTask | public void initTask(App application, Map<String, Object> properties) {
"""
If this task object was created from a class name, call init(xxx) for the task.
You may want to put logic in here that checks to make sure this object was not already inited.
Typically, you init a Task object and pass it to the job scheduler. The job scheduler
will check to see if this task is owned by an application... if not, initTask() is called.
@param application The parent application.
@param strParams The task properties.
"""
if (m_application != null)
return; // Never
this.init(application, null, properties);
} | java | public void initTask(App application, Map<String, Object> properties)
{
if (m_application != null)
return; // Never
this.init(application, null, properties);
} | [
"public",
"void",
"initTask",
"(",
"App",
"application",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"{",
"if",
"(",
"m_application",
"!=",
"null",
")",
"return",
";",
"// Never",
"this",
".",
"init",
"(",
"application",
",",
"null"... | If this task object was created from a class name, call init(xxx) for the task.
You may want to put logic in here that checks to make sure this object was not already inited.
Typically, you init a Task object and pass it to the job scheduler. The job scheduler
will check to see if this task is owned by an application... if not, initTask() is called.
@param application The parent application.
@param strParams The task properties. | [
"If",
"this",
"task",
"object",
"was",
"created",
"from",
"a",
"class",
"name",
"call",
"init",
"(",
"xxx",
")",
"for",
"the",
"task",
".",
"You",
"may",
"want",
"to",
"put",
"logic",
"in",
"here",
"that",
"checks",
"to",
"make",
"sure",
"this",
"obj... | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/thread/src/main/java/org/jbundle/thin/base/thread/AutoTask.java#L237-L242 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/ModelControllerLock.java | ModelControllerLock.lockSharedInterruptibly | boolean lockSharedInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {
"""
Acquire the shared lock, with a max wait timeout to acquire.
@param permit - the permit Integer for this operation. May not be {@code null}.
@param timeout - the timeout scalar quantity.
@param unit - see {@code TimeUnit} for quantities.
@return {@code boolean} true on successful acquire.
@throws InterruptedException - if the acquiring thread was interrupted.
@throws IllegalArgumentException if {@code permit} is null.
"""
if (permit == null) {
throw new IllegalArgumentException();
}
return sync.tryAcquireSharedNanos(permit, unit.toNanos(timeout));
} | java | boolean lockSharedInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {
if (permit == null) {
throw new IllegalArgumentException();
}
return sync.tryAcquireSharedNanos(permit, unit.toNanos(timeout));
} | [
"boolean",
"lockSharedInterruptibly",
"(",
"final",
"Integer",
"permit",
",",
"final",
"long",
"timeout",
",",
"final",
"TimeUnit",
"unit",
")",
"throws",
"InterruptedException",
"{",
"if",
"(",
"permit",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentE... | Acquire the shared lock, with a max wait timeout to acquire.
@param permit - the permit Integer for this operation. May not be {@code null}.
@param timeout - the timeout scalar quantity.
@param unit - see {@code TimeUnit} for quantities.
@return {@code boolean} true on successful acquire.
@throws InterruptedException - if the acquiring thread was interrupted.
@throws IllegalArgumentException if {@code permit} is null. | [
"Acquire",
"the",
"shared",
"lock",
"with",
"a",
"max",
"wait",
"timeout",
"to",
"acquire",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/ModelControllerLock.java#L151-L156 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.