repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
sequencelengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
sequencelengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
Whiley/WhileyCompiler | src/main/java/wyil/check/FlowTypeCheck.java | FlowTypeCheck.extractElementType | public SemanticType extractElementType(SemanticType.Reference type, SyntacticItem item) {
"""
Extract the element type from a reference. The array type can be null if some
earlier part of type checking generated an error message and we are just
continuing after that.
@param type
@param item
@return
"""
if (type == null) {
return null;
} else {
return type.getElement();
}
} | java | public SemanticType extractElementType(SemanticType.Reference type, SyntacticItem item) {
if (type == null) {
return null;
} else {
return type.getElement();
}
} | [
"public",
"SemanticType",
"extractElementType",
"(",
"SemanticType",
".",
"Reference",
"type",
",",
"SyntacticItem",
"item",
")",
"{",
"if",
"(",
"type",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"else",
"{",
"return",
"type",
".",
"getElement",
"(",
")",
";",
"}",
"}"
] | Extract the element type from a reference. The array type can be null if some
earlier part of type checking generated an error message and we are just
continuing after that.
@param type
@param item
@return | [
"Extract",
"the",
"element",
"type",
"from",
"a",
"reference",
".",
"The",
"array",
"type",
"can",
"be",
"null",
"if",
"some",
"earlier",
"part",
"of",
"type",
"checking",
"generated",
"an",
"error",
"message",
"and",
"we",
"are",
"just",
"continuing",
"after",
"that",
"."
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/check/FlowTypeCheck.java#L1978-L1984 |
graknlabs/grakn | server/src/graql/reasoner/cache/QueryCacheBase.java | QueryCacheBase.putEntry | CacheEntry<Q, SE> putEntry(Q query, SE answers) {
"""
Associates the specified answers with the specified query in this cache adding an (query) -> (answers) entry
@param query of the association
@param answers of the association
@return previous value if any or null
"""
return putEntry(new CacheEntry<>(query, answers));
} | java | CacheEntry<Q, SE> putEntry(Q query, SE answers) {
return putEntry(new CacheEntry<>(query, answers));
} | [
"CacheEntry",
"<",
"Q",
",",
"SE",
">",
"putEntry",
"(",
"Q",
"query",
",",
"SE",
"answers",
")",
"{",
"return",
"putEntry",
"(",
"new",
"CacheEntry",
"<>",
"(",
"query",
",",
"answers",
")",
")",
";",
"}"
] | Associates the specified answers with the specified query in this cache adding an (query) -> (answers) entry
@param query of the association
@param answers of the association
@return previous value if any or null | [
"Associates",
"the",
"specified",
"answers",
"with",
"the",
"specified",
"query",
"in",
"this",
"cache",
"adding",
"an",
"(",
"query",
")",
"-",
">",
"(",
"answers",
")",
"entry"
] | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/reasoner/cache/QueryCacheBase.java#L129-L131 |
b3dgs/lionengine | lionengine-core-awt/src/main/java/com/b3dgs/lionengine/awt/graphic/ScreenFullAwt.java | ScreenFullAwt.formatResolution | private static String formatResolution(Resolution resolution, int depth) {
"""
Format resolution to string.
@param resolution The resolution reference.
@param depth The depth reference.
@return The formatted string.
"""
return new StringBuilder(MIN_LENGTH).append(String.valueOf(resolution.getWidth()))
.append(Constant.STAR)
.append(String.valueOf(resolution.getHeight()))
.append(Constant.STAR)
.append(depth)
.append(Constant.SPACE)
.append(Constant.AT)
.append(String.valueOf(resolution.getRate()))
.append(Constant.UNIT_RATE)
.toString();
} | java | private static String formatResolution(Resolution resolution, int depth)
{
return new StringBuilder(MIN_LENGTH).append(String.valueOf(resolution.getWidth()))
.append(Constant.STAR)
.append(String.valueOf(resolution.getHeight()))
.append(Constant.STAR)
.append(depth)
.append(Constant.SPACE)
.append(Constant.AT)
.append(String.valueOf(resolution.getRate()))
.append(Constant.UNIT_RATE)
.toString();
} | [
"private",
"static",
"String",
"formatResolution",
"(",
"Resolution",
"resolution",
",",
"int",
"depth",
")",
"{",
"return",
"new",
"StringBuilder",
"(",
"MIN_LENGTH",
")",
".",
"append",
"(",
"String",
".",
"valueOf",
"(",
"resolution",
".",
"getWidth",
"(",
")",
")",
")",
".",
"append",
"(",
"Constant",
".",
"STAR",
")",
".",
"append",
"(",
"String",
".",
"valueOf",
"(",
"resolution",
".",
"getHeight",
"(",
")",
")",
")",
".",
"append",
"(",
"Constant",
".",
"STAR",
")",
".",
"append",
"(",
"depth",
")",
".",
"append",
"(",
"Constant",
".",
"SPACE",
")",
".",
"append",
"(",
"Constant",
".",
"AT",
")",
".",
"append",
"(",
"String",
".",
"valueOf",
"(",
"resolution",
".",
"getRate",
"(",
")",
")",
")",
".",
"append",
"(",
"Constant",
".",
"UNIT_RATE",
")",
".",
"toString",
"(",
")",
";",
"}"
] | Format resolution to string.
@param resolution The resolution reference.
@param depth The depth reference.
@return The formatted string. | [
"Format",
"resolution",
"to",
"string",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core-awt/src/main/java/com/b3dgs/lionengine/awt/graphic/ScreenFullAwt.java#L54-L66 |
selenide/selenide | src/main/java/com/codeborne/selenide/Condition.java | Condition.textCaseSensitive | public static Condition textCaseSensitive(final String text) {
"""
<p>Sample: <code>$("h1").shouldHave(textCaseSensitive("Hello\s*John"))</code></p>
<p>NB! Ignores multiple whitespaces between words</p>
@param text expected text of HTML element
"""
return new Condition("textCaseSensitive") {
@Override
public boolean apply(Driver driver, WebElement element) {
return Html.text.containsCaseSensitive(element.getText(), text);
}
@Override
public String toString() {
return name + " '" + text + '\'';
}
};
} | java | public static Condition textCaseSensitive(final String text) {
return new Condition("textCaseSensitive") {
@Override
public boolean apply(Driver driver, WebElement element) {
return Html.text.containsCaseSensitive(element.getText(), text);
}
@Override
public String toString() {
return name + " '" + text + '\'';
}
};
} | [
"public",
"static",
"Condition",
"textCaseSensitive",
"(",
"final",
"String",
"text",
")",
"{",
"return",
"new",
"Condition",
"(",
"\"textCaseSensitive\"",
")",
"{",
"@",
"Override",
"public",
"boolean",
"apply",
"(",
"Driver",
"driver",
",",
"WebElement",
"element",
")",
"{",
"return",
"Html",
".",
"text",
".",
"containsCaseSensitive",
"(",
"element",
".",
"getText",
"(",
")",
",",
"text",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"name",
"+",
"\" '\"",
"+",
"text",
"+",
"'",
"'",
";",
"}",
"}",
";",
"}"
] | <p>Sample: <code>$("h1").shouldHave(textCaseSensitive("Hello\s*John"))</code></p>
<p>NB! Ignores multiple whitespaces between words</p>
@param text expected text of HTML element | [
"<p",
">",
"Sample",
":",
"<code",
">",
"$",
"(",
"h1",
")",
".",
"shouldHave",
"(",
"textCaseSensitive",
"(",
"Hello",
"\\",
"s",
"*",
"John",
"))",
"<",
"/",
"code",
">",
"<",
"/",
"p",
">"
] | train | https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/Condition.java#L298-L310 |
Impetus/Kundera | src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/ThriftClient.java | ThriftClient.populateData | private List populateData(EntityMetadata m, List<KeySlice> keySlices, List<Object> entities, boolean isRelational,
List<String> relationNames) {
"""
Populate data.
@param m
the m
@param keySlices
the key slices
@param entities
the entities
@param isRelational
the is relational
@param relationNames
the relation names
@return the list
"""
try
{
if (m.getType().isSuperColumnFamilyMetadata())
{
List<Object> rowKeys = ThriftDataResultHelper.getRowKeys(keySlices, m);
Object[] rowIds = rowKeys.toArray();
entities.addAll(findAll(m.getEntityClazz(), null, rowIds));
}
else
{
for (KeySlice keySlice : keySlices)
{
byte[] key = keySlice.getKey();
List<ColumnOrSuperColumn> coscList = keySlice.getColumns();
List<Column> columns = ThriftDataResultHelper.transformThriftResult(coscList,
ColumnFamilyType.COLUMN, null);
Object e = null;
Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key);
e = dataHandler.populateEntity(new ThriftRow(id, m.getTableName(), columns,
new ArrayList<SuperColumn>(0), new ArrayList<CounterColumn>(0),
new ArrayList<CounterSuperColumn>(0)), m, KunderaCoreUtils.getEntity(e), relationNames,
isRelational);
entities.add(e);
}
}
}
catch (Exception e)
{
log.error("Error while populating data for relations of column family {}, Caused by: .", m.getTableName(),
e);
throw new KunderaException(e);
}
return entities;
} | java | private List populateData(EntityMetadata m, List<KeySlice> keySlices, List<Object> entities, boolean isRelational,
List<String> relationNames)
{
try
{
if (m.getType().isSuperColumnFamilyMetadata())
{
List<Object> rowKeys = ThriftDataResultHelper.getRowKeys(keySlices, m);
Object[] rowIds = rowKeys.toArray();
entities.addAll(findAll(m.getEntityClazz(), null, rowIds));
}
else
{
for (KeySlice keySlice : keySlices)
{
byte[] key = keySlice.getKey();
List<ColumnOrSuperColumn> coscList = keySlice.getColumns();
List<Column> columns = ThriftDataResultHelper.transformThriftResult(coscList,
ColumnFamilyType.COLUMN, null);
Object e = null;
Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key);
e = dataHandler.populateEntity(new ThriftRow(id, m.getTableName(), columns,
new ArrayList<SuperColumn>(0), new ArrayList<CounterColumn>(0),
new ArrayList<CounterSuperColumn>(0)), m, KunderaCoreUtils.getEntity(e), relationNames,
isRelational);
entities.add(e);
}
}
}
catch (Exception e)
{
log.error("Error while populating data for relations of column family {}, Caused by: .", m.getTableName(),
e);
throw new KunderaException(e);
}
return entities;
} | [
"private",
"List",
"populateData",
"(",
"EntityMetadata",
"m",
",",
"List",
"<",
"KeySlice",
">",
"keySlices",
",",
"List",
"<",
"Object",
">",
"entities",
",",
"boolean",
"isRelational",
",",
"List",
"<",
"String",
">",
"relationNames",
")",
"{",
"try",
"{",
"if",
"(",
"m",
".",
"getType",
"(",
")",
".",
"isSuperColumnFamilyMetadata",
"(",
")",
")",
"{",
"List",
"<",
"Object",
">",
"rowKeys",
"=",
"ThriftDataResultHelper",
".",
"getRowKeys",
"(",
"keySlices",
",",
"m",
")",
";",
"Object",
"[",
"]",
"rowIds",
"=",
"rowKeys",
".",
"toArray",
"(",
")",
";",
"entities",
".",
"addAll",
"(",
"findAll",
"(",
"m",
".",
"getEntityClazz",
"(",
")",
",",
"null",
",",
"rowIds",
")",
")",
";",
"}",
"else",
"{",
"for",
"(",
"KeySlice",
"keySlice",
":",
"keySlices",
")",
"{",
"byte",
"[",
"]",
"key",
"=",
"keySlice",
".",
"getKey",
"(",
")",
";",
"List",
"<",
"ColumnOrSuperColumn",
">",
"coscList",
"=",
"keySlice",
".",
"getColumns",
"(",
")",
";",
"List",
"<",
"Column",
">",
"columns",
"=",
"ThriftDataResultHelper",
".",
"transformThriftResult",
"(",
"coscList",
",",
"ColumnFamilyType",
".",
"COLUMN",
",",
"null",
")",
";",
"Object",
"e",
"=",
"null",
";",
"Object",
"id",
"=",
"PropertyAccessorHelper",
".",
"getObject",
"(",
"m",
".",
"getIdAttribute",
"(",
")",
".",
"getJavaType",
"(",
")",
",",
"key",
")",
";",
"e",
"=",
"dataHandler",
".",
"populateEntity",
"(",
"new",
"ThriftRow",
"(",
"id",
",",
"m",
".",
"getTableName",
"(",
")",
",",
"columns",
",",
"new",
"ArrayList",
"<",
"SuperColumn",
">",
"(",
"0",
")",
",",
"new",
"ArrayList",
"<",
"CounterColumn",
">",
"(",
"0",
")",
",",
"new",
"ArrayList",
"<",
"CounterSuperColumn",
">",
"(",
"0",
")",
")",
",",
"m",
",",
"KunderaCoreUtils",
".",
"getEntity",
"(",
"e",
")",
",",
"relationNames",
",",
"isRelational",
")",
";",
"entities",
".",
"add",
"(",
"e",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"Error while populating data for relations of column family {}, Caused by: .\"",
",",
"m",
".",
"getTableName",
"(",
")",
",",
"e",
")",
";",
"throw",
"new",
"KunderaException",
"(",
"e",
")",
";",
"}",
"return",
"entities",
";",
"}"
] | Populate data.
@param m
the m
@param keySlices
the key slices
@param entities
the entities
@param isRelational
the is relational
@param relationNames
the relation names
@return the list | [
"Populate",
"data",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/ThriftClient.java#L1000-L1039 |
spring-projects/spring-android | spring-android-rest-template/src/main/java/org/springframework/web/util/UriUtils.java | UriUtils.encodePathSegment | public static String encodePathSegment(String segment, String encoding) throws UnsupportedEncodingException {
"""
Encodes the given URI path segment with the given encoding.
@param segment the segment to be encoded
@param encoding the character encoding to encode to
@return the encoded segment
@throws UnsupportedEncodingException when the given encoding parameter is not supported
"""
return HierarchicalUriComponents.encodeUriComponent(segment, encoding, HierarchicalUriComponents.Type.PATH_SEGMENT);
} | java | public static String encodePathSegment(String segment, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(segment, encoding, HierarchicalUriComponents.Type.PATH_SEGMENT);
} | [
"public",
"static",
"String",
"encodePathSegment",
"(",
"String",
"segment",
",",
"String",
"encoding",
")",
"throws",
"UnsupportedEncodingException",
"{",
"return",
"HierarchicalUriComponents",
".",
"encodeUriComponent",
"(",
"segment",
",",
"encoding",
",",
"HierarchicalUriComponents",
".",
"Type",
".",
"PATH_SEGMENT",
")",
";",
"}"
] | Encodes the given URI path segment with the given encoding.
@param segment the segment to be encoded
@param encoding the character encoding to encode to
@return the encoded segment
@throws UnsupportedEncodingException when the given encoding parameter is not supported | [
"Encodes",
"the",
"given",
"URI",
"path",
"segment",
"with",
"the",
"given",
"encoding",
"."
] | train | https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-rest-template/src/main/java/org/springframework/web/util/UriUtils.java#L285-L287 |
sebastiangraf/treetank | interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/PipelineBuilder.java | PipelineBuilder.addIfExpression | public void addIfExpression(final INodeReadTrx mTransaction) {
"""
Adds a if expression to the pipeline.
@param mTransaction
Transaction to operate with.
"""
assert getPipeStack().size() >= 3;
final INodeReadTrx rtx = mTransaction;
final AbsAxis elseExpr = getPipeStack().pop().getExpr();
final AbsAxis thenExpr = getPipeStack().pop().getExpr();
final AbsAxis ifExpr = getPipeStack().pop().getExpr();
if (getPipeStack().empty() || getExpression().getSize() != 0) {
addExpressionSingle();
}
getExpression().add(new IfAxis(rtx, ifExpr, thenExpr, elseExpr));
} | java | public void addIfExpression(final INodeReadTrx mTransaction) {
assert getPipeStack().size() >= 3;
final INodeReadTrx rtx = mTransaction;
final AbsAxis elseExpr = getPipeStack().pop().getExpr();
final AbsAxis thenExpr = getPipeStack().pop().getExpr();
final AbsAxis ifExpr = getPipeStack().pop().getExpr();
if (getPipeStack().empty() || getExpression().getSize() != 0) {
addExpressionSingle();
}
getExpression().add(new IfAxis(rtx, ifExpr, thenExpr, elseExpr));
} | [
"public",
"void",
"addIfExpression",
"(",
"final",
"INodeReadTrx",
"mTransaction",
")",
"{",
"assert",
"getPipeStack",
"(",
")",
".",
"size",
"(",
")",
">=",
"3",
";",
"final",
"INodeReadTrx",
"rtx",
"=",
"mTransaction",
";",
"final",
"AbsAxis",
"elseExpr",
"=",
"getPipeStack",
"(",
")",
".",
"pop",
"(",
")",
".",
"getExpr",
"(",
")",
";",
"final",
"AbsAxis",
"thenExpr",
"=",
"getPipeStack",
"(",
")",
".",
"pop",
"(",
")",
".",
"getExpr",
"(",
")",
";",
"final",
"AbsAxis",
"ifExpr",
"=",
"getPipeStack",
"(",
")",
".",
"pop",
"(",
")",
".",
"getExpr",
"(",
")",
";",
"if",
"(",
"getPipeStack",
"(",
")",
".",
"empty",
"(",
")",
"||",
"getExpression",
"(",
")",
".",
"getSize",
"(",
")",
"!=",
"0",
")",
"{",
"addExpressionSingle",
"(",
")",
";",
"}",
"getExpression",
"(",
")",
".",
"add",
"(",
"new",
"IfAxis",
"(",
"rtx",
",",
"ifExpr",
",",
"thenExpr",
",",
"elseExpr",
")",
")",
";",
"}"
] | Adds a if expression to the pipeline.
@param mTransaction
Transaction to operate with. | [
"Adds",
"a",
"if",
"expression",
"to",
"the",
"pipeline",
"."
] | train | https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/PipelineBuilder.java#L250-L265 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringParser.java | StringParser.parseBigInteger | @Nullable
public static BigInteger parseBigInteger (@Nullable final String sStr,
@Nonnegative final int nRadix,
@Nullable final BigInteger aDefault) {
"""
Parse the given {@link String} as {@link BigInteger} with the specified
radix.
@param sStr
The String to parse. May be <code>null</code>.
@param nRadix
The radix to use. Must be ≥ {@link Character#MIN_RADIX} and ≤
{@link Character#MAX_RADIX}.
@param aDefault
The default value to be returned if the passed string could not be
converted to a valid value. May be <code>null</code>.
@return <code>aDefault</code> if the string does not represent a valid
value.
"""
if (sStr != null && sStr.length () > 0)
try
{
return new BigInteger (sStr, nRadix);
}
catch (final NumberFormatException ex)
{
// Fall through
}
return aDefault;
} | java | @Nullable
public static BigInteger parseBigInteger (@Nullable final String sStr,
@Nonnegative final int nRadix,
@Nullable final BigInteger aDefault)
{
if (sStr != null && sStr.length () > 0)
try
{
return new BigInteger (sStr, nRadix);
}
catch (final NumberFormatException ex)
{
// Fall through
}
return aDefault;
} | [
"@",
"Nullable",
"public",
"static",
"BigInteger",
"parseBigInteger",
"(",
"@",
"Nullable",
"final",
"String",
"sStr",
",",
"@",
"Nonnegative",
"final",
"int",
"nRadix",
",",
"@",
"Nullable",
"final",
"BigInteger",
"aDefault",
")",
"{",
"if",
"(",
"sStr",
"!=",
"null",
"&&",
"sStr",
".",
"length",
"(",
")",
">",
"0",
")",
"try",
"{",
"return",
"new",
"BigInteger",
"(",
"sStr",
",",
"nRadix",
")",
";",
"}",
"catch",
"(",
"final",
"NumberFormatException",
"ex",
")",
"{",
"// Fall through",
"}",
"return",
"aDefault",
";",
"}"
] | Parse the given {@link String} as {@link BigInteger} with the specified
radix.
@param sStr
The String to parse. May be <code>null</code>.
@param nRadix
The radix to use. Must be ≥ {@link Character#MIN_RADIX} and ≤
{@link Character#MAX_RADIX}.
@param aDefault
The default value to be returned if the passed string could not be
converted to a valid value. May be <code>null</code>.
@return <code>aDefault</code> if the string does not represent a valid
value. | [
"Parse",
"the",
"given",
"{",
"@link",
"String",
"}",
"as",
"{",
"@link",
"BigInteger",
"}",
"with",
"the",
"specified",
"radix",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L1438-L1453 |
libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/btree/utils/BehaviorTreeLibrary.java | BehaviorTreeLibrary.disposeBehaviorTree | public void disposeBehaviorTree(String treeReference, BehaviorTree<?> behaviorTree) {
"""
Dispose behavior tree obtain by this library.
@param treeReference the tree identifier.
@param behaviorTree the tree to dispose.
"""
if(Task.TASK_CLONER != null){
Task.TASK_CLONER.freeTask(behaviorTree);
}
} | java | public void disposeBehaviorTree(String treeReference, BehaviorTree<?> behaviorTree){
if(Task.TASK_CLONER != null){
Task.TASK_CLONER.freeTask(behaviorTree);
}
} | [
"public",
"void",
"disposeBehaviorTree",
"(",
"String",
"treeReference",
",",
"BehaviorTree",
"<",
"?",
">",
"behaviorTree",
")",
"{",
"if",
"(",
"Task",
".",
"TASK_CLONER",
"!=",
"null",
")",
"{",
"Task",
".",
"TASK_CLONER",
".",
"freeTask",
"(",
"behaviorTree",
")",
";",
"}",
"}"
] | Dispose behavior tree obtain by this library.
@param treeReference the tree identifier.
@param behaviorTree the tree to dispose. | [
"Dispose",
"behavior",
"tree",
"obtain",
"by",
"this",
"library",
"."
] | train | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/utils/BehaviorTreeLibrary.java#L160-L164 |
ReactiveX/RxJavaString | src/main/java/rx/observables/StringObservable.java | StringObservable.stringConcat | public static Observable<String> stringConcat(Observable<String> src) {
"""
Gather up all of the strings in to one string to be able to use it as one message. Don't use
this on infinite streams.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.stringConcat.png" alt="">
@param src
@return the Observable returing all strings concatenated as a single string
"""
return toString(src.reduce(new StringBuilder(), new Func2<StringBuilder, String, StringBuilder>() {
@Override
public StringBuilder call(StringBuilder a, String b) {
return a.append(b);
}
}));
} | java | public static Observable<String> stringConcat(Observable<String> src) {
return toString(src.reduce(new StringBuilder(), new Func2<StringBuilder, String, StringBuilder>() {
@Override
public StringBuilder call(StringBuilder a, String b) {
return a.append(b);
}
}));
} | [
"public",
"static",
"Observable",
"<",
"String",
">",
"stringConcat",
"(",
"Observable",
"<",
"String",
">",
"src",
")",
"{",
"return",
"toString",
"(",
"src",
".",
"reduce",
"(",
"new",
"StringBuilder",
"(",
")",
",",
"new",
"Func2",
"<",
"StringBuilder",
",",
"String",
",",
"StringBuilder",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"StringBuilder",
"call",
"(",
"StringBuilder",
"a",
",",
"String",
"b",
")",
"{",
"return",
"a",
".",
"append",
"(",
"b",
")",
";",
"}",
"}",
")",
")",
";",
"}"
] | Gather up all of the strings in to one string to be able to use it as one message. Don't use
this on infinite streams.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.stringConcat.png" alt="">
@param src
@return the Observable returing all strings concatenated as a single string | [
"Gather",
"up",
"all",
"of",
"the",
"strings",
"in",
"to",
"one",
"string",
"to",
"be",
"able",
"to",
"use",
"it",
"as",
"one",
"message",
".",
"Don",
"t",
"use",
"this",
"on",
"infinite",
"streams",
".",
"<p",
">",
"<img",
"width",
"=",
"640",
"src",
"=",
"https",
":",
"//",
"raw",
".",
"github",
".",
"com",
"/",
"wiki",
"/",
"ReactiveX",
"/",
"RxJava",
"/",
"images",
"/",
"rx",
"-",
"operators",
"/",
"St",
".",
"stringConcat",
".",
"png",
"alt",
"=",
">"
] | train | https://github.com/ReactiveX/RxJavaString/blob/3e73b759ff7bffd5d2e1c753630c5408cb5f9e5e/src/main/java/rx/observables/StringObservable.java#L321-L328 |
vdmeer/asciitable | src/main/java/de/vandermeer/asciitable/AT_Row.java | AT_Row.setPaddingTopBottom | public AT_Row setPaddingTopBottom(int paddingTop, int paddingBottom) {
"""
Sets top and bottom padding for all cells in the row (only if both values are not smaller than 0).
@param paddingTop new top padding, ignored if smaller than 0
@param paddingBottom new bottom padding, ignored if smaller than 0
@return this to allow chaining
"""
if(this.hasCells()){
for(AT_Cell cell : this.getCells()){
cell.getContext().setPaddingTopBottom(paddingTop, paddingBottom);
}
}
return this;
} | java | public AT_Row setPaddingTopBottom(int paddingTop, int paddingBottom){
if(this.hasCells()){
for(AT_Cell cell : this.getCells()){
cell.getContext().setPaddingTopBottom(paddingTop, paddingBottom);
}
}
return this;
} | [
"public",
"AT_Row",
"setPaddingTopBottom",
"(",
"int",
"paddingTop",
",",
"int",
"paddingBottom",
")",
"{",
"if",
"(",
"this",
".",
"hasCells",
"(",
")",
")",
"{",
"for",
"(",
"AT_Cell",
"cell",
":",
"this",
".",
"getCells",
"(",
")",
")",
"{",
"cell",
".",
"getContext",
"(",
")",
".",
"setPaddingTopBottom",
"(",
"paddingTop",
",",
"paddingBottom",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
] | Sets top and bottom padding for all cells in the row (only if both values are not smaller than 0).
@param paddingTop new top padding, ignored if smaller than 0
@param paddingBottom new bottom padding, ignored if smaller than 0
@return this to allow chaining | [
"Sets",
"top",
"and",
"bottom",
"padding",
"for",
"all",
"cells",
"in",
"the",
"row",
"(",
"only",
"if",
"both",
"values",
"are",
"not",
"smaller",
"than",
"0",
")",
"."
] | train | https://github.com/vdmeer/asciitable/blob/b6a73710271c89f9c749603be856ba84a969ed5f/src/main/java/de/vandermeer/asciitable/AT_Row.java#L285-L292 |
Erudika/para | para-server/src/main/java/com/erudika/para/rest/RestUtils.java | RestUtils.createLinksHandler | public static Response createLinksHandler(ParaObject pobj, String id2) {
"""
Handles requests to link an object to other objects.
@param pobj the object to operate on
@param id2 the id of the second object (optional)
@return a Response
"""
try (final Metrics.Context context = Metrics.time(null, RestUtils.class, "links", "create")) {
if (id2 != null && pobj != null) {
String linkid = pobj.link(id2);
if (linkid == null) {
return getStatusResponse(Response.Status.BAD_REQUEST, "Failed to create link.");
} else {
return Response.ok(linkid, MediaType.TEXT_PLAIN_TYPE).build();
}
} else {
return getStatusResponse(Response.Status.BAD_REQUEST, "Parameters 'type' and 'id' are missing.");
}
}
} | java | public static Response createLinksHandler(ParaObject pobj, String id2) {
try (final Metrics.Context context = Metrics.time(null, RestUtils.class, "links", "create")) {
if (id2 != null && pobj != null) {
String linkid = pobj.link(id2);
if (linkid == null) {
return getStatusResponse(Response.Status.BAD_REQUEST, "Failed to create link.");
} else {
return Response.ok(linkid, MediaType.TEXT_PLAIN_TYPE).build();
}
} else {
return getStatusResponse(Response.Status.BAD_REQUEST, "Parameters 'type' and 'id' are missing.");
}
}
} | [
"public",
"static",
"Response",
"createLinksHandler",
"(",
"ParaObject",
"pobj",
",",
"String",
"id2",
")",
"{",
"try",
"(",
"final",
"Metrics",
".",
"Context",
"context",
"=",
"Metrics",
".",
"time",
"(",
"null",
",",
"RestUtils",
".",
"class",
",",
"\"links\"",
",",
"\"create\"",
")",
")",
"{",
"if",
"(",
"id2",
"!=",
"null",
"&&",
"pobj",
"!=",
"null",
")",
"{",
"String",
"linkid",
"=",
"pobj",
".",
"link",
"(",
"id2",
")",
";",
"if",
"(",
"linkid",
"==",
"null",
")",
"{",
"return",
"getStatusResponse",
"(",
"Response",
".",
"Status",
".",
"BAD_REQUEST",
",",
"\"Failed to create link.\"",
")",
";",
"}",
"else",
"{",
"return",
"Response",
".",
"ok",
"(",
"linkid",
",",
"MediaType",
".",
"TEXT_PLAIN_TYPE",
")",
".",
"build",
"(",
")",
";",
"}",
"}",
"else",
"{",
"return",
"getStatusResponse",
"(",
"Response",
".",
"Status",
".",
"BAD_REQUEST",
",",
"\"Parameters 'type' and 'id' are missing.\"",
")",
";",
"}",
"}",
"}"
] | Handles requests to link an object to other objects.
@param pobj the object to operate on
@param id2 the id of the second object (optional)
@return a Response | [
"Handles",
"requests",
"to",
"link",
"an",
"object",
"to",
"other",
"objects",
"."
] | train | https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/rest/RestUtils.java#L702-L715 |
baratine/baratine | web/src/main/java/com/caucho/v5/health/warning/WarningSystem.java | WarningSystem.sendWarning | public void sendWarning(Object source, String msg) {
"""
Send a warning message to any registered handlers. A high priority warning
only goes to all handlers, high priority first. High priority handlers do
not receive non-high priority warnings.
@param source source of the message, usually you
@param msg test to print or send as an alert
@param isHighPriority set true to send to high priority warning handlers
"""
try {
String s = getClass().getSimpleName() + ": " + msg;
// if warning is high-priority then send to high priority handlers first
System.err.println(s);
for (WarningHandler handler : _priorityHandlers) {
handler.warning(source, msg);
}
// now send to the all handlers regardless of if its high priority
for (WarningHandler handler : _handlers) {
handler.warning(source, msg);
}
log.warning(msg);
} catch (Throwable e) {
// WarningService must not throw exception
log.log(Level.WARNING, e.toString(), e);
}
} | java | public void sendWarning(Object source, String msg)
{
try {
String s = getClass().getSimpleName() + ": " + msg;
// if warning is high-priority then send to high priority handlers first
System.err.println(s);
for (WarningHandler handler : _priorityHandlers) {
handler.warning(source, msg);
}
// now send to the all handlers regardless of if its high priority
for (WarningHandler handler : _handlers) {
handler.warning(source, msg);
}
log.warning(msg);
} catch (Throwable e) {
// WarningService must not throw exception
log.log(Level.WARNING, e.toString(), e);
}
} | [
"public",
"void",
"sendWarning",
"(",
"Object",
"source",
",",
"String",
"msg",
")",
"{",
"try",
"{",
"String",
"s",
"=",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
"+",
"\": \"",
"+",
"msg",
";",
"// if warning is high-priority then send to high priority handlers first",
"System",
".",
"err",
".",
"println",
"(",
"s",
")",
";",
"for",
"(",
"WarningHandler",
"handler",
":",
"_priorityHandlers",
")",
"{",
"handler",
".",
"warning",
"(",
"source",
",",
"msg",
")",
";",
"}",
"// now send to the all handlers regardless of if its high priority",
"for",
"(",
"WarningHandler",
"handler",
":",
"_handlers",
")",
"{",
"handler",
".",
"warning",
"(",
"source",
",",
"msg",
")",
";",
"}",
"log",
".",
"warning",
"(",
"msg",
")",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"// WarningService must not throw exception",
"log",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"e",
".",
"toString",
"(",
")",
",",
"e",
")",
";",
"}",
"}"
] | Send a warning message to any registered handlers. A high priority warning
only goes to all handlers, high priority first. High priority handlers do
not receive non-high priority warnings.
@param source source of the message, usually you
@param msg test to print or send as an alert
@param isHighPriority set true to send to high priority warning handlers | [
"Send",
"a",
"warning",
"message",
"to",
"any",
"registered",
"handlers",
".",
"A",
"high",
"priority",
"warning",
"only",
"goes",
"to",
"all",
"handlers",
"high",
"priority",
"first",
".",
"High",
"priority",
"handlers",
"do",
"not",
"receive",
"non",
"-",
"high",
"priority",
"warnings",
"."
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/web/src/main/java/com/caucho/v5/health/warning/WarningSystem.java#L84-L106 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UnicodeRegex.java | UnicodeRegex.appendLines | public static List<String> appendLines(List<String> result, InputStream inputStream, String encoding)
throws UnsupportedEncodingException, IOException {
"""
Utility for loading lines from a UTF8 file.
@param result The result of the appended lines.
@param inputStream The input stream.
@param encoding if null, then UTF-8
@return filled list
@throws IOException If there were problems opening the input stream for reading.
"""
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, encoding == null ? "UTF-8" : encoding));
while (true) {
String line = in.readLine();
if (line == null) break;
result.add(line);
}
return result;
} | java | public static List<String> appendLines(List<String> result, InputStream inputStream, String encoding)
throws UnsupportedEncodingException, IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, encoding == null ? "UTF-8" : encoding));
while (true) {
String line = in.readLine();
if (line == null) break;
result.add(line);
}
return result;
} | [
"public",
"static",
"List",
"<",
"String",
">",
"appendLines",
"(",
"List",
"<",
"String",
">",
"result",
",",
"InputStream",
"inputStream",
",",
"String",
"encoding",
")",
"throws",
"UnsupportedEncodingException",
",",
"IOException",
"{",
"BufferedReader",
"in",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"inputStream",
",",
"encoding",
"==",
"null",
"?",
"\"UTF-8\"",
":",
"encoding",
")",
")",
";",
"while",
"(",
"true",
")",
"{",
"String",
"line",
"=",
"in",
".",
"readLine",
"(",
")",
";",
"if",
"(",
"line",
"==",
"null",
")",
"break",
";",
"result",
".",
"add",
"(",
"line",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Utility for loading lines from a UTF8 file.
@param result The result of the appended lines.
@param inputStream The input stream.
@param encoding if null, then UTF-8
@return filled list
@throws IOException If there were problems opening the input stream for reading. | [
"Utility",
"for",
"loading",
"lines",
"from",
"a",
"UTF8",
"file",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UnicodeRegex.java#L296-L305 |
alkacon/opencms-core | src-gwt/org/opencms/ugc/client/export/CmsClientUgcSession.java | CmsClientUgcSession.initFormElement | @NoExport
public void initFormElement(Element formElement) {
"""
Initializes the form belonging to this session.<p>
@param formElement the form element
"""
m_formWrapper = new CmsUgcWrapper(formElement, getSessionId());
m_formWrapper.setFormSession(this);
} | java | @NoExport
public void initFormElement(Element formElement) {
m_formWrapper = new CmsUgcWrapper(formElement, getSessionId());
m_formWrapper.setFormSession(this);
} | [
"@",
"NoExport",
"public",
"void",
"initFormElement",
"(",
"Element",
"formElement",
")",
"{",
"m_formWrapper",
"=",
"new",
"CmsUgcWrapper",
"(",
"formElement",
",",
"getSessionId",
"(",
")",
")",
";",
"m_formWrapper",
".",
"setFormSession",
"(",
"this",
")",
";",
"}"
] | Initializes the form belonging to this session.<p>
@param formElement the form element | [
"Initializes",
"the",
"form",
"belonging",
"to",
"this",
"session",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ugc/client/export/CmsClientUgcSession.java#L173-L178 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/subdoc/SubdocHelper.java | SubdocHelper.commonSubdocErrors | public static CouchbaseException commonSubdocErrors(ResponseStatus status, String id, String path) {
"""
Convert status that can happen in a subdocument context to corresponding exceptions.
Other status just become a {@link CouchbaseException}.
"""
switch (status) {
case COMMAND_UNAVAILABLE:
case ACCESS_ERROR:
return new CouchbaseException("Access error for subdocument operations (This can also happen "+
"if the server version doesn't support it. Couchbase server 4.5 or later is required for Subdocument operations " +
"and Couchbase Server 5.0 or later is required for extended attributes access)");
case NOT_EXISTS:
return new DocumentDoesNotExistException("Document not found for subdoc API: " + id);
case TEMPORARY_FAILURE:
case SERVER_BUSY:
case LOCKED:
return new TemporaryFailureException();
case OUT_OF_MEMORY:
return new CouchbaseOutOfMemoryException();
//a bit specific for subdoc mutations
case EXISTS:
return new CASMismatchException("CAS provided in subdoc mutation didn't match the CAS of stored document " + id);
case TOO_BIG:
return new RequestTooBigException();
//subdoc errors
case SUBDOC_PATH_NOT_FOUND:
return new PathNotFoundException(id, path);
case SUBDOC_PATH_EXISTS:
return new PathExistsException(id, path);
case SUBDOC_DOC_NOT_JSON:
return new DocumentNotJsonException(id);
case SUBDOC_DOC_TOO_DEEP:
return new DocumentTooDeepException(id);
case SUBDOC_DELTA_RANGE:
return new BadDeltaException();
case SUBDOC_NUM_RANGE:
return new NumberTooBigException();
case SUBDOC_VALUE_TOO_DEEP:
return new ValueTooDeepException(id, path);
case SUBDOC_PATH_TOO_BIG:
return new PathTooDeepException(path);
//these two are a bit generic and should usually be handled upstream with a more meaningful message
case SUBDOC_PATH_INVALID:
return new PathInvalidException(id, path);
case SUBDOC_PATH_MISMATCH:
return new PathMismatchException(id, path);
case SUBDOC_VALUE_CANTINSERT: //this shouldn't happen outside of add-unique, since we use JSON serializer
return new CannotInsertValueException("Provided subdocument fragment is not valid JSON");
default:
return new CouchbaseException(status.toString());
}
} | java | public static CouchbaseException commonSubdocErrors(ResponseStatus status, String id, String path) {
switch (status) {
case COMMAND_UNAVAILABLE:
case ACCESS_ERROR:
return new CouchbaseException("Access error for subdocument operations (This can also happen "+
"if the server version doesn't support it. Couchbase server 4.5 or later is required for Subdocument operations " +
"and Couchbase Server 5.0 or later is required for extended attributes access)");
case NOT_EXISTS:
return new DocumentDoesNotExistException("Document not found for subdoc API: " + id);
case TEMPORARY_FAILURE:
case SERVER_BUSY:
case LOCKED:
return new TemporaryFailureException();
case OUT_OF_MEMORY:
return new CouchbaseOutOfMemoryException();
//a bit specific for subdoc mutations
case EXISTS:
return new CASMismatchException("CAS provided in subdoc mutation didn't match the CAS of stored document " + id);
case TOO_BIG:
return new RequestTooBigException();
//subdoc errors
case SUBDOC_PATH_NOT_FOUND:
return new PathNotFoundException(id, path);
case SUBDOC_PATH_EXISTS:
return new PathExistsException(id, path);
case SUBDOC_DOC_NOT_JSON:
return new DocumentNotJsonException(id);
case SUBDOC_DOC_TOO_DEEP:
return new DocumentTooDeepException(id);
case SUBDOC_DELTA_RANGE:
return new BadDeltaException();
case SUBDOC_NUM_RANGE:
return new NumberTooBigException();
case SUBDOC_VALUE_TOO_DEEP:
return new ValueTooDeepException(id, path);
case SUBDOC_PATH_TOO_BIG:
return new PathTooDeepException(path);
//these two are a bit generic and should usually be handled upstream with a more meaningful message
case SUBDOC_PATH_INVALID:
return new PathInvalidException(id, path);
case SUBDOC_PATH_MISMATCH:
return new PathMismatchException(id, path);
case SUBDOC_VALUE_CANTINSERT: //this shouldn't happen outside of add-unique, since we use JSON serializer
return new CannotInsertValueException("Provided subdocument fragment is not valid JSON");
default:
return new CouchbaseException(status.toString());
}
} | [
"public",
"static",
"CouchbaseException",
"commonSubdocErrors",
"(",
"ResponseStatus",
"status",
",",
"String",
"id",
",",
"String",
"path",
")",
"{",
"switch",
"(",
"status",
")",
"{",
"case",
"COMMAND_UNAVAILABLE",
":",
"case",
"ACCESS_ERROR",
":",
"return",
"new",
"CouchbaseException",
"(",
"\"Access error for subdocument operations (This can also happen \"",
"+",
"\"if the server version doesn't support it. Couchbase server 4.5 or later is required for Subdocument operations \"",
"+",
"\"and Couchbase Server 5.0 or later is required for extended attributes access)\"",
")",
";",
"case",
"NOT_EXISTS",
":",
"return",
"new",
"DocumentDoesNotExistException",
"(",
"\"Document not found for subdoc API: \"",
"+",
"id",
")",
";",
"case",
"TEMPORARY_FAILURE",
":",
"case",
"SERVER_BUSY",
":",
"case",
"LOCKED",
":",
"return",
"new",
"TemporaryFailureException",
"(",
")",
";",
"case",
"OUT_OF_MEMORY",
":",
"return",
"new",
"CouchbaseOutOfMemoryException",
"(",
")",
";",
"//a bit specific for subdoc mutations",
"case",
"EXISTS",
":",
"return",
"new",
"CASMismatchException",
"(",
"\"CAS provided in subdoc mutation didn't match the CAS of stored document \"",
"+",
"id",
")",
";",
"case",
"TOO_BIG",
":",
"return",
"new",
"RequestTooBigException",
"(",
")",
";",
"//subdoc errors",
"case",
"SUBDOC_PATH_NOT_FOUND",
":",
"return",
"new",
"PathNotFoundException",
"(",
"id",
",",
"path",
")",
";",
"case",
"SUBDOC_PATH_EXISTS",
":",
"return",
"new",
"PathExistsException",
"(",
"id",
",",
"path",
")",
";",
"case",
"SUBDOC_DOC_NOT_JSON",
":",
"return",
"new",
"DocumentNotJsonException",
"(",
"id",
")",
";",
"case",
"SUBDOC_DOC_TOO_DEEP",
":",
"return",
"new",
"DocumentTooDeepException",
"(",
"id",
")",
";",
"case",
"SUBDOC_DELTA_RANGE",
":",
"return",
"new",
"BadDeltaException",
"(",
")",
";",
"case",
"SUBDOC_NUM_RANGE",
":",
"return",
"new",
"NumberTooBigException",
"(",
")",
";",
"case",
"SUBDOC_VALUE_TOO_DEEP",
":",
"return",
"new",
"ValueTooDeepException",
"(",
"id",
",",
"path",
")",
";",
"case",
"SUBDOC_PATH_TOO_BIG",
":",
"return",
"new",
"PathTooDeepException",
"(",
"path",
")",
";",
"//these two are a bit generic and should usually be handled upstream with a more meaningful message",
"case",
"SUBDOC_PATH_INVALID",
":",
"return",
"new",
"PathInvalidException",
"(",
"id",
",",
"path",
")",
";",
"case",
"SUBDOC_PATH_MISMATCH",
":",
"return",
"new",
"PathMismatchException",
"(",
"id",
",",
"path",
")",
";",
"case",
"SUBDOC_VALUE_CANTINSERT",
":",
"//this shouldn't happen outside of add-unique, since we use JSON serializer",
"return",
"new",
"CannotInsertValueException",
"(",
"\"Provided subdocument fragment is not valid JSON\"",
")",
";",
"default",
":",
"return",
"new",
"CouchbaseException",
"(",
"status",
".",
"toString",
"(",
")",
")",
";",
"}",
"}"
] | Convert status that can happen in a subdocument context to corresponding exceptions.
Other status just become a {@link CouchbaseException}. | [
"Convert",
"status",
"that",
"can",
"happen",
"in",
"a",
"subdocument",
"context",
"to",
"corresponding",
"exceptions",
".",
"Other",
"status",
"just",
"become",
"a",
"{"
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/subdoc/SubdocHelper.java#L56-L103 |
Omertron/api-tvrage | src/main/java/com/omertron/tvrageapi/tools/DOMHelper.java | DOMHelper.requestWebContent | private static byte[] requestWebContent(String url) throws TVRageException {
"""
Get content from URL in byte array
@param url
@return
@throws TVRageException
"""
try {
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("accept", "application/xml");
final DigestedResponse response = DigestedResponseReader.requestContent(httpClient, httpGet, CHARSET);
if (response.getStatusCode() >= 500) {
throw new TVRageException(ApiExceptionType.HTTP_503_ERROR, url);
} else if (response.getStatusCode() >= 300) {
throw new TVRageException(ApiExceptionType.HTTP_404_ERROR, url);
}
return response.getContent().getBytes(DEFAULT_CHARSET);
} catch (IOException ex) {
throw new TVRageException(ApiExceptionType.MAPPING_FAILED, UNABLE_TO_PARSE, url, ex);
}
} | java | private static byte[] requestWebContent(String url) throws TVRageException {
try {
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("accept", "application/xml");
final DigestedResponse response = DigestedResponseReader.requestContent(httpClient, httpGet, CHARSET);
if (response.getStatusCode() >= 500) {
throw new TVRageException(ApiExceptionType.HTTP_503_ERROR, url);
} else if (response.getStatusCode() >= 300) {
throw new TVRageException(ApiExceptionType.HTTP_404_ERROR, url);
}
return response.getContent().getBytes(DEFAULT_CHARSET);
} catch (IOException ex) {
throw new TVRageException(ApiExceptionType.MAPPING_FAILED, UNABLE_TO_PARSE, url, ex);
}
} | [
"private",
"static",
"byte",
"[",
"]",
"requestWebContent",
"(",
"String",
"url",
")",
"throws",
"TVRageException",
"{",
"try",
"{",
"HttpGet",
"httpGet",
"=",
"new",
"HttpGet",
"(",
"url",
")",
";",
"httpGet",
".",
"addHeader",
"(",
"\"accept\"",
",",
"\"application/xml\"",
")",
";",
"final",
"DigestedResponse",
"response",
"=",
"DigestedResponseReader",
".",
"requestContent",
"(",
"httpClient",
",",
"httpGet",
",",
"CHARSET",
")",
";",
"if",
"(",
"response",
".",
"getStatusCode",
"(",
")",
">=",
"500",
")",
"{",
"throw",
"new",
"TVRageException",
"(",
"ApiExceptionType",
".",
"HTTP_503_ERROR",
",",
"url",
")",
";",
"}",
"else",
"if",
"(",
"response",
".",
"getStatusCode",
"(",
")",
">=",
"300",
")",
"{",
"throw",
"new",
"TVRageException",
"(",
"ApiExceptionType",
".",
"HTTP_404_ERROR",
",",
"url",
")",
";",
"}",
"return",
"response",
".",
"getContent",
"(",
")",
".",
"getBytes",
"(",
"DEFAULT_CHARSET",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"TVRageException",
"(",
"ApiExceptionType",
".",
"MAPPING_FAILED",
",",
"UNABLE_TO_PARSE",
",",
"url",
",",
"ex",
")",
";",
"}",
"}"
] | Get content from URL in byte array
@param url
@return
@throws TVRageException | [
"Get",
"content",
"from",
"URL",
"in",
"byte",
"array"
] | train | https://github.com/Omertron/api-tvrage/blob/4e805a99de812fabea69d97098f2376be14d51bc/src/main/java/com/omertron/tvrageapi/tools/DOMHelper.java#L132-L148 |
apache/groovy | src/main/java/org/codehaus/groovy/ast/ClassHelper.java | ClassHelper.makeWithoutCaching | public static ClassNode makeWithoutCaching(String name) {
"""
Creates a ClassNode using a given class.
Unlike make(String) this method will not use the cache
to create the ClassNode. This means the ClassNode created
from this method using the same name will have a different
reference
@param name of the class the ClassNode is representing
@see #make(String)
"""
ClassNode cn = new ClassNode(name, Opcodes.ACC_PUBLIC, OBJECT_TYPE);
cn.isPrimaryNode = false;
return cn;
} | java | public static ClassNode makeWithoutCaching(String name) {
ClassNode cn = new ClassNode(name, Opcodes.ACC_PUBLIC, OBJECT_TYPE);
cn.isPrimaryNode = false;
return cn;
} | [
"public",
"static",
"ClassNode",
"makeWithoutCaching",
"(",
"String",
"name",
")",
"{",
"ClassNode",
"cn",
"=",
"new",
"ClassNode",
"(",
"name",
",",
"Opcodes",
".",
"ACC_PUBLIC",
",",
"OBJECT_TYPE",
")",
";",
"cn",
".",
"isPrimaryNode",
"=",
"false",
";",
"return",
"cn",
";",
"}"
] | Creates a ClassNode using a given class.
Unlike make(String) this method will not use the cache
to create the ClassNode. This means the ClassNode created
from this method using the same name will have a different
reference
@param name of the class the ClassNode is representing
@see #make(String) | [
"Creates",
"a",
"ClassNode",
"using",
"a",
"given",
"class",
".",
"Unlike",
"make",
"(",
"String",
")",
"this",
"method",
"will",
"not",
"use",
"the",
"cache",
"to",
"create",
"the",
"ClassNode",
".",
"This",
"means",
"the",
"ClassNode",
"created",
"from",
"this",
"method",
"using",
"the",
"same",
"name",
"will",
"have",
"a",
"different",
"reference"
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/ast/ClassHelper.java#L249-L253 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java | ComputeNodeOperations.getComputeNode | public ComputeNode getComputeNode(String poolId, String nodeId) throws BatchErrorException, IOException {
"""
Gets the specified compute node.
@param poolId The ID of the pool.
@param nodeId the ID of the compute node to get from the pool.
@return A {@link ComputeNode} containing information about the specified compute node.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
"""
return getComputeNode(poolId, nodeId, null, null);
} | java | public ComputeNode getComputeNode(String poolId, String nodeId) throws BatchErrorException, IOException {
return getComputeNode(poolId, nodeId, null, null);
} | [
"public",
"ComputeNode",
"getComputeNode",
"(",
"String",
"poolId",
",",
"String",
"nodeId",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"return",
"getComputeNode",
"(",
"poolId",
",",
"nodeId",
",",
"null",
",",
"null",
")",
";",
"}"
] | Gets the specified compute node.
@param poolId The ID of the pool.
@param nodeId the ID of the compute node to get from the pool.
@return A {@link ComputeNode} containing information about the specified compute node.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. | [
"Gets",
"the",
"specified",
"compute",
"node",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java#L230-L232 |
mapsforge/mapsforge | sqlite-android/src/main/java/org/sqlite/database/DatabaseUtils.java | DatabaseUtils.cursorIntToContentValues | public static void cursorIntToContentValues(Cursor cursor, String field, ContentValues values) {
"""
Reads an Integer out of a field in a Cursor and writes it to a Map.
@param cursor The cursor to read from
@param field The INTEGER field to read
@param values The {@link ContentValues} to put the value into, with the field as the key
"""
cursorIntToContentValues(cursor, field, values, field);
} | java | public static void cursorIntToContentValues(Cursor cursor, String field, ContentValues values) {
cursorIntToContentValues(cursor, field, values, field);
} | [
"public",
"static",
"void",
"cursorIntToContentValues",
"(",
"Cursor",
"cursor",
",",
"String",
"field",
",",
"ContentValues",
"values",
")",
"{",
"cursorIntToContentValues",
"(",
"cursor",
",",
"field",
",",
"values",
",",
"field",
")",
";",
"}"
] | Reads an Integer out of a field in a Cursor and writes it to a Map.
@param cursor The cursor to read from
@param field The INTEGER field to read
@param values The {@link ContentValues} to put the value into, with the field as the key | [
"Reads",
"an",
"Integer",
"out",
"of",
"a",
"field",
"in",
"a",
"Cursor",
"and",
"writes",
"it",
"to",
"a",
"Map",
"."
] | train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/sqlite-android/src/main/java/org/sqlite/database/DatabaseUtils.java#L646-L648 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/db/GridTable.java | GridTable.init | public void init(BaseDatabase database, Record record) {
"""
Constructor.
@param database Should be null, as the last table on the chain contains the database.
@param record The record's current table will be changed to grid table and moved down my list.
"""
super.init(database, record);
m_gridList = new DataRecordList();
m_iEndOfFileIndex = UNKNOWN_POSITION; // Actual end of file (-1 means don't know)
m_gridBuffer = new DataRecordBuffer();
m_gridNew = new DataRecordBuffer();
m_iPhysicalFilePosition = UNKNOWN_POSITION;
m_iLogicalFilePosition = UNKNOWN_POSITION;
if (((record.getOpenMode() & DBConstants.OPEN_READ_ONLY) != DBConstants.OPEN_READ_ONLY)
&& (record.getCounterField() != null))
record.setOpenMode(record.getOpenMode() | DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY); // Must have for GridTable to re-read.
} | java | public void init(BaseDatabase database, Record record)
{
super.init(database, record);
m_gridList = new DataRecordList();
m_iEndOfFileIndex = UNKNOWN_POSITION; // Actual end of file (-1 means don't know)
m_gridBuffer = new DataRecordBuffer();
m_gridNew = new DataRecordBuffer();
m_iPhysicalFilePosition = UNKNOWN_POSITION;
m_iLogicalFilePosition = UNKNOWN_POSITION;
if (((record.getOpenMode() & DBConstants.OPEN_READ_ONLY) != DBConstants.OPEN_READ_ONLY)
&& (record.getCounterField() != null))
record.setOpenMode(record.getOpenMode() | DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY); // Must have for GridTable to re-read.
} | [
"public",
"void",
"init",
"(",
"BaseDatabase",
"database",
",",
"Record",
"record",
")",
"{",
"super",
".",
"init",
"(",
"database",
",",
"record",
")",
";",
"m_gridList",
"=",
"new",
"DataRecordList",
"(",
")",
";",
"m_iEndOfFileIndex",
"=",
"UNKNOWN_POSITION",
";",
"// Actual end of file (-1 means don't know)",
"m_gridBuffer",
"=",
"new",
"DataRecordBuffer",
"(",
")",
";",
"m_gridNew",
"=",
"new",
"DataRecordBuffer",
"(",
")",
";",
"m_iPhysicalFilePosition",
"=",
"UNKNOWN_POSITION",
";",
"m_iLogicalFilePosition",
"=",
"UNKNOWN_POSITION",
";",
"if",
"(",
"(",
"(",
"record",
".",
"getOpenMode",
"(",
")",
"&",
"DBConstants",
".",
"OPEN_READ_ONLY",
")",
"!=",
"DBConstants",
".",
"OPEN_READ_ONLY",
")",
"&&",
"(",
"record",
".",
"getCounterField",
"(",
")",
"!=",
"null",
")",
")",
"record",
".",
"setOpenMode",
"(",
"record",
".",
"getOpenMode",
"(",
")",
"|",
"DBConstants",
".",
"OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY",
")",
";",
"// Must have for GridTable to re-read.",
"}"
] | Constructor.
@param database Should be null, as the last table on the chain contains the database.
@param record The record's current table will be changed to grid table and moved down my list. | [
"Constructor",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/GridTable.java#L132-L147 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/io/IOUtils.java | IOUtils.iterFilesRecursive | public static Iterable<File> iterFilesRecursive(final File dir,
final String ext) {
"""
Iterate over all the files in the directory, recursively.
@param dir
The root directory.
@param ext
A string that must be at the end of all files (e.g. ".txt")
@return All files within the directory ending in the given extension.
"""
return iterFilesRecursive(dir, Pattern.compile(Pattern.quote(ext) + "$"));
} | java | public static Iterable<File> iterFilesRecursive(final File dir,
final String ext) {
return iterFilesRecursive(dir, Pattern.compile(Pattern.quote(ext) + "$"));
} | [
"public",
"static",
"Iterable",
"<",
"File",
">",
"iterFilesRecursive",
"(",
"final",
"File",
"dir",
",",
"final",
"String",
"ext",
")",
"{",
"return",
"iterFilesRecursive",
"(",
"dir",
",",
"Pattern",
".",
"compile",
"(",
"Pattern",
".",
"quote",
"(",
"ext",
")",
"+",
"\"$\"",
")",
")",
";",
"}"
] | Iterate over all the files in the directory, recursively.
@param dir
The root directory.
@param ext
A string that must be at the end of all files (e.g. ".txt")
@return All files within the directory ending in the given extension. | [
"Iterate",
"over",
"all",
"the",
"files",
"in",
"the",
"directory",
"recursively",
"."
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/io/IOUtils.java#L622-L625 |
dkpro/dkpro-jwpl | de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/templates/parser/ParseUtils.java | ParseUtils.parsePage | private static Object parsePage(AstVisitor v, String text, String title, long revision) throws LinkTargetException, EngineException, FileNotFoundException, JAXBException {
"""
Parses the page with the Sweble parser using a SimpleWikiConfiguration
and the provided visitor.
@return the parsed page. The actual return type depends on the provided
visitor. You have to cast the return type according to the return
type of the go() method of your visitor.
@throws EngineException if the wiki page could not be compiled by the parser
"""
// Use the provided visitor to parse the page
return v.go(getCompiledPage(text, title, revision).getPage());
} | java | private static Object parsePage(AstVisitor v, String text, String title, long revision) throws LinkTargetException, EngineException, FileNotFoundException, JAXBException{
// Use the provided visitor to parse the page
return v.go(getCompiledPage(text, title, revision).getPage());
} | [
"private",
"static",
"Object",
"parsePage",
"(",
"AstVisitor",
"v",
",",
"String",
"text",
",",
"String",
"title",
",",
"long",
"revision",
")",
"throws",
"LinkTargetException",
",",
"EngineException",
",",
"FileNotFoundException",
",",
"JAXBException",
"{",
"// Use the provided visitor to parse the page",
"return",
"v",
".",
"go",
"(",
"getCompiledPage",
"(",
"text",
",",
"title",
",",
"revision",
")",
".",
"getPage",
"(",
")",
")",
";",
"}"
] | Parses the page with the Sweble parser using a SimpleWikiConfiguration
and the provided visitor.
@return the parsed page. The actual return type depends on the provided
visitor. You have to cast the return type according to the return
type of the go() method of your visitor.
@throws EngineException if the wiki page could not be compiled by the parser | [
"Parses",
"the",
"page",
"with",
"the",
"Sweble",
"parser",
"using",
"a",
"SimpleWikiConfiguration",
"and",
"the",
"provided",
"visitor",
"."
] | train | https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/templates/parser/ParseUtils.java#L92-L95 |
pietermartin/sqlg | sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/Schema.java | Schema.removeVertexLabel | void removeVertexLabel(VertexLabel vertexLabel, boolean preserveData) {
"""
remove a given vertex label
@param vertexLabel the vertex label
@param preserveData should we keep the SQL data
"""
getTopology().lock();
String fn = this.name + "." + VERTEX_PREFIX + vertexLabel.getName();
if (!uncommittedRemovedVertexLabels.contains(fn)) {
uncommittedRemovedVertexLabels.add(fn);
TopologyManager.removeVertexLabel(this.sqlgGraph, vertexLabel);
for (EdgeRole er : vertexLabel.getOutEdgeRoles().values()) {
er.remove(preserveData);
}
for (EdgeRole er : vertexLabel.getInEdgeRoles().values()) {
er.remove(preserveData);
}
if (!preserveData) {
vertexLabel.delete();
}
getTopology().fire(vertexLabel, "", TopologyChangeAction.DELETE);
}
} | java | void removeVertexLabel(VertexLabel vertexLabel, boolean preserveData) {
getTopology().lock();
String fn = this.name + "." + VERTEX_PREFIX + vertexLabel.getName();
if (!uncommittedRemovedVertexLabels.contains(fn)) {
uncommittedRemovedVertexLabels.add(fn);
TopologyManager.removeVertexLabel(this.sqlgGraph, vertexLabel);
for (EdgeRole er : vertexLabel.getOutEdgeRoles().values()) {
er.remove(preserveData);
}
for (EdgeRole er : vertexLabel.getInEdgeRoles().values()) {
er.remove(preserveData);
}
if (!preserveData) {
vertexLabel.delete();
}
getTopology().fire(vertexLabel, "", TopologyChangeAction.DELETE);
}
} | [
"void",
"removeVertexLabel",
"(",
"VertexLabel",
"vertexLabel",
",",
"boolean",
"preserveData",
")",
"{",
"getTopology",
"(",
")",
".",
"lock",
"(",
")",
";",
"String",
"fn",
"=",
"this",
".",
"name",
"+",
"\".\"",
"+",
"VERTEX_PREFIX",
"+",
"vertexLabel",
".",
"getName",
"(",
")",
";",
"if",
"(",
"!",
"uncommittedRemovedVertexLabels",
".",
"contains",
"(",
"fn",
")",
")",
"{",
"uncommittedRemovedVertexLabels",
".",
"add",
"(",
"fn",
")",
";",
"TopologyManager",
".",
"removeVertexLabel",
"(",
"this",
".",
"sqlgGraph",
",",
"vertexLabel",
")",
";",
"for",
"(",
"EdgeRole",
"er",
":",
"vertexLabel",
".",
"getOutEdgeRoles",
"(",
")",
".",
"values",
"(",
")",
")",
"{",
"er",
".",
"remove",
"(",
"preserveData",
")",
";",
"}",
"for",
"(",
"EdgeRole",
"er",
":",
"vertexLabel",
".",
"getInEdgeRoles",
"(",
")",
".",
"values",
"(",
")",
")",
"{",
"er",
".",
"remove",
"(",
"preserveData",
")",
";",
"}",
"if",
"(",
"!",
"preserveData",
")",
"{",
"vertexLabel",
".",
"delete",
"(",
")",
";",
"}",
"getTopology",
"(",
")",
".",
"fire",
"(",
"vertexLabel",
",",
"\"\"",
",",
"TopologyChangeAction",
".",
"DELETE",
")",
";",
"}",
"}"
] | remove a given vertex label
@param vertexLabel the vertex label
@param preserveData should we keep the SQL data | [
"remove",
"a",
"given",
"vertex",
"label"
] | train | https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/Schema.java#L1784-L1802 |
h2oai/h2o-3 | h2o-core/src/main/java/water/parser/ParseSetup.java | ParseSetup.getFinalSetup | public final ParseSetup getFinalSetup(Key[] inputKeys, ParseSetup demandedSetup) {
"""
Return create a final parser-specific setup
for this configuration.
@param inputKeys inputs
@param demandedSetup setup demanded by a user
@return a parser specific setup based on demanded setup
"""
ParserProvider pp = ParserService.INSTANCE.getByInfo(_parse_type);
if (pp != null) {
ParseSetup ps = pp.createParserSetup(inputKeys, demandedSetup);
if (demandedSetup._decrypt_tool != null)
ps._decrypt_tool = demandedSetup._decrypt_tool;
ps.setSkippedColumns(demandedSetup.getSkippedColumns());
ps.setParseColumnIndices(demandedSetup.getNumberColumns(), demandedSetup.getSkippedColumns()); // final consistent check between skipped_columns and parse_columns_indices
return ps;
}
throw new H2OIllegalArgumentException("Unknown parser configuration! Configuration=" + this);
} | java | public final ParseSetup getFinalSetup(Key[] inputKeys, ParseSetup demandedSetup) {
ParserProvider pp = ParserService.INSTANCE.getByInfo(_parse_type);
if (pp != null) {
ParseSetup ps = pp.createParserSetup(inputKeys, demandedSetup);
if (demandedSetup._decrypt_tool != null)
ps._decrypt_tool = demandedSetup._decrypt_tool;
ps.setSkippedColumns(demandedSetup.getSkippedColumns());
ps.setParseColumnIndices(demandedSetup.getNumberColumns(), demandedSetup.getSkippedColumns()); // final consistent check between skipped_columns and parse_columns_indices
return ps;
}
throw new H2OIllegalArgumentException("Unknown parser configuration! Configuration=" + this);
} | [
"public",
"final",
"ParseSetup",
"getFinalSetup",
"(",
"Key",
"[",
"]",
"inputKeys",
",",
"ParseSetup",
"demandedSetup",
")",
"{",
"ParserProvider",
"pp",
"=",
"ParserService",
".",
"INSTANCE",
".",
"getByInfo",
"(",
"_parse_type",
")",
";",
"if",
"(",
"pp",
"!=",
"null",
")",
"{",
"ParseSetup",
"ps",
"=",
"pp",
".",
"createParserSetup",
"(",
"inputKeys",
",",
"demandedSetup",
")",
";",
"if",
"(",
"demandedSetup",
".",
"_decrypt_tool",
"!=",
"null",
")",
"ps",
".",
"_decrypt_tool",
"=",
"demandedSetup",
".",
"_decrypt_tool",
";",
"ps",
".",
"setSkippedColumns",
"(",
"demandedSetup",
".",
"getSkippedColumns",
"(",
")",
")",
";",
"ps",
".",
"setParseColumnIndices",
"(",
"demandedSetup",
".",
"getNumberColumns",
"(",
")",
",",
"demandedSetup",
".",
"getSkippedColumns",
"(",
")",
")",
";",
"// final consistent check between skipped_columns and parse_columns_indices",
"return",
"ps",
";",
"}",
"throw",
"new",
"H2OIllegalArgumentException",
"(",
"\"Unknown parser configuration! Configuration=\"",
"+",
"this",
")",
";",
"}"
] | Return create a final parser-specific setup
for this configuration.
@param inputKeys inputs
@param demandedSetup setup demanded by a user
@return a parser specific setup based on demanded setup | [
"Return",
"create",
"a",
"final",
"parser",
"-",
"specific",
"setup",
"for",
"this",
"configuration",
"."
] | train | https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/parser/ParseSetup.java#L267-L279 |
lessthanoptimal/ejml | main/ejml-core/src/org/ejml/data/DMatrixSparseTriplet.java | DMatrixSparseTriplet.addItemCheck | public void addItemCheck(int row , int col , double value ) {
"""
Adds a triplet of (row,vol,value) to the end of the list and performs a bounds check to make
sure it is a legal value.
@See #addItem(int, int, double)
@param row Row the element belongs in
@param col Column the element belongs in
@param value The value of the element
"""
if( row < 0 || col < 0 || row >= numRows || col >= numCols )
throw new IllegalArgumentException("Out of bounds. ("+row+","+col+") "+numRows+" "+numCols);
if( nz_length == nz_value.data.length ) {
int amount = nz_length + 10;
nz_value.growInternal(amount);
nz_rowcol.growInternal(amount*2);
}
nz_value.data[nz_length] = value;
nz_rowcol.data[nz_length*2] = row;
nz_rowcol.data[nz_length*2+1] = col;
nz_length += 1;
} | java | public void addItemCheck(int row , int col , double value ) {
if( row < 0 || col < 0 || row >= numRows || col >= numCols )
throw new IllegalArgumentException("Out of bounds. ("+row+","+col+") "+numRows+" "+numCols);
if( nz_length == nz_value.data.length ) {
int amount = nz_length + 10;
nz_value.growInternal(amount);
nz_rowcol.growInternal(amount*2);
}
nz_value.data[nz_length] = value;
nz_rowcol.data[nz_length*2] = row;
nz_rowcol.data[nz_length*2+1] = col;
nz_length += 1;
} | [
"public",
"void",
"addItemCheck",
"(",
"int",
"row",
",",
"int",
"col",
",",
"double",
"value",
")",
"{",
"if",
"(",
"row",
"<",
"0",
"||",
"col",
"<",
"0",
"||",
"row",
">=",
"numRows",
"||",
"col",
">=",
"numCols",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Out of bounds. (\"",
"+",
"row",
"+",
"\",\"",
"+",
"col",
"+",
"\") \"",
"+",
"numRows",
"+",
"\" \"",
"+",
"numCols",
")",
";",
"if",
"(",
"nz_length",
"==",
"nz_value",
".",
"data",
".",
"length",
")",
"{",
"int",
"amount",
"=",
"nz_length",
"+",
"10",
";",
"nz_value",
".",
"growInternal",
"(",
"amount",
")",
";",
"nz_rowcol",
".",
"growInternal",
"(",
"amount",
"*",
"2",
")",
";",
"}",
"nz_value",
".",
"data",
"[",
"nz_length",
"]",
"=",
"value",
";",
"nz_rowcol",
".",
"data",
"[",
"nz_length",
"*",
"2",
"]",
"=",
"row",
";",
"nz_rowcol",
".",
"data",
"[",
"nz_length",
"*",
"2",
"+",
"1",
"]",
"=",
"col",
";",
"nz_length",
"+=",
"1",
";",
"}"
] | Adds a triplet of (row,vol,value) to the end of the list and performs a bounds check to make
sure it is a legal value.
@See #addItem(int, int, double)
@param row Row the element belongs in
@param col Column the element belongs in
@param value The value of the element | [
"Adds",
"a",
"triplet",
"of",
"(",
"row",
"vol",
"value",
")",
"to",
"the",
"end",
"of",
"the",
"list",
"and",
"performs",
"a",
"bounds",
"check",
"to",
"make",
"sure",
"it",
"is",
"a",
"legal",
"value",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-core/src/org/ejml/data/DMatrixSparseTriplet.java#L130-L142 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/tools/net/support/AbstractClientServerSupport.java | AbstractClientServerSupport.sendMessage | protected Socket sendMessage(Socket socket, String message) throws IOException {
"""
Sends a simple {@link String message} over the given {@link Socket}.
@param socket {@link Socket} on which the {@link String message} is sent.
@param message {@link String} containing the message to send over the {@link Socket}.
@return the given {@link Socket} in order to chain multiple send operations.
@throws IOException if an I/O error occurs while sending the given {@code message}
using the provided {@link Socket}.
@see #newBufferedReader(Socket)
@see java.io.BufferedReader#readLine()
@see java.net.Socket
"""
PrintWriter printWriter = newPrintWriter(socket);
printWriter.println(message);
printWriter.flush();
return socket;
} | java | protected Socket sendMessage(Socket socket, String message) throws IOException {
PrintWriter printWriter = newPrintWriter(socket);
printWriter.println(message);
printWriter.flush();
return socket;
} | [
"protected",
"Socket",
"sendMessage",
"(",
"Socket",
"socket",
",",
"String",
"message",
")",
"throws",
"IOException",
"{",
"PrintWriter",
"printWriter",
"=",
"newPrintWriter",
"(",
"socket",
")",
";",
"printWriter",
".",
"println",
"(",
"message",
")",
";",
"printWriter",
".",
"flush",
"(",
")",
";",
"return",
"socket",
";",
"}"
] | Sends a simple {@link String message} over the given {@link Socket}.
@param socket {@link Socket} on which the {@link String message} is sent.
@param message {@link String} containing the message to send over the {@link Socket}.
@return the given {@link Socket} in order to chain multiple send operations.
@throws IOException if an I/O error occurs while sending the given {@code message}
using the provided {@link Socket}.
@see #newBufferedReader(Socket)
@see java.io.BufferedReader#readLine()
@see java.net.Socket | [
"Sends",
"a",
"simple",
"{",
"@link",
"String",
"message",
"}",
"over",
"the",
"given",
"{",
"@link",
"Socket",
"}",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/tools/net/support/AbstractClientServerSupport.java#L203-L210 |
gresrun/jesque | src/main/java/net/greghaines/jesque/Job.java | Job.setVars | @SuppressWarnings("unchecked")
public void setVars(final Map<String, ? extends Object> vars) {
"""
Set the named arguments.
@param vars
the new named arguments
"""
this.vars = (Map<String, Object>)vars;
} | java | @SuppressWarnings("unchecked")
public void setVars(final Map<String, ? extends Object> vars) {
this.vars = (Map<String, Object>)vars;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"void",
"setVars",
"(",
"final",
"Map",
"<",
"String",
",",
"?",
"extends",
"Object",
">",
"vars",
")",
"{",
"this",
".",
"vars",
"=",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
")",
"vars",
";",
"}"
] | Set the named arguments.
@param vars
the new named arguments | [
"Set",
"the",
"named",
"arguments",
"."
] | train | https://github.com/gresrun/jesque/blob/44749183dccc40962a94c2af547ea7d0d880b5d1/src/main/java/net/greghaines/jesque/Job.java#L193-L196 |
alexvasilkov/AndroidCommons | library/src/main/java/com/alexvasilkov/android/commons/prefs/PreferencesHelper.java | PreferencesHelper.getStringArray | @Nullable
public static String[] getStringArray(@NonNull SharedPreferences prefs, @NonNull String key) {
"""
Retrieves strings array stored as single string.
Uses {@link #DEFAULT_DELIMITER} as delimiter.
"""
return getStringArray(prefs, key, DEFAULT_DELIMITER);
} | java | @Nullable
public static String[] getStringArray(@NonNull SharedPreferences prefs, @NonNull String key) {
return getStringArray(prefs, key, DEFAULT_DELIMITER);
} | [
"@",
"Nullable",
"public",
"static",
"String",
"[",
"]",
"getStringArray",
"(",
"@",
"NonNull",
"SharedPreferences",
"prefs",
",",
"@",
"NonNull",
"String",
"key",
")",
"{",
"return",
"getStringArray",
"(",
"prefs",
",",
"key",
",",
"DEFAULT_DELIMITER",
")",
";",
"}"
] | Retrieves strings array stored as single string.
Uses {@link #DEFAULT_DELIMITER} as delimiter. | [
"Retrieves",
"strings",
"array",
"stored",
"as",
"single",
"string",
".",
"Uses",
"{"
] | train | https://github.com/alexvasilkov/AndroidCommons/blob/aca9f6d5acfc6bd3694984b7f89956e1a0146ddb/library/src/main/java/com/alexvasilkov/android/commons/prefs/PreferencesHelper.java#L101-L104 |
yanzhenjie/AndPermission | support/src/main/java/com/yanzhenjie/permission/AndPermission.java | AndPermission.hasPermissions | public static boolean hasPermissions(Activity activity, String[]... permissions) {
"""
Judgment already has the target permission.
@param activity {@link Activity}.
@param permissions one or more permission groups.
@return true, other wise is false.
"""
for (String[] permission : permissions) {
boolean hasPermission = PERMISSION_CHECKER.hasPermission(activity, permission);
if (!hasPermission) return false;
}
return true;
} | java | public static boolean hasPermissions(Activity activity, String[]... permissions) {
for (String[] permission : permissions) {
boolean hasPermission = PERMISSION_CHECKER.hasPermission(activity, permission);
if (!hasPermission) return false;
}
return true;
} | [
"public",
"static",
"boolean",
"hasPermissions",
"(",
"Activity",
"activity",
",",
"String",
"[",
"]",
"...",
"permissions",
")",
"{",
"for",
"(",
"String",
"[",
"]",
"permission",
":",
"permissions",
")",
"{",
"boolean",
"hasPermission",
"=",
"PERMISSION_CHECKER",
".",
"hasPermission",
"(",
"activity",
",",
"permission",
")",
";",
"if",
"(",
"!",
"hasPermission",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Judgment already has the target permission.
@param activity {@link Activity}.
@param permissions one or more permission groups.
@return true, other wise is false. | [
"Judgment",
"already",
"has",
"the",
"target",
"permission",
"."
] | train | https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/support/src/main/java/com/yanzhenjie/permission/AndPermission.java#L307-L313 |
operasoftware/operaprestodriver | src/com/opera/core/systems/common/lang/OperaStrings.java | OperaStrings.escapeJsString | public static String escapeJsString(String string, String quote) {
"""
Escape characters for safe insertion in a JavaScript string.
@param string the string to escape
@param quote the type of quote to escape. Either " or '
@return the escaped string
"""
// This should be expanded to match all invalid characters (e.g. newlines) but for the moment
// we'll trust we'll only get quotes.
Pattern escapePattern = Pattern.compile("([^\\\\])" + quote);
// Prepend a space so that the regex can match quotes at the beginning of the string
Matcher m = escapePattern.matcher(" " + string);
StringBuffer sb = new StringBuffer();
while (m.find()) {
// $1 -> inserts the character before the quote \\\\\" -> \\", apparently just \" isn't
// treated literally.
m.appendReplacement(sb, "$1\\\\" + quote);
}
m.appendTail(sb);
// Remove the prepended space.
return sb.substring(1);
} | java | public static String escapeJsString(String string, String quote) {
// This should be expanded to match all invalid characters (e.g. newlines) but for the moment
// we'll trust we'll only get quotes.
Pattern escapePattern = Pattern.compile("([^\\\\])" + quote);
// Prepend a space so that the regex can match quotes at the beginning of the string
Matcher m = escapePattern.matcher(" " + string);
StringBuffer sb = new StringBuffer();
while (m.find()) {
// $1 -> inserts the character before the quote \\\\\" -> \\", apparently just \" isn't
// treated literally.
m.appendReplacement(sb, "$1\\\\" + quote);
}
m.appendTail(sb);
// Remove the prepended space.
return sb.substring(1);
} | [
"public",
"static",
"String",
"escapeJsString",
"(",
"String",
"string",
",",
"String",
"quote",
")",
"{",
"// This should be expanded to match all invalid characters (e.g. newlines) but for the moment",
"// we'll trust we'll only get quotes.",
"Pattern",
"escapePattern",
"=",
"Pattern",
".",
"compile",
"(",
"\"([^\\\\\\\\])\"",
"+",
"quote",
")",
";",
"// Prepend a space so that the regex can match quotes at the beginning of the string",
"Matcher",
"m",
"=",
"escapePattern",
".",
"matcher",
"(",
"\" \"",
"+",
"string",
")",
";",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"while",
"(",
"m",
".",
"find",
"(",
")",
")",
"{",
"// $1 -> inserts the character before the quote \\\\\\\\\\\" -> \\\\\", apparently just \\\" isn't",
"// treated literally.",
"m",
".",
"appendReplacement",
"(",
"sb",
",",
"\"$1\\\\\\\\\"",
"+",
"quote",
")",
";",
"}",
"m",
".",
"appendTail",
"(",
"sb",
")",
";",
"// Remove the prepended space.",
"return",
"sb",
".",
"substring",
"(",
"1",
")",
";",
"}"
] | Escape characters for safe insertion in a JavaScript string.
@param string the string to escape
@param quote the type of quote to escape. Either " or '
@return the escaped string | [
"Escape",
"characters",
"for",
"safe",
"insertion",
"in",
"a",
"JavaScript",
"string",
"."
] | train | https://github.com/operasoftware/operaprestodriver/blob/1ccceda80f1c1a0489171d17dcaa6e7b18fb4c01/src/com/opera/core/systems/common/lang/OperaStrings.java#L96-L115 |
RestComm/sip-servlets | sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java | FacebookRestClient.sms_sendResponse | public void sms_sendResponse(Integer userId, CharSequence response, Integer mobileSessionId)
throws FacebookException, IOException {
"""
Sends a message via SMS to the user identified by <code>userId</code> in response
to a user query associated with <code>mobileSessionId</code>.
@param userId a user ID
@param response the message to be sent via SMS
@param mobileSessionId the mobile session
@throws FacebookException in case of error
@throws IOException
@see FacebookExtendedPerm#SMS
@see <a href="http://wiki.developers.facebook.com/index.php/Mobile#Application_generated_messages">
Developers Wiki: Mobile: Application Generated Messages</a>
@see <a href="http://wiki.developers.facebook.com/index.php/Mobile#Workflow">
Developers Wiki: Mobile: Workflow</a>
"""
this.callMethod(FacebookMethod.SMS_SEND_MESSAGE,
new Pair<String, CharSequence>("uid", userId.toString()),
new Pair<String, CharSequence>("message", response),
new Pair<String, CharSequence>("session_id", mobileSessionId.toString()));
} | java | public void sms_sendResponse(Integer userId, CharSequence response, Integer mobileSessionId)
throws FacebookException, IOException {
this.callMethod(FacebookMethod.SMS_SEND_MESSAGE,
new Pair<String, CharSequence>("uid", userId.toString()),
new Pair<String, CharSequence>("message", response),
new Pair<String, CharSequence>("session_id", mobileSessionId.toString()));
} | [
"public",
"void",
"sms_sendResponse",
"(",
"Integer",
"userId",
",",
"CharSequence",
"response",
",",
"Integer",
"mobileSessionId",
")",
"throws",
"FacebookException",
",",
"IOException",
"{",
"this",
".",
"callMethod",
"(",
"FacebookMethod",
".",
"SMS_SEND_MESSAGE",
",",
"new",
"Pair",
"<",
"String",
",",
"CharSequence",
">",
"(",
"\"uid\"",
",",
"userId",
".",
"toString",
"(",
")",
")",
",",
"new",
"Pair",
"<",
"String",
",",
"CharSequence",
">",
"(",
"\"message\"",
",",
"response",
")",
",",
"new",
"Pair",
"<",
"String",
",",
"CharSequence",
">",
"(",
"\"session_id\"",
",",
"mobileSessionId",
".",
"toString",
"(",
")",
")",
")",
";",
"}"
] | Sends a message via SMS to the user identified by <code>userId</code> in response
to a user query associated with <code>mobileSessionId</code>.
@param userId a user ID
@param response the message to be sent via SMS
@param mobileSessionId the mobile session
@throws FacebookException in case of error
@throws IOException
@see FacebookExtendedPerm#SMS
@see <a href="http://wiki.developers.facebook.com/index.php/Mobile#Application_generated_messages">
Developers Wiki: Mobile: Application Generated Messages</a>
@see <a href="http://wiki.developers.facebook.com/index.php/Mobile#Workflow">
Developers Wiki: Mobile: Workflow</a> | [
"Sends",
"a",
"message",
"via",
"SMS",
"to",
"the",
"user",
"identified",
"by",
"<code",
">",
"userId<",
"/",
"code",
">",
"in",
"response",
"to",
"a",
"user",
"query",
"associated",
"with",
"<code",
">",
"mobileSessionId<",
"/",
"code",
">",
"."
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L1635-L1641 |
alkacon/opencms-core | src-setup/org/opencms/setup/CmsSetupBean.java | CmsSetupBean.saveProperties | public void saveProperties(CmsParameterConfiguration properties, String file, boolean backup) {
"""
Saves properties to specified file.<p>
@param properties the properties to be saved
@param file the file to save the properties to
@param backup if true, create a backupfile
"""
if (new File(m_configRfsPath + file).isFile()) {
String backupFile = file + CmsConfigurationManager.POSTFIX_ORI;
String tempFile = file + ".tmp";
m_errors.clear();
if (backup) {
// make a backup copy
copyFile(file, FOLDER_BACKUP + backupFile);
}
//save to temporary file
copyFile(file, tempFile);
// save properties
save(properties, tempFile, file, null);
// delete temp file
File temp = new File(m_configRfsPath + tempFile);
temp.delete();
} else {
m_errors.add("No valid file: " + file + "\n");
}
} | java | public void saveProperties(CmsParameterConfiguration properties, String file, boolean backup) {
if (new File(m_configRfsPath + file).isFile()) {
String backupFile = file + CmsConfigurationManager.POSTFIX_ORI;
String tempFile = file + ".tmp";
m_errors.clear();
if (backup) {
// make a backup copy
copyFile(file, FOLDER_BACKUP + backupFile);
}
//save to temporary file
copyFile(file, tempFile);
// save properties
save(properties, tempFile, file, null);
// delete temp file
File temp = new File(m_configRfsPath + tempFile);
temp.delete();
} else {
m_errors.add("No valid file: " + file + "\n");
}
} | [
"public",
"void",
"saveProperties",
"(",
"CmsParameterConfiguration",
"properties",
",",
"String",
"file",
",",
"boolean",
"backup",
")",
"{",
"if",
"(",
"new",
"File",
"(",
"m_configRfsPath",
"+",
"file",
")",
".",
"isFile",
"(",
")",
")",
"{",
"String",
"backupFile",
"=",
"file",
"+",
"CmsConfigurationManager",
".",
"POSTFIX_ORI",
";",
"String",
"tempFile",
"=",
"file",
"+",
"\".tmp\"",
";",
"m_errors",
".",
"clear",
"(",
")",
";",
"if",
"(",
"backup",
")",
"{",
"// make a backup copy",
"copyFile",
"(",
"file",
",",
"FOLDER_BACKUP",
"+",
"backupFile",
")",
";",
"}",
"//save to temporary file",
"copyFile",
"(",
"file",
",",
"tempFile",
")",
";",
"// save properties",
"save",
"(",
"properties",
",",
"tempFile",
",",
"file",
",",
"null",
")",
";",
"// delete temp file",
"File",
"temp",
"=",
"new",
"File",
"(",
"m_configRfsPath",
"+",
"tempFile",
")",
";",
"temp",
".",
"delete",
"(",
")",
";",
"}",
"else",
"{",
"m_errors",
".",
"add",
"(",
"\"No valid file: \"",
"+",
"file",
"+",
"\"\\n\"",
")",
";",
"}",
"}"
] | Saves properties to specified file.<p>
@param properties the properties to be saved
@param file the file to save the properties to
@param backup if true, create a backupfile | [
"Saves",
"properties",
"to",
"specified",
"file",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/CmsSetupBean.java#L1732-L1758 |
azkaban/azkaban | azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java | FlowLoaderUtils.addEmailPropsToFlow | public static void addEmailPropsToFlow(final Flow flow, final Props prop) {
"""
Adds email properties to a flow.
@param flow the flow
@param prop the prop
"""
final List<String> successEmailList =
prop.getStringList(CommonJobProperties.SUCCESS_EMAILS,
Collections.EMPTY_LIST);
final Set<String> successEmail = new HashSet<>();
for (final String email : successEmailList) {
successEmail.add(email.toLowerCase());
}
final List<String> failureEmailList =
prop.getStringList(CommonJobProperties.FAILURE_EMAILS,
Collections.EMPTY_LIST);
final Set<String> failureEmail = new HashSet<>();
for (final String email : failureEmailList) {
failureEmail.add(email.toLowerCase());
}
final List<String> notifyEmailList =
prop.getStringList(CommonJobProperties.NOTIFY_EMAILS,
Collections.EMPTY_LIST);
for (String email : notifyEmailList) {
email = email.toLowerCase();
successEmail.add(email);
failureEmail.add(email);
}
flow.addFailureEmails(failureEmail);
flow.addSuccessEmails(successEmail);
} | java | public static void addEmailPropsToFlow(final Flow flow, final Props prop) {
final List<String> successEmailList =
prop.getStringList(CommonJobProperties.SUCCESS_EMAILS,
Collections.EMPTY_LIST);
final Set<String> successEmail = new HashSet<>();
for (final String email : successEmailList) {
successEmail.add(email.toLowerCase());
}
final List<String> failureEmailList =
prop.getStringList(CommonJobProperties.FAILURE_EMAILS,
Collections.EMPTY_LIST);
final Set<String> failureEmail = new HashSet<>();
for (final String email : failureEmailList) {
failureEmail.add(email.toLowerCase());
}
final List<String> notifyEmailList =
prop.getStringList(CommonJobProperties.NOTIFY_EMAILS,
Collections.EMPTY_LIST);
for (String email : notifyEmailList) {
email = email.toLowerCase();
successEmail.add(email);
failureEmail.add(email);
}
flow.addFailureEmails(failureEmail);
flow.addSuccessEmails(successEmail);
} | [
"public",
"static",
"void",
"addEmailPropsToFlow",
"(",
"final",
"Flow",
"flow",
",",
"final",
"Props",
"prop",
")",
"{",
"final",
"List",
"<",
"String",
">",
"successEmailList",
"=",
"prop",
".",
"getStringList",
"(",
"CommonJobProperties",
".",
"SUCCESS_EMAILS",
",",
"Collections",
".",
"EMPTY_LIST",
")",
";",
"final",
"Set",
"<",
"String",
">",
"successEmail",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"for",
"(",
"final",
"String",
"email",
":",
"successEmailList",
")",
"{",
"successEmail",
".",
"add",
"(",
"email",
".",
"toLowerCase",
"(",
")",
")",
";",
"}",
"final",
"List",
"<",
"String",
">",
"failureEmailList",
"=",
"prop",
".",
"getStringList",
"(",
"CommonJobProperties",
".",
"FAILURE_EMAILS",
",",
"Collections",
".",
"EMPTY_LIST",
")",
";",
"final",
"Set",
"<",
"String",
">",
"failureEmail",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"for",
"(",
"final",
"String",
"email",
":",
"failureEmailList",
")",
"{",
"failureEmail",
".",
"add",
"(",
"email",
".",
"toLowerCase",
"(",
")",
")",
";",
"}",
"final",
"List",
"<",
"String",
">",
"notifyEmailList",
"=",
"prop",
".",
"getStringList",
"(",
"CommonJobProperties",
".",
"NOTIFY_EMAILS",
",",
"Collections",
".",
"EMPTY_LIST",
")",
";",
"for",
"(",
"String",
"email",
":",
"notifyEmailList",
")",
"{",
"email",
"=",
"email",
".",
"toLowerCase",
"(",
")",
";",
"successEmail",
".",
"add",
"(",
"email",
")",
";",
"failureEmail",
".",
"add",
"(",
"email",
")",
";",
"}",
"flow",
".",
"addFailureEmails",
"(",
"failureEmail",
")",
";",
"flow",
".",
"addSuccessEmails",
"(",
"successEmail",
")",
";",
"}"
] | Adds email properties to a flow.
@param flow the flow
@param prop the prop | [
"Adds",
"email",
"properties",
"to",
"a",
"flow",
"."
] | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java#L198-L226 |
groupon/odo | proxylib/src/main/java/com/groupon/odo/proxylib/PluginManager.java | PluginManager.loadClass | public void loadClass(String className) throws Exception {
"""
Loads the specified class name and stores it in the hash
@param className class name
@throws Exception exception
"""
ClassInformation classInfo = classInformation.get(className);
logger.info("Loading plugin.: {}, {}", className, classInfo.pluginPath);
// get URL for proxylib
// need to load this also otherwise the annotations cannot be found later on
File libFile = new File(proxyLibPath);
URL libUrl = libFile.toURI().toURL();
// store the last modified time of the plugin
File pluginDirectoryFile = new File(classInfo.pluginPath);
classInfo.lastModified = pluginDirectoryFile.lastModified();
// load the plugin directory
URL classURL = new File(classInfo.pluginPath).toURI().toURL();
URL[] urls = new URL[] {classURL};
URLClassLoader child = new URLClassLoader(urls, this.getClass().getClassLoader());
// load the class
Class<?> cls = child.loadClass(className);
// put loaded class into classInfo
classInfo.loadedClass = cls;
classInfo.loaded = true;
classInformation.put(className, classInfo);
logger.info("Loaded plugin: {}, {} method(s)", cls.toString(), cls.getDeclaredMethods().length);
} | java | public void loadClass(String className) throws Exception {
ClassInformation classInfo = classInformation.get(className);
logger.info("Loading plugin.: {}, {}", className, classInfo.pluginPath);
// get URL for proxylib
// need to load this also otherwise the annotations cannot be found later on
File libFile = new File(proxyLibPath);
URL libUrl = libFile.toURI().toURL();
// store the last modified time of the plugin
File pluginDirectoryFile = new File(classInfo.pluginPath);
classInfo.lastModified = pluginDirectoryFile.lastModified();
// load the plugin directory
URL classURL = new File(classInfo.pluginPath).toURI().toURL();
URL[] urls = new URL[] {classURL};
URLClassLoader child = new URLClassLoader(urls, this.getClass().getClassLoader());
// load the class
Class<?> cls = child.loadClass(className);
// put loaded class into classInfo
classInfo.loadedClass = cls;
classInfo.loaded = true;
classInformation.put(className, classInfo);
logger.info("Loaded plugin: {}, {} method(s)", cls.toString(), cls.getDeclaredMethods().length);
} | [
"public",
"void",
"loadClass",
"(",
"String",
"className",
")",
"throws",
"Exception",
"{",
"ClassInformation",
"classInfo",
"=",
"classInformation",
".",
"get",
"(",
"className",
")",
";",
"logger",
".",
"info",
"(",
"\"Loading plugin.: {}, {}\"",
",",
"className",
",",
"classInfo",
".",
"pluginPath",
")",
";",
"// get URL for proxylib",
"// need to load this also otherwise the annotations cannot be found later on",
"File",
"libFile",
"=",
"new",
"File",
"(",
"proxyLibPath",
")",
";",
"URL",
"libUrl",
"=",
"libFile",
".",
"toURI",
"(",
")",
".",
"toURL",
"(",
")",
";",
"// store the last modified time of the plugin",
"File",
"pluginDirectoryFile",
"=",
"new",
"File",
"(",
"classInfo",
".",
"pluginPath",
")",
";",
"classInfo",
".",
"lastModified",
"=",
"pluginDirectoryFile",
".",
"lastModified",
"(",
")",
";",
"// load the plugin directory",
"URL",
"classURL",
"=",
"new",
"File",
"(",
"classInfo",
".",
"pluginPath",
")",
".",
"toURI",
"(",
")",
".",
"toURL",
"(",
")",
";",
"URL",
"[",
"]",
"urls",
"=",
"new",
"URL",
"[",
"]",
"{",
"classURL",
"}",
";",
"URLClassLoader",
"child",
"=",
"new",
"URLClassLoader",
"(",
"urls",
",",
"this",
".",
"getClass",
"(",
")",
".",
"getClassLoader",
"(",
")",
")",
";",
"// load the class",
"Class",
"<",
"?",
">",
"cls",
"=",
"child",
".",
"loadClass",
"(",
"className",
")",
";",
"// put loaded class into classInfo",
"classInfo",
".",
"loadedClass",
"=",
"cls",
";",
"classInfo",
".",
"loaded",
"=",
"true",
";",
"classInformation",
".",
"put",
"(",
"className",
",",
"classInfo",
")",
";",
"logger",
".",
"info",
"(",
"\"Loaded plugin: {}, {} method(s)\"",
",",
"cls",
".",
"toString",
"(",
")",
",",
"cls",
".",
"getDeclaredMethods",
"(",
")",
".",
"length",
")",
";",
"}"
] | Loads the specified class name and stores it in the hash
@param className class name
@throws Exception exception | [
"Loads",
"the",
"specified",
"class",
"name",
"and",
"stores",
"it",
"in",
"the",
"hash"
] | train | https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxylib/src/main/java/com/groupon/odo/proxylib/PluginManager.java#L218-L248 |
salesforce/Argus | ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AbstractResource.java | AbstractResource.validateAndGetOwner | protected PrincipalUser validateAndGetOwner(HttpServletRequest req, String ownerName) {
"""
Validates the owner name and returns the owner object.
@param req The HTTP request.
@param ownerName Name of the owner. It is optional.
@return The owner object
@throws WebApplicationException Throws exception if owner name does not exist.
"""
PrincipalUser remoteUser = getRemoteUser(req);
if (ownerName == null || ownerName.isEmpty() || ownerName.equalsIgnoreCase(remoteUser.getUserName())) {
//If ownerName is not present or if it is present and equal to remote username, then return remoteUser.
return remoteUser;
} else if (remoteUser.isPrivileged()) {
PrincipalUser owner;
owner = userService.findUserByUsername(ownerName);
if (owner == null) {
throw new WebApplicationException(ownerName + ": User does not exist.", Status.NOT_FOUND);
} else {
return owner;
}
}
throw new WebApplicationException(Status.FORBIDDEN.getReasonPhrase(), Status.FORBIDDEN);
} | java | protected PrincipalUser validateAndGetOwner(HttpServletRequest req, String ownerName) {
PrincipalUser remoteUser = getRemoteUser(req);
if (ownerName == null || ownerName.isEmpty() || ownerName.equalsIgnoreCase(remoteUser.getUserName())) {
//If ownerName is not present or if it is present and equal to remote username, then return remoteUser.
return remoteUser;
} else if (remoteUser.isPrivileged()) {
PrincipalUser owner;
owner = userService.findUserByUsername(ownerName);
if (owner == null) {
throw new WebApplicationException(ownerName + ": User does not exist.", Status.NOT_FOUND);
} else {
return owner;
}
}
throw new WebApplicationException(Status.FORBIDDEN.getReasonPhrase(), Status.FORBIDDEN);
} | [
"protected",
"PrincipalUser",
"validateAndGetOwner",
"(",
"HttpServletRequest",
"req",
",",
"String",
"ownerName",
")",
"{",
"PrincipalUser",
"remoteUser",
"=",
"getRemoteUser",
"(",
"req",
")",
";",
"if",
"(",
"ownerName",
"==",
"null",
"||",
"ownerName",
".",
"isEmpty",
"(",
")",
"||",
"ownerName",
".",
"equalsIgnoreCase",
"(",
"remoteUser",
".",
"getUserName",
"(",
")",
")",
")",
"{",
"//If ownerName is not present or if it is present and equal to remote username, then return remoteUser.",
"return",
"remoteUser",
";",
"}",
"else",
"if",
"(",
"remoteUser",
".",
"isPrivileged",
"(",
")",
")",
"{",
"PrincipalUser",
"owner",
";",
"owner",
"=",
"userService",
".",
"findUserByUsername",
"(",
"ownerName",
")",
";",
"if",
"(",
"owner",
"==",
"null",
")",
"{",
"throw",
"new",
"WebApplicationException",
"(",
"ownerName",
"+",
"\": User does not exist.\"",
",",
"Status",
".",
"NOT_FOUND",
")",
";",
"}",
"else",
"{",
"return",
"owner",
";",
"}",
"}",
"throw",
"new",
"WebApplicationException",
"(",
"Status",
".",
"FORBIDDEN",
".",
"getReasonPhrase",
"(",
")",
",",
"Status",
".",
"FORBIDDEN",
")",
";",
"}"
] | Validates the owner name and returns the owner object.
@param req The HTTP request.
@param ownerName Name of the owner. It is optional.
@return The owner object
@throws WebApplicationException Throws exception if owner name does not exist. | [
"Validates",
"the",
"owner",
"name",
"and",
"returns",
"the",
"owner",
"object",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AbstractResource.java#L192-L210 |
javers/javers | javers-core/src/main/java/org/javers/core/Changes.java | Changes.groupByObject | public List<ChangesByObject> groupByObject() {
"""
Changes grouped by entities.
<br/>
See example in {@link #groupByCommit()}
@since 3.9
"""
Map<GlobalId, List<Change>> changesByObject = changes.stream().collect(
groupingBy(c -> c.getAffectedGlobalId().masterObjectId()));
List<ChangesByObject> result = new ArrayList<>();
changesByObject.forEach((k, v) -> {
result.add(new ChangesByObject(k, v, valuePrinter));
});
return Collections.unmodifiableList(result);
} | java | public List<ChangesByObject> groupByObject() {
Map<GlobalId, List<Change>> changesByObject = changes.stream().collect(
groupingBy(c -> c.getAffectedGlobalId().masterObjectId()));
List<ChangesByObject> result = new ArrayList<>();
changesByObject.forEach((k, v) -> {
result.add(new ChangesByObject(k, v, valuePrinter));
});
return Collections.unmodifiableList(result);
} | [
"public",
"List",
"<",
"ChangesByObject",
">",
"groupByObject",
"(",
")",
"{",
"Map",
"<",
"GlobalId",
",",
"List",
"<",
"Change",
">",
">",
"changesByObject",
"=",
"changes",
".",
"stream",
"(",
")",
".",
"collect",
"(",
"groupingBy",
"(",
"c",
"->",
"c",
".",
"getAffectedGlobalId",
"(",
")",
".",
"masterObjectId",
"(",
")",
")",
")",
";",
"List",
"<",
"ChangesByObject",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"changesByObject",
".",
"forEach",
"(",
"(",
"k",
",",
"v",
")",
"->",
"{",
"result",
".",
"add",
"(",
"new",
"ChangesByObject",
"(",
"k",
",",
"v",
",",
"valuePrinter",
")",
")",
";",
"}",
")",
";",
"return",
"Collections",
".",
"unmodifiableList",
"(",
"result",
")",
";",
"}"
] | Changes grouped by entities.
<br/>
See example in {@link #groupByCommit()}
@since 3.9 | [
"Changes",
"grouped",
"by",
"entities",
".",
"<br",
"/",
">"
] | train | https://github.com/javers/javers/blob/a51511be7d8bcee3e1812db8b7e69a45330b4e14/javers-core/src/main/java/org/javers/core/Changes.java#L106-L116 |
ironjacamar/ironjacamar | core/src/main/java/org/ironjacamar/core/workmanager/transport/remote/jgroups/JGroupsTransport.java | JGroupsTransport.executeStartWork | public long executeStartWork(org.ironjacamar.core.spi.workmanager.Address logicalAddress,
ClassBundle classBundle, byte[] b)
throws WorkException {
"""
Execute startWork
@param logicalAddress The logical address
@param classBundle The class bundle
@param b The bytes
@return the start value
@throws WorkException in case of error
"""
ByteArrayInputStream bias = new ByteArrayInputStream(b);
WorkObjectInputStream wois = null;
try
{
WorkClassLoader wcl = SecurityActions.createWorkClassLoader(classBundle);
wois = new WorkObjectInputStream(bias, wcl);
DistributableWork dw = (DistributableWork)wois.readObject();
return localStartWork(logicalAddress, dw);
}
catch (WorkException we)
{
throw we;
}
catch (Throwable t)
{
throw new WorkException("Error during doWork: " + t.getMessage(), t);
}
finally
{
if (wois != null)
{
try
{
wois.close();
}
catch (IOException ioe)
{
// Ignore
}
}
}
} | java | public long executeStartWork(org.ironjacamar.core.spi.workmanager.Address logicalAddress,
ClassBundle classBundle, byte[] b)
throws WorkException
{
ByteArrayInputStream bias = new ByteArrayInputStream(b);
WorkObjectInputStream wois = null;
try
{
WorkClassLoader wcl = SecurityActions.createWorkClassLoader(classBundle);
wois = new WorkObjectInputStream(bias, wcl);
DistributableWork dw = (DistributableWork)wois.readObject();
return localStartWork(logicalAddress, dw);
}
catch (WorkException we)
{
throw we;
}
catch (Throwable t)
{
throw new WorkException("Error during doWork: " + t.getMessage(), t);
}
finally
{
if (wois != null)
{
try
{
wois.close();
}
catch (IOException ioe)
{
// Ignore
}
}
}
} | [
"public",
"long",
"executeStartWork",
"(",
"org",
".",
"ironjacamar",
".",
"core",
".",
"spi",
".",
"workmanager",
".",
"Address",
"logicalAddress",
",",
"ClassBundle",
"classBundle",
",",
"byte",
"[",
"]",
"b",
")",
"throws",
"WorkException",
"{",
"ByteArrayInputStream",
"bias",
"=",
"new",
"ByteArrayInputStream",
"(",
"b",
")",
";",
"WorkObjectInputStream",
"wois",
"=",
"null",
";",
"try",
"{",
"WorkClassLoader",
"wcl",
"=",
"SecurityActions",
".",
"createWorkClassLoader",
"(",
"classBundle",
")",
";",
"wois",
"=",
"new",
"WorkObjectInputStream",
"(",
"bias",
",",
"wcl",
")",
";",
"DistributableWork",
"dw",
"=",
"(",
"DistributableWork",
")",
"wois",
".",
"readObject",
"(",
")",
";",
"return",
"localStartWork",
"(",
"logicalAddress",
",",
"dw",
")",
";",
"}",
"catch",
"(",
"WorkException",
"we",
")",
"{",
"throw",
"we",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"throw",
"new",
"WorkException",
"(",
"\"Error during doWork: \"",
"+",
"t",
".",
"getMessage",
"(",
")",
",",
"t",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"wois",
"!=",
"null",
")",
"{",
"try",
"{",
"wois",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"ioe",
")",
"{",
"// Ignore",
"}",
"}",
"}",
"}"
] | Execute startWork
@param logicalAddress The logical address
@param classBundle The class bundle
@param b The bytes
@return the start value
@throws WorkException in case of error | [
"Execute",
"startWork"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/core/src/main/java/org/ironjacamar/core/workmanager/transport/remote/jgroups/JGroupsTransport.java#L358-L396 |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java | Element.buildAll | public void buildAll(MessageMLParser context, org.w3c.dom.Element element) throws InvalidInputException,
ProcessingException {
"""
Process a DOM element, descending into its children, and construct the output MessageML tree.
"""
NamedNodeMap attr = element.getAttributes();
for (int i = 0; i < attr.getLength(); i++) {
buildAttribute(attr.item(i));
}
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
buildNode(context, children.item(i));
}
} | java | public void buildAll(MessageMLParser context, org.w3c.dom.Element element) throws InvalidInputException,
ProcessingException {
NamedNodeMap attr = element.getAttributes();
for (int i = 0; i < attr.getLength(); i++) {
buildAttribute(attr.item(i));
}
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
buildNode(context, children.item(i));
}
} | [
"public",
"void",
"buildAll",
"(",
"MessageMLParser",
"context",
",",
"org",
".",
"w3c",
".",
"dom",
".",
"Element",
"element",
")",
"throws",
"InvalidInputException",
",",
"ProcessingException",
"{",
"NamedNodeMap",
"attr",
"=",
"element",
".",
"getAttributes",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"attr",
".",
"getLength",
"(",
")",
";",
"i",
"++",
")",
"{",
"buildAttribute",
"(",
"attr",
".",
"item",
"(",
"i",
")",
")",
";",
"}",
"NodeList",
"children",
"=",
"element",
".",
"getChildNodes",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"children",
".",
"getLength",
"(",
")",
";",
"i",
"++",
")",
"{",
"buildNode",
"(",
"context",
",",
"children",
".",
"item",
"(",
"i",
")",
")",
";",
"}",
"}"
] | Process a DOM element, descending into its children, and construct the output MessageML tree. | [
"Process",
"a",
"DOM",
"element",
"descending",
"into",
"its",
"children",
"and",
"construct",
"the",
"output",
"MessageML",
"tree",
"."
] | train | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java#L80-L93 |
JoeKerouac/utils | src/main/java/com/joe/utils/common/FormDataBuilder.java | FormDataBuilder.data | public String data(boolean useUrlencode, String charset) {
"""
获取form数据
@param useUrlencode 是否使用URLEncode对value进行编码,true表示使用URLEncode进行编码
@param charset 编码字符集
@return form数据
"""
StringBuilder sb = new StringBuilder();
if (useUrlencode) {
datas.forEach((k, v) -> sb.append("&").append(k).append("=")
.append(urlencode(String.valueOf(v), charset)));
} else {
datas.forEach((k, v) -> sb.append("&").append(k).append("=").append(String.valueOf(v)));
}
return sb.toString().substring(1);
} | java | public String data(boolean useUrlencode, String charset) {
StringBuilder sb = new StringBuilder();
if (useUrlencode) {
datas.forEach((k, v) -> sb.append("&").append(k).append("=")
.append(urlencode(String.valueOf(v), charset)));
} else {
datas.forEach((k, v) -> sb.append("&").append(k).append("=").append(String.valueOf(v)));
}
return sb.toString().substring(1);
} | [
"public",
"String",
"data",
"(",
"boolean",
"useUrlencode",
",",
"String",
"charset",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"if",
"(",
"useUrlencode",
")",
"{",
"datas",
".",
"forEach",
"(",
"(",
"k",
",",
"v",
")",
"->",
"sb",
".",
"append",
"(",
"\"&\"",
")",
".",
"append",
"(",
"k",
")",
".",
"append",
"(",
"\"=\"",
")",
".",
"append",
"(",
"urlencode",
"(",
"String",
".",
"valueOf",
"(",
"v",
")",
",",
"charset",
")",
")",
")",
";",
"}",
"else",
"{",
"datas",
".",
"forEach",
"(",
"(",
"k",
",",
"v",
")",
"->",
"sb",
".",
"append",
"(",
"\"&\"",
")",
".",
"append",
"(",
"k",
")",
".",
"append",
"(",
"\"=\"",
")",
".",
"append",
"(",
"String",
".",
"valueOf",
"(",
"v",
")",
")",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
".",
"substring",
"(",
"1",
")",
";",
"}"
] | 获取form数据
@param useUrlencode 是否使用URLEncode对value进行编码,true表示使用URLEncode进行编码
@param charset 编码字符集
@return form数据 | [
"获取form数据"
] | train | https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/common/FormDataBuilder.java#L74-L83 |
beangle/beangle3 | commons/web/src/main/java/org/beangle/commons/web/util/CookieUtils.java | CookieUtils.getCookie | public static Cookie getCookie(HttpServletRequest request, String name) {
"""
Convenience method to get a cookie by name
@param request
the current request
@param name
the name of the cookie to find
@return the cookie (if found), null if not found
"""
Cookie[] cookies = request.getCookies();
Cookie returnCookie = null;
if (cookies == null) { return returnCookie; }
for (int i = 0; i < cookies.length; i++) {
Cookie thisCookie = cookies[i];
if (thisCookie.getName().equals(name) && !thisCookie.getValue().equals("")) {
returnCookie = thisCookie;
break;
}
}
return returnCookie;
} | java | public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
Cookie returnCookie = null;
if (cookies == null) { return returnCookie; }
for (int i = 0; i < cookies.length; i++) {
Cookie thisCookie = cookies[i];
if (thisCookie.getName().equals(name) && !thisCookie.getValue().equals("")) {
returnCookie = thisCookie;
break;
}
}
return returnCookie;
} | [
"public",
"static",
"Cookie",
"getCookie",
"(",
"HttpServletRequest",
"request",
",",
"String",
"name",
")",
"{",
"Cookie",
"[",
"]",
"cookies",
"=",
"request",
".",
"getCookies",
"(",
")",
";",
"Cookie",
"returnCookie",
"=",
"null",
";",
"if",
"(",
"cookies",
"==",
"null",
")",
"{",
"return",
"returnCookie",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"cookies",
".",
"length",
";",
"i",
"++",
")",
"{",
"Cookie",
"thisCookie",
"=",
"cookies",
"[",
"i",
"]",
";",
"if",
"(",
"thisCookie",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"name",
")",
"&&",
"!",
"thisCookie",
".",
"getValue",
"(",
")",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"returnCookie",
"=",
"thisCookie",
";",
"break",
";",
"}",
"}",
"return",
"returnCookie",
";",
"}"
] | Convenience method to get a cookie by name
@param request
the current request
@param name
the name of the cookie to find
@return the cookie (if found), null if not found | [
"Convenience",
"method",
"to",
"get",
"a",
"cookie",
"by",
"name"
] | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/web/src/main/java/org/beangle/commons/web/util/CookieUtils.java#L83-L96 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/Util.java | Util.pwr2LawNext | public static final int pwr2LawNext(final int ppo, final int curPoint) {
"""
Computes the next larger integer point in the power series
<i>point = 2<sup>( i / ppo )</sup></i> given the current point in the series.
For illustration, this can be used in a loop as follows:
<pre>{@code
int maxP = 1024;
int minP = 1;
int ppo = 2;
for (int p = minP; p <= maxP; p = pwr2LawNext(ppo, p)) {
System.out.print(p + " ");
}
//generates the following series:
//1 2 3 4 6 8 11 16 23 32 45 64 91 128 181 256 362 512 724 1024
}</pre>
@param ppo Points-Per-Octave, or the number of points per integer powers of 2 in the series.
@param curPoint the current point of the series. Must be ≥ 1.
@return the next point in the power series.
"""
final int cur = (curPoint < 1) ? 1 : curPoint;
int gi = (int)round(log2(cur) * ppo); //current generating index
int next;
do {
next = (int)round(pow(2.0, (double) ++gi / ppo));
} while ( next <= curPoint);
return next;
} | java | public static final int pwr2LawNext(final int ppo, final int curPoint) {
final int cur = (curPoint < 1) ? 1 : curPoint;
int gi = (int)round(log2(cur) * ppo); //current generating index
int next;
do {
next = (int)round(pow(2.0, (double) ++gi / ppo));
} while ( next <= curPoint);
return next;
} | [
"public",
"static",
"final",
"int",
"pwr2LawNext",
"(",
"final",
"int",
"ppo",
",",
"final",
"int",
"curPoint",
")",
"{",
"final",
"int",
"cur",
"=",
"(",
"curPoint",
"<",
"1",
")",
"?",
"1",
":",
"curPoint",
";",
"int",
"gi",
"=",
"(",
"int",
")",
"round",
"(",
"log2",
"(",
"cur",
")",
"*",
"ppo",
")",
";",
"//current generating index",
"int",
"next",
";",
"do",
"{",
"next",
"=",
"(",
"int",
")",
"round",
"(",
"pow",
"(",
"2.0",
",",
"(",
"double",
")",
"++",
"gi",
"/",
"ppo",
")",
")",
";",
"}",
"while",
"(",
"next",
"<=",
"curPoint",
")",
";",
"return",
"next",
";",
"}"
] | Computes the next larger integer point in the power series
<i>point = 2<sup>( i / ppo )</sup></i> given the current point in the series.
For illustration, this can be used in a loop as follows:
<pre>{@code
int maxP = 1024;
int minP = 1;
int ppo = 2;
for (int p = minP; p <= maxP; p = pwr2LawNext(ppo, p)) {
System.out.print(p + " ");
}
//generates the following series:
//1 2 3 4 6 8 11 16 23 32 45 64 91 128 181 256 362 512 724 1024
}</pre>
@param ppo Points-Per-Octave, or the number of points per integer powers of 2 in the series.
@param curPoint the current point of the series. Must be ≥ 1.
@return the next point in the power series. | [
"Computes",
"the",
"next",
"larger",
"integer",
"point",
"in",
"the",
"power",
"series",
"<i",
">",
"point",
"=",
"2<sup",
">",
"(",
"i",
"/",
"ppo",
")",
"<",
"/",
"sup",
">",
"<",
"/",
"i",
">",
"given",
"the",
"current",
"point",
"in",
"the",
"series",
".",
"For",
"illustration",
"this",
"can",
"be",
"used",
"in",
"a",
"loop",
"as",
"follows",
":"
] | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/Util.java#L486-L494 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/StatementDMQL.java | StatementDMQL.isGroupByColumn | static boolean isGroupByColumn(QuerySpecification select, int index) {
"""
Returns true if the specified exprColumn index is in the list of column indices specified by groupIndex
@return true/false
"""
if (!select.isGrouped) {
return false;
}
for (int ii = 0; ii < select.groupIndex.getColumnCount(); ii++) {
if (index == select.groupIndex.getColumns()[ii]) {
return true;
}
}
return false;
} | java | static boolean isGroupByColumn(QuerySpecification select, int index) {
if (!select.isGrouped) {
return false;
}
for (int ii = 0; ii < select.groupIndex.getColumnCount(); ii++) {
if (index == select.groupIndex.getColumns()[ii]) {
return true;
}
}
return false;
} | [
"static",
"boolean",
"isGroupByColumn",
"(",
"QuerySpecification",
"select",
",",
"int",
"index",
")",
"{",
"if",
"(",
"!",
"select",
".",
"isGrouped",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"int",
"ii",
"=",
"0",
";",
"ii",
"<",
"select",
".",
"groupIndex",
".",
"getColumnCount",
"(",
")",
";",
"ii",
"++",
")",
"{",
"if",
"(",
"index",
"==",
"select",
".",
"groupIndex",
".",
"getColumns",
"(",
")",
"[",
"ii",
"]",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Returns true if the specified exprColumn index is in the list of column indices specified by groupIndex
@return true/false | [
"Returns",
"true",
"if",
"the",
"specified",
"exprColumn",
"index",
"is",
"in",
"the",
"list",
"of",
"column",
"indices",
"specified",
"by",
"groupIndex"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/StatementDMQL.java#L854-L864 |
junit-team/junit4 | src/main/java/org/junit/runner/manipulation/Ordering.java | Ordering.definedBy | public static Ordering definedBy(
Class<? extends Ordering.Factory> factoryClass, Description annotatedTestClass)
throws InvalidOrderingException {
"""
Creates an {@link Ordering} from the given factory class. The class must have a public no-arg
constructor.
@param factoryClass class to use to create the ordering
@param annotatedTestClass test class that is annotated with {@link OrderWith}.
@throws InvalidOrderingException if the instance could not be created
"""
if (factoryClass == null) {
throw new NullPointerException("factoryClass cannot be null");
}
if (annotatedTestClass == null) {
throw new NullPointerException("annotatedTestClass cannot be null");
}
Ordering.Factory factory;
try {
Constructor<? extends Ordering.Factory> constructor = factoryClass.getConstructor();
factory = constructor.newInstance();
} catch (NoSuchMethodException e) {
throw new InvalidOrderingException(String.format(
CONSTRUCTOR_ERROR_FORMAT,
getClassName(factoryClass),
factoryClass.getSimpleName()));
} catch (Exception e) {
throw new InvalidOrderingException(
"Could not create ordering for " + annotatedTestClass, e);
}
return definedBy(factory, annotatedTestClass);
} | java | public static Ordering definedBy(
Class<? extends Ordering.Factory> factoryClass, Description annotatedTestClass)
throws InvalidOrderingException {
if (factoryClass == null) {
throw new NullPointerException("factoryClass cannot be null");
}
if (annotatedTestClass == null) {
throw new NullPointerException("annotatedTestClass cannot be null");
}
Ordering.Factory factory;
try {
Constructor<? extends Ordering.Factory> constructor = factoryClass.getConstructor();
factory = constructor.newInstance();
} catch (NoSuchMethodException e) {
throw new InvalidOrderingException(String.format(
CONSTRUCTOR_ERROR_FORMAT,
getClassName(factoryClass),
factoryClass.getSimpleName()));
} catch (Exception e) {
throw new InvalidOrderingException(
"Could not create ordering for " + annotatedTestClass, e);
}
return definedBy(factory, annotatedTestClass);
} | [
"public",
"static",
"Ordering",
"definedBy",
"(",
"Class",
"<",
"?",
"extends",
"Ordering",
".",
"Factory",
">",
"factoryClass",
",",
"Description",
"annotatedTestClass",
")",
"throws",
"InvalidOrderingException",
"{",
"if",
"(",
"factoryClass",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"factoryClass cannot be null\"",
")",
";",
"}",
"if",
"(",
"annotatedTestClass",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"annotatedTestClass cannot be null\"",
")",
";",
"}",
"Ordering",
".",
"Factory",
"factory",
";",
"try",
"{",
"Constructor",
"<",
"?",
"extends",
"Ordering",
".",
"Factory",
">",
"constructor",
"=",
"factoryClass",
".",
"getConstructor",
"(",
")",
";",
"factory",
"=",
"constructor",
".",
"newInstance",
"(",
")",
";",
"}",
"catch",
"(",
"NoSuchMethodException",
"e",
")",
"{",
"throw",
"new",
"InvalidOrderingException",
"(",
"String",
".",
"format",
"(",
"CONSTRUCTOR_ERROR_FORMAT",
",",
"getClassName",
"(",
"factoryClass",
")",
",",
"factoryClass",
".",
"getSimpleName",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"InvalidOrderingException",
"(",
"\"Could not create ordering for \"",
"+",
"annotatedTestClass",
",",
"e",
")",
";",
"}",
"return",
"definedBy",
"(",
"factory",
",",
"annotatedTestClass",
")",
";",
"}"
] | Creates an {@link Ordering} from the given factory class. The class must have a public no-arg
constructor.
@param factoryClass class to use to create the ordering
@param annotatedTestClass test class that is annotated with {@link OrderWith}.
@throws InvalidOrderingException if the instance could not be created | [
"Creates",
"an",
"{",
"@link",
"Ordering",
"}",
"from",
"the",
"given",
"factory",
"class",
".",
"The",
"class",
"must",
"have",
"a",
"public",
"no",
"-",
"arg",
"constructor",
"."
] | train | https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/runner/manipulation/Ordering.java#L55-L79 |
bazaarvoice/emodb | auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java | ApiKeyRealm.hasPermissionsById | public boolean hasPermissionsById(String id, String... permissions) {
"""
Test for whether an API key has specific permissions using its ID.
"""
List<Permission> resolvedPermissions = Lists.newArrayListWithCapacity(permissions.length);
for (String permission : permissions) {
resolvedPermissions.add(getPermissionResolver().resolvePermission(permission));
}
return hasPermissionsById(id, resolvedPermissions);
} | java | public boolean hasPermissionsById(String id, String... permissions) {
List<Permission> resolvedPermissions = Lists.newArrayListWithCapacity(permissions.length);
for (String permission : permissions) {
resolvedPermissions.add(getPermissionResolver().resolvePermission(permission));
}
return hasPermissionsById(id, resolvedPermissions);
} | [
"public",
"boolean",
"hasPermissionsById",
"(",
"String",
"id",
",",
"String",
"...",
"permissions",
")",
"{",
"List",
"<",
"Permission",
">",
"resolvedPermissions",
"=",
"Lists",
".",
"newArrayListWithCapacity",
"(",
"permissions",
".",
"length",
")",
";",
"for",
"(",
"String",
"permission",
":",
"permissions",
")",
"{",
"resolvedPermissions",
".",
"add",
"(",
"getPermissionResolver",
"(",
")",
".",
"resolvePermission",
"(",
"permission",
")",
")",
";",
"}",
"return",
"hasPermissionsById",
"(",
"id",
",",
"resolvedPermissions",
")",
";",
"}"
] | Test for whether an API key has specific permissions using its ID. | [
"Test",
"for",
"whether",
"an",
"API",
"key",
"has",
"specific",
"permissions",
"using",
"its",
"ID",
"."
] | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java#L447-L453 |
threerings/narya | core/src/main/java/com/threerings/presents/client/Client.java | Client.gotBootstrap | protected void gotBootstrap (BootstrapData data, DObjectManager omgr) {
"""
Called by the {@link ClientDObjectMgr} when our bootstrap notification arrives. If the
client and server are being run in "merged" mode in a single JVM, this is how the client is
configured with the server's distributed object manager and provided with bootstrap data.
"""
if (debugLogMessages()) {
log.info("Got bootstrap " + data + ".");
}
// keep these around for interested parties
_bstrap = data;
_omgr = omgr;
// extract bootstrap information
_connectionId = data.connectionId;
_cloid = data.clientOid;
// notify the communicator that we got our bootstrap data (if we have one)
if (_comm != null) {
_comm.gotBootstrap();
}
// initialize our invocation director
_invdir.init(omgr, _cloid, this);
// send a few pings to the server to establish the clock offset between this client and
// server standard time
establishClockDelta(System.currentTimeMillis());
// we can't quite call initialization completed at this point because we need for the
// invocation director to fully initialize (which requires a round trip to the server)
// before turning the client loose to do things like request invocation services
} | java | protected void gotBootstrap (BootstrapData data, DObjectManager omgr)
{
if (debugLogMessages()) {
log.info("Got bootstrap " + data + ".");
}
// keep these around for interested parties
_bstrap = data;
_omgr = omgr;
// extract bootstrap information
_connectionId = data.connectionId;
_cloid = data.clientOid;
// notify the communicator that we got our bootstrap data (if we have one)
if (_comm != null) {
_comm.gotBootstrap();
}
// initialize our invocation director
_invdir.init(omgr, _cloid, this);
// send a few pings to the server to establish the clock offset between this client and
// server standard time
establishClockDelta(System.currentTimeMillis());
// we can't quite call initialization completed at this point because we need for the
// invocation director to fully initialize (which requires a round trip to the server)
// before turning the client loose to do things like request invocation services
} | [
"protected",
"void",
"gotBootstrap",
"(",
"BootstrapData",
"data",
",",
"DObjectManager",
"omgr",
")",
"{",
"if",
"(",
"debugLogMessages",
"(",
")",
")",
"{",
"log",
".",
"info",
"(",
"\"Got bootstrap \"",
"+",
"data",
"+",
"\".\"",
")",
";",
"}",
"// keep these around for interested parties",
"_bstrap",
"=",
"data",
";",
"_omgr",
"=",
"omgr",
";",
"// extract bootstrap information",
"_connectionId",
"=",
"data",
".",
"connectionId",
";",
"_cloid",
"=",
"data",
".",
"clientOid",
";",
"// notify the communicator that we got our bootstrap data (if we have one)",
"if",
"(",
"_comm",
"!=",
"null",
")",
"{",
"_comm",
".",
"gotBootstrap",
"(",
")",
";",
"}",
"// initialize our invocation director",
"_invdir",
".",
"init",
"(",
"omgr",
",",
"_cloid",
",",
"this",
")",
";",
"// send a few pings to the server to establish the clock offset between this client and",
"// server standard time",
"establishClockDelta",
"(",
"System",
".",
"currentTimeMillis",
"(",
")",
")",
";",
"// we can't quite call initialization completed at this point because we need for the",
"// invocation director to fully initialize (which requires a round trip to the server)",
"// before turning the client loose to do things like request invocation services",
"}"
] | Called by the {@link ClientDObjectMgr} when our bootstrap notification arrives. If the
client and server are being run in "merged" mode in a single JVM, this is how the client is
configured with the server's distributed object manager and provided with bootstrap data. | [
"Called",
"by",
"the",
"{"
] | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/client/Client.java#L692-L721 |
BlueBrain/bluima | modules/bluima_pdf/src/main/java/ch/epfl/bbp/uima/pdf/grobid/diff_match_patch.java | diff_match_patch.diff_xIndex | public int diff_xIndex(LinkedList<Diff> diffs, int loc) {
"""
loc is a location in text1, compute and return the equivalent location in
text2. e.g. "The cat" vs "The big cat", 1->1, 5->8
@param diffs
LinkedList of Diff objects.
@param loc
Location within text1.
@return Location within text2.
"""
int chars1 = 0;
int chars2 = 0;
int last_chars1 = 0;
int last_chars2 = 0;
Diff lastDiff = null;
for (Diff aDiff : diffs) {
if (aDiff.operation != Operation.INSERT) {
// Equality or deletion.
chars1 += aDiff.text.length();
}
if (aDiff.operation != Operation.DELETE) {
// Equality or insertion.
chars2 += aDiff.text.length();
}
if (chars1 > loc) {
// Overshot the location.
lastDiff = aDiff;
break;
}
last_chars1 = chars1;
last_chars2 = chars2;
}
if (lastDiff != null && lastDiff.operation == Operation.DELETE) {
// The location was deleted.
return last_chars2;
}
// Add the remaining character length.
return last_chars2 + (loc - last_chars1);
} | java | public int diff_xIndex(LinkedList<Diff> diffs, int loc) {
int chars1 = 0;
int chars2 = 0;
int last_chars1 = 0;
int last_chars2 = 0;
Diff lastDiff = null;
for (Diff aDiff : diffs) {
if (aDiff.operation != Operation.INSERT) {
// Equality or deletion.
chars1 += aDiff.text.length();
}
if (aDiff.operation != Operation.DELETE) {
// Equality or insertion.
chars2 += aDiff.text.length();
}
if (chars1 > loc) {
// Overshot the location.
lastDiff = aDiff;
break;
}
last_chars1 = chars1;
last_chars2 = chars2;
}
if (lastDiff != null && lastDiff.operation == Operation.DELETE) {
// The location was deleted.
return last_chars2;
}
// Add the remaining character length.
return last_chars2 + (loc - last_chars1);
} | [
"public",
"int",
"diff_xIndex",
"(",
"LinkedList",
"<",
"Diff",
">",
"diffs",
",",
"int",
"loc",
")",
"{",
"int",
"chars1",
"=",
"0",
";",
"int",
"chars2",
"=",
"0",
";",
"int",
"last_chars1",
"=",
"0",
";",
"int",
"last_chars2",
"=",
"0",
";",
"Diff",
"lastDiff",
"=",
"null",
";",
"for",
"(",
"Diff",
"aDiff",
":",
"diffs",
")",
"{",
"if",
"(",
"aDiff",
".",
"operation",
"!=",
"Operation",
".",
"INSERT",
")",
"{",
"// Equality or deletion.",
"chars1",
"+=",
"aDiff",
".",
"text",
".",
"length",
"(",
")",
";",
"}",
"if",
"(",
"aDiff",
".",
"operation",
"!=",
"Operation",
".",
"DELETE",
")",
"{",
"// Equality or insertion.",
"chars2",
"+=",
"aDiff",
".",
"text",
".",
"length",
"(",
")",
";",
"}",
"if",
"(",
"chars1",
">",
"loc",
")",
"{",
"// Overshot the location.",
"lastDiff",
"=",
"aDiff",
";",
"break",
";",
"}",
"last_chars1",
"=",
"chars1",
";",
"last_chars2",
"=",
"chars2",
";",
"}",
"if",
"(",
"lastDiff",
"!=",
"null",
"&&",
"lastDiff",
".",
"operation",
"==",
"Operation",
".",
"DELETE",
")",
"{",
"// The location was deleted.",
"return",
"last_chars2",
";",
"}",
"// Add the remaining character length.",
"return",
"last_chars2",
"+",
"(",
"loc",
"-",
"last_chars1",
")",
";",
"}"
] | loc is a location in text1, compute and return the equivalent location in
text2. e.g. "The cat" vs "The big cat", 1->1, 5->8
@param diffs
LinkedList of Diff objects.
@param loc
Location within text1.
@return Location within text2. | [
"loc",
"is",
"a",
"location",
"in",
"text1",
"compute",
"and",
"return",
"the",
"equivalent",
"location",
"in",
"text2",
".",
"e",
".",
"g",
".",
"The",
"cat",
"vs",
"The",
"big",
"cat",
"1",
"-",
">",
"1",
"5",
"-",
">",
"8"
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_pdf/src/main/java/ch/epfl/bbp/uima/pdf/grobid/diff_match_patch.java#L1415-L1444 |
jhg023/SimpleNet | src/main/java/simplenet/packet/Packet.java | Packet.putFloat | public Packet putFloat(float f, ByteOrder order) {
"""
Writes a single {@code float} with the specified {@link ByteOrder} to this {@link Packet}'s payload.
@param f A {@code float}.
@param order The internal byte order of the {@code float}.
@return The {@link Packet} to allow for chained writes.
@see #putInt(int, ByteOrder)
"""
return putInt(Float.floatToRawIntBits(f), order);
} | java | public Packet putFloat(float f, ByteOrder order) {
return putInt(Float.floatToRawIntBits(f), order);
} | [
"public",
"Packet",
"putFloat",
"(",
"float",
"f",
",",
"ByteOrder",
"order",
")",
"{",
"return",
"putInt",
"(",
"Float",
".",
"floatToRawIntBits",
"(",
"f",
")",
",",
"order",
")",
";",
"}"
] | Writes a single {@code float} with the specified {@link ByteOrder} to this {@link Packet}'s payload.
@param f A {@code float}.
@param order The internal byte order of the {@code float}.
@return The {@link Packet} to allow for chained writes.
@see #putInt(int, ByteOrder) | [
"Writes",
"a",
"single",
"{",
"@code",
"float",
"}",
"with",
"the",
"specified",
"{",
"@link",
"ByteOrder",
"}",
"to",
"this",
"{",
"@link",
"Packet",
"}",
"s",
"payload",
"."
] | train | https://github.com/jhg023/SimpleNet/blob/a5b55cbfe1768c6a28874f12adac3c748f2b509a/src/main/java/simplenet/packet/Packet.java#L208-L210 |
graknlabs/grakn | server/src/server/deduplicator/AttributeDeduplicatorDaemon.java | AttributeDeduplicatorDaemon.markForDeduplication | public void markForDeduplication(KeyspaceImpl keyspace, String index, ConceptId conceptId) {
"""
Marks an attribute for deduplication. The attribute will be inserted to an internal queue to be processed by the de-duplicator daemon in real-time.
The attribute must have been inserted to the database, prior to calling this method.
@param keyspace keyspace of the attribute
@param index the value of the attribute
@param conceptId the concept id of the attribute
"""
Attribute attribute = Attribute.create(keyspace, index, conceptId);
LOG.trace("insert({})", attribute);
queue.insert(attribute);
} | java | public void markForDeduplication(KeyspaceImpl keyspace, String index, ConceptId conceptId) {
Attribute attribute = Attribute.create(keyspace, index, conceptId);
LOG.trace("insert({})", attribute);
queue.insert(attribute);
} | [
"public",
"void",
"markForDeduplication",
"(",
"KeyspaceImpl",
"keyspace",
",",
"String",
"index",
",",
"ConceptId",
"conceptId",
")",
"{",
"Attribute",
"attribute",
"=",
"Attribute",
".",
"create",
"(",
"keyspace",
",",
"index",
",",
"conceptId",
")",
";",
"LOG",
".",
"trace",
"(",
"\"insert({})\"",
",",
"attribute",
")",
";",
"queue",
".",
"insert",
"(",
"attribute",
")",
";",
"}"
] | Marks an attribute for deduplication. The attribute will be inserted to an internal queue to be processed by the de-duplicator daemon in real-time.
The attribute must have been inserted to the database, prior to calling this method.
@param keyspace keyspace of the attribute
@param index the value of the attribute
@param conceptId the concept id of the attribute | [
"Marks",
"an",
"attribute",
"for",
"deduplication",
".",
"The",
"attribute",
"will",
"be",
"inserted",
"to",
"an",
"internal",
"queue",
"to",
"be",
"processed",
"by",
"the",
"de",
"-",
"duplicator",
"daemon",
"in",
"real",
"-",
"time",
".",
"The",
"attribute",
"must",
"have",
"been",
"inserted",
"to",
"the",
"database",
"prior",
"to",
"calling",
"this",
"method",
"."
] | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/deduplicator/AttributeDeduplicatorDaemon.java#L83-L87 |
guardtime/ksi-java-sdk | ksi-common/src/main/java/com/guardtime/ksi/util/Base32.java | Base32.encodeWithDashes | public static String encodeWithDashes(byte[] in) {
"""
Encodes the given bytes into a base-32 string, inserting dashes after
every 6 characters of output.
@param in
the bytes to encode.
@return The formatted base-32 string, or null if {@code in} is null.
"""
if (in == null) {
return null;
}
return encodeWithDashes(in, 0, in.length);
} | java | public static String encodeWithDashes(byte[] in) {
if (in == null) {
return null;
}
return encodeWithDashes(in, 0, in.length);
} | [
"public",
"static",
"String",
"encodeWithDashes",
"(",
"byte",
"[",
"]",
"in",
")",
"{",
"if",
"(",
"in",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"encodeWithDashes",
"(",
"in",
",",
"0",
",",
"in",
".",
"length",
")",
";",
"}"
] | Encodes the given bytes into a base-32 string, inserting dashes after
every 6 characters of output.
@param in
the bytes to encode.
@return The formatted base-32 string, or null if {@code in} is null. | [
"Encodes",
"the",
"given",
"bytes",
"into",
"a",
"base",
"-",
"32",
"string",
"inserting",
"dashes",
"after",
"every",
"6",
"characters",
"of",
"output",
"."
] | train | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-common/src/main/java/com/guardtime/ksi/util/Base32.java#L75-L80 |
milaboratory/milib | src/main/java/com/milaboratory/core/sequence/quality/QualityTrimmer.java | QualityTrimmer.extendRange | public static Range extendRange(SequenceQuality quality, QualityTrimmerParameters parameters, Range initialRange) {
"""
Extend initialRange to the biggest possible range that fulfils the criteria of QualityTrimmer along the whole extended region.
The criteria may not be fulfilled for the initial range.
@param quality quality values
@param parameters trimming parameters
@param initialRange initial range to extend
@return
"""
int lower = pabs(trim(quality, 0, initialRange.getLower(), -1, false, parameters));
int upper = pabs(trim(quality, initialRange.getUpper(), quality.size(), +1, false, parameters)) + 1;
return new Range(lower, upper, initialRange.isReverse());
} | java | public static Range extendRange(SequenceQuality quality, QualityTrimmerParameters parameters, Range initialRange) {
int lower = pabs(trim(quality, 0, initialRange.getLower(), -1, false, parameters));
int upper = pabs(trim(quality, initialRange.getUpper(), quality.size(), +1, false, parameters)) + 1;
return new Range(lower, upper, initialRange.isReverse());
} | [
"public",
"static",
"Range",
"extendRange",
"(",
"SequenceQuality",
"quality",
",",
"QualityTrimmerParameters",
"parameters",
",",
"Range",
"initialRange",
")",
"{",
"int",
"lower",
"=",
"pabs",
"(",
"trim",
"(",
"quality",
",",
"0",
",",
"initialRange",
".",
"getLower",
"(",
")",
",",
"-",
"1",
",",
"false",
",",
"parameters",
")",
")",
";",
"int",
"upper",
"=",
"pabs",
"(",
"trim",
"(",
"quality",
",",
"initialRange",
".",
"getUpper",
"(",
")",
",",
"quality",
".",
"size",
"(",
")",
",",
"+",
"1",
",",
"false",
",",
"parameters",
")",
")",
"+",
"1",
";",
"return",
"new",
"Range",
"(",
"lower",
",",
"upper",
",",
"initialRange",
".",
"isReverse",
"(",
")",
")",
";",
"}"
] | Extend initialRange to the biggest possible range that fulfils the criteria of QualityTrimmer along the whole extended region.
The criteria may not be fulfilled for the initial range.
@param quality quality values
@param parameters trimming parameters
@param initialRange initial range to extend
@return | [
"Extend",
"initialRange",
"to",
"the",
"biggest",
"possible",
"range",
"that",
"fulfils",
"the",
"criteria",
"of",
"QualityTrimmer",
"along",
"the",
"whole",
"extended",
"region",
"."
] | train | https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/quality/QualityTrimmer.java#L158-L162 |
VoltDB/voltdb | src/frontend/org/voltcore/agreement/MeshArbiter.java | MeshArbiter.reconfigureOnFault | Map<Long, Long> reconfigureOnFault(Set<Long> hsIds, FaultMessage fm) {
"""
Convenience wrapper for tests that don't care about unknown sites
"""
return reconfigureOnFault(hsIds, fm, new HashSet<Long>());
} | java | Map<Long, Long> reconfigureOnFault(Set<Long> hsIds, FaultMessage fm) {
return reconfigureOnFault(hsIds, fm, new HashSet<Long>());
} | [
"Map",
"<",
"Long",
",",
"Long",
">",
"reconfigureOnFault",
"(",
"Set",
"<",
"Long",
">",
"hsIds",
",",
"FaultMessage",
"fm",
")",
"{",
"return",
"reconfigureOnFault",
"(",
"hsIds",
",",
"fm",
",",
"new",
"HashSet",
"<",
"Long",
">",
"(",
")",
")",
";",
"}"
] | Convenience wrapper for tests that don't care about unknown sites | [
"Convenience",
"wrapper",
"for",
"tests",
"that",
"don",
"t",
"care",
"about",
"unknown",
"sites"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltcore/agreement/MeshArbiter.java#L259-L261 |
loldevs/riotapi | rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java | ThrottledApiHandler.getTeams | public Future<Map<String, RankedTeam>> getTeams(String... teamIds) {
"""
Retrieve information for the specified ranked teams
@param teamIds The ids of the teams
@return A map, mapping team ids to team information
@see <a href=https://developer.riotgames.com/api/methods#!/594/1866>Official API documentation</a>
"""
return new ApiFuture<>(() -> handler.getTeams(teamIds));
} | java | public Future<Map<String, RankedTeam>> getTeams(String... teamIds) {
return new ApiFuture<>(() -> handler.getTeams(teamIds));
} | [
"public",
"Future",
"<",
"Map",
"<",
"String",
",",
"RankedTeam",
">",
">",
"getTeams",
"(",
"String",
"...",
"teamIds",
")",
"{",
"return",
"new",
"ApiFuture",
"<>",
"(",
"(",
")",
"->",
"handler",
".",
"getTeams",
"(",
"teamIds",
")",
")",
";",
"}"
] | Retrieve information for the specified ranked teams
@param teamIds The ids of the teams
@return A map, mapping team ids to team information
@see <a href=https://developer.riotgames.com/api/methods#!/594/1866>Official API documentation</a> | [
"Retrieve",
"information",
"for",
"the",
"specified",
"ranked",
"teams"
] | train | https://github.com/loldevs/riotapi/blob/0b8aac407aa5289845f249024f9732332855544f/rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java#L1225-L1227 |
j256/simplejmx | src/main/java/com/j256/simplejmx/client/JmxClient.java | JmxClient.invokeOperation | public Object invokeOperation(ObjectName name, String operName, String... paramStrings) throws Exception {
"""
Invoke a JMX method as an array of parameter strings.
@return The value returned by the method or null if none.
"""
String[] paramTypes = lookupParamTypes(name, operName, paramStrings);
Object[] paramObjs;
if (paramStrings.length == 0) {
paramObjs = null;
} else {
paramObjs = new Object[paramStrings.length];
for (int i = 0; i < paramStrings.length; i++) {
paramObjs[i] = ClientUtils.stringToParam(paramStrings[i], paramTypes[i]);
}
}
return invokeOperation(name, operName, paramTypes, paramObjs);
} | java | public Object invokeOperation(ObjectName name, String operName, String... paramStrings) throws Exception {
String[] paramTypes = lookupParamTypes(name, operName, paramStrings);
Object[] paramObjs;
if (paramStrings.length == 0) {
paramObjs = null;
} else {
paramObjs = new Object[paramStrings.length];
for (int i = 0; i < paramStrings.length; i++) {
paramObjs[i] = ClientUtils.stringToParam(paramStrings[i], paramTypes[i]);
}
}
return invokeOperation(name, operName, paramTypes, paramObjs);
} | [
"public",
"Object",
"invokeOperation",
"(",
"ObjectName",
"name",
",",
"String",
"operName",
",",
"String",
"...",
"paramStrings",
")",
"throws",
"Exception",
"{",
"String",
"[",
"]",
"paramTypes",
"=",
"lookupParamTypes",
"(",
"name",
",",
"operName",
",",
"paramStrings",
")",
";",
"Object",
"[",
"]",
"paramObjs",
";",
"if",
"(",
"paramStrings",
".",
"length",
"==",
"0",
")",
"{",
"paramObjs",
"=",
"null",
";",
"}",
"else",
"{",
"paramObjs",
"=",
"new",
"Object",
"[",
"paramStrings",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"paramStrings",
".",
"length",
";",
"i",
"++",
")",
"{",
"paramObjs",
"[",
"i",
"]",
"=",
"ClientUtils",
".",
"stringToParam",
"(",
"paramStrings",
"[",
"i",
"]",
",",
"paramTypes",
"[",
"i",
"]",
")",
";",
"}",
"}",
"return",
"invokeOperation",
"(",
"name",
",",
"operName",
",",
"paramTypes",
",",
"paramObjs",
")",
";",
"}"
] | Invoke a JMX method as an array of parameter strings.
@return The value returned by the method or null if none. | [
"Invoke",
"a",
"JMX",
"method",
"as",
"an",
"array",
"of",
"parameter",
"strings",
"."
] | train | https://github.com/j256/simplejmx/blob/1a04f52512dfa0a711ba0cc7023c604dbc82a352/src/main/java/com/j256/simplejmx/client/JmxClient.java#L421-L433 |
VoltDB/voltdb | src/frontend/org/voltcore/messaging/HostMessenger.java | HostMessenger.sendPoisonPill | public void sendPoisonPill(Collection<Integer> hostIds, String err, int cause) {
"""
/*
Foreign hosts that share the same host id belong to the same machine, one
poison pill is deadly enough
"""
for (int hostId : hostIds) {
Iterator<ForeignHost> it = m_foreignHosts.get(hostId).iterator();
// No need to overdose the poison pill
if (it.hasNext()) {
ForeignHost fh = it.next();
if (fh.isUp()) {
fh.sendPoisonPill(err, cause);
}
}
}
} | java | public void sendPoisonPill(Collection<Integer> hostIds, String err, int cause) {
for (int hostId : hostIds) {
Iterator<ForeignHost> it = m_foreignHosts.get(hostId).iterator();
// No need to overdose the poison pill
if (it.hasNext()) {
ForeignHost fh = it.next();
if (fh.isUp()) {
fh.sendPoisonPill(err, cause);
}
}
}
} | [
"public",
"void",
"sendPoisonPill",
"(",
"Collection",
"<",
"Integer",
">",
"hostIds",
",",
"String",
"err",
",",
"int",
"cause",
")",
"{",
"for",
"(",
"int",
"hostId",
":",
"hostIds",
")",
"{",
"Iterator",
"<",
"ForeignHost",
">",
"it",
"=",
"m_foreignHosts",
".",
"get",
"(",
"hostId",
")",
".",
"iterator",
"(",
")",
";",
"// No need to overdose the poison pill",
"if",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{",
"ForeignHost",
"fh",
"=",
"it",
".",
"next",
"(",
")",
";",
"if",
"(",
"fh",
".",
"isUp",
"(",
")",
")",
"{",
"fh",
".",
"sendPoisonPill",
"(",
"err",
",",
"cause",
")",
";",
"}",
"}",
"}",
"}"
] | /*
Foreign hosts that share the same host id belong to the same machine, one
poison pill is deadly enough | [
"/",
"*",
"Foreign",
"hosts",
"that",
"share",
"the",
"same",
"host",
"id",
"belong",
"to",
"the",
"same",
"machine",
"one",
"poison",
"pill",
"is",
"deadly",
"enough"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltcore/messaging/HostMessenger.java#L1774-L1785 |
Jasig/uPortal | uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/PortletsRESTController.java | PortletsRESTController.getPortlet | @RequestMapping(value = "/portlet/ {
"""
Provides information about a single portlet in the registry. NOTE: Access to this API enpoint
requires only <code>IPermission.PORTAL_SUBSCRIBE</code> permission.
"""fname}.json", method = RequestMethod.GET)
public ModelAndView getPortlet(
HttpServletRequest request, HttpServletResponse response, @PathVariable String fname)
throws Exception {
IAuthorizationPrincipal ap = getAuthorizationPrincipal(request);
IPortletDefinition portletDef =
portletDefinitionRegistry.getPortletDefinitionByFname(fname);
if (portletDef != null && ap.canRender(portletDef.getPortletDefinitionId().getStringId())) {
LayoutPortlet portlet = new LayoutPortlet(portletDef);
return new ModelAndView("json", "portlet", portlet);
} else {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return new ModelAndView("json");
}
} | java | @RequestMapping(value = "/portlet/{fname}.json", method = RequestMethod.GET)
public ModelAndView getPortlet(
HttpServletRequest request, HttpServletResponse response, @PathVariable String fname)
throws Exception {
IAuthorizationPrincipal ap = getAuthorizationPrincipal(request);
IPortletDefinition portletDef =
portletDefinitionRegistry.getPortletDefinitionByFname(fname);
if (portletDef != null && ap.canRender(portletDef.getPortletDefinitionId().getStringId())) {
LayoutPortlet portlet = new LayoutPortlet(portletDef);
return new ModelAndView("json", "portlet", portlet);
} else {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return new ModelAndView("json");
}
} | [
"@",
"RequestMapping",
"(",
"value",
"=",
"\"/portlet/{fname}.json\"",
",",
"method",
"=",
"RequestMethod",
".",
"GET",
")",
"public",
"ModelAndView",
"getPortlet",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"@",
"PathVariable",
"String",
"fname",
")",
"throws",
"Exception",
"{",
"IAuthorizationPrincipal",
"ap",
"=",
"getAuthorizationPrincipal",
"(",
"request",
")",
";",
"IPortletDefinition",
"portletDef",
"=",
"portletDefinitionRegistry",
".",
"getPortletDefinitionByFname",
"(",
"fname",
")",
";",
"if",
"(",
"portletDef",
"!=",
"null",
"&&",
"ap",
".",
"canRender",
"(",
"portletDef",
".",
"getPortletDefinitionId",
"(",
")",
".",
"getStringId",
"(",
")",
")",
")",
"{",
"LayoutPortlet",
"portlet",
"=",
"new",
"LayoutPortlet",
"(",
"portletDef",
")",
";",
"return",
"new",
"ModelAndView",
"(",
"\"json\"",
",",
"\"portlet\"",
",",
"portlet",
")",
";",
"}",
"else",
"{",
"response",
".",
"setStatus",
"(",
"HttpServletResponse",
".",
"SC_FORBIDDEN",
")",
";",
"return",
"new",
"ModelAndView",
"(",
"\"json\"",
")",
";",
"}",
"}"
] | Provides information about a single portlet in the registry. NOTE: Access to this API enpoint
requires only <code>IPermission.PORTAL_SUBSCRIBE</code> permission. | [
"Provides",
"information",
"about",
"a",
"single",
"portlet",
"in",
"the",
"registry",
".",
"NOTE",
":",
"Access",
"to",
"this",
"API",
"enpoint",
"requires",
"only",
"<code",
">",
"IPermission",
".",
"PORTAL_SUBSCRIBE<",
"/",
"code",
">",
"permission",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/PortletsRESTController.java#L98-L112 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java | ApiOvhDedicatedCloud.serviceName_datacenter_datacenterId_host_hostId_GET | public OvhHost serviceName_datacenter_datacenterId_host_hostId_GET(String serviceName, Long datacenterId, Long hostId) throws IOException {
"""
Get this object properties
REST: GET /dedicatedCloud/{serviceName}/datacenter/{datacenterId}/host/{hostId}
@param serviceName [required] Domain of the service
@param datacenterId [required]
@param hostId [required] Id of the host
"""
String qPath = "/dedicatedCloud/{serviceName}/datacenter/{datacenterId}/host/{hostId}";
StringBuilder sb = path(qPath, serviceName, datacenterId, hostId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhHost.class);
} | java | public OvhHost serviceName_datacenter_datacenterId_host_hostId_GET(String serviceName, Long datacenterId, Long hostId) throws IOException {
String qPath = "/dedicatedCloud/{serviceName}/datacenter/{datacenterId}/host/{hostId}";
StringBuilder sb = path(qPath, serviceName, datacenterId, hostId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhHost.class);
} | [
"public",
"OvhHost",
"serviceName_datacenter_datacenterId_host_hostId_GET",
"(",
"String",
"serviceName",
",",
"Long",
"datacenterId",
",",
"Long",
"hostId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicatedCloud/{serviceName}/datacenter/{datacenterId}/host/{hostId}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"datacenterId",
",",
"hostId",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhHost",
".",
"class",
")",
";",
"}"
] | Get this object properties
REST: GET /dedicatedCloud/{serviceName}/datacenter/{datacenterId}/host/{hostId}
@param serviceName [required] Domain of the service
@param datacenterId [required]
@param hostId [required] Id of the host | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L1620-L1625 |
jferard/fastods | fastods/src/main/java/com/github/jferard/fastods/Table.java | Table.appendXMLToContentEntry | public void appendXMLToContentEntry(final XMLUtil util, final Appendable appendable)
throws IOException {
"""
Add XML to content.xml
@param util an util
@param appendable the output
@throws IOException if the XML could not be written
"""
this.appender.appendXMLToContentEntry(util, appendable);
} | java | public void appendXMLToContentEntry(final XMLUtil util, final Appendable appendable)
throws IOException {
this.appender.appendXMLToContentEntry(util, appendable);
} | [
"public",
"void",
"appendXMLToContentEntry",
"(",
"final",
"XMLUtil",
"util",
",",
"final",
"Appendable",
"appendable",
")",
"throws",
"IOException",
"{",
"this",
".",
"appender",
".",
"appendXMLToContentEntry",
"(",
"util",
",",
"appendable",
")",
";",
"}"
] | Add XML to content.xml
@param util an util
@param appendable the output
@throws IOException if the XML could not be written | [
"Add",
"XML",
"to",
"content",
".",
"xml"
] | train | https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/Table.java#L114-L117 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/query/dsl/clause/UpdateForClause.java | UpdateForClause.forWithin | public static UpdateForClause forWithin(String variable, String path) {
"""
Creates an updateFor clause that starts with <code>FOR variable WITHIN path</code>.
@param variable the first variable in the clause.
@param path the first path in the clause, a WITHIN path.
@return the clause, for chaining. See {@link #when(Expression)} and {@link #end()} to complete the clause.
"""
UpdateForClause clause = new UpdateForClause();
return clause.within(variable, path);
} | java | public static UpdateForClause forWithin(String variable, String path) {
UpdateForClause clause = new UpdateForClause();
return clause.within(variable, path);
} | [
"public",
"static",
"UpdateForClause",
"forWithin",
"(",
"String",
"variable",
",",
"String",
"path",
")",
"{",
"UpdateForClause",
"clause",
"=",
"new",
"UpdateForClause",
"(",
")",
";",
"return",
"clause",
".",
"within",
"(",
"variable",
",",
"path",
")",
";",
"}"
] | Creates an updateFor clause that starts with <code>FOR variable WITHIN path</code>.
@param variable the first variable in the clause.
@param path the first path in the clause, a WITHIN path.
@return the clause, for chaining. See {@link #when(Expression)} and {@link #end()} to complete the clause. | [
"Creates",
"an",
"updateFor",
"clause",
"that",
"starts",
"with",
"<code",
">",
"FOR",
"variable",
"WITHIN",
"path<",
"/",
"code",
">",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/clause/UpdateForClause.java#L59-L62 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/NFRule.java | NFRule.stripPrefix | private String stripPrefix(String text, String prefix, ParsePosition pp) {
"""
This function is used by parse() to match the text being parsed
against a possible prefix string. This function
matches characters from the beginning of the string being parsed
to characters from the prospective prefix. If they match, pp is
updated to the first character not matched, and the result is
the unparsed part of the string. If they don't match, the whole
string is returned, and pp is left unchanged.
@param text The string being parsed
@param prefix The text to match against
@param pp On entry, ignored and assumed to be 0. On exit, points
to the first unmatched character (assuming the whole prefix matched),
or is unchanged (if the whole prefix didn't match).
@return If things match, this is the unparsed part of "text";
if they didn't match, this is "text".
"""
// if the prefix text is empty, dump out without doing anything
if (prefix.length() == 0) {
return text;
} else {
// otherwise, use prefixLength() to match the beginning of
// "text" against "prefix". This function returns the
// number of characters from "text" that matched (or 0 if
// we didn't match the whole prefix)
int pfl = prefixLength(text, prefix);
if (pfl != 0) {
// if we got a successful match, update the parse position
// and strip the prefix off of "text"
pp.setIndex(pp.getIndex() + pfl);
return text.substring(pfl);
// if we didn't get a successful match, leave everything alone
} else {
return text;
}
}
} | java | private String stripPrefix(String text, String prefix, ParsePosition pp) {
// if the prefix text is empty, dump out without doing anything
if (prefix.length() == 0) {
return text;
} else {
// otherwise, use prefixLength() to match the beginning of
// "text" against "prefix". This function returns the
// number of characters from "text" that matched (or 0 if
// we didn't match the whole prefix)
int pfl = prefixLength(text, prefix);
if (pfl != 0) {
// if we got a successful match, update the parse position
// and strip the prefix off of "text"
pp.setIndex(pp.getIndex() + pfl);
return text.substring(pfl);
// if we didn't get a successful match, leave everything alone
} else {
return text;
}
}
} | [
"private",
"String",
"stripPrefix",
"(",
"String",
"text",
",",
"String",
"prefix",
",",
"ParsePosition",
"pp",
")",
"{",
"// if the prefix text is empty, dump out without doing anything",
"if",
"(",
"prefix",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
"text",
";",
"}",
"else",
"{",
"// otherwise, use prefixLength() to match the beginning of",
"// \"text\" against \"prefix\". This function returns the",
"// number of characters from \"text\" that matched (or 0 if",
"// we didn't match the whole prefix)",
"int",
"pfl",
"=",
"prefixLength",
"(",
"text",
",",
"prefix",
")",
";",
"if",
"(",
"pfl",
"!=",
"0",
")",
"{",
"// if we got a successful match, update the parse position",
"// and strip the prefix off of \"text\"",
"pp",
".",
"setIndex",
"(",
"pp",
".",
"getIndex",
"(",
")",
"+",
"pfl",
")",
";",
"return",
"text",
".",
"substring",
"(",
"pfl",
")",
";",
"// if we didn't get a successful match, leave everything alone",
"}",
"else",
"{",
"return",
"text",
";",
"}",
"}",
"}"
] | This function is used by parse() to match the text being parsed
against a possible prefix string. This function
matches characters from the beginning of the string being parsed
to characters from the prospective prefix. If they match, pp is
updated to the first character not matched, and the result is
the unparsed part of the string. If they don't match, the whole
string is returned, and pp is left unchanged.
@param text The string being parsed
@param prefix The text to match against
@param pp On entry, ignored and assumed to be 0. On exit, points
to the first unmatched character (assuming the whole prefix matched),
or is unchanged (if the whole prefix didn't match).
@return If things match, this is the unparsed part of "text";
if they didn't match, this is "text". | [
"This",
"function",
"is",
"used",
"by",
"parse",
"()",
"to",
"match",
"the",
"text",
"being",
"parsed",
"against",
"a",
"possible",
"prefix",
"string",
".",
"This",
"function",
"matches",
"characters",
"from",
"the",
"beginning",
"of",
"the",
"string",
"being",
"parsed",
"to",
"characters",
"from",
"the",
"prospective",
"prefix",
".",
"If",
"they",
"match",
"pp",
"is",
"updated",
"to",
"the",
"first",
"character",
"not",
"matched",
"and",
"the",
"result",
"is",
"the",
"unparsed",
"part",
"of",
"the",
"string",
".",
"If",
"they",
"don",
"t",
"match",
"the",
"whole",
"string",
"is",
"returned",
"and",
"pp",
"is",
"left",
"unchanged",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/NFRule.java#L1077-L1098 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/alert/ExtensionAlert.java | ExtensionAlert.showAlertAddDialog | public void showAlertAddDialog(HttpMessage httpMessage, int historyType) {
"""
Shows the Add Alert dialogue, using the given {@code HttpMessage} and history type for the {@code HistoryReference} that
will be created if the user creates the alert. The current session will be used to create the {@code HistoryReference}.
The alert created will be added to the newly created {@code HistoryReference}.
<p>
Should be used when the alert is added to a temporary {@code HistoryReference} as the temporary {@code HistoryReference}s
are deleted when the session is closed.
@param httpMessage the {@code HttpMessage} that will be used to create the {@code HistoryReference}, must not be
{@code null}.
@param historyType the type of the history reference that will be used to create the {@code HistoryReference}.
@since 2.7.0
@see Model#getSession()
@see HistoryReference#HistoryReference(org.parosproxy.paros.model.Session, int, HttpMessage)
"""
if (dialogAlertAdd == null || !dialogAlertAdd.isVisible()) {
dialogAlertAdd = new AlertAddDialog(getView().getMainFrame(), false);
dialogAlertAdd.setHttpMessage(httpMessage, historyType);
dialogAlertAdd.setVisible(true);
}
} | java | public void showAlertAddDialog(HttpMessage httpMessage, int historyType) {
if (dialogAlertAdd == null || !dialogAlertAdd.isVisible()) {
dialogAlertAdd = new AlertAddDialog(getView().getMainFrame(), false);
dialogAlertAdd.setHttpMessage(httpMessage, historyType);
dialogAlertAdd.setVisible(true);
}
} | [
"public",
"void",
"showAlertAddDialog",
"(",
"HttpMessage",
"httpMessage",
",",
"int",
"historyType",
")",
"{",
"if",
"(",
"dialogAlertAdd",
"==",
"null",
"||",
"!",
"dialogAlertAdd",
".",
"isVisible",
"(",
")",
")",
"{",
"dialogAlertAdd",
"=",
"new",
"AlertAddDialog",
"(",
"getView",
"(",
")",
".",
"getMainFrame",
"(",
")",
",",
"false",
")",
";",
"dialogAlertAdd",
".",
"setHttpMessage",
"(",
"httpMessage",
",",
"historyType",
")",
";",
"dialogAlertAdd",
".",
"setVisible",
"(",
"true",
")",
";",
"}",
"}"
] | Shows the Add Alert dialogue, using the given {@code HttpMessage} and history type for the {@code HistoryReference} that
will be created if the user creates the alert. The current session will be used to create the {@code HistoryReference}.
The alert created will be added to the newly created {@code HistoryReference}.
<p>
Should be used when the alert is added to a temporary {@code HistoryReference} as the temporary {@code HistoryReference}s
are deleted when the session is closed.
@param httpMessage the {@code HttpMessage} that will be used to create the {@code HistoryReference}, must not be
{@code null}.
@param historyType the type of the history reference that will be used to create the {@code HistoryReference}.
@since 2.7.0
@see Model#getSession()
@see HistoryReference#HistoryReference(org.parosproxy.paros.model.Session, int, HttpMessage) | [
"Shows",
"the",
"Add",
"Alert",
"dialogue",
"using",
"the",
"given",
"{",
"@code",
"HttpMessage",
"}",
"and",
"history",
"type",
"for",
"the",
"{",
"@code",
"HistoryReference",
"}",
"that",
"will",
"be",
"created",
"if",
"the",
"user",
"creates",
"the",
"alert",
".",
"The",
"current",
"session",
"will",
"be",
"used",
"to",
"create",
"the",
"{",
"@code",
"HistoryReference",
"}",
".",
"The",
"alert",
"created",
"will",
"be",
"added",
"to",
"the",
"newly",
"created",
"{",
"@code",
"HistoryReference",
"}",
".",
"<p",
">",
"Should",
"be",
"used",
"when",
"the",
"alert",
"is",
"added",
"to",
"a",
"temporary",
"{",
"@code",
"HistoryReference",
"}",
"as",
"the",
"temporary",
"{",
"@code",
"HistoryReference",
"}",
"s",
"are",
"deleted",
"when",
"the",
"session",
"is",
"closed",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/alert/ExtensionAlert.java#L981-L987 |
lettuce-io/lettuce-core | src/main/java/io/lettuce/core/dynamic/ReactiveTypes.java | ReactiveTypes.isAvailable | public static boolean isAvailable(ReactiveLibrary reactiveLibrary) {
"""
Returns {@literal true} if the {@link ReactiveLibrary} is available.
@param reactiveLibrary must not be {@literal null}.
@return {@literal true} if the {@link ReactiveLibrary} is available.
"""
LettuceAssert.notNull(reactiveLibrary, "ReactiveLibrary must not be null!");
switch (reactiveLibrary) {
case PROJECT_REACTOR:
return PROJECT_REACTOR_PRESENT;
case RXJAVA1:
return RXJAVA1_PRESENT;
case RXJAVA2:
return RXJAVA2_PRESENT;
}
throw new IllegalArgumentException(String.format("ReactiveLibrary %s not supported", reactiveLibrary));
} | java | public static boolean isAvailable(ReactiveLibrary reactiveLibrary) {
LettuceAssert.notNull(reactiveLibrary, "ReactiveLibrary must not be null!");
switch (reactiveLibrary) {
case PROJECT_REACTOR:
return PROJECT_REACTOR_PRESENT;
case RXJAVA1:
return RXJAVA1_PRESENT;
case RXJAVA2:
return RXJAVA2_PRESENT;
}
throw new IllegalArgumentException(String.format("ReactiveLibrary %s not supported", reactiveLibrary));
} | [
"public",
"static",
"boolean",
"isAvailable",
"(",
"ReactiveLibrary",
"reactiveLibrary",
")",
"{",
"LettuceAssert",
".",
"notNull",
"(",
"reactiveLibrary",
",",
"\"ReactiveLibrary must not be null!\"",
")",
";",
"switch",
"(",
"reactiveLibrary",
")",
"{",
"case",
"PROJECT_REACTOR",
":",
"return",
"PROJECT_REACTOR_PRESENT",
";",
"case",
"RXJAVA1",
":",
"return",
"RXJAVA1_PRESENT",
";",
"case",
"RXJAVA2",
":",
"return",
"RXJAVA2_PRESENT",
";",
"}",
"throw",
"new",
"IllegalArgumentException",
"(",
"String",
".",
"format",
"(",
"\"ReactiveLibrary %s not supported\"",
",",
"reactiveLibrary",
")",
")",
";",
"}"
] | Returns {@literal true} if the {@link ReactiveLibrary} is available.
@param reactiveLibrary must not be {@literal null}.
@return {@literal true} if the {@link ReactiveLibrary} is available. | [
"Returns",
"{",
"@literal",
"true",
"}",
"if",
"the",
"{",
"@link",
"ReactiveLibrary",
"}",
"is",
"available",
"."
] | train | https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/ReactiveTypes.java#L108-L122 |
dkpro/dkpro-jwpl | de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/revisions/RevisionUtils.java | RevisionUtils.getDiscussionRevisionForArticleRevision | public Revision getDiscussionRevisionForArticleRevision(int revisionId) throws WikiApiException, WikiPageNotFoundException {
"""
For a given article revision, the method returns the revision of the article discussion
page which was current at the time the revision was created.
@param revisionId revision of the article for which the talk page revision should be retrieved
@return the revision of the talk page that was current at the creation time of the given article revision
@throws WikiApiException if any error occurred accessing the Wiki db
@throws WikiPageNotFoundException if no discussion page was available at the time of the given article revision
"""
//get article revision
Revision rev = revApi.getRevision(revisionId);
Timestamp revTime = rev.getTimeStamp();
//get corresponding discussion page
Page discussion = wiki.getDiscussionPage(rev.getArticleID());
/*
* find correct revision of discussion page
*/
List<Timestamp> discussionTs = revApi.getRevisionTimestamps(discussion.getPageId());
// sort in reverse order - newest first
Collections.sort(discussionTs, new Comparator<Timestamp>()
{
public int compare(Timestamp ts1, Timestamp ts2)
{
return ts2.compareTo(ts1);
}
});
//find first timestamp equal to or before the article revision timestamp
for(Timestamp curDiscTime:discussionTs){
if(curDiscTime==revTime||curDiscTime.before(revTime)){
return revApi.getRevision(discussion.getPageId(), curDiscTime);
}
}
throw new WikiPageNotFoundException("Not discussion page was available at the time of the given article revision");
} | java | public Revision getDiscussionRevisionForArticleRevision(int revisionId) throws WikiApiException, WikiPageNotFoundException{
//get article revision
Revision rev = revApi.getRevision(revisionId);
Timestamp revTime = rev.getTimeStamp();
//get corresponding discussion page
Page discussion = wiki.getDiscussionPage(rev.getArticleID());
/*
* find correct revision of discussion page
*/
List<Timestamp> discussionTs = revApi.getRevisionTimestamps(discussion.getPageId());
// sort in reverse order - newest first
Collections.sort(discussionTs, new Comparator<Timestamp>()
{
public int compare(Timestamp ts1, Timestamp ts2)
{
return ts2.compareTo(ts1);
}
});
//find first timestamp equal to or before the article revision timestamp
for(Timestamp curDiscTime:discussionTs){
if(curDiscTime==revTime||curDiscTime.before(revTime)){
return revApi.getRevision(discussion.getPageId(), curDiscTime);
}
}
throw new WikiPageNotFoundException("Not discussion page was available at the time of the given article revision");
} | [
"public",
"Revision",
"getDiscussionRevisionForArticleRevision",
"(",
"int",
"revisionId",
")",
"throws",
"WikiApiException",
",",
"WikiPageNotFoundException",
"{",
"//get article revision\r",
"Revision",
"rev",
"=",
"revApi",
".",
"getRevision",
"(",
"revisionId",
")",
";",
"Timestamp",
"revTime",
"=",
"rev",
".",
"getTimeStamp",
"(",
")",
";",
"//get corresponding discussion page\r",
"Page",
"discussion",
"=",
"wiki",
".",
"getDiscussionPage",
"(",
"rev",
".",
"getArticleID",
"(",
")",
")",
";",
"/*\r\n\t\t * find correct revision of discussion page\r\n\t\t */",
"List",
"<",
"Timestamp",
">",
"discussionTs",
"=",
"revApi",
".",
"getRevisionTimestamps",
"(",
"discussion",
".",
"getPageId",
"(",
")",
")",
";",
"// sort in reverse order - newest first\r",
"Collections",
".",
"sort",
"(",
"discussionTs",
",",
"new",
"Comparator",
"<",
"Timestamp",
">",
"(",
")",
"{",
"public",
"int",
"compare",
"(",
"Timestamp",
"ts1",
",",
"Timestamp",
"ts2",
")",
"{",
"return",
"ts2",
".",
"compareTo",
"(",
"ts1",
")",
";",
"}",
"}",
")",
";",
"//find first timestamp equal to or before the article revision timestamp\r",
"for",
"(",
"Timestamp",
"curDiscTime",
":",
"discussionTs",
")",
"{",
"if",
"(",
"curDiscTime",
"==",
"revTime",
"||",
"curDiscTime",
".",
"before",
"(",
"revTime",
")",
")",
"{",
"return",
"revApi",
".",
"getRevision",
"(",
"discussion",
".",
"getPageId",
"(",
")",
",",
"curDiscTime",
")",
";",
"}",
"}",
"throw",
"new",
"WikiPageNotFoundException",
"(",
"\"Not discussion page was available at the time of the given article revision\"",
")",
";",
"}"
] | For a given article revision, the method returns the revision of the article discussion
page which was current at the time the revision was created.
@param revisionId revision of the article for which the talk page revision should be retrieved
@return the revision of the talk page that was current at the creation time of the given article revision
@throws WikiApiException if any error occurred accessing the Wiki db
@throws WikiPageNotFoundException if no discussion page was available at the time of the given article revision | [
"For",
"a",
"given",
"article",
"revision",
"the",
"method",
"returns",
"the",
"revision",
"of",
"the",
"article",
"discussion",
"page",
"which",
"was",
"current",
"at",
"the",
"time",
"the",
"revision",
"was",
"created",
"."
] | train | https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/revisions/RevisionUtils.java#L64-L94 |
jlinn/quartz-redis-jobstore | src/main/java/net/joelinn/quartz/jobstore/AbstractRedisStorage.java | AbstractRedisStorage.isBlockedJob | protected boolean isBlockedJob(String jobHashKey, T jedis) {
"""
Determine if the given job is blocked by an active instance
@param jobHashKey the job in question
@param jedis a thread-safe Redis connection
@return true if the given job is blocked by an active instance
"""
JobKey jobKey = redisSchema.jobKey(jobHashKey);
return jedis.sismember(redisSchema.blockedJobsSet(), jobHashKey) &&
isActiveInstance(jedis.get(redisSchema.jobBlockedKey(jobKey)), jedis);
} | java | protected boolean isBlockedJob(String jobHashKey, T jedis) {
JobKey jobKey = redisSchema.jobKey(jobHashKey);
return jedis.sismember(redisSchema.blockedJobsSet(), jobHashKey) &&
isActiveInstance(jedis.get(redisSchema.jobBlockedKey(jobKey)), jedis);
} | [
"protected",
"boolean",
"isBlockedJob",
"(",
"String",
"jobHashKey",
",",
"T",
"jedis",
")",
"{",
"JobKey",
"jobKey",
"=",
"redisSchema",
".",
"jobKey",
"(",
"jobHashKey",
")",
";",
"return",
"jedis",
".",
"sismember",
"(",
"redisSchema",
".",
"blockedJobsSet",
"(",
")",
",",
"jobHashKey",
")",
"&&",
"isActiveInstance",
"(",
"jedis",
".",
"get",
"(",
"redisSchema",
".",
"jobBlockedKey",
"(",
"jobKey",
")",
")",
",",
"jedis",
")",
";",
"}"
] | Determine if the given job is blocked by an active instance
@param jobHashKey the job in question
@param jedis a thread-safe Redis connection
@return true if the given job is blocked by an active instance | [
"Determine",
"if",
"the",
"given",
"job",
"is",
"blocked",
"by",
"an",
"active",
"instance"
] | train | https://github.com/jlinn/quartz-redis-jobstore/blob/be9a52ee776d8a09866fe99fd9718bc13a0cb992/src/main/java/net/joelinn/quartz/jobstore/AbstractRedisStorage.java#L768-L772 |
overturetool/overture | ide/ui/src/main/java/org/overture/ide/ui/navigator/VdmDropAdapterAssistent.java | VdmDropAdapterAssistent.mergeStatus | private void mergeStatus(MultiStatus status, IStatus toMerge) {
"""
Adds the given status to the list of problems. Discards OK statuses. If
the status is a multi-status, only its children are added.
"""
if (!toMerge.isOK()) {
status.merge(toMerge);
}
} | java | private void mergeStatus(MultiStatus status, IStatus toMerge) {
if (!toMerge.isOK()) {
status.merge(toMerge);
}
} | [
"private",
"void",
"mergeStatus",
"(",
"MultiStatus",
"status",
",",
"IStatus",
"toMerge",
")",
"{",
"if",
"(",
"!",
"toMerge",
".",
"isOK",
"(",
")",
")",
"{",
"status",
".",
"merge",
"(",
"toMerge",
")",
";",
"}",
"}"
] | Adds the given status to the list of problems. Discards OK statuses. If
the status is a multi-status, only its children are added. | [
"Adds",
"the",
"given",
"status",
"to",
"the",
"list",
"of",
"problems",
".",
"Discards",
"OK",
"statuses",
".",
"If",
"the",
"status",
"is",
"a",
"multi",
"-",
"status",
"only",
"its",
"children",
"are",
"added",
"."
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/ui/src/main/java/org/overture/ide/ui/navigator/VdmDropAdapterAssistent.java#L546-L550 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/HadoopUtils.java | HadoopUtils.getConfFromState | public static Configuration getConfFromState(State state, Optional<String> encryptedPath) {
"""
Provides Hadoop configuration given state.
It also supports decrypting values on "encryptedPath".
Note that this encryptedPath path will be removed from full path of each config key and leaving only child path on the key(s).
If there's same config path as child path, the one stripped will have higher priority.
e.g:
- encryptedPath: writer.fs.encrypted
before: writer.fs.encrypted.secret
after: secret
Common use case for these encryptedPath:
When there's have encrypted credential in job property but you'd like Filesystem to get decrypted value.
@param srcConfig source config.
@param encryptedPath Optional. If provided, config that is on this path will be decrypted. @see ConfigUtils.resolveEncrypted
Note that config on encryptedPath will be included in the end result even it's not part of includeOnlyPath
@return Hadoop Configuration.
"""
Config config = ConfigFactory.parseProperties(state.getProperties());
if (encryptedPath.isPresent()) {
config = ConfigUtils.resolveEncrypted(config, encryptedPath);
}
Configuration conf = newConfiguration();
for (Entry<String, ConfigValue> entry : config.entrySet()) {
conf.set(entry.getKey(), entry.getValue().unwrapped().toString());
}
return conf;
} | java | public static Configuration getConfFromState(State state, Optional<String> encryptedPath) {
Config config = ConfigFactory.parseProperties(state.getProperties());
if (encryptedPath.isPresent()) {
config = ConfigUtils.resolveEncrypted(config, encryptedPath);
}
Configuration conf = newConfiguration();
for (Entry<String, ConfigValue> entry : config.entrySet()) {
conf.set(entry.getKey(), entry.getValue().unwrapped().toString());
}
return conf;
} | [
"public",
"static",
"Configuration",
"getConfFromState",
"(",
"State",
"state",
",",
"Optional",
"<",
"String",
">",
"encryptedPath",
")",
"{",
"Config",
"config",
"=",
"ConfigFactory",
".",
"parseProperties",
"(",
"state",
".",
"getProperties",
"(",
")",
")",
";",
"if",
"(",
"encryptedPath",
".",
"isPresent",
"(",
")",
")",
"{",
"config",
"=",
"ConfigUtils",
".",
"resolveEncrypted",
"(",
"config",
",",
"encryptedPath",
")",
";",
"}",
"Configuration",
"conf",
"=",
"newConfiguration",
"(",
")",
";",
"for",
"(",
"Entry",
"<",
"String",
",",
"ConfigValue",
">",
"entry",
":",
"config",
".",
"entrySet",
"(",
")",
")",
"{",
"conf",
".",
"set",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
".",
"unwrapped",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"return",
"conf",
";",
"}"
] | Provides Hadoop configuration given state.
It also supports decrypting values on "encryptedPath".
Note that this encryptedPath path will be removed from full path of each config key and leaving only child path on the key(s).
If there's same config path as child path, the one stripped will have higher priority.
e.g:
- encryptedPath: writer.fs.encrypted
before: writer.fs.encrypted.secret
after: secret
Common use case for these encryptedPath:
When there's have encrypted credential in job property but you'd like Filesystem to get decrypted value.
@param srcConfig source config.
@param encryptedPath Optional. If provided, config that is on this path will be decrypted. @see ConfigUtils.resolveEncrypted
Note that config on encryptedPath will be included in the end result even it's not part of includeOnlyPath
@return Hadoop Configuration. | [
"Provides",
"Hadoop",
"configuration",
"given",
"state",
".",
"It",
"also",
"supports",
"decrypting",
"values",
"on",
"encryptedPath",
".",
"Note",
"that",
"this",
"encryptedPath",
"path",
"will",
"be",
"removed",
"from",
"full",
"path",
"of",
"each",
"config",
"key",
"and",
"leaving",
"only",
"child",
"path",
"on",
"the",
"key",
"(",
"s",
")",
".",
"If",
"there",
"s",
"same",
"config",
"path",
"as",
"child",
"path",
"the",
"one",
"stripped",
"will",
"have",
"higher",
"priority",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/HadoopUtils.java#L742-L753 |
alkacon/opencms-core | src/org/opencms/xml/CmsXmlContentDefinition.java | CmsXmlContentDefinition.getContentDefinitionForType | public static CmsXmlContentDefinition getContentDefinitionForType(CmsObject cms, String typeName)
throws CmsException {
"""
Reads the content definition which is configured for a resource type.<p>
@param cms the current CMS context
@param typeName the type name
@return the content definition
@throws CmsException if something goes wrong
"""
I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(typeName);
String schema = resType.getConfiguration().get(CmsResourceTypeXmlContent.CONFIGURATION_SCHEMA);
CmsXmlContentDefinition contentDef = null;
if (schema == null) {
return null;
}
contentDef = unmarshal(cms, schema);
return contentDef;
} | java | public static CmsXmlContentDefinition getContentDefinitionForType(CmsObject cms, String typeName)
throws CmsException {
I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(typeName);
String schema = resType.getConfiguration().get(CmsResourceTypeXmlContent.CONFIGURATION_SCHEMA);
CmsXmlContentDefinition contentDef = null;
if (schema == null) {
return null;
}
contentDef = unmarshal(cms, schema);
return contentDef;
} | [
"public",
"static",
"CmsXmlContentDefinition",
"getContentDefinitionForType",
"(",
"CmsObject",
"cms",
",",
"String",
"typeName",
")",
"throws",
"CmsException",
"{",
"I_CmsResourceType",
"resType",
"=",
"OpenCms",
".",
"getResourceManager",
"(",
")",
".",
"getResourceType",
"(",
"typeName",
")",
";",
"String",
"schema",
"=",
"resType",
".",
"getConfiguration",
"(",
")",
".",
"get",
"(",
"CmsResourceTypeXmlContent",
".",
"CONFIGURATION_SCHEMA",
")",
";",
"CmsXmlContentDefinition",
"contentDef",
"=",
"null",
";",
"if",
"(",
"schema",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"contentDef",
"=",
"unmarshal",
"(",
"cms",
",",
"schema",
")",
";",
"return",
"contentDef",
";",
"}"
] | Reads the content definition which is configured for a resource type.<p>
@param cms the current CMS context
@param typeName the type name
@return the content definition
@throws CmsException if something goes wrong | [
"Reads",
"the",
"content",
"definition",
"which",
"is",
"configured",
"for",
"a",
"resource",
"type",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/CmsXmlContentDefinition.java#L318-L329 |
jtrfp/javamod | src/main/java/de/quippy/javamod/multimedia/mod/loader/instrument/Sample.java | Sample.getFIRInterpolated | private int getFIRInterpolated(final int currentSamplePos, final int currentTuningPos) {
"""
does a windowed fir interploation with the next sample
@since 15.06.2006
@param currentTuningPos
@return
"""
final int poslo = currentTuningPos & WindowedFIR.WFIR_POSFRACMASK;
final int firidx = ((poslo+WindowedFIR.WFIR_FRACHALVE)>>WindowedFIR.WFIR_FRACSHIFT) & WindowedFIR.WFIR_FRACMASK;
final long v1 = (((currentSamplePos-3)<0)?0L: (long)WindowedFIR.lut[firidx ]*(long)sample[currentSamplePos-3]) +
(((currentSamplePos-2)<0)?0L: (long)WindowedFIR.lut[firidx+1]*(long)sample[currentSamplePos-2]) +
(((currentSamplePos-1)<0)?0L: (long)WindowedFIR.lut[firidx+2]*(long)sample[currentSamplePos-1]) +
( (long)WindowedFIR.lut[firidx+3]*(long)sample[currentSamplePos ]);
final long v2 = ( (long)WindowedFIR.lut[firidx+4]*(long)sample[currentSamplePos+1]) +
( (long)WindowedFIR.lut[firidx+5]*(long)sample[currentSamplePos+2]) +
( (long)WindowedFIR.lut[firidx+6]*(long)sample[currentSamplePos+3]) +
( (long)WindowedFIR.lut[firidx+7]*(long)sample[currentSamplePos+4]);
return (int)(((v1>>1) + (v2>>1)) >> WindowedFIR.WFIR_16BITSHIFT);
} | java | private int getFIRInterpolated(final int currentSamplePos, final int currentTuningPos)
{
final int poslo = currentTuningPos & WindowedFIR.WFIR_POSFRACMASK;
final int firidx = ((poslo+WindowedFIR.WFIR_FRACHALVE)>>WindowedFIR.WFIR_FRACSHIFT) & WindowedFIR.WFIR_FRACMASK;
final long v1 = (((currentSamplePos-3)<0)?0L: (long)WindowedFIR.lut[firidx ]*(long)sample[currentSamplePos-3]) +
(((currentSamplePos-2)<0)?0L: (long)WindowedFIR.lut[firidx+1]*(long)sample[currentSamplePos-2]) +
(((currentSamplePos-1)<0)?0L: (long)WindowedFIR.lut[firidx+2]*(long)sample[currentSamplePos-1]) +
( (long)WindowedFIR.lut[firidx+3]*(long)sample[currentSamplePos ]);
final long v2 = ( (long)WindowedFIR.lut[firidx+4]*(long)sample[currentSamplePos+1]) +
( (long)WindowedFIR.lut[firidx+5]*(long)sample[currentSamplePos+2]) +
( (long)WindowedFIR.lut[firidx+6]*(long)sample[currentSamplePos+3]) +
( (long)WindowedFIR.lut[firidx+7]*(long)sample[currentSamplePos+4]);
return (int)(((v1>>1) + (v2>>1)) >> WindowedFIR.WFIR_16BITSHIFT);
} | [
"private",
"int",
"getFIRInterpolated",
"(",
"final",
"int",
"currentSamplePos",
",",
"final",
"int",
"currentTuningPos",
")",
"{",
"final",
"int",
"poslo",
"=",
"currentTuningPos",
"&",
"WindowedFIR",
".",
"WFIR_POSFRACMASK",
";",
"final",
"int",
"firidx",
"=",
"(",
"(",
"poslo",
"+",
"WindowedFIR",
".",
"WFIR_FRACHALVE",
")",
">>",
"WindowedFIR",
".",
"WFIR_FRACSHIFT",
")",
"&",
"WindowedFIR",
".",
"WFIR_FRACMASK",
";",
"final",
"long",
"v1",
"=",
"(",
"(",
"(",
"currentSamplePos",
"-",
"3",
")",
"<",
"0",
")",
"?",
"0L",
":",
"(",
"long",
")",
"WindowedFIR",
".",
"lut",
"[",
"firidx",
"]",
"*",
"(",
"long",
")",
"sample",
"[",
"currentSamplePos",
"-",
"3",
"]",
")",
"+",
"(",
"(",
"(",
"currentSamplePos",
"-",
"2",
")",
"<",
"0",
")",
"?",
"0L",
":",
"(",
"long",
")",
"WindowedFIR",
".",
"lut",
"[",
"firidx",
"+",
"1",
"]",
"*",
"(",
"long",
")",
"sample",
"[",
"currentSamplePos",
"-",
"2",
"]",
")",
"+",
"(",
"(",
"(",
"currentSamplePos",
"-",
"1",
")",
"<",
"0",
")",
"?",
"0L",
":",
"(",
"long",
")",
"WindowedFIR",
".",
"lut",
"[",
"firidx",
"+",
"2",
"]",
"*",
"(",
"long",
")",
"sample",
"[",
"currentSamplePos",
"-",
"1",
"]",
")",
"+",
"(",
"(",
"long",
")",
"WindowedFIR",
".",
"lut",
"[",
"firidx",
"+",
"3",
"]",
"*",
"(",
"long",
")",
"sample",
"[",
"currentSamplePos",
"]",
")",
";",
"final",
"long",
"v2",
"=",
"(",
"(",
"long",
")",
"WindowedFIR",
".",
"lut",
"[",
"firidx",
"+",
"4",
"]",
"*",
"(",
"long",
")",
"sample",
"[",
"currentSamplePos",
"+",
"1",
"]",
")",
"+",
"(",
"(",
"long",
")",
"WindowedFIR",
".",
"lut",
"[",
"firidx",
"+",
"5",
"]",
"*",
"(",
"long",
")",
"sample",
"[",
"currentSamplePos",
"+",
"2",
"]",
")",
"+",
"(",
"(",
"long",
")",
"WindowedFIR",
".",
"lut",
"[",
"firidx",
"+",
"6",
"]",
"*",
"(",
"long",
")",
"sample",
"[",
"currentSamplePos",
"+",
"3",
"]",
")",
"+",
"(",
"(",
"long",
")",
"WindowedFIR",
".",
"lut",
"[",
"firidx",
"+",
"7",
"]",
"*",
"(",
"long",
")",
"sample",
"[",
"currentSamplePos",
"+",
"4",
"]",
")",
";",
"return",
"(",
"int",
")",
"(",
"(",
"(",
"v1",
">>",
"1",
")",
"+",
"(",
"v2",
">>",
"1",
")",
")",
">>",
"WindowedFIR",
".",
"WFIR_16BITSHIFT",
")",
";",
"}"
] | does a windowed fir interploation with the next sample
@since 15.06.2006
@param currentTuningPos
@return | [
"does",
"a",
"windowed",
"fir",
"interploation",
"with",
"the",
"next",
"sample"
] | train | https://github.com/jtrfp/javamod/blob/cda4fe943a589dc49415f4413453e2eece72076a/src/main/java/de/quippy/javamod/multimedia/mod/loader/instrument/Sample.java#L167-L180 |
hyperledger/fabric-chaincode-java | fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/Handler.java | Handler.getState | ByteString getState(String channelId, String txId, String collection, String key) {
"""
handleGetState communicates with the validator to fetch the requested state information from the ledger.
"""
return invokeChaincodeSupport(newGetStateEventMessage(channelId, txId, collection, key));
} | java | ByteString getState(String channelId, String txId, String collection, String key) {
return invokeChaincodeSupport(newGetStateEventMessage(channelId, txId, collection, key));
} | [
"ByteString",
"getState",
"(",
"String",
"channelId",
",",
"String",
"txId",
",",
"String",
"collection",
",",
"String",
"key",
")",
"{",
"return",
"invokeChaincodeSupport",
"(",
"newGetStateEventMessage",
"(",
"channelId",
",",
"txId",
",",
"collection",
",",
"key",
")",
")",
";",
"}"
] | handleGetState communicates with the validator to fetch the requested state information from the ledger. | [
"handleGetState",
"communicates",
"with",
"the",
"validator",
"to",
"fetch",
"the",
"requested",
"state",
"information",
"from",
"the",
"ledger",
"."
] | train | https://github.com/hyperledger/fabric-chaincode-java/blob/1c688a3c7824758448fec31daaf0a1410a427e91/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/Handler.java#L315-L317 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/SerializedFormBuilder.java | SerializedFormBuilder.buildFieldHeader | public void buildFieldHeader(XMLNode node, Content classContentTree) {
"""
Build the field header.
@param node the XML element that specifies which components to document
@param classContentTree content tree to which the documentation will be added
"""
if (!utils.serializableFields(currentTypeElement).isEmpty()) {
buildFieldSerializationOverview(currentTypeElement, classContentTree);
}
} | java | public void buildFieldHeader(XMLNode node, Content classContentTree) {
if (!utils.serializableFields(currentTypeElement).isEmpty()) {
buildFieldSerializationOverview(currentTypeElement, classContentTree);
}
} | [
"public",
"void",
"buildFieldHeader",
"(",
"XMLNode",
"node",
",",
"Content",
"classContentTree",
")",
"{",
"if",
"(",
"!",
"utils",
".",
"serializableFields",
"(",
"currentTypeElement",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"buildFieldSerializationOverview",
"(",
"currentTypeElement",
",",
"classContentTree",
")",
";",
"}",
"}"
] | Build the field header.
@param node the XML element that specifies which components to document
@param classContentTree content tree to which the documentation will be added | [
"Build",
"the",
"field",
"header",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/SerializedFormBuilder.java#L386-L390 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/ui/SeaGlassTextFieldUI.java | SeaGlassTextFieldUI.getContext | private SeaGlassContext getContext(JComponent c, Region region, int state) {
"""
DOCUMENT ME!
@param c DOCUMENT ME!
@param region DOCUMENT ME!
@param state DOCUMENT ME!
@return DOCUMENT ME!
"""
SynthStyle style = findStyle;
if (region == SeaGlassRegion.SEARCH_FIELD_CANCEL_BUTTON) {
style = cancelStyle;
}
return SeaGlassContext.getContext(SeaGlassContext.class, c, region, style, state);
} | java | private SeaGlassContext getContext(JComponent c, Region region, int state) {
SynthStyle style = findStyle;
if (region == SeaGlassRegion.SEARCH_FIELD_CANCEL_BUTTON) {
style = cancelStyle;
}
return SeaGlassContext.getContext(SeaGlassContext.class, c, region, style, state);
} | [
"private",
"SeaGlassContext",
"getContext",
"(",
"JComponent",
"c",
",",
"Region",
"region",
",",
"int",
"state",
")",
"{",
"SynthStyle",
"style",
"=",
"findStyle",
";",
"if",
"(",
"region",
"==",
"SeaGlassRegion",
".",
"SEARCH_FIELD_CANCEL_BUTTON",
")",
"{",
"style",
"=",
"cancelStyle",
";",
"}",
"return",
"SeaGlassContext",
".",
"getContext",
"(",
"SeaGlassContext",
".",
"class",
",",
"c",
",",
"region",
",",
"style",
",",
"state",
")",
";",
"}"
] | DOCUMENT ME!
@param c DOCUMENT ME!
@param region DOCUMENT ME!
@param state DOCUMENT ME!
@return DOCUMENT ME! | [
"DOCUMENT",
"ME!"
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/ui/SeaGlassTextFieldUI.java#L378-L386 |
pip-services3-java/pip-services3-commons-java | src/org/pipservices3/commons/random/RandomDateTime.java | RandomDateTime.nextDate | public static ZonedDateTime nextDate(int minYear, int maxYear) {
"""
Generates a random ZonedDateTime in the range ['minYear', 'maxYear']. This
method generate dates without time (or time set to 00:00:00)
@param minYear (optional) minimum range value
@param maxYear max range value
@return a random ZonedDateTime value.
"""
int currentYear = ZonedDateTime.now().getYear();
minYear = minYear == 0 ? currentYear - RandomInteger.nextInteger(10) : minYear;
maxYear = maxYear == 0 ? currentYear : maxYear;
int year = RandomInteger.nextInteger(minYear, maxYear);
int month = RandomInteger.nextInteger(1, 13);
int day = RandomInteger.nextInteger(1, 32);
if (month == 2)
day = Math.min(28, day);
else if (month == 4 || month == 6 || month == 9 || month == 11)
day = Math.min(30, day);
return ZonedDateTime.of(year, month, day, 0, 0, 0, 0, ZoneId.of("UTC"));
} | java | public static ZonedDateTime nextDate(int minYear, int maxYear) {
int currentYear = ZonedDateTime.now().getYear();
minYear = minYear == 0 ? currentYear - RandomInteger.nextInteger(10) : minYear;
maxYear = maxYear == 0 ? currentYear : maxYear;
int year = RandomInteger.nextInteger(minYear, maxYear);
int month = RandomInteger.nextInteger(1, 13);
int day = RandomInteger.nextInteger(1, 32);
if (month == 2)
day = Math.min(28, day);
else if (month == 4 || month == 6 || month == 9 || month == 11)
day = Math.min(30, day);
return ZonedDateTime.of(year, month, day, 0, 0, 0, 0, ZoneId.of("UTC"));
} | [
"public",
"static",
"ZonedDateTime",
"nextDate",
"(",
"int",
"minYear",
",",
"int",
"maxYear",
")",
"{",
"int",
"currentYear",
"=",
"ZonedDateTime",
".",
"now",
"(",
")",
".",
"getYear",
"(",
")",
";",
"minYear",
"=",
"minYear",
"==",
"0",
"?",
"currentYear",
"-",
"RandomInteger",
".",
"nextInteger",
"(",
"10",
")",
":",
"minYear",
";",
"maxYear",
"=",
"maxYear",
"==",
"0",
"?",
"currentYear",
":",
"maxYear",
";",
"int",
"year",
"=",
"RandomInteger",
".",
"nextInteger",
"(",
"minYear",
",",
"maxYear",
")",
";",
"int",
"month",
"=",
"RandomInteger",
".",
"nextInteger",
"(",
"1",
",",
"13",
")",
";",
"int",
"day",
"=",
"RandomInteger",
".",
"nextInteger",
"(",
"1",
",",
"32",
")",
";",
"if",
"(",
"month",
"==",
"2",
")",
"day",
"=",
"Math",
".",
"min",
"(",
"28",
",",
"day",
")",
";",
"else",
"if",
"(",
"month",
"==",
"4",
"||",
"month",
"==",
"6",
"||",
"month",
"==",
"9",
"||",
"month",
"==",
"11",
")",
"day",
"=",
"Math",
".",
"min",
"(",
"30",
",",
"day",
")",
";",
"return",
"ZonedDateTime",
".",
"of",
"(",
"year",
",",
"month",
",",
"day",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"ZoneId",
".",
"of",
"(",
"\"UTC\"",
")",
")",
";",
"}"
] | Generates a random ZonedDateTime in the range ['minYear', 'maxYear']. This
method generate dates without time (or time set to 00:00:00)
@param minYear (optional) minimum range value
@param maxYear max range value
@return a random ZonedDateTime value. | [
"Generates",
"a",
"random",
"ZonedDateTime",
"in",
"the",
"range",
"[",
"minYear",
"maxYear",
"]",
".",
"This",
"method",
"generate",
"dates",
"without",
"time",
"(",
"or",
"time",
"set",
"to",
"00",
":",
"00",
":",
"00",
")"
] | train | https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/random/RandomDateTime.java#L25-L39 |
lucee/Lucee | core/src/main/java/lucee/transformer/bytecode/util/ExpressionUtil.java | ExpressionUtil.visitLine | public static void visitLine(BytecodeContext bc, Position pos) {
"""
visit line number
@param adapter
@param line
@param silent id silent this is ignored for log
"""
if (pos != null) {
visitLine(bc, pos.line);
}
} | java | public static void visitLine(BytecodeContext bc, Position pos) {
if (pos != null) {
visitLine(bc, pos.line);
}
} | [
"public",
"static",
"void",
"visitLine",
"(",
"BytecodeContext",
"bc",
",",
"Position",
"pos",
")",
"{",
"if",
"(",
"pos",
"!=",
"null",
")",
"{",
"visitLine",
"(",
"bc",
",",
"pos",
".",
"line",
")",
";",
"}",
"}"
] | visit line number
@param adapter
@param line
@param silent id silent this is ignored for log | [
"visit",
"line",
"number"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/transformer/bytecode/util/ExpressionUtil.java#L72-L76 |
jOOQ/jOOL | jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java | Unchecked.doubleFunction | public static <R> DoubleFunction<R> doubleFunction(CheckedDoubleFunction<R> function) {
"""
Wrap a {@link CheckedDoubleFunction} in a {@link DoubleFunction}.
<p>
Example:
<code><pre>
DoubleStream.of(1.0, 2.0, 3.0).mapToObj(Unchecked.doubleFunction(d -> {
if (d < 0.0)
throw new Exception("Only positive numbers allowed");
return "" + d;
});
</pre></code>
"""
return doubleFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION);
} | java | public static <R> DoubleFunction<R> doubleFunction(CheckedDoubleFunction<R> function) {
return doubleFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION);
} | [
"public",
"static",
"<",
"R",
">",
"DoubleFunction",
"<",
"R",
">",
"doubleFunction",
"(",
"CheckedDoubleFunction",
"<",
"R",
">",
"function",
")",
"{",
"return",
"doubleFunction",
"(",
"function",
",",
"THROWABLE_TO_RUNTIME_EXCEPTION",
")",
";",
"}"
] | Wrap a {@link CheckedDoubleFunction} in a {@link DoubleFunction}.
<p>
Example:
<code><pre>
DoubleStream.of(1.0, 2.0, 3.0).mapToObj(Unchecked.doubleFunction(d -> {
if (d < 0.0)
throw new Exception("Only positive numbers allowed");
return "" + d;
});
</pre></code> | [
"Wrap",
"a",
"{",
"@link",
"CheckedDoubleFunction",
"}",
"in",
"a",
"{",
"@link",
"DoubleFunction",
"}",
".",
"<p",
">",
"Example",
":",
"<code",
">",
"<pre",
">",
"DoubleStream",
".",
"of",
"(",
"1",
".",
"0",
"2",
".",
"0",
"3",
".",
"0",
")",
".",
"mapToObj",
"(",
"Unchecked",
".",
"doubleFunction",
"(",
"d",
"-",
">",
"{",
"if",
"(",
"d",
"<",
";",
"0",
".",
"0",
")",
"throw",
"new",
"Exception",
"(",
"Only",
"positive",
"numbers",
"allowed",
")",
";"
] | train | https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L1333-L1335 |
nextreports/nextreports-engine | src/ro/nextreports/engine/querybuilder/sql/dialect/AbstractDialect.java | AbstractDialect.registerColumnType | protected void registerColumnType(String columnType, int jdbcType) {
"""
Subclasses register a typename for the given type code.
@param columnType the database column type
@param jdbcType <tt>java.sql.Types</tt> typecode
"""
columnTypeMatchers.add(new ColumnTypeMatcher(columnType));
jdbcTypes.put(columnType, jdbcType);
} | java | protected void registerColumnType(String columnType, int jdbcType) {
columnTypeMatchers.add(new ColumnTypeMatcher(columnType));
jdbcTypes.put(columnType, jdbcType);
} | [
"protected",
"void",
"registerColumnType",
"(",
"String",
"columnType",
",",
"int",
"jdbcType",
")",
"{",
"columnTypeMatchers",
".",
"add",
"(",
"new",
"ColumnTypeMatcher",
"(",
"columnType",
")",
")",
";",
"jdbcTypes",
".",
"put",
"(",
"columnType",
",",
"jdbcType",
")",
";",
"}"
] | Subclasses register a typename for the given type code.
@param columnType the database column type
@param jdbcType <tt>java.sql.Types</tt> typecode | [
"Subclasses",
"register",
"a",
"typename",
"for",
"the",
"given",
"type",
"code",
"."
] | train | https://github.com/nextreports/nextreports-engine/blob/a847575a9298b5fce63b88961190c5b83ddccc44/src/ro/nextreports/engine/querybuilder/sql/dialect/AbstractDialect.java#L116-L119 |
BlueBrain/bluima | modules/bluima_utils/src/main/java/ds/tree/RadixTreeImpl.java | RadixTreeImpl.formatNodeTo | private void formatNodeTo(Formatter f, int level, RadixTreeNode<T> node) {
"""
WARNING! Do not use this for a large Trie, it's for testing purpose only.
"""
for (int i = 0; i < level; i++) {
f.format(" ");
}
f.format("|");
for (int i = 0; i < level; i++) {
f.format("-");
}
if (node.isReal() == true)
f.format("%s[%s]*%n", node.getKey(), node.getValue());
else
f.format("%s%n", node.getKey());
for (RadixTreeNode<T> child : node.getChildern()) {
formatNodeTo(f, level + 1, child);
}
} | java | private void formatNodeTo(Formatter f, int level, RadixTreeNode<T> node) {
for (int i = 0; i < level; i++) {
f.format(" ");
}
f.format("|");
for (int i = 0; i < level; i++) {
f.format("-");
}
if (node.isReal() == true)
f.format("%s[%s]*%n", node.getKey(), node.getValue());
else
f.format("%s%n", node.getKey());
for (RadixTreeNode<T> child : node.getChildern()) {
formatNodeTo(f, level + 1, child);
}
} | [
"private",
"void",
"formatNodeTo",
"(",
"Formatter",
"f",
",",
"int",
"level",
",",
"RadixTreeNode",
"<",
"T",
">",
"node",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"level",
";",
"i",
"++",
")",
"{",
"f",
".",
"format",
"(",
"\" \"",
")",
";",
"}",
"f",
".",
"format",
"(",
"\"|\"",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"level",
";",
"i",
"++",
")",
"{",
"f",
".",
"format",
"(",
"\"-\"",
")",
";",
"}",
"if",
"(",
"node",
".",
"isReal",
"(",
")",
"==",
"true",
")",
"f",
".",
"format",
"(",
"\"%s[%s]*%n\"",
",",
"node",
".",
"getKey",
"(",
")",
",",
"node",
".",
"getValue",
"(",
")",
")",
";",
"else",
"f",
".",
"format",
"(",
"\"%s%n\"",
",",
"node",
".",
"getKey",
"(",
")",
")",
";",
"for",
"(",
"RadixTreeNode",
"<",
"T",
">",
"child",
":",
"node",
".",
"getChildern",
"(",
")",
")",
"{",
"formatNodeTo",
"(",
"f",
",",
"level",
"+",
"1",
",",
"child",
")",
";",
"}",
"}"
] | WARNING! Do not use this for a large Trie, it's for testing purpose only. | [
"WARNING!",
"Do",
"not",
"use",
"this",
"for",
"a",
"large",
"Trie",
"it",
"s",
"for",
"testing",
"purpose",
"only",
"."
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_utils/src/main/java/ds/tree/RadixTreeImpl.java#L374-L391 |
reactor/reactor-netty | src/main/java/reactor/netty/udp/UdpClient.java | UdpClient.doOnDisconnected | public final UdpClient doOnDisconnected(Consumer<? super Connection> doOnDisconnected) {
"""
Setup a callback called when {@link io.netty.channel.Channel} is
disconnected.
@param doOnDisconnected a consumer observing client stop event
@return a new {@link UdpClient}
"""
Objects.requireNonNull(doOnDisconnected, "doOnDisconnected");
return new UdpClientDoOn(this, null, null, doOnDisconnected);
} | java | public final UdpClient doOnDisconnected(Consumer<? super Connection> doOnDisconnected) {
Objects.requireNonNull(doOnDisconnected, "doOnDisconnected");
return new UdpClientDoOn(this, null, null, doOnDisconnected);
} | [
"public",
"final",
"UdpClient",
"doOnDisconnected",
"(",
"Consumer",
"<",
"?",
"super",
"Connection",
">",
"doOnDisconnected",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"doOnDisconnected",
",",
"\"doOnDisconnected\"",
")",
";",
"return",
"new",
"UdpClientDoOn",
"(",
"this",
",",
"null",
",",
"null",
",",
"doOnDisconnected",
")",
";",
"}"
] | Setup a callback called when {@link io.netty.channel.Channel} is
disconnected.
@param doOnDisconnected a consumer observing client stop event
@return a new {@link UdpClient} | [
"Setup",
"a",
"callback",
"called",
"when",
"{",
"@link",
"io",
".",
"netty",
".",
"channel",
".",
"Channel",
"}",
"is",
"disconnected",
"."
] | train | https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/udp/UdpClient.java#L206-L209 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/LogAnalyticsInner.java | LogAnalyticsInner.beginExportRequestRateByInterval | public LogAnalyticsOperationResultInner beginExportRequestRateByInterval(String location, RequestRateByIntervalInput parameters) {
"""
Export logs that show Api requests made by this subscription in the given time window to show throttling activities.
@param location The location upon which virtual-machine-sizes is queried.
@param parameters Parameters supplied to the LogAnalytics getRequestRateByInterval Api.
@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 LogAnalyticsOperationResultInner object if successful.
"""
return beginExportRequestRateByIntervalWithServiceResponseAsync(location, parameters).toBlocking().single().body();
} | java | public LogAnalyticsOperationResultInner beginExportRequestRateByInterval(String location, RequestRateByIntervalInput parameters) {
return beginExportRequestRateByIntervalWithServiceResponseAsync(location, parameters).toBlocking().single().body();
} | [
"public",
"LogAnalyticsOperationResultInner",
"beginExportRequestRateByInterval",
"(",
"String",
"location",
",",
"RequestRateByIntervalInput",
"parameters",
")",
"{",
"return",
"beginExportRequestRateByIntervalWithServiceResponseAsync",
"(",
"location",
",",
"parameters",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Export logs that show Api requests made by this subscription in the given time window to show throttling activities.
@param location The location upon which virtual-machine-sizes is queried.
@param parameters Parameters supplied to the LogAnalytics getRequestRateByInterval Api.
@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 LogAnalyticsOperationResultInner object if successful. | [
"Export",
"logs",
"that",
"show",
"Api",
"requests",
"made",
"by",
"this",
"subscription",
"in",
"the",
"given",
"time",
"window",
"to",
"show",
"throttling",
"activities",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/LogAnalyticsInner.java#L156-L158 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/ConfigUtils.java | ConfigUtils.getInt | public static Integer getInt(Config config, String path, Integer def) {
"""
Return {@link Integer} value at <code>path</code> if <code>config</code> has path. If not return <code>def</code>
@param config in which the path may be present
@param path key to look for in the config object
@return {@link Integer} value at <code>path</code> if <code>config</code> has path. If not return <code>def</code>
"""
if (config.hasPath(path)) {
return Integer.valueOf(config.getInt(path));
}
return def;
} | java | public static Integer getInt(Config config, String path, Integer def) {
if (config.hasPath(path)) {
return Integer.valueOf(config.getInt(path));
}
return def;
} | [
"public",
"static",
"Integer",
"getInt",
"(",
"Config",
"config",
",",
"String",
"path",
",",
"Integer",
"def",
")",
"{",
"if",
"(",
"config",
".",
"hasPath",
"(",
"path",
")",
")",
"{",
"return",
"Integer",
".",
"valueOf",
"(",
"config",
".",
"getInt",
"(",
"path",
")",
")",
";",
"}",
"return",
"def",
";",
"}"
] | Return {@link Integer} value at <code>path</code> if <code>config</code> has path. If not return <code>def</code>
@param config in which the path may be present
@param path key to look for in the config object
@return {@link Integer} value at <code>path</code> if <code>config</code> has path. If not return <code>def</code> | [
"Return",
"{",
"@link",
"Integer",
"}",
"value",
"at",
"<code",
">",
"path<",
"/",
"code",
">",
"if",
"<code",
">",
"config<",
"/",
"code",
">",
"has",
"path",
".",
"If",
"not",
"return",
"<code",
">",
"def<",
"/",
"code",
">"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ConfigUtils.java#L350-L355 |
elki-project/elki | elki-gui-minigui/src/main/java/de/lmu/ifi/dbs/elki/gui/util/LogPanel.java | LogPanel.removeProgressBar | private void removeProgressBar(Progress prog, JProgressBar pbar) {
"""
Remove a progress bar
@param prog Progress
@param pbar Associated progress bar
"""
synchronized(pbarmap) {
pbarmap.remove(prog);
SwingUtilities.invokeLater(() -> removeProgressBar(pbar));
}
} | java | private void removeProgressBar(Progress prog, JProgressBar pbar) {
synchronized(pbarmap) {
pbarmap.remove(prog);
SwingUtilities.invokeLater(() -> removeProgressBar(pbar));
}
} | [
"private",
"void",
"removeProgressBar",
"(",
"Progress",
"prog",
",",
"JProgressBar",
"pbar",
")",
"{",
"synchronized",
"(",
"pbarmap",
")",
"{",
"pbarmap",
".",
"remove",
"(",
"prog",
")",
";",
"SwingUtilities",
".",
"invokeLater",
"(",
"(",
")",
"->",
"removeProgressBar",
"(",
"pbar",
")",
")",
";",
"}",
"}"
] | Remove a progress bar
@param prog Progress
@param pbar Associated progress bar | [
"Remove",
"a",
"progress",
"bar"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-gui-minigui/src/main/java/de/lmu/ifi/dbs/elki/gui/util/LogPanel.java#L192-L197 |
stanfy/goro | goro/src/main/java/com/stanfy/enroscar/goro/Goro.java | Goro.bindAndAutoReconnectWith | public static BoundGoro bindAndAutoReconnectWith(final Context context) {
"""
Creates a Goro implementation that binds to {@link com.stanfy.enroscar.goro.GoroService}
in order to run scheduled tasks in service context.
<p>
This method is functionally identical to
</p>
<pre>
BoundGoro goro = Goro.bindWith(context, new BoundGoro.OnUnexpectedDisconnection() {
public void onServiceDisconnected(BoundGoro goro) {
goro.bind();
}
});
</pre>
@param context context that will bind to the service
@return Goro implementation that binds to {@link GoroService}.
@see #bindWith(Context, BoundGoro.OnUnexpectedDisconnection)
"""
if (context == null) {
throw new IllegalArgumentException("Context cannot be null");
}
return new BoundGoroImpl(context, null);
} | java | public static BoundGoro bindAndAutoReconnectWith(final Context context) {
if (context == null) {
throw new IllegalArgumentException("Context cannot be null");
}
return new BoundGoroImpl(context, null);
} | [
"public",
"static",
"BoundGoro",
"bindAndAutoReconnectWith",
"(",
"final",
"Context",
"context",
")",
"{",
"if",
"(",
"context",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Context cannot be null\"",
")",
";",
"}",
"return",
"new",
"BoundGoroImpl",
"(",
"context",
",",
"null",
")",
";",
"}"
] | Creates a Goro implementation that binds to {@link com.stanfy.enroscar.goro.GoroService}
in order to run scheduled tasks in service context.
<p>
This method is functionally identical to
</p>
<pre>
BoundGoro goro = Goro.bindWith(context, new BoundGoro.OnUnexpectedDisconnection() {
public void onServiceDisconnected(BoundGoro goro) {
goro.bind();
}
});
</pre>
@param context context that will bind to the service
@return Goro implementation that binds to {@link GoroService}.
@see #bindWith(Context, BoundGoro.OnUnexpectedDisconnection) | [
"Creates",
"a",
"Goro",
"implementation",
"that",
"binds",
"to",
"{"
] | train | https://github.com/stanfy/goro/blob/6618e63a926833d61f492ec611ee77668d756820/goro/src/main/java/com/stanfy/enroscar/goro/Goro.java#L69-L74 |
box/box-java-sdk | src/main/java/com/box/sdk/MetadataTemplate.java | MetadataTemplate.deleteMetadataTemplate | public static void deleteMetadataTemplate(BoxAPIConnection api, String scope, String template) {
"""
Deletes the schema of an existing metadata template.
@param api the API connection to be used
@param scope the scope of the object
@param template Unique identifier of the template
"""
URL url = METADATA_TEMPLATE_URL_TEMPLATE.build(api.getBaseURL(), scope, template);
BoxJSONRequest request = new BoxJSONRequest(api, url, "DELETE");
request.send();
} | java | public static void deleteMetadataTemplate(BoxAPIConnection api, String scope, String template) {
URL url = METADATA_TEMPLATE_URL_TEMPLATE.build(api.getBaseURL(), scope, template);
BoxJSONRequest request = new BoxJSONRequest(api, url, "DELETE");
request.send();
} | [
"public",
"static",
"void",
"deleteMetadataTemplate",
"(",
"BoxAPIConnection",
"api",
",",
"String",
"scope",
",",
"String",
"template",
")",
"{",
"URL",
"url",
"=",
"METADATA_TEMPLATE_URL_TEMPLATE",
".",
"build",
"(",
"api",
".",
"getBaseURL",
"(",
")",
",",
"scope",
",",
"template",
")",
";",
"BoxJSONRequest",
"request",
"=",
"new",
"BoxJSONRequest",
"(",
"api",
",",
"url",
",",
"\"DELETE\"",
")",
";",
"request",
".",
"send",
"(",
")",
";",
"}"
] | Deletes the schema of an existing metadata template.
@param api the API connection to be used
@param scope the scope of the object
@param template Unique identifier of the template | [
"Deletes",
"the",
"schema",
"of",
"an",
"existing",
"metadata",
"template",
"."
] | train | https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/MetadataTemplate.java#L304-L310 |
code4everything/util | src/main/java/com/zhazhapan/util/BeanUtils.java | BeanUtils.toJsonString | public static String toJsonString(Object object, FieldModifier modifier, JsonMethod method) throws IllegalAccessException {
"""
将Bean类指定修饰符的属性转换成JSON字符串
@param object Bean对象
@param modifier 属性的权限修饰符
@param method {@link JsonMethod}
@return 没有格式化的JSON字符串
@throws IllegalAccessException 异常
"""
JSONObject jsonObject = new JSONObject();
StringBuilder builder = new StringBuilder("{");
boolean isManual = false;
if (Checker.isNotNull(object)) {
Class<?> bean = object.getClass();
Field[] fields = bean.getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
boolean addable =
modifier == FieldModifier.ALL || (modifier == FieldModifier.PRIVATE && Modifier.isPrivate(mod)) || (modifier == FieldModifier.PUBLIC && Modifier.isPublic(mod));
if (addable) {
field.setAccessible(true);
isManual = Checker.isIn(method, METHODS);
if (isManual) {
Object f = field.get(object);
if (Checker.isNotNull(f)) {
builder.append(converter(field.getName(), f));
}
} else {
jsonObject.put(field.getName(), field.get(object));
}
}
}
}
return isManual ? builder.substring(0, builder.length() - 1) + "}" : jsonObject.toString();
} | java | public static String toJsonString(Object object, FieldModifier modifier, JsonMethod method) throws IllegalAccessException {
JSONObject jsonObject = new JSONObject();
StringBuilder builder = new StringBuilder("{");
boolean isManual = false;
if (Checker.isNotNull(object)) {
Class<?> bean = object.getClass();
Field[] fields = bean.getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
boolean addable =
modifier == FieldModifier.ALL || (modifier == FieldModifier.PRIVATE && Modifier.isPrivate(mod)) || (modifier == FieldModifier.PUBLIC && Modifier.isPublic(mod));
if (addable) {
field.setAccessible(true);
isManual = Checker.isIn(method, METHODS);
if (isManual) {
Object f = field.get(object);
if (Checker.isNotNull(f)) {
builder.append(converter(field.getName(), f));
}
} else {
jsonObject.put(field.getName(), field.get(object));
}
}
}
}
return isManual ? builder.substring(0, builder.length() - 1) + "}" : jsonObject.toString();
} | [
"public",
"static",
"String",
"toJsonString",
"(",
"Object",
"object",
",",
"FieldModifier",
"modifier",
",",
"JsonMethod",
"method",
")",
"throws",
"IllegalAccessException",
"{",
"JSONObject",
"jsonObject",
"=",
"new",
"JSONObject",
"(",
")",
";",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
"\"{\"",
")",
";",
"boolean",
"isManual",
"=",
"false",
";",
"if",
"(",
"Checker",
".",
"isNotNull",
"(",
"object",
")",
")",
"{",
"Class",
"<",
"?",
">",
"bean",
"=",
"object",
".",
"getClass",
"(",
")",
";",
"Field",
"[",
"]",
"fields",
"=",
"bean",
".",
"getDeclaredFields",
"(",
")",
";",
"for",
"(",
"Field",
"field",
":",
"fields",
")",
"{",
"int",
"mod",
"=",
"field",
".",
"getModifiers",
"(",
")",
";",
"boolean",
"addable",
"=",
"modifier",
"==",
"FieldModifier",
".",
"ALL",
"||",
"(",
"modifier",
"==",
"FieldModifier",
".",
"PRIVATE",
"&&",
"Modifier",
".",
"isPrivate",
"(",
"mod",
")",
")",
"||",
"(",
"modifier",
"==",
"FieldModifier",
".",
"PUBLIC",
"&&",
"Modifier",
".",
"isPublic",
"(",
"mod",
")",
")",
";",
"if",
"(",
"addable",
")",
"{",
"field",
".",
"setAccessible",
"(",
"true",
")",
";",
"isManual",
"=",
"Checker",
".",
"isIn",
"(",
"method",
",",
"METHODS",
")",
";",
"if",
"(",
"isManual",
")",
"{",
"Object",
"f",
"=",
"field",
".",
"get",
"(",
"object",
")",
";",
"if",
"(",
"Checker",
".",
"isNotNull",
"(",
"f",
")",
")",
"{",
"builder",
".",
"append",
"(",
"converter",
"(",
"field",
".",
"getName",
"(",
")",
",",
"f",
")",
")",
";",
"}",
"}",
"else",
"{",
"jsonObject",
".",
"put",
"(",
"field",
".",
"getName",
"(",
")",
",",
"field",
".",
"get",
"(",
"object",
")",
")",
";",
"}",
"}",
"}",
"}",
"return",
"isManual",
"?",
"builder",
".",
"substring",
"(",
"0",
",",
"builder",
".",
"length",
"(",
")",
"-",
"1",
")",
"+",
"\"}\"",
":",
"jsonObject",
".",
"toString",
"(",
")",
";",
"}"
] | 将Bean类指定修饰符的属性转换成JSON字符串
@param object Bean对象
@param modifier 属性的权限修饰符
@param method {@link JsonMethod}
@return 没有格式化的JSON字符串
@throws IllegalAccessException 异常 | [
"将Bean类指定修饰符的属性转换成JSON字符串"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/BeanUtils.java#L301-L327 |
BoltsFramework/Bolts-Android | bolts-tasks/src/main/java/bolts/Task.java | Task.continueWith | public <TContinuationResult> Task<TContinuationResult> continueWith(
Continuation<TResult, TContinuationResult> continuation) {
"""
Adds a synchronous continuation to this task, returning a new task that completes after the
continuation has finished running.
"""
return continueWith(continuation, IMMEDIATE_EXECUTOR, null);
} | java | public <TContinuationResult> Task<TContinuationResult> continueWith(
Continuation<TResult, TContinuationResult> continuation) {
return continueWith(continuation, IMMEDIATE_EXECUTOR, null);
} | [
"public",
"<",
"TContinuationResult",
">",
"Task",
"<",
"TContinuationResult",
">",
"continueWith",
"(",
"Continuation",
"<",
"TResult",
",",
"TContinuationResult",
">",
"continuation",
")",
"{",
"return",
"continueWith",
"(",
"continuation",
",",
"IMMEDIATE_EXECUTOR",
",",
"null",
")",
";",
"}"
] | Adds a synchronous continuation to this task, returning a new task that completes after the
continuation has finished running. | [
"Adds",
"a",
"synchronous",
"continuation",
"to",
"this",
"task",
"returning",
"a",
"new",
"task",
"that",
"completes",
"after",
"the",
"continuation",
"has",
"finished",
"running",
"."
] | train | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/Task.java#L667-L670 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/util/EventListenerListHelper.java | EventListenerListHelper.fireEventByReflection | private void fireEventByReflection(String methodName, Object[] eventArgs) {
"""
Invokes the method with the given name on each of the listeners registered with this list
helper. The given arguments are passed to each method invocation.
@param methodName The name of the method to be invoked on the listeners.
@param eventArgs The arguments that will be passed to each method invocation. The number
of arguments is also used to determine the method to be invoked.
@throws EventBroadcastException if an error occurs invoking the event method on any of the
listeners.
"""
Method eventMethod = (Method)methodCache.get(new MethodCacheKey(listenerClass, methodName, eventArgs.length));
Object[] listenersCopy = listeners;
for (int i = 0; i < listenersCopy.length; i++) {
try {
eventMethod.invoke(listenersCopy[i], eventArgs);
}
catch (InvocationTargetException e) {
throw new EventBroadcastException("Exception thrown by listener", e.getCause());
}
catch (IllegalAccessException e) {
throw new EventBroadcastException("Unable to invoke listener", e);
}
}
} | java | private void fireEventByReflection(String methodName, Object[] eventArgs) {
Method eventMethod = (Method)methodCache.get(new MethodCacheKey(listenerClass, methodName, eventArgs.length));
Object[] listenersCopy = listeners;
for (int i = 0; i < listenersCopy.length; i++) {
try {
eventMethod.invoke(listenersCopy[i], eventArgs);
}
catch (InvocationTargetException e) {
throw new EventBroadcastException("Exception thrown by listener", e.getCause());
}
catch (IllegalAccessException e) {
throw new EventBroadcastException("Unable to invoke listener", e);
}
}
} | [
"private",
"void",
"fireEventByReflection",
"(",
"String",
"methodName",
",",
"Object",
"[",
"]",
"eventArgs",
")",
"{",
"Method",
"eventMethod",
"=",
"(",
"Method",
")",
"methodCache",
".",
"get",
"(",
"new",
"MethodCacheKey",
"(",
"listenerClass",
",",
"methodName",
",",
"eventArgs",
".",
"length",
")",
")",
";",
"Object",
"[",
"]",
"listenersCopy",
"=",
"listeners",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"listenersCopy",
".",
"length",
";",
"i",
"++",
")",
"{",
"try",
"{",
"eventMethod",
".",
"invoke",
"(",
"listenersCopy",
"[",
"i",
"]",
",",
"eventArgs",
")",
";",
"}",
"catch",
"(",
"InvocationTargetException",
"e",
")",
"{",
"throw",
"new",
"EventBroadcastException",
"(",
"\"Exception thrown by listener\"",
",",
"e",
".",
"getCause",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IllegalAccessException",
"e",
")",
"{",
"throw",
"new",
"EventBroadcastException",
"(",
"\"Unable to invoke listener\"",
",",
"e",
")",
";",
"}",
"}",
"}"
] | Invokes the method with the given name on each of the listeners registered with this list
helper. The given arguments are passed to each method invocation.
@param methodName The name of the method to be invoked on the listeners.
@param eventArgs The arguments that will be passed to each method invocation. The number
of arguments is also used to determine the method to be invoked.
@throws EventBroadcastException if an error occurs invoking the event method on any of the
listeners. | [
"Invokes",
"the",
"method",
"with",
"the",
"given",
"name",
"on",
"each",
"of",
"the",
"listeners",
"registered",
"with",
"this",
"list",
"helper",
".",
"The",
"given",
"arguments",
"are",
"passed",
"to",
"each",
"method",
"invocation",
"."
] | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/util/EventListenerListHelper.java#L395-L409 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/PropertyBuilder.java | PropertyBuilder.buildTagInfo | public void buildTagInfo(XMLNode node, Content propertyDocTree) {
"""
Build the tag information.
@param node the XML element that specifies which components to document
@param propertyDocTree the content tree to which the documentation will be added
"""
writer.addTags((MethodDoc) properties.get(currentPropertyIndex), propertyDocTree);
} | java | public void buildTagInfo(XMLNode node, Content propertyDocTree) {
writer.addTags((MethodDoc) properties.get(currentPropertyIndex), propertyDocTree);
} | [
"public",
"void",
"buildTagInfo",
"(",
"XMLNode",
"node",
",",
"Content",
"propertyDocTree",
")",
"{",
"writer",
".",
"addTags",
"(",
"(",
"MethodDoc",
")",
"properties",
".",
"get",
"(",
"currentPropertyIndex",
")",
",",
"propertyDocTree",
")",
";",
"}"
] | Build the tag information.
@param node the XML element that specifies which components to document
@param propertyDocTree the content tree to which the documentation will be added | [
"Build",
"the",
"tag",
"information",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/PropertyBuilder.java#L217-L219 |
sporniket/core | sporniket-core-lang/src/main/java/com/sporniket/libre/lang/CollectionTools.java | CollectionTools.getObject | public static Object getObject(final ResourceBundle source, final String key, final Object defaultValue) {
"""
Return an object from a ResourceBundle.
@param source
ResourceBundle from which extract the value
@param key
The key to retrieve the value
@param defaultValue
When the wanted value doesn't exist, return this one
@return The wanted object or defaulValue
"""
try
{
return source.getObject(key);
}
catch (Exception _exception)
{
return defaultValue;
}
} | java | public static Object getObject(final ResourceBundle source, final String key, final Object defaultValue)
{
try
{
return source.getObject(key);
}
catch (Exception _exception)
{
return defaultValue;
}
} | [
"public",
"static",
"Object",
"getObject",
"(",
"final",
"ResourceBundle",
"source",
",",
"final",
"String",
"key",
",",
"final",
"Object",
"defaultValue",
")",
"{",
"try",
"{",
"return",
"source",
".",
"getObject",
"(",
"key",
")",
";",
"}",
"catch",
"(",
"Exception",
"_exception",
")",
"{",
"return",
"defaultValue",
";",
"}",
"}"
] | Return an object from a ResourceBundle.
@param source
ResourceBundle from which extract the value
@param key
The key to retrieve the value
@param defaultValue
When the wanted value doesn't exist, return this one
@return The wanted object or defaulValue | [
"Return",
"an",
"object",
"from",
"a",
"ResourceBundle",
"."
] | train | https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-lang/src/main/java/com/sporniket/libre/lang/CollectionTools.java#L54-L64 |
SonarSource/sonarqube | server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationService.java | NotificationService.hasProjectSubscribersForTypes | public boolean hasProjectSubscribersForTypes(String projectUuid, Set<Class<? extends Notification>> notificationTypes) {
"""
Returns true if at least one user is subscribed to at least one notification with given types.
Subscription can be global or on the specific project.
"""
Set<String> dispatcherKeys = handlers.stream()
.filter(handler -> notificationTypes.stream().anyMatch(notificationType -> handler.getNotificationClass() == notificationType))
.map(NotificationHandler::getMetadata)
.filter(Optional::isPresent)
.map(Optional::get)
.map(NotificationDispatcherMetadata::getDispatcherKey)
.collect(MoreCollectors.toSet(notificationTypes.size()));
return dbClient.propertiesDao().hasProjectNotificationSubscribersForDispatchers(projectUuid, dispatcherKeys);
} | java | public boolean hasProjectSubscribersForTypes(String projectUuid, Set<Class<? extends Notification>> notificationTypes) {
Set<String> dispatcherKeys = handlers.stream()
.filter(handler -> notificationTypes.stream().anyMatch(notificationType -> handler.getNotificationClass() == notificationType))
.map(NotificationHandler::getMetadata)
.filter(Optional::isPresent)
.map(Optional::get)
.map(NotificationDispatcherMetadata::getDispatcherKey)
.collect(MoreCollectors.toSet(notificationTypes.size()));
return dbClient.propertiesDao().hasProjectNotificationSubscribersForDispatchers(projectUuid, dispatcherKeys);
} | [
"public",
"boolean",
"hasProjectSubscribersForTypes",
"(",
"String",
"projectUuid",
",",
"Set",
"<",
"Class",
"<",
"?",
"extends",
"Notification",
">",
">",
"notificationTypes",
")",
"{",
"Set",
"<",
"String",
">",
"dispatcherKeys",
"=",
"handlers",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"handler",
"->",
"notificationTypes",
".",
"stream",
"(",
")",
".",
"anyMatch",
"(",
"notificationType",
"->",
"handler",
".",
"getNotificationClass",
"(",
")",
"==",
"notificationType",
")",
")",
".",
"map",
"(",
"NotificationHandler",
"::",
"getMetadata",
")",
".",
"filter",
"(",
"Optional",
"::",
"isPresent",
")",
".",
"map",
"(",
"Optional",
"::",
"get",
")",
".",
"map",
"(",
"NotificationDispatcherMetadata",
"::",
"getDispatcherKey",
")",
".",
"collect",
"(",
"MoreCollectors",
".",
"toSet",
"(",
"notificationTypes",
".",
"size",
"(",
")",
")",
")",
";",
"return",
"dbClient",
".",
"propertiesDao",
"(",
")",
".",
"hasProjectNotificationSubscribersForDispatchers",
"(",
"projectUuid",
",",
"dispatcherKeys",
")",
";",
"}"
] | Returns true if at least one user is subscribed to at least one notification with given types.
Subscription can be global or on the specific project. | [
"Returns",
"true",
"if",
"at",
"least",
"one",
"user",
"is",
"subscribed",
"to",
"at",
"least",
"one",
"notification",
"with",
"given",
"types",
".",
"Subscription",
"can",
"be",
"global",
"or",
"on",
"the",
"specific",
"project",
"."
] | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationService.java#L157-L167 |
iig-uni-freiburg/SEWOL | ext/org/deckfour/xes/extension/std/XConceptExtension.java | XConceptExtension.assignName | public void assignName(XAttributable element, String name) {
"""
Assigns any log data hierarchy element its name, as defined by this
extension's name attribute.
@param element
Log hierarchy element to assign name to.
@param name
The name to be assigned.
"""
if (name != null && name.trim().length() > 0) {
XAttributeLiteral attr = (XAttributeLiteral) ATTR_NAME.clone();
attr.setValue(name);
element.getAttributes().put(KEY_NAME, attr);
}
} | java | public void assignName(XAttributable element, String name) {
if (name != null && name.trim().length() > 0) {
XAttributeLiteral attr = (XAttributeLiteral) ATTR_NAME.clone();
attr.setValue(name);
element.getAttributes().put(KEY_NAME, attr);
}
} | [
"public",
"void",
"assignName",
"(",
"XAttributable",
"element",
",",
"String",
"name",
")",
"{",
"if",
"(",
"name",
"!=",
"null",
"&&",
"name",
".",
"trim",
"(",
")",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"XAttributeLiteral",
"attr",
"=",
"(",
"XAttributeLiteral",
")",
"ATTR_NAME",
".",
"clone",
"(",
")",
";",
"attr",
".",
"setValue",
"(",
"name",
")",
";",
"element",
".",
"getAttributes",
"(",
")",
".",
"put",
"(",
"KEY_NAME",
",",
"attr",
")",
";",
"}",
"}"
] | Assigns any log data hierarchy element its name, as defined by this
extension's name attribute.
@param element
Log hierarchy element to assign name to.
@param name
The name to be assigned. | [
"Assigns",
"any",
"log",
"data",
"hierarchy",
"element",
"its",
"name",
"as",
"defined",
"by",
"this",
"extension",
"s",
"name",
"attribute",
"."
] | train | https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/ext/org/deckfour/xes/extension/std/XConceptExtension.java#L180-L186 |
graphhopper/graphhopper | core/src/main/java/com/graphhopper/routing/weighting/AbstractWeighting.java | AbstractWeighting.weightingToFileName | public static String weightingToFileName(Weighting w, boolean edgeBased) {
"""
Replaces all characters which are not numbers, characters or underscores with underscores
"""
return toLowerCase(w.toString()).replaceAll("\\|", "_") + (edgeBased ? "_edge" : "_node");
} | java | public static String weightingToFileName(Weighting w, boolean edgeBased) {
return toLowerCase(w.toString()).replaceAll("\\|", "_") + (edgeBased ? "_edge" : "_node");
} | [
"public",
"static",
"String",
"weightingToFileName",
"(",
"Weighting",
"w",
",",
"boolean",
"edgeBased",
")",
"{",
"return",
"toLowerCase",
"(",
"w",
".",
"toString",
"(",
")",
")",
".",
"replaceAll",
"(",
"\"\\\\|\"",
",",
"\"_\"",
")",
"+",
"(",
"edgeBased",
"?",
"\"_edge\"",
":",
"\"_node\"",
")",
";",
"}"
] | Replaces all characters which are not numbers, characters or underscores with underscores | [
"Replaces",
"all",
"characters",
"which",
"are",
"not",
"numbers",
"characters",
"or",
"underscores",
"with",
"underscores"
] | train | https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/weighting/AbstractWeighting.java#L101-L103 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/stat/ns/nstrafficdomain_stats.java | nstrafficdomain_stats.get | public static nstrafficdomain_stats get(nitro_service service, Long td) throws Exception {
"""
Use this API to fetch statistics of nstrafficdomain_stats resource of given name .
"""
nstrafficdomain_stats obj = new nstrafficdomain_stats();
obj.set_td(td);
nstrafficdomain_stats response = (nstrafficdomain_stats) obj.stat_resource(service);
return response;
} | java | public static nstrafficdomain_stats get(nitro_service service, Long td) throws Exception{
nstrafficdomain_stats obj = new nstrafficdomain_stats();
obj.set_td(td);
nstrafficdomain_stats response = (nstrafficdomain_stats) obj.stat_resource(service);
return response;
} | [
"public",
"static",
"nstrafficdomain_stats",
"get",
"(",
"nitro_service",
"service",
",",
"Long",
"td",
")",
"throws",
"Exception",
"{",
"nstrafficdomain_stats",
"obj",
"=",
"new",
"nstrafficdomain_stats",
"(",
")",
";",
"obj",
".",
"set_td",
"(",
"td",
")",
";",
"nstrafficdomain_stats",
"response",
"=",
"(",
"nstrafficdomain_stats",
")",
"obj",
".",
"stat_resource",
"(",
"service",
")",
";",
"return",
"response",
";",
"}"
] | Use this API to fetch statistics of nstrafficdomain_stats resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"statistics",
"of",
"nstrafficdomain_stats",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/ns/nstrafficdomain_stats.java#L201-L206 |
Alluxio/alluxio | shell/src/main/java/alluxio/cli/fsadmin/report/UfsCommand.java | UfsCommand.printMountInfo | public static void printMountInfo(Map<String, MountPointInfo> mountTable) {
"""
Prints mount information for a mount table.
@param mountTable the mount table to get information from
"""
for (Map.Entry<String, MountPointInfo> entry : mountTable.entrySet()) {
String mMountPoint = entry.getKey();
MountPointInfo mountPointInfo = entry.getValue();
long capacityBytes = mountPointInfo.getUfsCapacityBytes();
long usedBytes = mountPointInfo.getUfsUsedBytes();
String usedPercentageInfo = "";
if (capacityBytes > 0) {
int usedPercentage = (int) (100L * usedBytes / capacityBytes);
usedPercentageInfo = String.format("(%s%%)", usedPercentage);
}
String leftAlignFormat = getAlignFormat(mountTable);
System.out.format(leftAlignFormat, mountPointInfo.getUfsUri(), mMountPoint,
mountPointInfo.getUfsType(), FormatUtils.getSizeFromBytes(capacityBytes),
FormatUtils.getSizeFromBytes(usedBytes) + usedPercentageInfo,
mountPointInfo.getReadOnly() ? "" : "not ",
mountPointInfo.getShared() ? "" : "not ");
System.out.println("properties=" + mountPointInfo.getProperties() + ")");
}
} | java | public static void printMountInfo(Map<String, MountPointInfo> mountTable) {
for (Map.Entry<String, MountPointInfo> entry : mountTable.entrySet()) {
String mMountPoint = entry.getKey();
MountPointInfo mountPointInfo = entry.getValue();
long capacityBytes = mountPointInfo.getUfsCapacityBytes();
long usedBytes = mountPointInfo.getUfsUsedBytes();
String usedPercentageInfo = "";
if (capacityBytes > 0) {
int usedPercentage = (int) (100L * usedBytes / capacityBytes);
usedPercentageInfo = String.format("(%s%%)", usedPercentage);
}
String leftAlignFormat = getAlignFormat(mountTable);
System.out.format(leftAlignFormat, mountPointInfo.getUfsUri(), mMountPoint,
mountPointInfo.getUfsType(), FormatUtils.getSizeFromBytes(capacityBytes),
FormatUtils.getSizeFromBytes(usedBytes) + usedPercentageInfo,
mountPointInfo.getReadOnly() ? "" : "not ",
mountPointInfo.getShared() ? "" : "not ");
System.out.println("properties=" + mountPointInfo.getProperties() + ")");
}
} | [
"public",
"static",
"void",
"printMountInfo",
"(",
"Map",
"<",
"String",
",",
"MountPointInfo",
">",
"mountTable",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"MountPointInfo",
">",
"entry",
":",
"mountTable",
".",
"entrySet",
"(",
")",
")",
"{",
"String",
"mMountPoint",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"MountPointInfo",
"mountPointInfo",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"long",
"capacityBytes",
"=",
"mountPointInfo",
".",
"getUfsCapacityBytes",
"(",
")",
";",
"long",
"usedBytes",
"=",
"mountPointInfo",
".",
"getUfsUsedBytes",
"(",
")",
";",
"String",
"usedPercentageInfo",
"=",
"\"\"",
";",
"if",
"(",
"capacityBytes",
">",
"0",
")",
"{",
"int",
"usedPercentage",
"=",
"(",
"int",
")",
"(",
"100L",
"*",
"usedBytes",
"/",
"capacityBytes",
")",
";",
"usedPercentageInfo",
"=",
"String",
".",
"format",
"(",
"\"(%s%%)\"",
",",
"usedPercentage",
")",
";",
"}",
"String",
"leftAlignFormat",
"=",
"getAlignFormat",
"(",
"mountTable",
")",
";",
"System",
".",
"out",
".",
"format",
"(",
"leftAlignFormat",
",",
"mountPointInfo",
".",
"getUfsUri",
"(",
")",
",",
"mMountPoint",
",",
"mountPointInfo",
".",
"getUfsType",
"(",
")",
",",
"FormatUtils",
".",
"getSizeFromBytes",
"(",
"capacityBytes",
")",
",",
"FormatUtils",
".",
"getSizeFromBytes",
"(",
"usedBytes",
")",
"+",
"usedPercentageInfo",
",",
"mountPointInfo",
".",
"getReadOnly",
"(",
")",
"?",
"\"\"",
":",
"\"not \"",
",",
"mountPointInfo",
".",
"getShared",
"(",
")",
"?",
"\"\"",
":",
"\"not \"",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"properties=\"",
"+",
"mountPointInfo",
".",
"getProperties",
"(",
")",
"+",
"\")\"",
")",
";",
"}",
"}"
] | Prints mount information for a mount table.
@param mountTable the mount table to get information from | [
"Prints",
"mount",
"information",
"for",
"a",
"mount",
"table",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fsadmin/report/UfsCommand.java#L54-L77 |
Harium/keel | src/main/java/com/harium/keel/catalano/math/distance/Distance.java | Distance.JensenShannonDivergence | public static double JensenShannonDivergence(double[] p, double[] q) {
"""
Gets the Jensen Shannon divergence.
@param p U vector.
@param q V vector.
@return The Jensen Shannon divergence between u and v.
"""
double[] m = new double[p.length];
for (int i = 0; i < m.length; i++) {
m[i] = (p[i] + q[i]) / 2;
}
return (KullbackLeiblerDivergence(p, m) + KullbackLeiblerDivergence(q, m)) / 2;
} | java | public static double JensenShannonDivergence(double[] p, double[] q) {
double[] m = new double[p.length];
for (int i = 0; i < m.length; i++) {
m[i] = (p[i] + q[i]) / 2;
}
return (KullbackLeiblerDivergence(p, m) + KullbackLeiblerDivergence(q, m)) / 2;
} | [
"public",
"static",
"double",
"JensenShannonDivergence",
"(",
"double",
"[",
"]",
"p",
",",
"double",
"[",
"]",
"q",
")",
"{",
"double",
"[",
"]",
"m",
"=",
"new",
"double",
"[",
"p",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"m",
".",
"length",
";",
"i",
"++",
")",
"{",
"m",
"[",
"i",
"]",
"=",
"(",
"p",
"[",
"i",
"]",
"+",
"q",
"[",
"i",
"]",
")",
"/",
"2",
";",
"}",
"return",
"(",
"KullbackLeiblerDivergence",
"(",
"p",
",",
"m",
")",
"+",
"KullbackLeiblerDivergence",
"(",
"q",
",",
"m",
")",
")",
"/",
"2",
";",
"}"
] | Gets the Jensen Shannon divergence.
@param p U vector.
@param q V vector.
@return The Jensen Shannon divergence between u and v. | [
"Gets",
"the",
"Jensen",
"Shannon",
"divergence",
"."
] | train | https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/distance/Distance.java#L509-L516 |
voldemort/voldemort | src/java/voldemort/tools/admin/command/AdminCommandStream.java | AdminCommandStream.executeHelp | public static void executeHelp(String[] args, PrintStream stream) throws Exception {
"""
Parses command-line input and prints help menu.
@throws Exception
"""
String subCmd = (args.length > 0) ? args[0] : "";
if(subCmd.equals("fetch-entries")) {
SubCommandStreamFetchEntries.printHelp(stream);
} else if(subCmd.equals("fetch-keys")) {
SubCommandStreamFetchKeys.printHelp(stream);
} else if(subCmd.equals("mirror")) {
SubCommandStreamMirror.printHelp(stream);
} else if(subCmd.equals("update-entries")) {
SubCommandStreamUpdateEntries.printHelp(stream);
} else {
printHelp(stream);
}
} | java | public static void executeHelp(String[] args, PrintStream stream) throws Exception {
String subCmd = (args.length > 0) ? args[0] : "";
if(subCmd.equals("fetch-entries")) {
SubCommandStreamFetchEntries.printHelp(stream);
} else if(subCmd.equals("fetch-keys")) {
SubCommandStreamFetchKeys.printHelp(stream);
} else if(subCmd.equals("mirror")) {
SubCommandStreamMirror.printHelp(stream);
} else if(subCmd.equals("update-entries")) {
SubCommandStreamUpdateEntries.printHelp(stream);
} else {
printHelp(stream);
}
} | [
"public",
"static",
"void",
"executeHelp",
"(",
"String",
"[",
"]",
"args",
",",
"PrintStream",
"stream",
")",
"throws",
"Exception",
"{",
"String",
"subCmd",
"=",
"(",
"args",
".",
"length",
">",
"0",
")",
"?",
"args",
"[",
"0",
"]",
":",
"\"\"",
";",
"if",
"(",
"subCmd",
".",
"equals",
"(",
"\"fetch-entries\"",
")",
")",
"{",
"SubCommandStreamFetchEntries",
".",
"printHelp",
"(",
"stream",
")",
";",
"}",
"else",
"if",
"(",
"subCmd",
".",
"equals",
"(",
"\"fetch-keys\"",
")",
")",
"{",
"SubCommandStreamFetchKeys",
".",
"printHelp",
"(",
"stream",
")",
";",
"}",
"else",
"if",
"(",
"subCmd",
".",
"equals",
"(",
"\"mirror\"",
")",
")",
"{",
"SubCommandStreamMirror",
".",
"printHelp",
"(",
"stream",
")",
";",
"}",
"else",
"if",
"(",
"subCmd",
".",
"equals",
"(",
"\"update-entries\"",
")",
")",
"{",
"SubCommandStreamUpdateEntries",
".",
"printHelp",
"(",
"stream",
")",
";",
"}",
"else",
"{",
"printHelp",
"(",
"stream",
")",
";",
"}",
"}"
] | Parses command-line input and prints help menu.
@throws Exception | [
"Parses",
"command",
"-",
"line",
"input",
"and",
"prints",
"help",
"menu",
"."
] | train | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/command/AdminCommandStream.java#L121-L134 |
GenesysPureEngage/workspace-client-java | src/main/java/com/genesys/internal/workspace/api/MediaApi.java | MediaApi.getContentMedia | public ApiSuccessResponse getContentMedia(String mediatype, String id, GetContentData getContentData) throws ApiException {
"""
Get the UCS content of the interaction
Get the UCS content of the interaction
@param mediatype media-type of interaction (required)
@param id id of the interaction (required)
@param getContentData (optional)
@return ApiSuccessResponse
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
"""
ApiResponse<ApiSuccessResponse> resp = getContentMediaWithHttpInfo(mediatype, id, getContentData);
return resp.getData();
} | java | public ApiSuccessResponse getContentMedia(String mediatype, String id, GetContentData getContentData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = getContentMediaWithHttpInfo(mediatype, id, getContentData);
return resp.getData();
} | [
"public",
"ApiSuccessResponse",
"getContentMedia",
"(",
"String",
"mediatype",
",",
"String",
"id",
",",
"GetContentData",
"getContentData",
")",
"throws",
"ApiException",
"{",
"ApiResponse",
"<",
"ApiSuccessResponse",
">",
"resp",
"=",
"getContentMediaWithHttpInfo",
"(",
"mediatype",
",",
"id",
",",
"getContentData",
")",
";",
"return",
"resp",
".",
"getData",
"(",
")",
";",
"}"
] | Get the UCS content of the interaction
Get the UCS content of the interaction
@param mediatype media-type of interaction (required)
@param id id of the interaction (required)
@param getContentData (optional)
@return ApiSuccessResponse
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"Get",
"the",
"UCS",
"content",
"of",
"the",
"interaction",
"Get",
"the",
"UCS",
"content",
"of",
"the",
"interaction"
] | train | https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/MediaApi.java#L1940-L1943 |
Jasig/spring-portlet-contrib | spring-webmvc-portlet-contrib/src/main/java/org/jasig/springframework/web/portlet/context/PortletApplicationContextUtils2.java | PortletApplicationContextUtils2.getPortletApplicationContext | public static PortletApplicationContext getPortletApplicationContext(PortletContext pc, String attrName) {
"""
Find a custom PortletApplicationContext for this web application.
@param pc PortletContext to find the web application context for
@param attrName the name of the PortletContext attribute to look for
@return the desired PortletApplicationContext for this web app, or <code>null</code> if none
"""
Assert.notNull(pc, "PortletContext must not be null");
Object attr = pc.getAttribute(attrName);
if (attr == null) {
return null;
}
if (attr instanceof RuntimeException) {
throw (RuntimeException) attr;
}
if (attr instanceof Error) {
throw (Error) attr;
}
if (attr instanceof Exception) {
throw new IllegalStateException((Exception) attr);
}
if (!(attr instanceof PortletApplicationContext)) {
throw new IllegalStateException("Context attribute is not of type PortletApplicationContext: " + attr.getClass() + " - " + attr);
}
return (PortletApplicationContext) attr;
} | java | public static PortletApplicationContext getPortletApplicationContext(PortletContext pc, String attrName) {
Assert.notNull(pc, "PortletContext must not be null");
Object attr = pc.getAttribute(attrName);
if (attr == null) {
return null;
}
if (attr instanceof RuntimeException) {
throw (RuntimeException) attr;
}
if (attr instanceof Error) {
throw (Error) attr;
}
if (attr instanceof Exception) {
throw new IllegalStateException((Exception) attr);
}
if (!(attr instanceof PortletApplicationContext)) {
throw new IllegalStateException("Context attribute is not of type PortletApplicationContext: " + attr.getClass() + " - " + attr);
}
return (PortletApplicationContext) attr;
} | [
"public",
"static",
"PortletApplicationContext",
"getPortletApplicationContext",
"(",
"PortletContext",
"pc",
",",
"String",
"attrName",
")",
"{",
"Assert",
".",
"notNull",
"(",
"pc",
",",
"\"PortletContext must not be null\"",
")",
";",
"Object",
"attr",
"=",
"pc",
".",
"getAttribute",
"(",
"attrName",
")",
";",
"if",
"(",
"attr",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"attr",
"instanceof",
"RuntimeException",
")",
"{",
"throw",
"(",
"RuntimeException",
")",
"attr",
";",
"}",
"if",
"(",
"attr",
"instanceof",
"Error",
")",
"{",
"throw",
"(",
"Error",
")",
"attr",
";",
"}",
"if",
"(",
"attr",
"instanceof",
"Exception",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"(",
"Exception",
")",
"attr",
")",
";",
"}",
"if",
"(",
"!",
"(",
"attr",
"instanceof",
"PortletApplicationContext",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Context attribute is not of type PortletApplicationContext: \"",
"+",
"attr",
".",
"getClass",
"(",
")",
"+",
"\" - \"",
"+",
"attr",
")",
";",
"}",
"return",
"(",
"PortletApplicationContext",
")",
"attr",
";",
"}"
] | Find a custom PortletApplicationContext for this web application.
@param pc PortletContext to find the web application context for
@param attrName the name of the PortletContext attribute to look for
@return the desired PortletApplicationContext for this web app, or <code>null</code> if none | [
"Find",
"a",
"custom",
"PortletApplicationContext",
"for",
"this",
"web",
"application",
"."
] | train | https://github.com/Jasig/spring-portlet-contrib/blob/719240fa268ddc69900ce9775d9cad3b9c543c6b/spring-webmvc-portlet-contrib/src/main/java/org/jasig/springframework/web/portlet/context/PortletApplicationContextUtils2.java#L118-L137 |
networknt/light-4j | utility/src/main/java/com/networknt/utility/RegExUtils.java | RegExUtils.replacePattern | public static String replacePattern(final String text, final String regex, final String replacement) {
"""
<p>Replaces each substring of the source String that matches the given regular expression with the given
replacement using the {@link Pattern#DOTALL} option. DOTALL is also known as single-line mode in Perl.</p>
This call is a {@code null} safe equivalent to:
<ul>
<li>{@code text.replaceAll("(?s)" + regex, replacement)}</li>
<li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(text).replaceAll(replacement)}</li>
</ul>
<p>A {@code null} reference passed to this method is a no-op.</p>
<pre>
StringUtils.replacePattern(null, *, *) = null
StringUtils.replacePattern("any", (String) null, *) = "any"
StringUtils.replacePattern("any", *, null) = "any"
StringUtils.replacePattern("", "", "zzz") = "zzz"
StringUtils.replacePattern("", ".*", "zzz") = "zzz"
StringUtils.replacePattern("", ".+", "zzz") = ""
StringUtils.replacePattern("<__>\n<__>", "<.*>", "z") = "z"
StringUtils.replacePattern("ABCabc123", "[a-z]", "_") = "ABC___123"
StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "_") = "ABC_123"
StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "") = "ABC123"
StringUtils.replacePattern("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum_dolor_sit"
</pre>
@param text
the source string
@param regex
the regular expression to which this string is to be matched
@param replacement
the string to be substituted for each match
@return The resulting {@code String}
@see #replaceAll(String, String, String)
@see String#replaceAll(String, String)
@see Pattern#DOTALL
"""
if (text == null || regex == null || replacement == null) {
return text;
}
return Pattern.compile(regex, Pattern.DOTALL).matcher(text).replaceAll(replacement);
} | java | public static String replacePattern(final String text, final String regex, final String replacement) {
if (text == null || regex == null || replacement == null) {
return text;
}
return Pattern.compile(regex, Pattern.DOTALL).matcher(text).replaceAll(replacement);
} | [
"public",
"static",
"String",
"replacePattern",
"(",
"final",
"String",
"text",
",",
"final",
"String",
"regex",
",",
"final",
"String",
"replacement",
")",
"{",
"if",
"(",
"text",
"==",
"null",
"||",
"regex",
"==",
"null",
"||",
"replacement",
"==",
"null",
")",
"{",
"return",
"text",
";",
"}",
"return",
"Pattern",
".",
"compile",
"(",
"regex",
",",
"Pattern",
".",
"DOTALL",
")",
".",
"matcher",
"(",
"text",
")",
".",
"replaceAll",
"(",
"replacement",
")",
";",
"}"
] | <p>Replaces each substring of the source String that matches the given regular expression with the given
replacement using the {@link Pattern#DOTALL} option. DOTALL is also known as single-line mode in Perl.</p>
This call is a {@code null} safe equivalent to:
<ul>
<li>{@code text.replaceAll("(?s)" + regex, replacement)}</li>
<li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(text).replaceAll(replacement)}</li>
</ul>
<p>A {@code null} reference passed to this method is a no-op.</p>
<pre>
StringUtils.replacePattern(null, *, *) = null
StringUtils.replacePattern("any", (String) null, *) = "any"
StringUtils.replacePattern("any", *, null) = "any"
StringUtils.replacePattern("", "", "zzz") = "zzz"
StringUtils.replacePattern("", ".*", "zzz") = "zzz"
StringUtils.replacePattern("", ".+", "zzz") = ""
StringUtils.replacePattern("<__>\n<__>", "<.*>", "z") = "z"
StringUtils.replacePattern("ABCabc123", "[a-z]", "_") = "ABC___123"
StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "_") = "ABC_123"
StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "") = "ABC123"
StringUtils.replacePattern("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum_dolor_sit"
</pre>
@param text
the source string
@param regex
the regular expression to which this string is to be matched
@param replacement
the string to be substituted for each match
@return The resulting {@code String}
@see #replaceAll(String, String, String)
@see String#replaceAll(String, String)
@see Pattern#DOTALL | [
"<p",
">",
"Replaces",
"each",
"substring",
"of",
"the",
"source",
"String",
"that",
"matches",
"the",
"given",
"regular",
"expression",
"with",
"the",
"given",
"replacement",
"using",
"the",
"{",
"@link",
"Pattern#DOTALL",
"}",
"option",
".",
"DOTALL",
"is",
"also",
"known",
"as",
"single",
"-",
"line",
"mode",
"in",
"Perl",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/utility/src/main/java/com/networknt/utility/RegExUtils.java#L451-L456 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/MariaDbStatement.java | MariaDbStatement.executeBatch | public int[] executeBatch() throws SQLException {
"""
Execute statements. depending on option, queries mays be rewritten :
<p>those queries will be rewritten if possible to INSERT INTO ... VALUES (...) ; INSERT INTO ...
VALUES (...);</p>
<p>if option rewriteBatchedStatements is set to true, rewritten to INSERT INTO ... VALUES (...),
(...);</p>
@return an array of update counts containing one element for each command in the batch. The
elements of the array are ordered according to the order in which send were added to the
batch.
@throws SQLException if a database access error occurs, this method is called on a closed
<code>Statement</code> or the driver does not support batch statements.
Throws {@link BatchUpdateException} (a subclass of
<code>SQLException</code>) if one of the send sent to the database fails
to execute properly or attempts to return a result set.
@see #addBatch
@see DatabaseMetaData#supportsBatchUpdates
@since 1.3
"""
checkClose();
int size;
if (batchQueries == null || (size = batchQueries.size()) == 0) {
return new int[0];
}
lock.lock();
try {
internalBatchExecution(size);
return results.getCmdInformation().getUpdateCounts();
} catch (SQLException initialSqlEx) {
throw executeBatchExceptionEpilogue(initialSqlEx, size);
} finally {
executeBatchEpilogue();
lock.unlock();
}
} | java | public int[] executeBatch() throws SQLException {
checkClose();
int size;
if (batchQueries == null || (size = batchQueries.size()) == 0) {
return new int[0];
}
lock.lock();
try {
internalBatchExecution(size);
return results.getCmdInformation().getUpdateCounts();
} catch (SQLException initialSqlEx) {
throw executeBatchExceptionEpilogue(initialSqlEx, size);
} finally {
executeBatchEpilogue();
lock.unlock();
}
} | [
"public",
"int",
"[",
"]",
"executeBatch",
"(",
")",
"throws",
"SQLException",
"{",
"checkClose",
"(",
")",
";",
"int",
"size",
";",
"if",
"(",
"batchQueries",
"==",
"null",
"||",
"(",
"size",
"=",
"batchQueries",
".",
"size",
"(",
")",
")",
"==",
"0",
")",
"{",
"return",
"new",
"int",
"[",
"0",
"]",
";",
"}",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"internalBatchExecution",
"(",
"size",
")",
";",
"return",
"results",
".",
"getCmdInformation",
"(",
")",
".",
"getUpdateCounts",
"(",
")",
";",
"}",
"catch",
"(",
"SQLException",
"initialSqlEx",
")",
"{",
"throw",
"executeBatchExceptionEpilogue",
"(",
"initialSqlEx",
",",
"size",
")",
";",
"}",
"finally",
"{",
"executeBatchEpilogue",
"(",
")",
";",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Execute statements. depending on option, queries mays be rewritten :
<p>those queries will be rewritten if possible to INSERT INTO ... VALUES (...) ; INSERT INTO ...
VALUES (...);</p>
<p>if option rewriteBatchedStatements is set to true, rewritten to INSERT INTO ... VALUES (...),
(...);</p>
@return an array of update counts containing one element for each command in the batch. The
elements of the array are ordered according to the order in which send were added to the
batch.
@throws SQLException if a database access error occurs, this method is called on a closed
<code>Statement</code> or the driver does not support batch statements.
Throws {@link BatchUpdateException} (a subclass of
<code>SQLException</code>) if one of the send sent to the database fails
to execute properly or attempts to return a result set.
@see #addBatch
@see DatabaseMetaData#supportsBatchUpdates
@since 1.3 | [
"Execute",
"statements",
".",
"depending",
"on",
"option",
"queries",
"mays",
"be",
"rewritten",
":"
] | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbStatement.java#L1284-L1301 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowController.java | FlowController.handleException | public synchronized ActionForward handleException( Throwable ex, ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response )
throws IOException, ServletException {
"""
Handle the given exception - invoke user code if appropriate and return a destination URI.
@param ex the Exception to handle.
@param mapping the Struts action mapping for current Struts action being processed.
@param form the form-bean (if any) associated with the Struts action being processed. May be null.
@param request the current HttpServletRequest.
@param response the current HttpServletResponse.
@return a Struts ActionForward object that specifies the URI that should be displayed.
@throws ServletException if another Exception is thrown during handling of <code>ex</code>.
"""
PerRequestState prevState = setPerRequestState( new PerRequestState( request, response, mapping ) );
try
{
ExceptionsHandler eh = Handlers.get( getServletContext() ).getExceptionsHandler();
FlowControllerHandlerContext context = getHandlerContext();
// First, put the exception into the request (or other applicable context).
Throwable unwrapped = eh.unwrapException( context, ex );
eh.exposeException( context, unwrapped, mapping );
return eh.handleException( context, unwrapped, mapping, form );
}
finally
{
setPerRequestState( prevState );
}
} | java | public synchronized ActionForward handleException( Throwable ex, ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response )
throws IOException, ServletException
{
PerRequestState prevState = setPerRequestState( new PerRequestState( request, response, mapping ) );
try
{
ExceptionsHandler eh = Handlers.get( getServletContext() ).getExceptionsHandler();
FlowControllerHandlerContext context = getHandlerContext();
// First, put the exception into the request (or other applicable context).
Throwable unwrapped = eh.unwrapException( context, ex );
eh.exposeException( context, unwrapped, mapping );
return eh.handleException( context, unwrapped, mapping, form );
}
finally
{
setPerRequestState( prevState );
}
} | [
"public",
"synchronized",
"ActionForward",
"handleException",
"(",
"Throwable",
"ex",
",",
"ActionMapping",
"mapping",
",",
"ActionForm",
"form",
",",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"IOException",
",",
"ServletException",
"{",
"PerRequestState",
"prevState",
"=",
"setPerRequestState",
"(",
"new",
"PerRequestState",
"(",
"request",
",",
"response",
",",
"mapping",
")",
")",
";",
"try",
"{",
"ExceptionsHandler",
"eh",
"=",
"Handlers",
".",
"get",
"(",
"getServletContext",
"(",
")",
")",
".",
"getExceptionsHandler",
"(",
")",
";",
"FlowControllerHandlerContext",
"context",
"=",
"getHandlerContext",
"(",
")",
";",
"// First, put the exception into the request (or other applicable context).",
"Throwable",
"unwrapped",
"=",
"eh",
".",
"unwrapException",
"(",
"context",
",",
"ex",
")",
";",
"eh",
".",
"exposeException",
"(",
"context",
",",
"unwrapped",
",",
"mapping",
")",
";",
"return",
"eh",
".",
"handleException",
"(",
"context",
",",
"unwrapped",
",",
"mapping",
",",
"form",
")",
";",
"}",
"finally",
"{",
"setPerRequestState",
"(",
"prevState",
")",
";",
"}",
"}"
] | Handle the given exception - invoke user code if appropriate and return a destination URI.
@param ex the Exception to handle.
@param mapping the Struts action mapping for current Struts action being processed.
@param form the form-bean (if any) associated with the Struts action being processed. May be null.
@param request the current HttpServletRequest.
@param response the current HttpServletResponse.
@return a Struts ActionForward object that specifies the URI that should be displayed.
@throws ServletException if another Exception is thrown during handling of <code>ex</code>. | [
"Handle",
"the",
"given",
"exception",
"-",
"invoke",
"user",
"code",
"if",
"appropriate",
"and",
"return",
"a",
"destination",
"URI",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowController.java#L258-L279 |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java | PluralCodeGenerator.buildConditionField | public FieldSpec buildConditionField(int index, Struct<PluralType> branch) {
"""
Constructs a lambda Condition field that represents a chain of AND conditions,
that together is a single branch in an OR condition.
"""
String fieldDoc = PluralRulePrinter.print(branch);
String name = String.format("COND_%d", index);
FieldSpec.Builder field = FieldSpec.builder(PLURAL_CONDITION, name, PRIVATE, STATIC, FINAL)
.addJavadoc(fieldDoc + "\n");
List<Node<PluralType>> expressions = branch.nodes();
CodeBlock.Builder code = CodeBlock.builder();
code.beginControlFlow("(o) ->");
int size = expressions.size();
for (int i = 0; i < size; i++) {
renderExpr(i == 0, code, expressions.get(i));
}
code.addStatement("return true");
code.endControlFlow();
field.initializer(code.build());
return field.build();
} | java | public FieldSpec buildConditionField(int index, Struct<PluralType> branch) {
String fieldDoc = PluralRulePrinter.print(branch);
String name = String.format("COND_%d", index);
FieldSpec.Builder field = FieldSpec.builder(PLURAL_CONDITION, name, PRIVATE, STATIC, FINAL)
.addJavadoc(fieldDoc + "\n");
List<Node<PluralType>> expressions = branch.nodes();
CodeBlock.Builder code = CodeBlock.builder();
code.beginControlFlow("(o) ->");
int size = expressions.size();
for (int i = 0; i < size; i++) {
renderExpr(i == 0, code, expressions.get(i));
}
code.addStatement("return true");
code.endControlFlow();
field.initializer(code.build());
return field.build();
} | [
"public",
"FieldSpec",
"buildConditionField",
"(",
"int",
"index",
",",
"Struct",
"<",
"PluralType",
">",
"branch",
")",
"{",
"String",
"fieldDoc",
"=",
"PluralRulePrinter",
".",
"print",
"(",
"branch",
")",
";",
"String",
"name",
"=",
"String",
".",
"format",
"(",
"\"COND_%d\"",
",",
"index",
")",
";",
"FieldSpec",
".",
"Builder",
"field",
"=",
"FieldSpec",
".",
"builder",
"(",
"PLURAL_CONDITION",
",",
"name",
",",
"PRIVATE",
",",
"STATIC",
",",
"FINAL",
")",
".",
"addJavadoc",
"(",
"fieldDoc",
"+",
"\"\\n\"",
")",
";",
"List",
"<",
"Node",
"<",
"PluralType",
">",
">",
"expressions",
"=",
"branch",
".",
"nodes",
"(",
")",
";",
"CodeBlock",
".",
"Builder",
"code",
"=",
"CodeBlock",
".",
"builder",
"(",
")",
";",
"code",
".",
"beginControlFlow",
"(",
"\"(o) ->\"",
")",
";",
"int",
"size",
"=",
"expressions",
".",
"size",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"++",
")",
"{",
"renderExpr",
"(",
"i",
"==",
"0",
",",
"code",
",",
"expressions",
".",
"get",
"(",
"i",
")",
")",
";",
"}",
"code",
".",
"addStatement",
"(",
"\"return true\"",
")",
";",
"code",
".",
"endControlFlow",
"(",
")",
";",
"field",
".",
"initializer",
"(",
"code",
".",
"build",
"(",
")",
")",
";",
"return",
"field",
".",
"build",
"(",
")",
";",
"}"
] | Constructs a lambda Condition field that represents a chain of AND conditions,
that together is a single branch in an OR condition. | [
"Constructs",
"a",
"lambda",
"Condition",
"field",
"that",
"represents",
"a",
"chain",
"of",
"AND",
"conditions",
"that",
"together",
"is",
"a",
"single",
"branch",
"in",
"an",
"OR",
"condition",
"."
] | train | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java#L211-L231 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.