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 |
|---|---|---|---|---|---|---|---|---|---|---|
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/EnumUtils.java | EnumUtils.generateBitVector | public static <E extends Enum<E>> long generateBitVector(final Class<E> enumClass, final Iterable<? extends E> values) {
"""
<p>Creates a long bit vector representation of the given subset of an Enum.</p>
<p>This generates a value that is usable by {@link EnumUtils#processBitVector}.</p>
<p>Do not use this method if you have more than 64 values in your Enum, as this
would create a value greater than a long can hold.</p>
@param enumClass the class of the enum we are working with, not {@code null}
@param values the values we want to convert, not {@code null}, neither containing {@code null}
@param <E> the type of the enumeration
@return a long whose value provides a binary representation of the given set of enum values.
@throws NullPointerException if {@code enumClass} or {@code values} is {@code null}
@throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values,
or if any {@code values} {@code null}
@since 3.0.1
@see #generateBitVectors(Class, Iterable)
"""
checkBitVectorable(enumClass);
Validate.notNull(values);
long total = 0;
for (final E constant : values) {
Validate.isTrue(constant != null, NULL_ELEMENTS_NOT_PERMITTED);
total |= 1L << constant.ordinal();
}
return total;
} | java | public static <E extends Enum<E>> long generateBitVector(final Class<E> enumClass, final Iterable<? extends E> values) {
checkBitVectorable(enumClass);
Validate.notNull(values);
long total = 0;
for (final E constant : values) {
Validate.isTrue(constant != null, NULL_ELEMENTS_NOT_PERMITTED);
total |= 1L << constant.ordinal();
}
return total;
} | [
"public",
"static",
"<",
"E",
"extends",
"Enum",
"<",
"E",
">",
">",
"long",
"generateBitVector",
"(",
"final",
"Class",
"<",
"E",
">",
"enumClass",
",",
"final",
"Iterable",
"<",
"?",
"extends",
"E",
">",
"values",
")",
"{",
"checkBitVectorable",
"(",
... | <p>Creates a long bit vector representation of the given subset of an Enum.</p>
<p>This generates a value that is usable by {@link EnumUtils#processBitVector}.</p>
<p>Do not use this method if you have more than 64 values in your Enum, as this
would create a value greater than a long can hold.</p>
@param enumClass the class of the enum we are working with, not {@code null}
@param values the values we want to convert, not {@code null}, neither containing {@code null}
@param <E> the type of the enumeration
@return a long whose value provides a binary representation of the given set of enum values.
@throws NullPointerException if {@code enumClass} or {@code values} is {@code null}
@throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values,
or if any {@code values} {@code null}
@since 3.0.1
@see #generateBitVectors(Class, Iterable) | [
"<p",
">",
"Creates",
"a",
"long",
"bit",
"vector",
"representation",
"of",
"the",
"given",
"subset",
"of",
"an",
"Enum",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/EnumUtils.java#L143-L152 |
alibaba/jstorm | jstorm-core/src/main/java/backtype/storm/topology/TopologyBuilder.java | TopologyBuilder.setBolt | public <T extends State> BoltDeclarer setBolt(String id, IStatefulBolt<T> bolt, Number parallelism_hint) throws IllegalArgumentException {
"""
Define a new bolt in this topology. This defines a stateful bolt, that requires its
state (of computation) to be saved. When this bolt is initialized, the {@link IStatefulBolt#initState(State)} method
is invoked after {@link IStatefulBolt#prepare(Map, TopologyContext, OutputCollector)} but before {@link IStatefulBolt#execute(Tuple)}
with its previously saved state.
<p>
The framework provides at-least once guarantee for the state updates. Bolts (both stateful and non-stateful) in a stateful topology
are expected to anchor the tuples while emitting and ack the input tuples once its processed.
</p>
@param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs.
@param bolt the stateful bolt
@param parallelism_hint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process somwehere around the cluster.
@return use the returned object to declare the inputs to this component
@throws IllegalArgumentException if {@code parallelism_hint} is not positive
"""
hasStatefulBolt = true;
return setBolt(id, new StatefulBoltExecutor<T>(bolt), parallelism_hint);
} | java | public <T extends State> BoltDeclarer setBolt(String id, IStatefulBolt<T> bolt, Number parallelism_hint) throws IllegalArgumentException {
hasStatefulBolt = true;
return setBolt(id, new StatefulBoltExecutor<T>(bolt), parallelism_hint);
} | [
"public",
"<",
"T",
"extends",
"State",
">",
"BoltDeclarer",
"setBolt",
"(",
"String",
"id",
",",
"IStatefulBolt",
"<",
"T",
">",
"bolt",
",",
"Number",
"parallelism_hint",
")",
"throws",
"IllegalArgumentException",
"{",
"hasStatefulBolt",
"=",
"true",
";",
"r... | Define a new bolt in this topology. This defines a stateful bolt, that requires its
state (of computation) to be saved. When this bolt is initialized, the {@link IStatefulBolt#initState(State)} method
is invoked after {@link IStatefulBolt#prepare(Map, TopologyContext, OutputCollector)} but before {@link IStatefulBolt#execute(Tuple)}
with its previously saved state.
<p>
The framework provides at-least once guarantee for the state updates. Bolts (both stateful and non-stateful) in a stateful topology
are expected to anchor the tuples while emitting and ack the input tuples once its processed.
</p>
@param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs.
@param bolt the stateful bolt
@param parallelism_hint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process somwehere around the cluster.
@return use the returned object to declare the inputs to this component
@throws IllegalArgumentException if {@code parallelism_hint} is not positive | [
"Define",
"a",
"new",
"bolt",
"in",
"this",
"topology",
".",
"This",
"defines",
"a",
"stateful",
"bolt",
"that",
"requires",
"its",
"state",
"(",
"of",
"computation",
")",
"to",
"be",
"saved",
".",
"When",
"this",
"bolt",
"is",
"initialized",
"the",
"{"
... | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/topology/TopologyBuilder.java#L278-L281 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/accesslayer/sql/SqlGeneratorDefaultImpl.java | SqlGeneratorDefaultImpl.getSelectMNStatement | public String getSelectMNStatement(String table, String[] selectColumns, String[] columns) {
"""
generate a SELECT-Statement for M:N indirection table
@param table the indirection table
@param selectColumns selected columns
@param columns for where
"""
SqlStatement sql;
String result;
sql = new SqlSelectMNStatement(table, selectColumns, columns, logger);
result = sql.getStatement();
if (logger.isDebugEnabled())
{
logger.debug("SQL:" + result);
}
return result;
} | java | public String getSelectMNStatement(String table, String[] selectColumns, String[] columns)
{
SqlStatement sql;
String result;
sql = new SqlSelectMNStatement(table, selectColumns, columns, logger);
result = sql.getStatement();
if (logger.isDebugEnabled())
{
logger.debug("SQL:" + result);
}
return result;
} | [
"public",
"String",
"getSelectMNStatement",
"(",
"String",
"table",
",",
"String",
"[",
"]",
"selectColumns",
",",
"String",
"[",
"]",
"columns",
")",
"{",
"SqlStatement",
"sql",
";",
"String",
"result",
";",
"sql",
"=",
"new",
"SqlSelectMNStatement",
"(",
"... | generate a SELECT-Statement for M:N indirection table
@param table the indirection table
@param selectColumns selected columns
@param columns for where | [
"generate",
"a",
"SELECT",
"-",
"Statement",
"for",
"M",
":",
"N",
"indirection",
"table"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/sql/SqlGeneratorDefaultImpl.java#L261-L274 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/preprocessor/serializer/NormalizerSerializer.java | NormalizerSerializer.write | public void write(@NonNull Normalizer normalizer, @NonNull String path) throws IOException {
"""
Serialize a normalizer to the given file path
@param normalizer the normalizer
@param path the destination file path
@throws IOException
"""
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(path))) {
write(normalizer, out);
}
} | java | public void write(@NonNull Normalizer normalizer, @NonNull String path) throws IOException {
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(path))) {
write(normalizer, out);
}
} | [
"public",
"void",
"write",
"(",
"@",
"NonNull",
"Normalizer",
"normalizer",
",",
"@",
"NonNull",
"String",
"path",
")",
"throws",
"IOException",
"{",
"try",
"(",
"OutputStream",
"out",
"=",
"new",
"BufferedOutputStream",
"(",
"new",
"FileOutputStream",
"(",
"p... | Serialize a normalizer to the given file path
@param normalizer the normalizer
@param path the destination file path
@throws IOException | [
"Serialize",
"a",
"normalizer",
"to",
"the",
"given",
"file",
"path"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/preprocessor/serializer/NormalizerSerializer.java#L59-L63 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/Comment.java | Comment.findInlineTagDelim | private static int findInlineTagDelim(String inlineText, int searchStart) {
"""
Recursively find the index of the closing '}' character for an inline tag
and return it. If it can't be found, return -1.
@param inlineText the text to search in.
@param searchStart the index of the place to start searching at.
@return the index of the closing '}' character for an inline tag.
If it can't be found, return -1.
"""
int delimEnd, nestedOpenBrace;
if ((delimEnd = inlineText.indexOf("}", searchStart)) == -1) {
return -1;
} else if (((nestedOpenBrace = inlineText.indexOf("{", searchStart)) != -1) &&
nestedOpenBrace < delimEnd){
//Found a nested open brace.
int nestedCloseBrace = findInlineTagDelim(inlineText, nestedOpenBrace + 1);
return (nestedCloseBrace != -1) ?
findInlineTagDelim(inlineText, nestedCloseBrace + 1) :
-1;
} else {
return delimEnd;
}
} | java | private static int findInlineTagDelim(String inlineText, int searchStart) {
int delimEnd, nestedOpenBrace;
if ((delimEnd = inlineText.indexOf("}", searchStart)) == -1) {
return -1;
} else if (((nestedOpenBrace = inlineText.indexOf("{", searchStart)) != -1) &&
nestedOpenBrace < delimEnd){
//Found a nested open brace.
int nestedCloseBrace = findInlineTagDelim(inlineText, nestedOpenBrace + 1);
return (nestedCloseBrace != -1) ?
findInlineTagDelim(inlineText, nestedCloseBrace + 1) :
-1;
} else {
return delimEnd;
}
} | [
"private",
"static",
"int",
"findInlineTagDelim",
"(",
"String",
"inlineText",
",",
"int",
"searchStart",
")",
"{",
"int",
"delimEnd",
",",
"nestedOpenBrace",
";",
"if",
"(",
"(",
"delimEnd",
"=",
"inlineText",
".",
"indexOf",
"(",
"\"}\"",
",",
"searchStart",... | Recursively find the index of the closing '}' character for an inline tag
and return it. If it can't be found, return -1.
@param inlineText the text to search in.
@param searchStart the index of the place to start searching at.
@return the index of the closing '}' character for an inline tag.
If it can't be found, return -1. | [
"Recursively",
"find",
"the",
"index",
"of",
"the",
"closing",
"}",
"character",
"for",
"an",
"inline",
"tag",
"and",
"return",
"it",
".",
"If",
"it",
"can",
"t",
"be",
"found",
"return",
"-",
"1",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/Comment.java#L405-L419 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/query/SqlPredicate.java | SqlPredicate.flattenCompound | static <T extends CompoundPredicate> T flattenCompound(Predicate predicateLeft, Predicate predicateRight, Class<T> klass) {
"""
Return a {@link CompoundPredicate}, possibly flattened if one or both arguments is an instance of
{@code CompoundPredicate}.
"""
// The following could have been achieved with {@link com.hazelcast.query.impl.predicates.FlatteningVisitor},
// however since we only care for 2-argument flattening, we can avoid constructing a visitor and its internals
// for each token pass at the cost of the following explicit code.
Predicate[] predicates;
if (klass.isInstance(predicateLeft) || klass.isInstance(predicateRight)) {
Predicate[] left = getSubPredicatesIfClass(predicateLeft, klass);
Predicate[] right = getSubPredicatesIfClass(predicateRight, klass);
predicates = new Predicate[left.length + right.length];
ArrayUtils.concat(left, right, predicates);
} else {
predicates = new Predicate[]{predicateLeft, predicateRight};
}
try {
CompoundPredicate compoundPredicate = klass.newInstance();
compoundPredicate.setPredicates(predicates);
return (T) compoundPredicate;
} catch (InstantiationException e) {
throw new RuntimeException(String.format("%s should have a public default constructor", klass.getName()));
} catch (IllegalAccessException e) {
throw new RuntimeException(String.format("%s should have a public default constructor", klass.getName()));
}
} | java | static <T extends CompoundPredicate> T flattenCompound(Predicate predicateLeft, Predicate predicateRight, Class<T> klass) {
// The following could have been achieved with {@link com.hazelcast.query.impl.predicates.FlatteningVisitor},
// however since we only care for 2-argument flattening, we can avoid constructing a visitor and its internals
// for each token pass at the cost of the following explicit code.
Predicate[] predicates;
if (klass.isInstance(predicateLeft) || klass.isInstance(predicateRight)) {
Predicate[] left = getSubPredicatesIfClass(predicateLeft, klass);
Predicate[] right = getSubPredicatesIfClass(predicateRight, klass);
predicates = new Predicate[left.length + right.length];
ArrayUtils.concat(left, right, predicates);
} else {
predicates = new Predicate[]{predicateLeft, predicateRight};
}
try {
CompoundPredicate compoundPredicate = klass.newInstance();
compoundPredicate.setPredicates(predicates);
return (T) compoundPredicate;
} catch (InstantiationException e) {
throw new RuntimeException(String.format("%s should have a public default constructor", klass.getName()));
} catch (IllegalAccessException e) {
throw new RuntimeException(String.format("%s should have a public default constructor", klass.getName()));
}
} | [
"static",
"<",
"T",
"extends",
"CompoundPredicate",
">",
"T",
"flattenCompound",
"(",
"Predicate",
"predicateLeft",
",",
"Predicate",
"predicateRight",
",",
"Class",
"<",
"T",
">",
"klass",
")",
"{",
"// The following could have been achieved with {@link com.hazelcast.que... | Return a {@link CompoundPredicate}, possibly flattened if one or both arguments is an instance of
{@code CompoundPredicate}. | [
"Return",
"a",
"{"
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/query/SqlPredicate.java#L371-L394 |
bullhorn/sdk-rest | src/main/java/com/bullhornsdk/data/api/helper/RestUriVariablesFactory.java | RestUriVariablesFactory.addModifyingUriVariables | private void addModifyingUriVariables(Map<String, String> uriVariables, BullhornEntityInfo entityInfo) {
"""
Adds common URI Variables for calls that are creating, updating, or deleting data.
Adds the execute form triggers url parameter if it has been configured.
@param uriVariables The variables map to add the flag to
@param entityInfo The bullhorn entity that is being modified by this call
"""
String bhRestToken = bullhornApiRest.getBhRestToken();
uriVariables.put(BH_REST_TOKEN, bhRestToken);
uriVariables.put(ENTITY_TYPE, entityInfo.getName());
uriVariables.put(EXECUTE_FORM_TRIGGERS, bullhornApiRest.getExecuteFormTriggers() ? "true" : "false");
} | java | private void addModifyingUriVariables(Map<String, String> uriVariables, BullhornEntityInfo entityInfo) {
String bhRestToken = bullhornApiRest.getBhRestToken();
uriVariables.put(BH_REST_TOKEN, bhRestToken);
uriVariables.put(ENTITY_TYPE, entityInfo.getName());
uriVariables.put(EXECUTE_FORM_TRIGGERS, bullhornApiRest.getExecuteFormTriggers() ? "true" : "false");
} | [
"private",
"void",
"addModifyingUriVariables",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"uriVariables",
",",
"BullhornEntityInfo",
"entityInfo",
")",
"{",
"String",
"bhRestToken",
"=",
"bullhornApiRest",
".",
"getBhRestToken",
"(",
")",
";",
"uriVariables",
... | Adds common URI Variables for calls that are creating, updating, or deleting data.
Adds the execute form triggers url parameter if it has been configured.
@param uriVariables The variables map to add the flag to
@param entityInfo The bullhorn entity that is being modified by this call | [
"Adds",
"common",
"URI",
"Variables",
"for",
"calls",
"that",
"are",
"creating",
"updating",
"or",
"deleting",
"data",
"."
] | train | https://github.com/bullhorn/sdk-rest/blob/0c75a141c768bb31510afc3a412c11bd101eca06/src/main/java/com/bullhornsdk/data/api/helper/RestUriVariablesFactory.java#L490-L495 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/PriorityQueue.java | PriorityQueue.siftUp | private void siftUp(int k, E x) {
"""
Inserts item x at position k, maintaining heap invariant by
promoting x up the tree until it is greater than or equal to
its parent, or is the root.
To simplify and speed up coercions and comparisons. the
Comparable and Comparator versions are separated into different
methods that are otherwise identical. (Similarly for siftDown.)
@param k the position to fill
@param x the item to insert
"""
if (comparator != null)
siftUpUsingComparator(k, x);
else
siftUpComparable(k, x);
} | java | private void siftUp(int k, E x) {
if (comparator != null)
siftUpUsingComparator(k, x);
else
siftUpComparable(k, x);
} | [
"private",
"void",
"siftUp",
"(",
"int",
"k",
",",
"E",
"x",
")",
"{",
"if",
"(",
"comparator",
"!=",
"null",
")",
"siftUpUsingComparator",
"(",
"k",
",",
"x",
")",
";",
"else",
"siftUpComparable",
"(",
"k",
",",
"x",
")",
";",
"}"
] | Inserts item x at position k, maintaining heap invariant by
promoting x up the tree until it is greater than or equal to
its parent, or is the root.
To simplify and speed up coercions and comparisons. the
Comparable and Comparator versions are separated into different
methods that are otherwise identical. (Similarly for siftDown.)
@param k the position to fill
@param x the item to insert | [
"Inserts",
"item",
"x",
"at",
"position",
"k",
"maintaining",
"heap",
"invariant",
"by",
"promoting",
"x",
"up",
"the",
"tree",
"until",
"it",
"is",
"greater",
"than",
"or",
"equal",
"to",
"its",
"parent",
"or",
"is",
"the",
"root",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/PriorityQueue.java#L643-L648 |
google/closure-compiler | src/com/google/javascript/jscomp/NodeUtil.java | NodeUtil.getNthSibling | private static Node getNthSibling(Node first, int index) {
"""
Given the first sibling, this returns the nth
sibling or null if no such sibling exists.
This is like "getChildAtIndex" but returns null for non-existent indexes.
"""
Node sibling = first;
while (index != 0 && sibling != null) {
sibling = sibling.getNext();
index--;
}
return sibling;
} | java | private static Node getNthSibling(Node first, int index) {
Node sibling = first;
while (index != 0 && sibling != null) {
sibling = sibling.getNext();
index--;
}
return sibling;
} | [
"private",
"static",
"Node",
"getNthSibling",
"(",
"Node",
"first",
",",
"int",
"index",
")",
"{",
"Node",
"sibling",
"=",
"first",
";",
"while",
"(",
"index",
"!=",
"0",
"&&",
"sibling",
"!=",
"null",
")",
"{",
"sibling",
"=",
"sibling",
".",
"getNext... | Given the first sibling, this returns the nth
sibling or null if no such sibling exists.
This is like "getChildAtIndex" but returns null for non-existent indexes. | [
"Given",
"the",
"first",
"sibling",
"this",
"returns",
"the",
"nth",
"sibling",
"or",
"null",
"if",
"no",
"such",
"sibling",
"exists",
".",
"This",
"is",
"like",
"getChildAtIndex",
"but",
"returns",
"null",
"for",
"non",
"-",
"existent",
"indexes",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/NodeUtil.java#L5197-L5204 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/OIDMap.java | OIDMap.addInternal | private static void addInternal(String name, ObjectIdentifier oid,
Class clazz) {
"""
Add attributes to the table. For internal use in the static
initializer.
"""
OIDInfo info = new OIDInfo(name, oid, clazz);
oidMap.put(oid, info);
nameMap.put(name, info);
} | java | private static void addInternal(String name, ObjectIdentifier oid,
Class clazz) {
OIDInfo info = new OIDInfo(name, oid, clazz);
oidMap.put(oid, info);
nameMap.put(name, info);
} | [
"private",
"static",
"void",
"addInternal",
"(",
"String",
"name",
",",
"ObjectIdentifier",
"oid",
",",
"Class",
"clazz",
")",
"{",
"OIDInfo",
"info",
"=",
"new",
"OIDInfo",
"(",
"name",
",",
"oid",
",",
"clazz",
")",
";",
"oidMap",
".",
"put",
"(",
"o... | Add attributes to the table. For internal use in the static
initializer. | [
"Add",
"attributes",
"to",
"the",
"table",
".",
"For",
"internal",
"use",
"in",
"the",
"static",
"initializer",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/OIDMap.java#L174-L179 |
sarl/sarl | main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/codemining/SARLCodeMiningProvider.java | SARLCodeMiningProvider.createImplicitFieldType | private void createImplicitFieldType(XtextResource resource, IAcceptor<? super ICodeMining> acceptor) {
"""
Add an annotation when the field's type is implicit and inferred by the SARL compiler.
@param resource the resource to parse.
@param acceptor the code mining acceptor.
"""
createImplicitVarValType(resource, acceptor, XtendField.class,
it -> it.getType(),
it -> {
final JvmField inferredField = (JvmField) this.jvmModelAssocitions.getPrimaryJvmElement(it);
if (inferredField == null || inferredField.getType() == null || inferredField.getType().eIsProxy()) {
return null;
}
return inferredField.getType().getSimpleName();
},
null,
() -> this.grammar.getAOPMemberAccess().getInitialValueAssignment_2_3_3_1());
} | java | private void createImplicitFieldType(XtextResource resource, IAcceptor<? super ICodeMining> acceptor) {
createImplicitVarValType(resource, acceptor, XtendField.class,
it -> it.getType(),
it -> {
final JvmField inferredField = (JvmField) this.jvmModelAssocitions.getPrimaryJvmElement(it);
if (inferredField == null || inferredField.getType() == null || inferredField.getType().eIsProxy()) {
return null;
}
return inferredField.getType().getSimpleName();
},
null,
() -> this.grammar.getAOPMemberAccess().getInitialValueAssignment_2_3_3_1());
} | [
"private",
"void",
"createImplicitFieldType",
"(",
"XtextResource",
"resource",
",",
"IAcceptor",
"<",
"?",
"super",
"ICodeMining",
">",
"acceptor",
")",
"{",
"createImplicitVarValType",
"(",
"resource",
",",
"acceptor",
",",
"XtendField",
".",
"class",
",",
"it",... | Add an annotation when the field's type is implicit and inferred by the SARL compiler.
@param resource the resource to parse.
@param acceptor the code mining acceptor. | [
"Add",
"an",
"annotation",
"when",
"the",
"field",
"s",
"type",
"is",
"implicit",
"and",
"inferred",
"by",
"the",
"SARL",
"compiler",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/codemining/SARLCodeMiningProvider.java#L233-L245 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/PathAndPackageVerifier.java | PathAndPackageVerifier.checkPathAndPackage | private boolean checkPathAndPackage(Path dir, JCTree pkgName) {
"""
/* Returns true if dir matches pkgName.
Examples:
(a/b/c, a.b.c) gives true
(i/j/k, i.x.k) gives false
Currently (x/a/b/c, a.b.c) also gives true. See JDK-8059598.
"""
Iterator<String> pathIter = new ParentIterator(dir);
Iterator<String> pkgIter = new EnclosingPkgIterator(pkgName);
while (pathIter.hasNext() && pkgIter.hasNext()) {
if (!pathIter.next().equals(pkgIter.next()))
return false;
}
return !pkgIter.hasNext(); /*&& !pathIter.hasNext() See JDK-8059598 */
} | java | private boolean checkPathAndPackage(Path dir, JCTree pkgName) {
Iterator<String> pathIter = new ParentIterator(dir);
Iterator<String> pkgIter = new EnclosingPkgIterator(pkgName);
while (pathIter.hasNext() && pkgIter.hasNext()) {
if (!pathIter.next().equals(pkgIter.next()))
return false;
}
return !pkgIter.hasNext(); /*&& !pathIter.hasNext() See JDK-8059598 */
} | [
"private",
"boolean",
"checkPathAndPackage",
"(",
"Path",
"dir",
",",
"JCTree",
"pkgName",
")",
"{",
"Iterator",
"<",
"String",
">",
"pathIter",
"=",
"new",
"ParentIterator",
"(",
"dir",
")",
";",
"Iterator",
"<",
"String",
">",
"pkgIter",
"=",
"new",
"Enc... | /* Returns true if dir matches pkgName.
Examples:
(a/b/c, a.b.c) gives true
(i/j/k, i.x.k) gives false
Currently (x/a/b/c, a.b.c) also gives true. See JDK-8059598. | [
"/",
"*",
"Returns",
"true",
"if",
"dir",
"matches",
"pkgName",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/PathAndPackageVerifier.java#L96-L104 |
alkacon/opencms-core | src-gwt/org/opencms/ade/sitemap/client/CmsSitemapTreeItem.java | CmsSitemapTreeItem.setAdditionalStyles | private static void setAdditionalStyles(CmsClientSitemapEntry entry, CmsListItemWidget itemWidget) {
"""
Sets the additional style to mark expired entries or those that have the hide in navigation property set.<p>
@param entry the sitemap entry
@param itemWidget the item widget
"""
if (!entry.isResleasedAndNotExpired()
|| ((CmsSitemapView.getInstance().getEditorMode() == EditorMode.navigation)
&& !entry.isDefaultFileReleased())) {
itemWidget.getContentPanel().addStyleName(
I_CmsSitemapLayoutBundle.INSTANCE.sitemapItemCss().expiredOrNotReleased());
} else {
itemWidget.getContentPanel().removeStyleName(
I_CmsSitemapLayoutBundle.INSTANCE.sitemapItemCss().expiredOrNotReleased());
}
if (entry.isHiddenNavigationEntry()) {
itemWidget.getContentPanel().addStyleName(
I_CmsSitemapLayoutBundle.INSTANCE.sitemapItemCss().hiddenNavEntry());
} else {
itemWidget.getContentPanel().removeStyleName(
I_CmsSitemapLayoutBundle.INSTANCE.sitemapItemCss().hiddenNavEntry());
}
} | java | private static void setAdditionalStyles(CmsClientSitemapEntry entry, CmsListItemWidget itemWidget) {
if (!entry.isResleasedAndNotExpired()
|| ((CmsSitemapView.getInstance().getEditorMode() == EditorMode.navigation)
&& !entry.isDefaultFileReleased())) {
itemWidget.getContentPanel().addStyleName(
I_CmsSitemapLayoutBundle.INSTANCE.sitemapItemCss().expiredOrNotReleased());
} else {
itemWidget.getContentPanel().removeStyleName(
I_CmsSitemapLayoutBundle.INSTANCE.sitemapItemCss().expiredOrNotReleased());
}
if (entry.isHiddenNavigationEntry()) {
itemWidget.getContentPanel().addStyleName(
I_CmsSitemapLayoutBundle.INSTANCE.sitemapItemCss().hiddenNavEntry());
} else {
itemWidget.getContentPanel().removeStyleName(
I_CmsSitemapLayoutBundle.INSTANCE.sitemapItemCss().hiddenNavEntry());
}
} | [
"private",
"static",
"void",
"setAdditionalStyles",
"(",
"CmsClientSitemapEntry",
"entry",
",",
"CmsListItemWidget",
"itemWidget",
")",
"{",
"if",
"(",
"!",
"entry",
".",
"isResleasedAndNotExpired",
"(",
")",
"||",
"(",
"(",
"CmsSitemapView",
".",
"getInstance",
"... | Sets the additional style to mark expired entries or those that have the hide in navigation property set.<p>
@param entry the sitemap entry
@param itemWidget the item widget | [
"Sets",
"the",
"additional",
"style",
"to",
"mark",
"expired",
"entries",
"or",
"those",
"that",
"have",
"the",
"hide",
"in",
"navigation",
"property",
"set",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/CmsSitemapTreeItem.java#L384-L402 |
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/lang/StringUtil.java | StringUtil.replaceIgnoreCase | public static String replaceIgnoreCase(String pSource, String pPattern, String pReplace) {
"""
Replaces a substring of a string with another string, ignoring case.
All matches are replaced.
@param pSource The source String
@param pPattern The pattern to replace
@param pReplace The new String to be inserted instead of the
replace String
@return The new String with the pattern replaced
@see #replace(String,String,String)
"""
if (pPattern.length() == 0) {
return pSource;// Special case: No pattern to replace
}
int match;
int offset = 0;
StringBuilder result = new StringBuilder();
while ((match = indexOfIgnoreCase(pSource, pPattern, offset)) != -1) {
result.append(pSource.substring(offset, match));
result.append(pReplace);
offset = match + pPattern.length();
}
result.append(pSource.substring(offset));
return result.toString();
} | java | public static String replaceIgnoreCase(String pSource, String pPattern, String pReplace) {
if (pPattern.length() == 0) {
return pSource;// Special case: No pattern to replace
}
int match;
int offset = 0;
StringBuilder result = new StringBuilder();
while ((match = indexOfIgnoreCase(pSource, pPattern, offset)) != -1) {
result.append(pSource.substring(offset, match));
result.append(pReplace);
offset = match + pPattern.length();
}
result.append(pSource.substring(offset));
return result.toString();
} | [
"public",
"static",
"String",
"replaceIgnoreCase",
"(",
"String",
"pSource",
",",
"String",
"pPattern",
",",
"String",
"pReplace",
")",
"{",
"if",
"(",
"pPattern",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
"pSource",
";",
"// Special case: No p... | Replaces a substring of a string with another string, ignoring case.
All matches are replaced.
@param pSource The source String
@param pPattern The pattern to replace
@param pReplace The new String to be inserted instead of the
replace String
@return The new String with the pattern replaced
@see #replace(String,String,String) | [
"Replaces",
"a",
"substring",
"of",
"a",
"string",
"with",
"another",
"string",
"ignoring",
"case",
".",
"All",
"matches",
"are",
"replaced",
"."
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/lang/StringUtil.java#L659-L674 |
webmetrics/browsermob-proxy | src/main/java/org/browsermob/proxy/selenium/CertificateCreator.java | CertificateCreator.mitmDuplicateCertificate | public static X509Certificate mitmDuplicateCertificate(final X509Certificate originalCert,
final PublicKey newPubKey,
final X509Certificate caCert,
final PrivateKey caPrivateKey)
throws CertificateParsingException, SignatureException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException {
"""
Convenience method for the most common case of certificate duplication.
This method will not add any custom extensions and won't copy the extensions 2.5.29.8 : Issuer Alternative Name,
2.5.29.18 : Issuer Alternative Name 2, 2.5.29.31 : CRL Distribution Point or 1.3.6.1.5.5.7.1.1 : Authority Info Access, if they are present.
@param originalCert
@param newPubKey
@param caCert
@param caPrivateKey
@return
@throws CertificateParsingException
@throws SignatureException
@throws InvalidKeyException
@throws CertificateExpiredException
@throws CertificateNotYetValidException
@throws CertificateException
@throws NoSuchAlgorithmException
@throws NoSuchProviderException
"""
return mitmDuplicateCertificate(originalCert, newPubKey, caCert, caPrivateKey, clientCertDefaultOidsNotToCopy);
} | java | public static X509Certificate mitmDuplicateCertificate(final X509Certificate originalCert,
final PublicKey newPubKey,
final X509Certificate caCert,
final PrivateKey caPrivateKey)
throws CertificateParsingException, SignatureException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException
{
return mitmDuplicateCertificate(originalCert, newPubKey, caCert, caPrivateKey, clientCertDefaultOidsNotToCopy);
} | [
"public",
"static",
"X509Certificate",
"mitmDuplicateCertificate",
"(",
"final",
"X509Certificate",
"originalCert",
",",
"final",
"PublicKey",
"newPubKey",
",",
"final",
"X509Certificate",
"caCert",
",",
"final",
"PrivateKey",
"caPrivateKey",
")",
"throws",
"CertificatePa... | Convenience method for the most common case of certificate duplication.
This method will not add any custom extensions and won't copy the extensions 2.5.29.8 : Issuer Alternative Name,
2.5.29.18 : Issuer Alternative Name 2, 2.5.29.31 : CRL Distribution Point or 1.3.6.1.5.5.7.1.1 : Authority Info Access, if they are present.
@param originalCert
@param newPubKey
@param caCert
@param caPrivateKey
@return
@throws CertificateParsingException
@throws SignatureException
@throws InvalidKeyException
@throws CertificateExpiredException
@throws CertificateNotYetValidException
@throws CertificateException
@throws NoSuchAlgorithmException
@throws NoSuchProviderException | [
"Convenience",
"method",
"for",
"the",
"most",
"common",
"case",
"of",
"certificate",
"duplication",
"."
] | train | https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/selenium/CertificateCreator.java#L333-L340 |
jingwei/krati | krati-main/src/retention/java/krati/retention/clock/SourceWaterMarksClock.java | SourceWaterMarksClock.updateHWMark | @Override
public synchronized Clock updateHWMark(String source, long hwm) {
"""
Save the high water mark of a given source.
@param source
@param hwm
"""
_sourceWaterMarks.saveHWMark(source, hwm);
return current();
} | java | @Override
public synchronized Clock updateHWMark(String source, long hwm) {
_sourceWaterMarks.saveHWMark(source, hwm);
return current();
} | [
"@",
"Override",
"public",
"synchronized",
"Clock",
"updateHWMark",
"(",
"String",
"source",
",",
"long",
"hwm",
")",
"{",
"_sourceWaterMarks",
".",
"saveHWMark",
"(",
"source",
",",
"hwm",
")",
";",
"return",
"current",
"(",
")",
";",
"}"
] | Save the high water mark of a given source.
@param source
@param hwm | [
"Save",
"the",
"high",
"water",
"mark",
"of",
"a",
"given",
"source",
"."
] | train | https://github.com/jingwei/krati/blob/1ca0f994a7b0c8215b827eac9aaf95789ec08d21/krati-main/src/retention/java/krati/retention/clock/SourceWaterMarksClock.java#L134-L138 |
wildfly/wildfly-core | cli/src/main/java/org/jboss/as/cli/parsing/ParserUtil.java | ParserUtil.parseCommandArgs | public static String parseCommandArgs(String commandLine, final CommandLineParser.CallbackHandler handler) throws CommandFormatException {
"""
Returns the string which was actually parsed with all the substitutions performed
"""
if(commandLine == null) {
return null;
}
final ParsingStateCallbackHandler callbackHandler = getCallbackHandler(handler);
return StateParser.parse(commandLine, callbackHandler, ArgumentListState.INSTANCE);
} | java | public static String parseCommandArgs(String commandLine, final CommandLineParser.CallbackHandler handler) throws CommandFormatException {
if(commandLine == null) {
return null;
}
final ParsingStateCallbackHandler callbackHandler = getCallbackHandler(handler);
return StateParser.parse(commandLine, callbackHandler, ArgumentListState.INSTANCE);
} | [
"public",
"static",
"String",
"parseCommandArgs",
"(",
"String",
"commandLine",
",",
"final",
"CommandLineParser",
".",
"CallbackHandler",
"handler",
")",
"throws",
"CommandFormatException",
"{",
"if",
"(",
"commandLine",
"==",
"null",
")",
"{",
"return",
"null",
... | Returns the string which was actually parsed with all the substitutions performed | [
"Returns",
"the",
"string",
"which",
"was",
"actually",
"parsed",
"with",
"all",
"the",
"substitutions",
"performed"
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/cli/src/main/java/org/jboss/as/cli/parsing/ParserUtil.java#L170-L176 |
graphhopper/graphhopper | api/src/main/java/com/graphhopper/util/Helper.java | Helper.keepIn | public static final double keepIn(double value, double min, double max) {
"""
This methods returns the value or min if too small or max if too big.
"""
return Math.max(min, Math.min(value, max));
} | java | public static final double keepIn(double value, double min, double max) {
return Math.max(min, Math.min(value, max));
} | [
"public",
"static",
"final",
"double",
"keepIn",
"(",
"double",
"value",
",",
"double",
"min",
",",
"double",
"max",
")",
"{",
"return",
"Math",
".",
"max",
"(",
"min",
",",
"Math",
".",
"min",
"(",
"value",
",",
"max",
")",
")",
";",
"}"
] | This methods returns the value or min if too small or max if too big. | [
"This",
"methods",
"returns",
"the",
"value",
"or",
"min",
"if",
"too",
"small",
"or",
"max",
"if",
"too",
"big",
"."
] | train | https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/Helper.java#L370-L372 |
radkovo/jStyleParser | src/main/java/cz/vutbr/web/css/CSSFactory.java | CSSFactory.assignDOM | public static final StyleMap assignDOM(Document doc, String encoding, NetworkProcessor network,
URL base, MediaSpec media, boolean useInheritance, final MatchCondition matchCond) {
"""
This is the same as {@link CSSFactory#assignDOM(Document, String, URL, MediaSpec, boolean)}
with the possibility of specifying a custom network processor for obtaining data from URL
resources.
@param doc
DOM tree
@param encoding
The default encoding used for the referenced style sheets
@param network
Custom network processor
@param base
Base URL against which all files are searched
@param media
Current media specification used for evaluating the media queries
@param useInheritance
Whether inheritance will be used to determine values
@param matchCond
The match condition to match the against.
@return Map between DOM element nodes and data structure containing CSS
information
"""
SourceData pair = new SourceData(base, network, media);
Traversal<StyleSheet> traversal = new CSSAssignTraversal(doc, encoding,
pair, NodeFilter.SHOW_ELEMENT);
StyleSheet style = (StyleSheet) getRuleFactory().createStyleSheet()
.unlock();
traversal.listTraversal(style);
Analyzer analyzer = new Analyzer(style);
if (matchCond != null) {
analyzer.registerMatchCondition(matchCond);
}
return analyzer.evaluateDOM(doc, media, useInheritance);
} | java | public static final StyleMap assignDOM(Document doc, String encoding, NetworkProcessor network,
URL base, MediaSpec media, boolean useInheritance, final MatchCondition matchCond) {
SourceData pair = new SourceData(base, network, media);
Traversal<StyleSheet> traversal = new CSSAssignTraversal(doc, encoding,
pair, NodeFilter.SHOW_ELEMENT);
StyleSheet style = (StyleSheet) getRuleFactory().createStyleSheet()
.unlock();
traversal.listTraversal(style);
Analyzer analyzer = new Analyzer(style);
if (matchCond != null) {
analyzer.registerMatchCondition(matchCond);
}
return analyzer.evaluateDOM(doc, media, useInheritance);
} | [
"public",
"static",
"final",
"StyleMap",
"assignDOM",
"(",
"Document",
"doc",
",",
"String",
"encoding",
",",
"NetworkProcessor",
"network",
",",
"URL",
"base",
",",
"MediaSpec",
"media",
",",
"boolean",
"useInheritance",
",",
"final",
"MatchCondition",
"matchCond... | This is the same as {@link CSSFactory#assignDOM(Document, String, URL, MediaSpec, boolean)}
with the possibility of specifying a custom network processor for obtaining data from URL
resources.
@param doc
DOM tree
@param encoding
The default encoding used for the referenced style sheets
@param network
Custom network processor
@param base
Base URL against which all files are searched
@param media
Current media specification used for evaluating the media queries
@param useInheritance
Whether inheritance will be used to determine values
@param matchCond
The match condition to match the against.
@return Map between DOM element nodes and data structure containing CSS
information | [
"This",
"is",
"the",
"same",
"as",
"{",
"@link",
"CSSFactory#assignDOM",
"(",
"Document",
"String",
"URL",
"MediaSpec",
"boolean",
")",
"}",
"with",
"the",
"possibility",
"of",
"specifying",
"a",
"custom",
"network",
"processor",
"for",
"obtaining",
"data",
"f... | train | https://github.com/radkovo/jStyleParser/blob/8ab049ac6866aa52c4d7deee25c9e294e7191957/src/main/java/cz/vutbr/web/css/CSSFactory.java#L732-L749 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/Factory.java | Factory.newInstance | public static <T> T newInstance(final Class<T> interfaz) {
"""
Given an interface, instantiate a class implementing that interface.
The classname to instantiate is obtained by looking in the runtime {@link Config configuration}, under the
bordertech.wcomponents.factory.impl.<interface name> key.
@param <T> the interface type.
@param interfaz the interface to instantiate an implementation for.
@return an Object which implements the given interface.
@throws SystemException if no implementing class is registered in the {@link Config configuration}.
"""
String classname = ConfigurationProperties.getFactoryImplementation(interfaz.getName());
if (classname == null) {
// Hmmm - this is bad. For the time being let's dump the parameters.
LOG.fatal("No implementing class for " + interfaz.getName());
LOG.fatal("There needs to be a parameter defined for " + ConfigurationProperties.FACTORY_PREFIX + interfaz.getName());
throw new SystemException("No implementing class for " + interfaz.getName() + "; "
+ "There needs to be a parameter defined for " + ConfigurationProperties.FACTORY_PREFIX + interfaz.getName());
}
try {
Class<T> clas = (Class<T>) Class.forName(classname.trim());
return clas.newInstance();
} catch (Exception ex) {
throw new SystemException("Failed to instantiate object of class " + classname, ex);
}
} | java | public static <T> T newInstance(final Class<T> interfaz) {
String classname = ConfigurationProperties.getFactoryImplementation(interfaz.getName());
if (classname == null) {
// Hmmm - this is bad. For the time being let's dump the parameters.
LOG.fatal("No implementing class for " + interfaz.getName());
LOG.fatal("There needs to be a parameter defined for " + ConfigurationProperties.FACTORY_PREFIX + interfaz.getName());
throw new SystemException("No implementing class for " + interfaz.getName() + "; "
+ "There needs to be a parameter defined for " + ConfigurationProperties.FACTORY_PREFIX + interfaz.getName());
}
try {
Class<T> clas = (Class<T>) Class.forName(classname.trim());
return clas.newInstance();
} catch (Exception ex) {
throw new SystemException("Failed to instantiate object of class " + classname, ex);
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"newInstance",
"(",
"final",
"Class",
"<",
"T",
">",
"interfaz",
")",
"{",
"String",
"classname",
"=",
"ConfigurationProperties",
".",
"getFactoryImplementation",
"(",
"interfaz",
".",
"getName",
"(",
")",
")",
";",
... | Given an interface, instantiate a class implementing that interface.
The classname to instantiate is obtained by looking in the runtime {@link Config configuration}, under the
bordertech.wcomponents.factory.impl.<interface name> key.
@param <T> the interface type.
@param interfaz the interface to instantiate an implementation for.
@return an Object which implements the given interface.
@throws SystemException if no implementing class is registered in the {@link Config configuration}. | [
"Given",
"an",
"interface",
"instantiate",
"a",
"class",
"implementing",
"that",
"interface",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/Factory.java#L46-L64 |
apiman/apiman | gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/LocalClientFactory.java | LocalClientFactory.createLocalClient | public JestClient createLocalClient(Map<String, String> config, String indexName, String defaultIndexName) {
"""
Creates a local client from a configuration map.
@param config the config from apiman.properties
@param indexName the name of the ES index
@param defaultIndexName the default ES index name
@return the ES client
"""
String clientLocClassName = config.get("client.class"); //$NON-NLS-1$
String clientLocFieldName = config.get("client.field"); //$NON-NLS-1$
return createLocalClient(clientLocClassName, clientLocFieldName, indexName, defaultIndexName);
} | java | public JestClient createLocalClient(Map<String, String> config, String indexName, String defaultIndexName) {
String clientLocClassName = config.get("client.class"); //$NON-NLS-1$
String clientLocFieldName = config.get("client.field"); //$NON-NLS-1$
return createLocalClient(clientLocClassName, clientLocFieldName, indexName, defaultIndexName);
} | [
"public",
"JestClient",
"createLocalClient",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"config",
",",
"String",
"indexName",
",",
"String",
"defaultIndexName",
")",
"{",
"String",
"clientLocClassName",
"=",
"config",
".",
"get",
"(",
"\"client.class\"",
")"... | Creates a local client from a configuration map.
@param config the config from apiman.properties
@param indexName the name of the ES index
@param defaultIndexName the default ES index name
@return the ES client | [
"Creates",
"a",
"local",
"client",
"from",
"a",
"configuration",
"map",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/LocalClientFactory.java#L59-L63 |
dain/leveldb | leveldb/src/main/java/org/iq80/leveldb/util/Slice.java | Slice.getBytes | public void getBytes(int index, Slice dst, int dstIndex, int length) {
"""
Transfers this buffer's data to the specified destination starting at
the specified absolute {@code index}.
@param dstIndex the first index of the destination
@param length the number of bytes to transfer
@throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0},
if the specified {@code dstIndex} is less than {@code 0},
if {@code index + length} is greater than
{@code this.capacity}, or
if {@code dstIndex + length} is greater than
{@code dst.capacity}
"""
getBytes(index, dst.data, dstIndex, length);
} | java | public void getBytes(int index, Slice dst, int dstIndex, int length)
{
getBytes(index, dst.data, dstIndex, length);
} | [
"public",
"void",
"getBytes",
"(",
"int",
"index",
",",
"Slice",
"dst",
",",
"int",
"dstIndex",
",",
"int",
"length",
")",
"{",
"getBytes",
"(",
"index",
",",
"dst",
".",
"data",
",",
"dstIndex",
",",
"length",
")",
";",
"}"
] | Transfers this buffer's data to the specified destination starting at
the specified absolute {@code index}.
@param dstIndex the first index of the destination
@param length the number of bytes to transfer
@throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0},
if the specified {@code dstIndex} is less than {@code 0},
if {@code index + length} is greater than
{@code this.capacity}, or
if {@code dstIndex + length} is greater than
{@code dst.capacity} | [
"Transfers",
"this",
"buffer",
"s",
"data",
"to",
"the",
"specified",
"destination",
"starting",
"at",
"the",
"specified",
"absolute",
"{",
"@code",
"index",
"}",
"."
] | train | https://github.com/dain/leveldb/blob/7994065b48eada2ef29e7fefd172c2ad1e0110eb/leveldb/src/main/java/org/iq80/leveldb/util/Slice.java#L189-L192 |
TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/ProxySettings.java | ProxySettings.setCredentials | public ProxySettings setCredentials(String id, String password) {
"""
Set credentials for authentication at the proxy server.
This method is an alias of {@link #setId(String) setId}{@code
(id).}{@link #setPassword(String) setPassword}{@code
(password)}.
@param id
The ID.
@param password
The password.
@return
{@code this} object.
"""
return setId(id).setPassword(password);
} | java | public ProxySettings setCredentials(String id, String password)
{
return setId(id).setPassword(password);
} | [
"public",
"ProxySettings",
"setCredentials",
"(",
"String",
"id",
",",
"String",
"password",
")",
"{",
"return",
"setId",
"(",
"id",
")",
".",
"setPassword",
"(",
"password",
")",
";",
"}"
] | Set credentials for authentication at the proxy server.
This method is an alias of {@link #setId(String) setId}{@code
(id).}{@link #setPassword(String) setPassword}{@code
(password)}.
@param id
The ID.
@param password
The password.
@return
{@code this} object. | [
"Set",
"credentials",
"for",
"authentication",
"at",
"the",
"proxy",
"server",
".",
"This",
"method",
"is",
"an",
"alias",
"of",
"{",
"@link",
"#setId",
"(",
"String",
")",
"setId",
"}",
"{",
"@code",
"(",
"id",
")",
".",
"}",
"{",
"@link",
"#setPasswo... | train | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/ProxySettings.java#L384-L387 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/util/BrokerHelper.java | BrokerHelper.getKeyValues | public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid, boolean convertToSql) throws PersistenceBrokerException {
"""
Return key Values of an Identity
@param cld
@param oid
@param convertToSql
@return Object[]
@throws PersistenceBrokerException
"""
FieldDescriptor[] pkFields = cld.getPkFields();
ValueContainer[] result = new ValueContainer[pkFields.length];
Object[] pkValues = oid.getPrimaryKeyValues();
try
{
for(int i = 0; i < result.length; i++)
{
FieldDescriptor fd = pkFields[i];
Object cv = pkValues[i];
if(convertToSql)
{
// BRJ : apply type and value mapping
cv = fd.getFieldConversion().javaToSql(cv);
}
result[i] = new ValueContainer(cv, fd.getJdbcType());
}
}
catch(Exception e)
{
throw new PersistenceBrokerException("Can't generate primary key values for given Identity " + oid, e);
}
return result;
} | java | public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid, boolean convertToSql) throws PersistenceBrokerException
{
FieldDescriptor[] pkFields = cld.getPkFields();
ValueContainer[] result = new ValueContainer[pkFields.length];
Object[] pkValues = oid.getPrimaryKeyValues();
try
{
for(int i = 0; i < result.length; i++)
{
FieldDescriptor fd = pkFields[i];
Object cv = pkValues[i];
if(convertToSql)
{
// BRJ : apply type and value mapping
cv = fd.getFieldConversion().javaToSql(cv);
}
result[i] = new ValueContainer(cv, fd.getJdbcType());
}
}
catch(Exception e)
{
throw new PersistenceBrokerException("Can't generate primary key values for given Identity " + oid, e);
}
return result;
} | [
"public",
"ValueContainer",
"[",
"]",
"getKeyValues",
"(",
"ClassDescriptor",
"cld",
",",
"Identity",
"oid",
",",
"boolean",
"convertToSql",
")",
"throws",
"PersistenceBrokerException",
"{",
"FieldDescriptor",
"[",
"]",
"pkFields",
"=",
"cld",
".",
"getPkFields",
... | Return key Values of an Identity
@param cld
@param oid
@param convertToSql
@return Object[]
@throws PersistenceBrokerException | [
"Return",
"key",
"Values",
"of",
"an",
"Identity"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/util/BrokerHelper.java#L203-L228 |
docusign/docusign-java-client | src/main/java/com/docusign/esign/api/AccountsApi.java | AccountsApi.getBrandResourcesByContentType | public void getBrandResourcesByContentType(String accountId, String brandId, String resourceContentType) throws ApiException {
"""
Returns the specified branding resource file.
@param accountId The external account number (int) or account ID Guid. (required)
@param brandId The unique identifier of a brand. (required)
@param resourceContentType (required)
@return void
"""
getBrandResourcesByContentType(accountId, brandId, resourceContentType, null);
} | java | public void getBrandResourcesByContentType(String accountId, String brandId, String resourceContentType) throws ApiException {
getBrandResourcesByContentType(accountId, brandId, resourceContentType, null);
} | [
"public",
"void",
"getBrandResourcesByContentType",
"(",
"String",
"accountId",
",",
"String",
"brandId",
",",
"String",
"resourceContentType",
")",
"throws",
"ApiException",
"{",
"getBrandResourcesByContentType",
"(",
"accountId",
",",
"brandId",
",",
"resourceContentTyp... | Returns the specified branding resource file.
@param accountId The external account number (int) or account ID Guid. (required)
@param brandId The unique identifier of a brand. (required)
@param resourceContentType (required)
@return void | [
"Returns",
"the",
"specified",
"branding",
"resource",
"file",
"."
] | train | https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/AccountsApi.java#L1298-L1300 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/layout/UIManager.java | UIManager.getRenderer | public static Renderer getRenderer(final WComponent component, final RenderContext context) {
"""
Retrieves a renderer which can renderer the given component to the context.
@param component the component to retrieve the renderer for.
@param context the render context.
@return an appropriate renderer for the component and context, or null if a suitable renderer could not be found.
"""
Class<? extends WComponent> clazz = component.getClass();
Duplet<String, Class<?>> key = new Duplet<String, Class<?>>(context.getRenderPackage(),
clazz);
Renderer renderer = INSTANCE.renderers.get(key);
if (renderer == null) {
renderer = INSTANCE.findRenderer(component, key);
} else if (renderer == NULL_RENDERER) {
return null;
}
return renderer;
} | java | public static Renderer getRenderer(final WComponent component, final RenderContext context) {
Class<? extends WComponent> clazz = component.getClass();
Duplet<String, Class<?>> key = new Duplet<String, Class<?>>(context.getRenderPackage(),
clazz);
Renderer renderer = INSTANCE.renderers.get(key);
if (renderer == null) {
renderer = INSTANCE.findRenderer(component, key);
} else if (renderer == NULL_RENDERER) {
return null;
}
return renderer;
} | [
"public",
"static",
"Renderer",
"getRenderer",
"(",
"final",
"WComponent",
"component",
",",
"final",
"RenderContext",
"context",
")",
"{",
"Class",
"<",
"?",
"extends",
"WComponent",
">",
"clazz",
"=",
"component",
".",
"getClass",
"(",
")",
";",
"Duplet",
... | Retrieves a renderer which can renderer the given component to the context.
@param component the component to retrieve the renderer for.
@param context the render context.
@return an appropriate renderer for the component and context, or null if a suitable renderer could not be found. | [
"Retrieves",
"a",
"renderer",
"which",
"can",
"renderer",
"the",
"given",
"component",
"to",
"the",
"context",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/layout/UIManager.java#L120-L134 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/PushbackReader.java | PushbackReader.unread | public void unread(char cbuf[], int off, int len) throws IOException {
"""
Pushes back a portion of an array of characters by copying it to the
front of the pushback buffer. After this method returns, the next
character to be read will have the value <code>cbuf[off]</code>, the
character after that will have the value <code>cbuf[off+1]</code>, and
so forth.
@param cbuf Character array
@param off Offset of first character to push back
@param len Number of characters to push back
@exception IOException If there is insufficient room in the pushback
buffer, or if some other I/O error occurs
"""
synchronized (lock) {
ensureOpen();
if (len > pos)
throw new IOException("Pushback buffer overflow");
pos -= len;
System.arraycopy(cbuf, off, buf, pos, len);
}
} | java | public void unread(char cbuf[], int off, int len) throws IOException {
synchronized (lock) {
ensureOpen();
if (len > pos)
throw new IOException("Pushback buffer overflow");
pos -= len;
System.arraycopy(cbuf, off, buf, pos, len);
}
} | [
"public",
"void",
"unread",
"(",
"char",
"cbuf",
"[",
"]",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"ensureOpen",
"(",
")",
";",
"if",
"(",
"len",
">",
"pos",
")",
"throw",
"new... | Pushes back a portion of an array of characters by copying it to the
front of the pushback buffer. After this method returns, the next
character to be read will have the value <code>cbuf[off]</code>, the
character after that will have the value <code>cbuf[off+1]</code>, and
so forth.
@param cbuf Character array
@param off Offset of first character to push back
@param len Number of characters to push back
@exception IOException If there is insufficient room in the pushback
buffer, or if some other I/O error occurs | [
"Pushes",
"back",
"a",
"portion",
"of",
"an",
"array",
"of",
"characters",
"by",
"copying",
"it",
"to",
"the",
"front",
"of",
"the",
"pushback",
"buffer",
".",
"After",
"this",
"method",
"returns",
"the",
"next",
"character",
"to",
"be",
"read",
"will",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/PushbackReader.java#L174-L182 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/kml/KMLGeometry.java | KMLGeometry.appendKMLCoordinates | public static void appendKMLCoordinates(Coordinate[] coords, StringBuilder sb) {
"""
Build a string represention to kml coordinates
Syntax :
<coordinates>...</coordinates> <!-- lon,lat[,alt] tuples -->
@param coords
"""
sb.append("<coordinates>");
for (int i = 0; i < coords.length; i++) {
Coordinate coord = coords[i];
sb.append(coord.x).append(",").append(coord.y);
if (!Double.isNaN(coord.z)) {
sb.append(",").append(coord.z);
}
if (i < coords.length - 1) {
sb.append(" ");
}
}
sb.append("</coordinates>");
} | java | public static void appendKMLCoordinates(Coordinate[] coords, StringBuilder sb) {
sb.append("<coordinates>");
for (int i = 0; i < coords.length; i++) {
Coordinate coord = coords[i];
sb.append(coord.x).append(",").append(coord.y);
if (!Double.isNaN(coord.z)) {
sb.append(",").append(coord.z);
}
if (i < coords.length - 1) {
sb.append(" ");
}
}
sb.append("</coordinates>");
} | [
"public",
"static",
"void",
"appendKMLCoordinates",
"(",
"Coordinate",
"[",
"]",
"coords",
",",
"StringBuilder",
"sb",
")",
"{",
"sb",
".",
"append",
"(",
"\"<coordinates>\"",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"coords",
".",
"l... | Build a string represention to kml coordinates
Syntax :
<coordinates>...</coordinates> <!-- lon,lat[,alt] tuples -->
@param coords | [
"Build",
"a",
"string",
"represention",
"to",
"kml",
"coordinates"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/kml/KMLGeometry.java#L282-L295 |
osmdroid/osmdroid | osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java | SphericalUtil.computeSignedArea | static double computeSignedArea(List<IGeoPoint> path, double radius) {
"""
Returns the signed area of a closed path on a sphere of given radius.
The computed area uses the same units as the radius squared.
Used by SphericalUtilTest.
"""
int size = path.size();
if (size < 3) { return 0; }
double total = 0;
IGeoPoint prev = path.get(size - 1);
double prevTanLat = tan((PI / 2 - toRadians(prev.getLatitude())) / 2);
double prevLng = toRadians(prev.getLongitude());
// For each edge, accumulate the signed area of the triangle formed by the North Pole
// and that edge ("polar triangle").
for (IGeoPoint point : path) {
double tanLat = tan((PI / 2 - toRadians(point.getLatitude())) / 2);
double lng = toRadians(point.getLongitude());
total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng);
prevTanLat = tanLat;
prevLng = lng;
}
return total * (radius * radius);
} | java | static double computeSignedArea(List<IGeoPoint> path, double radius) {
int size = path.size();
if (size < 3) { return 0; }
double total = 0;
IGeoPoint prev = path.get(size - 1);
double prevTanLat = tan((PI / 2 - toRadians(prev.getLatitude())) / 2);
double prevLng = toRadians(prev.getLongitude());
// For each edge, accumulate the signed area of the triangle formed by the North Pole
// and that edge ("polar triangle").
for (IGeoPoint point : path) {
double tanLat = tan((PI / 2 - toRadians(point.getLatitude())) / 2);
double lng = toRadians(point.getLongitude());
total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng);
prevTanLat = tanLat;
prevLng = lng;
}
return total * (radius * radius);
} | [
"static",
"double",
"computeSignedArea",
"(",
"List",
"<",
"IGeoPoint",
">",
"path",
",",
"double",
"radius",
")",
"{",
"int",
"size",
"=",
"path",
".",
"size",
"(",
")",
";",
"if",
"(",
"size",
"<",
"3",
")",
"{",
"return",
"0",
";",
"}",
"double"... | Returns the signed area of a closed path on a sphere of given radius.
The computed area uses the same units as the radius squared.
Used by SphericalUtilTest. | [
"Returns",
"the",
"signed",
"area",
"of",
"a",
"closed",
"path",
"on",
"a",
"sphere",
"of",
"given",
"radius",
".",
"The",
"computed",
"area",
"uses",
"the",
"same",
"units",
"as",
"the",
"radius",
"squared",
".",
"Used",
"by",
"SphericalUtilTest",
"."
] | train | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java#L323-L340 |
codescape/bitvunit | bitvunit-core/src/main/java/de/codescape/bitvunit/report/XmlReportWriter.java | XmlReportWriter.printViolations | private void printViolations(Violations violations, PrintWriter out) {
"""
Writes the part where all {@link Violations} that were found are listed.
@param violations {@link Violations} that were found
@param out target where the report is written to
"""
out.println("<Violations>");
for (Violation violation : violations.asList()) {
out.println("<Violation ruleName='" + violation.getRule().getName() + "' position='" + violation.getPosition() + "'>");
out.println("<Message><![CDATA[" + violation.getMessage() + "]]></Message>");
out.println("</Violation>");
}
out.println("</Violations>");
} | java | private void printViolations(Violations violations, PrintWriter out) {
out.println("<Violations>");
for (Violation violation : violations.asList()) {
out.println("<Violation ruleName='" + violation.getRule().getName() + "' position='" + violation.getPosition() + "'>");
out.println("<Message><![CDATA[" + violation.getMessage() + "]]></Message>");
out.println("</Violation>");
}
out.println("</Violations>");
} | [
"private",
"void",
"printViolations",
"(",
"Violations",
"violations",
",",
"PrintWriter",
"out",
")",
"{",
"out",
".",
"println",
"(",
"\"<Violations>\"",
")",
";",
"for",
"(",
"Violation",
"violation",
":",
"violations",
".",
"asList",
"(",
")",
")",
"{",
... | Writes the part where all {@link Violations} that were found are listed.
@param violations {@link Violations} that were found
@param out target where the report is written to | [
"Writes",
"the",
"part",
"where",
"all",
"{",
"@link",
"Violations",
"}",
"that",
"were",
"found",
"are",
"listed",
"."
] | train | https://github.com/codescape/bitvunit/blob/cef6d9af60d684e41294981c10b6d92c8f063a4e/bitvunit-core/src/main/java/de/codescape/bitvunit/report/XmlReportWriter.java#L62-L70 |
RestComm/sip-servlets | sip-servlets-application-router/src/main/java/org/mobicents/servlet/sip/router/DefaultApplicationRouter.java | DefaultApplicationRouter.init | public void init() {
"""
load the configuration file as defined in appendix C of JSR289
"""
defaultApplicationRouterParser.init();
try {
defaultSipApplicationRouterInfos = defaultApplicationRouterParser.parse();
} catch (ParseException e) {
log.fatal("Impossible to parse the default application router configuration file", e);
throw new IllegalArgumentException("Impossible to parse the default application router configuration file", e);
}
} | java | public void init() {
defaultApplicationRouterParser.init();
try {
defaultSipApplicationRouterInfos = defaultApplicationRouterParser.parse();
} catch (ParseException e) {
log.fatal("Impossible to parse the default application router configuration file", e);
throw new IllegalArgumentException("Impossible to parse the default application router configuration file", e);
}
} | [
"public",
"void",
"init",
"(",
")",
"{",
"defaultApplicationRouterParser",
".",
"init",
"(",
")",
";",
"try",
"{",
"defaultSipApplicationRouterInfos",
"=",
"defaultApplicationRouterParser",
".",
"parse",
"(",
")",
";",
"}",
"catch",
"(",
"ParseException",
"e",
"... | load the configuration file as defined in appendix C of JSR289 | [
"load",
"the",
"configuration",
"file",
"as",
"defined",
"in",
"appendix",
"C",
"of",
"JSR289"
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-application-router/src/main/java/org/mobicents/servlet/sip/router/DefaultApplicationRouter.java#L442-L450 |
versionone/VersionOne.SDK.Java.ObjectModel | src/main/java/com/versionone/om/Project.java | Project.getTotalDetailEstimate | public Double getTotalDetailEstimate(WorkitemFilter filter, boolean includeChildProjects) {
"""
Count the total detail estimate for all workitems in this project
optionally filtered.
@param filter Criteria to filter workitems on.
@param includeChildProjects If true, include open sub projects, otherwise
only include this project.
@return total detail estimate for all workitems in this project
optionally filtered.
"""
filter = (filter != null) ? filter : new WorkitemFilter();
return getRollup("Workitems", "DetailEstimate", filter,
includeChildProjects);
} | java | public Double getTotalDetailEstimate(WorkitemFilter filter, boolean includeChildProjects) {
filter = (filter != null) ? filter : new WorkitemFilter();
return getRollup("Workitems", "DetailEstimate", filter,
includeChildProjects);
} | [
"public",
"Double",
"getTotalDetailEstimate",
"(",
"WorkitemFilter",
"filter",
",",
"boolean",
"includeChildProjects",
")",
"{",
"filter",
"=",
"(",
"filter",
"!=",
"null",
")",
"?",
"filter",
":",
"new",
"WorkitemFilter",
"(",
")",
";",
"return",
"getRollup",
... | Count the total detail estimate for all workitems in this project
optionally filtered.
@param filter Criteria to filter workitems on.
@param includeChildProjects If true, include open sub projects, otherwise
only include this project.
@return total detail estimate for all workitems in this project
optionally filtered. | [
"Count",
"the",
"total",
"detail",
"estimate",
"for",
"all",
"workitems",
"in",
"this",
"project",
"optionally",
"filtered",
"."
] | train | https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/om/Project.java#L1101-L1106 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/lang/Assert.java | Assert.notBlank | public static String notBlank(String text, String errorMsgTemplate, Object... params) throws IllegalArgumentException {
"""
检查给定字符串是否为空白(null、空串或只包含空白符),为空抛出 {@link IllegalArgumentException}
<pre class="code">
Assert.notBlank(name, "Name must not be blank");
</pre>
@param text 被检查字符串
@param errorMsgTemplate 错误消息模板,变量使用{}表示
@param params 参数
@return 非空字符串
@see StrUtil#isNotBlank(CharSequence)
@throws IllegalArgumentException 被检查字符串为空白
"""
if (StrUtil.isBlank(text)) {
throw new IllegalArgumentException(StrUtil.format(errorMsgTemplate, params));
}
return text;
} | java | public static String notBlank(String text, String errorMsgTemplate, Object... params) throws IllegalArgumentException {
if (StrUtil.isBlank(text)) {
throw new IllegalArgumentException(StrUtil.format(errorMsgTemplate, params));
}
return text;
} | [
"public",
"static",
"String",
"notBlank",
"(",
"String",
"text",
",",
"String",
"errorMsgTemplate",
",",
"Object",
"...",
"params",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"StrUtil",
".",
"isBlank",
"(",
"text",
")",
")",
"{",
"throw",
"ne... | 检查给定字符串是否为空白(null、空串或只包含空白符),为空抛出 {@link IllegalArgumentException}
<pre class="code">
Assert.notBlank(name, "Name must not be blank");
</pre>
@param text 被检查字符串
@param errorMsgTemplate 错误消息模板,变量使用{}表示
@param params 参数
@return 非空字符串
@see StrUtil#isNotBlank(CharSequence)
@throws IllegalArgumentException 被检查字符串为空白 | [
"检查给定字符串是否为空白(null、空串或只包含空白符),为空抛出",
"{",
"@link",
"IllegalArgumentException",
"}"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/lang/Assert.java#L205-L210 |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/ProtoUtils.java | ProtoUtils.getBuildMethod | private static MethodRef getBuildMethod(Descriptor descriptor) {
"""
Returns the {@link MethodRef} for the generated build method.
"""
TypeInfo message = messageRuntimeType(descriptor);
TypeInfo builder = builderRuntimeType(descriptor);
return MethodRef.createInstanceMethod(
builder, new Method("build", message.type(), NO_METHOD_ARGS))
.asNonNullable();
} | java | private static MethodRef getBuildMethod(Descriptor descriptor) {
TypeInfo message = messageRuntimeType(descriptor);
TypeInfo builder = builderRuntimeType(descriptor);
return MethodRef.createInstanceMethod(
builder, new Method("build", message.type(), NO_METHOD_ARGS))
.asNonNullable();
} | [
"private",
"static",
"MethodRef",
"getBuildMethod",
"(",
"Descriptor",
"descriptor",
")",
"{",
"TypeInfo",
"message",
"=",
"messageRuntimeType",
"(",
"descriptor",
")",
";",
"TypeInfo",
"builder",
"=",
"builderRuntimeType",
"(",
"descriptor",
")",
";",
"return",
"... | Returns the {@link MethodRef} for the generated build method. | [
"Returns",
"the",
"{"
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/ProtoUtils.java#L1289-L1295 |
OpenLiberty/open-liberty | dev/com.ibm.ws.repository/src/com/ibm/ws/repository/transport/client/RestClient.java | RestClient.deleteAttachment | @Override
public void deleteAttachment(final String assetId, final String attachmentId) throws IOException, RequestFailureException {
"""
Delete an attachment from an asset
@param assetId
The ID of the asset containing the attachment
@param attachmentId
The ID of the attachment to delete
@return <code>true</code> if the delete was successful
@throws IOException
@throws RequestFailureException
"""
HttpURLConnection connection = createHttpURLConnectionToMassive("/assets/"
+ assetId + "/attachments/" + attachmentId);
connection.setRequestMethod("DELETE");
testResponseCode(connection, true);
} | java | @Override
public void deleteAttachment(final String assetId, final String attachmentId) throws IOException, RequestFailureException {
HttpURLConnection connection = createHttpURLConnectionToMassive("/assets/"
+ assetId + "/attachments/" + attachmentId);
connection.setRequestMethod("DELETE");
testResponseCode(connection, true);
} | [
"@",
"Override",
"public",
"void",
"deleteAttachment",
"(",
"final",
"String",
"assetId",
",",
"final",
"String",
"attachmentId",
")",
"throws",
"IOException",
",",
"RequestFailureException",
"{",
"HttpURLConnection",
"connection",
"=",
"createHttpURLConnectionToMassive",... | Delete an attachment from an asset
@param assetId
The ID of the asset containing the attachment
@param attachmentId
The ID of the attachment to delete
@return <code>true</code> if the delete was successful
@throws IOException
@throws RequestFailureException | [
"Delete",
"an",
"attachment",
"from",
"an",
"asset"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository/src/com/ibm/ws/repository/transport/client/RestClient.java#L528-L534 |
liyiorg/weixin-popular | src/main/java/weixin/popular/api/SnsAPI.java | SnsAPI.oauth2AccessToken | public static SnsToken oauth2AccessToken(String appid,String secret,String code) {
"""
通过code换取网页授权access_token
@param appid appid
@param secret secret
@param code code
@return SnsToken
"""
HttpUriRequest httpUriRequest = RequestBuilder.post()
.setUri(BASE_URI + "/sns/oauth2/access_token")
.addParameter("appid", appid)
.addParameter("secret", secret)
.addParameter("code", code)
.addParameter("grant_type", "authorization_code")
.build();
return LocalHttpClient.executeJsonResult(httpUriRequest,SnsToken.class);
} | java | public static SnsToken oauth2AccessToken(String appid,String secret,String code){
HttpUriRequest httpUriRequest = RequestBuilder.post()
.setUri(BASE_URI + "/sns/oauth2/access_token")
.addParameter("appid", appid)
.addParameter("secret", secret)
.addParameter("code", code)
.addParameter("grant_type", "authorization_code")
.build();
return LocalHttpClient.executeJsonResult(httpUriRequest,SnsToken.class);
} | [
"public",
"static",
"SnsToken",
"oauth2AccessToken",
"(",
"String",
"appid",
",",
"String",
"secret",
",",
"String",
"code",
")",
"{",
"HttpUriRequest",
"httpUriRequest",
"=",
"RequestBuilder",
".",
"post",
"(",
")",
".",
"setUri",
"(",
"BASE_URI",
"+",
"\"/sn... | 通过code换取网页授权access_token
@param appid appid
@param secret secret
@param code code
@return SnsToken | [
"通过code换取网页授权access_token"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/SnsAPI.java#L34-L43 |
Erudika/para | para-core/src/main/java/com/erudika/para/utils/RegistryUtils.java | RegistryUtils.putValue | public static void putValue(String registryName, String key, Object value) {
"""
Add a specific value to a registry. If the registry doesn't exist yet, create it.
@param registryName the name of the registry.
@param key the unique key corresponding to the value to insert (typically an appid).
@param value the value to add to the registry.
"""
if (StringUtils.isBlank(registryName) || StringUtils.isBlank(key) || value == null) {
return;
}
Sysprop registryObject = readRegistryObject(registryName);
if (registryObject == null) {
registryObject = new Sysprop(getRegistryID(registryName));
registryObject.addProperty(key, value);
CoreUtils.getInstance().getDao().create(REGISTRY_APP_ID, registryObject);
} else {
registryObject.addProperty(key, value);
CoreUtils.getInstance().getDao().update(REGISTRY_APP_ID, registryObject);
}
} | java | public static void putValue(String registryName, String key, Object value) {
if (StringUtils.isBlank(registryName) || StringUtils.isBlank(key) || value == null) {
return;
}
Sysprop registryObject = readRegistryObject(registryName);
if (registryObject == null) {
registryObject = new Sysprop(getRegistryID(registryName));
registryObject.addProperty(key, value);
CoreUtils.getInstance().getDao().create(REGISTRY_APP_ID, registryObject);
} else {
registryObject.addProperty(key, value);
CoreUtils.getInstance().getDao().update(REGISTRY_APP_ID, registryObject);
}
} | [
"public",
"static",
"void",
"putValue",
"(",
"String",
"registryName",
",",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"registryName",
")",
"||",
"StringUtils",
".",
"isBlank",
"(",
"key",
")",
"||",
... | Add a specific value to a registry. If the registry doesn't exist yet, create it.
@param registryName the name of the registry.
@param key the unique key corresponding to the value to insert (typically an appid).
@param value the value to add to the registry. | [
"Add",
"a",
"specific",
"value",
"to",
"a",
"registry",
".",
"If",
"the",
"registry",
"doesn",
"t",
"exist",
"yet",
"create",
"it",
"."
] | train | https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-core/src/main/java/com/erudika/para/utils/RegistryUtils.java#L44-L57 |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/LPARemoveParameter.java | LPARemoveParameter.perform | @Override
public void perform() throws PortalException {
"""
Remove the parameter from a channel in both the ILF and PLF using the appropriate mechanisms
for incorporated nodes versus owned nodes.
"""
// push the change into the PLF
if (nodeId.startsWith(Constants.FRAGMENT_ID_USER_PREFIX)) {
// we are dealing with an incorporated node
ParameterEditManager.removeParmEditDirective(nodeId, name, person);
} else {
// node owned by user so add parameter child directly
Document plf = RDBMDistributedLayoutStore.getPLF(person);
Element plfNode = plf.getElementById(nodeId);
removeParameterChild(plfNode, name);
}
// push the change into the ILF
removeParameterChild(ilfNode, name);
} | java | @Override
public void perform() throws PortalException {
// push the change into the PLF
if (nodeId.startsWith(Constants.FRAGMENT_ID_USER_PREFIX)) {
// we are dealing with an incorporated node
ParameterEditManager.removeParmEditDirective(nodeId, name, person);
} else {
// node owned by user so add parameter child directly
Document plf = RDBMDistributedLayoutStore.getPLF(person);
Element plfNode = plf.getElementById(nodeId);
removeParameterChild(plfNode, name);
}
// push the change into the ILF
removeParameterChild(ilfNode, name);
} | [
"@",
"Override",
"public",
"void",
"perform",
"(",
")",
"throws",
"PortalException",
"{",
"// push the change into the PLF",
"if",
"(",
"nodeId",
".",
"startsWith",
"(",
"Constants",
".",
"FRAGMENT_ID_USER_PREFIX",
")",
")",
"{",
"// we are dealing with an incorporated ... | Remove the parameter from a channel in both the ILF and PLF using the appropriate mechanisms
for incorporated nodes versus owned nodes. | [
"Remove",
"the",
"parameter",
"from",
"a",
"channel",
"in",
"both",
"the",
"ILF",
"and",
"PLF",
"using",
"the",
"appropriate",
"mechanisms",
"for",
"incorporated",
"nodes",
"versus",
"owned",
"nodes",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/LPARemoveParameter.java#L40-L54 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetsInner.java | VirtualMachineScaleSetsInner.beginReimageAllAsync | public Observable<OperationStatusResponseInner> beginReimageAllAsync(String resourceGroupName, String vmScaleSetName) {
"""
Reimages all the disks ( including data disks ) in the virtual machines in a VM scale set. This operation is only supported for managed disks.
@param resourceGroupName The name of the resource group.
@param vmScaleSetName The name of the VM scale set.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the OperationStatusResponseInner object
"""
return beginReimageAllWithServiceResponseAsync(resourceGroupName, vmScaleSetName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() {
@Override
public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) {
return response.body();
}
});
} | java | public Observable<OperationStatusResponseInner> beginReimageAllAsync(String resourceGroupName, String vmScaleSetName) {
return beginReimageAllWithServiceResponseAsync(resourceGroupName, vmScaleSetName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() {
@Override
public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"OperationStatusResponseInner",
">",
"beginReimageAllAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"vmScaleSetName",
")",
"{",
"return",
"beginReimageAllWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"vmScaleSetName",
")",
... | Reimages all the disks ( including data disks ) in the virtual machines in a VM scale set. This operation is only supported for managed disks.
@param resourceGroupName The name of the resource group.
@param vmScaleSetName The name of the VM scale set.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the OperationStatusResponseInner object | [
"Reimages",
"all",
"the",
"disks",
"(",
"including",
"data",
"disks",
")",
"in",
"the",
"virtual",
"machines",
"in",
"a",
"VM",
"scale",
"set",
".",
"This",
"operation",
"is",
"only",
"supported",
"for",
"managed",
"disks",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetsInner.java#L3393-L3400 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/text/StrBuilder.java | StrBuilder.appendFixedWidthPadLeft | public StrBuilder appendFixedWidthPadLeft(final int value, final int width, final char padChar) {
"""
Appends an object to the builder padding on the left to a fixed width.
The <code>String.valueOf</code> of the <code>int</code> value is used.
If the formatted value is larger than the length, the left hand side is lost.
@param value the value to append
@param width the fixed field width, zero or negative has no effect
@param padChar the pad character to use
@return this, to enable chaining
"""
return appendFixedWidthPadLeft(String.valueOf(value), width, padChar);
} | java | public StrBuilder appendFixedWidthPadLeft(final int value, final int width, final char padChar) {
return appendFixedWidthPadLeft(String.valueOf(value), width, padChar);
} | [
"public",
"StrBuilder",
"appendFixedWidthPadLeft",
"(",
"final",
"int",
"value",
",",
"final",
"int",
"width",
",",
"final",
"char",
"padChar",
")",
"{",
"return",
"appendFixedWidthPadLeft",
"(",
"String",
".",
"valueOf",
"(",
"value",
")",
",",
"width",
",",
... | Appends an object to the builder padding on the left to a fixed width.
The <code>String.valueOf</code> of the <code>int</code> value is used.
If the formatted value is larger than the length, the left hand side is lost.
@param value the value to append
@param width the fixed field width, zero or negative has no effect
@param padChar the pad character to use
@return this, to enable chaining | [
"Appends",
"an",
"object",
"to",
"the",
"builder",
"padding",
"on",
"the",
"left",
"to",
"a",
"fixed",
"width",
".",
"The",
"<code",
">",
"String",
".",
"valueOf<",
"/",
"code",
">",
"of",
"the",
"<code",
">",
"int<",
"/",
"code",
">",
"value",
"is",... | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrBuilder.java#L1534-L1536 |
javafxports/javafxmobile-plugin | src/main/java/org/javafxports/jfxmobile/plugin/android/task/ApkBuilder.java | ApkBuilder.addZipFile | public void addZipFile(File zipFile) throws ApkCreationException, SealedApkException,
DuplicateFileException {
"""
Adds the content from a zip file.
All file keep the same path inside the archive.
@param zipFile the zip File.
@throws ApkCreationException if an error occurred
@throws SealedApkException if the APK is already sealed.
@throws DuplicateFileException if a file conflicts with another already added to the APK
at the same location inside the APK archive.
"""
if (mIsSealed) {
throw new SealedApkException("APK is already sealed");
}
try {
verbosePrintln("%s:", zipFile);
// reset the filter with this input.
mNullFilter.reset(zipFile);
// ask the builder to add the content of the file.
FileInputStream fis = new FileInputStream(zipFile);
mBuilder.writeZip(fis, mNullFilter);
fis.close();
} catch (DuplicateFileException e) {
mBuilder.cleanUp();
throw e;
} catch (Exception e) {
mBuilder.cleanUp();
throw new ApkCreationException(e, "Failed to add %s", zipFile);
}
} | java | public void addZipFile(File zipFile) throws ApkCreationException, SealedApkException,
DuplicateFileException {
if (mIsSealed) {
throw new SealedApkException("APK is already sealed");
}
try {
verbosePrintln("%s:", zipFile);
// reset the filter with this input.
mNullFilter.reset(zipFile);
// ask the builder to add the content of the file.
FileInputStream fis = new FileInputStream(zipFile);
mBuilder.writeZip(fis, mNullFilter);
fis.close();
} catch (DuplicateFileException e) {
mBuilder.cleanUp();
throw e;
} catch (Exception e) {
mBuilder.cleanUp();
throw new ApkCreationException(e, "Failed to add %s", zipFile);
}
} | [
"public",
"void",
"addZipFile",
"(",
"File",
"zipFile",
")",
"throws",
"ApkCreationException",
",",
"SealedApkException",
",",
"DuplicateFileException",
"{",
"if",
"(",
"mIsSealed",
")",
"{",
"throw",
"new",
"SealedApkException",
"(",
"\"APK is already sealed\"",
")",... | Adds the content from a zip file.
All file keep the same path inside the archive.
@param zipFile the zip File.
@throws ApkCreationException if an error occurred
@throws SealedApkException if the APK is already sealed.
@throws DuplicateFileException if a file conflicts with another already added to the APK
at the same location inside the APK archive. | [
"Adds",
"the",
"content",
"from",
"a",
"zip",
"file",
".",
"All",
"file",
"keep",
"the",
"same",
"path",
"inside",
"the",
"archive",
"."
] | train | https://github.com/javafxports/javafxmobile-plugin/blob/a9bef513b7e1bfa85f9a668226e6943c6d9f847f/src/main/java/org/javafxports/jfxmobile/plugin/android/task/ApkBuilder.java#L579-L602 |
docusign/docusign-java-client | src/main/java/com/docusign/esign/api/EnvelopesApi.java | EnvelopesApi.listTabs | public Tabs listTabs(String accountId, String envelopeId, String recipientId) throws ApiException {
"""
Gets the tabs information for a signer or sign-in-person recipient in an envelope.
Retrieves information about the tabs associated with a recipient in a draft envelope.
@param accountId The external account number (int) or account ID Guid. (required)
@param envelopeId The envelopeId Guid of the envelope being accessed. (required)
@param recipientId The ID of the recipient being accessed. (required)
@return Tabs
"""
return listTabs(accountId, envelopeId, recipientId, null);
} | java | public Tabs listTabs(String accountId, String envelopeId, String recipientId) throws ApiException {
return listTabs(accountId, envelopeId, recipientId, null);
} | [
"public",
"Tabs",
"listTabs",
"(",
"String",
"accountId",
",",
"String",
"envelopeId",
",",
"String",
"recipientId",
")",
"throws",
"ApiException",
"{",
"return",
"listTabs",
"(",
"accountId",
",",
"envelopeId",
",",
"recipientId",
",",
"null",
")",
";",
"}"
] | Gets the tabs information for a signer or sign-in-person recipient in an envelope.
Retrieves information about the tabs associated with a recipient in a draft envelope.
@param accountId The external account number (int) or account ID Guid. (required)
@param envelopeId The envelopeId Guid of the envelope being accessed. (required)
@param recipientId The ID of the recipient being accessed. (required)
@return Tabs | [
"Gets",
"the",
"tabs",
"information",
"for",
"a",
"signer",
"or",
"sign",
"-",
"in",
"-",
"person",
"recipient",
"in",
"an",
"envelope",
".",
"Retrieves",
"information",
"about",
"the",
"tabs",
"associated",
"with",
"a",
"recipient",
"in",
"a",
"draft",
"e... | train | https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/EnvelopesApi.java#L4255-L4257 |
artikcloud/artikcloud-java | src/main/java/cloud/artik/api/RulesApi.java | RulesApi.updateRule | public RuleEnvelope updateRule(String ruleId, RuleUpdateInfo ruleInfo) throws ApiException {
"""
Update Rule
Update an existing Rule
@param ruleId Rule ID. (required)
@param ruleInfo Rule object that needs to be updated (required)
@return RuleEnvelope
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
"""
ApiResponse<RuleEnvelope> resp = updateRuleWithHttpInfo(ruleId, ruleInfo);
return resp.getData();
} | java | public RuleEnvelope updateRule(String ruleId, RuleUpdateInfo ruleInfo) throws ApiException {
ApiResponse<RuleEnvelope> resp = updateRuleWithHttpInfo(ruleId, ruleInfo);
return resp.getData();
} | [
"public",
"RuleEnvelope",
"updateRule",
"(",
"String",
"ruleId",
",",
"RuleUpdateInfo",
"ruleInfo",
")",
"throws",
"ApiException",
"{",
"ApiResponse",
"<",
"RuleEnvelope",
">",
"resp",
"=",
"updateRuleWithHttpInfo",
"(",
"ruleId",
",",
"ruleInfo",
")",
";",
"retur... | Update Rule
Update an existing Rule
@param ruleId Rule ID. (required)
@param ruleInfo Rule object that needs to be updated (required)
@return RuleEnvelope
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"Update",
"Rule",
"Update",
"an",
"existing",
"Rule"
] | train | https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/RulesApi.java#L498-L501 |
grails/grails-core | grails-encoder/src/main/groovy/org/grails/charsequences/CharSequences.java | CharSequences.getChars | public static void getChars(CharSequence csq, int srcBegin, int srcEnd, char dst[], int dstBegin) {
"""
Provides an optimized way to copy CharSequence content to target array.
Uses getChars method available on String, StringBuilder and StringBuffer classes.
Characters are copied from the source sequence <code>csq</code> into the
destination character array <code>dst</code>. The first character to
be copied is at index <code>srcBegin</code>; the last character to
be copied is at index <code>srcEnd-1</code>. The total number of
characters to be copied is <code>srcEnd-srcBegin</code>. The
characters are copied into the subarray of <code>dst</code> starting
at index <code>dstBegin</code> and ending at index:
<p><blockquote><pre>
dstbegin + (srcEnd-srcBegin) - 1
</pre></blockquote>
@param csq the source CharSequence instance.
@param srcBegin start copying at this offset.
@param srcEnd stop copying at this offset.
@param dst the array to copy the data into.
@param dstBegin offset into <code>dst</code>.
@throws NullPointerException if <code>dst</code> is
<code>null</code>.
@throws IndexOutOfBoundsException if any of the following is true:
<ul>
<li><code>srcBegin</code> is negative
<li><code>dstBegin</code> is negative
<li>the <code>srcBegin</code> argument is greater than
the <code>srcEnd</code> argument.
<li><code>srcEnd</code> is greater than
<code>this.length()</code>.
<li><code>dstBegin+srcEnd-srcBegin</code> is greater than
<code>dst.length</code>
</ul>
"""
final Class<?> csqClass = csq.getClass();
if (csqClass == String.class) {
((String)csq).getChars(srcBegin, srcEnd, dst, dstBegin);
}
else if (csqClass == StringBuffer.class) {
((StringBuffer)csq).getChars(srcBegin, srcEnd, dst, dstBegin);
}
else if (csqClass == StringBuilder.class) {
((StringBuilder)csq).getChars(srcBegin, srcEnd, dst, dstBegin);
}
else if (csq instanceof CharArrayAccessible) {
((CharArrayAccessible)csq).getChars(srcBegin, srcEnd, dst, dstBegin);
}
else {
String str = csq.subSequence(srcBegin, srcEnd).toString();
str.getChars(0, str.length(), dst, dstBegin);
}
} | java | public static void getChars(CharSequence csq, int srcBegin, int srcEnd, char dst[], int dstBegin) {
final Class<?> csqClass = csq.getClass();
if (csqClass == String.class) {
((String)csq).getChars(srcBegin, srcEnd, dst, dstBegin);
}
else if (csqClass == StringBuffer.class) {
((StringBuffer)csq).getChars(srcBegin, srcEnd, dst, dstBegin);
}
else if (csqClass == StringBuilder.class) {
((StringBuilder)csq).getChars(srcBegin, srcEnd, dst, dstBegin);
}
else if (csq instanceof CharArrayAccessible) {
((CharArrayAccessible)csq).getChars(srcBegin, srcEnd, dst, dstBegin);
}
else {
String str = csq.subSequence(srcBegin, srcEnd).toString();
str.getChars(0, str.length(), dst, dstBegin);
}
} | [
"public",
"static",
"void",
"getChars",
"(",
"CharSequence",
"csq",
",",
"int",
"srcBegin",
",",
"int",
"srcEnd",
",",
"char",
"dst",
"[",
"]",
",",
"int",
"dstBegin",
")",
"{",
"final",
"Class",
"<",
"?",
">",
"csqClass",
"=",
"csq",
".",
"getClass",
... | Provides an optimized way to copy CharSequence content to target array.
Uses getChars method available on String, StringBuilder and StringBuffer classes.
Characters are copied from the source sequence <code>csq</code> into the
destination character array <code>dst</code>. The first character to
be copied is at index <code>srcBegin</code>; the last character to
be copied is at index <code>srcEnd-1</code>. The total number of
characters to be copied is <code>srcEnd-srcBegin</code>. The
characters are copied into the subarray of <code>dst</code> starting
at index <code>dstBegin</code> and ending at index:
<p><blockquote><pre>
dstbegin + (srcEnd-srcBegin) - 1
</pre></blockquote>
@param csq the source CharSequence instance.
@param srcBegin start copying at this offset.
@param srcEnd stop copying at this offset.
@param dst the array to copy the data into.
@param dstBegin offset into <code>dst</code>.
@throws NullPointerException if <code>dst</code> is
<code>null</code>.
@throws IndexOutOfBoundsException if any of the following is true:
<ul>
<li><code>srcBegin</code> is negative
<li><code>dstBegin</code> is negative
<li>the <code>srcBegin</code> argument is greater than
the <code>srcEnd</code> argument.
<li><code>srcEnd</code> is greater than
<code>this.length()</code>.
<li><code>dstBegin+srcEnd-srcBegin</code> is greater than
<code>dst.length</code>
</ul> | [
"Provides",
"an",
"optimized",
"way",
"to",
"copy",
"CharSequence",
"content",
"to",
"target",
"array",
".",
"Uses",
"getChars",
"method",
"available",
"on",
"String",
"StringBuilder",
"and",
"StringBuffer",
"classes",
"."
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-encoder/src/main/groovy/org/grails/charsequences/CharSequences.java#L150-L168 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/glove/AbstractCoOccurrences.java | AbstractCoOccurrences.getCoOccurrenceCount | public double getCoOccurrenceCount(@NonNull T element1, @NonNull T element2) {
"""
This method returns cooccurrence distance weights for two SequenceElements
@param element1
@param element2
@return distance weight
"""
return coOccurrenceCounts.getCount(element1, element2);
} | java | public double getCoOccurrenceCount(@NonNull T element1, @NonNull T element2) {
return coOccurrenceCounts.getCount(element1, element2);
} | [
"public",
"double",
"getCoOccurrenceCount",
"(",
"@",
"NonNull",
"T",
"element1",
",",
"@",
"NonNull",
"T",
"element2",
")",
"{",
"return",
"coOccurrenceCounts",
".",
"getCount",
"(",
"element1",
",",
"element2",
")",
";",
"}"
] | This method returns cooccurrence distance weights for two SequenceElements
@param element1
@param element2
@return distance weight | [
"This",
"method",
"returns",
"cooccurrence",
"distance",
"weights",
"for",
"two",
"SequenceElements"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/glove/AbstractCoOccurrences.java#L94-L96 |
pip-services3-java/pip-services3-commons-java | src/org/pipservices3/commons/refer/References.java | References.getOptional | public List<Object> getOptional(Object locator) {
"""
Gets all component references that match specified locator.
@param locator the locator to find references by.
@return a list with matching component references or empty list if nothing
was found.
"""
try {
return find(Object.class, locator, false);
} catch (Exception ex) {
return new ArrayList<Object>();
}
} | java | public List<Object> getOptional(Object locator) {
try {
return find(Object.class, locator, false);
} catch (Exception ex) {
return new ArrayList<Object>();
}
} | [
"public",
"List",
"<",
"Object",
">",
"getOptional",
"(",
"Object",
"locator",
")",
"{",
"try",
"{",
"return",
"find",
"(",
"Object",
".",
"class",
",",
"locator",
",",
"false",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"return",
"new... | Gets all component references that match specified locator.
@param locator the locator to find references by.
@return a list with matching component references or empty list if nothing
was found. | [
"Gets",
"all",
"component",
"references",
"that",
"match",
"specified",
"locator",
"."
] | train | https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/refer/References.java#L226-L232 |
sarl/sarl | main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/SARLEclipsePlugin.java | SARLEclipsePlugin.openError | public void openError(Shell shell, String title, String message, Throwable exception) {
"""
Display an error dialog and log the error.
@param shell the parent container.
@param title the title of the dialog box.
@param message the message to display into the dialog box.
@param exception the exception to be logged.
@since 0.6
@see #log(Throwable)
"""
final Throwable ex = (exception != null) ? Throwables.getRootCause(exception) : null;
if (ex != null) {
log(ex);
final IStatus status = createStatus(IStatus.ERROR, message, ex);
ErrorDialog.openError(shell, title, message, status);
} else {
MessageDialog.openError(shell, title, message);
}
} | java | public void openError(Shell shell, String title, String message, Throwable exception) {
final Throwable ex = (exception != null) ? Throwables.getRootCause(exception) : null;
if (ex != null) {
log(ex);
final IStatus status = createStatus(IStatus.ERROR, message, ex);
ErrorDialog.openError(shell, title, message, status);
} else {
MessageDialog.openError(shell, title, message);
}
} | [
"public",
"void",
"openError",
"(",
"Shell",
"shell",
",",
"String",
"title",
",",
"String",
"message",
",",
"Throwable",
"exception",
")",
"{",
"final",
"Throwable",
"ex",
"=",
"(",
"exception",
"!=",
"null",
")",
"?",
"Throwables",
".",
"getRootCause",
"... | Display an error dialog and log the error.
@param shell the parent container.
@param title the title of the dialog box.
@param message the message to display into the dialog box.
@param exception the exception to be logged.
@since 0.6
@see #log(Throwable) | [
"Display",
"an",
"error",
"dialog",
"and",
"log",
"the",
"error",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/SARLEclipsePlugin.java#L375-L384 |
Impetus/Kundera | src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java | CassandraSchemaManager.getCompositeIdEmbeddables | private void getCompositeIdEmbeddables(EmbeddableType embeddable, List compositeEmbeddables, MetamodelImpl metaModel) {
"""
Gets the composite id embeddables.
@param embeddable
the embeddable
@param compositeEmbeddables
the composite embeddables
@param metaModel
the meta model
@return the composite id embeddables
"""
compositeEmbeddables.add(embeddable.getJavaType().getSimpleName());
for (Object column : embeddable.getAttributes())
{
Attribute columnAttribute = (Attribute) column;
Field f = (Field) columnAttribute.getJavaMember();
if (columnAttribute.getJavaType().isAnnotationPresent(Embeddable.class))
{
getCompositeIdEmbeddables(metaModel.embeddable(columnAttribute.getJavaType()), compositeEmbeddables,
metaModel);
}
}
} | java | private void getCompositeIdEmbeddables(EmbeddableType embeddable, List compositeEmbeddables, MetamodelImpl metaModel)
{
compositeEmbeddables.add(embeddable.getJavaType().getSimpleName());
for (Object column : embeddable.getAttributes())
{
Attribute columnAttribute = (Attribute) column;
Field f = (Field) columnAttribute.getJavaMember();
if (columnAttribute.getJavaType().isAnnotationPresent(Embeddable.class))
{
getCompositeIdEmbeddables(metaModel.embeddable(columnAttribute.getJavaType()), compositeEmbeddables,
metaModel);
}
}
} | [
"private",
"void",
"getCompositeIdEmbeddables",
"(",
"EmbeddableType",
"embeddable",
",",
"List",
"compositeEmbeddables",
",",
"MetamodelImpl",
"metaModel",
")",
"{",
"compositeEmbeddables",
".",
"add",
"(",
"embeddable",
".",
"getJavaType",
"(",
")",
".",
"getSimpleN... | Gets the composite id embeddables.
@param embeddable
the embeddable
@param compositeEmbeddables
the composite embeddables
@param metaModel
the meta model
@return the composite id embeddables | [
"Gets",
"the",
"composite",
"id",
"embeddables",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java#L872-L888 |
javalite/activejdbc | activejdbc/src/main/java/org/javalite/activejdbc/validation/ValidatorAdapter.java | ValidatorAdapter.formatMessage | @Override
public String formatMessage(Locale locale, Object ... params) {
"""
Provides default implementation, will look for a property in resource bundle, using set message as key.
If property in resource bundle not found, treats message verbatim.
@param locale locale to use, or null for default locale.
@param params parameters in case a message is parametrized.
@return formatted message.
"""
return Messages.message(message, locale, params);
} | java | @Override
public String formatMessage(Locale locale, Object ... params) {
return Messages.message(message, locale, params);
} | [
"@",
"Override",
"public",
"String",
"formatMessage",
"(",
"Locale",
"locale",
",",
"Object",
"...",
"params",
")",
"{",
"return",
"Messages",
".",
"message",
"(",
"message",
",",
"locale",
",",
"params",
")",
";",
"}"
] | Provides default implementation, will look for a property in resource bundle, using set message as key.
If property in resource bundle not found, treats message verbatim.
@param locale locale to use, or null for default locale.
@param params parameters in case a message is parametrized.
@return formatted message. | [
"Provides",
"default",
"implementation",
"will",
"look",
"for",
"a",
"property",
"in",
"resource",
"bundle",
"using",
"set",
"message",
"as",
"key",
".",
"If",
"property",
"in",
"resource",
"bundle",
"not",
"found",
"treats",
"message",
"verbatim",
"."
] | train | https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/validation/ValidatorAdapter.java#L28-L31 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpx/Record.java | Record.getCurrency | public Number getCurrency(int field) throws MPXJException {
"""
Accessor method used to retrieve an Number instance representing the
contents of an individual field. If the field does not exist in the
record, null is returned.
@param field the index number of the field to be retrieved
@return the value of the required field
@throws MPXJException normally thrown when parsing fails
"""
Number result;
if ((field < m_fields.length) && (m_fields[field].length() != 0))
{
try
{
result = m_formats.getCurrencyFormat().parse(m_fields[field]);
}
catch (ParseException ex)
{
throw new MPXJException("Failed to parse currency", ex);
}
}
else
{
result = null;
}
return (result);
} | java | public Number getCurrency(int field) throws MPXJException
{
Number result;
if ((field < m_fields.length) && (m_fields[field].length() != 0))
{
try
{
result = m_formats.getCurrencyFormat().parse(m_fields[field]);
}
catch (ParseException ex)
{
throw new MPXJException("Failed to parse currency", ex);
}
}
else
{
result = null;
}
return (result);
} | [
"public",
"Number",
"getCurrency",
"(",
"int",
"field",
")",
"throws",
"MPXJException",
"{",
"Number",
"result",
";",
"if",
"(",
"(",
"field",
"<",
"m_fields",
".",
"length",
")",
"&&",
"(",
"m_fields",
"[",
"field",
"]",
".",
"length",
"(",
")",
"!=",... | Accessor method used to retrieve an Number instance representing the
contents of an individual field. If the field does not exist in the
record, null is returned.
@param field the index number of the field to be retrieved
@return the value of the required field
@throws MPXJException normally thrown when parsing fails | [
"Accessor",
"method",
"used",
"to",
"retrieve",
"an",
"Number",
"instance",
"representing",
"the",
"contents",
"of",
"an",
"individual",
"field",
".",
"If",
"the",
"field",
"does",
"not",
"exist",
"in",
"the",
"record",
"null",
"is",
"returned",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/Record.java#L418-L440 |
jbundle/jbundle | thin/base/db/base/src/main/java/org/jbundle/thin/base/db/mem/base/PKeyArea.java | PKeyArea.doSeek | public BaseBuffer doSeek(String strSeekSign, FieldTable table, KeyAreaInfo keyArea) throws DBException {
"""
Read the record that matches this record's temp key area.<p>
WARNING - This method changes the current record's buffer.
@param strSeekSign - Seek sign:<p>
<pre>
"=" - Look for the first match.
"==" - Look for an exact match (On non-unique keys, must match primary key also).
">" - Look for the first record greater than this.
">=" - Look for the first record greater than or equal to this.
"<" - Look for the first record less than or equal to this.
"<=" - Look for the first record less than or equal to this.
</pre>
returns: success/failure (true/false).
@param table The basetable.
@param keyArea The key area.
@exception DBException File exception.
"""
return null;
} | java | public BaseBuffer doSeek(String strSeekSign, FieldTable table, KeyAreaInfo keyArea) throws DBException
{
return null;
} | [
"public",
"BaseBuffer",
"doSeek",
"(",
"String",
"strSeekSign",
",",
"FieldTable",
"table",
",",
"KeyAreaInfo",
"keyArea",
")",
"throws",
"DBException",
"{",
"return",
"null",
";",
"}"
] | Read the record that matches this record's temp key area.<p>
WARNING - This method changes the current record's buffer.
@param strSeekSign - Seek sign:<p>
<pre>
"=" - Look for the first match.
"==" - Look for an exact match (On non-unique keys, must match primary key also).
">" - Look for the first record greater than this.
">=" - Look for the first record greater than or equal to this.
"<" - Look for the first record less than or equal to this.
"<=" - Look for the first record less than or equal to this.
</pre>
returns: success/failure (true/false).
@param table The basetable.
@param keyArea The key area.
@exception DBException File exception. | [
"Read",
"the",
"record",
"that",
"matches",
"this",
"record",
"s",
"temp",
"key",
"area",
".",
"<p",
">",
"WARNING",
"-",
"This",
"method",
"changes",
"the",
"current",
"record",
"s",
"buffer",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/db/base/src/main/java/org/jbundle/thin/base/db/mem/base/PKeyArea.java#L149-L152 |
aws/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/util/TimingInfo.java | TimingInfo.newTimingInfoFullSupport | public static TimingInfo newTimingInfoFullSupport(long startTimeNano, long endTimeNano) {
"""
Returns a {@link TimingInfoFullSupport} based on the given
start and end time in nanosecond, ignoring the wall clock time.
@param startTimeNano start time in nanosecond
@param endTimeNano end time in nanosecond
"""
return new TimingInfoFullSupport(null, startTimeNano, Long.valueOf(endTimeNano));
} | java | public static TimingInfo newTimingInfoFullSupport(long startTimeNano, long endTimeNano) {
return new TimingInfoFullSupport(null, startTimeNano, Long.valueOf(endTimeNano));
} | [
"public",
"static",
"TimingInfo",
"newTimingInfoFullSupport",
"(",
"long",
"startTimeNano",
",",
"long",
"endTimeNano",
")",
"{",
"return",
"new",
"TimingInfoFullSupport",
"(",
"null",
",",
"startTimeNano",
",",
"Long",
".",
"valueOf",
"(",
"endTimeNano",
")",
")"... | Returns a {@link TimingInfoFullSupport} based on the given
start and end time in nanosecond, ignoring the wall clock time.
@param startTimeNano start time in nanosecond
@param endTimeNano end time in nanosecond | [
"Returns",
"a",
"{",
"@link",
"TimingInfoFullSupport",
"}",
"based",
"on",
"the",
"given",
"start",
"and",
"end",
"time",
"in",
"nanosecond",
"ignoring",
"the",
"wall",
"clock",
"time",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/util/TimingInfo.java#L116-L118 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java | AppServiceEnvironmentsInner.getMultiRolePool | public WorkerPoolResourceInner getMultiRolePool(String resourceGroupName, String name) {
"""
Get properties of a multi-role pool.
Get properties of a multi-role pool.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@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 WorkerPoolResourceInner object if successful.
"""
return getMultiRolePoolWithServiceResponseAsync(resourceGroupName, name).toBlocking().single().body();
} | java | public WorkerPoolResourceInner getMultiRolePool(String resourceGroupName, String name) {
return getMultiRolePoolWithServiceResponseAsync(resourceGroupName, name).toBlocking().single().body();
} | [
"public",
"WorkerPoolResourceInner",
"getMultiRolePool",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
")",
"{",
"return",
"getMultiRolePoolWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
... | Get properties of a multi-role pool.
Get properties of a multi-role pool.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@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 WorkerPoolResourceInner object if successful. | [
"Get",
"properties",
"of",
"a",
"multi",
"-",
"role",
"pool",
".",
"Get",
"properties",
"of",
"a",
"multi",
"-",
"role",
"pool",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L2182-L2184 |
apache/incubator-druid | processing/src/main/java/org/apache/druid/segment/DimensionHandlerUtils.java | DimensionHandlerUtils.createColumnSelectorPlus | public static <ColumnSelectorStrategyClass extends ColumnSelectorStrategy> ColumnSelectorPlus<ColumnSelectorStrategyClass> createColumnSelectorPlus(
ColumnSelectorStrategyFactory<ColumnSelectorStrategyClass> strategyFactory,
DimensionSpec dimensionSpec,
ColumnSelectorFactory cursor
) {
"""
Convenience function equivalent to calling
{@link #createColumnSelectorPluses(ColumnSelectorStrategyFactory, List, ColumnSelectorFactory)} with a singleton
list of dimensionSpecs and then retrieving the only element in the returned array.
@param <ColumnSelectorStrategyClass> The strategy type created by the provided strategy factory.
@param strategyFactory A factory provided by query engines that generates type-handling strategies
@param dimensionSpec column to generate a ColumnSelectorPlus object for
@param cursor Used to create value selectors for columns.
@return A ColumnSelectorPlus object
"""
return createColumnSelectorPluses(strategyFactory, ImmutableList.of(dimensionSpec), cursor)[0];
} | java | public static <ColumnSelectorStrategyClass extends ColumnSelectorStrategy> ColumnSelectorPlus<ColumnSelectorStrategyClass> createColumnSelectorPlus(
ColumnSelectorStrategyFactory<ColumnSelectorStrategyClass> strategyFactory,
DimensionSpec dimensionSpec,
ColumnSelectorFactory cursor
)
{
return createColumnSelectorPluses(strategyFactory, ImmutableList.of(dimensionSpec), cursor)[0];
} | [
"public",
"static",
"<",
"ColumnSelectorStrategyClass",
"extends",
"ColumnSelectorStrategy",
">",
"ColumnSelectorPlus",
"<",
"ColumnSelectorStrategyClass",
">",
"createColumnSelectorPlus",
"(",
"ColumnSelectorStrategyFactory",
"<",
"ColumnSelectorStrategyClass",
">",
"strategyFacto... | Convenience function equivalent to calling
{@link #createColumnSelectorPluses(ColumnSelectorStrategyFactory, List, ColumnSelectorFactory)} with a singleton
list of dimensionSpecs and then retrieving the only element in the returned array.
@param <ColumnSelectorStrategyClass> The strategy type created by the provided strategy factory.
@param strategyFactory A factory provided by query engines that generates type-handling strategies
@param dimensionSpec column to generate a ColumnSelectorPlus object for
@param cursor Used to create value selectors for columns.
@return A ColumnSelectorPlus object | [
"Convenience",
"function",
"equivalent",
"to",
"calling",
"{",
"@link",
"#createColumnSelectorPluses",
"(",
"ColumnSelectorStrategyFactory",
"List",
"ColumnSelectorFactory",
")",
"}",
"with",
"a",
"singleton",
"list",
"of",
"dimensionSpecs",
"and",
"then",
"retrieving",
... | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/processing/src/main/java/org/apache/druid/segment/DimensionHandlerUtils.java#L117-L124 |
elki-project/elki | addons/3dpc/src/main/java/de/lmu/ifi/dbs/elki/visualization/parallel3d/layout/SimpleCircularMSTLayout3DPC.java | SimpleCircularMSTLayout3DPC.computePositions | public static void computePositions(Node node, int depth, double aoff, double awid, int maxdepth) {
"""
Compute the layout positions
@param node Node to start with
@param depth Depth of the node
@param aoff Angular offset
@param awid Angular width
@param maxdepth Maximum depth (used for radius computations)
"""
double r = depth / (maxdepth - 1.);
node.x = FastMath.sin(aoff + awid * .5) * r;
node.y = FastMath.cos(aoff + awid * .5) * r;
double cpos = aoff;
double cwid = awid / node.weight;
for(Node c : node.children) {
computePositions(c, depth + 1, cpos, cwid * c.weight, maxdepth);
cpos += cwid * c.weight;
}
} | java | public static void computePositions(Node node, int depth, double aoff, double awid, int maxdepth) {
double r = depth / (maxdepth - 1.);
node.x = FastMath.sin(aoff + awid * .5) * r;
node.y = FastMath.cos(aoff + awid * .5) * r;
double cpos = aoff;
double cwid = awid / node.weight;
for(Node c : node.children) {
computePositions(c, depth + 1, cpos, cwid * c.weight, maxdepth);
cpos += cwid * c.weight;
}
} | [
"public",
"static",
"void",
"computePositions",
"(",
"Node",
"node",
",",
"int",
"depth",
",",
"double",
"aoff",
",",
"double",
"awid",
",",
"int",
"maxdepth",
")",
"{",
"double",
"r",
"=",
"depth",
"/",
"(",
"maxdepth",
"-",
"1.",
")",
";",
"node",
... | Compute the layout positions
@param node Node to start with
@param depth Depth of the node
@param aoff Angular offset
@param awid Angular width
@param maxdepth Maximum depth (used for radius computations) | [
"Compute",
"the",
"layout",
"positions"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/3dpc/src/main/java/de/lmu/ifi/dbs/elki/visualization/parallel3d/layout/SimpleCircularMSTLayout3DPC.java#L114-L125 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/HftpFileSystem.java | HftpFileSystem.openConnection | protected HttpURLConnection openConnection(String path, String query)
throws IOException {
"""
Open an HTTP connection to the namenode to read file data and metadata.
@param path The path component of the URL
@param query The query component of the URL
"""
try {
final URL url = new URI("http", null, nnAddr.getAddress().getHostAddress(),
nnAddr.getPort(), path, query, null).toURL();
if (LOG.isTraceEnabled()) {
LOG.trace("url=" + url);
}
return (HttpURLConnection)url.openConnection();
} catch (URISyntaxException e) {
throw (IOException)new IOException().initCause(e);
}
} | java | protected HttpURLConnection openConnection(String path, String query)
throws IOException {
try {
final URL url = new URI("http", null, nnAddr.getAddress().getHostAddress(),
nnAddr.getPort(), path, query, null).toURL();
if (LOG.isTraceEnabled()) {
LOG.trace("url=" + url);
}
return (HttpURLConnection)url.openConnection();
} catch (URISyntaxException e) {
throw (IOException)new IOException().initCause(e);
}
} | [
"protected",
"HttpURLConnection",
"openConnection",
"(",
"String",
"path",
",",
"String",
"query",
")",
"throws",
"IOException",
"{",
"try",
"{",
"final",
"URL",
"url",
"=",
"new",
"URI",
"(",
"\"http\"",
",",
"null",
",",
"nnAddr",
".",
"getAddress",
"(",
... | Open an HTTP connection to the namenode to read file data and metadata.
@param path The path component of the URL
@param query The query component of the URL | [
"Open",
"an",
"HTTP",
"connection",
"to",
"the",
"namenode",
"to",
"read",
"file",
"data",
"and",
"metadata",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/HftpFileSystem.java#L133-L145 |
phax/ph-javacc-maven-plugin | src/main/java/org/codehaus/mojo/javacc/UrlUtils.java | UrlUtils.getResourceRoot | public static File getResourceRoot (final URL url, final String resource) {
"""
Gets the absolute filesystem path to the class path root for the specified
resource. The root is either a JAR file or a directory with loose class
files. If the URL does not use a supported protocol, an exception will be
thrown.
@param url
The URL to the resource, may be <code>null</code>.
@param resource
The name of the resource, must not be <code>null</code>.
@return The absolute filesystem path to the class path root of the resource
or <code>null</code> if the input URL was <code>null</code>.
"""
String path = null;
if (url != null)
{
final String spec = url.toExternalForm ();
if ((JAR_FILE).regionMatches (true, 0, spec, 0, JAR_FILE.length ()))
{
URL jar;
try
{
jar = new URL (spec.substring (JAR.length (), spec.lastIndexOf ("!/")));
}
catch (final MalformedURLException e)
{
throw new IllegalArgumentException ("Invalid JAR URL: " + url + ", " + e.getMessage ());
}
path = decodeUrl (jar.getPath ());
}
else
if (FILE.regionMatches (true, 0, spec, 0, FILE.length ()))
{
path = decodeUrl (url.getPath ());
path = path.substring (0, path.length () - resource.length ());
}
else
{
throw new IllegalArgumentException ("Invalid class path URL: " + url);
}
}
return path != null ? new File (path) : null;
} | java | public static File getResourceRoot (final URL url, final String resource)
{
String path = null;
if (url != null)
{
final String spec = url.toExternalForm ();
if ((JAR_FILE).regionMatches (true, 0, spec, 0, JAR_FILE.length ()))
{
URL jar;
try
{
jar = new URL (spec.substring (JAR.length (), spec.lastIndexOf ("!/")));
}
catch (final MalformedURLException e)
{
throw new IllegalArgumentException ("Invalid JAR URL: " + url + ", " + e.getMessage ());
}
path = decodeUrl (jar.getPath ());
}
else
if (FILE.regionMatches (true, 0, spec, 0, FILE.length ()))
{
path = decodeUrl (url.getPath ());
path = path.substring (0, path.length () - resource.length ());
}
else
{
throw new IllegalArgumentException ("Invalid class path URL: " + url);
}
}
return path != null ? new File (path) : null;
} | [
"public",
"static",
"File",
"getResourceRoot",
"(",
"final",
"URL",
"url",
",",
"final",
"String",
"resource",
")",
"{",
"String",
"path",
"=",
"null",
";",
"if",
"(",
"url",
"!=",
"null",
")",
"{",
"final",
"String",
"spec",
"=",
"url",
".",
"toExtern... | Gets the absolute filesystem path to the class path root for the specified
resource. The root is either a JAR file or a directory with loose class
files. If the URL does not use a supported protocol, an exception will be
thrown.
@param url
The URL to the resource, may be <code>null</code>.
@param resource
The name of the resource, must not be <code>null</code>.
@return The absolute filesystem path to the class path root of the resource
or <code>null</code> if the input URL was <code>null</code>. | [
"Gets",
"the",
"absolute",
"filesystem",
"path",
"to",
"the",
"class",
"path",
"root",
"for",
"the",
"specified",
"resource",
".",
"The",
"root",
"is",
"either",
"a",
"JAR",
"file",
"or",
"a",
"directory",
"with",
"loose",
"class",
"files",
".",
"If",
"t... | train | https://github.com/phax/ph-javacc-maven-plugin/blob/99497a971fe59ab2289258ca7ddcfa40e651f19f/src/main/java/org/codehaus/mojo/javacc/UrlUtils.java#L70-L101 |
stratosphere/stratosphere | stratosphere-runtime/src/main/java/eu/stratosphere/nephele/ipc/Client.java | Client.getConnection | private Connection getConnection(InetSocketAddress addr, Class<?> protocol, Call call) throws IOException {
"""
Get a connection from the pool, or create a new one and add it to the
pool. Connections to a given host/port are reused.
"""
if (!running.get()) {
// the client is stopped
throw new IOException("The client is stopped");
}
Connection connection;
/*
* we could avoid this allocation for each RPC by having a
* connectionsId object and with set() method. We need to manage the
* refs for keys in HashMap properly. For now its ok.
*/
ConnectionId remoteId = new ConnectionId(addr, protocol);
do {
synchronized (connections) {
connection = connections.get(remoteId);
if (connection == null) {
connection = new Connection(remoteId);
connections.put(remoteId, connection);
}
}
} while (!connection.addCall(call));
// we don't invoke the method below inside "synchronized (connections)"
// block above. The reason for that is if the server happens to be slow,
// it will take longer to establish a connection and that will slow the
// entire system down.
connection.setupIOstreams();
return connection;
} | java | private Connection getConnection(InetSocketAddress addr, Class<?> protocol, Call call) throws IOException {
if (!running.get()) {
// the client is stopped
throw new IOException("The client is stopped");
}
Connection connection;
/*
* we could avoid this allocation for each RPC by having a
* connectionsId object and with set() method. We need to manage the
* refs for keys in HashMap properly. For now its ok.
*/
ConnectionId remoteId = new ConnectionId(addr, protocol);
do {
synchronized (connections) {
connection = connections.get(remoteId);
if (connection == null) {
connection = new Connection(remoteId);
connections.put(remoteId, connection);
}
}
} while (!connection.addCall(call));
// we don't invoke the method below inside "synchronized (connections)"
// block above. The reason for that is if the server happens to be slow,
// it will take longer to establish a connection and that will slow the
// entire system down.
connection.setupIOstreams();
return connection;
} | [
"private",
"Connection",
"getConnection",
"(",
"InetSocketAddress",
"addr",
",",
"Class",
"<",
"?",
">",
"protocol",
",",
"Call",
"call",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"running",
".",
"get",
"(",
")",
")",
"{",
"// the client is stopped"... | Get a connection from the pool, or create a new one and add it to the
pool. Connections to a given host/port are reused. | [
"Get",
"a",
"connection",
"from",
"the",
"pool",
"or",
"create",
"a",
"new",
"one",
"and",
"add",
"it",
"to",
"the",
"pool",
".",
"Connections",
"to",
"a",
"given",
"host",
"/",
"port",
"are",
"reused",
"."
] | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/ipc/Client.java#L744-L772 |
zaproxy/zaproxy | src/org/zaproxy/zap/view/DynamicFieldsPanel.java | DynamicFieldsPanel.setFields | public void setFields(String[] requiredFields, String[] optionalFields) {
"""
Sets the required and optional fields that should be shown in the panel.
<p>
Any fields previously set are removed.
@param requiredFields the required fields.
@param optionalFields the optional fields.
@throws IllegalArgumentException if the any of the arguments is {@code null}.
@since 2.7.0
@see #setFields(String[])
"""
if (requiredFields == null) {
throw new IllegalArgumentException("Parameter requiredFields must not be null.");
}
if (optionalFields == null) {
throw new IllegalArgumentException("Parameter optionalFields must not be null.");
}
this.requiredFields = requiredFields;
this.optionalFields = optionalFields;
this.textFields = new HashMap<>(requiredFields.length + optionalFields.length);
removeAll();
int fieldIndex = 0;
for (String fieldName : requiredFields) {
addRequiredField(fieldName, fieldIndex);
fieldIndex++;
}
for (String fieldName : optionalFields) {
addField(fieldName, fieldIndex);
fieldIndex++;
}
add(Box.createVerticalGlue(), LayoutHelper.getGBC(0, fieldIndex, 2, 0.0d, 1.0d));
validate();
} | java | public void setFields(String[] requiredFields, String[] optionalFields) {
if (requiredFields == null) {
throw new IllegalArgumentException("Parameter requiredFields must not be null.");
}
if (optionalFields == null) {
throw new IllegalArgumentException("Parameter optionalFields must not be null.");
}
this.requiredFields = requiredFields;
this.optionalFields = optionalFields;
this.textFields = new HashMap<>(requiredFields.length + optionalFields.length);
removeAll();
int fieldIndex = 0;
for (String fieldName : requiredFields) {
addRequiredField(fieldName, fieldIndex);
fieldIndex++;
}
for (String fieldName : optionalFields) {
addField(fieldName, fieldIndex);
fieldIndex++;
}
add(Box.createVerticalGlue(), LayoutHelper.getGBC(0, fieldIndex, 2, 0.0d, 1.0d));
validate();
} | [
"public",
"void",
"setFields",
"(",
"String",
"[",
"]",
"requiredFields",
",",
"String",
"[",
"]",
"optionalFields",
")",
"{",
"if",
"(",
"requiredFields",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Parameter requiredFields must no... | Sets the required and optional fields that should be shown in the panel.
<p>
Any fields previously set are removed.
@param requiredFields the required fields.
@param optionalFields the optional fields.
@throws IllegalArgumentException if the any of the arguments is {@code null}.
@since 2.7.0
@see #setFields(String[]) | [
"Sets",
"the",
"required",
"and",
"optional",
"fields",
"that",
"should",
"be",
"shown",
"in",
"the",
"panel",
".",
"<p",
">",
"Any",
"fields",
"previously",
"set",
"are",
"removed",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/view/DynamicFieldsPanel.java#L76-L105 |
ops4j/org.ops4j.pax.logging | pax-logging-log4j2/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java | ThrowableProxy.toCacheEntry | private CacheEntry toCacheEntry(final StackTraceElement stackTraceElement, final Class<?> callerClass,
final boolean exact) {
"""
Construct the CacheEntry from the Class's information.
@param stackTraceElement The stack trace element
@param callerClass The Class.
@param exact True if the class was obtained via Reflection.getCallerClass.
@return The CacheEntry.
"""
String location = "?";
String version = "?";
ClassLoader lastLoader = null;
if (callerClass != null) {
try {
Bundle bundle = FrameworkUtil.getBundle(callerClass);
if (bundle != null) {
location = bundle.getBundleId() + ":" + bundle.getSymbolicName();
version = bundle.getVersion().toString();
}
} catch (final Exception ex) {
// Ignore the exception.
}
lastLoader = callerClass.getClassLoader();
}
return new CacheEntry(new ExtendedClassInfo(exact, location, version), lastLoader);
} | java | private CacheEntry toCacheEntry(final StackTraceElement stackTraceElement, final Class<?> callerClass,
final boolean exact) {
String location = "?";
String version = "?";
ClassLoader lastLoader = null;
if (callerClass != null) {
try {
Bundle bundle = FrameworkUtil.getBundle(callerClass);
if (bundle != null) {
location = bundle.getBundleId() + ":" + bundle.getSymbolicName();
version = bundle.getVersion().toString();
}
} catch (final Exception ex) {
// Ignore the exception.
}
lastLoader = callerClass.getClassLoader();
}
return new CacheEntry(new ExtendedClassInfo(exact, location, version), lastLoader);
} | [
"private",
"CacheEntry",
"toCacheEntry",
"(",
"final",
"StackTraceElement",
"stackTraceElement",
",",
"final",
"Class",
"<",
"?",
">",
"callerClass",
",",
"final",
"boolean",
"exact",
")",
"{",
"String",
"location",
"=",
"\"?\"",
";",
"String",
"version",
"=",
... | Construct the CacheEntry from the Class's information.
@param stackTraceElement The stack trace element
@param callerClass The Class.
@param exact True if the class was obtained via Reflection.getCallerClass.
@return The CacheEntry. | [
"Construct",
"the",
"CacheEntry",
"from",
"the",
"Class",
"s",
"information",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-log4j2/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java#L626-L644 |
vkostyukov/la4j | src/main/java/org/la4j/matrix/RowMajorSparseMatrix.java | RowMajorSparseMatrix.randomSymmetric | public static RowMajorSparseMatrix randomSymmetric(int size, double density, Random random) {
"""
Creates a random symmetric {@link RowMajorSparseMatrix} of the given {@code size}.
"""
return CRSMatrix.randomSymmetric(size, density, random);
} | java | public static RowMajorSparseMatrix randomSymmetric(int size, double density, Random random) {
return CRSMatrix.randomSymmetric(size, density, random);
} | [
"public",
"static",
"RowMajorSparseMatrix",
"randomSymmetric",
"(",
"int",
"size",
",",
"double",
"density",
",",
"Random",
"random",
")",
"{",
"return",
"CRSMatrix",
".",
"randomSymmetric",
"(",
"size",
",",
"density",
",",
"random",
")",
";",
"}"
] | Creates a random symmetric {@link RowMajorSparseMatrix} of the given {@code size}. | [
"Creates",
"a",
"random",
"symmetric",
"{"
] | train | https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/matrix/RowMajorSparseMatrix.java#L93-L95 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/convert/Convert.java | Convert.toEnum | public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value) {
"""
转换为Enum对象<br>
如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
@param <E> 枚举类型
@param clazz Enum的Class
@param value 值
@return Enum
"""
return toEnum(clazz, value, null);
} | java | public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value) {
return toEnum(clazz, value, null);
} | [
"public",
"static",
"<",
"E",
"extends",
"Enum",
"<",
"E",
">",
">",
"E",
"toEnum",
"(",
"Class",
"<",
"E",
">",
"clazz",
",",
"Object",
"value",
")",
"{",
"return",
"toEnum",
"(",
"clazz",
",",
"value",
",",
"null",
")",
";",
"}"
] | 转换为Enum对象<br>
如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
@param <E> 枚举类型
@param clazz Enum的Class
@param value 值
@return Enum | [
"转换为Enum对象<br",
">",
"如果给定的值为空,或者转换失败,返回默认值<code",
">",
"null<",
"/",
"code",
">",
"<br",
">"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/convert/Convert.java#L487-L489 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectPropertyRangeAxiomImpl_CustomFieldSerializer.java | OWLObjectPropertyRangeAxiomImpl_CustomFieldSerializer.deserializeInstance | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLObjectPropertyRangeAxiomImpl instance) throws SerializationException {
"""
Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful
"""
deserialize(streamReader, instance);
} | java | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLObjectPropertyRangeAxiomImpl instance) throws SerializationException {
deserialize(streamReader, instance);
} | [
"@",
"Override",
"public",
"void",
"deserializeInstance",
"(",
"SerializationStreamReader",
"streamReader",
",",
"OWLObjectPropertyRangeAxiomImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"deserialize",
"(",
"streamReader",
",",
"instance",
")",
";",
"}"... | Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful | [
"Deserializes",
"the",
"content",
"of",
"the",
"object",
"from",
"the",
"{",
"@link",
"com",
".",
"google",
".",
"gwt",
".",
"user",
".",
"client",
".",
"rpc",
".",
"SerializationStreamReader",
"}",
"."
] | train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectPropertyRangeAxiomImpl_CustomFieldSerializer.java#L98-L101 |
igniterealtime/Smack | smack-core/src/main/java/org/jivesoftware/smack/packet/Stanza.java | Stanza.hasExtension | public boolean hasExtension(String elementName, String namespace) {
"""
Check if a stanza extension with the given element and namespace exists.
<p>
The argument <code>elementName</code> may be null.
</p>
@param elementName
@param namespace
@return true if a stanza extension exists, false otherwise.
"""
if (elementName == null) {
return hasExtension(namespace);
}
String key = XmppStringUtils.generateKey(elementName, namespace);
synchronized (packetExtensions) {
return packetExtensions.containsKey(key);
}
} | java | public boolean hasExtension(String elementName, String namespace) {
if (elementName == null) {
return hasExtension(namespace);
}
String key = XmppStringUtils.generateKey(elementName, namespace);
synchronized (packetExtensions) {
return packetExtensions.containsKey(key);
}
} | [
"public",
"boolean",
"hasExtension",
"(",
"String",
"elementName",
",",
"String",
"namespace",
")",
"{",
"if",
"(",
"elementName",
"==",
"null",
")",
"{",
"return",
"hasExtension",
"(",
"namespace",
")",
";",
"}",
"String",
"key",
"=",
"XmppStringUtils",
"."... | Check if a stanza extension with the given element and namespace exists.
<p>
The argument <code>elementName</code> may be null.
</p>
@param elementName
@param namespace
@return true if a stanza extension exists, false otherwise. | [
"Check",
"if",
"a",
"stanza",
"extension",
"with",
"the",
"given",
"element",
"and",
"namespace",
"exists",
".",
"<p",
">",
"The",
"argument",
"<code",
">",
"elementName<",
"/",
"code",
">",
"may",
"be",
"null",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/packet/Stanza.java#L428-L436 |
googleads/googleads-java-lib | modules/ads_lib_appengine/src/main/java/com/google/api/ads/common/lib/soap/jaxws/JaxWsHandler.java | JaxWsHandler.setRequestTimeout | @Override
public void setRequestTimeout(BindingProvider bindingProvider, int timeout) {
"""
Sets properties into the message context to alter the timeout on App Engine.
"""
// Production App Engine
bindingProvider.getRequestContext().put(PRODUCTION_REQUEST_TIMEOUT_KEY, timeout);
// Dev App Engine
bindingProvider.getRequestContext().put(DEVEL_REQUEST_TIMEOUT_KEY, timeout);
} | java | @Override
public void setRequestTimeout(BindingProvider bindingProvider, int timeout) {
// Production App Engine
bindingProvider.getRequestContext().put(PRODUCTION_REQUEST_TIMEOUT_KEY, timeout);
// Dev App Engine
bindingProvider.getRequestContext().put(DEVEL_REQUEST_TIMEOUT_KEY, timeout);
} | [
"@",
"Override",
"public",
"void",
"setRequestTimeout",
"(",
"BindingProvider",
"bindingProvider",
",",
"int",
"timeout",
")",
"{",
"// Production App Engine",
"bindingProvider",
".",
"getRequestContext",
"(",
")",
".",
"put",
"(",
"PRODUCTION_REQUEST_TIMEOUT_KEY",
",",... | Sets properties into the message context to alter the timeout on App Engine. | [
"Sets",
"properties",
"into",
"the",
"message",
"context",
"to",
"alter",
"the",
"timeout",
"on",
"App",
"Engine",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/ads_lib_appengine/src/main/java/com/google/api/ads/common/lib/soap/jaxws/JaxWsHandler.java#L245-L251 |
azkaban/azkaban | az-core/src/main/java/azkaban/utils/PropsUtils.java | PropsUtils.loadPropsInDir | public static Props loadPropsInDir(final Props parent, final File dir, final String... suffixes) {
"""
Load job schedules from the given directories
@param parent The parent properties for these properties
@param dir The directory to look in
@param suffixes File suffixes to load
@return The loaded set of schedules
"""
try {
final Props props = new Props(parent);
final File[] files = dir.listFiles();
Arrays.sort(files);
if (files != null) {
for (final File f : files) {
if (f.isFile() && endsWith(f, suffixes)) {
props.putAll(new Props(null, f.getAbsolutePath()));
}
}
}
return props;
} catch (final IOException e) {
throw new RuntimeException("Error loading properties.", e);
}
} | java | public static Props loadPropsInDir(final Props parent, final File dir, final String... suffixes) {
try {
final Props props = new Props(parent);
final File[] files = dir.listFiles();
Arrays.sort(files);
if (files != null) {
for (final File f : files) {
if (f.isFile() && endsWith(f, suffixes)) {
props.putAll(new Props(null, f.getAbsolutePath()));
}
}
}
return props;
} catch (final IOException e) {
throw new RuntimeException("Error loading properties.", e);
}
} | [
"public",
"static",
"Props",
"loadPropsInDir",
"(",
"final",
"Props",
"parent",
",",
"final",
"File",
"dir",
",",
"final",
"String",
"...",
"suffixes",
")",
"{",
"try",
"{",
"final",
"Props",
"props",
"=",
"new",
"Props",
"(",
"parent",
")",
";",
"final"... | Load job schedules from the given directories
@param parent The parent properties for these properties
@param dir The directory to look in
@param suffixes File suffixes to load
@return The loaded set of schedules | [
"Load",
"job",
"schedules",
"from",
"the",
"given",
"directories"
] | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/az-core/src/main/java/azkaban/utils/PropsUtils.java#L74-L90 |
apache/flink | flink-queryable-state/flink-queryable-state-client-java/src/main/java/org/apache/flink/queryablestate/client/QueryableStateClient.java | QueryableStateClient.getKvState | private CompletableFuture<KvStateResponse> getKvState(
final JobID jobId,
final String queryableStateName,
final int keyHashCode,
final byte[] serializedKeyAndNamespace) {
"""
Returns a future holding the serialized request result.
@param jobId JobID of the job the queryable state
belongs to
@param queryableStateName Name under which the state is queryable
@param keyHashCode Integer hash code of the key (result of
a call to {@link Object#hashCode()}
@param serializedKeyAndNamespace Serialized key and namespace to query
KvState instance with
@return Future holding the serialized result
"""
LOG.debug("Sending State Request to {}.", remoteAddress);
try {
KvStateRequest request = new KvStateRequest(jobId, queryableStateName, keyHashCode, serializedKeyAndNamespace);
return client.sendRequest(remoteAddress, request);
} catch (Exception e) {
LOG.error("Unable to send KVStateRequest: ", e);
return FutureUtils.getFailedFuture(e);
}
} | java | private CompletableFuture<KvStateResponse> getKvState(
final JobID jobId,
final String queryableStateName,
final int keyHashCode,
final byte[] serializedKeyAndNamespace) {
LOG.debug("Sending State Request to {}.", remoteAddress);
try {
KvStateRequest request = new KvStateRequest(jobId, queryableStateName, keyHashCode, serializedKeyAndNamespace);
return client.sendRequest(remoteAddress, request);
} catch (Exception e) {
LOG.error("Unable to send KVStateRequest: ", e);
return FutureUtils.getFailedFuture(e);
}
} | [
"private",
"CompletableFuture",
"<",
"KvStateResponse",
">",
"getKvState",
"(",
"final",
"JobID",
"jobId",
",",
"final",
"String",
"queryableStateName",
",",
"final",
"int",
"keyHashCode",
",",
"final",
"byte",
"[",
"]",
"serializedKeyAndNamespace",
")",
"{",
"LOG... | Returns a future holding the serialized request result.
@param jobId JobID of the job the queryable state
belongs to
@param queryableStateName Name under which the state is queryable
@param keyHashCode Integer hash code of the key (result of
a call to {@link Object#hashCode()}
@param serializedKeyAndNamespace Serialized key and namespace to query
KvState instance with
@return Future holding the serialized result | [
"Returns",
"a",
"future",
"holding",
"the",
"serialized",
"request",
"result",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-queryable-state/flink-queryable-state-client-java/src/main/java/org/apache/flink/queryablestate/client/QueryableStateClient.java#L305-L318 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/allocator/impl/AtomicAllocator.java | AtomicAllocator.getPointer | @Override
public Pointer getPointer(INDArray array, CudaContext context) {
"""
This method returns actual device pointer valid for specified INDArray
@param array
"""
// DataBuffer buffer = array.data().originalDataBuffer() == null ? array.data() : array.data().originalDataBuffer();
if (array.isEmpty())
return null;
return memoryHandler.getDevicePointer(array.data(), context);
} | java | @Override
public Pointer getPointer(INDArray array, CudaContext context) {
// DataBuffer buffer = array.data().originalDataBuffer() == null ? array.data() : array.data().originalDataBuffer();
if (array.isEmpty())
return null;
return memoryHandler.getDevicePointer(array.data(), context);
} | [
"@",
"Override",
"public",
"Pointer",
"getPointer",
"(",
"INDArray",
"array",
",",
"CudaContext",
"context",
")",
"{",
"// DataBuffer buffer = array.data().originalDataBuffer() == null ? array.data() : array.data().originalDataBuffer();",
"if",
"(",
"array",
".",
"isEmpty",
... | This method returns actual device pointer valid for specified INDArray
@param array | [
"This",
"method",
"returns",
"actual",
"device",
"pointer",
"valid",
"for",
"specified",
"INDArray"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/allocator/impl/AtomicAllocator.java#L314-L321 |
mkotsur/restito | examples/popular-page/src/main/java/com/xebialabs/restito/examples/WikiClient.java | WikiClient.getMostRecentRevision | public PageRevision getMostRecentRevision(String... titles) throws Exception {
"""
Returns the latest revision of the page which was edited last
"""
URL url = new URL(entryPoint +
"/w/api.php?format=json&action=query&prop=revisions&rvprop=user|timestamp&titles=" +
encode(Joiner.on("|").join(titles), "UTF-8")
);
String response = readURL(url);
List<PageRevision> revisions = extractRevisions(response);
Collections.sort(revisions, new Comparator<PageRevision>() {
@Override
public int compare(final PageRevision o1, final PageRevision o2) {
return o2.date.compareTo(o1.date);
}
});
return revisions.get(0);
} | java | public PageRevision getMostRecentRevision(String... titles) throws Exception {
URL url = new URL(entryPoint +
"/w/api.php?format=json&action=query&prop=revisions&rvprop=user|timestamp&titles=" +
encode(Joiner.on("|").join(titles), "UTF-8")
);
String response = readURL(url);
List<PageRevision> revisions = extractRevisions(response);
Collections.sort(revisions, new Comparator<PageRevision>() {
@Override
public int compare(final PageRevision o1, final PageRevision o2) {
return o2.date.compareTo(o1.date);
}
});
return revisions.get(0);
} | [
"public",
"PageRevision",
"getMostRecentRevision",
"(",
"String",
"...",
"titles",
")",
"throws",
"Exception",
"{",
"URL",
"url",
"=",
"new",
"URL",
"(",
"entryPoint",
"+",
"\"/w/api.php?format=json&action=query&prop=revisions&rvprop=user|timestamp&titles=\"",
"+",
"encode"... | Returns the latest revision of the page which was edited last | [
"Returns",
"the",
"latest",
"revision",
"of",
"the",
"page",
"which",
"was",
"edited",
"last"
] | train | https://github.com/mkotsur/restito/blob/b999293616ca84fdea1ffe929e92a5db29c7e415/examples/popular-page/src/main/java/com/xebialabs/restito/examples/WikiClient.java#L32-L51 |
nguyenq/tess4j | src/main/java/net/sourceforge/tess4j/util/ImageIOHelper.java | ImageIOHelper.mergeTiff | public static void mergeTiff(BufferedImage[] inputImages, File outputTiff) throws IOException {
"""
Merges multiple images into one multi-page TIFF image.
@param inputImages an array of <code>BufferedImage</code>
@param outputTiff the output TIFF file
@throws IOException
"""
mergeTiff(inputImages, outputTiff, null);
} | java | public static void mergeTiff(BufferedImage[] inputImages, File outputTiff) throws IOException {
mergeTiff(inputImages, outputTiff, null);
} | [
"public",
"static",
"void",
"mergeTiff",
"(",
"BufferedImage",
"[",
"]",
"inputImages",
",",
"File",
"outputTiff",
")",
"throws",
"IOException",
"{",
"mergeTiff",
"(",
"inputImages",
",",
"outputTiff",
",",
"null",
")",
";",
"}"
] | Merges multiple images into one multi-page TIFF image.
@param inputImages an array of <code>BufferedImage</code>
@param outputTiff the output TIFF file
@throws IOException | [
"Merges",
"multiple",
"images",
"into",
"one",
"multi",
"-",
"page",
"TIFF",
"image",
"."
] | train | https://github.com/nguyenq/tess4j/blob/cfcd4a8a44042f150b4aaf7bdf5ffc485a2236e1/src/main/java/net/sourceforge/tess4j/util/ImageIOHelper.java#L505-L507 |
Azure/azure-sdk-for-java | automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ConnectionTypesInner.java | ConnectionTypesInner.listByAutomationAccountAsync | public Observable<Page<ConnectionTypeInner>> listByAutomationAccountAsync(final String resourceGroupName, final String automationAccountName) {
"""
Retrieve a list of connectiontypes.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ConnectionTypeInner> object
"""
return listByAutomationAccountWithServiceResponseAsync(resourceGroupName, automationAccountName)
.map(new Func1<ServiceResponse<Page<ConnectionTypeInner>>, Page<ConnectionTypeInner>>() {
@Override
public Page<ConnectionTypeInner> call(ServiceResponse<Page<ConnectionTypeInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<ConnectionTypeInner>> listByAutomationAccountAsync(final String resourceGroupName, final String automationAccountName) {
return listByAutomationAccountWithServiceResponseAsync(resourceGroupName, automationAccountName)
.map(new Func1<ServiceResponse<Page<ConnectionTypeInner>>, Page<ConnectionTypeInner>>() {
@Override
public Page<ConnectionTypeInner> call(ServiceResponse<Page<ConnectionTypeInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"ConnectionTypeInner",
">",
">",
"listByAutomationAccountAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"automationAccountName",
")",
"{",
"return",
"listByAutomationAccountWithServiceResponseAsync",
"(... | Retrieve a list of connectiontypes.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ConnectionTypeInner> object | [
"Retrieve",
"a",
"list",
"of",
"connectiontypes",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ConnectionTypesInner.java#L418-L426 |
groovy/groovy-core | src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java | StringGroovyMethods.replaceFirst | public static String replaceFirst(final CharSequence self, final Pattern pattern, final @ClosureParams(value=FromString.class, options= {
"""
Replaces the first occurrence of a captured group by the result of a closure call on that text.
<p>
For example (with some replaceAll variants thrown in for comparison purposes),
<pre>
assert "hellO world" == "hello world".replaceFirst(~"(o)") { it[0].toUpperCase() } // first match
assert "hellO wOrld" == "hello world".replaceAll(~"(o)") { it[0].toUpperCase() } // all matches
assert '1-FISH, two fish' == "one fish, two fish".replaceFirst(~/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() }
assert '1-FISH, 2-FISH' == "one fish, two fish".replaceAll(~/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() }
</pre>
@param self a CharSequence
@param pattern the capturing regex Pattern
@param closure the closure to apply on the first captured group
@return a CharSequence with replaced content
@since 1.8.2
""""List<String>","String[]"}) Closure closure) {
final String s = self.toString();
final Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
final StringBuffer sb = new StringBuffer(s.length() + 16);
String replacement = getReplacement(matcher, closure);
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
matcher.appendTail(sb);
return sb.toString();
} else {
return s;
}
} | java | public static String replaceFirst(final CharSequence self, final Pattern pattern, final @ClosureParams(value=FromString.class, options={"List<String>","String[]"}) Closure closure) {
final String s = self.toString();
final Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
final StringBuffer sb = new StringBuffer(s.length() + 16);
String replacement = getReplacement(matcher, closure);
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
matcher.appendTail(sb);
return sb.toString();
} else {
return s;
}
} | [
"public",
"static",
"String",
"replaceFirst",
"(",
"final",
"CharSequence",
"self",
",",
"final",
"Pattern",
"pattern",
",",
"final",
"@",
"ClosureParams",
"(",
"value",
"=",
"FromString",
".",
"class",
",",
"options",
"=",
"{",
"\"List<String>\"",
",",
"\"Str... | Replaces the first occurrence of a captured group by the result of a closure call on that text.
<p>
For example (with some replaceAll variants thrown in for comparison purposes),
<pre>
assert "hellO world" == "hello world".replaceFirst(~"(o)") { it[0].toUpperCase() } // first match
assert "hellO wOrld" == "hello world".replaceAll(~"(o)") { it[0].toUpperCase() } // all matches
assert '1-FISH, two fish' == "one fish, two fish".replaceFirst(~/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() }
assert '1-FISH, 2-FISH' == "one fish, two fish".replaceAll(~/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() }
</pre>
@param self a CharSequence
@param pattern the capturing regex Pattern
@param closure the closure to apply on the first captured group
@return a CharSequence with replaced content
@since 1.8.2 | [
"Replaces",
"the",
"first",
"occurrence",
"of",
"a",
"captured",
"group",
"by",
"the",
"result",
"of",
"a",
"closure",
"call",
"on",
"that",
"text",
".",
"<p",
">",
"For",
"example",
"(",
"with",
"some",
"replaceAll",
"variants",
"thrown",
"in",
"for",
"... | train | https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java#L2701-L2713 |
btrplace/scheduler | api/src/main/java/org/btrplace/model/view/ShareableResource.java | ShareableResource.setCapacity | public ShareableResource setCapacity(int val, Node... nodes) {
"""
Set the resource consumption of nodes.
@param val the value to set
@param nodes the nodes
@return the current resource
"""
Stream.of(nodes).forEach(n -> this.setCapacity(n, val));
return this;
} | java | public ShareableResource setCapacity(int val, Node... nodes) {
Stream.of(nodes).forEach(n -> this.setCapacity(n, val));
return this;
} | [
"public",
"ShareableResource",
"setCapacity",
"(",
"int",
"val",
",",
"Node",
"...",
"nodes",
")",
"{",
"Stream",
".",
"of",
"(",
"nodes",
")",
".",
"forEach",
"(",
"n",
"->",
"this",
".",
"setCapacity",
"(",
"n",
",",
"val",
")",
")",
";",
"return",... | Set the resource consumption of nodes.
@param val the value to set
@param nodes the nodes
@return the current resource | [
"Set",
"the",
"resource",
"consumption",
"of",
"nodes",
"."
] | train | https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/model/view/ShareableResource.java#L192-L195 |
alkacon/opencms-core | src/org/opencms/ui/apps/git/CmsGitToolOptionsPanel.java | CmsGitToolOptionsPanel.setUserInfo | private void setUserInfo(CmsUser user, String key, String value) {
"""
Sets an additional info value if it's not empty.<p>
@param user the user on which to set the additional info
@param key the additional info key
@param value the additional info value
"""
if (!CmsStringUtil.isEmptyOrWhitespaceOnly(value)) {
user.getAdditionalInfo().put(key, value);
}
} | java | private void setUserInfo(CmsUser user, String key, String value) {
if (!CmsStringUtil.isEmptyOrWhitespaceOnly(value)) {
user.getAdditionalInfo().put(key, value);
}
} | [
"private",
"void",
"setUserInfo",
"(",
"CmsUser",
"user",
",",
"String",
"key",
",",
"String",
"value",
")",
"{",
"if",
"(",
"!",
"CmsStringUtil",
".",
"isEmptyOrWhitespaceOnly",
"(",
"value",
")",
")",
"{",
"user",
".",
"getAdditionalInfo",
"(",
")",
".",... | Sets an additional info value if it's not empty.<p>
@param user the user on which to set the additional info
@param key the additional info key
@param value the additional info value | [
"Sets",
"an",
"additional",
"info",
"value",
"if",
"it",
"s",
"not",
"empty",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/git/CmsGitToolOptionsPanel.java#L773-L778 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java | ResourceGroovyMethods.newReader | public static BufferedReader newReader(URL url, String charset) throws MalformedURLException, IOException {
"""
Creates a buffered reader for this URL using the given encoding.
@param url a URL
@param charset opens the stream with a specified charset
@return a BufferedReader for the URL
@throws MalformedURLException is thrown if the URL is not well formed
@throws IOException if an I/O error occurs while creating the input stream
@since 1.5.5
"""
return new BufferedReader(new InputStreamReader(configuredInputStream(null, url), charset));
} | java | public static BufferedReader newReader(URL url, String charset) throws MalformedURLException, IOException {
return new BufferedReader(new InputStreamReader(configuredInputStream(null, url), charset));
} | [
"public",
"static",
"BufferedReader",
"newReader",
"(",
"URL",
"url",
",",
"String",
"charset",
")",
"throws",
"MalformedURLException",
",",
"IOException",
"{",
"return",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"configuredInputStream",
"(",
"n... | Creates a buffered reader for this URL using the given encoding.
@param url a URL
@param charset opens the stream with a specified charset
@return a BufferedReader for the URL
@throws MalformedURLException is thrown if the URL is not well formed
@throws IOException if an I/O error occurs while creating the input stream
@since 1.5.5 | [
"Creates",
"a",
"buffered",
"reader",
"for",
"this",
"URL",
"using",
"the",
"given",
"encoding",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java#L2268-L2270 |
apache/incubator-shardingsphere | sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/BackendConnection.java | BackendConnection.setTransactionType | public void setTransactionType(final TransactionType transactionType) {
"""
Change transaction type of current channel.
@param transactionType transaction type
"""
if (null == schemaName) {
throw new ShardingException("Please select database, then switch transaction type.");
}
if (isSwitchFailed()) {
throw new ShardingException("Failed to switch transaction type, please terminate current transaction.");
}
this.transactionType = transactionType;
} | java | public void setTransactionType(final TransactionType transactionType) {
if (null == schemaName) {
throw new ShardingException("Please select database, then switch transaction type.");
}
if (isSwitchFailed()) {
throw new ShardingException("Failed to switch transaction type, please terminate current transaction.");
}
this.transactionType = transactionType;
} | [
"public",
"void",
"setTransactionType",
"(",
"final",
"TransactionType",
"transactionType",
")",
"{",
"if",
"(",
"null",
"==",
"schemaName",
")",
"{",
"throw",
"new",
"ShardingException",
"(",
"\"Please select database, then switch transaction type.\"",
")",
";",
"}",
... | Change transaction type of current channel.
@param transactionType transaction type | [
"Change",
"transaction",
"type",
"of",
"current",
"channel",
"."
] | train | https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/BackendConnection.java#L90-L98 |
google/j2objc | jre_emul/android/platform/libcore/luni/src/main/java/org/apache/harmony/xml/dom/NodeImpl.java | NodeImpl.validatePrefix | static String validatePrefix(String prefix, boolean namespaceAware, String namespaceURI) {
"""
Validates the element or attribute namespace prefix on this node.
@param namespaceAware whether this node is namespace aware
@param namespaceURI this node's namespace URI
"""
if (!namespaceAware) {
throw new DOMException(DOMException.NAMESPACE_ERR, prefix);
}
if (prefix != null) {
if (namespaceURI == null
|| !DocumentImpl.isXMLIdentifier(prefix)
|| "xml".equals(prefix) && !"http://www.w3.org/XML/1998/namespace".equals(namespaceURI)
|| "xmlns".equals(prefix) && !"http://www.w3.org/2000/xmlns/".equals(namespaceURI)) {
throw new DOMException(DOMException.NAMESPACE_ERR, prefix);
}
}
return prefix;
} | java | static String validatePrefix(String prefix, boolean namespaceAware, String namespaceURI) {
if (!namespaceAware) {
throw new DOMException(DOMException.NAMESPACE_ERR, prefix);
}
if (prefix != null) {
if (namespaceURI == null
|| !DocumentImpl.isXMLIdentifier(prefix)
|| "xml".equals(prefix) && !"http://www.w3.org/XML/1998/namespace".equals(namespaceURI)
|| "xmlns".equals(prefix) && !"http://www.w3.org/2000/xmlns/".equals(namespaceURI)) {
throw new DOMException(DOMException.NAMESPACE_ERR, prefix);
}
}
return prefix;
} | [
"static",
"String",
"validatePrefix",
"(",
"String",
"prefix",
",",
"boolean",
"namespaceAware",
",",
"String",
"namespaceURI",
")",
"{",
"if",
"(",
"!",
"namespaceAware",
")",
"{",
"throw",
"new",
"DOMException",
"(",
"DOMException",
".",
"NAMESPACE_ERR",
",",
... | Validates the element or attribute namespace prefix on this node.
@param namespaceAware whether this node is namespace aware
@param namespaceURI this node's namespace URI | [
"Validates",
"the",
"element",
"or",
"attribute",
"namespace",
"prefix",
"on",
"this",
"node",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/luni/src/main/java/org/apache/harmony/xml/dom/NodeImpl.java#L205-L220 |
defei/codelogger-utils | src/main/java/org/codelogger/utils/BeanUtils.java | BeanUtils.copyProperties | public static void copyProperties(final Object source, final Object target) {
"""
把相同名称和类型的字段从源对象中复制到目标对象中去(目标对象中final字段除外)。 Copy same name and type field
value from source to target(except target final field).
@param source
源对象。source object.
@param target
目标对象。target object.
"""
ExceptionUtils.iae.throwIfNull(source, SOURCE_IS_NULL_MESSAGE);
ExceptionUtils.iae.throwIfNull(target, TARGETIS_NULL_MESSAGE);
Class<Object> sourceClass = ClassUtils.getClass(source);
Class<Object> targetClass = ClassUtils.getClass(target);
Field[] sourceFields = sourceClass.getDeclaredFields();
Field[] targetFields = targetClass.getDeclaredFields();
try {
for (Field sourceField : sourceFields) {
Field targetField = getFieldByField(targetFields, sourceField);
if (targetField != null) {
getAndSetValue(source, sourceField, target, targetField);
}
}
} catch (Exception e) {
throw new FatalBeanException(CAN_NOT_COPY_PROPERTIES, e);
}
} | java | public static void copyProperties(final Object source, final Object target) {
ExceptionUtils.iae.throwIfNull(source, SOURCE_IS_NULL_MESSAGE);
ExceptionUtils.iae.throwIfNull(target, TARGETIS_NULL_MESSAGE);
Class<Object> sourceClass = ClassUtils.getClass(source);
Class<Object> targetClass = ClassUtils.getClass(target);
Field[] sourceFields = sourceClass.getDeclaredFields();
Field[] targetFields = targetClass.getDeclaredFields();
try {
for (Field sourceField : sourceFields) {
Field targetField = getFieldByField(targetFields, sourceField);
if (targetField != null) {
getAndSetValue(source, sourceField, target, targetField);
}
}
} catch (Exception e) {
throw new FatalBeanException(CAN_NOT_COPY_PROPERTIES, e);
}
} | [
"public",
"static",
"void",
"copyProperties",
"(",
"final",
"Object",
"source",
",",
"final",
"Object",
"target",
")",
"{",
"ExceptionUtils",
".",
"iae",
".",
"throwIfNull",
"(",
"source",
",",
"SOURCE_IS_NULL_MESSAGE",
")",
";",
"ExceptionUtils",
".",
"iae",
... | 把相同名称和类型的字段从源对象中复制到目标对象中去(目标对象中final字段除外)。 Copy same name and type field
value from source to target(except target final field).
@param source
源对象。source object.
@param target
目标对象。target object. | [
"把相同名称和类型的字段从源对象中复制到目标对象中去",
"(",
"目标对象中final字段除外",
")",
"。",
"Copy",
"same",
"name",
"and",
"type",
"field",
"value",
"from",
"source",
"to",
"target",
"(",
"except",
"target",
"final",
"field",
")",
"."
] | train | https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/BeanUtils.java#L83-L101 |
googlemaps/google-maps-services-java | src/main/java/com/google/maps/PlacesApi.java | PlacesApi.textSearchQuery | public static TextSearchRequest textSearchQuery(GeoApiContext context, String query) {
"""
Performs a search for Places using a text query; for example, "pizza in New York" or "shoe
stores near Ottawa".
@param context The context on which to make Geo API requests.
@param query The text string on which to search, for example: "restaurant".
@return Returns a TextSearchRequest that can be configured and executed.
"""
TextSearchRequest request = new TextSearchRequest(context);
request.query(query);
return request;
} | java | public static TextSearchRequest textSearchQuery(GeoApiContext context, String query) {
TextSearchRequest request = new TextSearchRequest(context);
request.query(query);
return request;
} | [
"public",
"static",
"TextSearchRequest",
"textSearchQuery",
"(",
"GeoApiContext",
"context",
",",
"String",
"query",
")",
"{",
"TextSearchRequest",
"request",
"=",
"new",
"TextSearchRequest",
"(",
"context",
")",
";",
"request",
".",
"query",
"(",
"query",
")",
... | Performs a search for Places using a text query; for example, "pizza in New York" or "shoe
stores near Ottawa".
@param context The context on which to make Geo API requests.
@param query The text string on which to search, for example: "restaurant".
@return Returns a TextSearchRequest that can be configured and executed. | [
"Performs",
"a",
"search",
"for",
"Places",
"using",
"a",
"text",
"query",
";",
"for",
"example",
"pizza",
"in",
"New",
"York",
"or",
"shoe",
"stores",
"near",
"Ottawa",
"."
] | train | https://github.com/googlemaps/google-maps-services-java/blob/23d20d1930f80e310d856d2da51d72ee0db4476b/src/main/java/com/google/maps/PlacesApi.java#L70-L74 |
jfinal/jfinal | src/main/java/com/jfinal/core/ActionMapping.java | ActionMapping.getAction | public Action getAction(String url, String[] urlPara) {
"""
Support four types of url
1: http://abc.com/controllerKey ---> 00
2: http://abc.com/controllerKey/para ---> 01
3: http://abc.com/controllerKey/method ---> 10
4: http://abc.com/controllerKey/method/para ---> 11
The controllerKey can also contains "/"
Example: http://abc.com/uvw/xyz/method/para
"""
Action action = mapping.get(url);
if (action != null) {
return action;
}
// --------
int i = url.lastIndexOf('/');
if (i != -1) {
action = mapping.get(url.substring(0, i));
if (action != null) {
urlPara[0] = url.substring(i + 1);
}
}
return action;
} | java | public Action getAction(String url, String[] urlPara) {
Action action = mapping.get(url);
if (action != null) {
return action;
}
// --------
int i = url.lastIndexOf('/');
if (i != -1) {
action = mapping.get(url.substring(0, i));
if (action != null) {
urlPara[0] = url.substring(i + 1);
}
}
return action;
} | [
"public",
"Action",
"getAction",
"(",
"String",
"url",
",",
"String",
"[",
"]",
"urlPara",
")",
"{",
"Action",
"action",
"=",
"mapping",
".",
"get",
"(",
"url",
")",
";",
"if",
"(",
"action",
"!=",
"null",
")",
"{",
"return",
"action",
";",
"}",
"/... | Support four types of url
1: http://abc.com/controllerKey ---> 00
2: http://abc.com/controllerKey/para ---> 01
3: http://abc.com/controllerKey/method ---> 10
4: http://abc.com/controllerKey/method/para ---> 11
The controllerKey can also contains "/"
Example: http://abc.com/uvw/xyz/method/para | [
"Support",
"four",
"types",
"of",
"url",
"1",
":",
"http",
":",
"//",
"abc",
".",
"com",
"/",
"controllerKey",
"---",
">",
"00",
"2",
":",
"http",
":",
"//",
"abc",
".",
"com",
"/",
"controllerKey",
"/",
"para",
"---",
">",
"01",
"3",
":",
"http"... | train | https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/core/ActionMapping.java#L138-L154 |
wcm-io/wcm-io-sling | commons/src/main/java/io/wcm/sling/commons/request/RequestPath.java | RequestPath.hasSelector | public static boolean hasSelector(@NotNull SlingHttpServletRequest request, @NotNull String expectedSelector) {
"""
Checks if the given selector is present in the current URL request (at any position).
@param request Sling request
@param expectedSelector Selector string to check for.
@return true if the selector was found
"""
String[] selectors = request.getRequestPathInfo().getSelectors();
return ArrayUtils.contains(selectors, expectedSelector);
} | java | public static boolean hasSelector(@NotNull SlingHttpServletRequest request, @NotNull String expectedSelector) {
String[] selectors = request.getRequestPathInfo().getSelectors();
return ArrayUtils.contains(selectors, expectedSelector);
} | [
"public",
"static",
"boolean",
"hasSelector",
"(",
"@",
"NotNull",
"SlingHttpServletRequest",
"request",
",",
"@",
"NotNull",
"String",
"expectedSelector",
")",
"{",
"String",
"[",
"]",
"selectors",
"=",
"request",
".",
"getRequestPathInfo",
"(",
")",
".",
"getS... | Checks if the given selector is present in the current URL request (at any position).
@param request Sling request
@param expectedSelector Selector string to check for.
@return true if the selector was found | [
"Checks",
"if",
"the",
"given",
"selector",
"is",
"present",
"in",
"the",
"current",
"URL",
"request",
"(",
"at",
"any",
"position",
")",
"."
] | train | https://github.com/wcm-io/wcm-io-sling/blob/90adbe432469378794b5695c72e9cdfa2b7d36f1/commons/src/main/java/io/wcm/sling/commons/request/RequestPath.java#L43-L46 |
foundation-runtime/common | commons/src/main/java/com/cisco/oss/foundation/application/exception/ExceptionUtil.java | ExceptionUtil.getLowestException | public static Exception getLowestException(final Exception exception, final String exceptionPrefix) {
"""
Get the most inner exception that is exception from "exceptionPrefix"
type. If the exception does not include inner exception of type
"exceptionPrefix", returns null.
@param exception
@param exceptionPrefix
@return
"""
if (exception == null) {
return null;
}
Throwable nestedException = (Throwable) exception;
Exception lastLowException = null;
while (nestedException != null) {
if (nestedException.getClass().toString().startsWith("class " + exceptionPrefix)) {
lastLowException = (Exception) nestedException;
}
nestedException = getInnerException(nestedException);
}
return lastLowException;
} | java | public static Exception getLowestException(final Exception exception, final String exceptionPrefix) {
if (exception == null) {
return null;
}
Throwable nestedException = (Throwable) exception;
Exception lastLowException = null;
while (nestedException != null) {
if (nestedException.getClass().toString().startsWith("class " + exceptionPrefix)) {
lastLowException = (Exception) nestedException;
}
nestedException = getInnerException(nestedException);
}
return lastLowException;
} | [
"public",
"static",
"Exception",
"getLowestException",
"(",
"final",
"Exception",
"exception",
",",
"final",
"String",
"exceptionPrefix",
")",
"{",
"if",
"(",
"exception",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"Throwable",
"nestedException",
"=",
... | Get the most inner exception that is exception from "exceptionPrefix"
type. If the exception does not include inner exception of type
"exceptionPrefix", returns null.
@param exception
@param exceptionPrefix
@return | [
"Get",
"the",
"most",
"inner",
"exception",
"that",
"is",
"exception",
"from",
"exceptionPrefix",
"type",
".",
"If",
"the",
"exception",
"does",
"not",
"include",
"inner",
"exception",
"of",
"type",
"exceptionPrefix",
"returns",
"null",
"."
] | train | https://github.com/foundation-runtime/common/blob/8d243111f68dc620bdea0659f9fff75fe05f0447/commons/src/main/java/com/cisco/oss/foundation/application/exception/ExceptionUtil.java#L92-L109 |
xcesco/kripton | kripton-core/src/main/java/com/abubusoft/kripton/common/TypeAdapterUtils.java | TypeAdapterUtils.toData | @SuppressWarnings("unchecked")
public static <D, J> D toData(Class<? extends TypeAdapter<J, D>> clazz, J javaValue) {
"""
To data.
@param <D> the generic type
@param <J> the generic type
@param clazz the clazz
@param javaValue the java value
@return the d
"""
TypeAdapter<J, D> adapter = cache.get(clazz);
if (adapter == null) {
adapter = generateAdapter(cache, lock, clazz);
}
return adapter.toData(javaValue);
} | java | @SuppressWarnings("unchecked")
public static <D, J> D toData(Class<? extends TypeAdapter<J, D>> clazz, J javaValue) {
TypeAdapter<J, D> adapter = cache.get(clazz);
if (adapter == null) {
adapter = generateAdapter(cache, lock, clazz);
}
return adapter.toData(javaValue);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"D",
",",
"J",
">",
"D",
"toData",
"(",
"Class",
"<",
"?",
"extends",
"TypeAdapter",
"<",
"J",
",",
"D",
">",
">",
"clazz",
",",
"J",
"javaValue",
")",
"{",
"TypeAdapter",
"... | To data.
@param <D> the generic type
@param <J> the generic type
@param clazz the clazz
@param javaValue the java value
@return the d | [
"To",
"data",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-core/src/main/java/com/abubusoft/kripton/common/TypeAdapterUtils.java#L66-L75 |
wildfly/wildfly-core | patching/src/main/java/org/jboss/as/patching/installation/LayersFactory.java | LayersFactory.createPatchableTarget | static AbstractLazyPatchableTarget createPatchableTarget(final String name, final LayerPathConfig layer, final File metadata, final InstalledImage image) throws IOException {
"""
Create the actual patchable target.
@param name the layer name
@param layer the layer path config
@param metadata the metadata location for this target
@param image the installed image
@return the patchable target
@throws IOException
"""
// patchable target
return new AbstractLazyPatchableTarget() {
@Override
public InstalledImage getInstalledImage() {
return image;
}
@Override
public File getModuleRoot() {
return layer.modulePath;
}
@Override
public File getBundleRepositoryRoot() {
return layer.bundlePath;
}
public File getPatchesMetadata() {
return metadata;
}
@Override
public String getName() {
return name;
}
};
} | java | static AbstractLazyPatchableTarget createPatchableTarget(final String name, final LayerPathConfig layer, final File metadata, final InstalledImage image) throws IOException {
// patchable target
return new AbstractLazyPatchableTarget() {
@Override
public InstalledImage getInstalledImage() {
return image;
}
@Override
public File getModuleRoot() {
return layer.modulePath;
}
@Override
public File getBundleRepositoryRoot() {
return layer.bundlePath;
}
public File getPatchesMetadata() {
return metadata;
}
@Override
public String getName() {
return name;
}
};
} | [
"static",
"AbstractLazyPatchableTarget",
"createPatchableTarget",
"(",
"final",
"String",
"name",
",",
"final",
"LayerPathConfig",
"layer",
",",
"final",
"File",
"metadata",
",",
"final",
"InstalledImage",
"image",
")",
"throws",
"IOException",
"{",
"// patchable target... | Create the actual patchable target.
@param name the layer name
@param layer the layer path config
@param metadata the metadata location for this target
@param image the installed image
@return the patchable target
@throws IOException | [
"Create",
"the",
"actual",
"patchable",
"target",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/patching/src/main/java/org/jboss/as/patching/installation/LayersFactory.java#L205-L233 |
nguillaumin/slick2d-maven | slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/truetype/FontData.java | FontData.getKerning | public int getKerning(char first, char second) {
"""
Get the kerning value between two characters
@param first The first character
@param second The second character
@return The amount of kerning to apply between the two characters
"""
Map toMap = (Map) ansiKerning.get(new Integer(first));
if (toMap == null) {
return 0;
}
Integer kerning = (Integer) toMap.get(new Integer(second));
if (kerning == null) {
return 0;
}
return Math.round(convertUnitToEm(size, kerning.intValue()));
} | java | public int getKerning(char first, char second) {
Map toMap = (Map) ansiKerning.get(new Integer(first));
if (toMap == null) {
return 0;
}
Integer kerning = (Integer) toMap.get(new Integer(second));
if (kerning == null) {
return 0;
}
return Math.round(convertUnitToEm(size, kerning.intValue()));
} | [
"public",
"int",
"getKerning",
"(",
"char",
"first",
",",
"char",
"second",
")",
"{",
"Map",
"toMap",
"=",
"(",
"Map",
")",
"ansiKerning",
".",
"get",
"(",
"new",
"Integer",
"(",
"first",
")",
")",
";",
"if",
"(",
"toMap",
"==",
"null",
")",
"{",
... | Get the kerning value between two characters
@param first The first character
@param second The second character
@return The amount of kerning to apply between the two characters | [
"Get",
"the",
"kerning",
"value",
"between",
"two",
"characters"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/truetype/FontData.java#L493-L505 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/MembersView.java | MembersView.createNew | public static MembersView createNew(int version, Collection<MemberImpl> members) {
"""
Creates a new {@code MemberMap} including given members.
@param version version
@param members members
@return a new {@code MemberMap}
"""
List<MemberInfo> list = new ArrayList<>(members.size());
for (MemberImpl member : members) {
list.add(new MemberInfo(member));
}
return new MembersView(version, unmodifiableList(list));
} | java | public static MembersView createNew(int version, Collection<MemberImpl> members) {
List<MemberInfo> list = new ArrayList<>(members.size());
for (MemberImpl member : members) {
list.add(new MemberInfo(member));
}
return new MembersView(version, unmodifiableList(list));
} | [
"public",
"static",
"MembersView",
"createNew",
"(",
"int",
"version",
",",
"Collection",
"<",
"MemberImpl",
">",
"members",
")",
"{",
"List",
"<",
"MemberInfo",
">",
"list",
"=",
"new",
"ArrayList",
"<>",
"(",
"members",
".",
"size",
"(",
")",
")",
";",... | Creates a new {@code MemberMap} including given members.
@param version version
@param members members
@return a new {@code MemberMap} | [
"Creates",
"a",
"new",
"{",
"@code",
"MemberMap",
"}",
"including",
"given",
"members",
"."
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/MembersView.java#L81-L89 |
orhanobut/dialogplus | dialogplus/src/main/java/com/orhanobut/dialogplus/DialogPlusBuilder.java | DialogPlusBuilder.setFooter | public DialogPlusBuilder setFooter(@NonNull View view, boolean fixed) {
"""
Sets the given view as footer.
@param fixed is used to determine whether footer should be fixed or not. Fixed if true, scrollable otherwise
"""
this.footerView = view;
this.fixedFooter = fixed;
return this;
} | java | public DialogPlusBuilder setFooter(@NonNull View view, boolean fixed) {
this.footerView = view;
this.fixedFooter = fixed;
return this;
} | [
"public",
"DialogPlusBuilder",
"setFooter",
"(",
"@",
"NonNull",
"View",
"view",
",",
"boolean",
"fixed",
")",
"{",
"this",
".",
"footerView",
"=",
"view",
";",
"this",
".",
"fixedFooter",
"=",
"fixed",
";",
"return",
"this",
";",
"}"
] | Sets the given view as footer.
@param fixed is used to determine whether footer should be fixed or not. Fixed if true, scrollable otherwise | [
"Sets",
"the",
"given",
"view",
"as",
"footer",
"."
] | train | https://github.com/orhanobut/dialogplus/blob/291bf4daaa3c81bf5537125f547913beb8ee2c17/dialogplus/src/main/java/com/orhanobut/dialogplus/DialogPlusBuilder.java#L101-L105 |
jferard/fastods | fastods/src/main/java/com/github/jferard/fastods/odselement/StylesContainer.java | StylesContainer.writeContentAutomaticStyles | public void writeContentAutomaticStyles(final XMLUtil util, final Appendable appendable)
throws IOException {
"""
Write the various styles in the automatic styles.
@param util an XML util
@param appendable the destination
@throws IOException if the styles can't be written
"""
final Iterable<ObjectStyle> styles = this.objectStylesContainer
.getValues(Dest.CONTENT_AUTOMATIC_STYLES);
for (final ObjectStyle style : styles)
assert style.isHidden() : style.toString();
this.write(styles, util, appendable);
} | java | public void writeContentAutomaticStyles(final XMLUtil util, final Appendable appendable)
throws IOException {
final Iterable<ObjectStyle> styles = this.objectStylesContainer
.getValues(Dest.CONTENT_AUTOMATIC_STYLES);
for (final ObjectStyle style : styles)
assert style.isHidden() : style.toString();
this.write(styles, util, appendable);
} | [
"public",
"void",
"writeContentAutomaticStyles",
"(",
"final",
"XMLUtil",
"util",
",",
"final",
"Appendable",
"appendable",
")",
"throws",
"IOException",
"{",
"final",
"Iterable",
"<",
"ObjectStyle",
">",
"styles",
"=",
"this",
".",
"objectStylesContainer",
".",
"... | Write the various styles in the automatic styles.
@param util an XML util
@param appendable the destination
@throws IOException if the styles can't be written | [
"Write",
"the",
"various",
"styles",
"in",
"the",
"automatic",
"styles",
"."
] | train | https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/odselement/StylesContainer.java#L363-L371 |
codescape/bitvunit | bitvunit-core/src/main/java/de/codescape/bitvunit/util/html/HtmlPageUtil.java | HtmlPageUtil.toHtmlPage | public static HtmlPage toHtmlPage(WebDriver webDriver) {
"""
Create a {@link HtmlPage} from a given {@link WebDriver} that has been navigated to a HTML page.
@param webDriver {@link WebDriver} that has been navigated to a HTML page
@return {@link HtmlPage} for the {@link WebDriver}
"""
try {
return HTMLParser.parseHtml(
new StringWebResponse(webDriver.getPageSource(), new URL(webDriver.getCurrentUrl())),
new WebClient().getCurrentWindow()
);
} catch (IOException e) {
throw new RuntimeException("Error creating HtmlPage from WebDriver.", e);
}
} | java | public static HtmlPage toHtmlPage(WebDriver webDriver) {
try {
return HTMLParser.parseHtml(
new StringWebResponse(webDriver.getPageSource(), new URL(webDriver.getCurrentUrl())),
new WebClient().getCurrentWindow()
);
} catch (IOException e) {
throw new RuntimeException("Error creating HtmlPage from WebDriver.", e);
}
} | [
"public",
"static",
"HtmlPage",
"toHtmlPage",
"(",
"WebDriver",
"webDriver",
")",
"{",
"try",
"{",
"return",
"HTMLParser",
".",
"parseHtml",
"(",
"new",
"StringWebResponse",
"(",
"webDriver",
".",
"getPageSource",
"(",
")",
",",
"new",
"URL",
"(",
"webDriver",... | Create a {@link HtmlPage} from a given {@link WebDriver} that has been navigated to a HTML page.
@param webDriver {@link WebDriver} that has been navigated to a HTML page
@return {@link HtmlPage} for the {@link WebDriver} | [
"Create",
"a",
"{",
"@link",
"HtmlPage",
"}",
"from",
"a",
"given",
"{",
"@link",
"WebDriver",
"}",
"that",
"has",
"been",
"navigated",
"to",
"a",
"HTML",
"page",
"."
] | train | https://github.com/codescape/bitvunit/blob/cef6d9af60d684e41294981c10b6d92c8f063a4e/bitvunit-core/src/main/java/de/codescape/bitvunit/util/html/HtmlPageUtil.java#L89-L98 |
jhunters/jprotobuf | src/main/java/com/baidu/bjf/remoting/protobuf/ProtobufIDLProxy.java | ProtobufIDLProxy.createSingle | public static IDLProxyObject createSingle(InputStream is, boolean debug, File path, boolean isUniName)
throws IOException {
"""
Creates the single {@link IDLProxyObject}.
@param is the is
@param debug the debug
@param path the path
@param isUniName the is uni name
@return the IDL proxy object
@throws IOException Signals that an I/O exception has occurred.
"""
ProtoFile protoFile = ProtoSchemaParser.parseUtf8(DEFAULT_FILE_NAME, is);
List<CodeDependent> cds = new ArrayList<CodeDependent>();
Map<String, IDLProxyObject> map =
doCreate(protoFile, false, debug, path, false, null, cds, new HashMap<String, String>(), isUniName);
return map.entrySet().iterator().next().getValue();
} | java | public static IDLProxyObject createSingle(InputStream is, boolean debug, File path, boolean isUniName)
throws IOException {
ProtoFile protoFile = ProtoSchemaParser.parseUtf8(DEFAULT_FILE_NAME, is);
List<CodeDependent> cds = new ArrayList<CodeDependent>();
Map<String, IDLProxyObject> map =
doCreate(protoFile, false, debug, path, false, null, cds, new HashMap<String, String>(), isUniName);
return map.entrySet().iterator().next().getValue();
} | [
"public",
"static",
"IDLProxyObject",
"createSingle",
"(",
"InputStream",
"is",
",",
"boolean",
"debug",
",",
"File",
"path",
",",
"boolean",
"isUniName",
")",
"throws",
"IOException",
"{",
"ProtoFile",
"protoFile",
"=",
"ProtoSchemaParser",
".",
"parseUtf8",
"(",... | Creates the single {@link IDLProxyObject}.
@param is the is
@param debug the debug
@param path the path
@param isUniName the is uni name
@return the IDL proxy object
@throws IOException Signals that an I/O exception has occurred. | [
"Creates",
"the",
"single",
"{",
"@link",
"IDLProxyObject",
"}",
"."
] | train | https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/src/main/java/com/baidu/bjf/remoting/protobuf/ProtobufIDLProxy.java#L1016-L1023 |
apache/groovy | subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java | NioGroovyMethods.leftShift | public static Path leftShift(Path path, InputStream data) throws IOException {
"""
Append binary data to the file. See {@link #append(Path, java.io.InputStream)}
@param path a Path
@param data an InputStream of data to write to the file
@return the file
@throws java.io.IOException if an IOException occurs.
@since 2.3.0
"""
append(path, data);
return path;
} | java | public static Path leftShift(Path path, InputStream data) throws IOException {
append(path, data);
return path;
} | [
"public",
"static",
"Path",
"leftShift",
"(",
"Path",
"path",
",",
"InputStream",
"data",
")",
"throws",
"IOException",
"{",
"append",
"(",
"path",
",",
"data",
")",
";",
"return",
"path",
";",
"}"
] | Append binary data to the file. See {@link #append(Path, java.io.InputStream)}
@param path a Path
@param data an InputStream of data to write to the file
@return the file
@throws java.io.IOException if an IOException occurs.
@since 2.3.0 | [
"Append",
"binary",
"data",
"to",
"the",
"file",
".",
"See",
"{",
"@link",
"#append",
"(",
"Path",
"java",
".",
"io",
".",
"InputStream",
")",
"}"
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java#L520-L523 |
apache/incubator-druid | processing/src/main/java/org/apache/druid/segment/data/GenericIndexed.java | GenericIndexed.checkIndex | private void checkIndex(int index) {
"""
Checks if {@code index} a valid `element index` in GenericIndexed.
Similar to Preconditions.checkElementIndex() except this method throws {@link IAE} with custom error message.
<p>
Used here to get existing behavior(same error message and exception) of V1 GenericIndexed.
@param index index identifying an element of an GenericIndexed.
"""
if (index < 0) {
throw new IAE("Index[%s] < 0", index);
}
if (index >= size) {
throw new IAE("Index[%d] >= size[%d]", index, size);
}
} | java | private void checkIndex(int index)
{
if (index < 0) {
throw new IAE("Index[%s] < 0", index);
}
if (index >= size) {
throw new IAE("Index[%d] >= size[%d]", index, size);
}
} | [
"private",
"void",
"checkIndex",
"(",
"int",
"index",
")",
"{",
"if",
"(",
"index",
"<",
"0",
")",
"{",
"throw",
"new",
"IAE",
"(",
"\"Index[%s] < 0\"",
",",
"index",
")",
";",
"}",
"if",
"(",
"index",
">=",
"size",
")",
"{",
"throw",
"new",
"IAE",... | Checks if {@code index} a valid `element index` in GenericIndexed.
Similar to Preconditions.checkElementIndex() except this method throws {@link IAE} with custom error message.
<p>
Used here to get existing behavior(same error message and exception) of V1 GenericIndexed.
@param index index identifying an element of an GenericIndexed. | [
"Checks",
"if",
"{",
"@code",
"index",
"}",
"a",
"valid",
"element",
"index",
"in",
"GenericIndexed",
".",
"Similar",
"to",
"Preconditions",
".",
"checkElementIndex",
"()",
"except",
"this",
"method",
"throws",
"{",
"@link",
"IAE",
"}",
"with",
"custom",
"er... | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/processing/src/main/java/org/apache/druid/segment/data/GenericIndexed.java#L265-L273 |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/util/XmlPrintStream.java | XmlPrintStream.printElement | public void printElement(String elementName, String value, Map<String, String> attributes) {
"""
Output a complete element with the given content and attributes.
@param elementName Name of element.
@param value Content of element.
@param attributes A map of name value pairs which will be used to add attributes to
the element.
"""
print("<" + elementName);
for (Entry<String, String> entry : attributes.entrySet()) {
print(" " + entry.getKey() + "=\"" + escape(entry.getValue()) + "\"");
}
if (value != null) {
println(">" + escape(value) + "</" + elementName + ">");
} else {
println("/>");
}
} | java | public void printElement(String elementName, String value, Map<String, String> attributes) {
print("<" + elementName);
for (Entry<String, String> entry : attributes.entrySet()) {
print(" " + entry.getKey() + "=\"" + escape(entry.getValue()) + "\"");
}
if (value != null) {
println(">" + escape(value) + "</" + elementName + ">");
} else {
println("/>");
}
} | [
"public",
"void",
"printElement",
"(",
"String",
"elementName",
",",
"String",
"value",
",",
"Map",
"<",
"String",
",",
"String",
">",
"attributes",
")",
"{",
"print",
"(",
"\"<\"",
"+",
"elementName",
")",
";",
"for",
"(",
"Entry",
"<",
"String",
",",
... | Output a complete element with the given content and attributes.
@param elementName Name of element.
@param value Content of element.
@param attributes A map of name value pairs which will be used to add attributes to
the element. | [
"Output",
"a",
"complete",
"element",
"with",
"the",
"given",
"content",
"and",
"attributes",
"."
] | train | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/util/XmlPrintStream.java#L133-L145 |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/shapes/ellipse/SnapToEllipseEdge.java | SnapToEllipseEdge.computePointsAndWeights | void computePointsAndWeights(EllipseRotated_F64 ellipse) {
"""
Computes the location of points along the line and their weights
"""
// use the semi-major axis to scale the input points for numerical stability
double localScale = ellipse.a;
samplePts.reset();
weights.reset();
int numSamples = radialSamples * 2 + 2;
int numPts = numSamples - 1;
Point2D_F64 sample = new Point2D_F64();
for (int i = 0; i < numSampleContour; i++) {
// find a point along the ellipse at evenly spaced angles
double theta = 2.0 * Math.PI * i / numSampleContour;
UtilEllipse_F64.computePoint(theta, ellipse, sample);
// compute the unit tangent along the ellipse at this point
double tanX = sample.x - ellipse.center.x;
double tanY = sample.y - ellipse.center.y;
double r = Math.sqrt(tanX * tanX + tanY * tanY);
tanX /= r;
tanY /= r;
// define the line it will sample along
double x = sample.x - numSamples * tanX / 2.0;
double y = sample.y - numSamples * tanY / 2.0;
double lengthX = numSamples * tanX;
double lengthY = numSamples * tanY;
// Unless all the sample points are inside the image, ignore this point
if (!integral.isInside(x, y) || !integral.isInside(x + lengthX, y + lengthY))
continue;
double sample0 = integral.compute(x, y, x + tanX, y + tanY);
x += tanX;
y += tanY;
for (int j = 0; j < numPts; j++) {
double sample1 = integral.compute(x, y, x + tanX, y + tanY);
double w = sample0 - sample1;
if (w < 0) w = -w;
if (w > 0) {
// convert into a local coordinate so make the linear fitting more numerically stable and
// independent on position in the image
samplePts.grow().set((x - ellipse.center.x) / localScale, (y - ellipse.center.y) / localScale);
weights.add(w);
}
x += tanX;
y += tanY;
sample0 = sample1;
}
}
} | java | void computePointsAndWeights(EllipseRotated_F64 ellipse) {
// use the semi-major axis to scale the input points for numerical stability
double localScale = ellipse.a;
samplePts.reset();
weights.reset();
int numSamples = radialSamples * 2 + 2;
int numPts = numSamples - 1;
Point2D_F64 sample = new Point2D_F64();
for (int i = 0; i < numSampleContour; i++) {
// find a point along the ellipse at evenly spaced angles
double theta = 2.0 * Math.PI * i / numSampleContour;
UtilEllipse_F64.computePoint(theta, ellipse, sample);
// compute the unit tangent along the ellipse at this point
double tanX = sample.x - ellipse.center.x;
double tanY = sample.y - ellipse.center.y;
double r = Math.sqrt(tanX * tanX + tanY * tanY);
tanX /= r;
tanY /= r;
// define the line it will sample along
double x = sample.x - numSamples * tanX / 2.0;
double y = sample.y - numSamples * tanY / 2.0;
double lengthX = numSamples * tanX;
double lengthY = numSamples * tanY;
// Unless all the sample points are inside the image, ignore this point
if (!integral.isInside(x, y) || !integral.isInside(x + lengthX, y + lengthY))
continue;
double sample0 = integral.compute(x, y, x + tanX, y + tanY);
x += tanX;
y += tanY;
for (int j = 0; j < numPts; j++) {
double sample1 = integral.compute(x, y, x + tanX, y + tanY);
double w = sample0 - sample1;
if (w < 0) w = -w;
if (w > 0) {
// convert into a local coordinate so make the linear fitting more numerically stable and
// independent on position in the image
samplePts.grow().set((x - ellipse.center.x) / localScale, (y - ellipse.center.y) / localScale);
weights.add(w);
}
x += tanX;
y += tanY;
sample0 = sample1;
}
}
} | [
"void",
"computePointsAndWeights",
"(",
"EllipseRotated_F64",
"ellipse",
")",
"{",
"// use the semi-major axis to scale the input points for numerical stability",
"double",
"localScale",
"=",
"ellipse",
".",
"a",
";",
"samplePts",
".",
"reset",
"(",
")",
";",
"weights",
"... | Computes the location of points along the line and their weights | [
"Computes",
"the",
"location",
"of",
"points",
"along",
"the",
"line",
"and",
"their",
"weights"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/ellipse/SnapToEllipseEdge.java#L134-L192 |
forge/core | scaffold/spi/src/main/java/org/jboss/forge/addon/scaffold/metawidget/inspector/propertystyle/ForgePropertyStyle.java | ForgePropertyStyle.isGetter | protected String isGetter(final Method<?, ?> method) {
"""
Returns whether the given method is a 'getter' method.
@param method a parameterless method that returns a non-void
@return the property name
"""
String methodName = method.getName();
String propertyName;
if (methodName.startsWith(ClassUtils.JAVABEAN_GET_PREFIX))
{
propertyName = methodName.substring(ClassUtils.JAVABEAN_GET_PREFIX.length());
}
else if (methodName.startsWith(ClassUtils.JAVABEAN_IS_PREFIX)
&& method.getReturnType() != null && boolean.class.equals(method.getReturnType().getQualifiedName()))
{
// As per section 8.3.2 (Boolean properties) of The JavaBeans API specification, 'is'
// only applies to boolean (little 'b')
propertyName = methodName.substring(ClassUtils.JAVABEAN_IS_PREFIX.length());
}
else
{
return null;
}
return StringUtils.decapitalize(propertyName);
} | java | protected String isGetter(final Method<?, ?> method)
{
String methodName = method.getName();
String propertyName;
if (methodName.startsWith(ClassUtils.JAVABEAN_GET_PREFIX))
{
propertyName = methodName.substring(ClassUtils.JAVABEAN_GET_PREFIX.length());
}
else if (methodName.startsWith(ClassUtils.JAVABEAN_IS_PREFIX)
&& method.getReturnType() != null && boolean.class.equals(method.getReturnType().getQualifiedName()))
{
// As per section 8.3.2 (Boolean properties) of The JavaBeans API specification, 'is'
// only applies to boolean (little 'b')
propertyName = methodName.substring(ClassUtils.JAVABEAN_IS_PREFIX.length());
}
else
{
return null;
}
return StringUtils.decapitalize(propertyName);
} | [
"protected",
"String",
"isGetter",
"(",
"final",
"Method",
"<",
"?",
",",
"?",
">",
"method",
")",
"{",
"String",
"methodName",
"=",
"method",
".",
"getName",
"(",
")",
";",
"String",
"propertyName",
";",
"if",
"(",
"methodName",
".",
"startsWith",
"(",
... | Returns whether the given method is a 'getter' method.
@param method a parameterless method that returns a non-void
@return the property name | [
"Returns",
"whether",
"the",
"given",
"method",
"is",
"a",
"getter",
"method",
"."
] | train | https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/scaffold/spi/src/main/java/org/jboss/forge/addon/scaffold/metawidget/inspector/propertystyle/ForgePropertyStyle.java#L240-L266 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/field/event/MainFieldHandler.java | MainFieldHandler.init | public void init(BaseField field, String keyName) {
"""
Constructor.
@param field The basefield owner of this listener (usually null and set on setOwner()).
@param iKeySeq The key area this field accesses.
"""
super.init(field);
this.keyName = keyName;
m_bInitMove = false; // DONT respond to these moves!
m_bReadMove = false;
m_bReadOnly = false;
} | java | public void init(BaseField field, String keyName)
{
super.init(field);
this.keyName = keyName;
m_bInitMove = false; // DONT respond to these moves!
m_bReadMove = false;
m_bReadOnly = false;
} | [
"public",
"void",
"init",
"(",
"BaseField",
"field",
",",
"String",
"keyName",
")",
"{",
"super",
".",
"init",
"(",
"field",
")",
";",
"this",
".",
"keyName",
"=",
"keyName",
";",
"m_bInitMove",
"=",
"false",
";",
"// DONT respond to these moves!",
"m_bReadM... | Constructor.
@param field The basefield owner of this listener (usually null and set on setOwner()).
@param iKeySeq The key area this field accesses. | [
"Constructor",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/MainFieldHandler.java#L65-L73 |
crowmagnumb/s6-util | src/main/java/net/crowmagnumb/util/net/AbstractMultipartUtility.java | AbstractMultipartUtility.addFilePart | public void addFilePart(final String fieldName, final InputStream stream, final String fileName, final String contentType)
throws IOException {
"""
Adds a upload file section to the request
@param fieldName name attribute in <input type="file" name="..." />
@param stream input stream of data to upload
@param fileName name of file represented by this input stream
@param contentType content type of data
@throws IOException if problems
"""
writer.append("--").append(boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"").append(fieldName).append("\"");
if (fileName != null) {
writer.append("; filename=\"").append(fileName).append("\"");
}
writer.append(LINE_FEED);
writer.append("Content-Type: ").append(contentType).append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
OsUtils.copyStreams(stream, outputStream);
outputStream.flush();
writer.append(LINE_FEED);
writer.flush();
} | java | public void addFilePart(final String fieldName, final InputStream stream, final String fileName, final String contentType)
throws IOException
{
writer.append("--").append(boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"").append(fieldName).append("\"");
if (fileName != null) {
writer.append("; filename=\"").append(fileName).append("\"");
}
writer.append(LINE_FEED);
writer.append("Content-Type: ").append(contentType).append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
OsUtils.copyStreams(stream, outputStream);
outputStream.flush();
writer.append(LINE_FEED);
writer.flush();
} | [
"public",
"void",
"addFilePart",
"(",
"final",
"String",
"fieldName",
",",
"final",
"InputStream",
"stream",
",",
"final",
"String",
"fileName",
",",
"final",
"String",
"contentType",
")",
"throws",
"IOException",
"{",
"writer",
".",
"append",
"(",
"\"--\"",
"... | Adds a upload file section to the request
@param fieldName name attribute in <input type="file" name="..." />
@param stream input stream of data to upload
@param fileName name of file represented by this input stream
@param contentType content type of data
@throws IOException if problems | [
"Adds",
"a",
"upload",
"file",
"section",
"to",
"the",
"request"
] | train | https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/net/AbstractMultipartUtility.java#L105-L127 |
lazy-koala/java-toolkit | fast-toolkit/src/main/java/com/thankjava/toolkit/core/reflect/ReflectUtil.java | ReflectUtil.setFieldVal | public static void setFieldVal(Object obj, String fieldName, Object value) {
"""
为字段属性设置属性值
<p>Function: setFieldVal</p>
<p>Description: </p>
@param obj
@param fieldName
@param value
@author acexy@thankjava.com
@date 2014-12-18 上午9:52:18
@version 1.0
"""
Field field;
if (obj == null) {
return;
}
try {
field = getField(obj.getClass(), fieldName);
field.setAccessible(true);//取消安全机制限制
field.set(obj, value);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} | java | public static void setFieldVal(Object obj, String fieldName, Object value) {
Field field;
if (obj == null) {
return;
}
try {
field = getField(obj.getClass(), fieldName);
field.setAccessible(true);//取消安全机制限制
field.set(obj, value);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} | [
"public",
"static",
"void",
"setFieldVal",
"(",
"Object",
"obj",
",",
"String",
"fieldName",
",",
"Object",
"value",
")",
"{",
"Field",
"field",
";",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"return",
";",
"}",
"try",
"{",
"field",
"=",
"getField",
... | 为字段属性设置属性值
<p>Function: setFieldVal</p>
<p>Description: </p>
@param obj
@param fieldName
@param value
@author acexy@thankjava.com
@date 2014-12-18 上午9:52:18
@version 1.0 | [
"为字段属性设置属性值",
"<p",
">",
"Function",
":",
"setFieldVal<",
"/",
"p",
">",
"<p",
">",
"Description",
":",
"<",
"/",
"p",
">"
] | train | https://github.com/lazy-koala/java-toolkit/blob/f46055fae0cc73049597a3708e515f5c6582d27a/fast-toolkit/src/main/java/com/thankjava/toolkit/core/reflect/ReflectUtil.java#L168-L184 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/uri/ContentUriChecker.java | ContentUriChecker.replaceInternalFromUri | private String replaceInternalFromUri(String input, final List<Triple<Token, Token, String>> replace, UriBaseListener rewriterListener) {
"""
Replace internal from uri.
@param input the input
@param replace the replace
@param rewriterListener the rewriter listener
@return the string
"""
Pair<ParserRuleContext, CommonTokenStream> parser = prepareUri(input);
pathSegmentIndex = -1;
walker.walk(rewriterListener, parser.value0);
TokenStreamRewriter rewriter = new TokenStreamRewriter(parser.value1);
for (Triple<Token, Token, String> item : replace) {
rewriter.replace(item.value0, item.value1, item.value2);
}
return rewriter.getText();
} | java | private String replaceInternalFromUri(String input, final List<Triple<Token, Token, String>> replace, UriBaseListener rewriterListener) {
Pair<ParserRuleContext, CommonTokenStream> parser = prepareUri(input);
pathSegmentIndex = -1;
walker.walk(rewriterListener, parser.value0);
TokenStreamRewriter rewriter = new TokenStreamRewriter(parser.value1);
for (Triple<Token, Token, String> item : replace) {
rewriter.replace(item.value0, item.value1, item.value2);
}
return rewriter.getText();
} | [
"private",
"String",
"replaceInternalFromUri",
"(",
"String",
"input",
",",
"final",
"List",
"<",
"Triple",
"<",
"Token",
",",
"Token",
",",
"String",
">",
">",
"replace",
",",
"UriBaseListener",
"rewriterListener",
")",
"{",
"Pair",
"<",
"ParserRuleContext",
... | Replace internal from uri.
@param input the input
@param replace the replace
@param rewriterListener the rewriter listener
@return the string | [
"Replace",
"internal",
"from",
"uri",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/uri/ContentUriChecker.java#L279-L291 |
mozilla/rhino | toolsrc/org/mozilla/javascript/tools/debugger/Dim.java | Dim.stringIsCompilableUnit | public boolean stringIsCompilableUnit(String str) {
"""
Returns whether the given string is syntactically valid script.
"""
DimIProxy action = new DimIProxy(this, IPROXY_STRING_IS_COMPILABLE);
action.text = str;
action.withContext();
return action.booleanResult;
} | java | public boolean stringIsCompilableUnit(String str) {
DimIProxy action = new DimIProxy(this, IPROXY_STRING_IS_COMPILABLE);
action.text = str;
action.withContext();
return action.booleanResult;
} | [
"public",
"boolean",
"stringIsCompilableUnit",
"(",
"String",
"str",
")",
"{",
"DimIProxy",
"action",
"=",
"new",
"DimIProxy",
"(",
"this",
",",
"IPROXY_STRING_IS_COMPILABLE",
")",
";",
"action",
".",
"text",
"=",
"str",
";",
"action",
".",
"withContext",
"(",... | Returns whether the given string is syntactically valid script. | [
"Returns",
"whether",
"the",
"given",
"string",
"is",
"syntactically",
"valid",
"script",
"."
] | train | https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/toolsrc/org/mozilla/javascript/tools/debugger/Dim.java#L624-L629 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.