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
|
---|---|---|---|---|---|---|---|---|---|---|
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/filter/binary/LinearContourLabelChang2004.java | LinearContourLabelChang2004.scanForOne | private int scanForOne(byte[] data , int index , int end ) {
"""
Faster when there's a specialized function which searches for one pixels
"""
while (index < end && data[index] != 1) {
index++;
}
return index;
} | java | private int scanForOne(byte[] data , int index , int end ) {
while (index < end && data[index] != 1) {
index++;
}
return index;
} | [
"private",
"int",
"scanForOne",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"index",
",",
"int",
"end",
")",
"{",
"while",
"(",
"index",
"<",
"end",
"&&",
"data",
"[",
"index",
"]",
"!=",
"1",
")",
"{",
"index",
"++",
";",
"}",
"return",
"index",
";",
"}"
] | Faster when there's a specialized function which searches for one pixels | [
"Faster",
"when",
"there",
"s",
"a",
"specialized",
"function",
"which",
"searches",
"for",
"one",
"pixels"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/filter/binary/LinearContourLabelChang2004.java#L157-L162 |
pravega/pravega | controller/src/main/java/io/pravega/controller/store/stream/PravegaTablesStoreHelper.java | PravegaTablesStoreHelper.invalidateCache | public void invalidateCache(String table, String key) {
"""
Method to invalidate cached value in the cache for the specified table.
@param table table name
@param key key to invalidate
"""
cache.invalidateCache(new TableCacheKey<>(table, key, x -> null));
} | java | public void invalidateCache(String table, String key) {
cache.invalidateCache(new TableCacheKey<>(table, key, x -> null));
} | [
"public",
"void",
"invalidateCache",
"(",
"String",
"table",
",",
"String",
"key",
")",
"{",
"cache",
".",
"invalidateCache",
"(",
"new",
"TableCacheKey",
"<>",
"(",
"table",
",",
"key",
",",
"x",
"->",
"null",
")",
")",
";",
"}"
] | Method to invalidate cached value in the cache for the specified table.
@param table table name
@param key key to invalidate | [
"Method",
"to",
"invalidate",
"cached",
"value",
"in",
"the",
"cache",
"for",
"the",
"specified",
"table",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/store/stream/PravegaTablesStoreHelper.java#L115-L117 |
BioPAX/Paxtools | pattern/src/main/java/org/biopax/paxtools/pattern/miner/ControlsStateChangeDetailedMiner.java | ControlsStateChangeDetailedMiner.getValue | @Override
public String getValue(Match m, int col) {
"""
Creates values for the result file columns.
@param m current match
@param col current column
@return value of the given match at the given column
"""
switch(col)
{
case 0:
{
return getGeneSymbol(m, "controller ER");
}
case 1:
{
return concat(getModifications(m, "controller simple PE", "controller PE"), " ");
}
case 2:
{
return getGeneSymbol(m, "changed ER");
}
case 3:
{
return concat(getDeltaModifications(m,
"input simple PE", "input PE", "output simple PE", "output PE")[0], " ");
}
case 4:
{
return concat(getDeltaModifications(m,
"input simple PE", "input PE", "output simple PE", "output PE")[1], " ");
}
default: throw new RuntimeException("Invalid col number: " + col);
}
} | java | @Override
public String getValue(Match m, int col)
{
switch(col)
{
case 0:
{
return getGeneSymbol(m, "controller ER");
}
case 1:
{
return concat(getModifications(m, "controller simple PE", "controller PE"), " ");
}
case 2:
{
return getGeneSymbol(m, "changed ER");
}
case 3:
{
return concat(getDeltaModifications(m,
"input simple PE", "input PE", "output simple PE", "output PE")[0], " ");
}
case 4:
{
return concat(getDeltaModifications(m,
"input simple PE", "input PE", "output simple PE", "output PE")[1], " ");
}
default: throw new RuntimeException("Invalid col number: " + col);
}
} | [
"@",
"Override",
"public",
"String",
"getValue",
"(",
"Match",
"m",
",",
"int",
"col",
")",
"{",
"switch",
"(",
"col",
")",
"{",
"case",
"0",
":",
"{",
"return",
"getGeneSymbol",
"(",
"m",
",",
"\"controller ER\"",
")",
";",
"}",
"case",
"1",
":",
"{",
"return",
"concat",
"(",
"getModifications",
"(",
"m",
",",
"\"controller simple PE\"",
",",
"\"controller PE\"",
")",
",",
"\" \"",
")",
";",
"}",
"case",
"2",
":",
"{",
"return",
"getGeneSymbol",
"(",
"m",
",",
"\"changed ER\"",
")",
";",
"}",
"case",
"3",
":",
"{",
"return",
"concat",
"(",
"getDeltaModifications",
"(",
"m",
",",
"\"input simple PE\"",
",",
"\"input PE\"",
",",
"\"output simple PE\"",
",",
"\"output PE\"",
")",
"[",
"0",
"]",
",",
"\" \"",
")",
";",
"}",
"case",
"4",
":",
"{",
"return",
"concat",
"(",
"getDeltaModifications",
"(",
"m",
",",
"\"input simple PE\"",
",",
"\"input PE\"",
",",
"\"output simple PE\"",
",",
"\"output PE\"",
")",
"[",
"1",
"]",
",",
"\" \"",
")",
";",
"}",
"default",
":",
"throw",
"new",
"RuntimeException",
"(",
"\"Invalid col number: \"",
"+",
"col",
")",
";",
"}",
"}"
] | Creates values for the result file columns.
@param m current match
@param col current column
@return value of the given match at the given column | [
"Creates",
"values",
"for",
"the",
"result",
"file",
"columns",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/miner/ControlsStateChangeDetailedMiner.java#L71-L100 |
buschmais/jqa-maven3-plugin | src/main/java/com/buschmais/jqassistant/plugin/maven3/impl/scanner/MavenModelScannerPlugin.java | MavenModelScannerPlugin.addPlugins | private void addPlugins(BaseProfileDescriptor pomDescriptor, BuildBase build, ScannerContext scannerContext) {
"""
Adds information about plugins.
@param pomDescriptor
The descriptor for the current POM.
@param build
Information required to build the project.
@param scannerContext
The scanner context.
"""
if (null == build) {
return;
}
List<Plugin> plugins = build.getPlugins();
List<MavenPluginDescriptor> pluginDescriptors = createMavenPluginDescriptors(plugins, scannerContext);
pomDescriptor.getPlugins().addAll(pluginDescriptors);
} | java | private void addPlugins(BaseProfileDescriptor pomDescriptor, BuildBase build, ScannerContext scannerContext) {
if (null == build) {
return;
}
List<Plugin> plugins = build.getPlugins();
List<MavenPluginDescriptor> pluginDescriptors = createMavenPluginDescriptors(plugins, scannerContext);
pomDescriptor.getPlugins().addAll(pluginDescriptors);
} | [
"private",
"void",
"addPlugins",
"(",
"BaseProfileDescriptor",
"pomDescriptor",
",",
"BuildBase",
"build",
",",
"ScannerContext",
"scannerContext",
")",
"{",
"if",
"(",
"null",
"==",
"build",
")",
"{",
"return",
";",
"}",
"List",
"<",
"Plugin",
">",
"plugins",
"=",
"build",
".",
"getPlugins",
"(",
")",
";",
"List",
"<",
"MavenPluginDescriptor",
">",
"pluginDescriptors",
"=",
"createMavenPluginDescriptors",
"(",
"plugins",
",",
"scannerContext",
")",
";",
"pomDescriptor",
".",
"getPlugins",
"(",
")",
".",
"addAll",
"(",
"pluginDescriptors",
")",
";",
"}"
] | Adds information about plugins.
@param pomDescriptor
The descriptor for the current POM.
@param build
Information required to build the project.
@param scannerContext
The scanner context. | [
"Adds",
"information",
"about",
"plugins",
"."
] | train | https://github.com/buschmais/jqa-maven3-plugin/blob/6c6e2dca56de6d5b8ceeb2f28982fb6d7c98778f/src/main/java/com/buschmais/jqassistant/plugin/maven3/impl/scanner/MavenModelScannerPlugin.java#L524-L531 |
Azure/azure-sdk-for-java | containerinstance/resource-manager/v2018_02_01_preview/src/main/java/com/microsoft/azure/management/containerinstance/v2018_02_01_preview/implementation/ContainerGroupsInner.java | ContainerGroupsInner.getByResourceGroup | public ContainerGroupInner getByResourceGroup(String resourceGroupName, String containerGroupName) {
"""
Get the properties of the specified container group.
Gets the properties of the specified container group in the specified subscription and resource group. The operation returns the properties of each container group including containers, image registry credentials, restart policy, IP address type, OS type, state, and volumes.
@param resourceGroupName The name of the resource group.
@param containerGroupName The name of the container group.
@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 ContainerGroupInner object if successful.
"""
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, containerGroupName).toBlocking().single().body();
} | java | public ContainerGroupInner getByResourceGroup(String resourceGroupName, String containerGroupName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, containerGroupName).toBlocking().single().body();
} | [
"public",
"ContainerGroupInner",
"getByResourceGroup",
"(",
"String",
"resourceGroupName",
",",
"String",
"containerGroupName",
")",
"{",
"return",
"getByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"containerGroupName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Get the properties of the specified container group.
Gets the properties of the specified container group in the specified subscription and resource group. The operation returns the properties of each container group including containers, image registry credentials, restart policy, IP address type, OS type, state, and volumes.
@param resourceGroupName The name of the resource group.
@param containerGroupName The name of the container group.
@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 ContainerGroupInner object if successful. | [
"Get",
"the",
"properties",
"of",
"the",
"specified",
"container",
"group",
".",
"Gets",
"the",
"properties",
"of",
"the",
"specified",
"container",
"group",
"in",
"the",
"specified",
"subscription",
"and",
"resource",
"group",
".",
"The",
"operation",
"returns",
"the",
"properties",
"of",
"each",
"container",
"group",
"including",
"containers",
"image",
"registry",
"credentials",
"restart",
"policy",
"IP",
"address",
"type",
"OS",
"type",
"state",
"and",
"volumes",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerinstance/resource-manager/v2018_02_01_preview/src/main/java/com/microsoft/azure/management/containerinstance/v2018_02_01_preview/implementation/ContainerGroupsInner.java#L350-L352 |
amzn/ion-java | src/com/amazon/ion/impl/_Private_Utils.java | _Private_Utils.iterate | public static Iterator<IonValue> iterate(ValueFactory valueFactory,
IonReader input) {
"""
Create a value iterator from a reader.
Primarily a trampoline for access permission.
"""
return new IonIteratorImpl(valueFactory, input);
} | java | public static Iterator<IonValue> iterate(ValueFactory valueFactory,
IonReader input)
{
return new IonIteratorImpl(valueFactory, input);
} | [
"public",
"static",
"Iterator",
"<",
"IonValue",
">",
"iterate",
"(",
"ValueFactory",
"valueFactory",
",",
"IonReader",
"input",
")",
"{",
"return",
"new",
"IonIteratorImpl",
"(",
"valueFactory",
",",
"input",
")",
";",
"}"
] | Create a value iterator from a reader.
Primarily a trampoline for access permission. | [
"Create",
"a",
"value",
"iterator",
"from",
"a",
"reader",
".",
"Primarily",
"a",
"trampoline",
"for",
"access",
"permission",
"."
] | train | https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/impl/_Private_Utils.java#L661-L665 |
JodaOrg/joda-time | src/main/java/org/joda/time/Instant.java | Instant.withDurationAdded | public Instant withDurationAdded(ReadableDuration durationToAdd, int scalar) {
"""
Gets a copy of this instant with the specified duration added.
<p>
If the addition is zero, then <code>this</code> is returned.
@param durationToAdd the duration to add to this one, null means zero
@param scalar the amount of times to add, such as -1 to subtract once
@return a copy of this instant with the duration added
@throws ArithmeticException if the new instant exceeds the capacity of a long
"""
if (durationToAdd == null || scalar == 0) {
return this;
}
return withDurationAdded(durationToAdd.getMillis(), scalar);
} | java | public Instant withDurationAdded(ReadableDuration durationToAdd, int scalar) {
if (durationToAdd == null || scalar == 0) {
return this;
}
return withDurationAdded(durationToAdd.getMillis(), scalar);
} | [
"public",
"Instant",
"withDurationAdded",
"(",
"ReadableDuration",
"durationToAdd",
",",
"int",
"scalar",
")",
"{",
"if",
"(",
"durationToAdd",
"==",
"null",
"||",
"scalar",
"==",
"0",
")",
"{",
"return",
"this",
";",
"}",
"return",
"withDurationAdded",
"(",
"durationToAdd",
".",
"getMillis",
"(",
")",
",",
"scalar",
")",
";",
"}"
] | Gets a copy of this instant with the specified duration added.
<p>
If the addition is zero, then <code>this</code> is returned.
@param durationToAdd the duration to add to this one, null means zero
@param scalar the amount of times to add, such as -1 to subtract once
@return a copy of this instant with the duration added
@throws ArithmeticException if the new instant exceeds the capacity of a long | [
"Gets",
"a",
"copy",
"of",
"this",
"instant",
"with",
"the",
"specified",
"duration",
"added",
".",
"<p",
">",
"If",
"the",
"addition",
"is",
"zero",
"then",
"<code",
">",
"this<",
"/",
"code",
">",
"is",
"returned",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/Instant.java#L220-L225 |
azkaban/azkaban | az-hdfs-viewer/src/main/java/azkaban/viewer/hdfs/utils/SerDeUtilsWrapper.java | SerDeUtilsWrapper.getJSON | public static String getJSON(Object obj, ObjectInspector objIns) {
"""
Get serialized json using an orc object and corresponding object
inspector Adapted from
{@link org.apache.hadoop.hive.serde2.SerDeUtils#getJSONString(Object, ObjectInspector)}
@param obj
@param objIns
@return
"""
StringBuilder sb = new StringBuilder();
buildJSONString(sb, obj, objIns);
return sb.toString();
} | java | public static String getJSON(Object obj, ObjectInspector objIns) {
StringBuilder sb = new StringBuilder();
buildJSONString(sb, obj, objIns);
return sb.toString();
} | [
"public",
"static",
"String",
"getJSON",
"(",
"Object",
"obj",
",",
"ObjectInspector",
"objIns",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"buildJSONString",
"(",
"sb",
",",
"obj",
",",
"objIns",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | Get serialized json using an orc object and corresponding object
inspector Adapted from
{@link org.apache.hadoop.hive.serde2.SerDeUtils#getJSONString(Object, ObjectInspector)}
@param obj
@param objIns
@return | [
"Get",
"serialized",
"json",
"using",
"an",
"orc",
"object",
"and",
"corresponding",
"object",
"inspector",
"Adapted",
"from",
"{",
"@link",
"org",
".",
"apache",
".",
"hadoop",
".",
"hive",
".",
"serde2",
".",
"SerDeUtils#getJSONString",
"(",
"Object",
"ObjectInspector",
")",
"}"
] | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/az-hdfs-viewer/src/main/java/azkaban/viewer/hdfs/utils/SerDeUtilsWrapper.java#L46-L50 |
apache/spark | core/src/main/java/org/apache/spark/util/collection/unsafe/sort/UnsafeInMemorySorter.java | UnsafeInMemorySorter.insertRecord | public void insertRecord(long recordPointer, long keyPrefix, boolean prefixIsNull) {
"""
Inserts a record to be sorted. Assumes that the record pointer points to a record length
stored as a 4-byte integer, followed by the record's bytes.
@param recordPointer pointer to a record in a data page, encoded by {@link TaskMemoryManager}.
@param keyPrefix a user-defined key prefix
"""
if (!hasSpaceForAnotherRecord()) {
throw new IllegalStateException("There is no space for new record");
}
if (prefixIsNull && radixSortSupport != null) {
// Swap forward a non-null record to make room for this one at the beginning of the array.
array.set(pos, array.get(nullBoundaryPos));
pos++;
array.set(pos, array.get(nullBoundaryPos + 1));
pos++;
// Place this record in the vacated position.
array.set(nullBoundaryPos, recordPointer);
nullBoundaryPos++;
array.set(nullBoundaryPos, keyPrefix);
nullBoundaryPos++;
} else {
array.set(pos, recordPointer);
pos++;
array.set(pos, keyPrefix);
pos++;
}
} | java | public void insertRecord(long recordPointer, long keyPrefix, boolean prefixIsNull) {
if (!hasSpaceForAnotherRecord()) {
throw new IllegalStateException("There is no space for new record");
}
if (prefixIsNull && radixSortSupport != null) {
// Swap forward a non-null record to make room for this one at the beginning of the array.
array.set(pos, array.get(nullBoundaryPos));
pos++;
array.set(pos, array.get(nullBoundaryPos + 1));
pos++;
// Place this record in the vacated position.
array.set(nullBoundaryPos, recordPointer);
nullBoundaryPos++;
array.set(nullBoundaryPos, keyPrefix);
nullBoundaryPos++;
} else {
array.set(pos, recordPointer);
pos++;
array.set(pos, keyPrefix);
pos++;
}
} | [
"public",
"void",
"insertRecord",
"(",
"long",
"recordPointer",
",",
"long",
"keyPrefix",
",",
"boolean",
"prefixIsNull",
")",
"{",
"if",
"(",
"!",
"hasSpaceForAnotherRecord",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"There is no space for new record\"",
")",
";",
"}",
"if",
"(",
"prefixIsNull",
"&&",
"radixSortSupport",
"!=",
"null",
")",
"{",
"// Swap forward a non-null record to make room for this one at the beginning of the array.",
"array",
".",
"set",
"(",
"pos",
",",
"array",
".",
"get",
"(",
"nullBoundaryPos",
")",
")",
";",
"pos",
"++",
";",
"array",
".",
"set",
"(",
"pos",
",",
"array",
".",
"get",
"(",
"nullBoundaryPos",
"+",
"1",
")",
")",
";",
"pos",
"++",
";",
"// Place this record in the vacated position.",
"array",
".",
"set",
"(",
"nullBoundaryPos",
",",
"recordPointer",
")",
";",
"nullBoundaryPos",
"++",
";",
"array",
".",
"set",
"(",
"nullBoundaryPos",
",",
"keyPrefix",
")",
";",
"nullBoundaryPos",
"++",
";",
"}",
"else",
"{",
"array",
".",
"set",
"(",
"pos",
",",
"recordPointer",
")",
";",
"pos",
"++",
";",
"array",
".",
"set",
"(",
"pos",
",",
"keyPrefix",
")",
";",
"pos",
"++",
";",
"}",
"}"
] | Inserts a record to be sorted. Assumes that the record pointer points to a record length
stored as a 4-byte integer, followed by the record's bytes.
@param recordPointer pointer to a record in a data page, encoded by {@link TaskMemoryManager}.
@param keyPrefix a user-defined key prefix | [
"Inserts",
"a",
"record",
"to",
"be",
"sorted",
".",
"Assumes",
"that",
"the",
"record",
"pointer",
"points",
"to",
"a",
"record",
"length",
"stored",
"as",
"a",
"4",
"-",
"byte",
"integer",
"followed",
"by",
"the",
"record",
"s",
"bytes",
"."
] | train | https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/core/src/main/java/org/apache/spark/util/collection/unsafe/sort/UnsafeInMemorySorter.java#L239-L260 |
aspectran/aspectran | core/src/main/java/com/aspectran/core/util/MethodUtils.java | MethodUtils.invokeGetter | public static Object invokeGetter(Object object, String getterName, Object arg)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
"""
Gets an Object property from a bean.
@param object the bean
@param getterName the property name or getter method name
@param arg use this argument
@return the property value (as an Object)
@throws NoSuchMethodException the no such method exception
@throws IllegalAccessException the illegal access exception
@throws InvocationTargetException the invocation target exception
"""
Object[] args = { arg };
return invokeGetter(object, getterName, args);
} | java | public static Object invokeGetter(Object object, String getterName, Object arg)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Object[] args = { arg };
return invokeGetter(object, getterName, args);
} | [
"public",
"static",
"Object",
"invokeGetter",
"(",
"Object",
"object",
",",
"String",
"getterName",
",",
"Object",
"arg",
")",
"throws",
"NoSuchMethodException",
",",
"IllegalAccessException",
",",
"InvocationTargetException",
"{",
"Object",
"[",
"]",
"args",
"=",
"{",
"arg",
"}",
";",
"return",
"invokeGetter",
"(",
"object",
",",
"getterName",
",",
"args",
")",
";",
"}"
] | Gets an Object property from a bean.
@param object the bean
@param getterName the property name or getter method name
@param arg use this argument
@return the property value (as an Object)
@throws NoSuchMethodException the no such method exception
@throws IllegalAccessException the illegal access exception
@throws InvocationTargetException the invocation target exception | [
"Gets",
"an",
"Object",
"property",
"from",
"a",
"bean",
"."
] | train | https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/MethodUtils.java#L110-L114 |
xetorthio/jedis | src/main/java/redis/clients/jedis/util/JedisClusterCRC16.java | JedisClusterCRC16.getCRC16 | public static int getCRC16(byte[] bytes, int s, int e) {
"""
Create a CRC16 checksum from the bytes. implementation is from mp911de/lettuce, modified with
some more optimizations
@param bytes
@param s
@param e
@return CRC16 as integer value See <a
href="https://github.com/xetorthio/jedis/pull/733#issuecomment-55840331">Issue 733</a>
"""
int crc = 0x0000;
for (int i = s; i < e; i++) {
crc = ((crc << 8) ^ LOOKUP_TABLE[((crc >>> 8) ^ (bytes[i] & 0xFF)) & 0xFF]);
}
return crc & 0xFFFF;
} | java | public static int getCRC16(byte[] bytes, int s, int e) {
int crc = 0x0000;
for (int i = s; i < e; i++) {
crc = ((crc << 8) ^ LOOKUP_TABLE[((crc >>> 8) ^ (bytes[i] & 0xFF)) & 0xFF]);
}
return crc & 0xFFFF;
} | [
"public",
"static",
"int",
"getCRC16",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"s",
",",
"int",
"e",
")",
"{",
"int",
"crc",
"=",
"0x0000",
";",
"for",
"(",
"int",
"i",
"=",
"s",
";",
"i",
"<",
"e",
";",
"i",
"++",
")",
"{",
"crc",
"=",
"(",
"(",
"crc",
"<<",
"8",
")",
"^",
"LOOKUP_TABLE",
"[",
"(",
"(",
"crc",
">>>",
"8",
")",
"^",
"(",
"bytes",
"[",
"i",
"]",
"&",
"0xFF",
")",
")",
"&",
"0xFF",
"]",
")",
";",
"}",
"return",
"crc",
"&",
"0xFFFF",
";",
"}"
] | Create a CRC16 checksum from the bytes. implementation is from mp911de/lettuce, modified with
some more optimizations
@param bytes
@param s
@param e
@return CRC16 as integer value See <a
href="https://github.com/xetorthio/jedis/pull/733#issuecomment-55840331">Issue 733</a> | [
"Create",
"a",
"CRC16",
"checksum",
"from",
"the",
"bytes",
".",
"implementation",
"is",
"from",
"mp911de",
"/",
"lettuce",
"modified",
"with",
"some",
"more",
"optimizations"
] | train | https://github.com/xetorthio/jedis/blob/ef4ab403f9d8fd88bd05092fea96de2e9db0bede/src/main/java/redis/clients/jedis/util/JedisClusterCRC16.java#L83-L90 |
jbossas/jboss-invocation | src/main/java/org/jboss/invocation/proxy/AbstractSubclassFactory.java | AbstractSubclassFactory.overrideHashcode | protected boolean overrideHashcode(MethodBodyCreator creator) {
"""
Override the hashCode method using the given {@link MethodBodyCreator}.
@param creator the method body creator to use
@return true if the method was not already overridden
"""
Method hashCode = null;
ClassMetadataSource data = reflectionMetadataSource.getClassMetadata(Object.class);
try {
hashCode = data.getMethod("hashCode", Integer.TYPE);
} catch (Exception e) {
throw new RuntimeException(e);
}
return overrideMethod(hashCode, MethodIdentifier.getIdentifierForMethod(hashCode), creator);
} | java | protected boolean overrideHashcode(MethodBodyCreator creator) {
Method hashCode = null;
ClassMetadataSource data = reflectionMetadataSource.getClassMetadata(Object.class);
try {
hashCode = data.getMethod("hashCode", Integer.TYPE);
} catch (Exception e) {
throw new RuntimeException(e);
}
return overrideMethod(hashCode, MethodIdentifier.getIdentifierForMethod(hashCode), creator);
} | [
"protected",
"boolean",
"overrideHashcode",
"(",
"MethodBodyCreator",
"creator",
")",
"{",
"Method",
"hashCode",
"=",
"null",
";",
"ClassMetadataSource",
"data",
"=",
"reflectionMetadataSource",
".",
"getClassMetadata",
"(",
"Object",
".",
"class",
")",
";",
"try",
"{",
"hashCode",
"=",
"data",
".",
"getMethod",
"(",
"\"hashCode\"",
",",
"Integer",
".",
"TYPE",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"return",
"overrideMethod",
"(",
"hashCode",
",",
"MethodIdentifier",
".",
"getIdentifierForMethod",
"(",
"hashCode",
")",
",",
"creator",
")",
";",
"}"
] | Override the hashCode method using the given {@link MethodBodyCreator}.
@param creator the method body creator to use
@return true if the method was not already overridden | [
"Override",
"the",
"hashCode",
"method",
"using",
"the",
"given",
"{",
"@link",
"MethodBodyCreator",
"}",
"."
] | train | https://github.com/jbossas/jboss-invocation/blob/f72586a554264cbc78fcdad9fdd3e84b833249c9/src/main/java/org/jboss/invocation/proxy/AbstractSubclassFactory.java#L272-L282 |
indeedeng/proctor | proctor-common/src/main/java/com/indeed/proctor/common/ProctorUtils.java | ProctorUtils.generateSpecification | public static TestSpecification generateSpecification(@Nonnull final TestDefinition testDefinition) {
"""
Generates a usable test specification for a given test definition
Uses the first bucket as the fallback value
@param testDefinition a {@link TestDefinition}
@return a {@link TestSpecification} which corresponding to given test definition.
"""
final TestSpecification testSpecification = new TestSpecification();
// Sort buckets by value ascending
final Map<String,Integer> buckets = Maps.newLinkedHashMap();
final List<TestBucket> testDefinitionBuckets = Ordering.from(new Comparator<TestBucket>() {
@Override
public int compare(final TestBucket lhs, final TestBucket rhs) {
return Ints.compare(lhs.getValue(), rhs.getValue());
}
}).immutableSortedCopy(testDefinition.getBuckets());
int fallbackValue = -1;
if(testDefinitionBuckets.size() > 0) {
final TestBucket firstBucket = testDefinitionBuckets.get(0);
fallbackValue = firstBucket.getValue(); // buckets are sorted, choose smallest value as the fallback value
final PayloadSpecification payloadSpecification = new PayloadSpecification();
if(firstBucket.getPayload() != null && !firstBucket.getPayload().equals(Payload.EMPTY_PAYLOAD)) {
final PayloadType payloadType = PayloadType.payloadTypeForName(firstBucket.getPayload().fetchType());
payloadSpecification.setType(payloadType.payloadTypeName);
if (payloadType == PayloadType.MAP) {
final Map<String, String> payloadSpecificationSchema = new HashMap<String, String>();
for (Map.Entry<String, Object> entry : firstBucket.getPayload().getMap().entrySet()) {
payloadSpecificationSchema.put(entry.getKey(), PayloadType.payloadTypeForValue(entry.getValue()).payloadTypeName);
}
payloadSpecification.setSchema(payloadSpecificationSchema);
}
testSpecification.setPayload(payloadSpecification);
}
for (int i = 0; i < testDefinitionBuckets.size(); i++) {
final TestBucket bucket = testDefinitionBuckets.get(i);
buckets.put(bucket.getName(), bucket.getValue());
}
}
testSpecification.setBuckets(buckets);
testSpecification.setDescription(testDefinition.getDescription());
testSpecification.setFallbackValue(fallbackValue);
return testSpecification;
} | java | public static TestSpecification generateSpecification(@Nonnull final TestDefinition testDefinition) {
final TestSpecification testSpecification = new TestSpecification();
// Sort buckets by value ascending
final Map<String,Integer> buckets = Maps.newLinkedHashMap();
final List<TestBucket> testDefinitionBuckets = Ordering.from(new Comparator<TestBucket>() {
@Override
public int compare(final TestBucket lhs, final TestBucket rhs) {
return Ints.compare(lhs.getValue(), rhs.getValue());
}
}).immutableSortedCopy(testDefinition.getBuckets());
int fallbackValue = -1;
if(testDefinitionBuckets.size() > 0) {
final TestBucket firstBucket = testDefinitionBuckets.get(0);
fallbackValue = firstBucket.getValue(); // buckets are sorted, choose smallest value as the fallback value
final PayloadSpecification payloadSpecification = new PayloadSpecification();
if(firstBucket.getPayload() != null && !firstBucket.getPayload().equals(Payload.EMPTY_PAYLOAD)) {
final PayloadType payloadType = PayloadType.payloadTypeForName(firstBucket.getPayload().fetchType());
payloadSpecification.setType(payloadType.payloadTypeName);
if (payloadType == PayloadType.MAP) {
final Map<String, String> payloadSpecificationSchema = new HashMap<String, String>();
for (Map.Entry<String, Object> entry : firstBucket.getPayload().getMap().entrySet()) {
payloadSpecificationSchema.put(entry.getKey(), PayloadType.payloadTypeForValue(entry.getValue()).payloadTypeName);
}
payloadSpecification.setSchema(payloadSpecificationSchema);
}
testSpecification.setPayload(payloadSpecification);
}
for (int i = 0; i < testDefinitionBuckets.size(); i++) {
final TestBucket bucket = testDefinitionBuckets.get(i);
buckets.put(bucket.getName(), bucket.getValue());
}
}
testSpecification.setBuckets(buckets);
testSpecification.setDescription(testDefinition.getDescription());
testSpecification.setFallbackValue(fallbackValue);
return testSpecification;
} | [
"public",
"static",
"TestSpecification",
"generateSpecification",
"(",
"@",
"Nonnull",
"final",
"TestDefinition",
"testDefinition",
")",
"{",
"final",
"TestSpecification",
"testSpecification",
"=",
"new",
"TestSpecification",
"(",
")",
";",
"// Sort buckets by value ascending",
"final",
"Map",
"<",
"String",
",",
"Integer",
">",
"buckets",
"=",
"Maps",
".",
"newLinkedHashMap",
"(",
")",
";",
"final",
"List",
"<",
"TestBucket",
">",
"testDefinitionBuckets",
"=",
"Ordering",
".",
"from",
"(",
"new",
"Comparator",
"<",
"TestBucket",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"int",
"compare",
"(",
"final",
"TestBucket",
"lhs",
",",
"final",
"TestBucket",
"rhs",
")",
"{",
"return",
"Ints",
".",
"compare",
"(",
"lhs",
".",
"getValue",
"(",
")",
",",
"rhs",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
")",
".",
"immutableSortedCopy",
"(",
"testDefinition",
".",
"getBuckets",
"(",
")",
")",
";",
"int",
"fallbackValue",
"=",
"-",
"1",
";",
"if",
"(",
"testDefinitionBuckets",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"final",
"TestBucket",
"firstBucket",
"=",
"testDefinitionBuckets",
".",
"get",
"(",
"0",
")",
";",
"fallbackValue",
"=",
"firstBucket",
".",
"getValue",
"(",
")",
";",
"// buckets are sorted, choose smallest value as the fallback value",
"final",
"PayloadSpecification",
"payloadSpecification",
"=",
"new",
"PayloadSpecification",
"(",
")",
";",
"if",
"(",
"firstBucket",
".",
"getPayload",
"(",
")",
"!=",
"null",
"&&",
"!",
"firstBucket",
".",
"getPayload",
"(",
")",
".",
"equals",
"(",
"Payload",
".",
"EMPTY_PAYLOAD",
")",
")",
"{",
"final",
"PayloadType",
"payloadType",
"=",
"PayloadType",
".",
"payloadTypeForName",
"(",
"firstBucket",
".",
"getPayload",
"(",
")",
".",
"fetchType",
"(",
")",
")",
";",
"payloadSpecification",
".",
"setType",
"(",
"payloadType",
".",
"payloadTypeName",
")",
";",
"if",
"(",
"payloadType",
"==",
"PayloadType",
".",
"MAP",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"payloadSpecificationSchema",
"=",
"new",
"HashMap",
"<",
"String",
",",
"String",
">",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Object",
">",
"entry",
":",
"firstBucket",
".",
"getPayload",
"(",
")",
".",
"getMap",
"(",
")",
".",
"entrySet",
"(",
")",
")",
"{",
"payloadSpecificationSchema",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"PayloadType",
".",
"payloadTypeForValue",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
".",
"payloadTypeName",
")",
";",
"}",
"payloadSpecification",
".",
"setSchema",
"(",
"payloadSpecificationSchema",
")",
";",
"}",
"testSpecification",
".",
"setPayload",
"(",
"payloadSpecification",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"testDefinitionBuckets",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"final",
"TestBucket",
"bucket",
"=",
"testDefinitionBuckets",
".",
"get",
"(",
"i",
")",
";",
"buckets",
".",
"put",
"(",
"bucket",
".",
"getName",
"(",
")",
",",
"bucket",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"testSpecification",
".",
"setBuckets",
"(",
"buckets",
")",
";",
"testSpecification",
".",
"setDescription",
"(",
"testDefinition",
".",
"getDescription",
"(",
")",
")",
";",
"testSpecification",
".",
"setFallbackValue",
"(",
"fallbackValue",
")",
";",
"return",
"testSpecification",
";",
"}"
] | Generates a usable test specification for a given test definition
Uses the first bucket as the fallback value
@param testDefinition a {@link TestDefinition}
@return a {@link TestSpecification} which corresponding to given test definition. | [
"Generates",
"a",
"usable",
"test",
"specification",
"for",
"a",
"given",
"test",
"definition",
"Uses",
"the",
"first",
"bucket",
"as",
"the",
"fallback",
"value"
] | train | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-common/src/main/java/com/indeed/proctor/common/ProctorUtils.java#L924-L962 |
mojohaus/mrm | mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/MD5DigestFileEntry.java | MD5DigestFileEntry.getContent | private byte[] getContent()
throws IOException {
"""
Generates the digest.
@return the digest.
@throws IOException if the backing entry could not be read.
@since 1.0
"""
InputStream is = null;
try
{
MessageDigest digest = MessageDigest.getInstance( "MD5" );
digest.reset();
byte[] buffer = new byte[8192];
int read;
try
{
is = entry.getInputStream();
while ( ( read = is.read( buffer ) ) > 0 )
{
digest.update( buffer, 0, read );
}
}
catch ( IOException e )
{
if ( is != null )
{
throw e;
}
}
final String md5 = StringUtils.leftPad( new BigInteger( 1, digest.digest() ).toString( 16 ), 32, "0" );
return md5.getBytes();
}
catch ( NoSuchAlgorithmException e )
{
IOException ioe = new IOException( "Unable to calculate hash" );
ioe.initCause( e );
throw ioe;
}
finally
{
IOUtils.closeQuietly( is );
}
} | java | private byte[] getContent()
throws IOException
{
InputStream is = null;
try
{
MessageDigest digest = MessageDigest.getInstance( "MD5" );
digest.reset();
byte[] buffer = new byte[8192];
int read;
try
{
is = entry.getInputStream();
while ( ( read = is.read( buffer ) ) > 0 )
{
digest.update( buffer, 0, read );
}
}
catch ( IOException e )
{
if ( is != null )
{
throw e;
}
}
final String md5 = StringUtils.leftPad( new BigInteger( 1, digest.digest() ).toString( 16 ), 32, "0" );
return md5.getBytes();
}
catch ( NoSuchAlgorithmException e )
{
IOException ioe = new IOException( "Unable to calculate hash" );
ioe.initCause( e );
throw ioe;
}
finally
{
IOUtils.closeQuietly( is );
}
} | [
"private",
"byte",
"[",
"]",
"getContent",
"(",
")",
"throws",
"IOException",
"{",
"InputStream",
"is",
"=",
"null",
";",
"try",
"{",
"MessageDigest",
"digest",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"\"MD5\"",
")",
";",
"digest",
".",
"reset",
"(",
")",
";",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"8192",
"]",
";",
"int",
"read",
";",
"try",
"{",
"is",
"=",
"entry",
".",
"getInputStream",
"(",
")",
";",
"while",
"(",
"(",
"read",
"=",
"is",
".",
"read",
"(",
"buffer",
")",
")",
">",
"0",
")",
"{",
"digest",
".",
"update",
"(",
"buffer",
",",
"0",
",",
"read",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"if",
"(",
"is",
"!=",
"null",
")",
"{",
"throw",
"e",
";",
"}",
"}",
"final",
"String",
"md5",
"=",
"StringUtils",
".",
"leftPad",
"(",
"new",
"BigInteger",
"(",
"1",
",",
"digest",
".",
"digest",
"(",
")",
")",
".",
"toString",
"(",
"16",
")",
",",
"32",
",",
"\"0\"",
")",
";",
"return",
"md5",
".",
"getBytes",
"(",
")",
";",
"}",
"catch",
"(",
"NoSuchAlgorithmException",
"e",
")",
"{",
"IOException",
"ioe",
"=",
"new",
"IOException",
"(",
"\"Unable to calculate hash\"",
")",
";",
"ioe",
".",
"initCause",
"(",
"e",
")",
";",
"throw",
"ioe",
";",
"}",
"finally",
"{",
"IOUtils",
".",
"closeQuietly",
"(",
"is",
")",
";",
"}",
"}"
] | Generates the digest.
@return the digest.
@throws IOException if the backing entry could not be read.
@since 1.0 | [
"Generates",
"the",
"digest",
"."
] | train | https://github.com/mojohaus/mrm/blob/ecbe54a1866f210c10bf2e9274b63d4804d6a151/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/MD5DigestFileEntry.java#L103-L141 |
jbundle/jbundle | base/screen/model/src/main/java/org/jbundle/base/screen/model/BasePanel.java | BasePanel.onForm | public BasePanel onForm(Record recordMain, int iDocMode, boolean bReadCurrentRecord, int iCommandOptions, Map<String,Object> properties) {
"""
Create a data entry screen with this main record.
(null means use this screen's main record)
@param recordMain The main record for the new form.
@param iDocMode The document type of the new form.
@param bReadCurrentRecord Sync the new screen with my current record?
@param bUseSameWindow Use the same window?
@return true if successful.
"""
boolean bLinkGridToQuery = false;
if ((iCommandOptions & ScreenConstants.USE_NEW_WINDOW) == ScreenConstants.USE_NEW_WINDOW)
bLinkGridToQuery = true;
return this.onForm(recordMain, iDocMode, bReadCurrentRecord, iCommandOptions, bLinkGridToQuery, properties);
} | java | public BasePanel onForm(Record recordMain, int iDocMode, boolean bReadCurrentRecord, int iCommandOptions, Map<String,Object> properties)
{
boolean bLinkGridToQuery = false;
if ((iCommandOptions & ScreenConstants.USE_NEW_WINDOW) == ScreenConstants.USE_NEW_WINDOW)
bLinkGridToQuery = true;
return this.onForm(recordMain, iDocMode, bReadCurrentRecord, iCommandOptions, bLinkGridToQuery, properties);
} | [
"public",
"BasePanel",
"onForm",
"(",
"Record",
"recordMain",
",",
"int",
"iDocMode",
",",
"boolean",
"bReadCurrentRecord",
",",
"int",
"iCommandOptions",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"{",
"boolean",
"bLinkGridToQuery",
"=",
"false",
";",
"if",
"(",
"(",
"iCommandOptions",
"&",
"ScreenConstants",
".",
"USE_NEW_WINDOW",
")",
"==",
"ScreenConstants",
".",
"USE_NEW_WINDOW",
")",
"bLinkGridToQuery",
"=",
"true",
";",
"return",
"this",
".",
"onForm",
"(",
"recordMain",
",",
"iDocMode",
",",
"bReadCurrentRecord",
",",
"iCommandOptions",
",",
"bLinkGridToQuery",
",",
"properties",
")",
";",
"}"
] | Create a data entry screen with this main record.
(null means use this screen's main record)
@param recordMain The main record for the new form.
@param iDocMode The document type of the new form.
@param bReadCurrentRecord Sync the new screen with my current record?
@param bUseSameWindow Use the same window?
@return true if successful. | [
"Create",
"a",
"data",
"entry",
"screen",
"with",
"this",
"main",
"record",
".",
"(",
"null",
"means",
"use",
"this",
"screen",
"s",
"main",
"record",
")"
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/BasePanel.java#L808-L814 |
xsonorg/xson | src/main/java/org/xson/core/asm/ClassReader.java | ClassReader.readConst | public Object readConst(final int item, final char[] buf) {
"""
Reads a numeric or string constant pool item in {@link #b b}. <i>This
method is intended for {@link Attribute} sub classes, and is normally not
needed by class generators or adapters.</i>
@param item the index of a constant pool item.
@param buf buffer to be used to read the item. This buffer must be
sufficiently large. It is not automatically resized.
@return the {@link Integer}, {@link Float}, {@link Long},
{@link Double}, {@link String} or {@link Type} corresponding to
the given constant pool item.
"""
int index = items[item];
switch (b[index - 1]) {
case ClassWriter.INT:
return new Integer(readInt(index));
case ClassWriter.FLOAT:
return new Float(Float.intBitsToFloat(readInt(index)));
case ClassWriter.LONG:
return new Long(readLong(index));
case ClassWriter.DOUBLE:
return new Double(Double.longBitsToDouble(readLong(index)));
case ClassWriter.CLASS:
return Type.getObjectType(readUTF8(index, buf));
// case ClassWriter.STR:
default:
return readUTF8(index, buf);
}
} | java | public Object readConst(final int item, final char[] buf) {
int index = items[item];
switch (b[index - 1]) {
case ClassWriter.INT:
return new Integer(readInt(index));
case ClassWriter.FLOAT:
return new Float(Float.intBitsToFloat(readInt(index)));
case ClassWriter.LONG:
return new Long(readLong(index));
case ClassWriter.DOUBLE:
return new Double(Double.longBitsToDouble(readLong(index)));
case ClassWriter.CLASS:
return Type.getObjectType(readUTF8(index, buf));
// case ClassWriter.STR:
default:
return readUTF8(index, buf);
}
} | [
"public",
"Object",
"readConst",
"(",
"final",
"int",
"item",
",",
"final",
"char",
"[",
"]",
"buf",
")",
"{",
"int",
"index",
"=",
"items",
"[",
"item",
"]",
";",
"switch",
"(",
"b",
"[",
"index",
"-",
"1",
"]",
")",
"{",
"case",
"ClassWriter",
".",
"INT",
":",
"return",
"new",
"Integer",
"(",
"readInt",
"(",
"index",
")",
")",
";",
"case",
"ClassWriter",
".",
"FLOAT",
":",
"return",
"new",
"Float",
"(",
"Float",
".",
"intBitsToFloat",
"(",
"readInt",
"(",
"index",
")",
")",
")",
";",
"case",
"ClassWriter",
".",
"LONG",
":",
"return",
"new",
"Long",
"(",
"readLong",
"(",
"index",
")",
")",
";",
"case",
"ClassWriter",
".",
"DOUBLE",
":",
"return",
"new",
"Double",
"(",
"Double",
".",
"longBitsToDouble",
"(",
"readLong",
"(",
"index",
")",
")",
")",
";",
"case",
"ClassWriter",
".",
"CLASS",
":",
"return",
"Type",
".",
"getObjectType",
"(",
"readUTF8",
"(",
"index",
",",
"buf",
")",
")",
";",
"// case ClassWriter.STR:",
"default",
":",
"return",
"readUTF8",
"(",
"index",
",",
"buf",
")",
";",
"}",
"}"
] | Reads a numeric or string constant pool item in {@link #b b}. <i>This
method is intended for {@link Attribute} sub classes, and is normally not
needed by class generators or adapters.</i>
@param item the index of a constant pool item.
@param buf buffer to be used to read the item. This buffer must be
sufficiently large. It is not automatically resized.
@return the {@link Integer}, {@link Float}, {@link Long},
{@link Double}, {@link String} or {@link Type} corresponding to
the given constant pool item. | [
"Reads",
"a",
"numeric",
"or",
"string",
"constant",
"pool",
"item",
"in",
"{",
"@link",
"#b",
"b",
"}",
".",
"<i",
">",
"This",
"method",
"is",
"intended",
"for",
"{",
"@link",
"Attribute",
"}",
"sub",
"classes",
"and",
"is",
"normally",
"not",
"needed",
"by",
"class",
"generators",
"or",
"adapters",
".",
"<",
"/",
"i",
">"
] | train | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/ClassReader.java#L1991-L2008 |
apache/incubator-druid | sql/src/main/java/org/apache/druid/sql/calcite/planner/Calcites.java | Calcites.jodaToCalciteTimestampString | public static TimestampString jodaToCalciteTimestampString(final DateTime dateTime, final DateTimeZone timeZone) {
"""
Calcite expects TIMESTAMP literals to be represented by TimestampStrings in the local time zone.
@param dateTime joda timestamp
@param timeZone session time zone
@return Calcite style Calendar, appropriate for literals
"""
// The replaceAll is because Calcite doesn't like trailing zeroes in its fractional seconds part.
String timestampString = TRAILING_ZEROS
.matcher(CALCITE_TIMESTAMP_PRINTER.print(dateTime.withZone(timeZone)))
.replaceAll("");
return new TimestampString(timestampString);
} | java | public static TimestampString jodaToCalciteTimestampString(final DateTime dateTime, final DateTimeZone timeZone)
{
// The replaceAll is because Calcite doesn't like trailing zeroes in its fractional seconds part.
String timestampString = TRAILING_ZEROS
.matcher(CALCITE_TIMESTAMP_PRINTER.print(dateTime.withZone(timeZone)))
.replaceAll("");
return new TimestampString(timestampString);
} | [
"public",
"static",
"TimestampString",
"jodaToCalciteTimestampString",
"(",
"final",
"DateTime",
"dateTime",
",",
"final",
"DateTimeZone",
"timeZone",
")",
"{",
"// The replaceAll is because Calcite doesn't like trailing zeroes in its fractional seconds part.",
"String",
"timestampString",
"=",
"TRAILING_ZEROS",
".",
"matcher",
"(",
"CALCITE_TIMESTAMP_PRINTER",
".",
"print",
"(",
"dateTime",
".",
"withZone",
"(",
"timeZone",
")",
")",
")",
".",
"replaceAll",
"(",
"\"\"",
")",
";",
"return",
"new",
"TimestampString",
"(",
"timestampString",
")",
";",
"}"
] | Calcite expects TIMESTAMP literals to be represented by TimestampStrings in the local time zone.
@param dateTime joda timestamp
@param timeZone session time zone
@return Calcite style Calendar, appropriate for literals | [
"Calcite",
"expects",
"TIMESTAMP",
"literals",
"to",
"be",
"represented",
"by",
"TimestampStrings",
"in",
"the",
"local",
"time",
"zone",
"."
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/sql/src/main/java/org/apache/druid/sql/calcite/planner/Calcites.java#L251-L258 |
tdomzal/junit-docker-rule | src/main/java/pl/domzal/junit/docker/rule/DockerRuleMountBuilder.java | DockerRuleMountBuilder.toUnixStylePath | static String toUnixStylePath(String absolutePath) {
"""
Convert any absolute path (no matter Unix or Windows style) to Unix style
path compatible to docker volume mount from syntax.
"""
if (StringUtils.isEmpty(absolutePath)) {
throw new IllegalStateException("empty path given");
}
if (absolutePath.startsWith("/")) {
return absolutePath;
} else if (absolutePath.length()>=2 && Character.isLetter(absolutePath.charAt(0)) && ':' == absolutePath.charAt(1) && '\\' == absolutePath.charAt(2)) {
char driveLetter = Character.toLowerCase(absolutePath.charAt(0));
String drivePath = StringUtils.substringAfter(absolutePath, ":");
String drivePathUnixStyle = drivePath.replace('\\', '/');
return "/"+driveLetter+drivePathUnixStyle;
} else {
throw new IllegalStateException(String.format("unable to convert path %s", absolutePath));
}
} | java | static String toUnixStylePath(String absolutePath) {
if (StringUtils.isEmpty(absolutePath)) {
throw new IllegalStateException("empty path given");
}
if (absolutePath.startsWith("/")) {
return absolutePath;
} else if (absolutePath.length()>=2 && Character.isLetter(absolutePath.charAt(0)) && ':' == absolutePath.charAt(1) && '\\' == absolutePath.charAt(2)) {
char driveLetter = Character.toLowerCase(absolutePath.charAt(0));
String drivePath = StringUtils.substringAfter(absolutePath, ":");
String drivePathUnixStyle = drivePath.replace('\\', '/');
return "/"+driveLetter+drivePathUnixStyle;
} else {
throw new IllegalStateException(String.format("unable to convert path %s", absolutePath));
}
} | [
"static",
"String",
"toUnixStylePath",
"(",
"String",
"absolutePath",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"absolutePath",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"empty path given\"",
")",
";",
"}",
"if",
"(",
"absolutePath",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
"{",
"return",
"absolutePath",
";",
"}",
"else",
"if",
"(",
"absolutePath",
".",
"length",
"(",
")",
">=",
"2",
"&&",
"Character",
".",
"isLetter",
"(",
"absolutePath",
".",
"charAt",
"(",
"0",
")",
")",
"&&",
"'",
"'",
"==",
"absolutePath",
".",
"charAt",
"(",
"1",
")",
"&&",
"'",
"'",
"==",
"absolutePath",
".",
"charAt",
"(",
"2",
")",
")",
"{",
"char",
"driveLetter",
"=",
"Character",
".",
"toLowerCase",
"(",
"absolutePath",
".",
"charAt",
"(",
"0",
")",
")",
";",
"String",
"drivePath",
"=",
"StringUtils",
".",
"substringAfter",
"(",
"absolutePath",
",",
"\":\"",
")",
";",
"String",
"drivePathUnixStyle",
"=",
"drivePath",
".",
"replace",
"(",
"'",
"'",
",",
"'",
"'",
")",
";",
"return",
"\"/\"",
"+",
"driveLetter",
"+",
"drivePathUnixStyle",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"String",
".",
"format",
"(",
"\"unable to convert path %s\"",
",",
"absolutePath",
")",
")",
";",
"}",
"}"
] | Convert any absolute path (no matter Unix or Windows style) to Unix style
path compatible to docker volume mount from syntax. | [
"Convert",
"any",
"absolute",
"path",
"(",
"no",
"matter",
"Unix",
"or",
"Windows",
"style",
")",
"to",
"Unix",
"style",
"path",
"compatible",
"to",
"docker",
"volume",
"mount",
"from",
"syntax",
"."
] | train | https://github.com/tdomzal/junit-docker-rule/blob/5a0ba2fd095d201530d3f9e614bc5e88d0afaeb2/src/main/java/pl/domzal/junit/docker/rule/DockerRuleMountBuilder.java#L83-L97 |
carewebframework/carewebframework-core | org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/dialog/DialogResponse.java | DialogResponse.isResponseType | private boolean isResponseType(String text, String label) {
"""
Returns true if the text corresponds to a specific response type.
@param text Text to test.
@param label The label.
@return True if represents the specified response type.
"""
return label.equals(text) || StrUtil.formatMessage(label).equals(text);
} | java | private boolean isResponseType(String text, String label) {
return label.equals(text) || StrUtil.formatMessage(label).equals(text);
} | [
"private",
"boolean",
"isResponseType",
"(",
"String",
"text",
",",
"String",
"label",
")",
"{",
"return",
"label",
".",
"equals",
"(",
"text",
")",
"||",
"StrUtil",
".",
"formatMessage",
"(",
"label",
")",
".",
"equals",
"(",
"text",
")",
";",
"}"
] | Returns true if the text corresponds to a specific response type.
@param text Text to test.
@param label The label.
@return True if represents the specified response type. | [
"Returns",
"true",
"if",
"the",
"text",
"corresponds",
"to",
"a",
"specific",
"response",
"type",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/dialog/DialogResponse.java#L180-L182 |
languagetool-org/languagetool | languagetool-core/src/main/java/org/languagetool/AnalyzedTokenReadings.java | AnalyzedTokenReadings.leaveReading | public void leaveReading(AnalyzedToken token) {
"""
Removes all readings but the one that matches the token given.
@param token Token to be matched
@since 1.5
"""
List<AnalyzedToken> l = new ArrayList<>();
AnalyzedToken tmpTok = new AnalyzedToken(token.getToken(), token.getPOSTag(), token.getLemma());
tmpTok.setWhitespaceBefore(isWhitespaceBefore);
for (AnalyzedToken anTokReading : anTokReadings) {
if (anTokReading.matches(tmpTok)) {
l.add(anTokReading);
}
}
if (l.isEmpty()) {
l.add(new AnalyzedToken(this.token, null, null));
l.get(0).setWhitespaceBefore(isWhitespaceBefore);
}
anTokReadings = l.toArray(new AnalyzedToken[0]);
setNoRealPOStag();
hasSameLemmas = areLemmasSame();
} | java | public void leaveReading(AnalyzedToken token) {
List<AnalyzedToken> l = new ArrayList<>();
AnalyzedToken tmpTok = new AnalyzedToken(token.getToken(), token.getPOSTag(), token.getLemma());
tmpTok.setWhitespaceBefore(isWhitespaceBefore);
for (AnalyzedToken anTokReading : anTokReadings) {
if (anTokReading.matches(tmpTok)) {
l.add(anTokReading);
}
}
if (l.isEmpty()) {
l.add(new AnalyzedToken(this.token, null, null));
l.get(0).setWhitespaceBefore(isWhitespaceBefore);
}
anTokReadings = l.toArray(new AnalyzedToken[0]);
setNoRealPOStag();
hasSameLemmas = areLemmasSame();
} | [
"public",
"void",
"leaveReading",
"(",
"AnalyzedToken",
"token",
")",
"{",
"List",
"<",
"AnalyzedToken",
">",
"l",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"AnalyzedToken",
"tmpTok",
"=",
"new",
"AnalyzedToken",
"(",
"token",
".",
"getToken",
"(",
")",
",",
"token",
".",
"getPOSTag",
"(",
")",
",",
"token",
".",
"getLemma",
"(",
")",
")",
";",
"tmpTok",
".",
"setWhitespaceBefore",
"(",
"isWhitespaceBefore",
")",
";",
"for",
"(",
"AnalyzedToken",
"anTokReading",
":",
"anTokReadings",
")",
"{",
"if",
"(",
"anTokReading",
".",
"matches",
"(",
"tmpTok",
")",
")",
"{",
"l",
".",
"add",
"(",
"anTokReading",
")",
";",
"}",
"}",
"if",
"(",
"l",
".",
"isEmpty",
"(",
")",
")",
"{",
"l",
".",
"add",
"(",
"new",
"AnalyzedToken",
"(",
"this",
".",
"token",
",",
"null",
",",
"null",
")",
")",
";",
"l",
".",
"get",
"(",
"0",
")",
".",
"setWhitespaceBefore",
"(",
"isWhitespaceBefore",
")",
";",
"}",
"anTokReadings",
"=",
"l",
".",
"toArray",
"(",
"new",
"AnalyzedToken",
"[",
"0",
"]",
")",
";",
"setNoRealPOStag",
"(",
")",
";",
"hasSameLemmas",
"=",
"areLemmasSame",
"(",
")",
";",
"}"
] | Removes all readings but the one that matches the token given.
@param token Token to be matched
@since 1.5 | [
"Removes",
"all",
"readings",
"but",
"the",
"one",
"that",
"matches",
"the",
"token",
"given",
"."
] | train | https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/AnalyzedTokenReadings.java#L305-L321 |
alkacon/opencms-core | src/org/opencms/search/CmsSearchManager.java | CmsSearchManager.rebuildIndex | public void rebuildIndex(String indexName, I_CmsReport report) throws CmsException {
"""
Rebuilds (if required creates) the index with the given name.<p>
@param indexName the name of the index to rebuild
@param report the report object to write messages (or <code>null</code>)
@throws CmsException if something goes wrong
"""
try {
SEARCH_MANAGER_LOCK.lock();
// get the search index by name
I_CmsSearchIndex index = getIndex(indexName);
// update the index
updateIndex(index, report, null);
// clean up the extraction result cache
cleanExtractionCache();
} finally {
SEARCH_MANAGER_LOCK.unlock();
}
} | java | public void rebuildIndex(String indexName, I_CmsReport report) throws CmsException {
try {
SEARCH_MANAGER_LOCK.lock();
// get the search index by name
I_CmsSearchIndex index = getIndex(indexName);
// update the index
updateIndex(index, report, null);
// clean up the extraction result cache
cleanExtractionCache();
} finally {
SEARCH_MANAGER_LOCK.unlock();
}
} | [
"public",
"void",
"rebuildIndex",
"(",
"String",
"indexName",
",",
"I_CmsReport",
"report",
")",
"throws",
"CmsException",
"{",
"try",
"{",
"SEARCH_MANAGER_LOCK",
".",
"lock",
"(",
")",
";",
"// get the search index by name",
"I_CmsSearchIndex",
"index",
"=",
"getIndex",
"(",
"indexName",
")",
";",
"// update the index",
"updateIndex",
"(",
"index",
",",
"report",
",",
"null",
")",
";",
"// clean up the extraction result cache",
"cleanExtractionCache",
"(",
")",
";",
"}",
"finally",
"{",
"SEARCH_MANAGER_LOCK",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Rebuilds (if required creates) the index with the given name.<p>
@param indexName the name of the index to rebuild
@param report the report object to write messages (or <code>null</code>)
@throws CmsException if something goes wrong | [
"Rebuilds",
"(",
"if",
"required",
"creates",
")",
"the",
"index",
"with",
"the",
"given",
"name",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/CmsSearchManager.java#L1708-L1721 |
aws/aws-sdk-java | aws-java-sdk-fms/src/main/java/com/amazonaws/services/fms/model/PolicyComplianceStatus.java | PolicyComplianceStatus.withIssueInfoMap | public PolicyComplianceStatus withIssueInfoMap(java.util.Map<String, String> issueInfoMap) {
"""
<p>
Details about problems with dependent services, such as AWS WAF or AWS Config, that are causing a resource to be
non-compliant. The details include the name of the dependent service and the error message received that
indicates the problem with the service.
</p>
@param issueInfoMap
Details about problems with dependent services, such as AWS WAF or AWS Config, that are causing a resource
to be non-compliant. The details include the name of the dependent service and the error message received
that indicates the problem with the service.
@return Returns a reference to this object so that method calls can be chained together.
"""
setIssueInfoMap(issueInfoMap);
return this;
} | java | public PolicyComplianceStatus withIssueInfoMap(java.util.Map<String, String> issueInfoMap) {
setIssueInfoMap(issueInfoMap);
return this;
} | [
"public",
"PolicyComplianceStatus",
"withIssueInfoMap",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"issueInfoMap",
")",
"{",
"setIssueInfoMap",
"(",
"issueInfoMap",
")",
";",
"return",
"this",
";",
"}"
] | <p>
Details about problems with dependent services, such as AWS WAF or AWS Config, that are causing a resource to be
non-compliant. The details include the name of the dependent service and the error message received that
indicates the problem with the service.
</p>
@param issueInfoMap
Details about problems with dependent services, such as AWS WAF or AWS Config, that are causing a resource
to be non-compliant. The details include the name of the dependent service and the error message received
that indicates the problem with the service.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"Details",
"about",
"problems",
"with",
"dependent",
"services",
"such",
"as",
"AWS",
"WAF",
"or",
"AWS",
"Config",
"that",
"are",
"causing",
"a",
"resource",
"to",
"be",
"non",
"-",
"compliant",
".",
"The",
"details",
"include",
"the",
"name",
"of",
"the",
"dependent",
"service",
"and",
"the",
"error",
"message",
"received",
"that",
"indicates",
"the",
"problem",
"with",
"the",
"service",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-fms/src/main/java/com/amazonaws/services/fms/model/PolicyComplianceStatus.java#L394-L397 |
googleads/googleads-java-lib | modules/ads_lib_appengine/src/main/java/com/google/api/ads/common/lib/soap/jaxws/JaxWsHandler.java | JaxWsHandler.getHeader | @Override
public Object getHeader(BindingProvider soapClient, String headerName) {
"""
Returns a SOAP header from the given SOAP client, if it exists.
@param soapClient the SOAP client to check for the given header
@param headerName the name of the header being looked for
@return the header element, if it exists
"""
for (SOAPElement addedHeader : getContextHandlerFromClient(soapClient).getAddedHeaders()) {
if (addedHeader.getNodeName().equals(headerName)) {
return addedHeader;
}
}
return null;
} | java | @Override
public Object getHeader(BindingProvider soapClient, String headerName) {
for (SOAPElement addedHeader : getContextHandlerFromClient(soapClient).getAddedHeaders()) {
if (addedHeader.getNodeName().equals(headerName)) {
return addedHeader;
}
}
return null;
} | [
"@",
"Override",
"public",
"Object",
"getHeader",
"(",
"BindingProvider",
"soapClient",
",",
"String",
"headerName",
")",
"{",
"for",
"(",
"SOAPElement",
"addedHeader",
":",
"getContextHandlerFromClient",
"(",
"soapClient",
")",
".",
"getAddedHeaders",
"(",
")",
")",
"{",
"if",
"(",
"addedHeader",
".",
"getNodeName",
"(",
")",
".",
"equals",
"(",
"headerName",
")",
")",
"{",
"return",
"addedHeader",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Returns a SOAP header from the given SOAP client, if it exists.
@param soapClient the SOAP client to check for the given header
@param headerName the name of the header being looked for
@return the header element, if it exists | [
"Returns",
"a",
"SOAP",
"header",
"from",
"the",
"given",
"SOAP",
"client",
"if",
"it",
"exists",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/ads_lib_appengine/src/main/java/com/google/api/ads/common/lib/soap/jaxws/JaxWsHandler.java#L85-L93 |
nakamura5akihito/six-util | src/main/java/jp/go/aist/six/util/search/RelationalBinding.java | RelationalBinding.lessThanBinding | public static RelationalBinding lessThanBinding(
final String property,
final Object value
) {
"""
Creates a 'LESS_THAN' binding.
@param property
the property.
@param value
the value to which the property should be related.
@return
a 'LESS_THAN' binding.
"""
return (new RelationalBinding( property, Relation.LESS_THAN, value ));
} | java | public static RelationalBinding lessThanBinding(
final String property,
final Object value
)
{
return (new RelationalBinding( property, Relation.LESS_THAN, value ));
} | [
"public",
"static",
"RelationalBinding",
"lessThanBinding",
"(",
"final",
"String",
"property",
",",
"final",
"Object",
"value",
")",
"{",
"return",
"(",
"new",
"RelationalBinding",
"(",
"property",
",",
"Relation",
".",
"LESS_THAN",
",",
"value",
")",
")",
";",
"}"
] | Creates a 'LESS_THAN' binding.
@param property
the property.
@param value
the value to which the property should be related.
@return
a 'LESS_THAN' binding. | [
"Creates",
"a",
"LESS_THAN",
"binding",
"."
] | train | https://github.com/nakamura5akihito/six-util/blob/a6db388a345e220cea2b1fa6324d15c80c6278b6/src/main/java/jp/go/aist/six/util/search/RelationalBinding.java#L90-L96 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java | CPMeasurementUnitPersistenceImpl.countByG_K_T | @Override
public int countByG_K_T(long groupId, String key, int type) {
"""
Returns the number of cp measurement units where groupId = ? and key = ? and type = ?.
@param groupId the group ID
@param key the key
@param type the type
@return the number of matching cp measurement units
"""
FinderPath finderPath = FINDER_PATH_COUNT_BY_G_K_T;
Object[] finderArgs = new Object[] { groupId, key, type };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(4);
query.append(_SQL_COUNT_CPMEASUREMENTUNIT_WHERE);
query.append(_FINDER_COLUMN_G_K_T_GROUPID_2);
boolean bindKey = false;
if (key == null) {
query.append(_FINDER_COLUMN_G_K_T_KEY_1);
}
else if (key.equals("")) {
query.append(_FINDER_COLUMN_G_K_T_KEY_3);
}
else {
bindKey = true;
query.append(_FINDER_COLUMN_G_K_T_KEY_2);
}
query.append(_FINDER_COLUMN_G_K_T_TYPE_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(groupId);
if (bindKey) {
qPos.add(StringUtil.toLowerCase(key));
}
qPos.add(type);
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
} | java | @Override
public int countByG_K_T(long groupId, String key, int type) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_G_K_T;
Object[] finderArgs = new Object[] { groupId, key, type };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(4);
query.append(_SQL_COUNT_CPMEASUREMENTUNIT_WHERE);
query.append(_FINDER_COLUMN_G_K_T_GROUPID_2);
boolean bindKey = false;
if (key == null) {
query.append(_FINDER_COLUMN_G_K_T_KEY_1);
}
else if (key.equals("")) {
query.append(_FINDER_COLUMN_G_K_T_KEY_3);
}
else {
bindKey = true;
query.append(_FINDER_COLUMN_G_K_T_KEY_2);
}
query.append(_FINDER_COLUMN_G_K_T_TYPE_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(groupId);
if (bindKey) {
qPos.add(StringUtil.toLowerCase(key));
}
qPos.add(type);
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
} | [
"@",
"Override",
"public",
"int",
"countByG_K_T",
"(",
"long",
"groupId",
",",
"String",
"key",
",",
"int",
"type",
")",
"{",
"FinderPath",
"finderPath",
"=",
"FINDER_PATH_COUNT_BY_G_K_T",
";",
"Object",
"[",
"]",
"finderArgs",
"=",
"new",
"Object",
"[",
"]",
"{",
"groupId",
",",
"key",
",",
"type",
"}",
";",
"Long",
"count",
"=",
"(",
"Long",
")",
"finderCache",
".",
"getResult",
"(",
"finderPath",
",",
"finderArgs",
",",
"this",
")",
";",
"if",
"(",
"count",
"==",
"null",
")",
"{",
"StringBundler",
"query",
"=",
"new",
"StringBundler",
"(",
"4",
")",
";",
"query",
".",
"append",
"(",
"_SQL_COUNT_CPMEASUREMENTUNIT_WHERE",
")",
";",
"query",
".",
"append",
"(",
"_FINDER_COLUMN_G_K_T_GROUPID_2",
")",
";",
"boolean",
"bindKey",
"=",
"false",
";",
"if",
"(",
"key",
"==",
"null",
")",
"{",
"query",
".",
"append",
"(",
"_FINDER_COLUMN_G_K_T_KEY_1",
")",
";",
"}",
"else",
"if",
"(",
"key",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"query",
".",
"append",
"(",
"_FINDER_COLUMN_G_K_T_KEY_3",
")",
";",
"}",
"else",
"{",
"bindKey",
"=",
"true",
";",
"query",
".",
"append",
"(",
"_FINDER_COLUMN_G_K_T_KEY_2",
")",
";",
"}",
"query",
".",
"append",
"(",
"_FINDER_COLUMN_G_K_T_TYPE_2",
")",
";",
"String",
"sql",
"=",
"query",
".",
"toString",
"(",
")",
";",
"Session",
"session",
"=",
"null",
";",
"try",
"{",
"session",
"=",
"openSession",
"(",
")",
";",
"Query",
"q",
"=",
"session",
".",
"createQuery",
"(",
"sql",
")",
";",
"QueryPos",
"qPos",
"=",
"QueryPos",
".",
"getInstance",
"(",
"q",
")",
";",
"qPos",
".",
"add",
"(",
"groupId",
")",
";",
"if",
"(",
"bindKey",
")",
"{",
"qPos",
".",
"add",
"(",
"StringUtil",
".",
"toLowerCase",
"(",
"key",
")",
")",
";",
"}",
"qPos",
".",
"add",
"(",
"type",
")",
";",
"count",
"=",
"(",
"Long",
")",
"q",
".",
"uniqueResult",
"(",
")",
";",
"finderCache",
".",
"putResult",
"(",
"finderPath",
",",
"finderArgs",
",",
"count",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"finderCache",
".",
"removeResult",
"(",
"finderPath",
",",
"finderArgs",
")",
";",
"throw",
"processException",
"(",
"e",
")",
";",
"}",
"finally",
"{",
"closeSession",
"(",
"session",
")",
";",
"}",
"}",
"return",
"count",
".",
"intValue",
"(",
")",
";",
"}"
] | Returns the number of cp measurement units where groupId = ? and key = ? and type = ?.
@param groupId the group ID
@param key the key
@param type the type
@return the number of matching cp measurement units | [
"Returns",
"the",
"number",
"of",
"cp",
"measurement",
"units",
"where",
"groupId",
"=",
"?",
";",
"and",
"key",
"=",
"?",
";",
"and",
"type",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java#L2740-L2805 |
OpenTSDB/opentsdb | src/tsd/HttpJsonSerializer.java | HttpJsonSerializer.parsePutV1 | @Override
public List<IncomingDataPoint> parsePutV1() {
"""
Parses one or more data points for storage
@return an array of data points to process for storage
@throws JSONException if parsing failed
@throws BadRequestException if the content was missing or parsing failed
"""
if (!query.hasContent()) {
throw new BadRequestException("Missing request content");
}
// convert to a string so we can handle character encoding properly
final String content = query.getContent().trim();
final int firstbyte = content.charAt(0);
try {
if (firstbyte == '{') {
final IncomingDataPoint dp =
JSON.parseToObject(content, IncomingDataPoint.class);
final ArrayList<IncomingDataPoint> dps =
new ArrayList<IncomingDataPoint>(1);
dps.add(dp);
return dps;
} else {
return JSON.parseToObject(content, TR_INCOMING);
}
} catch (IllegalArgumentException iae) {
throw new BadRequestException("Unable to parse the given JSON", iae);
}
} | java | @Override
public List<IncomingDataPoint> parsePutV1() {
if (!query.hasContent()) {
throw new BadRequestException("Missing request content");
}
// convert to a string so we can handle character encoding properly
final String content = query.getContent().trim();
final int firstbyte = content.charAt(0);
try {
if (firstbyte == '{') {
final IncomingDataPoint dp =
JSON.parseToObject(content, IncomingDataPoint.class);
final ArrayList<IncomingDataPoint> dps =
new ArrayList<IncomingDataPoint>(1);
dps.add(dp);
return dps;
} else {
return JSON.parseToObject(content, TR_INCOMING);
}
} catch (IllegalArgumentException iae) {
throw new BadRequestException("Unable to parse the given JSON", iae);
}
} | [
"@",
"Override",
"public",
"List",
"<",
"IncomingDataPoint",
">",
"parsePutV1",
"(",
")",
"{",
"if",
"(",
"!",
"query",
".",
"hasContent",
"(",
")",
")",
"{",
"throw",
"new",
"BadRequestException",
"(",
"\"Missing request content\"",
")",
";",
"}",
"// convert to a string so we can handle character encoding properly",
"final",
"String",
"content",
"=",
"query",
".",
"getContent",
"(",
")",
".",
"trim",
"(",
")",
";",
"final",
"int",
"firstbyte",
"=",
"content",
".",
"charAt",
"(",
"0",
")",
";",
"try",
"{",
"if",
"(",
"firstbyte",
"==",
"'",
"'",
")",
"{",
"final",
"IncomingDataPoint",
"dp",
"=",
"JSON",
".",
"parseToObject",
"(",
"content",
",",
"IncomingDataPoint",
".",
"class",
")",
";",
"final",
"ArrayList",
"<",
"IncomingDataPoint",
">",
"dps",
"=",
"new",
"ArrayList",
"<",
"IncomingDataPoint",
">",
"(",
"1",
")",
";",
"dps",
".",
"add",
"(",
"dp",
")",
";",
"return",
"dps",
";",
"}",
"else",
"{",
"return",
"JSON",
".",
"parseToObject",
"(",
"content",
",",
"TR_INCOMING",
")",
";",
"}",
"}",
"catch",
"(",
"IllegalArgumentException",
"iae",
")",
"{",
"throw",
"new",
"BadRequestException",
"(",
"\"Unable to parse the given JSON\"",
",",
"iae",
")",
";",
"}",
"}"
] | Parses one or more data points for storage
@return an array of data points to process for storage
@throws JSONException if parsing failed
@throws BadRequestException if the content was missing or parsing failed | [
"Parses",
"one",
"or",
"more",
"data",
"points",
"for",
"storage"
] | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tsd/HttpJsonSerializer.java#L136-L159 |
Azure/azure-sdk-for-java | datamigration/resource-manager/v2018_03_31_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_03_31_preview/implementation/TasksInner.java | TasksInner.listWithServiceResponseAsync | public Observable<ServiceResponse<Page<ProjectTaskInner>>> listWithServiceResponseAsync(final String groupName, final String serviceName, final String projectName, final String taskType) {
"""
Get tasks in a service.
The services resource is the top-level resource that represents the Data Migration Service. This method returns a list of tasks owned by a service resource. Some tasks may have a status of Unknown, which indicates that an error occurred while querying the status of that task.
@param groupName Name of the resource group
@param serviceName Name of the service
@param projectName Name of the project
@param taskType Filter tasks by task type
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ProjectTaskInner> object
"""
return listSinglePageAsync(groupName, serviceName, projectName, taskType)
.concatMap(new Func1<ServiceResponse<Page<ProjectTaskInner>>, Observable<ServiceResponse<Page<ProjectTaskInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ProjectTaskInner>>> call(ServiceResponse<Page<ProjectTaskInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
} | java | public Observable<ServiceResponse<Page<ProjectTaskInner>>> listWithServiceResponseAsync(final String groupName, final String serviceName, final String projectName, final String taskType) {
return listSinglePageAsync(groupName, serviceName, projectName, taskType)
.concatMap(new Func1<ServiceResponse<Page<ProjectTaskInner>>, Observable<ServiceResponse<Page<ProjectTaskInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ProjectTaskInner>>> call(ServiceResponse<Page<ProjectTaskInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ProjectTaskInner",
">",
">",
">",
"listWithServiceResponseAsync",
"(",
"final",
"String",
"groupName",
",",
"final",
"String",
"serviceName",
",",
"final",
"String",
"projectName",
",",
"final",
"String",
"taskType",
")",
"{",
"return",
"listSinglePageAsync",
"(",
"groupName",
",",
"serviceName",
",",
"projectName",
",",
"taskType",
")",
".",
"concatMap",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ProjectTaskInner",
">",
">",
",",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ProjectTaskInner",
">",
">",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ProjectTaskInner",
">",
">",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"ProjectTaskInner",
">",
">",
"page",
")",
"{",
"String",
"nextPageLink",
"=",
"page",
".",
"body",
"(",
")",
".",
"nextPageLink",
"(",
")",
";",
"if",
"(",
"nextPageLink",
"==",
"null",
")",
"{",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
";",
"}",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
".",
"concatWith",
"(",
"listNextWithServiceResponseAsync",
"(",
"nextPageLink",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] | Get tasks in a service.
The services resource is the top-level resource that represents the Data Migration Service. This method returns a list of tasks owned by a service resource. Some tasks may have a status of Unknown, which indicates that an error occurred while querying the status of that task.
@param groupName Name of the resource group
@param serviceName Name of the service
@param projectName Name of the project
@param taskType Filter tasks by task type
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ProjectTaskInner> object | [
"Get",
"tasks",
"in",
"a",
"service",
".",
"The",
"services",
"resource",
"is",
"the",
"top",
"-",
"level",
"resource",
"that",
"represents",
"the",
"Data",
"Migration",
"Service",
".",
"This",
"method",
"returns",
"a",
"list",
"of",
"tasks",
"owned",
"by",
"a",
"service",
"resource",
".",
"Some",
"tasks",
"may",
"have",
"a",
"status",
"of",
"Unknown",
"which",
"indicates",
"that",
"an",
"error",
"occurred",
"while",
"querying",
"the",
"status",
"of",
"that",
"task",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2018_03_31_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_03_31_preview/implementation/TasksInner.java#L305-L317 |
fcrepo3/fcrepo | fcrepo-server/src/main/java/org/fcrepo/server/storage/GSearchDOManager.java | GSearchDOManager.postInitModule | @Override
public void postInitModule() throws ModuleInitializationException {
"""
Performs superclass post-initialization, then completes initialization
using GSearch-specific parameters.
"""
super.postInitModule();
// validate required param: GSEARCH_REST_URL
_gSearchRESTURL = getParameter(GSEARCH_REST_URL);
if (_gSearchRESTURL == null) {
throw new ModuleInitializationException("Required parameter, "
+ GSEARCH_REST_URL + " was not specified", getRole());
} else {
try {
new URL(_gSearchRESTURL);
logger.debug("Configured GSearch REST URL: " + _gSearchRESTURL);
} catch (MalformedURLException e) {
throw new ModuleInitializationException("Malformed URL given "
+ "for " + GSEARCH_REST_URL + " parameter: "
+ _gSearchRESTURL, getRole());
}
}
// validate credentials: if GSEARCH_USERNAME is given, GSEARCH_PASSWORD
// should also be.
String user = getParameter(GSEARCH_USERNAME);
if (user != null) {
logger.debug("Will authenticate to GSearch service as user: " + user);
String pass = getParameter(GSEARCH_PASSWORD);
if (pass != null) {
_gSearchCredentials =
new UsernamePasswordCredentials(user, pass);
} else {
throw new ModuleInitializationException(GSEARCH_PASSWORD
+ " must be specified because " + GSEARCH_USERNAME
+ " was specified", getRole());
}
} else {
logger.debug(GSEARCH_USERNAME + " unspecified; will not attempt "
+ "to authenticate to GSearch service");
}
// finally, init the http client we'll use
_webClientConfig = getServer().getWebClientConfig();
_webClient = new WebClient(_webClientConfig);
} | java | @Override
public void postInitModule() throws ModuleInitializationException {
super.postInitModule();
// validate required param: GSEARCH_REST_URL
_gSearchRESTURL = getParameter(GSEARCH_REST_URL);
if (_gSearchRESTURL == null) {
throw new ModuleInitializationException("Required parameter, "
+ GSEARCH_REST_URL + " was not specified", getRole());
} else {
try {
new URL(_gSearchRESTURL);
logger.debug("Configured GSearch REST URL: " + _gSearchRESTURL);
} catch (MalformedURLException e) {
throw new ModuleInitializationException("Malformed URL given "
+ "for " + GSEARCH_REST_URL + " parameter: "
+ _gSearchRESTURL, getRole());
}
}
// validate credentials: if GSEARCH_USERNAME is given, GSEARCH_PASSWORD
// should also be.
String user = getParameter(GSEARCH_USERNAME);
if (user != null) {
logger.debug("Will authenticate to GSearch service as user: " + user);
String pass = getParameter(GSEARCH_PASSWORD);
if (pass != null) {
_gSearchCredentials =
new UsernamePasswordCredentials(user, pass);
} else {
throw new ModuleInitializationException(GSEARCH_PASSWORD
+ " must be specified because " + GSEARCH_USERNAME
+ " was specified", getRole());
}
} else {
logger.debug(GSEARCH_USERNAME + " unspecified; will not attempt "
+ "to authenticate to GSearch service");
}
// finally, init the http client we'll use
_webClientConfig = getServer().getWebClientConfig();
_webClient = new WebClient(_webClientConfig);
} | [
"@",
"Override",
"public",
"void",
"postInitModule",
"(",
")",
"throws",
"ModuleInitializationException",
"{",
"super",
".",
"postInitModule",
"(",
")",
";",
"// validate required param: GSEARCH_REST_URL",
"_gSearchRESTURL",
"=",
"getParameter",
"(",
"GSEARCH_REST_URL",
")",
";",
"if",
"(",
"_gSearchRESTURL",
"==",
"null",
")",
"{",
"throw",
"new",
"ModuleInitializationException",
"(",
"\"Required parameter, \"",
"+",
"GSEARCH_REST_URL",
"+",
"\" was not specified\"",
",",
"getRole",
"(",
")",
")",
";",
"}",
"else",
"{",
"try",
"{",
"new",
"URL",
"(",
"_gSearchRESTURL",
")",
";",
"logger",
".",
"debug",
"(",
"\"Configured GSearch REST URL: \"",
"+",
"_gSearchRESTURL",
")",
";",
"}",
"catch",
"(",
"MalformedURLException",
"e",
")",
"{",
"throw",
"new",
"ModuleInitializationException",
"(",
"\"Malformed URL given \"",
"+",
"\"for \"",
"+",
"GSEARCH_REST_URL",
"+",
"\" parameter: \"",
"+",
"_gSearchRESTURL",
",",
"getRole",
"(",
")",
")",
";",
"}",
"}",
"// validate credentials: if GSEARCH_USERNAME is given, GSEARCH_PASSWORD",
"// should also be.",
"String",
"user",
"=",
"getParameter",
"(",
"GSEARCH_USERNAME",
")",
";",
"if",
"(",
"user",
"!=",
"null",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Will authenticate to GSearch service as user: \"",
"+",
"user",
")",
";",
"String",
"pass",
"=",
"getParameter",
"(",
"GSEARCH_PASSWORD",
")",
";",
"if",
"(",
"pass",
"!=",
"null",
")",
"{",
"_gSearchCredentials",
"=",
"new",
"UsernamePasswordCredentials",
"(",
"user",
",",
"pass",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"ModuleInitializationException",
"(",
"GSEARCH_PASSWORD",
"+",
"\" must be specified because \"",
"+",
"GSEARCH_USERNAME",
"+",
"\" was specified\"",
",",
"getRole",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"logger",
".",
"debug",
"(",
"GSEARCH_USERNAME",
"+",
"\" unspecified; will not attempt \"",
"+",
"\"to authenticate to GSearch service\"",
")",
";",
"}",
"// finally, init the http client we'll use",
"_webClientConfig",
"=",
"getServer",
"(",
")",
".",
"getWebClientConfig",
"(",
")",
";",
"_webClient",
"=",
"new",
"WebClient",
"(",
"_webClientConfig",
")",
";",
"}"
] | Performs superclass post-initialization, then completes initialization
using GSearch-specific parameters. | [
"Performs",
"superclass",
"post",
"-",
"initialization",
"then",
"completes",
"initialization",
"using",
"GSearch",
"-",
"specific",
"parameters",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/storage/GSearchDOManager.java#L100-L143 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/painter/AbstractRegionPainter.java | AbstractRegionPainter.paintDirectly | private void paintDirectly(Graphics2D g, JComponent c, int w, int h, Object[] extendedCacheKeys) {
"""
Convenience method which creates a temporary graphics object by creating
a clone of the passed in one, configuring it, drawing with it, disposing
it. These steps have to be taken to ensure that any hints set on the
graphics are removed subsequent to painting.
@param g the Graphics2D context to paint with.
@param c the component to paint.
@param w the component width.
@param h the component height.
@param extendedCacheKeys extended cache keys.
"""
g = (Graphics2D) g.create();
configureGraphics(g);
doPaint(g, c, w, h, extendedCacheKeys);
g.dispose();
} | java | private void paintDirectly(Graphics2D g, JComponent c, int w, int h, Object[] extendedCacheKeys) {
g = (Graphics2D) g.create();
configureGraphics(g);
doPaint(g, c, w, h, extendedCacheKeys);
g.dispose();
} | [
"private",
"void",
"paintDirectly",
"(",
"Graphics2D",
"g",
",",
"JComponent",
"c",
",",
"int",
"w",
",",
"int",
"h",
",",
"Object",
"[",
"]",
"extendedCacheKeys",
")",
"{",
"g",
"=",
"(",
"Graphics2D",
")",
"g",
".",
"create",
"(",
")",
";",
"configureGraphics",
"(",
"g",
")",
";",
"doPaint",
"(",
"g",
",",
"c",
",",
"w",
",",
"h",
",",
"extendedCacheKeys",
")",
";",
"g",
".",
"dispose",
"(",
")",
";",
"}"
] | Convenience method which creates a temporary graphics object by creating
a clone of the passed in one, configuring it, drawing with it, disposing
it. These steps have to be taken to ensure that any hints set on the
graphics are removed subsequent to painting.
@param g the Graphics2D context to paint with.
@param c the component to paint.
@param w the component width.
@param h the component height.
@param extendedCacheKeys extended cache keys. | [
"Convenience",
"method",
"which",
"creates",
"a",
"temporary",
"graphics",
"object",
"by",
"creating",
"a",
"clone",
"of",
"the",
"passed",
"in",
"one",
"configuring",
"it",
"drawing",
"with",
"it",
"disposing",
"it",
".",
"These",
"steps",
"have",
"to",
"be",
"taken",
"to",
"ensure",
"that",
"any",
"hints",
"set",
"on",
"the",
"graphics",
"are",
"removed",
"subsequent",
"to",
"painting",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/AbstractRegionPainter.java#L636-L641 |
goldmansachs/reladomo | reladomo/src/main/java/com/gs/fw/common/mithra/cache/offheap/FastUnsafeOffHeapMemoryInitialiser.java | FastUnsafeOffHeapMemoryInitialiser.unsafeZeroMemoryOptimisedForSmallBuffer | protected void unsafeZeroMemoryOptimisedForSmallBuffer(long address, long sizeInBytes) {
"""
protected for test purposes (this is also why the method cannot be static)
"""
long endAddress = address + sizeInBytes;
long endOfLastLong = address + ((sizeInBytes >> 3) << 3);
for (long i = address; i < endOfLastLong; i += 8L)
{
UNSAFE.putLong(i, 0L);
}
for (long i = endOfLastLong; i < endAddress; i++)
{
UNSAFE.putByte(i, (byte) 0);
}
} | java | protected void unsafeZeroMemoryOptimisedForSmallBuffer(long address, long sizeInBytes)
{
long endAddress = address + sizeInBytes;
long endOfLastLong = address + ((sizeInBytes >> 3) << 3);
for (long i = address; i < endOfLastLong; i += 8L)
{
UNSAFE.putLong(i, 0L);
}
for (long i = endOfLastLong; i < endAddress; i++)
{
UNSAFE.putByte(i, (byte) 0);
}
} | [
"protected",
"void",
"unsafeZeroMemoryOptimisedForSmallBuffer",
"(",
"long",
"address",
",",
"long",
"sizeInBytes",
")",
"{",
"long",
"endAddress",
"=",
"address",
"+",
"sizeInBytes",
";",
"long",
"endOfLastLong",
"=",
"address",
"+",
"(",
"(",
"sizeInBytes",
">>",
"3",
")",
"<<",
"3",
")",
";",
"for",
"(",
"long",
"i",
"=",
"address",
";",
"i",
"<",
"endOfLastLong",
";",
"i",
"+=",
"8L",
")",
"{",
"UNSAFE",
".",
"putLong",
"(",
"i",
",",
"0L",
")",
";",
"}",
"for",
"(",
"long",
"i",
"=",
"endOfLastLong",
";",
"i",
"<",
"endAddress",
";",
"i",
"++",
")",
"{",
"UNSAFE",
".",
"putByte",
"(",
"i",
",",
"(",
"byte",
")",
"0",
")",
";",
"}",
"}"
] | protected for test purposes (this is also why the method cannot be static) | [
"protected",
"for",
"test",
"purposes",
"(",
"this",
"is",
"also",
"why",
"the",
"method",
"cannot",
"be",
"static",
")"
] | train | https://github.com/goldmansachs/reladomo/blob/e9a069452eece7a6ef9551caf81a69d3d9a3d990/reladomo/src/main/java/com/gs/fw/common/mithra/cache/offheap/FastUnsafeOffHeapMemoryInitialiser.java#L56-L68 |
phax/ph-javacc-maven-plugin | src/main/java/org/codehaus/mojo/javacc/AbstractJavaCCMojo.java | AbstractJavaCCMojo.determineNonGeneratedSourceRoots | private void determineNonGeneratedSourceRoots () throws MojoExecutionException {
"""
Determines those compile source roots of the project that do not reside below
the project's build directories. These compile source roots are assumed to
contain hand-crafted sources that must not be overwritten with generated
files. In most cases, this is simply "${project.build.sourceDirectory}".
@throws MojoExecutionException
If the compile source rotos could not be determined.
"""
this.nonGeneratedSourceRoots = new LinkedHashSet <> ();
try
{
final String targetPrefix = new File (this.project.getBuild ().getDirectory ()).getCanonicalPath () +
File.separator;
final List <String> sourceRoots = this.project.getCompileSourceRoots ();
for (final String aElement : sourceRoots)
{
File sourceRoot = new File (aElement);
if (!sourceRoot.isAbsolute ())
{
sourceRoot = new File (this.project.getBasedir (), sourceRoot.getPath ());
}
final String sourcePath = sourceRoot.getCanonicalPath ();
if (!sourcePath.startsWith (targetPrefix))
{
this.nonGeneratedSourceRoots.add (sourceRoot);
getLog ().debug ("Non-generated compile source root: " + sourceRoot);
}
else
{
getLog ().debug ("Generated compile source root: " + sourceRoot);
}
}
}
catch (final IOException e)
{
throw new MojoExecutionException ("Failed to determine non-generated source roots", e);
}
} | java | private void determineNonGeneratedSourceRoots () throws MojoExecutionException
{
this.nonGeneratedSourceRoots = new LinkedHashSet <> ();
try
{
final String targetPrefix = new File (this.project.getBuild ().getDirectory ()).getCanonicalPath () +
File.separator;
final List <String> sourceRoots = this.project.getCompileSourceRoots ();
for (final String aElement : sourceRoots)
{
File sourceRoot = new File (aElement);
if (!sourceRoot.isAbsolute ())
{
sourceRoot = new File (this.project.getBasedir (), sourceRoot.getPath ());
}
final String sourcePath = sourceRoot.getCanonicalPath ();
if (!sourcePath.startsWith (targetPrefix))
{
this.nonGeneratedSourceRoots.add (sourceRoot);
getLog ().debug ("Non-generated compile source root: " + sourceRoot);
}
else
{
getLog ().debug ("Generated compile source root: " + sourceRoot);
}
}
}
catch (final IOException e)
{
throw new MojoExecutionException ("Failed to determine non-generated source roots", e);
}
} | [
"private",
"void",
"determineNonGeneratedSourceRoots",
"(",
")",
"throws",
"MojoExecutionException",
"{",
"this",
".",
"nonGeneratedSourceRoots",
"=",
"new",
"LinkedHashSet",
"<>",
"(",
")",
";",
"try",
"{",
"final",
"String",
"targetPrefix",
"=",
"new",
"File",
"(",
"this",
".",
"project",
".",
"getBuild",
"(",
")",
".",
"getDirectory",
"(",
")",
")",
".",
"getCanonicalPath",
"(",
")",
"+",
"File",
".",
"separator",
";",
"final",
"List",
"<",
"String",
">",
"sourceRoots",
"=",
"this",
".",
"project",
".",
"getCompileSourceRoots",
"(",
")",
";",
"for",
"(",
"final",
"String",
"aElement",
":",
"sourceRoots",
")",
"{",
"File",
"sourceRoot",
"=",
"new",
"File",
"(",
"aElement",
")",
";",
"if",
"(",
"!",
"sourceRoot",
".",
"isAbsolute",
"(",
")",
")",
"{",
"sourceRoot",
"=",
"new",
"File",
"(",
"this",
".",
"project",
".",
"getBasedir",
"(",
")",
",",
"sourceRoot",
".",
"getPath",
"(",
")",
")",
";",
"}",
"final",
"String",
"sourcePath",
"=",
"sourceRoot",
".",
"getCanonicalPath",
"(",
")",
";",
"if",
"(",
"!",
"sourcePath",
".",
"startsWith",
"(",
"targetPrefix",
")",
")",
"{",
"this",
".",
"nonGeneratedSourceRoots",
".",
"add",
"(",
"sourceRoot",
")",
";",
"getLog",
"(",
")",
".",
"debug",
"(",
"\"Non-generated compile source root: \"",
"+",
"sourceRoot",
")",
";",
"}",
"else",
"{",
"getLog",
"(",
")",
".",
"debug",
"(",
"\"Generated compile source root: \"",
"+",
"sourceRoot",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"final",
"IOException",
"e",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"\"Failed to determine non-generated source roots\"",
",",
"e",
")",
";",
"}",
"}"
] | Determines those compile source roots of the project that do not reside below
the project's build directories. These compile source roots are assumed to
contain hand-crafted sources that must not be overwritten with generated
files. In most cases, this is simply "${project.build.sourceDirectory}".
@throws MojoExecutionException
If the compile source rotos could not be determined. | [
"Determines",
"those",
"compile",
"source",
"roots",
"of",
"the",
"project",
"that",
"do",
"not",
"reside",
"below",
"the",
"project",
"s",
"build",
"directories",
".",
"These",
"compile",
"source",
"roots",
"are",
"assumed",
"to",
"contain",
"hand",
"-",
"crafted",
"sources",
"that",
"must",
"not",
"be",
"overwritten",
"with",
"generated",
"files",
".",
"In",
"most",
"cases",
"this",
"is",
"simply",
"$",
"{",
"project",
".",
"build",
".",
"sourceDirectory",
"}",
"."
] | train | https://github.com/phax/ph-javacc-maven-plugin/blob/99497a971fe59ab2289258ca7ddcfa40e651f19f/src/main/java/org/codehaus/mojo/javacc/AbstractJavaCCMojo.java#L650-L681 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/imports/TypeUsageCollector.java | TypeUsageCollector.findPreferredType | protected PreferredType findPreferredType(EObject owner, EReference reference, String text) {
"""
Tries to locate the syntax for the type reference that the user used in the original code.
Especially interesting for nested types, where one could prefer the (arguably) more explicit (or verbose)
{@code Resource$Factory} with an import of {@code org.eclipse.emf.core.Resource} over the probably shorter
{@code Factory} with an import of {@code org.eclipse.emf.core.Resource$Factory}.
The function relies on a node model to be available. Otherwise the actually referenced type is
used as the preferred type.
@param owner the referrer to the JVM concept.
@param reference a reference to a {@link JvmType} or {@link JvmMember} that is declared in a type.
@return the referenced type or one of its containers.
"""
JvmIdentifiableElement referencedThing = getReferencedElement(owner, reference);
JvmDeclaredType referencedType = null;
if (referencedThing instanceof JvmDeclaredType) {
referencedType = (JvmDeclaredType) referencedThing;
} else if (referencedThing instanceof JvmMember) {
referencedType = ((JvmMember) referencedThing).getDeclaringType();
} else if(referencedThing instanceof JvmType) {
if (referencedThing.eIsProxy()) {
String importedName = getFirstNameSegment(owner, reference);
return new PreferredType(importedName);
}
return null;
}
return findPreferredType(referencedType, text);
} | java | protected PreferredType findPreferredType(EObject owner, EReference reference, String text) {
JvmIdentifiableElement referencedThing = getReferencedElement(owner, reference);
JvmDeclaredType referencedType = null;
if (referencedThing instanceof JvmDeclaredType) {
referencedType = (JvmDeclaredType) referencedThing;
} else if (referencedThing instanceof JvmMember) {
referencedType = ((JvmMember) referencedThing).getDeclaringType();
} else if(referencedThing instanceof JvmType) {
if (referencedThing.eIsProxy()) {
String importedName = getFirstNameSegment(owner, reference);
return new PreferredType(importedName);
}
return null;
}
return findPreferredType(referencedType, text);
} | [
"protected",
"PreferredType",
"findPreferredType",
"(",
"EObject",
"owner",
",",
"EReference",
"reference",
",",
"String",
"text",
")",
"{",
"JvmIdentifiableElement",
"referencedThing",
"=",
"getReferencedElement",
"(",
"owner",
",",
"reference",
")",
";",
"JvmDeclaredType",
"referencedType",
"=",
"null",
";",
"if",
"(",
"referencedThing",
"instanceof",
"JvmDeclaredType",
")",
"{",
"referencedType",
"=",
"(",
"JvmDeclaredType",
")",
"referencedThing",
";",
"}",
"else",
"if",
"(",
"referencedThing",
"instanceof",
"JvmMember",
")",
"{",
"referencedType",
"=",
"(",
"(",
"JvmMember",
")",
"referencedThing",
")",
".",
"getDeclaringType",
"(",
")",
";",
"}",
"else",
"if",
"(",
"referencedThing",
"instanceof",
"JvmType",
")",
"{",
"if",
"(",
"referencedThing",
".",
"eIsProxy",
"(",
")",
")",
"{",
"String",
"importedName",
"=",
"getFirstNameSegment",
"(",
"owner",
",",
"reference",
")",
";",
"return",
"new",
"PreferredType",
"(",
"importedName",
")",
";",
"}",
"return",
"null",
";",
"}",
"return",
"findPreferredType",
"(",
"referencedType",
",",
"text",
")",
";",
"}"
] | Tries to locate the syntax for the type reference that the user used in the original code.
Especially interesting for nested types, where one could prefer the (arguably) more explicit (or verbose)
{@code Resource$Factory} with an import of {@code org.eclipse.emf.core.Resource} over the probably shorter
{@code Factory} with an import of {@code org.eclipse.emf.core.Resource$Factory}.
The function relies on a node model to be available. Otherwise the actually referenced type is
used as the preferred type.
@param owner the referrer to the JVM concept.
@param reference a reference to a {@link JvmType} or {@link JvmMember} that is declared in a type.
@return the referenced type or one of its containers. | [
"Tries",
"to",
"locate",
"the",
"syntax",
"for",
"the",
"type",
"reference",
"that",
"the",
"user",
"used",
"in",
"the",
"original",
"code",
".",
"Especially",
"interesting",
"for",
"nested",
"types",
"where",
"one",
"could",
"prefer",
"the",
"(",
"arguably",
")",
"more",
"explicit",
"(",
"or",
"verbose",
")",
"{",
"@code",
"Resource$Factory",
"}",
"with",
"an",
"import",
"of",
"{",
"@code",
"org",
".",
"eclipse",
".",
"emf",
".",
"core",
".",
"Resource",
"}",
"over",
"the",
"probably",
"shorter",
"{",
"@code",
"Factory",
"}",
"with",
"an",
"import",
"of",
"{",
"@code",
"org",
".",
"eclipse",
".",
"emf",
".",
"core",
".",
"Resource$Factory",
"}",
"."
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/imports/TypeUsageCollector.java#L414-L429 |
tempodb/tempodb-java | src/main/java/com/tempodb/Client.java | Client.readMultiRollupDataPoints | public Cursor<MultiDataPoint> readMultiRollupDataPoints(Series series, Interval interval, DateTimeZone timezone, MultiRollup rollup, Interpolation interpolation) {
"""
Returns a cursor of datapoints specified by series with multiple rollups.
@param series The series
@param interval An interval of time for the query (start/end datetimes)
@param timezone The time zone for the returned datapoints.
@param rollup The MultiRollup for the read query.
@param interpolation The interpolation for the read query. This can be null.
@return A Cursor of DataPoints. The cursor.iterator().next() may throw a {@link TempoDBException} if an error occurs while making a request.
@see Cursor
@see MultiRollup
@since 1.0.0
"""
checkNotNull(series);
checkNotNull(interval);
checkNotNull(timezone);
checkNotNull(rollup);
URI uri = null;
try {
URIBuilder builder = new URIBuilder(String.format("/%s/series/key/%s/data/rollups/segment/", API_VERSION, urlencode(series.getKey())));
addInterpolationToURI(builder, interpolation);
addIntervalToURI(builder, interval);
addMultiRollupToURI(builder, rollup);
addTimeZoneToURI(builder, timezone);
uri = builder.build();
} catch (URISyntaxException e) {
String message = String.format("Could not build URI with inputs: key: %s, interval: %s, rollup: %s, timezone: %s", series.getKey(), interval, rollup, timezone);
throw new IllegalArgumentException(message, e);
}
Cursor<MultiDataPoint> cursor = new MultiRollupDataPointCursor(uri, this);
return cursor;
} | java | public Cursor<MultiDataPoint> readMultiRollupDataPoints(Series series, Interval interval, DateTimeZone timezone, MultiRollup rollup, Interpolation interpolation) {
checkNotNull(series);
checkNotNull(interval);
checkNotNull(timezone);
checkNotNull(rollup);
URI uri = null;
try {
URIBuilder builder = new URIBuilder(String.format("/%s/series/key/%s/data/rollups/segment/", API_VERSION, urlencode(series.getKey())));
addInterpolationToURI(builder, interpolation);
addIntervalToURI(builder, interval);
addMultiRollupToURI(builder, rollup);
addTimeZoneToURI(builder, timezone);
uri = builder.build();
} catch (URISyntaxException e) {
String message = String.format("Could not build URI with inputs: key: %s, interval: %s, rollup: %s, timezone: %s", series.getKey(), interval, rollup, timezone);
throw new IllegalArgumentException(message, e);
}
Cursor<MultiDataPoint> cursor = new MultiRollupDataPointCursor(uri, this);
return cursor;
} | [
"public",
"Cursor",
"<",
"MultiDataPoint",
">",
"readMultiRollupDataPoints",
"(",
"Series",
"series",
",",
"Interval",
"interval",
",",
"DateTimeZone",
"timezone",
",",
"MultiRollup",
"rollup",
",",
"Interpolation",
"interpolation",
")",
"{",
"checkNotNull",
"(",
"series",
")",
";",
"checkNotNull",
"(",
"interval",
")",
";",
"checkNotNull",
"(",
"timezone",
")",
";",
"checkNotNull",
"(",
"rollup",
")",
";",
"URI",
"uri",
"=",
"null",
";",
"try",
"{",
"URIBuilder",
"builder",
"=",
"new",
"URIBuilder",
"(",
"String",
".",
"format",
"(",
"\"/%s/series/key/%s/data/rollups/segment/\"",
",",
"API_VERSION",
",",
"urlencode",
"(",
"series",
".",
"getKey",
"(",
")",
")",
")",
")",
";",
"addInterpolationToURI",
"(",
"builder",
",",
"interpolation",
")",
";",
"addIntervalToURI",
"(",
"builder",
",",
"interval",
")",
";",
"addMultiRollupToURI",
"(",
"builder",
",",
"rollup",
")",
";",
"addTimeZoneToURI",
"(",
"builder",
",",
"timezone",
")",
";",
"uri",
"=",
"builder",
".",
"build",
"(",
")",
";",
"}",
"catch",
"(",
"URISyntaxException",
"e",
")",
"{",
"String",
"message",
"=",
"String",
".",
"format",
"(",
"\"Could not build URI with inputs: key: %s, interval: %s, rollup: %s, timezone: %s\"",
",",
"series",
".",
"getKey",
"(",
")",
",",
"interval",
",",
"rollup",
",",
"timezone",
")",
";",
"throw",
"new",
"IllegalArgumentException",
"(",
"message",
",",
"e",
")",
";",
"}",
"Cursor",
"<",
"MultiDataPoint",
">",
"cursor",
"=",
"new",
"MultiRollupDataPointCursor",
"(",
"uri",
",",
"this",
")",
";",
"return",
"cursor",
";",
"}"
] | Returns a cursor of datapoints specified by series with multiple rollups.
@param series The series
@param interval An interval of time for the query (start/end datetimes)
@param timezone The time zone for the returned datapoints.
@param rollup The MultiRollup for the read query.
@param interpolation The interpolation for the read query. This can be null.
@return A Cursor of DataPoints. The cursor.iterator().next() may throw a {@link TempoDBException} if an error occurs while making a request.
@see Cursor
@see MultiRollup
@since 1.0.0 | [
"Returns",
"a",
"cursor",
"of",
"datapoints",
"specified",
"by",
"series",
"with",
"multiple",
"rollups",
"."
] | train | https://github.com/tempodb/tempodb-java/blob/5733f204fe4c8dda48916ba1f67cf44f5a3f9c69/src/main/java/com/tempodb/Client.java#L725-L746 |
pagehelper/Mybatis-PageHelper | src/main/java/com/github/pagehelper/parser/SqlServerParser.java | SqlServerParser.cloneOrderByElement | protected OrderByElement cloneOrderByElement(OrderByElement orig, String alias) {
"""
复制 OrderByElement
@param orig 原 OrderByElement
@param alias 新 OrderByElement 的排序要素
@return 复制的新 OrderByElement
"""
return cloneOrderByElement(orig, new Column(alias));
} | java | protected OrderByElement cloneOrderByElement(OrderByElement orig, String alias) {
return cloneOrderByElement(orig, new Column(alias));
} | [
"protected",
"OrderByElement",
"cloneOrderByElement",
"(",
"OrderByElement",
"orig",
",",
"String",
"alias",
")",
"{",
"return",
"cloneOrderByElement",
"(",
"orig",
",",
"new",
"Column",
"(",
"alias",
")",
")",
";",
"}"
] | 复制 OrderByElement
@param orig 原 OrderByElement
@param alias 新 OrderByElement 的排序要素
@return 复制的新 OrderByElement | [
"复制",
"OrderByElement"
] | train | https://github.com/pagehelper/Mybatis-PageHelper/blob/319750fd47cf75328ff321f38125fa15e954e60f/src/main/java/com/github/pagehelper/parser/SqlServerParser.java#L403-L405 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/file/PathFileObject.java | PathFileObject.forDirectoryPath | static PathFileObject forDirectoryPath(BaseFileManager fileManager, Path path,
Path userPackageRootDir, RelativePath relativePath) {
"""
Create a PathFileObject for a file within a directory, such that the
binary name can be inferred from the relationship to an enclosing directory.
The binary name is derived from {@code relativePath}.
The name is derived from the composition of {@code userPackageRootDir}
and {@code relativePath}.
@param fileManager the file manager creating this file object
@param path the absolute path referred to by this file object
@param userPackageRootDir the path of the directory containing the
root of the package hierarchy
@param relativePath the path of this file relative to {@code userPackageRootDir}
"""
return new DirectoryFileObject(fileManager, path, userPackageRootDir, relativePath);
} | java | static PathFileObject forDirectoryPath(BaseFileManager fileManager, Path path,
Path userPackageRootDir, RelativePath relativePath) {
return new DirectoryFileObject(fileManager, path, userPackageRootDir, relativePath);
} | [
"static",
"PathFileObject",
"forDirectoryPath",
"(",
"BaseFileManager",
"fileManager",
",",
"Path",
"path",
",",
"Path",
"userPackageRootDir",
",",
"RelativePath",
"relativePath",
")",
"{",
"return",
"new",
"DirectoryFileObject",
"(",
"fileManager",
",",
"path",
",",
"userPackageRootDir",
",",
"relativePath",
")",
";",
"}"
] | Create a PathFileObject for a file within a directory, such that the
binary name can be inferred from the relationship to an enclosing directory.
The binary name is derived from {@code relativePath}.
The name is derived from the composition of {@code userPackageRootDir}
and {@code relativePath}.
@param fileManager the file manager creating this file object
@param path the absolute path referred to by this file object
@param userPackageRootDir the path of the directory containing the
root of the package hierarchy
@param relativePath the path of this file relative to {@code userPackageRootDir} | [
"Create",
"a",
"PathFileObject",
"for",
"a",
"file",
"within",
"a",
"directory",
"such",
"that",
"the",
"binary",
"name",
"can",
"be",
"inferred",
"from",
"the",
"relationship",
"to",
"an",
"enclosing",
"directory",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/file/PathFileObject.java#L100-L103 |
igniterealtime/Smack | smack-experimental/src/main/java/org/jivesoftware/smackx/httpfileupload/HttpFileUploadManager.java | HttpFileUploadManager.requestSlot | public Slot requestSlot(String filename, long fileSize) throws InterruptedException,
XMPPException.XMPPErrorException, SmackException {
"""
Request a new upload slot from default upload service (if discovered). When you get slot you should upload file
to PUT URL and share GET URL. Note that this is a synchronous call -- Smack must wait for the server response.
@param filename name of file to be uploaded
@param fileSize file size in bytes.
@return file upload Slot in case of success
@throws IllegalArgumentException if fileSize is less than or equal to zero or greater than the maximum size
supported by the service.
@throws InterruptedException
@throws XMPPException.XMPPErrorException
@throws SmackException.NotConnectedException
@throws SmackException.NoResponseException
"""
return requestSlot(filename, fileSize, null, null);
} | java | public Slot requestSlot(String filename, long fileSize) throws InterruptedException,
XMPPException.XMPPErrorException, SmackException {
return requestSlot(filename, fileSize, null, null);
} | [
"public",
"Slot",
"requestSlot",
"(",
"String",
"filename",
",",
"long",
"fileSize",
")",
"throws",
"InterruptedException",
",",
"XMPPException",
".",
"XMPPErrorException",
",",
"SmackException",
"{",
"return",
"requestSlot",
"(",
"filename",
",",
"fileSize",
",",
"null",
",",
"null",
")",
";",
"}"
] | Request a new upload slot from default upload service (if discovered). When you get slot you should upload file
to PUT URL and share GET URL. Note that this is a synchronous call -- Smack must wait for the server response.
@param filename name of file to be uploaded
@param fileSize file size in bytes.
@return file upload Slot in case of success
@throws IllegalArgumentException if fileSize is less than or equal to zero or greater than the maximum size
supported by the service.
@throws InterruptedException
@throws XMPPException.XMPPErrorException
@throws SmackException.NotConnectedException
@throws SmackException.NoResponseException | [
"Request",
"a",
"new",
"upload",
"slot",
"from",
"default",
"upload",
"service",
"(",
"if",
"discovered",
")",
".",
"When",
"you",
"get",
"slot",
"you",
"should",
"upload",
"file",
"to",
"PUT",
"URL",
"and",
"share",
"GET",
"URL",
".",
"Note",
"that",
"this",
"is",
"a",
"synchronous",
"call",
"--",
"Smack",
"must",
"wait",
"for",
"the",
"server",
"response",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/httpfileupload/HttpFileUploadManager.java#L283-L286 |
jOOQ/jOOL | jOOL-java-8/src/main/java/org/jooq/lambda/Agg.java | Agg.maxAllBy | public static <T, U extends Comparable<? super U>> Collector<T, ?, Seq<T>> maxAllBy(Function<? super T, ? extends U> function) {
"""
Get a {@link Collector} that calculates the <code>MAX()</code> function, producing multiple results.
"""
return maxAllBy(function, naturalOrder());
} | java | public static <T, U extends Comparable<? super U>> Collector<T, ?, Seq<T>> maxAllBy(Function<? super T, ? extends U> function) {
return maxAllBy(function, naturalOrder());
} | [
"public",
"static",
"<",
"T",
",",
"U",
"extends",
"Comparable",
"<",
"?",
"super",
"U",
">",
">",
"Collector",
"<",
"T",
",",
"?",
",",
"Seq",
"<",
"T",
">",
">",
"maxAllBy",
"(",
"Function",
"<",
"?",
"super",
"T",
",",
"?",
"extends",
"U",
">",
"function",
")",
"{",
"return",
"maxAllBy",
"(",
"function",
",",
"naturalOrder",
"(",
")",
")",
";",
"}"
] | Get a {@link Collector} that calculates the <code>MAX()</code> function, producing multiple results. | [
"Get",
"a",
"{"
] | train | https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Agg.java#L357-L359 |
taimos/RESTUtils | src/main/java/de/taimos/restutils/RESTAssert.java | RESTAssert.assertNotEmpty | public static void assertNotEmpty(final Collection<?> collection, final StatusType status) {
"""
assert that collection is not empty
@param collection the collection to check
@param status the status code to throw
@throws WebApplicationException with given status code
"""
RESTAssert.assertNotNull(collection, status);
RESTAssert.assertFalse(collection.isEmpty(), status);
} | java | public static void assertNotEmpty(final Collection<?> collection, final StatusType status) {
RESTAssert.assertNotNull(collection, status);
RESTAssert.assertFalse(collection.isEmpty(), status);
} | [
"public",
"static",
"void",
"assertNotEmpty",
"(",
"final",
"Collection",
"<",
"?",
">",
"collection",
",",
"final",
"StatusType",
"status",
")",
"{",
"RESTAssert",
".",
"assertNotNull",
"(",
"collection",
",",
"status",
")",
";",
"RESTAssert",
".",
"assertFalse",
"(",
"collection",
".",
"isEmpty",
"(",
")",
",",
"status",
")",
";",
"}"
] | assert that collection is not empty
@param collection the collection to check
@param status the status code to throw
@throws WebApplicationException with given status code | [
"assert",
"that",
"collection",
"is",
"not",
"empty"
] | train | https://github.com/taimos/RESTUtils/blob/bdb1bf9a2eb13ede0eec6f071c10cb2698313501/src/main/java/de/taimos/restutils/RESTAssert.java#L203-L206 |
VoltDB/voltdb | src/frontend/org/voltdb/NonVoltDBBackend.java | NonVoltDBBackend.transformQuery | protected String transformQuery(String query, QueryTransformer ... qts) {
"""
Calls the transformQuery method above multiple times, for each
specified QueryTransformer.
"""
String result = query;
for (QueryTransformer qt : qts) {
result = transformQuery(result, qt);
}
return result;
} | java | protected String transformQuery(String query, QueryTransformer ... qts) {
String result = query;
for (QueryTransformer qt : qts) {
result = transformQuery(result, qt);
}
return result;
} | [
"protected",
"String",
"transformQuery",
"(",
"String",
"query",
",",
"QueryTransformer",
"...",
"qts",
")",
"{",
"String",
"result",
"=",
"query",
";",
"for",
"(",
"QueryTransformer",
"qt",
":",
"qts",
")",
"{",
"result",
"=",
"transformQuery",
"(",
"result",
",",
"qt",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Calls the transformQuery method above multiple times, for each
specified QueryTransformer. | [
"Calls",
"the",
"transformQuery",
"method",
"above",
"multiple",
"times",
"for",
"each",
"specified",
"QueryTransformer",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/NonVoltDBBackend.java#L899-L905 |
apache/incubator-shardingsphere | sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/antlr/rule/jaxb/loader/RuleDefinitionFileConstant.java | RuleDefinitionFileConstant.getSQLStatementRuleDefinitionFileName | public static String getSQLStatementRuleDefinitionFileName(final String rootDir, final DatabaseType databaseType) {
"""
Get SQL statement rule definition file name.
@param rootDir root dir
@param databaseType database type
@return SQL statement rule definition file name
"""
return Joiner.on('/').join(rootDir, databaseType.name().toLowerCase(), SQL_STATEMENT_RULE_DEFINITION_FILE_NAME);
} | java | public static String getSQLStatementRuleDefinitionFileName(final String rootDir, final DatabaseType databaseType) {
return Joiner.on('/').join(rootDir, databaseType.name().toLowerCase(), SQL_STATEMENT_RULE_DEFINITION_FILE_NAME);
} | [
"public",
"static",
"String",
"getSQLStatementRuleDefinitionFileName",
"(",
"final",
"String",
"rootDir",
",",
"final",
"DatabaseType",
"databaseType",
")",
"{",
"return",
"Joiner",
".",
"on",
"(",
"'",
"'",
")",
".",
"join",
"(",
"rootDir",
",",
"databaseType",
".",
"name",
"(",
")",
".",
"toLowerCase",
"(",
")",
",",
"SQL_STATEMENT_RULE_DEFINITION_FILE_NAME",
")",
";",
"}"
] | Get SQL statement rule definition file name.
@param rootDir root dir
@param databaseType database type
@return SQL statement rule definition file name | [
"Get",
"SQL",
"statement",
"rule",
"definition",
"file",
"name",
"."
] | train | https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/antlr/rule/jaxb/loader/RuleDefinitionFileConstant.java#L54-L56 |
UrielCh/ovh-java-sdk | ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java | ApiOvhXdsl.serviceName_lines_number_GET | public net.minidev.ovh.api.xdsl.OvhLine serviceName_lines_number_GET(String serviceName, String number) throws IOException {
"""
Get this object properties
REST: GET /xdsl/{serviceName}/lines/{number}
@param serviceName [required] The internal name of your XDSL offer
@param number [required] The number of the line
"""
String qPath = "/xdsl/{serviceName}/lines/{number}";
StringBuilder sb = path(qPath, serviceName, number);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, net.minidev.ovh.api.xdsl.OvhLine.class);
} | java | public net.minidev.ovh.api.xdsl.OvhLine serviceName_lines_number_GET(String serviceName, String number) throws IOException {
String qPath = "/xdsl/{serviceName}/lines/{number}";
StringBuilder sb = path(qPath, serviceName, number);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, net.minidev.ovh.api.xdsl.OvhLine.class);
} | [
"public",
"net",
".",
"minidev",
".",
"ovh",
".",
"api",
".",
"xdsl",
".",
"OvhLine",
"serviceName_lines_number_GET",
"(",
"String",
"serviceName",
",",
"String",
"number",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/xdsl/{serviceName}/lines/{number}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"number",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"net",
".",
"minidev",
".",
"ovh",
".",
"api",
".",
"xdsl",
".",
"OvhLine",
".",
"class",
")",
";",
"}"
] | Get this object properties
REST: GET /xdsl/{serviceName}/lines/{number}
@param serviceName [required] The internal name of your XDSL offer
@param number [required] The number of the line | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java#L443-L448 |
TheCoder4eu/BootsFaces-OSP | src/main/java/net/bootsfaces/component/carouselCaption/CarouselCaptionRenderer.java | CarouselCaptionRenderer.encodeBegin | @Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
"""
This methods generates the HTML code of the current b:carouselCaption.
<code>encodeBegin</code> generates the start of the component. After the,
the JSF framework calls <code>encodeChildren()</code> to generate the
HTML code between the beginning and the end of the component. For
instance, in the case of a panel component the content of the panel is
generated by <code>encodeChildren()</code>. After that,
<code>encodeEnd()</code> is called to generate the rest of the HTML code.
@param context
the FacesContext.
@param component
the current b:carouselCaption.
@throws IOException
thrown if something goes wrong when writing the HTML code.
"""
if (!component.isRendered()) {
return;
}
ResponseWriter rw = context.getResponseWriter();
rw.startElement("div", component);
rw.writeAttribute("id", component.getId(), "id");
if (component instanceof CarouselCaption) {
Tooltip.generateTooltip(context, ((CarouselCaption) component), rw);
AJAXRenderer.generateBootsFacesAJAXAndJavaScript(context, ((CarouselCaption) component), rw, false);
rw.writeAttribute("style", ((CarouselCaption) component).getStyle(), "style");
}
String styleClass = null;
if (component instanceof CarouselCaption) {
styleClass = ((CarouselCaption) component).getStyleClass();
}
if (null == styleClass)
styleClass = "carousel-caption";
else
styleClass = "carousel-caption " + styleClass;
rw.writeAttribute("class", styleClass, "class");
} | java | @Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) {
return;
}
ResponseWriter rw = context.getResponseWriter();
rw.startElement("div", component);
rw.writeAttribute("id", component.getId(), "id");
if (component instanceof CarouselCaption) {
Tooltip.generateTooltip(context, ((CarouselCaption) component), rw);
AJAXRenderer.generateBootsFacesAJAXAndJavaScript(context, ((CarouselCaption) component), rw, false);
rw.writeAttribute("style", ((CarouselCaption) component).getStyle(), "style");
}
String styleClass = null;
if (component instanceof CarouselCaption) {
styleClass = ((CarouselCaption) component).getStyleClass();
}
if (null == styleClass)
styleClass = "carousel-caption";
else
styleClass = "carousel-caption " + styleClass;
rw.writeAttribute("class", styleClass, "class");
} | [
"@",
"Override",
"public",
"void",
"encodeBegin",
"(",
"FacesContext",
"context",
",",
"UIComponent",
"component",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"component",
".",
"isRendered",
"(",
")",
")",
"{",
"return",
";",
"}",
"ResponseWriter",
"rw",
"=",
"context",
".",
"getResponseWriter",
"(",
")",
";",
"rw",
".",
"startElement",
"(",
"\"div\"",
",",
"component",
")",
";",
"rw",
".",
"writeAttribute",
"(",
"\"id\"",
",",
"component",
".",
"getId",
"(",
")",
",",
"\"id\"",
")",
";",
"if",
"(",
"component",
"instanceof",
"CarouselCaption",
")",
"{",
"Tooltip",
".",
"generateTooltip",
"(",
"context",
",",
"(",
"(",
"CarouselCaption",
")",
"component",
")",
",",
"rw",
")",
";",
"AJAXRenderer",
".",
"generateBootsFacesAJAXAndJavaScript",
"(",
"context",
",",
"(",
"(",
"CarouselCaption",
")",
"component",
")",
",",
"rw",
",",
"false",
")",
";",
"rw",
".",
"writeAttribute",
"(",
"\"style\"",
",",
"(",
"(",
"CarouselCaption",
")",
"component",
")",
".",
"getStyle",
"(",
")",
",",
"\"style\"",
")",
";",
"}",
"String",
"styleClass",
"=",
"null",
";",
"if",
"(",
"component",
"instanceof",
"CarouselCaption",
")",
"{",
"styleClass",
"=",
"(",
"(",
"CarouselCaption",
")",
"component",
")",
".",
"getStyleClass",
"(",
")",
";",
"}",
"if",
"(",
"null",
"==",
"styleClass",
")",
"styleClass",
"=",
"\"carousel-caption\"",
";",
"else",
"styleClass",
"=",
"\"carousel-caption \"",
"+",
"styleClass",
";",
"rw",
".",
"writeAttribute",
"(",
"\"class\"",
",",
"styleClass",
",",
"\"class\"",
")",
";",
"}"
] | This methods generates the HTML code of the current b:carouselCaption.
<code>encodeBegin</code> generates the start of the component. After the,
the JSF framework calls <code>encodeChildren()</code> to generate the
HTML code between the beginning and the end of the component. For
instance, in the case of a panel component the content of the panel is
generated by <code>encodeChildren()</code>. After that,
<code>encodeEnd()</code> is called to generate the rest of the HTML code.
@param context
the FacesContext.
@param component
the current b:carouselCaption.
@throws IOException
thrown if something goes wrong when writing the HTML code. | [
"This",
"methods",
"generates",
"the",
"HTML",
"code",
"of",
"the",
"current",
"b",
":",
"carouselCaption",
".",
"<code",
">",
"encodeBegin<",
"/",
"code",
">",
"generates",
"the",
"start",
"of",
"the",
"component",
".",
"After",
"the",
"the",
"JSF",
"framework",
"calls",
"<code",
">",
"encodeChildren",
"()",
"<",
"/",
"code",
">",
"to",
"generate",
"the",
"HTML",
"code",
"between",
"the",
"beginning",
"and",
"the",
"end",
"of",
"the",
"component",
".",
"For",
"instance",
"in",
"the",
"case",
"of",
"a",
"panel",
"component",
"the",
"content",
"of",
"the",
"panel",
"is",
"generated",
"by",
"<code",
">",
"encodeChildren",
"()",
"<",
"/",
"code",
">",
".",
"After",
"that",
"<code",
">",
"encodeEnd",
"()",
"<",
"/",
"code",
">",
"is",
"called",
"to",
"generate",
"the",
"rest",
"of",
"the",
"HTML",
"code",
"."
] | train | https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/carouselCaption/CarouselCaptionRenderer.java#L69-L94 |
wildfly/wildfly-core | server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java | DeploymentResourceSupport.getOrCreateSubDeployment | static Resource getOrCreateSubDeployment(final String deploymentName, final DeploymentUnit parent) {
"""
Gets or creates the a resource for the sub-deployment on the parent deployments resource.
@param deploymentName the name of the deployment
@param parent the parent deployment used to find the parent resource
@return the already registered resource or a newly created resource
"""
final Resource root = parent.getAttachment(DEPLOYMENT_RESOURCE);
return getOrCreate(root, PathElement.pathElement(SUBDEPLOYMENT, deploymentName));
} | java | static Resource getOrCreateSubDeployment(final String deploymentName, final DeploymentUnit parent) {
final Resource root = parent.getAttachment(DEPLOYMENT_RESOURCE);
return getOrCreate(root, PathElement.pathElement(SUBDEPLOYMENT, deploymentName));
} | [
"static",
"Resource",
"getOrCreateSubDeployment",
"(",
"final",
"String",
"deploymentName",
",",
"final",
"DeploymentUnit",
"parent",
")",
"{",
"final",
"Resource",
"root",
"=",
"parent",
".",
"getAttachment",
"(",
"DEPLOYMENT_RESOURCE",
")",
";",
"return",
"getOrCreate",
"(",
"root",
",",
"PathElement",
".",
"pathElement",
"(",
"SUBDEPLOYMENT",
",",
"deploymentName",
")",
")",
";",
"}"
] | Gets or creates the a resource for the sub-deployment on the parent deployments resource.
@param deploymentName the name of the deployment
@param parent the parent deployment used to find the parent resource
@return the already registered resource or a newly created resource | [
"Gets",
"or",
"creates",
"the",
"a",
"resource",
"for",
"the",
"sub",
"-",
"deployment",
"on",
"the",
"parent",
"deployments",
"resource",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java#L231-L234 |
radkovo/CSSBox | src/main/java/org/fit/cssbox/layout/FloatList.java | FloatList.getMaxYForOwner | public int getMaxYForOwner(BlockBox owner, boolean requireVisible) {
"""
Goes through all the boxes and computes the Y coordinate of the bottom edge
of the lowest box. Only the boxes with the 'owner' containing block are taken
into account.
@param owner the owning block
@return the maximal Y coordinate
"""
int maxy = 0;
for (int i = 0; i < size(); i++)
{
Box box = getBox(i);
if ((!requireVisible || box.isDeclaredVisible()) && box.getContainingBlockBox() == owner)
{
int ny = box.bounds.y + box.bounds.height; //TODO: -1 here?
if (ny > maxy) maxy = ny;
}
}
return maxy;
} | java | public int getMaxYForOwner(BlockBox owner, boolean requireVisible)
{
int maxy = 0;
for (int i = 0; i < size(); i++)
{
Box box = getBox(i);
if ((!requireVisible || box.isDeclaredVisible()) && box.getContainingBlockBox() == owner)
{
int ny = box.bounds.y + box.bounds.height; //TODO: -1 here?
if (ny > maxy) maxy = ny;
}
}
return maxy;
} | [
"public",
"int",
"getMaxYForOwner",
"(",
"BlockBox",
"owner",
",",
"boolean",
"requireVisible",
")",
"{",
"int",
"maxy",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"Box",
"box",
"=",
"getBox",
"(",
"i",
")",
";",
"if",
"(",
"(",
"!",
"requireVisible",
"||",
"box",
".",
"isDeclaredVisible",
"(",
")",
")",
"&&",
"box",
".",
"getContainingBlockBox",
"(",
")",
"==",
"owner",
")",
"{",
"int",
"ny",
"=",
"box",
".",
"bounds",
".",
"y",
"+",
"box",
".",
"bounds",
".",
"height",
";",
"//TODO: -1 here?",
"if",
"(",
"ny",
">",
"maxy",
")",
"maxy",
"=",
"ny",
";",
"}",
"}",
"return",
"maxy",
";",
"}"
] | Goes through all the boxes and computes the Y coordinate of the bottom edge
of the lowest box. Only the boxes with the 'owner' containing block are taken
into account.
@param owner the owning block
@return the maximal Y coordinate | [
"Goes",
"through",
"all",
"the",
"boxes",
"and",
"computes",
"the",
"Y",
"coordinate",
"of",
"the",
"bottom",
"edge",
"of",
"the",
"lowest",
"box",
".",
"Only",
"the",
"boxes",
"with",
"the",
"owner",
"containing",
"block",
"are",
"taken",
"into",
"account",
"."
] | train | https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/layout/FloatList.java#L170-L183 |
graknlabs/grakn | server/src/server/keyspace/KeyspaceManager.java | KeyspaceManager.putKeyspace | public void putKeyspace(KeyspaceImpl keyspace) {
"""
Logs a new KeyspaceImpl to the KeyspaceManager.
@param keyspace The new KeyspaceImpl we have just created
"""
if (containsKeyspace(keyspace)) return;
try (TransactionOLTP tx = systemKeyspaceSession.transaction().write()) {
AttributeType<String> keyspaceName = tx.getSchemaConcept(KEYSPACE_RESOURCE);
if (keyspaceName == null) {
throw GraknServerException.initializationException(keyspace);
}
Attribute<String> attribute = keyspaceName.create(keyspace.name());
if (attribute.owner() == null) {
tx.<EntityType>getSchemaConcept(KEYSPACE_ENTITY).create().has(attribute);
}
tx.commit();
// add to cache
existingKeyspaces.add(keyspace);
} catch (InvalidKBException e) {
throw new RuntimeException("Could not add keyspace [" + keyspace + "] to system graph", e);
}
} | java | public void putKeyspace(KeyspaceImpl keyspace) {
if (containsKeyspace(keyspace)) return;
try (TransactionOLTP tx = systemKeyspaceSession.transaction().write()) {
AttributeType<String> keyspaceName = tx.getSchemaConcept(KEYSPACE_RESOURCE);
if (keyspaceName == null) {
throw GraknServerException.initializationException(keyspace);
}
Attribute<String> attribute = keyspaceName.create(keyspace.name());
if (attribute.owner() == null) {
tx.<EntityType>getSchemaConcept(KEYSPACE_ENTITY).create().has(attribute);
}
tx.commit();
// add to cache
existingKeyspaces.add(keyspace);
} catch (InvalidKBException e) {
throw new RuntimeException("Could not add keyspace [" + keyspace + "] to system graph", e);
}
} | [
"public",
"void",
"putKeyspace",
"(",
"KeyspaceImpl",
"keyspace",
")",
"{",
"if",
"(",
"containsKeyspace",
"(",
"keyspace",
")",
")",
"return",
";",
"try",
"(",
"TransactionOLTP",
"tx",
"=",
"systemKeyspaceSession",
".",
"transaction",
"(",
")",
".",
"write",
"(",
")",
")",
"{",
"AttributeType",
"<",
"String",
">",
"keyspaceName",
"=",
"tx",
".",
"getSchemaConcept",
"(",
"KEYSPACE_RESOURCE",
")",
";",
"if",
"(",
"keyspaceName",
"==",
"null",
")",
"{",
"throw",
"GraknServerException",
".",
"initializationException",
"(",
"keyspace",
")",
";",
"}",
"Attribute",
"<",
"String",
">",
"attribute",
"=",
"keyspaceName",
".",
"create",
"(",
"keyspace",
".",
"name",
"(",
")",
")",
";",
"if",
"(",
"attribute",
".",
"owner",
"(",
")",
"==",
"null",
")",
"{",
"tx",
".",
"<",
"EntityType",
">",
"getSchemaConcept",
"(",
"KEYSPACE_ENTITY",
")",
".",
"create",
"(",
")",
".",
"has",
"(",
"attribute",
")",
";",
"}",
"tx",
".",
"commit",
"(",
")",
";",
"// add to cache",
"existingKeyspaces",
".",
"add",
"(",
"keyspace",
")",
";",
"}",
"catch",
"(",
"InvalidKBException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Could not add keyspace [\"",
"+",
"keyspace",
"+",
"\"] to system graph\"",
",",
"e",
")",
";",
"}",
"}"
] | Logs a new KeyspaceImpl to the KeyspaceManager.
@param keyspace The new KeyspaceImpl we have just created | [
"Logs",
"a",
"new",
"KeyspaceImpl",
"to",
"the",
"KeyspaceManager",
"."
] | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/keyspace/KeyspaceManager.java#L72-L91 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java | IoUtil.read | public static String read(FileChannel fileChannel, String charsetName) throws IORuntimeException {
"""
从FileChannel中读取内容,读取完毕后并不关闭Channel
@param fileChannel 文件管道
@param charsetName 字符集
@return 内容
@throws IORuntimeException IO异常
"""
return read(fileChannel, CharsetUtil.charset(charsetName));
} | java | public static String read(FileChannel fileChannel, String charsetName) throws IORuntimeException {
return read(fileChannel, CharsetUtil.charset(charsetName));
} | [
"public",
"static",
"String",
"read",
"(",
"FileChannel",
"fileChannel",
",",
"String",
"charsetName",
")",
"throws",
"IORuntimeException",
"{",
"return",
"read",
"(",
"fileChannel",
",",
"CharsetUtil",
".",
"charset",
"(",
"charsetName",
")",
")",
";",
"}"
] | 从FileChannel中读取内容,读取完毕后并不关闭Channel
@param fileChannel 文件管道
@param charsetName 字符集
@return 内容
@throws IORuntimeException IO异常 | [
"从FileChannel中读取内容,读取完毕后并不关闭Channel"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java#L493-L495 |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/circle/DetectCircleGrid.java | DetectCircleGrid.pruneIncorrectSize | static void pruneIncorrectSize(List<List<EllipsesIntoClusters.Node>> clusters, int N) {
"""
Prune clusters which do not have the expected number of elements
"""
// prune clusters which can't be a member calibration target
for (int i = clusters.size()-1; i >= 0; i--) {
if( clusters.get(i).size() != N ) {
clusters.remove(i);
}
}
} | java | static void pruneIncorrectSize(List<List<EllipsesIntoClusters.Node>> clusters, int N) {
// prune clusters which can't be a member calibration target
for (int i = clusters.size()-1; i >= 0; i--) {
if( clusters.get(i).size() != N ) {
clusters.remove(i);
}
}
} | [
"static",
"void",
"pruneIncorrectSize",
"(",
"List",
"<",
"List",
"<",
"EllipsesIntoClusters",
".",
"Node",
">",
">",
"clusters",
",",
"int",
"N",
")",
"{",
"// prune clusters which can't be a member calibration target",
"for",
"(",
"int",
"i",
"=",
"clusters",
".",
"size",
"(",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"if",
"(",
"clusters",
".",
"get",
"(",
"i",
")",
".",
"size",
"(",
")",
"!=",
"N",
")",
"{",
"clusters",
".",
"remove",
"(",
"i",
")",
";",
"}",
"}",
"}"
] | Prune clusters which do not have the expected number of elements | [
"Prune",
"clusters",
"which",
"do",
"not",
"have",
"the",
"expected",
"number",
"of",
"elements"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/circle/DetectCircleGrid.java#L260-L267 |
hankcs/HanLP | src/main/java/com/hankcs/hanlp/dictionary/ns/PlaceDictionary.java | PlaceDictionary.parsePattern | public static void parsePattern(List<NS> nsList, List<Vertex> vertexList, final WordNet wordNetOptimum, final WordNet wordNetAll) {
"""
模式匹配
@param nsList 确定的标注序列
@param vertexList 原始的未加角色标注的序列
@param wordNetOptimum 待优化的图
@param wordNetAll
"""
// ListIterator<Vertex> listIterator = vertexList.listIterator();
StringBuilder sbPattern = new StringBuilder(nsList.size());
for (NS ns : nsList)
{
sbPattern.append(ns.toString());
}
String pattern = sbPattern.toString();
final Vertex[] wordArray = vertexList.toArray(new Vertex[0]);
trie.parseText(pattern, new AhoCorasickDoubleArrayTrie.IHit<String>()
{
@Override
public void hit(int begin, int end, String value)
{
StringBuilder sbName = new StringBuilder();
for (int i = begin; i < end; ++i)
{
sbName.append(wordArray[i].realWord);
}
String name = sbName.toString();
// 对一些bad case做出调整
if (isBadCase(name)) return;
// 正式算它是一个名字
if (HanLP.Config.DEBUG)
{
System.out.printf("识别出地名:%s %s\n", name, value);
}
int offset = 0;
for (int i = 0; i < begin; ++i)
{
offset += wordArray[i].realWord.length();
}
wordNetOptimum.insert(offset, new Vertex(Predefine.TAG_PLACE, name, ATTRIBUTE, WORD_ID), wordNetAll);
}
});
} | java | public static void parsePattern(List<NS> nsList, List<Vertex> vertexList, final WordNet wordNetOptimum, final WordNet wordNetAll)
{
// ListIterator<Vertex> listIterator = vertexList.listIterator();
StringBuilder sbPattern = new StringBuilder(nsList.size());
for (NS ns : nsList)
{
sbPattern.append(ns.toString());
}
String pattern = sbPattern.toString();
final Vertex[] wordArray = vertexList.toArray(new Vertex[0]);
trie.parseText(pattern, new AhoCorasickDoubleArrayTrie.IHit<String>()
{
@Override
public void hit(int begin, int end, String value)
{
StringBuilder sbName = new StringBuilder();
for (int i = begin; i < end; ++i)
{
sbName.append(wordArray[i].realWord);
}
String name = sbName.toString();
// 对一些bad case做出调整
if (isBadCase(name)) return;
// 正式算它是一个名字
if (HanLP.Config.DEBUG)
{
System.out.printf("识别出地名:%s %s\n", name, value);
}
int offset = 0;
for (int i = 0; i < begin; ++i)
{
offset += wordArray[i].realWord.length();
}
wordNetOptimum.insert(offset, new Vertex(Predefine.TAG_PLACE, name, ATTRIBUTE, WORD_ID), wordNetAll);
}
});
} | [
"public",
"static",
"void",
"parsePattern",
"(",
"List",
"<",
"NS",
">",
"nsList",
",",
"List",
"<",
"Vertex",
">",
"vertexList",
",",
"final",
"WordNet",
"wordNetOptimum",
",",
"final",
"WordNet",
"wordNetAll",
")",
"{",
"// ListIterator<Vertex> listIterator = vertexList.listIterator();",
"StringBuilder",
"sbPattern",
"=",
"new",
"StringBuilder",
"(",
"nsList",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"NS",
"ns",
":",
"nsList",
")",
"{",
"sbPattern",
".",
"append",
"(",
"ns",
".",
"toString",
"(",
")",
")",
";",
"}",
"String",
"pattern",
"=",
"sbPattern",
".",
"toString",
"(",
")",
";",
"final",
"Vertex",
"[",
"]",
"wordArray",
"=",
"vertexList",
".",
"toArray",
"(",
"new",
"Vertex",
"[",
"0",
"]",
")",
";",
"trie",
".",
"parseText",
"(",
"pattern",
",",
"new",
"AhoCorasickDoubleArrayTrie",
".",
"IHit",
"<",
"String",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"hit",
"(",
"int",
"begin",
",",
"int",
"end",
",",
"String",
"value",
")",
"{",
"StringBuilder",
"sbName",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"begin",
";",
"i",
"<",
"end",
";",
"++",
"i",
")",
"{",
"sbName",
".",
"append",
"(",
"wordArray",
"[",
"i",
"]",
".",
"realWord",
")",
";",
"}",
"String",
"name",
"=",
"sbName",
".",
"toString",
"(",
")",
";",
"// 对一些bad case做出调整",
"if",
"(",
"isBadCase",
"(",
"name",
")",
")",
"return",
";",
"// 正式算它是一个名字",
"if",
"(",
"HanLP",
".",
"Config",
".",
"DEBUG",
")",
"{",
"System",
".",
"out",
".",
"printf",
"(",
"\"识别出地名:%s %s\\n\", name, valu",
"e",
";",
"",
"",
"",
"",
"}",
"int",
"offset",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"begin",
";",
"++",
"i",
")",
"{",
"offset",
"+=",
"wordArray",
"[",
"i",
"]",
".",
"realWord",
".",
"length",
"(",
")",
";",
"}",
"wordNetOptimum",
".",
"insert",
"(",
"offset",
",",
"new",
"Vertex",
"(",
"Predefine",
".",
"TAG_PLACE",
",",
"name",
",",
"ATTRIBUTE",
",",
"WORD_ID",
")",
",",
"wordNetAll",
")",
";",
"}",
"}",
")",
";",
"}"
] | 模式匹配
@param nsList 确定的标注序列
@param vertexList 原始的未加角色标注的序列
@param wordNetOptimum 待优化的图
@param wordNetAll | [
"模式匹配"
] | train | https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/dictionary/ns/PlaceDictionary.java#L84-L121 |
atomix/catalyst | serializer/src/main/java/io/atomix/catalyst/serializer/SerializerRegistry.java | SerializerRegistry.registerDefault | public synchronized SerializerRegistry registerDefault(Class<?> baseType, TypeSerializerFactory factory) {
"""
Registers the given factory as a default serializer factory for the given base type.
@param baseType The base type for which to register the serializer.
@param factory The serializer factory.
@return The serializer registry.
"""
defaultFactories.put(baseType, factory);
return this;
} | java | public synchronized SerializerRegistry registerDefault(Class<?> baseType, TypeSerializerFactory factory) {
defaultFactories.put(baseType, factory);
return this;
} | [
"public",
"synchronized",
"SerializerRegistry",
"registerDefault",
"(",
"Class",
"<",
"?",
">",
"baseType",
",",
"TypeSerializerFactory",
"factory",
")",
"{",
"defaultFactories",
".",
"put",
"(",
"baseType",
",",
"factory",
")",
";",
"return",
"this",
";",
"}"
] | Registers the given factory as a default serializer factory for the given base type.
@param baseType The base type for which to register the serializer.
@param factory The serializer factory.
@return The serializer registry. | [
"Registers",
"the",
"given",
"factory",
"as",
"a",
"default",
"serializer",
"factory",
"for",
"the",
"given",
"base",
"type",
"."
] | train | https://github.com/atomix/catalyst/blob/140e762cb975cd8ee1fd85119043c5b8bf917c5c/serializer/src/main/java/io/atomix/catalyst/serializer/SerializerRegistry.java#L268-L271 |
osglworks/java-tool | src/main/java/org/osgl/util/E.java | E.invalidConfigurationIfNot | public static void invalidConfigurationIfNot(boolean tester, String msg, Object... args) {
"""
Throws out a {@link ConfigurationException} with message specified if `tester` evaluated to `false`.
@param tester
when `false` then throw out the exception
@param msg
the error message format pattern.
@param args
the error message format arguments.
"""
if (!tester) {
invalidConfiguration(msg, args);
}
} | java | public static void invalidConfigurationIfNot(boolean tester, String msg, Object... args) {
if (!tester) {
invalidConfiguration(msg, args);
}
} | [
"public",
"static",
"void",
"invalidConfigurationIfNot",
"(",
"boolean",
"tester",
",",
"String",
"msg",
",",
"Object",
"...",
"args",
")",
"{",
"if",
"(",
"!",
"tester",
")",
"{",
"invalidConfiguration",
"(",
"msg",
",",
"args",
")",
";",
"}",
"}"
] | Throws out a {@link ConfigurationException} with message specified if `tester` evaluated to `false`.
@param tester
when `false` then throw out the exception
@param msg
the error message format pattern.
@param args
the error message format arguments. | [
"Throws",
"out",
"a",
"{"
] | train | https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/util/E.java#L327-L331 |
dropwizard/metrics | metrics-graphite/src/main/java/com/codahale/metrics/graphite/PickledGraphite.java | PickledGraphite.pickleMetrics | byte[] pickleMetrics(List<MetricTuple> metrics) throws IOException {
"""
See: http://readthedocs.org/docs/graphite/en/1.0/feeding-carbon.html
@throws IOException shouldn't happen because we write to memory.
"""
// Extremely rough estimate of 75 bytes per message
ByteArrayOutputStream out = new ByteArrayOutputStream(metrics.size() * 75);
Writer pickled = new OutputStreamWriter(out, charset);
pickled.append(MARK);
pickled.append(LIST);
for (MetricTuple tuple : metrics) {
// start the outer tuple
pickled.append(MARK);
// the metric name is a string.
pickled.append(STRING);
// the single quotes are to match python's repr("abcd")
pickled.append(QUOTE);
pickled.append(tuple.name);
pickled.append(QUOTE);
pickled.append(LF);
// start the inner tuple
pickled.append(MARK);
// timestamp is a long
pickled.append(LONG);
pickled.append(Long.toString(tuple.timestamp));
// the trailing L is to match python's repr(long(1234))
pickled.append(LONG);
pickled.append(LF);
// and the value is a string.
pickled.append(STRING);
pickled.append(QUOTE);
pickled.append(tuple.value);
pickled.append(QUOTE);
pickled.append(LF);
pickled.append(TUPLE); // inner close
pickled.append(TUPLE); // outer close
pickled.append(APPEND);
}
// every pickle ends with STOP
pickled.append(STOP);
pickled.flush();
return out.toByteArray();
} | java | byte[] pickleMetrics(List<MetricTuple> metrics) throws IOException {
// Extremely rough estimate of 75 bytes per message
ByteArrayOutputStream out = new ByteArrayOutputStream(metrics.size() * 75);
Writer pickled = new OutputStreamWriter(out, charset);
pickled.append(MARK);
pickled.append(LIST);
for (MetricTuple tuple : metrics) {
// start the outer tuple
pickled.append(MARK);
// the metric name is a string.
pickled.append(STRING);
// the single quotes are to match python's repr("abcd")
pickled.append(QUOTE);
pickled.append(tuple.name);
pickled.append(QUOTE);
pickled.append(LF);
// start the inner tuple
pickled.append(MARK);
// timestamp is a long
pickled.append(LONG);
pickled.append(Long.toString(tuple.timestamp));
// the trailing L is to match python's repr(long(1234))
pickled.append(LONG);
pickled.append(LF);
// and the value is a string.
pickled.append(STRING);
pickled.append(QUOTE);
pickled.append(tuple.value);
pickled.append(QUOTE);
pickled.append(LF);
pickled.append(TUPLE); // inner close
pickled.append(TUPLE); // outer close
pickled.append(APPEND);
}
// every pickle ends with STOP
pickled.append(STOP);
pickled.flush();
return out.toByteArray();
} | [
"byte",
"[",
"]",
"pickleMetrics",
"(",
"List",
"<",
"MetricTuple",
">",
"metrics",
")",
"throws",
"IOException",
"{",
"// Extremely rough estimate of 75 bytes per message",
"ByteArrayOutputStream",
"out",
"=",
"new",
"ByteArrayOutputStream",
"(",
"metrics",
".",
"size",
"(",
")",
"*",
"75",
")",
";",
"Writer",
"pickled",
"=",
"new",
"OutputStreamWriter",
"(",
"out",
",",
"charset",
")",
";",
"pickled",
".",
"append",
"(",
"MARK",
")",
";",
"pickled",
".",
"append",
"(",
"LIST",
")",
";",
"for",
"(",
"MetricTuple",
"tuple",
":",
"metrics",
")",
"{",
"// start the outer tuple",
"pickled",
".",
"append",
"(",
"MARK",
")",
";",
"// the metric name is a string.",
"pickled",
".",
"append",
"(",
"STRING",
")",
";",
"// the single quotes are to match python's repr(\"abcd\")",
"pickled",
".",
"append",
"(",
"QUOTE",
")",
";",
"pickled",
".",
"append",
"(",
"tuple",
".",
"name",
")",
";",
"pickled",
".",
"append",
"(",
"QUOTE",
")",
";",
"pickled",
".",
"append",
"(",
"LF",
")",
";",
"// start the inner tuple",
"pickled",
".",
"append",
"(",
"MARK",
")",
";",
"// timestamp is a long",
"pickled",
".",
"append",
"(",
"LONG",
")",
";",
"pickled",
".",
"append",
"(",
"Long",
".",
"toString",
"(",
"tuple",
".",
"timestamp",
")",
")",
";",
"// the trailing L is to match python's repr(long(1234))",
"pickled",
".",
"append",
"(",
"LONG",
")",
";",
"pickled",
".",
"append",
"(",
"LF",
")",
";",
"// and the value is a string.",
"pickled",
".",
"append",
"(",
"STRING",
")",
";",
"pickled",
".",
"append",
"(",
"QUOTE",
")",
";",
"pickled",
".",
"append",
"(",
"tuple",
".",
"value",
")",
";",
"pickled",
".",
"append",
"(",
"QUOTE",
")",
";",
"pickled",
".",
"append",
"(",
"LF",
")",
";",
"pickled",
".",
"append",
"(",
"TUPLE",
")",
";",
"// inner close",
"pickled",
".",
"append",
"(",
"TUPLE",
")",
";",
"// outer close",
"pickled",
".",
"append",
"(",
"APPEND",
")",
";",
"}",
"// every pickle ends with STOP",
"pickled",
".",
"append",
"(",
"STOP",
")",
";",
"pickled",
".",
"flush",
"(",
")",
";",
"return",
"out",
".",
"toByteArray",
"(",
")",
";",
"}"
] | See: http://readthedocs.org/docs/graphite/en/1.0/feeding-carbon.html
@throws IOException shouldn't happen because we write to memory. | [
"See",
":",
"http",
":",
"//",
"readthedocs",
".",
"org",
"/",
"docs",
"/",
"graphite",
"/",
"en",
"/",
"1",
".",
"0",
"/",
"feeding",
"-",
"carbon",
".",
"html"
] | train | https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-graphite/src/main/java/com/codahale/metrics/graphite/PickledGraphite.java#L282-L331 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/DistributedFileSystem.java | DistributedFileSystem.reportChecksumFailure | public boolean reportChecksumFailure(Path f,
FSDataInputStream in, long inPos,
FSDataInputStream sums, long sumsPos) {
"""
We need to find the blocks that didn't match. Likely only one
is corrupt but we will report both to the namenode. In the future,
we can consider figuring out exactly which block is corrupt.
"""
LocatedBlock lblocks[] = new LocatedBlock[2];
// Find block in data stream.
DFSClient.DFSDataInputStream dfsIn = (DFSClient.DFSDataInputStream) in;
Block dataBlock = dfsIn.getCurrentBlock();
if (dataBlock == null) {
LOG.error("Error: Current block in data stream is null! ");
return false;
}
DatanodeInfo[] dataNode = {dfsIn.getCurrentDatanode()};
lblocks[0] = new LocatedBlock(dataBlock, dataNode);
LOG.info("Found checksum error in data stream at block="
+ dataBlock + " on datanode="
+ dataNode[0].getName());
// Find block in checksum stream
DFSClient.DFSDataInputStream dfsSums = (DFSClient.DFSDataInputStream) sums;
Block sumsBlock = dfsSums.getCurrentBlock();
if (sumsBlock == null) {
LOG.error("Error: Current block in checksum stream is null! ");
return false;
}
DatanodeInfo[] sumsNode = {dfsSums.getCurrentDatanode()};
lblocks[1] = new LocatedBlock(sumsBlock, sumsNode);
LOG.info("Found checksum error in checksum stream at block="
+ sumsBlock + " on datanode="
+ sumsNode[0].getName());
// Ask client to delete blocks.
dfs.reportChecksumFailure(f.toString(), lblocks);
return true;
} | java | public boolean reportChecksumFailure(Path f,
FSDataInputStream in, long inPos,
FSDataInputStream sums, long sumsPos) {
LocatedBlock lblocks[] = new LocatedBlock[2];
// Find block in data stream.
DFSClient.DFSDataInputStream dfsIn = (DFSClient.DFSDataInputStream) in;
Block dataBlock = dfsIn.getCurrentBlock();
if (dataBlock == null) {
LOG.error("Error: Current block in data stream is null! ");
return false;
}
DatanodeInfo[] dataNode = {dfsIn.getCurrentDatanode()};
lblocks[0] = new LocatedBlock(dataBlock, dataNode);
LOG.info("Found checksum error in data stream at block="
+ dataBlock + " on datanode="
+ dataNode[0].getName());
// Find block in checksum stream
DFSClient.DFSDataInputStream dfsSums = (DFSClient.DFSDataInputStream) sums;
Block sumsBlock = dfsSums.getCurrentBlock();
if (sumsBlock == null) {
LOG.error("Error: Current block in checksum stream is null! ");
return false;
}
DatanodeInfo[] sumsNode = {dfsSums.getCurrentDatanode()};
lblocks[1] = new LocatedBlock(sumsBlock, sumsNode);
LOG.info("Found checksum error in checksum stream at block="
+ sumsBlock + " on datanode="
+ sumsNode[0].getName());
// Ask client to delete blocks.
dfs.reportChecksumFailure(f.toString(), lblocks);
return true;
} | [
"public",
"boolean",
"reportChecksumFailure",
"(",
"Path",
"f",
",",
"FSDataInputStream",
"in",
",",
"long",
"inPos",
",",
"FSDataInputStream",
"sums",
",",
"long",
"sumsPos",
")",
"{",
"LocatedBlock",
"lblocks",
"[",
"]",
"=",
"new",
"LocatedBlock",
"[",
"2",
"]",
";",
"// Find block in data stream.",
"DFSClient",
".",
"DFSDataInputStream",
"dfsIn",
"=",
"(",
"DFSClient",
".",
"DFSDataInputStream",
")",
"in",
";",
"Block",
"dataBlock",
"=",
"dfsIn",
".",
"getCurrentBlock",
"(",
")",
";",
"if",
"(",
"dataBlock",
"==",
"null",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Error: Current block in data stream is null! \"",
")",
";",
"return",
"false",
";",
"}",
"DatanodeInfo",
"[",
"]",
"dataNode",
"=",
"{",
"dfsIn",
".",
"getCurrentDatanode",
"(",
")",
"}",
";",
"lblocks",
"[",
"0",
"]",
"=",
"new",
"LocatedBlock",
"(",
"dataBlock",
",",
"dataNode",
")",
";",
"LOG",
".",
"info",
"(",
"\"Found checksum error in data stream at block=\"",
"+",
"dataBlock",
"+",
"\" on datanode=\"",
"+",
"dataNode",
"[",
"0",
"]",
".",
"getName",
"(",
")",
")",
";",
"// Find block in checksum stream",
"DFSClient",
".",
"DFSDataInputStream",
"dfsSums",
"=",
"(",
"DFSClient",
".",
"DFSDataInputStream",
")",
"sums",
";",
"Block",
"sumsBlock",
"=",
"dfsSums",
".",
"getCurrentBlock",
"(",
")",
";",
"if",
"(",
"sumsBlock",
"==",
"null",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Error: Current block in checksum stream is null! \"",
")",
";",
"return",
"false",
";",
"}",
"DatanodeInfo",
"[",
"]",
"sumsNode",
"=",
"{",
"dfsSums",
".",
"getCurrentDatanode",
"(",
")",
"}",
";",
"lblocks",
"[",
"1",
"]",
"=",
"new",
"LocatedBlock",
"(",
"sumsBlock",
",",
"sumsNode",
")",
";",
"LOG",
".",
"info",
"(",
"\"Found checksum error in checksum stream at block=\"",
"+",
"sumsBlock",
"+",
"\" on datanode=\"",
"+",
"sumsNode",
"[",
"0",
"]",
".",
"getName",
"(",
")",
")",
";",
"// Ask client to delete blocks.",
"dfs",
".",
"reportChecksumFailure",
"(",
"f",
".",
"toString",
"(",
")",
",",
"lblocks",
")",
";",
"return",
"true",
";",
"}"
] | We need to find the blocks that didn't match. Likely only one
is corrupt but we will report both to the namenode. In the future,
we can consider figuring out exactly which block is corrupt. | [
"We",
"need",
"to",
"find",
"the",
"blocks",
"that",
"didn",
"t",
"match",
".",
"Likely",
"only",
"one",
"is",
"corrupt",
"but",
"we",
"will",
"report",
"both",
"to",
"the",
"namenode",
".",
"In",
"the",
"future",
"we",
"can",
"consider",
"figuring",
"out",
"exactly",
"which",
"block",
"is",
"corrupt",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/DistributedFileSystem.java#L780-L816 |
Talend/tesb-rt-se | sam/sam-agent/src/main/java/org/talend/esb/sam/agent/feature/EventFeatureImpl.java | EventFeatureImpl.detectWSAddressingFeature | private boolean detectWSAddressingFeature(InterceptorProvider provider, Bus bus) {
"""
detect if WS Addressing feature already enabled.
@param provider the interceptor provider
@param bus the bus
@return true, if successful
"""
//detect on the bus level
if (bus.getFeatures() != null) {
Iterator<Feature> busFeatures = bus.getFeatures().iterator();
while (busFeatures.hasNext()) {
Feature busFeature = busFeatures.next();
if (busFeature instanceof WSAddressingFeature) {
return true;
}
}
}
//detect on the endpoint/client level
Iterator<Interceptor<? extends Message>> interceptors = provider.getInInterceptors().iterator();
while (interceptors.hasNext()) {
Interceptor<? extends Message> ic = interceptors.next();
if (ic instanceof MAPAggregator) {
return true;
}
}
return false;
} | java | private boolean detectWSAddressingFeature(InterceptorProvider provider, Bus bus) {
//detect on the bus level
if (bus.getFeatures() != null) {
Iterator<Feature> busFeatures = bus.getFeatures().iterator();
while (busFeatures.hasNext()) {
Feature busFeature = busFeatures.next();
if (busFeature instanceof WSAddressingFeature) {
return true;
}
}
}
//detect on the endpoint/client level
Iterator<Interceptor<? extends Message>> interceptors = provider.getInInterceptors().iterator();
while (interceptors.hasNext()) {
Interceptor<? extends Message> ic = interceptors.next();
if (ic instanceof MAPAggregator) {
return true;
}
}
return false;
} | [
"private",
"boolean",
"detectWSAddressingFeature",
"(",
"InterceptorProvider",
"provider",
",",
"Bus",
"bus",
")",
"{",
"//detect on the bus level",
"if",
"(",
"bus",
".",
"getFeatures",
"(",
")",
"!=",
"null",
")",
"{",
"Iterator",
"<",
"Feature",
">",
"busFeatures",
"=",
"bus",
".",
"getFeatures",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"busFeatures",
".",
"hasNext",
"(",
")",
")",
"{",
"Feature",
"busFeature",
"=",
"busFeatures",
".",
"next",
"(",
")",
";",
"if",
"(",
"busFeature",
"instanceof",
"WSAddressingFeature",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"//detect on the endpoint/client level",
"Iterator",
"<",
"Interceptor",
"<",
"?",
"extends",
"Message",
">",
">",
"interceptors",
"=",
"provider",
".",
"getInInterceptors",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"interceptors",
".",
"hasNext",
"(",
")",
")",
"{",
"Interceptor",
"<",
"?",
"extends",
"Message",
">",
"ic",
"=",
"interceptors",
".",
"next",
"(",
")",
";",
"if",
"(",
"ic",
"instanceof",
"MAPAggregator",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | detect if WS Addressing feature already enabled.
@param provider the interceptor provider
@param bus the bus
@return true, if successful | [
"detect",
"if",
"WS",
"Addressing",
"feature",
"already",
"enabled",
"."
] | train | https://github.com/Talend/tesb-rt-se/blob/0a151a6d91ffff65ac4b5ee0c5b2c882ac28d886/sam/sam-agent/src/main/java/org/talend/esb/sam/agent/feature/EventFeatureImpl.java#L181-L203 |
lecho/hellocharts-android | hellocharts-library/src/lecho/lib/hellocharts/model/PointValue.java | PointValue.setTarget | public PointValue setTarget(float targetX, float targetY) {
"""
Set target values that should be reached when data animation finish then call {@link Chart#startDataAnimation()}
"""
set(x, y);
this.diffX = targetX - originX;
this.diffY = targetY - originY;
return this;
} | java | public PointValue setTarget(float targetX, float targetY) {
set(x, y);
this.diffX = targetX - originX;
this.diffY = targetY - originY;
return this;
} | [
"public",
"PointValue",
"setTarget",
"(",
"float",
"targetX",
",",
"float",
"targetY",
")",
"{",
"set",
"(",
"x",
",",
"y",
")",
";",
"this",
".",
"diffX",
"=",
"targetX",
"-",
"originX",
";",
"this",
".",
"diffY",
"=",
"targetY",
"-",
"originY",
";",
"return",
"this",
";",
"}"
] | Set target values that should be reached when data animation finish then call {@link Chart#startDataAnimation()} | [
"Set",
"target",
"values",
"that",
"should",
"be",
"reached",
"when",
"data",
"animation",
"finish",
"then",
"call",
"{"
] | train | https://github.com/lecho/hellocharts-android/blob/c41419c9afa097452dee823c7eba0e5136aa96bd/hellocharts-library/src/lecho/lib/hellocharts/model/PointValue.java#L55-L60 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/internal/FeatureLinkingCandidate.java | FeatureLinkingCandidate.getArguments | @Override
protected List<XExpression> getArguments() {
"""
Returns the actual arguments of the expression. These do not include the
receiver.
"""
List<XExpression> syntacticArguments = getSyntacticArguments();
XExpression firstArgument = getFirstArgument();
if (firstArgument != null) {
return createArgumentList(firstArgument, syntacticArguments);
}
return syntacticArguments;
} | java | @Override
protected List<XExpression> getArguments() {
List<XExpression> syntacticArguments = getSyntacticArguments();
XExpression firstArgument = getFirstArgument();
if (firstArgument != null) {
return createArgumentList(firstArgument, syntacticArguments);
}
return syntacticArguments;
} | [
"@",
"Override",
"protected",
"List",
"<",
"XExpression",
">",
"getArguments",
"(",
")",
"{",
"List",
"<",
"XExpression",
">",
"syntacticArguments",
"=",
"getSyntacticArguments",
"(",
")",
";",
"XExpression",
"firstArgument",
"=",
"getFirstArgument",
"(",
")",
";",
"if",
"(",
"firstArgument",
"!=",
"null",
")",
"{",
"return",
"createArgumentList",
"(",
"firstArgument",
",",
"syntacticArguments",
")",
";",
"}",
"return",
"syntacticArguments",
";",
"}"
] | Returns the actual arguments of the expression. These do not include the
receiver. | [
"Returns",
"the",
"actual",
"arguments",
"of",
"the",
"expression",
".",
"These",
"do",
"not",
"include",
"the",
"receiver",
"."
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/internal/FeatureLinkingCandidate.java#L122-L130 |
javalite/activejdbc | javalite-common/src/main/java/org/javalite/common/Inflector.java | Inflector.getOtherName | public static String getOtherName(String source, String target) {
"""
If a table name is made of two other table names (as is typical for many to many relationships),
this method retrieves a name of "another" table from a join table name.
For instance, if a source table is "payer" and the target is "player_game", then the returned value
will be "game".
@param source known table name. It may or may not exist in the target table name.
@param target this is a potential "join" table name.
@return a name of "another" table from a join table name.
"""
String other;
if (target.contains(source) && !target.equals(source)) {
int start = target.indexOf(source);
other = start == 0 ? target.substring(source.length()) : target.substring(0, start);
}
else{
return null;
}
if(other.startsWith("_")){
other = other.replaceFirst("_", " ");
}
if(other.endsWith("_")){
byte[] otherb = other.getBytes();
otherb[otherb.length - 1] = ' ';
other = new String(otherb);
}
return other.trim();
} | java | public static String getOtherName(String source, String target){
String other;
if (target.contains(source) && !target.equals(source)) {
int start = target.indexOf(source);
other = start == 0 ? target.substring(source.length()) : target.substring(0, start);
}
else{
return null;
}
if(other.startsWith("_")){
other = other.replaceFirst("_", " ");
}
if(other.endsWith("_")){
byte[] otherb = other.getBytes();
otherb[otherb.length - 1] = ' ';
other = new String(otherb);
}
return other.trim();
} | [
"public",
"static",
"String",
"getOtherName",
"(",
"String",
"source",
",",
"String",
"target",
")",
"{",
"String",
"other",
";",
"if",
"(",
"target",
".",
"contains",
"(",
"source",
")",
"&&",
"!",
"target",
".",
"equals",
"(",
"source",
")",
")",
"{",
"int",
"start",
"=",
"target",
".",
"indexOf",
"(",
"source",
")",
";",
"other",
"=",
"start",
"==",
"0",
"?",
"target",
".",
"substring",
"(",
"source",
".",
"length",
"(",
")",
")",
":",
"target",
".",
"substring",
"(",
"0",
",",
"start",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"other",
".",
"startsWith",
"(",
"\"_\"",
")",
")",
"{",
"other",
"=",
"other",
".",
"replaceFirst",
"(",
"\"_\"",
",",
"\" \"",
")",
";",
"}",
"if",
"(",
"other",
".",
"endsWith",
"(",
"\"_\"",
")",
")",
"{",
"byte",
"[",
"]",
"otherb",
"=",
"other",
".",
"getBytes",
"(",
")",
";",
"otherb",
"[",
"otherb",
".",
"length",
"-",
"1",
"]",
"=",
"'",
"'",
";",
"other",
"=",
"new",
"String",
"(",
"otherb",
")",
";",
"}",
"return",
"other",
".",
"trim",
"(",
")",
";",
"}"
] | If a table name is made of two other table names (as is typical for many to many relationships),
this method retrieves a name of "another" table from a join table name.
For instance, if a source table is "payer" and the target is "player_game", then the returned value
will be "game".
@param source known table name. It may or may not exist in the target table name.
@param target this is a potential "join" table name.
@return a name of "another" table from a join table name. | [
"If",
"a",
"table",
"name",
"is",
"made",
"of",
"two",
"other",
"table",
"names",
"(",
"as",
"is",
"typical",
"for",
"many",
"to",
"many",
"relationships",
")",
"this",
"method",
"retrieves",
"a",
"name",
"of",
"another",
"table",
"from",
"a",
"join",
"table",
"name",
".",
"For",
"instance",
"if",
"a",
"source",
"table",
"is",
"payer",
"and",
"the",
"target",
"is",
"player_game",
"then",
"the",
"returned",
"value",
"will",
"be",
"game",
"."
] | train | https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/javalite-common/src/main/java/org/javalite/common/Inflector.java#L265-L285 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java | TextRowProtocol.getInternalLocalDate | public LocalDate getInternalLocalDate(ColumnInformation columnInfo, TimeZone timeZone)
throws SQLException {
"""
Get LocalDate format from raw text format.
@param columnInfo column information
@param timeZone time zone
@return LocalDate value
@throws SQLException if column type doesn't permit conversion
"""
if (lastValueWasNull()) {
return null;
}
if (length == 0) {
lastValueNull |= BIT_LAST_FIELD_NULL;
return null;
}
String raw = new String(buf, pos, length, StandardCharsets.UTF_8);
switch (columnInfo.getColumnType().getSqlType()) {
case Types.DATE:
case Types.VARCHAR:
case Types.LONGVARCHAR:
case Types.CHAR:
if (raw.startsWith("0000-00-00")) {
return null;
}
try {
return LocalDate
.parse(raw, DateTimeFormatter.ISO_LOCAL_DATE.withZone(timeZone.toZoneId()));
} catch (DateTimeParseException dateParserEx) {
throw new SQLException(
raw + " cannot be parse as LocalDate (format is \"yyyy-MM-dd\" for data type \""
+ columnInfo.getColumnType() + "\")");
}
case Types.TIMESTAMP:
ZonedDateTime zonedDateTime = getInternalZonedDateTime(columnInfo, LocalDate.class,
timeZone);
return zonedDateTime == null ? null
: zonedDateTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDate();
default:
throw new SQLException(
"Cannot read LocalDate using a " + columnInfo.getColumnType().getJavaTypeName()
+ " field");
}
} | java | public LocalDate getInternalLocalDate(ColumnInformation columnInfo, TimeZone timeZone)
throws SQLException {
if (lastValueWasNull()) {
return null;
}
if (length == 0) {
lastValueNull |= BIT_LAST_FIELD_NULL;
return null;
}
String raw = new String(buf, pos, length, StandardCharsets.UTF_8);
switch (columnInfo.getColumnType().getSqlType()) {
case Types.DATE:
case Types.VARCHAR:
case Types.LONGVARCHAR:
case Types.CHAR:
if (raw.startsWith("0000-00-00")) {
return null;
}
try {
return LocalDate
.parse(raw, DateTimeFormatter.ISO_LOCAL_DATE.withZone(timeZone.toZoneId()));
} catch (DateTimeParseException dateParserEx) {
throw new SQLException(
raw + " cannot be parse as LocalDate (format is \"yyyy-MM-dd\" for data type \""
+ columnInfo.getColumnType() + "\")");
}
case Types.TIMESTAMP:
ZonedDateTime zonedDateTime = getInternalZonedDateTime(columnInfo, LocalDate.class,
timeZone);
return zonedDateTime == null ? null
: zonedDateTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDate();
default:
throw new SQLException(
"Cannot read LocalDate using a " + columnInfo.getColumnType().getJavaTypeName()
+ " field");
}
} | [
"public",
"LocalDate",
"getInternalLocalDate",
"(",
"ColumnInformation",
"columnInfo",
",",
"TimeZone",
"timeZone",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"lastValueWasNull",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"length",
"==",
"0",
")",
"{",
"lastValueNull",
"|=",
"BIT_LAST_FIELD_NULL",
";",
"return",
"null",
";",
"}",
"String",
"raw",
"=",
"new",
"String",
"(",
"buf",
",",
"pos",
",",
"length",
",",
"StandardCharsets",
".",
"UTF_8",
")",
";",
"switch",
"(",
"columnInfo",
".",
"getColumnType",
"(",
")",
".",
"getSqlType",
"(",
")",
")",
"{",
"case",
"Types",
".",
"DATE",
":",
"case",
"Types",
".",
"VARCHAR",
":",
"case",
"Types",
".",
"LONGVARCHAR",
":",
"case",
"Types",
".",
"CHAR",
":",
"if",
"(",
"raw",
".",
"startsWith",
"(",
"\"0000-00-00\"",
")",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"return",
"LocalDate",
".",
"parse",
"(",
"raw",
",",
"DateTimeFormatter",
".",
"ISO_LOCAL_DATE",
".",
"withZone",
"(",
"timeZone",
".",
"toZoneId",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"DateTimeParseException",
"dateParserEx",
")",
"{",
"throw",
"new",
"SQLException",
"(",
"raw",
"+",
"\" cannot be parse as LocalDate (format is \\\"yyyy-MM-dd\\\" for data type \\\"\"",
"+",
"columnInfo",
".",
"getColumnType",
"(",
")",
"+",
"\"\\\")\"",
")",
";",
"}",
"case",
"Types",
".",
"TIMESTAMP",
":",
"ZonedDateTime",
"zonedDateTime",
"=",
"getInternalZonedDateTime",
"(",
"columnInfo",
",",
"LocalDate",
".",
"class",
",",
"timeZone",
")",
";",
"return",
"zonedDateTime",
"==",
"null",
"?",
"null",
":",
"zonedDateTime",
".",
"withZoneSameInstant",
"(",
"ZoneId",
".",
"systemDefault",
"(",
")",
")",
".",
"toLocalDate",
"(",
")",
";",
"default",
":",
"throw",
"new",
"SQLException",
"(",
"\"Cannot read LocalDate using a \"",
"+",
"columnInfo",
".",
"getColumnType",
"(",
")",
".",
"getJavaTypeName",
"(",
")",
"+",
"\" field\"",
")",
";",
"}",
"}"
] | Get LocalDate format from raw text format.
@param columnInfo column information
@param timeZone time zone
@return LocalDate value
@throws SQLException if column type doesn't permit conversion | [
"Get",
"LocalDate",
"format",
"from",
"raw",
"text",
"format",
"."
] | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L1071-L1112 |
duracloud/duracloud | durastore/src/main/java/org/duracloud/durastore/rest/ContentResourceImpl.java | ContentResourceImpl.getContent | @Override
public RetrievedContent getContent(String spaceID,
String contentID,
String storeID,
String range)
throws InvalidRequestException, ResourceException {
"""
Retrieves content from a space.
@param spaceID
@param contentID
@return InputStream which can be used to read content.
"""
try {
StorageProvider storage =
storageProviderFactory.getStorageProvider(storeID);
return storage.getContent(spaceID, contentID, range);
} catch (NotFoundException e) {
throw new ResourceNotFoundException("get content",
spaceID,
contentID,
e);
} catch (StorageStateException e) {
throw new ResourceStateException("get content",
spaceID,
contentID,
e);
} catch (IllegalArgumentException e) {
throw new InvalidRequestException(e.getMessage());
} catch (Exception e) {
storageProviderFactory.expireStorageProvider(storeID);
throw new ResourceException("get content", spaceID, contentID, e);
}
} | java | @Override
public RetrievedContent getContent(String spaceID,
String contentID,
String storeID,
String range)
throws InvalidRequestException, ResourceException {
try {
StorageProvider storage =
storageProviderFactory.getStorageProvider(storeID);
return storage.getContent(spaceID, contentID, range);
} catch (NotFoundException e) {
throw new ResourceNotFoundException("get content",
spaceID,
contentID,
e);
} catch (StorageStateException e) {
throw new ResourceStateException("get content",
spaceID,
contentID,
e);
} catch (IllegalArgumentException e) {
throw new InvalidRequestException(e.getMessage());
} catch (Exception e) {
storageProviderFactory.expireStorageProvider(storeID);
throw new ResourceException("get content", spaceID, contentID, e);
}
} | [
"@",
"Override",
"public",
"RetrievedContent",
"getContent",
"(",
"String",
"spaceID",
",",
"String",
"contentID",
",",
"String",
"storeID",
",",
"String",
"range",
")",
"throws",
"InvalidRequestException",
",",
"ResourceException",
"{",
"try",
"{",
"StorageProvider",
"storage",
"=",
"storageProviderFactory",
".",
"getStorageProvider",
"(",
"storeID",
")",
";",
"return",
"storage",
".",
"getContent",
"(",
"spaceID",
",",
"contentID",
",",
"range",
")",
";",
"}",
"catch",
"(",
"NotFoundException",
"e",
")",
"{",
"throw",
"new",
"ResourceNotFoundException",
"(",
"\"get content\"",
",",
"spaceID",
",",
"contentID",
",",
"e",
")",
";",
"}",
"catch",
"(",
"StorageStateException",
"e",
")",
"{",
"throw",
"new",
"ResourceStateException",
"(",
"\"get content\"",
",",
"spaceID",
",",
"contentID",
",",
"e",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"e",
")",
"{",
"throw",
"new",
"InvalidRequestException",
"(",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"storageProviderFactory",
".",
"expireStorageProvider",
"(",
"storeID",
")",
";",
"throw",
"new",
"ResourceException",
"(",
"\"get content\"",
",",
"spaceID",
",",
"contentID",
",",
"e",
")",
";",
"}",
"}"
] | Retrieves content from a space.
@param spaceID
@param contentID
@return InputStream which can be used to read content. | [
"Retrieves",
"content",
"from",
"a",
"space",
"."
] | train | https://github.com/duracloud/duracloud/blob/dc4f3a1716d43543cc3b2e1880605f9389849b66/durastore/src/main/java/org/duracloud/durastore/rest/ContentResourceImpl.java#L56-L83 |
alkacon/opencms-core | src/org/opencms/importexport/CmsImportVersion7.java | CmsImportVersion7.addAccountsOrgunitRules | protected void addAccountsOrgunitRules(Digester digester, String xpath) {
"""
Adds the XML digester rules for organizational units.<p>
@param digester the digester to add the rules to
@param xpath the base xpath for the rules
"""
digester.addCallMethod(xpath + N_NAME, "setOrgUnitName", 0);
digester.addCallMethod(xpath + N_DESCRIPTION, "setOrgUnitDescription", 0);
digester.addCallMethod(xpath + N_FLAGS, "setOrgUnitFlags", 0);
digester.addCallMethod(xpath + N_RESOURCES + "/" + N_RESOURCE, "addOrgUnitResource", 0);
digester.addCallMethod(xpath + N_RESOURCES, "importOrgUnit");
} | java | protected void addAccountsOrgunitRules(Digester digester, String xpath) {
digester.addCallMethod(xpath + N_NAME, "setOrgUnitName", 0);
digester.addCallMethod(xpath + N_DESCRIPTION, "setOrgUnitDescription", 0);
digester.addCallMethod(xpath + N_FLAGS, "setOrgUnitFlags", 0);
digester.addCallMethod(xpath + N_RESOURCES + "/" + N_RESOURCE, "addOrgUnitResource", 0);
digester.addCallMethod(xpath + N_RESOURCES, "importOrgUnit");
} | [
"protected",
"void",
"addAccountsOrgunitRules",
"(",
"Digester",
"digester",
",",
"String",
"xpath",
")",
"{",
"digester",
".",
"addCallMethod",
"(",
"xpath",
"+",
"N_NAME",
",",
"\"setOrgUnitName\"",
",",
"0",
")",
";",
"digester",
".",
"addCallMethod",
"(",
"xpath",
"+",
"N_DESCRIPTION",
",",
"\"setOrgUnitDescription\"",
",",
"0",
")",
";",
"digester",
".",
"addCallMethod",
"(",
"xpath",
"+",
"N_FLAGS",
",",
"\"setOrgUnitFlags\"",
",",
"0",
")",
";",
"digester",
".",
"addCallMethod",
"(",
"xpath",
"+",
"N_RESOURCES",
"+",
"\"/\"",
"+",
"N_RESOURCE",
",",
"\"addOrgUnitResource\"",
",",
"0",
")",
";",
"digester",
".",
"addCallMethod",
"(",
"xpath",
"+",
"N_RESOURCES",
",",
"\"importOrgUnit\"",
")",
";",
"}"
] | Adds the XML digester rules for organizational units.<p>
@param digester the digester to add the rules to
@param xpath the base xpath for the rules | [
"Adds",
"the",
"XML",
"digester",
"rules",
"for",
"organizational",
"units",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/CmsImportVersion7.java#L2993-L3000 |
medined/d4m | src/main/java/com/codebits/d4m/TableManager.java | TableManager.createTables | public void createTables() {
"""
Create D4M tables.
Five Accumulo tables support D4M. This method creates them
using the default root (unless the caller changes that default).
Tedge, TedgeTranspose, TedgeDegree, TedgeMetadata, TedgeText
"""
Validate.notNull(connector, "connector must not be null");
Validate.notNull(tableOperations, "tableOperations must not be null");
/*
* This code sets the default values. If you want to change them,
* you can over-write the metadata entries instead of changing
* the values here.
*/
Value defaultFieldDelimiter = new Value("\t".getBytes(charset));
Value defaultFactDelimiter = new Value("|".getBytes(charset));
int isEdgePresent = tableOperations.exists(getEdgeTable()) ? 1 : 0;
int isTransposePresent = tableOperations.exists(getTransposeTable()) ? 1 : 0;
int isDegreePresent = tableOperations.exists(getDegreeTable()) ? 1 : 0;
int isMetatablePresent = tableOperations.exists(getMetadataTable()) ? 1 : 0;
int isTextPresent = tableOperations.exists(getTextTable()) ? 1 : 0;
int tableCount = isEdgePresent + isTransposePresent + isDegreePresent + isMetatablePresent + isTextPresent;
if (tableCount > 0 && tableCount < 5) {
throw new D4MException("D4M: RootName[" + getRootName() + "] Inconsistent state - one or more D4M tables is missing.");
}
if (tableCount == 5) {
// assume the tables are correct.
return;
}
try {
tableOperations.create(getEdgeTable());
tableOperations.create(getTransposeTable());
tableOperations.create(getDegreeTable());
tableOperations.create(getMetadataTable());
tableOperations.create(getTextTable());
IteratorSetting degreeIteratorSetting = new IteratorSetting(7, SummingCombiner.class);
SummingCombiner.setEncodingType(degreeIteratorSetting, LongCombiner.Type.STRING);
SummingCombiner.setColumns(degreeIteratorSetting, Collections.singletonList(new IteratorSetting.Column("", "degree")));
tableOperations.attachIterator(getDegreeTable(), degreeIteratorSetting);
IteratorSetting fieldIteratorSetting = new IteratorSetting(7, SummingCombiner.class);
SummingCombiner.setEncodingType(fieldIteratorSetting, LongCombiner.Type.STRING);
SummingCombiner.setColumns(fieldIteratorSetting, Collections.singletonList(new IteratorSetting.Column("field", "")));
tableOperations.attachIterator(getMetadataTable(), fieldIteratorSetting);
Mutation mutation = new Mutation(PROPERTY);
mutation.put(FIELD_DELIMITER_PROPERTY_NAME, EMPTY_CQ, defaultFieldDelimiter);
mutation.put(FACT_DELIMITER_PROPERTY_NAME, EMPTY_CQ, defaultFactDelimiter);
BatchWriterConfig bwConfig = new BatchWriterConfig();
bwConfig.setMaxLatency(10000, TimeUnit.MINUTES);
bwConfig.setMaxMemory(10000000);
bwConfig.setMaxWriteThreads(5);
bwConfig.setTimeout(5, TimeUnit.MINUTES);
BatchWriter writer = connector.createBatchWriter(getMetadataTable(), bwConfig);
writer.addMutation(mutation);
writer.close();
} catch (AccumuloException | AccumuloSecurityException | TableExistsException | TableNotFoundException e) {
throw new D4MException("Error creating tables.", e);
}
} | java | public void createTables() {
Validate.notNull(connector, "connector must not be null");
Validate.notNull(tableOperations, "tableOperations must not be null");
/*
* This code sets the default values. If you want to change them,
* you can over-write the metadata entries instead of changing
* the values here.
*/
Value defaultFieldDelimiter = new Value("\t".getBytes(charset));
Value defaultFactDelimiter = new Value("|".getBytes(charset));
int isEdgePresent = tableOperations.exists(getEdgeTable()) ? 1 : 0;
int isTransposePresent = tableOperations.exists(getTransposeTable()) ? 1 : 0;
int isDegreePresent = tableOperations.exists(getDegreeTable()) ? 1 : 0;
int isMetatablePresent = tableOperations.exists(getMetadataTable()) ? 1 : 0;
int isTextPresent = tableOperations.exists(getTextTable()) ? 1 : 0;
int tableCount = isEdgePresent + isTransposePresent + isDegreePresent + isMetatablePresent + isTextPresent;
if (tableCount > 0 && tableCount < 5) {
throw new D4MException("D4M: RootName[" + getRootName() + "] Inconsistent state - one or more D4M tables is missing.");
}
if (tableCount == 5) {
// assume the tables are correct.
return;
}
try {
tableOperations.create(getEdgeTable());
tableOperations.create(getTransposeTable());
tableOperations.create(getDegreeTable());
tableOperations.create(getMetadataTable());
tableOperations.create(getTextTable());
IteratorSetting degreeIteratorSetting = new IteratorSetting(7, SummingCombiner.class);
SummingCombiner.setEncodingType(degreeIteratorSetting, LongCombiner.Type.STRING);
SummingCombiner.setColumns(degreeIteratorSetting, Collections.singletonList(new IteratorSetting.Column("", "degree")));
tableOperations.attachIterator(getDegreeTable(), degreeIteratorSetting);
IteratorSetting fieldIteratorSetting = new IteratorSetting(7, SummingCombiner.class);
SummingCombiner.setEncodingType(fieldIteratorSetting, LongCombiner.Type.STRING);
SummingCombiner.setColumns(fieldIteratorSetting, Collections.singletonList(new IteratorSetting.Column("field", "")));
tableOperations.attachIterator(getMetadataTable(), fieldIteratorSetting);
Mutation mutation = new Mutation(PROPERTY);
mutation.put(FIELD_DELIMITER_PROPERTY_NAME, EMPTY_CQ, defaultFieldDelimiter);
mutation.put(FACT_DELIMITER_PROPERTY_NAME, EMPTY_CQ, defaultFactDelimiter);
BatchWriterConfig bwConfig = new BatchWriterConfig();
bwConfig.setMaxLatency(10000, TimeUnit.MINUTES);
bwConfig.setMaxMemory(10000000);
bwConfig.setMaxWriteThreads(5);
bwConfig.setTimeout(5, TimeUnit.MINUTES);
BatchWriter writer = connector.createBatchWriter(getMetadataTable(), bwConfig);
writer.addMutation(mutation);
writer.close();
} catch (AccumuloException | AccumuloSecurityException | TableExistsException | TableNotFoundException e) {
throw new D4MException("Error creating tables.", e);
}
} | [
"public",
"void",
"createTables",
"(",
")",
"{",
"Validate",
".",
"notNull",
"(",
"connector",
",",
"\"connector must not be null\"",
")",
";",
"Validate",
".",
"notNull",
"(",
"tableOperations",
",",
"\"tableOperations must not be null\"",
")",
";",
"/*\n * This code sets the default values. If you want to change them,\n * you can over-write the metadata entries instead of changing\n * the values here.\n */",
"Value",
"defaultFieldDelimiter",
"=",
"new",
"Value",
"(",
"\"\\t\"",
".",
"getBytes",
"(",
"charset",
")",
")",
";",
"Value",
"defaultFactDelimiter",
"=",
"new",
"Value",
"(",
"\"|\"",
".",
"getBytes",
"(",
"charset",
")",
")",
";",
"int",
"isEdgePresent",
"=",
"tableOperations",
".",
"exists",
"(",
"getEdgeTable",
"(",
")",
")",
"?",
"1",
":",
"0",
";",
"int",
"isTransposePresent",
"=",
"tableOperations",
".",
"exists",
"(",
"getTransposeTable",
"(",
")",
")",
"?",
"1",
":",
"0",
";",
"int",
"isDegreePresent",
"=",
"tableOperations",
".",
"exists",
"(",
"getDegreeTable",
"(",
")",
")",
"?",
"1",
":",
"0",
";",
"int",
"isMetatablePresent",
"=",
"tableOperations",
".",
"exists",
"(",
"getMetadataTable",
"(",
")",
")",
"?",
"1",
":",
"0",
";",
"int",
"isTextPresent",
"=",
"tableOperations",
".",
"exists",
"(",
"getTextTable",
"(",
")",
")",
"?",
"1",
":",
"0",
";",
"int",
"tableCount",
"=",
"isEdgePresent",
"+",
"isTransposePresent",
"+",
"isDegreePresent",
"+",
"isMetatablePresent",
"+",
"isTextPresent",
";",
"if",
"(",
"tableCount",
">",
"0",
"&&",
"tableCount",
"<",
"5",
")",
"{",
"throw",
"new",
"D4MException",
"(",
"\"D4M: RootName[\"",
"+",
"getRootName",
"(",
")",
"+",
"\"] Inconsistent state - one or more D4M tables is missing.\"",
")",
";",
"}",
"if",
"(",
"tableCount",
"==",
"5",
")",
"{",
"// assume the tables are correct.",
"return",
";",
"}",
"try",
"{",
"tableOperations",
".",
"create",
"(",
"getEdgeTable",
"(",
")",
")",
";",
"tableOperations",
".",
"create",
"(",
"getTransposeTable",
"(",
")",
")",
";",
"tableOperations",
".",
"create",
"(",
"getDegreeTable",
"(",
")",
")",
";",
"tableOperations",
".",
"create",
"(",
"getMetadataTable",
"(",
")",
")",
";",
"tableOperations",
".",
"create",
"(",
"getTextTable",
"(",
")",
")",
";",
"IteratorSetting",
"degreeIteratorSetting",
"=",
"new",
"IteratorSetting",
"(",
"7",
",",
"SummingCombiner",
".",
"class",
")",
";",
"SummingCombiner",
".",
"setEncodingType",
"(",
"degreeIteratorSetting",
",",
"LongCombiner",
".",
"Type",
".",
"STRING",
")",
";",
"SummingCombiner",
".",
"setColumns",
"(",
"degreeIteratorSetting",
",",
"Collections",
".",
"singletonList",
"(",
"new",
"IteratorSetting",
".",
"Column",
"(",
"\"\"",
",",
"\"degree\"",
")",
")",
")",
";",
"tableOperations",
".",
"attachIterator",
"(",
"getDegreeTable",
"(",
")",
",",
"degreeIteratorSetting",
")",
";",
"IteratorSetting",
"fieldIteratorSetting",
"=",
"new",
"IteratorSetting",
"(",
"7",
",",
"SummingCombiner",
".",
"class",
")",
";",
"SummingCombiner",
".",
"setEncodingType",
"(",
"fieldIteratorSetting",
",",
"LongCombiner",
".",
"Type",
".",
"STRING",
")",
";",
"SummingCombiner",
".",
"setColumns",
"(",
"fieldIteratorSetting",
",",
"Collections",
".",
"singletonList",
"(",
"new",
"IteratorSetting",
".",
"Column",
"(",
"\"field\"",
",",
"\"\"",
")",
")",
")",
";",
"tableOperations",
".",
"attachIterator",
"(",
"getMetadataTable",
"(",
")",
",",
"fieldIteratorSetting",
")",
";",
"Mutation",
"mutation",
"=",
"new",
"Mutation",
"(",
"PROPERTY",
")",
";",
"mutation",
".",
"put",
"(",
"FIELD_DELIMITER_PROPERTY_NAME",
",",
"EMPTY_CQ",
",",
"defaultFieldDelimiter",
")",
";",
"mutation",
".",
"put",
"(",
"FACT_DELIMITER_PROPERTY_NAME",
",",
"EMPTY_CQ",
",",
"defaultFactDelimiter",
")",
";",
"BatchWriterConfig",
"bwConfig",
"=",
"new",
"BatchWriterConfig",
"(",
")",
";",
"bwConfig",
".",
"setMaxLatency",
"(",
"10000",
",",
"TimeUnit",
".",
"MINUTES",
")",
";",
"bwConfig",
".",
"setMaxMemory",
"(",
"10000000",
")",
";",
"bwConfig",
".",
"setMaxWriteThreads",
"(",
"5",
")",
";",
"bwConfig",
".",
"setTimeout",
"(",
"5",
",",
"TimeUnit",
".",
"MINUTES",
")",
";",
"BatchWriter",
"writer",
"=",
"connector",
".",
"createBatchWriter",
"(",
"getMetadataTable",
"(",
")",
",",
"bwConfig",
")",
";",
"writer",
".",
"addMutation",
"(",
"mutation",
")",
";",
"writer",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"AccumuloException",
"|",
"AccumuloSecurityException",
"|",
"TableExistsException",
"|",
"TableNotFoundException",
"e",
")",
"{",
"throw",
"new",
"D4MException",
"(",
"\"Error creating tables.\"",
",",
"e",
")",
";",
"}",
"}"
] | Create D4M tables.
Five Accumulo tables support D4M. This method creates them
using the default root (unless the caller changes that default).
Tedge, TedgeTranspose, TedgeDegree, TedgeMetadata, TedgeText | [
"Create",
"D4M",
"tables",
"."
] | train | https://github.com/medined/d4m/blob/b61100609fba6961f6c903fcf96b687122c5bf05/src/main/java/com/codebits/d4m/TableManager.java#L101-L164 |
belaban/JGroups | src/org/jgroups/protocols/tom/SenderManager.java | SenderManager.addNewMessageToSend | public void addNewMessageToSend(MessageID messageID, Collection<Address> destinations, long initialSequenceNumber,
boolean deliverToMyself) {
"""
Add a new message sent
@param messageID the message ID
@param destinations the destination set
@param initialSequenceNumber the initial sequence number
@param deliverToMyself true if *this* member is in destination sent, false otherwise
"""
MessageInfo messageInfo = new MessageInfo(destinations, initialSequenceNumber, deliverToMyself);
if (deliverToMyself) {
messageInfo.setProposeReceived(messageID.getAddress());
}
sentMessages.put(messageID, messageInfo);
} | java | public void addNewMessageToSend(MessageID messageID, Collection<Address> destinations, long initialSequenceNumber,
boolean deliverToMyself) {
MessageInfo messageInfo = new MessageInfo(destinations, initialSequenceNumber, deliverToMyself);
if (deliverToMyself) {
messageInfo.setProposeReceived(messageID.getAddress());
}
sentMessages.put(messageID, messageInfo);
} | [
"public",
"void",
"addNewMessageToSend",
"(",
"MessageID",
"messageID",
",",
"Collection",
"<",
"Address",
">",
"destinations",
",",
"long",
"initialSequenceNumber",
",",
"boolean",
"deliverToMyself",
")",
"{",
"MessageInfo",
"messageInfo",
"=",
"new",
"MessageInfo",
"(",
"destinations",
",",
"initialSequenceNumber",
",",
"deliverToMyself",
")",
";",
"if",
"(",
"deliverToMyself",
")",
"{",
"messageInfo",
".",
"setProposeReceived",
"(",
"messageID",
".",
"getAddress",
"(",
")",
")",
";",
"}",
"sentMessages",
".",
"put",
"(",
"messageID",
",",
"messageInfo",
")",
";",
"}"
] | Add a new message sent
@param messageID the message ID
@param destinations the destination set
@param initialSequenceNumber the initial sequence number
@param deliverToMyself true if *this* member is in destination sent, false otherwise | [
"Add",
"a",
"new",
"message",
"sent"
] | train | https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/protocols/tom/SenderManager.java#L28-L35 |
carewebframework/carewebframework-core | org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/property/PropertyUtil.java | PropertyUtil.saveValue | public static void saveValue(String propertyName, String instanceName, boolean asGlobal, String value) {
"""
Saves a string value to the underlying property store.
@param propertyName Name of the property to be saved.
@param instanceName An optional instance name. Specify null to indicate the default instance.
@param asGlobal If true, save as a global property. If false, save as a user property.
@param value Value to be saved. If null, any existing value is removed.
@see IPropertyService#saveValue
"""
getPropertyService().saveValue(propertyName, instanceName, asGlobal, value);
} | java | public static void saveValue(String propertyName, String instanceName, boolean asGlobal, String value) {
getPropertyService().saveValue(propertyName, instanceName, asGlobal, value);
} | [
"public",
"static",
"void",
"saveValue",
"(",
"String",
"propertyName",
",",
"String",
"instanceName",
",",
"boolean",
"asGlobal",
",",
"String",
"value",
")",
"{",
"getPropertyService",
"(",
")",
".",
"saveValue",
"(",
"propertyName",
",",
"instanceName",
",",
"asGlobal",
",",
"value",
")",
";",
"}"
] | Saves a string value to the underlying property store.
@param propertyName Name of the property to be saved.
@param instanceName An optional instance name. Specify null to indicate the default instance.
@param asGlobal If true, save as a global property. If false, save as a user property.
@param value Value to be saved. If null, any existing value is removed.
@see IPropertyService#saveValue | [
"Saves",
"a",
"string",
"value",
"to",
"the",
"underlying",
"property",
"store",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/property/PropertyUtil.java#L119-L121 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/util/selenium/by/GridBy.java | GridBy.getXPathForHeaderRowByHeaders | public static String getXPathForHeaderRowByHeaders(String columnName, String... extraColumnNames) {
"""
Creates an XPath expression that will find a header row, selecting the row based on the
header texts present.
@param columnName first header text which must be present.
@param extraColumnNames name of other header texts that must be present in table's header row.
@return XPath expression selecting a tr in the row
"""
String allHeadersPresent;
if (extraColumnNames != null && extraColumnNames.length > 0) {
int extraCount = extraColumnNames.length;
String[] columnNames = new String[extraCount + 1];
columnNames[0] = columnName;
System.arraycopy(extraColumnNames, 0, columnNames, 1, extraCount);
allHeadersPresent = Stream.of(columnNames)
.map(GridBy::getXPathForHeaderCellWithText)
.collect(Collectors.joining(" and "));
} else {
allHeadersPresent = getXPathForHeaderCellWithText(columnName);
}
return String.format("/tr[%1$s]", allHeadersPresent);
} | java | public static String getXPathForHeaderRowByHeaders(String columnName, String... extraColumnNames) {
String allHeadersPresent;
if (extraColumnNames != null && extraColumnNames.length > 0) {
int extraCount = extraColumnNames.length;
String[] columnNames = new String[extraCount + 1];
columnNames[0] = columnName;
System.arraycopy(extraColumnNames, 0, columnNames, 1, extraCount);
allHeadersPresent = Stream.of(columnNames)
.map(GridBy::getXPathForHeaderCellWithText)
.collect(Collectors.joining(" and "));
} else {
allHeadersPresent = getXPathForHeaderCellWithText(columnName);
}
return String.format("/tr[%1$s]", allHeadersPresent);
} | [
"public",
"static",
"String",
"getXPathForHeaderRowByHeaders",
"(",
"String",
"columnName",
",",
"String",
"...",
"extraColumnNames",
")",
"{",
"String",
"allHeadersPresent",
";",
"if",
"(",
"extraColumnNames",
"!=",
"null",
"&&",
"extraColumnNames",
".",
"length",
">",
"0",
")",
"{",
"int",
"extraCount",
"=",
"extraColumnNames",
".",
"length",
";",
"String",
"[",
"]",
"columnNames",
"=",
"new",
"String",
"[",
"extraCount",
"+",
"1",
"]",
";",
"columnNames",
"[",
"0",
"]",
"=",
"columnName",
";",
"System",
".",
"arraycopy",
"(",
"extraColumnNames",
",",
"0",
",",
"columnNames",
",",
"1",
",",
"extraCount",
")",
";",
"allHeadersPresent",
"=",
"Stream",
".",
"of",
"(",
"columnNames",
")",
".",
"map",
"(",
"GridBy",
"::",
"getXPathForHeaderCellWithText",
")",
".",
"collect",
"(",
"Collectors",
".",
"joining",
"(",
"\" and \"",
")",
")",
";",
"}",
"else",
"{",
"allHeadersPresent",
"=",
"getXPathForHeaderCellWithText",
"(",
"columnName",
")",
";",
"}",
"return",
"String",
".",
"format",
"(",
"\"/tr[%1$s]\"",
",",
"allHeadersPresent",
")",
";",
"}"
] | Creates an XPath expression that will find a header row, selecting the row based on the
header texts present.
@param columnName first header text which must be present.
@param extraColumnNames name of other header texts that must be present in table's header row.
@return XPath expression selecting a tr in the row | [
"Creates",
"an",
"XPath",
"expression",
"that",
"will",
"find",
"a",
"header",
"row",
"selecting",
"the",
"row",
"based",
"on",
"the",
"header",
"texts",
"present",
"."
] | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/selenium/by/GridBy.java#L89-L104 |
jmxtrans/embedded-jmxtrans | src/main/java/org/jmxtrans/embedded/util/jmx/JmxUtils2.java | JmxUtils2.unregisterObject | public static void unregisterObject(ObjectName objectName, MBeanServer mbeanServer) {
"""
Try to unregister given <code>objectName</code>.
If given <code>objectName</code> is <code>null</code>, nothing is done.
If registration fails, a {@link Logger#warn(String)} message is emitted and <code>null</code> is returned.
@param objectName objectName to unregister
@param mbeanServer MBeanServer to which the objectName is unregistered
"""
if (objectName == null) {
return;
}
try {
mbeanServer.unregisterMBean(objectName);
} catch (Exception e) {
logger.warn("Failure to unregister {}", objectName, e);
}
} | java | public static void unregisterObject(ObjectName objectName, MBeanServer mbeanServer) {
if (objectName == null) {
return;
}
try {
mbeanServer.unregisterMBean(objectName);
} catch (Exception e) {
logger.warn("Failure to unregister {}", objectName, e);
}
} | [
"public",
"static",
"void",
"unregisterObject",
"(",
"ObjectName",
"objectName",
",",
"MBeanServer",
"mbeanServer",
")",
"{",
"if",
"(",
"objectName",
"==",
"null",
")",
"{",
"return",
";",
"}",
"try",
"{",
"mbeanServer",
".",
"unregisterMBean",
"(",
"objectName",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"logger",
".",
"warn",
"(",
"\"Failure to unregister {}\"",
",",
"objectName",
",",
"e",
")",
";",
"}",
"}"
] | Try to unregister given <code>objectName</code>.
If given <code>objectName</code> is <code>null</code>, nothing is done.
If registration fails, a {@link Logger#warn(String)} message is emitted and <code>null</code> is returned.
@param objectName objectName to unregister
@param mbeanServer MBeanServer to which the objectName is unregistered | [
"Try",
"to",
"unregister",
"given",
"<code",
">",
"objectName<",
"/",
"code",
">",
"."
] | train | https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/util/jmx/JmxUtils2.java#L74-L83 |
Red5/red5-server-common | src/main/java/org/red5/server/stream/StreamService.java | StreamService.play2 | public void play2(String oldStreamName, int start, String transition, int length, double offset, String streamName) {
"""
Dynamic streaming play method. This is a convenience method.
@param oldStreamName
old
@param start
start pos
@param transition
type of transition
@param length
length to play
@param offset
offset
@param streamName
stream name
"""
Map<String, Object> playOptions = new HashMap<String, Object>();
playOptions.put("oldStreamName", oldStreamName);
playOptions.put("streamName", streamName);
playOptions.put("start", start);
playOptions.put("len", length);
playOptions.put("offset", offset);
play2(playOptions);
} | java | public void play2(String oldStreamName, int start, String transition, int length, double offset, String streamName) {
Map<String, Object> playOptions = new HashMap<String, Object>();
playOptions.put("oldStreamName", oldStreamName);
playOptions.put("streamName", streamName);
playOptions.put("start", start);
playOptions.put("len", length);
playOptions.put("offset", offset);
play2(playOptions);
} | [
"public",
"void",
"play2",
"(",
"String",
"oldStreamName",
",",
"int",
"start",
",",
"String",
"transition",
",",
"int",
"length",
",",
"double",
"offset",
",",
"String",
"streamName",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"playOptions",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"playOptions",
".",
"put",
"(",
"\"oldStreamName\"",
",",
"oldStreamName",
")",
";",
"playOptions",
".",
"put",
"(",
"\"streamName\"",
",",
"streamName",
")",
";",
"playOptions",
".",
"put",
"(",
"\"start\"",
",",
"start",
")",
";",
"playOptions",
".",
"put",
"(",
"\"len\"",
",",
"length",
")",
";",
"playOptions",
".",
"put",
"(",
"\"offset\"",
",",
"offset",
")",
";",
"play2",
"(",
"playOptions",
")",
";",
"}"
] | Dynamic streaming play method. This is a convenience method.
@param oldStreamName
old
@param start
start pos
@param transition
type of transition
@param length
length to play
@param offset
offset
@param streamName
stream name | [
"Dynamic",
"streaming",
"play",
"method",
".",
"This",
"is",
"a",
"convenience",
"method",
"."
] | train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/StreamService.java#L462-L470 |
dkpro/dkpro-jwpl | de.tudarmstadt.ukp.wikipedia.revisionmachine/src/main/java/de/tudarmstadt/ukp/wikipedia/revisionmachine/difftool/config/ConfigurationReader.java | ConfigurationReader.parseModeConfig | private void parseModeConfig(final Node node, final ConfigSettings config) {
"""
Parses the mode parameter section.
@param node
Reference to the current used xml node
@param config
Reference to the ConfigSettings
"""
String name;
Integer value;
Node nnode;
NodeList list = node.getChildNodes();
int length = list.getLength();
for (int i = 0; i < length; i++) {
nnode = list.item(i);
name = nnode.getNodeName().toUpperCase();
if (name.equals(KEY_VALUE_MINIMUM_LONGEST_COMMON_SUBSTRING)) {
value = Integer.parseInt(nnode.getChildNodes().item(0)
.getNodeValue());
config.setConfigParameter(
ConfigurationKeys.VALUE_MINIMUM_LONGEST_COMMON_SUBSTRING,
value);
}
else if (name.equals(KEY_COUNTER_FULL_REVISION)) {
value = Integer.parseInt(nnode.getChildNodes().item(0)
.getNodeValue());
config.setConfigParameter(
ConfigurationKeys.COUNTER_FULL_REVISION, value);
}
}
} | java | private void parseModeConfig(final Node node, final ConfigSettings config)
{
String name;
Integer value;
Node nnode;
NodeList list = node.getChildNodes();
int length = list.getLength();
for (int i = 0; i < length; i++) {
nnode = list.item(i);
name = nnode.getNodeName().toUpperCase();
if (name.equals(KEY_VALUE_MINIMUM_LONGEST_COMMON_SUBSTRING)) {
value = Integer.parseInt(nnode.getChildNodes().item(0)
.getNodeValue());
config.setConfigParameter(
ConfigurationKeys.VALUE_MINIMUM_LONGEST_COMMON_SUBSTRING,
value);
}
else if (name.equals(KEY_COUNTER_FULL_REVISION)) {
value = Integer.parseInt(nnode.getChildNodes().item(0)
.getNodeValue());
config.setConfigParameter(
ConfigurationKeys.COUNTER_FULL_REVISION, value);
}
}
} | [
"private",
"void",
"parseModeConfig",
"(",
"final",
"Node",
"node",
",",
"final",
"ConfigSettings",
"config",
")",
"{",
"String",
"name",
";",
"Integer",
"value",
";",
"Node",
"nnode",
";",
"NodeList",
"list",
"=",
"node",
".",
"getChildNodes",
"(",
")",
";",
"int",
"length",
"=",
"list",
".",
"getLength",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"nnode",
"=",
"list",
".",
"item",
"(",
"i",
")",
";",
"name",
"=",
"nnode",
".",
"getNodeName",
"(",
")",
".",
"toUpperCase",
"(",
")",
";",
"if",
"(",
"name",
".",
"equals",
"(",
"KEY_VALUE_MINIMUM_LONGEST_COMMON_SUBSTRING",
")",
")",
"{",
"value",
"=",
"Integer",
".",
"parseInt",
"(",
"nnode",
".",
"getChildNodes",
"(",
")",
".",
"item",
"(",
"0",
")",
".",
"getNodeValue",
"(",
")",
")",
";",
"config",
".",
"setConfigParameter",
"(",
"ConfigurationKeys",
".",
"VALUE_MINIMUM_LONGEST_COMMON_SUBSTRING",
",",
"value",
")",
";",
"}",
"else",
"if",
"(",
"name",
".",
"equals",
"(",
"KEY_COUNTER_FULL_REVISION",
")",
")",
"{",
"value",
"=",
"Integer",
".",
"parseInt",
"(",
"nnode",
".",
"getChildNodes",
"(",
")",
".",
"item",
"(",
"0",
")",
".",
"getNodeValue",
"(",
")",
")",
";",
"config",
".",
"setConfigParameter",
"(",
"ConfigurationKeys",
".",
"COUNTER_FULL_REVISION",
",",
"value",
")",
";",
"}",
"}",
"}"
] | Parses the mode parameter section.
@param node
Reference to the current used xml node
@param config
Reference to the ConfigSettings | [
"Parses",
"the",
"mode",
"parameter",
"section",
"."
] | train | https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.revisionmachine/src/main/java/de/tudarmstadt/ukp/wikipedia/revisionmachine/difftool/config/ConfigurationReader.java#L331-L362 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java | ArrayUtil.resize | public static <T> T[] resize(T[] buffer, int newSize) {
"""
生成一个新的重新设置大小的数组<br>
新数组的类型为原数组的类型,调整大小后拷贝原数组到新数组下。扩大则占位前N个位置,缩小则截断
@param <T> 数组元素类型
@param buffer 原数组
@param newSize 新的数组大小
@return 调整后的新数组
"""
return resize(buffer, newSize, buffer.getClass().getComponentType());
} | java | public static <T> T[] resize(T[] buffer, int newSize) {
return resize(buffer, newSize, buffer.getClass().getComponentType());
} | [
"public",
"static",
"<",
"T",
">",
"T",
"[",
"]",
"resize",
"(",
"T",
"[",
"]",
"buffer",
",",
"int",
"newSize",
")",
"{",
"return",
"resize",
"(",
"buffer",
",",
"newSize",
",",
"buffer",
".",
"getClass",
"(",
")",
".",
"getComponentType",
"(",
")",
")",
";",
"}"
] | 生成一个新的重新设置大小的数组<br>
新数组的类型为原数组的类型,调整大小后拷贝原数组到新数组下。扩大则占位前N个位置,缩小则截断
@param <T> 数组元素类型
@param buffer 原数组
@param newSize 新的数组大小
@return 调整后的新数组 | [
"生成一个新的重新设置大小的数组<br",
">",
"新数组的类型为原数组的类型,调整大小后拷贝原数组到新数组下。扩大则占位前N个位置,缩小则截断"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java#L523-L525 |
quattor/pan | panc/src/main/java/org/quattor/pan/dml/operators/Add.java | Add.execute | @Override
public Element execute(Context context) {
"""
Perform the addition of the two top values on the data stack in the given
DMLContext. This method will handle long, double, and string values.
Exceptions are thrown if the types of the arguments do not match or they
are another type.
"""
try {
Element[] args = calculateArgs(context);
Property a = (Property) args[0];
Property b = (Property) args[1];
return execute(sourceRange, a, b);
} catch (ClassCastException cce) {
throw new EvaluationException(MessageUtils
.format(MSG_INVALID_ARGS_ADD), sourceRange);
}
} | java | @Override
public Element execute(Context context) {
try {
Element[] args = calculateArgs(context);
Property a = (Property) args[0];
Property b = (Property) args[1];
return execute(sourceRange, a, b);
} catch (ClassCastException cce) {
throw new EvaluationException(MessageUtils
.format(MSG_INVALID_ARGS_ADD), sourceRange);
}
} | [
"@",
"Override",
"public",
"Element",
"execute",
"(",
"Context",
"context",
")",
"{",
"try",
"{",
"Element",
"[",
"]",
"args",
"=",
"calculateArgs",
"(",
"context",
")",
";",
"Property",
"a",
"=",
"(",
"Property",
")",
"args",
"[",
"0",
"]",
";",
"Property",
"b",
"=",
"(",
"Property",
")",
"args",
"[",
"1",
"]",
";",
"return",
"execute",
"(",
"sourceRange",
",",
"a",
",",
"b",
")",
";",
"}",
"catch",
"(",
"ClassCastException",
"cce",
")",
"{",
"throw",
"new",
"EvaluationException",
"(",
"MessageUtils",
".",
"format",
"(",
"MSG_INVALID_ARGS_ADD",
")",
",",
"sourceRange",
")",
";",
"}",
"}"
] | Perform the addition of the two top values on the data stack in the given
DMLContext. This method will handle long, double, and string values.
Exceptions are thrown if the types of the arguments do not match or they
are another type. | [
"Perform",
"the",
"addition",
"of",
"the",
"two",
"top",
"values",
"on",
"the",
"data",
"stack",
"in",
"the",
"given",
"DMLContext",
".",
"This",
"method",
"will",
"handle",
"long",
"double",
"and",
"string",
"values",
".",
"Exceptions",
"are",
"thrown",
"if",
"the",
"types",
"of",
"the",
"arguments",
"do",
"not",
"match",
"or",
"they",
"are",
"another",
"type",
"."
] | train | https://github.com/quattor/pan/blob/009934a603dd0c08d3fa4bb7d9389c380a916f54/panc/src/main/java/org/quattor/pan/dml/operators/Add.java#L107-L119 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/ST_AsGeoJSON.java | ST_AsGeoJSON.toGeojsonPolygon | public static void toGeojsonPolygon(Polygon polygon, StringBuilder sb) {
"""
Coordinates of a Polygon are an array of LinearRing coordinate arrays.
The first element in the array represents the exterior ring. Any
subsequent elements represent interior rings (or holes).
Syntax:
No holes:
{ "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0],
[101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] }
With holes:
{ "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0],
[101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], [ [100.2, 0.2], [100.8, 0.2],
[100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] ] }
@param polygon
@param sb
"""
sb.append("{\"type\":\"Polygon\",\"coordinates\":[");
//Process exterior ring
toGeojsonCoordinates(polygon.getExteriorRing().getCoordinates(), sb);
//Process interior rings
for (int i = 0; i < polygon.getNumInteriorRing(); i++) {
sb.append(",");
toGeojsonCoordinates(polygon.getInteriorRingN(i).getCoordinates(), sb);
}
sb.append("]}");
} | java | public static void toGeojsonPolygon(Polygon polygon, StringBuilder sb) {
sb.append("{\"type\":\"Polygon\",\"coordinates\":[");
//Process exterior ring
toGeojsonCoordinates(polygon.getExteriorRing().getCoordinates(), sb);
//Process interior rings
for (int i = 0; i < polygon.getNumInteriorRing(); i++) {
sb.append(",");
toGeojsonCoordinates(polygon.getInteriorRingN(i).getCoordinates(), sb);
}
sb.append("]}");
} | [
"public",
"static",
"void",
"toGeojsonPolygon",
"(",
"Polygon",
"polygon",
",",
"StringBuilder",
"sb",
")",
"{",
"sb",
".",
"append",
"(",
"\"{\\\"type\\\":\\\"Polygon\\\",\\\"coordinates\\\":[\"",
")",
";",
"//Process exterior ring",
"toGeojsonCoordinates",
"(",
"polygon",
".",
"getExteriorRing",
"(",
")",
".",
"getCoordinates",
"(",
")",
",",
"sb",
")",
";",
"//Process interior rings",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"polygon",
".",
"getNumInteriorRing",
"(",
")",
";",
"i",
"++",
")",
"{",
"sb",
".",
"append",
"(",
"\",\"",
")",
";",
"toGeojsonCoordinates",
"(",
"polygon",
".",
"getInteriorRingN",
"(",
"i",
")",
".",
"getCoordinates",
"(",
")",
",",
"sb",
")",
";",
"}",
"sb",
".",
"append",
"(",
"\"]}\"",
")",
";",
"}"
] | Coordinates of a Polygon are an array of LinearRing coordinate arrays.
The first element in the array represents the exterior ring. Any
subsequent elements represent interior rings (or holes).
Syntax:
No holes:
{ "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0],
[101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] }
With holes:
{ "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0],
[101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], [ [100.2, 0.2], [100.8, 0.2],
[100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] ] }
@param polygon
@param sb | [
"Coordinates",
"of",
"a",
"Polygon",
"are",
"an",
"array",
"of",
"LinearRing",
"coordinate",
"arrays",
".",
"The",
"first",
"element",
"in",
"the",
"array",
"represents",
"the",
"exterior",
"ring",
".",
"Any",
"subsequent",
"elements",
"represent",
"interior",
"rings",
"(",
"or",
"holes",
")",
"."
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/ST_AsGeoJSON.java#L193-L203 |
goldmansachs/gs-collections | collections/src/main/java/com/gs/collections/impl/utility/MapIterate.java | MapIterate.forEachKeyValue | public static <K, V> void forEachKeyValue(Map<K, V> map, Procedure2<? super K, ? super V> procedure) {
"""
For each entry of the map, {@code procedure} is evaluated with the element as the parameter.
"""
if (map == null)
{
throw new IllegalArgumentException("Cannot perform a forEachKeyValue on null");
}
if (MapIterate.notEmpty(map))
{
if (map instanceof UnsortedMapIterable)
{
((MapIterable<K, V>) map).forEachKeyValue(procedure);
}
else
{
IterableIterate.forEach(map.entrySet(), new MapEntryToProcedure2<K, V>(procedure));
}
}
} | java | public static <K, V> void forEachKeyValue(Map<K, V> map, Procedure2<? super K, ? super V> procedure)
{
if (map == null)
{
throw new IllegalArgumentException("Cannot perform a forEachKeyValue on null");
}
if (MapIterate.notEmpty(map))
{
if (map instanceof UnsortedMapIterable)
{
((MapIterable<K, V>) map).forEachKeyValue(procedure);
}
else
{
IterableIterate.forEach(map.entrySet(), new MapEntryToProcedure2<K, V>(procedure));
}
}
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"void",
"forEachKeyValue",
"(",
"Map",
"<",
"K",
",",
"V",
">",
"map",
",",
"Procedure2",
"<",
"?",
"super",
"K",
",",
"?",
"super",
"V",
">",
"procedure",
")",
"{",
"if",
"(",
"map",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Cannot perform a forEachKeyValue on null\"",
")",
";",
"}",
"if",
"(",
"MapIterate",
".",
"notEmpty",
"(",
"map",
")",
")",
"{",
"if",
"(",
"map",
"instanceof",
"UnsortedMapIterable",
")",
"{",
"(",
"(",
"MapIterable",
"<",
"K",
",",
"V",
">",
")",
"map",
")",
".",
"forEachKeyValue",
"(",
"procedure",
")",
";",
"}",
"else",
"{",
"IterableIterate",
".",
"forEach",
"(",
"map",
".",
"entrySet",
"(",
")",
",",
"new",
"MapEntryToProcedure2",
"<",
"K",
",",
"V",
">",
"(",
"procedure",
")",
")",
";",
"}",
"}",
"}"
] | For each entry of the map, {@code procedure} is evaluated with the element as the parameter. | [
"For",
"each",
"entry",
"of",
"the",
"map",
"{"
] | train | https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/MapIterate.java#L816-L834 |
FasterXML/woodstox | src/main/java/com/ctc/wstx/evt/WstxEventReader.java | WstxEventReader.getErrorDesc | protected String getErrorDesc(int errorType, int currEvent) {
"""
Method called upon encountering a problem that should result
in an exception being thrown. If non-null String is returned.
that will be used as the message of exception thrown; if null,
a standard message will be used instead.
@param errorType Type of the problem, one of <code>ERR_</code>
constants
@param eventType Type of the event that triggered the problem,
if any; -1 if not available.
"""
// Defaults are mostly fine, except we can easily add event type desc
switch (errorType) {
case ERR_GETELEMTEXT_NOT_START_ELEM:
return ErrorConsts.ERR_STATE_NOT_STELEM+", got "+ErrorConsts.tokenTypeDesc(currEvent);
case ERR_GETELEMTEXT_NON_TEXT_EVENT:
return "Expected a text token, got "+ErrorConsts.tokenTypeDesc(currEvent);
case ERR_NEXTTAG_NON_WS_TEXT:
return "Only all-whitespace CHARACTERS/CDATA (or SPACE) allowed for nextTag(), got "+ErrorConsts.tokenTypeDesc(currEvent);
case ERR_NEXTTAG_WRONG_TYPE:
return "Got "+ErrorConsts.tokenTypeDesc(currEvent)+", instead of START_ELEMENT, END_ELEMENT or SPACE";
}
return null;
} | java | protected String getErrorDesc(int errorType, int currEvent)
{
// Defaults are mostly fine, except we can easily add event type desc
switch (errorType) {
case ERR_GETELEMTEXT_NOT_START_ELEM:
return ErrorConsts.ERR_STATE_NOT_STELEM+", got "+ErrorConsts.tokenTypeDesc(currEvent);
case ERR_GETELEMTEXT_NON_TEXT_EVENT:
return "Expected a text token, got "+ErrorConsts.tokenTypeDesc(currEvent);
case ERR_NEXTTAG_NON_WS_TEXT:
return "Only all-whitespace CHARACTERS/CDATA (or SPACE) allowed for nextTag(), got "+ErrorConsts.tokenTypeDesc(currEvent);
case ERR_NEXTTAG_WRONG_TYPE:
return "Got "+ErrorConsts.tokenTypeDesc(currEvent)+", instead of START_ELEMENT, END_ELEMENT or SPACE";
}
return null;
} | [
"protected",
"String",
"getErrorDesc",
"(",
"int",
"errorType",
",",
"int",
"currEvent",
")",
"{",
"// Defaults are mostly fine, except we can easily add event type desc",
"switch",
"(",
"errorType",
")",
"{",
"case",
"ERR_GETELEMTEXT_NOT_START_ELEM",
":",
"return",
"ErrorConsts",
".",
"ERR_STATE_NOT_STELEM",
"+",
"\", got \"",
"+",
"ErrorConsts",
".",
"tokenTypeDesc",
"(",
"currEvent",
")",
";",
"case",
"ERR_GETELEMTEXT_NON_TEXT_EVENT",
":",
"return",
"\"Expected a text token, got \"",
"+",
"ErrorConsts",
".",
"tokenTypeDesc",
"(",
"currEvent",
")",
";",
"case",
"ERR_NEXTTAG_NON_WS_TEXT",
":",
"return",
"\"Only all-whitespace CHARACTERS/CDATA (or SPACE) allowed for nextTag(), got \"",
"+",
"ErrorConsts",
".",
"tokenTypeDesc",
"(",
"currEvent",
")",
";",
"case",
"ERR_NEXTTAG_WRONG_TYPE",
":",
"return",
"\"Got \"",
"+",
"ErrorConsts",
".",
"tokenTypeDesc",
"(",
"currEvent",
")",
"+",
"\", instead of START_ELEMENT, END_ELEMENT or SPACE\"",
";",
"}",
"return",
"null",
";",
"}"
] | Method called upon encountering a problem that should result
in an exception being thrown. If non-null String is returned.
that will be used as the message of exception thrown; if null,
a standard message will be used instead.
@param errorType Type of the problem, one of <code>ERR_</code>
constants
@param eventType Type of the event that triggered the problem,
if any; -1 if not available. | [
"Method",
"called",
"upon",
"encountering",
"a",
"problem",
"that",
"should",
"result",
"in",
"an",
"exception",
"being",
"thrown",
".",
"If",
"non",
"-",
"null",
"String",
"is",
"returned",
".",
"that",
"will",
"be",
"used",
"as",
"the",
"message",
"of",
"exception",
"thrown",
";",
"if",
"null",
"a",
"standard",
"message",
"will",
"be",
"used",
"instead",
"."
] | train | https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/evt/WstxEventReader.java#L173-L187 |
huahin/huahin-core | src/main/java/org/huahinframework/core/SimpleJob.java | SimpleJob.setSimpleJoin | public SimpleJob setSimpleJoin(String[] masterLabels, String masterColumn,
String dataColumn, String masterPath) {
"""
Easily supports the Join. To use the setSimpleJoin,
you must be a size master data appear in the memory of the task.
@param masterLabels label of master data
@param masterColumn master column
@param dataColumn data column
@param masterPath master data HDFS path
@return this
"""
String separator = conf.get(SEPARATOR);
return setSimpleJoin(masterLabels, masterColumn, dataColumn, masterPath, separator, false);
} | java | public SimpleJob setSimpleJoin(String[] masterLabels, String masterColumn,
String dataColumn, String masterPath) {
String separator = conf.get(SEPARATOR);
return setSimpleJoin(masterLabels, masterColumn, dataColumn, masterPath, separator, false);
} | [
"public",
"SimpleJob",
"setSimpleJoin",
"(",
"String",
"[",
"]",
"masterLabels",
",",
"String",
"masterColumn",
",",
"String",
"dataColumn",
",",
"String",
"masterPath",
")",
"{",
"String",
"separator",
"=",
"conf",
".",
"get",
"(",
"SEPARATOR",
")",
";",
"return",
"setSimpleJoin",
"(",
"masterLabels",
",",
"masterColumn",
",",
"dataColumn",
",",
"masterPath",
",",
"separator",
",",
"false",
")",
";",
"}"
] | Easily supports the Join. To use the setSimpleJoin,
you must be a size master data appear in the memory of the task.
@param masterLabels label of master data
@param masterColumn master column
@param dataColumn data column
@param masterPath master data HDFS path
@return this | [
"Easily",
"supports",
"the",
"Join",
".",
"To",
"use",
"the",
"setSimpleJoin",
"you",
"must",
"be",
"a",
"size",
"master",
"data",
"appear",
"in",
"the",
"memory",
"of",
"the",
"task",
"."
] | train | https://github.com/huahin/huahin-core/blob/a87921b5a12be92a822f753c075ab2431036e6f5/src/main/java/org/huahinframework/core/SimpleJob.java#L248-L252 |
pravega/pravega | client/src/main/java/io/pravega/client/stream/ScalingPolicy.java | ScalingPolicy.byDataRate | public static ScalingPolicy byDataRate(int targetKBps, int scaleFactor, int minNumSegments) {
"""
Create a scaling policy to configure a stream to scale up and down according
to byte rate. Pravega scales a stream segment up in the case that one of these
conditions holds:
- The two-minute rate is greater than 5x the target rate
- The five-minute rate is greater than 2x the target rate
- The ten-minute rate is greater than the target rate
It scales a segment down (merges with a neighbor segment) in the case that
both these conditions hold:
- The two-, five-, ten-minute rate is smaller than the target rate
- The twenty-minute rate is smaller than half of the target rate
We additionally consider a cool-down period during which the segment is not
considered for scaling. This period is determined by the configuration
parameter autoScale.cooldownInSeconds; the default value is 10 minutes.
The scale factor bounds the number of new segments that can be created upon
a scaling event. In the case the controller computes the number of splits
to be greater than the scale factor for a given scale-up event, the number
of splits for the event is going to be equal to the scale factor.
The policy is configured with a minimum number of segments for a stream,
independent of the number of scale down events.
@param targetKBps Target rate in kilo bytes per second to enable scaling events
per segment.
@param scaleFactor Maximum number of splits of a segment for a scale-up event.
@param minNumSegments Minimum number of segments that a stream can have
independent of the number of scale down events.
@return Scaling policy object.
"""
Preconditions.checkArgument(targetKBps > 0, "KBps should be > 0.");
Preconditions.checkArgument(scaleFactor > 0, "Scale factor should be > 0. Otherwise use fixed scaling policy.");
Preconditions.checkArgument(minNumSegments > 0, "Minimum number of segments should be > 0.");
return new ScalingPolicy(ScaleType.BY_RATE_IN_KBYTES_PER_SEC, targetKBps, scaleFactor, minNumSegments);
} | java | public static ScalingPolicy byDataRate(int targetKBps, int scaleFactor, int minNumSegments) {
Preconditions.checkArgument(targetKBps > 0, "KBps should be > 0.");
Preconditions.checkArgument(scaleFactor > 0, "Scale factor should be > 0. Otherwise use fixed scaling policy.");
Preconditions.checkArgument(minNumSegments > 0, "Minimum number of segments should be > 0.");
return new ScalingPolicy(ScaleType.BY_RATE_IN_KBYTES_PER_SEC, targetKBps, scaleFactor, minNumSegments);
} | [
"public",
"static",
"ScalingPolicy",
"byDataRate",
"(",
"int",
"targetKBps",
",",
"int",
"scaleFactor",
",",
"int",
"minNumSegments",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"targetKBps",
">",
"0",
",",
"\"KBps should be > 0.\"",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"scaleFactor",
">",
"0",
",",
"\"Scale factor should be > 0. Otherwise use fixed scaling policy.\"",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"minNumSegments",
">",
"0",
",",
"\"Minimum number of segments should be > 0.\"",
")",
";",
"return",
"new",
"ScalingPolicy",
"(",
"ScaleType",
".",
"BY_RATE_IN_KBYTES_PER_SEC",
",",
"targetKBps",
",",
"scaleFactor",
",",
"minNumSegments",
")",
";",
"}"
] | Create a scaling policy to configure a stream to scale up and down according
to byte rate. Pravega scales a stream segment up in the case that one of these
conditions holds:
- The two-minute rate is greater than 5x the target rate
- The five-minute rate is greater than 2x the target rate
- The ten-minute rate is greater than the target rate
It scales a segment down (merges with a neighbor segment) in the case that
both these conditions hold:
- The two-, five-, ten-minute rate is smaller than the target rate
- The twenty-minute rate is smaller than half of the target rate
We additionally consider a cool-down period during which the segment is not
considered for scaling. This period is determined by the configuration
parameter autoScale.cooldownInSeconds; the default value is 10 minutes.
The scale factor bounds the number of new segments that can be created upon
a scaling event. In the case the controller computes the number of splits
to be greater than the scale factor for a given scale-up event, the number
of splits for the event is going to be equal to the scale factor.
The policy is configured with a minimum number of segments for a stream,
independent of the number of scale down events.
@param targetKBps Target rate in kilo bytes per second to enable scaling events
per segment.
@param scaleFactor Maximum number of splits of a segment for a scale-up event.
@param minNumSegments Minimum number of segments that a stream can have
independent of the number of scale down events.
@return Scaling policy object. | [
"Create",
"a",
"scaling",
"policy",
"to",
"configure",
"a",
"stream",
"to",
"scale",
"up",
"and",
"down",
"according",
"to",
"byte",
"rate",
".",
"Pravega",
"scales",
"a",
"stream",
"segment",
"up",
"in",
"the",
"case",
"that",
"one",
"of",
"these",
"conditions",
"holds",
":",
"-",
"The",
"two",
"-",
"minute",
"rate",
"is",
"greater",
"than",
"5x",
"the",
"target",
"rate",
"-",
"The",
"five",
"-",
"minute",
"rate",
"is",
"greater",
"than",
"2x",
"the",
"target",
"rate",
"-",
"The",
"ten",
"-",
"minute",
"rate",
"is",
"greater",
"than",
"the",
"target",
"rate"
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/client/src/main/java/io/pravega/client/stream/ScalingPolicy.java#L139-L144 |
alkacon/opencms-core | src/org/opencms/jsp/util/CmsJspContentAccessBean.java | CmsJspContentAccessBean.createImageDndAttr | protected static String createImageDndAttr(CmsUUID structureId, String imagePath, String locale) {
"""
Generates the HTML attribute "data-imagednd" that enables the ADE image drag and drop feature.<p>
@param structureId the structure ID of the XML document to insert the image
@param locale the locale to generate the image in
@param imagePath the XML path to the image source node.
@return the HTML attribute "data-imagednd" that enables the ADE image drag and drop feature
"""
String attrValue = structureId + "|" + imagePath + "|" + locale;
String escapedAttrValue = CmsEncoder.escapeXml(attrValue);
return ("data-imagednd=\"" + escapedAttrValue + "\"");
} | java | protected static String createImageDndAttr(CmsUUID structureId, String imagePath, String locale) {
String attrValue = structureId + "|" + imagePath + "|" + locale;
String escapedAttrValue = CmsEncoder.escapeXml(attrValue);
return ("data-imagednd=\"" + escapedAttrValue + "\"");
} | [
"protected",
"static",
"String",
"createImageDndAttr",
"(",
"CmsUUID",
"structureId",
",",
"String",
"imagePath",
",",
"String",
"locale",
")",
"{",
"String",
"attrValue",
"=",
"structureId",
"+",
"\"|\"",
"+",
"imagePath",
"+",
"\"|\"",
"+",
"locale",
";",
"String",
"escapedAttrValue",
"=",
"CmsEncoder",
".",
"escapeXml",
"(",
"attrValue",
")",
";",
"return",
"(",
"\"data-imagednd=\\\"\"",
"+",
"escapedAttrValue",
"+",
"\"\\\"\"",
")",
";",
"}"
] | Generates the HTML attribute "data-imagednd" that enables the ADE image drag and drop feature.<p>
@param structureId the structure ID of the XML document to insert the image
@param locale the locale to generate the image in
@param imagePath the XML path to the image source node.
@return the HTML attribute "data-imagednd" that enables the ADE image drag and drop feature | [
"Generates",
"the",
"HTML",
"attribute",
"data",
"-",
"imagednd",
"that",
"enables",
"the",
"ADE",
"image",
"drag",
"and",
"drop",
"feature",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/util/CmsJspContentAccessBean.java#L523-L528 |
Azure/azure-sdk-for-java | sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/EncryptionProtectorsInner.java | EncryptionProtectorsInner.listByServerAsync | public Observable<Page<EncryptionProtectorInner>> listByServerAsync(final String resourceGroupName, final String serverName) {
"""
Gets a list of server encryption protectors.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<EncryptionProtectorInner> object
"""
return listByServerWithServiceResponseAsync(resourceGroupName, serverName)
.map(new Func1<ServiceResponse<Page<EncryptionProtectorInner>>, Page<EncryptionProtectorInner>>() {
@Override
public Page<EncryptionProtectorInner> call(ServiceResponse<Page<EncryptionProtectorInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<EncryptionProtectorInner>> listByServerAsync(final String resourceGroupName, final String serverName) {
return listByServerWithServiceResponseAsync(resourceGroupName, serverName)
.map(new Func1<ServiceResponse<Page<EncryptionProtectorInner>>, Page<EncryptionProtectorInner>>() {
@Override
public Page<EncryptionProtectorInner> call(ServiceResponse<Page<EncryptionProtectorInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"EncryptionProtectorInner",
">",
">",
"listByServerAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"serverName",
")",
"{",
"return",
"listByServerWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"EncryptionProtectorInner",
">",
">",
",",
"Page",
"<",
"EncryptionProtectorInner",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Page",
"<",
"EncryptionProtectorInner",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"EncryptionProtectorInner",
">",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Gets a list of server encryption protectors.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<EncryptionProtectorInner> object | [
"Gets",
"a",
"list",
"of",
"server",
"encryption",
"protectors",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/EncryptionProtectorsInner.java#L134-L142 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java | ArrayFunctions.arrayPrepend | public static Expression arrayPrepend(JsonArray array, Expression value) {
"""
Returned expression results in the new array with value pre-pended.
"""
return arrayPrepend(x(array), value);
} | java | public static Expression arrayPrepend(JsonArray array, Expression value) {
return arrayPrepend(x(array), value);
} | [
"public",
"static",
"Expression",
"arrayPrepend",
"(",
"JsonArray",
"array",
",",
"Expression",
"value",
")",
"{",
"return",
"arrayPrepend",
"(",
"x",
"(",
"array",
")",
",",
"value",
")",
";",
"}"
] | Returned expression results in the new array with value pre-pended. | [
"Returned",
"expression",
"results",
"in",
"the",
"new",
"array",
"with",
"value",
"pre",
"-",
"pended",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java#L296-L298 |
jboss/jboss-jstl-api_spec | src/main/java/org/apache/taglibs/standard/tag/common/core/ImportSupport.java | ImportSupport.doStartTag | @Override
public int doStartTag() throws JspException {
"""
determines what kind of import and variable exposure to perform
"""
// Sanity check
if (context != null
&& (!context.startsWith("/") || !url.startsWith("/"))) {
throw new JspTagException(
Resources.getMessage("IMPORT_BAD_RELATIVE"));
}
// reset parameter-related state
urlWithParams = null;
params = new ParamSupport.ParamManager();
// check the URL
if (url == null || url.equals("")) {
throw new NullAttributeException("import", "url");
}
// Record whether our URL is absolute or relative
isAbsoluteUrl = UrlUtil.isAbsoluteUrl(url);
try {
// If we need to expose a Reader, we've got to do it right away
if (varReader != null) {
r = acquireReader();
pageContext.setAttribute(varReader, r);
}
} catch (IOException ex) {
throw new JspTagException(ex.toString(), ex);
}
return EVAL_BODY_INCLUDE;
} | java | @Override
public int doStartTag() throws JspException {
// Sanity check
if (context != null
&& (!context.startsWith("/") || !url.startsWith("/"))) {
throw new JspTagException(
Resources.getMessage("IMPORT_BAD_RELATIVE"));
}
// reset parameter-related state
urlWithParams = null;
params = new ParamSupport.ParamManager();
// check the URL
if (url == null || url.equals("")) {
throw new NullAttributeException("import", "url");
}
// Record whether our URL is absolute or relative
isAbsoluteUrl = UrlUtil.isAbsoluteUrl(url);
try {
// If we need to expose a Reader, we've got to do it right away
if (varReader != null) {
r = acquireReader();
pageContext.setAttribute(varReader, r);
}
} catch (IOException ex) {
throw new JspTagException(ex.toString(), ex);
}
return EVAL_BODY_INCLUDE;
} | [
"@",
"Override",
"public",
"int",
"doStartTag",
"(",
")",
"throws",
"JspException",
"{",
"// Sanity check",
"if",
"(",
"context",
"!=",
"null",
"&&",
"(",
"!",
"context",
".",
"startsWith",
"(",
"\"/\"",
")",
"||",
"!",
"url",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
")",
"{",
"throw",
"new",
"JspTagException",
"(",
"Resources",
".",
"getMessage",
"(",
"\"IMPORT_BAD_RELATIVE\"",
")",
")",
";",
"}",
"// reset parameter-related state",
"urlWithParams",
"=",
"null",
";",
"params",
"=",
"new",
"ParamSupport",
".",
"ParamManager",
"(",
")",
";",
"// check the URL",
"if",
"(",
"url",
"==",
"null",
"||",
"url",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"throw",
"new",
"NullAttributeException",
"(",
"\"import\"",
",",
"\"url\"",
")",
";",
"}",
"// Record whether our URL is absolute or relative",
"isAbsoluteUrl",
"=",
"UrlUtil",
".",
"isAbsoluteUrl",
"(",
"url",
")",
";",
"try",
"{",
"// If we need to expose a Reader, we've got to do it right away",
"if",
"(",
"varReader",
"!=",
"null",
")",
"{",
"r",
"=",
"acquireReader",
"(",
")",
";",
"pageContext",
".",
"setAttribute",
"(",
"varReader",
",",
"r",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"JspTagException",
"(",
"ex",
".",
"toString",
"(",
")",
",",
"ex",
")",
";",
"}",
"return",
"EVAL_BODY_INCLUDE",
";",
"}"
] | determines what kind of import and variable exposure to perform | [
"determines",
"what",
"kind",
"of",
"import",
"and",
"variable",
"exposure",
"to",
"perform"
] | train | https://github.com/jboss/jboss-jstl-api_spec/blob/4ad412ae5be1ae606b8d33c188cb3d98bfcbe84c/src/main/java/org/apache/taglibs/standard/tag/common/core/ImportSupport.java#L109-L141 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/util/ReflectUtil.java | ReflectUtil.getField | public static Field getField(String fieldName, Class<?> clazz) {
"""
Returns the field of the given class or null if it doesnt exist.
"""
Field field = null;
try {
field = clazz.getDeclaredField(fieldName);
}
catch (SecurityException e) {
throw LOG.unableToAccessField(field, clazz.getName());
}
catch (NoSuchFieldException e) {
// for some reason getDeclaredFields doesnt search superclasses
// (which getFields() does ... but that gives only public fields)
Class<?> superClass = clazz.getSuperclass();
if (superClass != null) {
return getField(fieldName, superClass);
}
}
return field;
} | java | public static Field getField(String fieldName, Class<?> clazz) {
Field field = null;
try {
field = clazz.getDeclaredField(fieldName);
}
catch (SecurityException e) {
throw LOG.unableToAccessField(field, clazz.getName());
}
catch (NoSuchFieldException e) {
// for some reason getDeclaredFields doesnt search superclasses
// (which getFields() does ... but that gives only public fields)
Class<?> superClass = clazz.getSuperclass();
if (superClass != null) {
return getField(fieldName, superClass);
}
}
return field;
} | [
"public",
"static",
"Field",
"getField",
"(",
"String",
"fieldName",
",",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"Field",
"field",
"=",
"null",
";",
"try",
"{",
"field",
"=",
"clazz",
".",
"getDeclaredField",
"(",
"fieldName",
")",
";",
"}",
"catch",
"(",
"SecurityException",
"e",
")",
"{",
"throw",
"LOG",
".",
"unableToAccessField",
"(",
"field",
",",
"clazz",
".",
"getName",
"(",
")",
")",
";",
"}",
"catch",
"(",
"NoSuchFieldException",
"e",
")",
"{",
"// for some reason getDeclaredFields doesnt search superclasses",
"// (which getFields() does ... but that gives only public fields)",
"Class",
"<",
"?",
">",
"superClass",
"=",
"clazz",
".",
"getSuperclass",
"(",
")",
";",
"if",
"(",
"superClass",
"!=",
"null",
")",
"{",
"return",
"getField",
"(",
"fieldName",
",",
"superClass",
")",
";",
"}",
"}",
"return",
"field",
";",
"}"
] | Returns the field of the given class or null if it doesnt exist. | [
"Returns",
"the",
"field",
"of",
"the",
"given",
"class",
"or",
"null",
"if",
"it",
"doesnt",
"exist",
"."
] | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/util/ReflectUtil.java#L222-L239 |
jenkinsci/jenkins | core/src/main/java/jenkins/model/identity/IdentityRootAction.java | IdentityRootAction.getPublicKey | public String getPublicKey() {
"""
Returns the PEM encoded public key.
@return the PEM encoded public key.
"""
RSAPublicKey key = InstanceIdentityProvider.RSA.getPublicKey();
if (key == null) {
return null;
}
byte[] encoded = Base64.encodeBase64(key.getEncoded());
int index = 0;
StringBuilder buf = new StringBuilder(encoded.length + 20);
while (index < encoded.length) {
int len = Math.min(64, encoded.length - index);
if (index > 0) {
buf.append("\n");
}
buf.append(new String(encoded, index, len, Charsets.UTF_8));
index += len;
}
return String.format("-----BEGIN PUBLIC KEY-----%n%s%n-----END PUBLIC KEY-----%n", buf.toString());
} | java | public String getPublicKey() {
RSAPublicKey key = InstanceIdentityProvider.RSA.getPublicKey();
if (key == null) {
return null;
}
byte[] encoded = Base64.encodeBase64(key.getEncoded());
int index = 0;
StringBuilder buf = new StringBuilder(encoded.length + 20);
while (index < encoded.length) {
int len = Math.min(64, encoded.length - index);
if (index > 0) {
buf.append("\n");
}
buf.append(new String(encoded, index, len, Charsets.UTF_8));
index += len;
}
return String.format("-----BEGIN PUBLIC KEY-----%n%s%n-----END PUBLIC KEY-----%n", buf.toString());
} | [
"public",
"String",
"getPublicKey",
"(",
")",
"{",
"RSAPublicKey",
"key",
"=",
"InstanceIdentityProvider",
".",
"RSA",
".",
"getPublicKey",
"(",
")",
";",
"if",
"(",
"key",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"byte",
"[",
"]",
"encoded",
"=",
"Base64",
".",
"encodeBase64",
"(",
"key",
".",
"getEncoded",
"(",
")",
")",
";",
"int",
"index",
"=",
"0",
";",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
"encoded",
".",
"length",
"+",
"20",
")",
";",
"while",
"(",
"index",
"<",
"encoded",
".",
"length",
")",
"{",
"int",
"len",
"=",
"Math",
".",
"min",
"(",
"64",
",",
"encoded",
".",
"length",
"-",
"index",
")",
";",
"if",
"(",
"index",
">",
"0",
")",
"{",
"buf",
".",
"append",
"(",
"\"\\n\"",
")",
";",
"}",
"buf",
".",
"append",
"(",
"new",
"String",
"(",
"encoded",
",",
"index",
",",
"len",
",",
"Charsets",
".",
"UTF_8",
")",
")",
";",
"index",
"+=",
"len",
";",
"}",
"return",
"String",
".",
"format",
"(",
"\"-----BEGIN PUBLIC KEY-----%n%s%n-----END PUBLIC KEY-----%n\"",
",",
"buf",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Returns the PEM encoded public key.
@return the PEM encoded public key. | [
"Returns",
"the",
"PEM",
"encoded",
"public",
"key",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/model/identity/IdentityRootAction.java#L49-L66 |
airlift/airline | src/main/java/io/airlift/airline/Parser.java | Parser.parse | public ParseState parse(GlobalMetadata metadata, String... params) {
"""
global> (option value*)* (group (option value*)*)? (command (option value* | arg)* '--'? args*)?
"""
return parse(metadata, ImmutableList.copyOf(params));
} | java | public ParseState parse(GlobalMetadata metadata, String... params)
{
return parse(metadata, ImmutableList.copyOf(params));
} | [
"public",
"ParseState",
"parse",
"(",
"GlobalMetadata",
"metadata",
",",
"String",
"...",
"params",
")",
"{",
"return",
"parse",
"(",
"metadata",
",",
"ImmutableList",
".",
"copyOf",
"(",
"params",
")",
")",
";",
"}"
] | global> (option value*)* (group (option value*)*)? (command (option value* | arg)* '--'? args*)? | [
"global",
">",
"(",
"option",
"value",
"*",
")",
"*",
"(",
"group",
"(",
"option",
"value",
"*",
")",
"*",
")",
"?",
"(",
"command",
"(",
"option",
"value",
"*",
"|",
"arg",
")",
"*",
"--",
"?",
"args",
"*",
")",
"?"
] | train | https://github.com/airlift/airline/blob/fc7a55e34b6361cb97235de5a1b21cba9b508f4b/src/main/java/io/airlift/airline/Parser.java#L25-L28 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/kits/WalletAppKit.java | WalletAppKit.setUserAgent | public WalletAppKit setUserAgent(String userAgent, String version) {
"""
Sets the string that will appear in the subver field of the version message.
@param userAgent A short string that should be the name of your app, e.g. "My Wallet"
@param version A short string that contains the version number, e.g. "1.0-BETA"
"""
this.userAgent = checkNotNull(userAgent);
this.version = checkNotNull(version);
return this;
} | java | public WalletAppKit setUserAgent(String userAgent, String version) {
this.userAgent = checkNotNull(userAgent);
this.version = checkNotNull(version);
return this;
} | [
"public",
"WalletAppKit",
"setUserAgent",
"(",
"String",
"userAgent",
",",
"String",
"version",
")",
"{",
"this",
".",
"userAgent",
"=",
"checkNotNull",
"(",
"userAgent",
")",
";",
"this",
".",
"version",
"=",
"checkNotNull",
"(",
"version",
")",
";",
"return",
"this",
";",
"}"
] | Sets the string that will appear in the subver field of the version message.
@param userAgent A short string that should be the name of your app, e.g. "My Wallet"
@param version A short string that contains the version number, e.g. "1.0-BETA" | [
"Sets",
"the",
"string",
"that",
"will",
"appear",
"in",
"the",
"subver",
"field",
"of",
"the",
"version",
"message",
"."
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/kits/WalletAppKit.java#L190-L194 |
ixa-ehu/kaflib | src/main/java/ixa/kaflib/KAFDocument.java | KAFDocument.newFactvalue | public Factvalue newFactvalue(WF wf, String prediction) {
"""
Creates a factualitylayer object and add it to the document
@param term the Term of the coreference.
@return a new factuality.
"""
Factvalue factuality = new Factvalue(wf, prediction);
annotationContainer.add(factuality, Layer.FACTUALITY_LAYER, AnnotationType.FACTVALUE);
return factuality;
} | java | public Factvalue newFactvalue(WF wf, String prediction) {
Factvalue factuality = new Factvalue(wf, prediction);
annotationContainer.add(factuality, Layer.FACTUALITY_LAYER, AnnotationType.FACTVALUE);
return factuality;
} | [
"public",
"Factvalue",
"newFactvalue",
"(",
"WF",
"wf",
",",
"String",
"prediction",
")",
"{",
"Factvalue",
"factuality",
"=",
"new",
"Factvalue",
"(",
"wf",
",",
"prediction",
")",
";",
"annotationContainer",
".",
"add",
"(",
"factuality",
",",
"Layer",
".",
"FACTUALITY_LAYER",
",",
"AnnotationType",
".",
"FACTVALUE",
")",
";",
"return",
"factuality",
";",
"}"
] | Creates a factualitylayer object and add it to the document
@param term the Term of the coreference.
@return a new factuality. | [
"Creates",
"a",
"factualitylayer",
"object",
"and",
"add",
"it",
"to",
"the",
"document"
] | train | https://github.com/ixa-ehu/kaflib/blob/3921f55d9ae4621736a329418f6334fb721834b8/src/main/java/ixa/kaflib/KAFDocument.java#L877-L881 |
moparisthebest/beehive | beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/PropertySetProxy.java | PropertySetProxy.getProxy | public static <T extends Annotation> T getProxy(Class<T> propertySet, PropertyMap propertyMap) {
"""
Creates a new proxy instance implementing the PropertySet interface and backed
by the data from the property map.
@param propertySet an annotation type that has the PropertySet meta-annotation
@param propertyMap the PropertyMap containing property values backing the proxy
@return proxy that implements the PropertySet interface
"""
assert propertySet != null && propertyMap != null;
if (!propertySet.isAnnotation())
throw new IllegalArgumentException(propertySet + " is not an annotation type");
return (T)Proxy.newProxyInstance(propertySet.getClassLoader(),
new Class [] {propertySet },
new PropertySetProxy(propertySet, propertyMap));
} | java | public static <T extends Annotation> T getProxy(Class<T> propertySet, PropertyMap propertyMap)
{
assert propertySet != null && propertyMap != null;
if (!propertySet.isAnnotation())
throw new IllegalArgumentException(propertySet + " is not an annotation type");
return (T)Proxy.newProxyInstance(propertySet.getClassLoader(),
new Class [] {propertySet },
new PropertySetProxy(propertySet, propertyMap));
} | [
"public",
"static",
"<",
"T",
"extends",
"Annotation",
">",
"T",
"getProxy",
"(",
"Class",
"<",
"T",
">",
"propertySet",
",",
"PropertyMap",
"propertyMap",
")",
"{",
"assert",
"propertySet",
"!=",
"null",
"&&",
"propertyMap",
"!=",
"null",
";",
"if",
"(",
"!",
"propertySet",
".",
"isAnnotation",
"(",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"propertySet",
"+",
"\" is not an annotation type\"",
")",
";",
"return",
"(",
"T",
")",
"Proxy",
".",
"newProxyInstance",
"(",
"propertySet",
".",
"getClassLoader",
"(",
")",
",",
"new",
"Class",
"[",
"]",
"{",
"propertySet",
"}",
",",
"new",
"PropertySetProxy",
"(",
"propertySet",
",",
"propertyMap",
")",
")",
";",
"}"
] | Creates a new proxy instance implementing the PropertySet interface and backed
by the data from the property map.
@param propertySet an annotation type that has the PropertySet meta-annotation
@param propertyMap the PropertyMap containing property values backing the proxy
@return proxy that implements the PropertySet interface | [
"Creates",
"a",
"new",
"proxy",
"instance",
"implementing",
"the",
"PropertySet",
"interface",
"and",
"backed",
"by",
"the",
"data",
"from",
"the",
"property",
"map",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/PropertySetProxy.java#L52-L62 |
alexvasilkov/GestureViews | library/src/main/java/com/alexvasilkov/gestures/animation/ViewPositionAnimator.java | ViewPositionAnimator.setState | public void setState(@FloatRange(from = 0f, to = 1f) float pos,
boolean leaving, boolean animate) {
"""
Stops current animation and sets position state to particular values.
<p>
Note, that once animator reaches {@code state = 0f} and {@code isLeaving = true}
it will cleanup all internal stuff. So you will need to call {@link #enter(View, boolean)}
or {@link #enter(ViewPosition, boolean)} again in order to continue using animator.
@param pos Current position
@param leaving Whether we we are in exiting direction ({@code true}) or in entering
({@code false})
@param animate Whether we should start animating from given position and in given direction
"""
if (!isActivated) {
throw new IllegalStateException(
"You should call enter(...) before calling setState(...)");
}
stopAnimation();
position = pos < 0f ? 0f : (pos > 1f ? 1f : pos);
isLeaving = leaving;
if (animate) {
startAnimationInternal();
}
applyCurrentPosition();
} | java | public void setState(@FloatRange(from = 0f, to = 1f) float pos,
boolean leaving, boolean animate) {
if (!isActivated) {
throw new IllegalStateException(
"You should call enter(...) before calling setState(...)");
}
stopAnimation();
position = pos < 0f ? 0f : (pos > 1f ? 1f : pos);
isLeaving = leaving;
if (animate) {
startAnimationInternal();
}
applyCurrentPosition();
} | [
"public",
"void",
"setState",
"(",
"@",
"FloatRange",
"(",
"from",
"=",
"0f",
",",
"to",
"=",
"1f",
")",
"float",
"pos",
",",
"boolean",
"leaving",
",",
"boolean",
"animate",
")",
"{",
"if",
"(",
"!",
"isActivated",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"You should call enter(...) before calling setState(...)\"",
")",
";",
"}",
"stopAnimation",
"(",
")",
";",
"position",
"=",
"pos",
"<",
"0f",
"?",
"0f",
":",
"(",
"pos",
">",
"1f",
"?",
"1f",
":",
"pos",
")",
";",
"isLeaving",
"=",
"leaving",
";",
"if",
"(",
"animate",
")",
"{",
"startAnimationInternal",
"(",
")",
";",
"}",
"applyCurrentPosition",
"(",
")",
";",
"}"
] | Stops current animation and sets position state to particular values.
<p>
Note, that once animator reaches {@code state = 0f} and {@code isLeaving = true}
it will cleanup all internal stuff. So you will need to call {@link #enter(View, boolean)}
or {@link #enter(ViewPosition, boolean)} again in order to continue using animator.
@param pos Current position
@param leaving Whether we we are in exiting direction ({@code true}) or in entering
({@code false})
@param animate Whether we should start animating from given position and in given direction | [
"Stops",
"current",
"animation",
"and",
"sets",
"position",
"state",
"to",
"particular",
"values",
".",
"<p",
">",
"Note",
"that",
"once",
"animator",
"reaches",
"{",
"@code",
"state",
"=",
"0f",
"}",
"and",
"{",
"@code",
"isLeaving",
"=",
"true",
"}",
"it",
"will",
"cleanup",
"all",
"internal",
"stuff",
".",
"So",
"you",
"will",
"need",
"to",
"call",
"{",
"@link",
"#enter",
"(",
"View",
"boolean",
")",
"}",
"or",
"{",
"@link",
"#enter",
"(",
"ViewPosition",
"boolean",
")",
"}",
"again",
"in",
"order",
"to",
"continue",
"using",
"animator",
"."
] | train | https://github.com/alexvasilkov/GestureViews/blob/f0a4c266e31dcad23bd0d9013531bc1c501b9c9f/library/src/main/java/com/alexvasilkov/gestures/animation/ViewPositionAnimator.java#L484-L498 |
apache/reef | lang/java/reef-applications/reef-vortex/src/main/java/org/apache/reef/vortex/driver/VortexRequestor.java | VortexRequestor.sendAsync | void sendAsync(final RunningTask reefTask, final MasterToWorkerRequest masterToWorkerRequest) {
"""
Sends a {@link MasterToWorkerRequest} asynchronously to a {@link org.apache.reef.vortex.evaluator.VortexWorker}.
"""
executorService.execute(new Runnable() {
@Override
public void run() {
// Possible race condition with VortexWorkerManager#terminate is addressed by the global lock in VortexMaster
send(reefTask, masterToWorkerRequest);
}
});
} | java | void sendAsync(final RunningTask reefTask, final MasterToWorkerRequest masterToWorkerRequest) {
executorService.execute(new Runnable() {
@Override
public void run() {
// Possible race condition with VortexWorkerManager#terminate is addressed by the global lock in VortexMaster
send(reefTask, masterToWorkerRequest);
}
});
} | [
"void",
"sendAsync",
"(",
"final",
"RunningTask",
"reefTask",
",",
"final",
"MasterToWorkerRequest",
"masterToWorkerRequest",
")",
"{",
"executorService",
".",
"execute",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"// Possible race condition with VortexWorkerManager#terminate is addressed by the global lock in VortexMaster",
"send",
"(",
"reefTask",
",",
"masterToWorkerRequest",
")",
";",
"}",
"}",
")",
";",
"}"
] | Sends a {@link MasterToWorkerRequest} asynchronously to a {@link org.apache.reef.vortex.evaluator.VortexWorker}. | [
"Sends",
"a",
"{"
] | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-applications/reef-vortex/src/main/java/org/apache/reef/vortex/driver/VortexRequestor.java#L46-L54 |
Waikato/moa | moa/src/main/java/moa/clusterers/clustree/ClusTree.java | ClusTree.insertBreadthFirst | private Entry insertBreadthFirst(ClusKernel newPoint, Budget budget, long timestamp) {
"""
insert newPoint into the tree using the BreadthFirst strategy, i.e.: insert into
the closest entry in a leaf node.
@param newPoint
@param budget
@param timestamp
@return
"""
//check all leaf nodes and get the one with the closest entry to newPoint
Node bestFit = findBestLeafNode(newPoint);
bestFit.makeOlder(timestamp, negLambda);
Entry parent = bestFit.getEntries()[0].getParentEntry();
// Search for an Entry with a weight under the threshold.
Entry irrelevantEntry = bestFit.getIrrelevantEntry(this.weightThreshold);
int numFreeEntries = bestFit.numFreeEntries();
Entry newEntry = new Entry(newPoint.getCenter().length,
newPoint, timestamp, parent, bestFit);
//if there is space, add it to the node ( doesn't ever occur, since nodes are created with 3 entries)
if (numFreeEntries>0){
bestFit.addEntry(newEntry, timestamp);
}
//if outdated cluster in this best fitting node, replace it
else if (irrelevantEntry != null) {
irrelevantEntry.overwriteOldEntry(newEntry);
}
//if there is space/outdated cluster on path to top, split. Else merge without split
else {
if (existsOutdatedEntryOnPath(bestFit)||!this.hasMaximalSize()){
// We have to split.
insertHereWithSplit(newEntry, bestFit, timestamp);
}
else {
mergeEntryWithoutSplit(bestFit, newEntry,
timestamp);
}
}
//update all nodes on path to top.
if (bestFit.getEntries()[0].getParentEntry()!=null)
updateToTop(bestFit.getEntries()[0].getParentEntry().getNode());
return null;
} | java | private Entry insertBreadthFirst(ClusKernel newPoint, Budget budget, long timestamp) {
//check all leaf nodes and get the one with the closest entry to newPoint
Node bestFit = findBestLeafNode(newPoint);
bestFit.makeOlder(timestamp, negLambda);
Entry parent = bestFit.getEntries()[0].getParentEntry();
// Search for an Entry with a weight under the threshold.
Entry irrelevantEntry = bestFit.getIrrelevantEntry(this.weightThreshold);
int numFreeEntries = bestFit.numFreeEntries();
Entry newEntry = new Entry(newPoint.getCenter().length,
newPoint, timestamp, parent, bestFit);
//if there is space, add it to the node ( doesn't ever occur, since nodes are created with 3 entries)
if (numFreeEntries>0){
bestFit.addEntry(newEntry, timestamp);
}
//if outdated cluster in this best fitting node, replace it
else if (irrelevantEntry != null) {
irrelevantEntry.overwriteOldEntry(newEntry);
}
//if there is space/outdated cluster on path to top, split. Else merge without split
else {
if (existsOutdatedEntryOnPath(bestFit)||!this.hasMaximalSize()){
// We have to split.
insertHereWithSplit(newEntry, bestFit, timestamp);
}
else {
mergeEntryWithoutSplit(bestFit, newEntry,
timestamp);
}
}
//update all nodes on path to top.
if (bestFit.getEntries()[0].getParentEntry()!=null)
updateToTop(bestFit.getEntries()[0].getParentEntry().getNode());
return null;
} | [
"private",
"Entry",
"insertBreadthFirst",
"(",
"ClusKernel",
"newPoint",
",",
"Budget",
"budget",
",",
"long",
"timestamp",
")",
"{",
"//check all leaf nodes and get the one with the closest entry to newPoint",
"Node",
"bestFit",
"=",
"findBestLeafNode",
"(",
"newPoint",
")",
";",
"bestFit",
".",
"makeOlder",
"(",
"timestamp",
",",
"negLambda",
")",
";",
"Entry",
"parent",
"=",
"bestFit",
".",
"getEntries",
"(",
")",
"[",
"0",
"]",
".",
"getParentEntry",
"(",
")",
";",
"// Search for an Entry with a weight under the threshold.",
"Entry",
"irrelevantEntry",
"=",
"bestFit",
".",
"getIrrelevantEntry",
"(",
"this",
".",
"weightThreshold",
")",
";",
"int",
"numFreeEntries",
"=",
"bestFit",
".",
"numFreeEntries",
"(",
")",
";",
"Entry",
"newEntry",
"=",
"new",
"Entry",
"(",
"newPoint",
".",
"getCenter",
"(",
")",
".",
"length",
",",
"newPoint",
",",
"timestamp",
",",
"parent",
",",
"bestFit",
")",
";",
"//if there is space, add it to the node ( doesn't ever occur, since nodes are created with 3 entries) ",
"if",
"(",
"numFreeEntries",
">",
"0",
")",
"{",
"bestFit",
".",
"addEntry",
"(",
"newEntry",
",",
"timestamp",
")",
";",
"}",
"//if outdated cluster in this best fitting node, replace it",
"else",
"if",
"(",
"irrelevantEntry",
"!=",
"null",
")",
"{",
"irrelevantEntry",
".",
"overwriteOldEntry",
"(",
"newEntry",
")",
";",
"}",
"//if there is space/outdated cluster on path to top, split. Else merge without split",
"else",
"{",
"if",
"(",
"existsOutdatedEntryOnPath",
"(",
"bestFit",
")",
"||",
"!",
"this",
".",
"hasMaximalSize",
"(",
")",
")",
"{",
"// We have to split.",
"insertHereWithSplit",
"(",
"newEntry",
",",
"bestFit",
",",
"timestamp",
")",
";",
"}",
"else",
"{",
"mergeEntryWithoutSplit",
"(",
"bestFit",
",",
"newEntry",
",",
"timestamp",
")",
";",
"}",
"}",
"//update all nodes on path to top.",
"if",
"(",
"bestFit",
".",
"getEntries",
"(",
")",
"[",
"0",
"]",
".",
"getParentEntry",
"(",
")",
"!=",
"null",
")",
"updateToTop",
"(",
"bestFit",
".",
"getEntries",
"(",
")",
"[",
"0",
"]",
".",
"getParentEntry",
"(",
")",
".",
"getNode",
"(",
")",
")",
";",
"return",
"null",
";",
"}"
] | insert newPoint into the tree using the BreadthFirst strategy, i.e.: insert into
the closest entry in a leaf node.
@param newPoint
@param budget
@param timestamp
@return | [
"insert",
"newPoint",
"into",
"the",
"tree",
"using",
"the",
"BreadthFirst",
"strategy",
"i",
".",
"e",
".",
":",
"insert",
"into",
"the",
"closest",
"entry",
"in",
"a",
"leaf",
"node",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/clustree/ClusTree.java#L214-L247 |
JRebirth/JRebirth | org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/util/ClassUtility.java | ClassUtility.findProperty | public static Field findProperty(final Class<?> sourceClass, final String itemName, final Class<?> searchedClass) {
"""
Retrieve a field according to the item name first, then according to searched class.
@param sourceClass the class to inspect
@param itemName the item name to find (LIKE_THIS)
@param searchedClass the property class to find if item name query has failed
@return the source class field that match provided criterion
"""
Field found = null;
if (itemName != null && !itemName.trim().isEmpty()) {
try {
found = sourceClass.getField(ClassUtility.underscoreToCamelCase(itemName));
} catch (NoSuchFieldException | SecurityException e) {
found = null;
}
}
if (found == null) {
Field f = null;
for (int i = 0; found == null && i < sourceClass.getFields().length; i++) {
f = sourceClass.getFields()[i];
if (f.getClass().equals(searchedClass)) {
found = f;
}
}
}
return found;
} | java | public static Field findProperty(final Class<?> sourceClass, final String itemName, final Class<?> searchedClass) {
Field found = null;
if (itemName != null && !itemName.trim().isEmpty()) {
try {
found = sourceClass.getField(ClassUtility.underscoreToCamelCase(itemName));
} catch (NoSuchFieldException | SecurityException e) {
found = null;
}
}
if (found == null) {
Field f = null;
for (int i = 0; found == null && i < sourceClass.getFields().length; i++) {
f = sourceClass.getFields()[i];
if (f.getClass().equals(searchedClass)) {
found = f;
}
}
}
return found;
} | [
"public",
"static",
"Field",
"findProperty",
"(",
"final",
"Class",
"<",
"?",
">",
"sourceClass",
",",
"final",
"String",
"itemName",
",",
"final",
"Class",
"<",
"?",
">",
"searchedClass",
")",
"{",
"Field",
"found",
"=",
"null",
";",
"if",
"(",
"itemName",
"!=",
"null",
"&&",
"!",
"itemName",
".",
"trim",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"try",
"{",
"found",
"=",
"sourceClass",
".",
"getField",
"(",
"ClassUtility",
".",
"underscoreToCamelCase",
"(",
"itemName",
")",
")",
";",
"}",
"catch",
"(",
"NoSuchFieldException",
"|",
"SecurityException",
"e",
")",
"{",
"found",
"=",
"null",
";",
"}",
"}",
"if",
"(",
"found",
"==",
"null",
")",
"{",
"Field",
"f",
"=",
"null",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"found",
"==",
"null",
"&&",
"i",
"<",
"sourceClass",
".",
"getFields",
"(",
")",
".",
"length",
";",
"i",
"++",
")",
"{",
"f",
"=",
"sourceClass",
".",
"getFields",
"(",
")",
"[",
"i",
"]",
";",
"if",
"(",
"f",
".",
"getClass",
"(",
")",
".",
"equals",
"(",
"searchedClass",
")",
")",
"{",
"found",
"=",
"f",
";",
"}",
"}",
"}",
"return",
"found",
";",
"}"
] | Retrieve a field according to the item name first, then according to searched class.
@param sourceClass the class to inspect
@param itemName the item name to find (LIKE_THIS)
@param searchedClass the property class to find if item name query has failed
@return the source class field that match provided criterion | [
"Retrieve",
"a",
"field",
"according",
"to",
"the",
"item",
"name",
"first",
"then",
"according",
"to",
"searched",
"class",
"."
] | train | https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/util/ClassUtility.java#L329-L350 |
sagiegurari/fax4j | src/main/java/org/fax4j/spi/http/XMLHTTPResponseHandler.java | XMLHTTPResponseHandler.findValueImpl | @Override
protected String findValueImpl(Document object,String path) {
"""
This function returns the requested value from the object data.<br>
The path is a set of key names seperated by ';'.
@param object
The object holding all the data
@param path
The path to the value (elements seperated by ;)
@return The value (null if not found)
"""
//split path to parts
String[] pathParts=path.split(AbstractMappingHTTPResponseHandler.VALUES_SEPERATOR);
int pathPartsAmount=pathParts.length;
String pathPart=null;
StringBuilder buffer=new StringBuilder(500);
for(int index=0;index<pathPartsAmount;index++)
{
//get next path part
pathPart=pathParts[index];
if(pathPart.length()>0)
{
buffer.append("/");
buffer.append(pathPart);
}
}
String xpathExpressionStr=buffer.toString();
XPathFactory xpathFactory=XPathFactory.newInstance();
XPath xpath=xpathFactory.newXPath();
String value=null;
try
{
//compile path to xpath
XPathExpression xpathExpression=xpath.compile(xpathExpressionStr);
//find value
value=xpathExpression.evaluate(object);
}
catch(XPathExpressionException exception)
{
throw new FaxException("Unable to parse/evaluate xpath expression: "+path,exception);
}
return value;
} | java | @Override
protected String findValueImpl(Document object,String path)
{
//split path to parts
String[] pathParts=path.split(AbstractMappingHTTPResponseHandler.VALUES_SEPERATOR);
int pathPartsAmount=pathParts.length;
String pathPart=null;
StringBuilder buffer=new StringBuilder(500);
for(int index=0;index<pathPartsAmount;index++)
{
//get next path part
pathPart=pathParts[index];
if(pathPart.length()>0)
{
buffer.append("/");
buffer.append(pathPart);
}
}
String xpathExpressionStr=buffer.toString();
XPathFactory xpathFactory=XPathFactory.newInstance();
XPath xpath=xpathFactory.newXPath();
String value=null;
try
{
//compile path to xpath
XPathExpression xpathExpression=xpath.compile(xpathExpressionStr);
//find value
value=xpathExpression.evaluate(object);
}
catch(XPathExpressionException exception)
{
throw new FaxException("Unable to parse/evaluate xpath expression: "+path,exception);
}
return value;
} | [
"@",
"Override",
"protected",
"String",
"findValueImpl",
"(",
"Document",
"object",
",",
"String",
"path",
")",
"{",
"//split path to parts",
"String",
"[",
"]",
"pathParts",
"=",
"path",
".",
"split",
"(",
"AbstractMappingHTTPResponseHandler",
".",
"VALUES_SEPERATOR",
")",
";",
"int",
"pathPartsAmount",
"=",
"pathParts",
".",
"length",
";",
"String",
"pathPart",
"=",
"null",
";",
"StringBuilder",
"buffer",
"=",
"new",
"StringBuilder",
"(",
"500",
")",
";",
"for",
"(",
"int",
"index",
"=",
"0",
";",
"index",
"<",
"pathPartsAmount",
";",
"index",
"++",
")",
"{",
"//get next path part",
"pathPart",
"=",
"pathParts",
"[",
"index",
"]",
";",
"if",
"(",
"pathPart",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"buffer",
".",
"append",
"(",
"\"/\"",
")",
";",
"buffer",
".",
"append",
"(",
"pathPart",
")",
";",
"}",
"}",
"String",
"xpathExpressionStr",
"=",
"buffer",
".",
"toString",
"(",
")",
";",
"XPathFactory",
"xpathFactory",
"=",
"XPathFactory",
".",
"newInstance",
"(",
")",
";",
"XPath",
"xpath",
"=",
"xpathFactory",
".",
"newXPath",
"(",
")",
";",
"String",
"value",
"=",
"null",
";",
"try",
"{",
"//compile path to xpath",
"XPathExpression",
"xpathExpression",
"=",
"xpath",
".",
"compile",
"(",
"xpathExpressionStr",
")",
";",
"//find value",
"value",
"=",
"xpathExpression",
".",
"evaluate",
"(",
"object",
")",
";",
"}",
"catch",
"(",
"XPathExpressionException",
"exception",
")",
"{",
"throw",
"new",
"FaxException",
"(",
"\"Unable to parse/evaluate xpath expression: \"",
"+",
"path",
",",
"exception",
")",
";",
"}",
"return",
"value",
";",
"}"
] | This function returns the requested value from the object data.<br>
The path is a set of key names seperated by ';'.
@param object
The object holding all the data
@param path
The path to the value (elements seperated by ;)
@return The value (null if not found) | [
"This",
"function",
"returns",
"the",
"requested",
"value",
"from",
"the",
"object",
"data",
".",
"<br",
">",
"The",
"path",
"is",
"a",
"set",
"of",
"key",
"names",
"seperated",
"by",
";",
"."
] | train | https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/http/XMLHTTPResponseHandler.java#L270-L308 |
cdk/cdk | storage/smiles/src/main/java/org/openscience/cdk/smiles/CDKToBeam.java | CDKToBeam.toBeamEdgeLabel | private static Bond toBeamEdgeLabel(IBond b, int flavour) throws CDKException {
"""
Convert a CDK {@link IBond} to the Beam edge label type.
@param b cdk bond
@return the edge label for the Beam edge
@throws NullPointerException the bond order was null and the bond was
not-aromatic
@throws IllegalArgumentException the bond order could not be converted
"""
if (SmiFlavor.isSet(flavour, SmiFlavor.UseAromaticSymbols) && b.isAromatic()) {
if (!b.getBegin().isAromatic() || !b.getEnd().isAromatic())
throw new IllegalStateException("Aromatic bond connects non-aromatic atomic atoms");
return Bond.AROMATIC;
}
if (b.getOrder() == null) throw new CDKException("A bond had undefined order, possible query bond?");
IBond.Order order = b.getOrder();
switch (order) {
case SINGLE:
return Bond.SINGLE;
case DOUBLE:
return Bond.DOUBLE;
case TRIPLE:
return Bond.TRIPLE;
case QUADRUPLE:
return Bond.QUADRUPLE;
default:
if (!SmiFlavor.isSet(flavour, SmiFlavor.UseAromaticSymbols) && b.isAromatic())
throw new CDKException("Cannot write Kekulé SMILES output due to aromatic bond with unset bond order - molecule should be Kekulized");
throw new CDKException("Unsupported bond order: " + order);
}
} | java | private static Bond toBeamEdgeLabel(IBond b, int flavour) throws CDKException {
if (SmiFlavor.isSet(flavour, SmiFlavor.UseAromaticSymbols) && b.isAromatic()) {
if (!b.getBegin().isAromatic() || !b.getEnd().isAromatic())
throw new IllegalStateException("Aromatic bond connects non-aromatic atomic atoms");
return Bond.AROMATIC;
}
if (b.getOrder() == null) throw new CDKException("A bond had undefined order, possible query bond?");
IBond.Order order = b.getOrder();
switch (order) {
case SINGLE:
return Bond.SINGLE;
case DOUBLE:
return Bond.DOUBLE;
case TRIPLE:
return Bond.TRIPLE;
case QUADRUPLE:
return Bond.QUADRUPLE;
default:
if (!SmiFlavor.isSet(flavour, SmiFlavor.UseAromaticSymbols) && b.isAromatic())
throw new CDKException("Cannot write Kekulé SMILES output due to aromatic bond with unset bond order - molecule should be Kekulized");
throw new CDKException("Unsupported bond order: " + order);
}
} | [
"private",
"static",
"Bond",
"toBeamEdgeLabel",
"(",
"IBond",
"b",
",",
"int",
"flavour",
")",
"throws",
"CDKException",
"{",
"if",
"(",
"SmiFlavor",
".",
"isSet",
"(",
"flavour",
",",
"SmiFlavor",
".",
"UseAromaticSymbols",
")",
"&&",
"b",
".",
"isAromatic",
"(",
")",
")",
"{",
"if",
"(",
"!",
"b",
".",
"getBegin",
"(",
")",
".",
"isAromatic",
"(",
")",
"||",
"!",
"b",
".",
"getEnd",
"(",
")",
".",
"isAromatic",
"(",
")",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Aromatic bond connects non-aromatic atomic atoms\"",
")",
";",
"return",
"Bond",
".",
"AROMATIC",
";",
"}",
"if",
"(",
"b",
".",
"getOrder",
"(",
")",
"==",
"null",
")",
"throw",
"new",
"CDKException",
"(",
"\"A bond had undefined order, possible query bond?\"",
")",
";",
"IBond",
".",
"Order",
"order",
"=",
"b",
".",
"getOrder",
"(",
")",
";",
"switch",
"(",
"order",
")",
"{",
"case",
"SINGLE",
":",
"return",
"Bond",
".",
"SINGLE",
";",
"case",
"DOUBLE",
":",
"return",
"Bond",
".",
"DOUBLE",
";",
"case",
"TRIPLE",
":",
"return",
"Bond",
".",
"TRIPLE",
";",
"case",
"QUADRUPLE",
":",
"return",
"Bond",
".",
"QUADRUPLE",
";",
"default",
":",
"if",
"(",
"!",
"SmiFlavor",
".",
"isSet",
"(",
"flavour",
",",
"SmiFlavor",
".",
"UseAromaticSymbols",
")",
"&&",
"b",
".",
"isAromatic",
"(",
")",
")",
"throw",
"new",
"CDKException",
"(",
"\"Cannot write Kekulé SMILES output due to aromatic bond with unset bond order - molecule should be Kekulized\")",
";",
"",
"throw",
"new",
"CDKException",
"(",
"\"Unsupported bond order: \"",
"+",
"order",
")",
";",
"}",
"}"
] | Convert a CDK {@link IBond} to the Beam edge label type.
@param b cdk bond
@return the edge label for the Beam edge
@throws NullPointerException the bond order was null and the bond was
not-aromatic
@throws IllegalArgumentException the bond order could not be converted | [
"Convert",
"a",
"CDK",
"{",
"@link",
"IBond",
"}",
"to",
"the",
"Beam",
"edge",
"label",
"type",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/storage/smiles/src/main/java/org/openscience/cdk/smiles/CDKToBeam.java#L274-L300 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java | MultiViewOps.createHomography | public static DMatrixRMaj createHomography(DMatrixRMaj R, Vector3D_F64 T,
double d, Vector3D_F64 N,
DMatrixRMaj K) {
"""
<p>
Computes a homography matrix from a rotation, translation, plane normal, plane distance, and
calibration matrix:<br>
x[2] = H*x[1]<br>
where x[1] is the point on the first camera and x[2] the location in the second camera.<br>
H = K*(R+(1/d)*T*N<sup>T</sup>)*K<sup>-1</sup><br>
Where [R,T] is the transform from camera 1 to camera, and K is the calibration matrix for both cameras.
</p>
@param R Rotation matrix from camera 1 to camera 2.
@param T Translation vector from camera 1 to camera 2.
@param d Distance > 0 of closest point on plane to the origin of camera 1.
@param N Normal of plane with respect to the first camera.
@param K Intrinsic calibration matrix
@return Uncalibrated homography matrix
"""
DMatrixRMaj temp = new DMatrixRMaj(3,3);
DMatrixRMaj K_inv = new DMatrixRMaj(3,3);
DMatrixRMaj H = createHomography(R, T, d, N);
// apply calibration matrix to R
CommonOps_DDRM.mult(K,H,temp);
CommonOps_DDRM.invert(K,K_inv);
CommonOps_DDRM.mult(temp,K_inv,H);
return H;
} | java | public static DMatrixRMaj createHomography(DMatrixRMaj R, Vector3D_F64 T,
double d, Vector3D_F64 N,
DMatrixRMaj K)
{
DMatrixRMaj temp = new DMatrixRMaj(3,3);
DMatrixRMaj K_inv = new DMatrixRMaj(3,3);
DMatrixRMaj H = createHomography(R, T, d, N);
// apply calibration matrix to R
CommonOps_DDRM.mult(K,H,temp);
CommonOps_DDRM.invert(K,K_inv);
CommonOps_DDRM.mult(temp,K_inv,H);
return H;
} | [
"public",
"static",
"DMatrixRMaj",
"createHomography",
"(",
"DMatrixRMaj",
"R",
",",
"Vector3D_F64",
"T",
",",
"double",
"d",
",",
"Vector3D_F64",
"N",
",",
"DMatrixRMaj",
"K",
")",
"{",
"DMatrixRMaj",
"temp",
"=",
"new",
"DMatrixRMaj",
"(",
"3",
",",
"3",
")",
";",
"DMatrixRMaj",
"K_inv",
"=",
"new",
"DMatrixRMaj",
"(",
"3",
",",
"3",
")",
";",
"DMatrixRMaj",
"H",
"=",
"createHomography",
"(",
"R",
",",
"T",
",",
"d",
",",
"N",
")",
";",
"// apply calibration matrix to R",
"CommonOps_DDRM",
".",
"mult",
"(",
"K",
",",
"H",
",",
"temp",
")",
";",
"CommonOps_DDRM",
".",
"invert",
"(",
"K",
",",
"K_inv",
")",
";",
"CommonOps_DDRM",
".",
"mult",
"(",
"temp",
",",
"K_inv",
",",
"H",
")",
";",
"return",
"H",
";",
"}"
] | <p>
Computes a homography matrix from a rotation, translation, plane normal, plane distance, and
calibration matrix:<br>
x[2] = H*x[1]<br>
where x[1] is the point on the first camera and x[2] the location in the second camera.<br>
H = K*(R+(1/d)*T*N<sup>T</sup>)*K<sup>-1</sup><br>
Where [R,T] is the transform from camera 1 to camera, and K is the calibration matrix for both cameras.
</p>
@param R Rotation matrix from camera 1 to camera 2.
@param T Translation vector from camera 1 to camera 2.
@param d Distance > 0 of closest point on plane to the origin of camera 1.
@param N Normal of plane with respect to the first camera.
@param K Intrinsic calibration matrix
@return Uncalibrated homography matrix | [
"<p",
">",
"Computes",
"a",
"homography",
"matrix",
"from",
"a",
"rotation",
"translation",
"plane",
"normal",
"plane",
"distance",
"and",
"calibration",
"matrix",
":",
"<br",
">",
"x",
"[",
"2",
"]",
"=",
"H",
"*",
"x",
"[",
"1",
"]",
"<br",
">",
"where",
"x",
"[",
"1",
"]",
"is",
"the",
"point",
"on",
"the",
"first",
"camera",
"and",
"x",
"[",
"2",
"]",
"the",
"location",
"in",
"the",
"second",
"camera",
".",
"<br",
">",
"H",
"=",
"K",
"*",
"(",
"R",
"+",
"(",
"1",
"/",
"d",
")",
"*",
"T",
"*",
"N<sup",
">",
"T<",
"/",
"sup",
">",
")",
"*",
"K<sup",
">",
"-",
"1<",
"/",
"sup",
">",
"<br",
">",
"Where",
"[",
"R",
"T",
"]",
"is",
"the",
"transform",
"from",
"camera",
"1",
"to",
"camera",
"and",
"K",
"is",
"the",
"calibration",
"matrix",
"for",
"both",
"cameras",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java#L808-L824 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ServiceEndpointPolicyDefinitionsInner.java | ServiceEndpointPolicyDefinitionsInner.createOrUpdate | public ServiceEndpointPolicyDefinitionInner createOrUpdate(String resourceGroupName, String serviceEndpointPolicyName, String serviceEndpointPolicyDefinitionName, ServiceEndpointPolicyDefinitionInner serviceEndpointPolicyDefinitions) {
"""
Creates or updates a service endpoint policy definition in the specified service endpoint policy.
@param resourceGroupName The name of the resource group.
@param serviceEndpointPolicyName The name of the service endpoint policy.
@param serviceEndpointPolicyDefinitionName The name of the service endpoint policy definition name.
@param serviceEndpointPolicyDefinitions Parameters supplied to the create or update service endpoint policy operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ServiceEndpointPolicyDefinitionInner object if successful.
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, serviceEndpointPolicyDefinitions).toBlocking().last().body();
} | java | public ServiceEndpointPolicyDefinitionInner createOrUpdate(String resourceGroupName, String serviceEndpointPolicyName, String serviceEndpointPolicyDefinitionName, ServiceEndpointPolicyDefinitionInner serviceEndpointPolicyDefinitions) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, serviceEndpointPolicyDefinitions).toBlocking().last().body();
} | [
"public",
"ServiceEndpointPolicyDefinitionInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"serviceEndpointPolicyName",
",",
"String",
"serviceEndpointPolicyDefinitionName",
",",
"ServiceEndpointPolicyDefinitionInner",
"serviceEndpointPolicyDefinitions",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serviceEndpointPolicyName",
",",
"serviceEndpointPolicyDefinitionName",
",",
"serviceEndpointPolicyDefinitions",
")",
".",
"toBlocking",
"(",
")",
".",
"last",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Creates or updates a service endpoint policy definition in the specified service endpoint policy.
@param resourceGroupName The name of the resource group.
@param serviceEndpointPolicyName The name of the service endpoint policy.
@param serviceEndpointPolicyDefinitionName The name of the service endpoint policy definition name.
@param serviceEndpointPolicyDefinitions Parameters supplied to the create or update service endpoint policy operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ServiceEndpointPolicyDefinitionInner object if successful. | [
"Creates",
"or",
"updates",
"a",
"service",
"endpoint",
"policy",
"definition",
"in",
"the",
"specified",
"service",
"endpoint",
"policy",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ServiceEndpointPolicyDefinitionsInner.java#L362-L364 |
albfernandez/itext2 | src/main/java/com/lowagie/text/xml/SAXmyHandler.java | SAXmyHandler.endElement | public void endElement(String uri, String lname, String name) {
"""
This method gets called when an end tag is encountered.
@param uri the Uniform Resource Identifier
@param lname the local name (without prefix), or the empty string if Namespace processing is not being performed.
@param name the name of the tag that ends
"""
if (myTags.containsKey(name)) {
XmlPeer peer = (XmlPeer) myTags.get(name);
handleEndingTags(peer.getTag());
}
else {
handleEndingTags(name);
}
} | java | public void endElement(String uri, String lname, String name) {
if (myTags.containsKey(name)) {
XmlPeer peer = (XmlPeer) myTags.get(name);
handleEndingTags(peer.getTag());
}
else {
handleEndingTags(name);
}
} | [
"public",
"void",
"endElement",
"(",
"String",
"uri",
",",
"String",
"lname",
",",
"String",
"name",
")",
"{",
"if",
"(",
"myTags",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"XmlPeer",
"peer",
"=",
"(",
"XmlPeer",
")",
"myTags",
".",
"get",
"(",
"name",
")",
";",
"handleEndingTags",
"(",
"peer",
".",
"getTag",
"(",
")",
")",
";",
"}",
"else",
"{",
"handleEndingTags",
"(",
"name",
")",
";",
"}",
"}"
] | This method gets called when an end tag is encountered.
@param uri the Uniform Resource Identifier
@param lname the local name (without prefix), or the empty string if Namespace processing is not being performed.
@param name the name of the tag that ends | [
"This",
"method",
"gets",
"called",
"when",
"an",
"end",
"tag",
"is",
"encountered",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/xml/SAXmyHandler.java#L111-L119 |
OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.openapi/src/com/ibm/ws/microprofile/openapi/impl/core/jackson/JAXBAnnotationsHelper.java | JAXBAnnotationsHelper.applyAttribute | private static void applyAttribute(Annotated member, Schema property) {
"""
Puts definitions for XML attribute.
@param member annotations provider
@param property property instance to be updated
"""
final XmlAttribute attribute = member.getAnnotation(XmlAttribute.class);
if (attribute != null) {
final XML xml = getXml(property);
xml.setAttribute(true);
setName(attribute.namespace(), attribute.name(), property);
}
} | java | private static void applyAttribute(Annotated member, Schema property) {
final XmlAttribute attribute = member.getAnnotation(XmlAttribute.class);
if (attribute != null) {
final XML xml = getXml(property);
xml.setAttribute(true);
setName(attribute.namespace(), attribute.name(), property);
}
} | [
"private",
"static",
"void",
"applyAttribute",
"(",
"Annotated",
"member",
",",
"Schema",
"property",
")",
"{",
"final",
"XmlAttribute",
"attribute",
"=",
"member",
".",
"getAnnotation",
"(",
"XmlAttribute",
".",
"class",
")",
";",
"if",
"(",
"attribute",
"!=",
"null",
")",
"{",
"final",
"XML",
"xml",
"=",
"getXml",
"(",
"property",
")",
";",
"xml",
".",
"setAttribute",
"(",
"true",
")",
";",
"setName",
"(",
"attribute",
".",
"namespace",
"(",
")",
",",
"attribute",
".",
"name",
"(",
")",
",",
"property",
")",
";",
"}",
"}"
] | Puts definitions for XML attribute.
@param member annotations provider
@param property property instance to be updated | [
"Puts",
"definitions",
"for",
"XML",
"attribute",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.openapi/src/com/ibm/ws/microprofile/openapi/impl/core/jackson/JAXBAnnotationsHelper.java#L78-L85 |
app55/app55-java | src/support/java/com/googlecode/openbeans/beancontext/BeanContextServicesSupport.java | BeanContextServicesSupport.releaseServiceWithoutCheck | private void releaseServiceWithoutCheck(BeanContextChild child, BCSSChild bcssChild, Object requestor, Object service, boolean callRevokedListener) {
"""
Releases a service without checking the membership of the child.
"""
if (bcssChild.serviceRecords == null || bcssChild.serviceRecords.isEmpty())
{
return;
}
synchronized (child)
{
// scan record
for (Iterator iter = bcssChild.serviceRecords.iterator(); iter.hasNext();)
{
ServiceRecord rec = (ServiceRecord) iter.next();
if (rec.requestor == requestor && rec.service == service)
{
// release service
rec.provider.releaseService(getBeanContextServicesPeer(), requestor, service);
// call service revoked listener
if (callRevokedListener && rec.revokedListener != null)
{
rec.revokedListener.serviceRevoked(new BeanContextServiceRevokedEvent(getBeanContextServicesPeer(), rec.serviceClass, true));
}
// remove record
iter.remove();
break;
}
}
}
} | java | private void releaseServiceWithoutCheck(BeanContextChild child, BCSSChild bcssChild, Object requestor, Object service, boolean callRevokedListener)
{
if (bcssChild.serviceRecords == null || bcssChild.serviceRecords.isEmpty())
{
return;
}
synchronized (child)
{
// scan record
for (Iterator iter = bcssChild.serviceRecords.iterator(); iter.hasNext();)
{
ServiceRecord rec = (ServiceRecord) iter.next();
if (rec.requestor == requestor && rec.service == service)
{
// release service
rec.provider.releaseService(getBeanContextServicesPeer(), requestor, service);
// call service revoked listener
if (callRevokedListener && rec.revokedListener != null)
{
rec.revokedListener.serviceRevoked(new BeanContextServiceRevokedEvent(getBeanContextServicesPeer(), rec.serviceClass, true));
}
// remove record
iter.remove();
break;
}
}
}
} | [
"private",
"void",
"releaseServiceWithoutCheck",
"(",
"BeanContextChild",
"child",
",",
"BCSSChild",
"bcssChild",
",",
"Object",
"requestor",
",",
"Object",
"service",
",",
"boolean",
"callRevokedListener",
")",
"{",
"if",
"(",
"bcssChild",
".",
"serviceRecords",
"==",
"null",
"||",
"bcssChild",
".",
"serviceRecords",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"synchronized",
"(",
"child",
")",
"{",
"// scan record",
"for",
"(",
"Iterator",
"iter",
"=",
"bcssChild",
".",
"serviceRecords",
".",
"iterator",
"(",
")",
";",
"iter",
".",
"hasNext",
"(",
")",
";",
")",
"{",
"ServiceRecord",
"rec",
"=",
"(",
"ServiceRecord",
")",
"iter",
".",
"next",
"(",
")",
";",
"if",
"(",
"rec",
".",
"requestor",
"==",
"requestor",
"&&",
"rec",
".",
"service",
"==",
"service",
")",
"{",
"// release service",
"rec",
".",
"provider",
".",
"releaseService",
"(",
"getBeanContextServicesPeer",
"(",
")",
",",
"requestor",
",",
"service",
")",
";",
"// call service revoked listener",
"if",
"(",
"callRevokedListener",
"&&",
"rec",
".",
"revokedListener",
"!=",
"null",
")",
"{",
"rec",
".",
"revokedListener",
".",
"serviceRevoked",
"(",
"new",
"BeanContextServiceRevokedEvent",
"(",
"getBeanContextServicesPeer",
"(",
")",
",",
"rec",
".",
"serviceClass",
",",
"true",
")",
")",
";",
"}",
"// remove record",
"iter",
".",
"remove",
"(",
")",
";",
"break",
";",
"}",
"}",
"}",
"}"
] | Releases a service without checking the membership of the child. | [
"Releases",
"a",
"service",
"without",
"checking",
"the",
"membership",
"of",
"the",
"child",
"."
] | train | https://github.com/app55/app55-java/blob/73e51d0f3141a859dfbd37ca9becef98477e553e/src/support/java/com/googlecode/openbeans/beancontext/BeanContextServicesSupport.java#L850-L879 |
jbundle/jbundle | main/msg/src/main/java/org/jbundle/main/msg/db/CalcTimeoutTimeHandler.java | CalcTimeoutTimeHandler.doRecordChange | public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) {
"""
Called when a change is the record status is about to happen/has happened.
@param field If this file change is due to a field, this is the field.
@param iChangeType The type of change that occurred.
@param bDisplayOption If true, display any changes.
@return an error code.
ADD_TYPE - Before a write.
UPDATE_TYPE - Before an update.
DELETE_TYPE - Before a delete.
AFTER_UPDATE_TYPE - After a write or update.
LOCK_TYPE - Before a lock.
SELECT_TYPE - After a select.
DESELECT_TYPE - After a deselect.
MOVE_NEXT_TYPE - After a move.
AFTER_REQUERY_TYPE - Record opened.
SELECT_EOF_TYPE - EOF Hit.
"""
switch (iChangeType)
{
case DBConstants.ADD_TYPE:
case DBConstants.UPDATE_TYPE:
if (this.getOwner().getField(MessageLog.LAST_CHANGED) != null) // Always
if (this.getOwner().getField(MessageLog.TIMEOUT_SECONDS).getValue() > 0)
if (this.getOwner().getField(MessageLog.TIMEOUT_TIME).getValue() == 0) // Don't change timeout after it was set
{
if (MessageStatus.SENT.equalsIgnoreCase(((ReferenceField)this.getOwner().getField(MessageLog.MESSAGE_STATUS_ID)).getReference().getField(MessageStatus.CODE).toString()))
{
Calendar cal = ((DateTimeField)this.getOwner().getField(MessageLog.LAST_CHANGED)).getCalendar();
int iSeconds = (int)this.getOwner().getField(MessageLog.TIMEOUT_SECONDS).getValue();
cal.add(Calendar.SECOND, iSeconds);
((DateTimeField)this.getOwner().getField(MessageLog.TIMEOUT_TIME)).setCalendar(cal, bDisplayOption, DBConstants.SCREEN_MOVE);
}
else
{ // Clear the timeout
((DateTimeField)this.getOwner().getField(MessageLog.TIMEOUT_TIME)).setData(null, bDisplayOption, DBConstants.SCREEN_MOVE);
}
}
break;
}
return super.doRecordChange(field, iChangeType, bDisplayOption);
} | java | public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption)
{
switch (iChangeType)
{
case DBConstants.ADD_TYPE:
case DBConstants.UPDATE_TYPE:
if (this.getOwner().getField(MessageLog.LAST_CHANGED) != null) // Always
if (this.getOwner().getField(MessageLog.TIMEOUT_SECONDS).getValue() > 0)
if (this.getOwner().getField(MessageLog.TIMEOUT_TIME).getValue() == 0) // Don't change timeout after it was set
{
if (MessageStatus.SENT.equalsIgnoreCase(((ReferenceField)this.getOwner().getField(MessageLog.MESSAGE_STATUS_ID)).getReference().getField(MessageStatus.CODE).toString()))
{
Calendar cal = ((DateTimeField)this.getOwner().getField(MessageLog.LAST_CHANGED)).getCalendar();
int iSeconds = (int)this.getOwner().getField(MessageLog.TIMEOUT_SECONDS).getValue();
cal.add(Calendar.SECOND, iSeconds);
((DateTimeField)this.getOwner().getField(MessageLog.TIMEOUT_TIME)).setCalendar(cal, bDisplayOption, DBConstants.SCREEN_MOVE);
}
else
{ // Clear the timeout
((DateTimeField)this.getOwner().getField(MessageLog.TIMEOUT_TIME)).setData(null, bDisplayOption, DBConstants.SCREEN_MOVE);
}
}
break;
}
return super.doRecordChange(field, iChangeType, bDisplayOption);
} | [
"public",
"int",
"doRecordChange",
"(",
"FieldInfo",
"field",
",",
"int",
"iChangeType",
",",
"boolean",
"bDisplayOption",
")",
"{",
"switch",
"(",
"iChangeType",
")",
"{",
"case",
"DBConstants",
".",
"ADD_TYPE",
":",
"case",
"DBConstants",
".",
"UPDATE_TYPE",
":",
"if",
"(",
"this",
".",
"getOwner",
"(",
")",
".",
"getField",
"(",
"MessageLog",
".",
"LAST_CHANGED",
")",
"!=",
"null",
")",
"// Always",
"if",
"(",
"this",
".",
"getOwner",
"(",
")",
".",
"getField",
"(",
"MessageLog",
".",
"TIMEOUT_SECONDS",
")",
".",
"getValue",
"(",
")",
">",
"0",
")",
"if",
"(",
"this",
".",
"getOwner",
"(",
")",
".",
"getField",
"(",
"MessageLog",
".",
"TIMEOUT_TIME",
")",
".",
"getValue",
"(",
")",
"==",
"0",
")",
"// Don't change timeout after it was set",
"{",
"if",
"(",
"MessageStatus",
".",
"SENT",
".",
"equalsIgnoreCase",
"(",
"(",
"(",
"ReferenceField",
")",
"this",
".",
"getOwner",
"(",
")",
".",
"getField",
"(",
"MessageLog",
".",
"MESSAGE_STATUS_ID",
")",
")",
".",
"getReference",
"(",
")",
".",
"getField",
"(",
"MessageStatus",
".",
"CODE",
")",
".",
"toString",
"(",
")",
")",
")",
"{",
"Calendar",
"cal",
"=",
"(",
"(",
"DateTimeField",
")",
"this",
".",
"getOwner",
"(",
")",
".",
"getField",
"(",
"MessageLog",
".",
"LAST_CHANGED",
")",
")",
".",
"getCalendar",
"(",
")",
";",
"int",
"iSeconds",
"=",
"(",
"int",
")",
"this",
".",
"getOwner",
"(",
")",
".",
"getField",
"(",
"MessageLog",
".",
"TIMEOUT_SECONDS",
")",
".",
"getValue",
"(",
")",
";",
"cal",
".",
"add",
"(",
"Calendar",
".",
"SECOND",
",",
"iSeconds",
")",
";",
"(",
"(",
"DateTimeField",
")",
"this",
".",
"getOwner",
"(",
")",
".",
"getField",
"(",
"MessageLog",
".",
"TIMEOUT_TIME",
")",
")",
".",
"setCalendar",
"(",
"cal",
",",
"bDisplayOption",
",",
"DBConstants",
".",
"SCREEN_MOVE",
")",
";",
"}",
"else",
"{",
"// Clear the timeout",
"(",
"(",
"DateTimeField",
")",
"this",
".",
"getOwner",
"(",
")",
".",
"getField",
"(",
"MessageLog",
".",
"TIMEOUT_TIME",
")",
")",
".",
"setData",
"(",
"null",
",",
"bDisplayOption",
",",
"DBConstants",
".",
"SCREEN_MOVE",
")",
";",
"}",
"}",
"break",
";",
"}",
"return",
"super",
".",
"doRecordChange",
"(",
"field",
",",
"iChangeType",
",",
"bDisplayOption",
")",
";",
"}"
] | Called when a change is the record status is about to happen/has happened.
@param field If this file change is due to a field, this is the field.
@param iChangeType The type of change that occurred.
@param bDisplayOption If true, display any changes.
@return an error code.
ADD_TYPE - Before a write.
UPDATE_TYPE - Before an update.
DELETE_TYPE - Before a delete.
AFTER_UPDATE_TYPE - After a write or update.
LOCK_TYPE - Before a lock.
SELECT_TYPE - After a select.
DESELECT_TYPE - After a deselect.
MOVE_NEXT_TYPE - After a move.
AFTER_REQUERY_TYPE - Record opened.
SELECT_EOF_TYPE - EOF Hit. | [
"Called",
"when",
"a",
"change",
"is",
"the",
"record",
"status",
"is",
"about",
"to",
"happen",
"/",
"has",
"happened",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/main/msg/src/main/java/org/jbundle/main/msg/db/CalcTimeoutTimeHandler.java#L73-L98 |
RestComm/Restcomm-Connect | restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/SupervisorEndpoint.java | SupervisorEndpoint.registerForMetricsUpdates | @Path("/remote")
@POST
@Produces( {
"""
Register a remote location where Restcomm will send monitoring updates
"""MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response registerForMetricsUpdates(@PathParam("accountSid") final String accountSid,
@Context UriInfo info,
@HeaderParam("Accept") String accept) {
return registerForUpdates(accountSid, info, retrieveMediaType(accept));
} | java | @Path("/remote")
@POST
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response registerForMetricsUpdates(@PathParam("accountSid") final String accountSid,
@Context UriInfo info,
@HeaderParam("Accept") String accept) {
return registerForUpdates(accountSid, info, retrieveMediaType(accept));
} | [
"@",
"Path",
"(",
"\"/remote\"",
")",
"@",
"POST",
"@",
"Produces",
"(",
"{",
"MediaType",
".",
"APPLICATION_XML",
",",
"MediaType",
".",
"APPLICATION_JSON",
"}",
")",
"public",
"Response",
"registerForMetricsUpdates",
"(",
"@",
"PathParam",
"(",
"\"accountSid\"",
")",
"final",
"String",
"accountSid",
",",
"@",
"Context",
"UriInfo",
"info",
",",
"@",
"HeaderParam",
"(",
"\"Accept\"",
")",
"String",
"accept",
")",
"{",
"return",
"registerForUpdates",
"(",
"accountSid",
",",
"info",
",",
"retrieveMediaType",
"(",
"accept",
")",
")",
";",
"}"
] | Register a remote location where Restcomm will send monitoring updates | [
"Register",
"a",
"remote",
"location",
"where",
"Restcomm",
"will",
"send",
"monitoring",
"updates"
] | train | https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/SupervisorEndpoint.java#L314-L321 |
samskivert/samskivert | src/main/java/com/samskivert/net/cddb/CDDB.java | CDDB.lscat | public String[] lscat()
throws IOException, CDDBException {
"""
Fetches and returns the list of categories supported by the server.
@throws IOException if a problem occurs chatting to the server.
@throws CDDBException if the server responds with an error.
"""
// sanity check
if (_sock == null) {
throw new CDDBException(500, "Not connected");
}
// make the request
Response rsp = request("cddb lscat");
// anything other than an OK response earns an exception
if (rsp.code != 210) {
throw new CDDBException(rsp.code, rsp.message);
}
ArrayList<String> list = new ArrayList<String>();
String input;
while (!(input = _in.readLine()).equals(CDDBProtocol.TERMINATOR)) {
list.add(input);
}
String[] categories = new String[list.size()];
list.toArray(categories);
return categories;
} | java | public String[] lscat()
throws IOException, CDDBException
{
// sanity check
if (_sock == null) {
throw new CDDBException(500, "Not connected");
}
// make the request
Response rsp = request("cddb lscat");
// anything other than an OK response earns an exception
if (rsp.code != 210) {
throw new CDDBException(rsp.code, rsp.message);
}
ArrayList<String> list = new ArrayList<String>();
String input;
while (!(input = _in.readLine()).equals(CDDBProtocol.TERMINATOR)) {
list.add(input);
}
String[] categories = new String[list.size()];
list.toArray(categories);
return categories;
} | [
"public",
"String",
"[",
"]",
"lscat",
"(",
")",
"throws",
"IOException",
",",
"CDDBException",
"{",
"// sanity check",
"if",
"(",
"_sock",
"==",
"null",
")",
"{",
"throw",
"new",
"CDDBException",
"(",
"500",
",",
"\"Not connected\"",
")",
";",
"}",
"// make the request",
"Response",
"rsp",
"=",
"request",
"(",
"\"cddb lscat\"",
")",
";",
"// anything other than an OK response earns an exception",
"if",
"(",
"rsp",
".",
"code",
"!=",
"210",
")",
"{",
"throw",
"new",
"CDDBException",
"(",
"rsp",
".",
"code",
",",
"rsp",
".",
"message",
")",
";",
"}",
"ArrayList",
"<",
"String",
">",
"list",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"String",
"input",
";",
"while",
"(",
"!",
"(",
"input",
"=",
"_in",
".",
"readLine",
"(",
")",
")",
".",
"equals",
"(",
"CDDBProtocol",
".",
"TERMINATOR",
")",
")",
"{",
"list",
".",
"add",
"(",
"input",
")",
";",
"}",
"String",
"[",
"]",
"categories",
"=",
"new",
"String",
"[",
"list",
".",
"size",
"(",
")",
"]",
";",
"list",
".",
"toArray",
"(",
"categories",
")",
";",
"return",
"categories",
";",
"}"
] | Fetches and returns the list of categories supported by the server.
@throws IOException if a problem occurs chatting to the server.
@throws CDDBException if the server responds with an error. | [
"Fetches",
"and",
"returns",
"the",
"list",
"of",
"categories",
"supported",
"by",
"the",
"server",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/net/cddb/CDDB.java#L227-L252 |
sirensolutions/siren-join | src/main/java/solutions/siren/join/action/terms/collector/LongBloomFilter.java | LongBloomFilter.getblock | protected static long getblock(byte[] key, int offset, int index) {
"""
NOTE: don't replace this code with the o.e.common.hashing.MurmurHash3 method which returns a different hash
"""
int i_8 = index << 3;
int blockOffset = offset + i_8;
return ((long) key[blockOffset + 0] & 0xff) + (((long) key[blockOffset + 1] & 0xff) << 8) +
(((long) key[blockOffset + 2] & 0xff) << 16) + (((long) key[blockOffset + 3] & 0xff) << 24) +
(((long) key[blockOffset + 4] & 0xff) << 32) + (((long) key[blockOffset + 5] & 0xff) << 40) +
(((long) key[blockOffset + 6] & 0xff) << 48) + (((long) key[blockOffset + 7] & 0xff) << 56);
} | java | protected static long getblock(byte[] key, int offset, int index) {
int i_8 = index << 3;
int blockOffset = offset + i_8;
return ((long) key[blockOffset + 0] & 0xff) + (((long) key[blockOffset + 1] & 0xff) << 8) +
(((long) key[blockOffset + 2] & 0xff) << 16) + (((long) key[blockOffset + 3] & 0xff) << 24) +
(((long) key[blockOffset + 4] & 0xff) << 32) + (((long) key[blockOffset + 5] & 0xff) << 40) +
(((long) key[blockOffset + 6] & 0xff) << 48) + (((long) key[blockOffset + 7] & 0xff) << 56);
} | [
"protected",
"static",
"long",
"getblock",
"(",
"byte",
"[",
"]",
"key",
",",
"int",
"offset",
",",
"int",
"index",
")",
"{",
"int",
"i_8",
"=",
"index",
"<<",
"3",
";",
"int",
"blockOffset",
"=",
"offset",
"+",
"i_8",
";",
"return",
"(",
"(",
"long",
")",
"key",
"[",
"blockOffset",
"+",
"0",
"]",
"&",
"0xff",
")",
"+",
"(",
"(",
"(",
"long",
")",
"key",
"[",
"blockOffset",
"+",
"1",
"]",
"&",
"0xff",
")",
"<<",
"8",
")",
"+",
"(",
"(",
"(",
"long",
")",
"key",
"[",
"blockOffset",
"+",
"2",
"]",
"&",
"0xff",
")",
"<<",
"16",
")",
"+",
"(",
"(",
"(",
"long",
")",
"key",
"[",
"blockOffset",
"+",
"3",
"]",
"&",
"0xff",
")",
"<<",
"24",
")",
"+",
"(",
"(",
"(",
"long",
")",
"key",
"[",
"blockOffset",
"+",
"4",
"]",
"&",
"0xff",
")",
"<<",
"32",
")",
"+",
"(",
"(",
"(",
"long",
")",
"key",
"[",
"blockOffset",
"+",
"5",
"]",
"&",
"0xff",
")",
"<<",
"40",
")",
"+",
"(",
"(",
"(",
"long",
")",
"key",
"[",
"blockOffset",
"+",
"6",
"]",
"&",
"0xff",
")",
"<<",
"48",
")",
"+",
"(",
"(",
"(",
"long",
")",
"key",
"[",
"blockOffset",
"+",
"7",
"]",
"&",
"0xff",
")",
"<<",
"56",
")",
";",
"}"
] | NOTE: don't replace this code with the o.e.common.hashing.MurmurHash3 method which returns a different hash | [
"NOTE",
":",
"don",
"t",
"replace",
"this",
"code",
"with",
"the",
"o",
".",
"e",
".",
"common",
".",
"hashing",
".",
"MurmurHash3",
"method",
"which",
"returns",
"a",
"different",
"hash"
] | train | https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/terms/collector/LongBloomFilter.java#L355-L362 |
jaxio/celerio | celerio-engine/src/main/java/com/jaxio/celerio/util/IOUtil.java | IOUtil.stringToFile | public void stringToFile(String content, File file) throws IOException {
"""
Save a string to a file.
@param content the string to be written to file
@param file fhe file object
"""
stringToOutputStream(content, new FileOutputStream(file));
} | java | public void stringToFile(String content, File file) throws IOException {
stringToOutputStream(content, new FileOutputStream(file));
} | [
"public",
"void",
"stringToFile",
"(",
"String",
"content",
",",
"File",
"file",
")",
"throws",
"IOException",
"{",
"stringToOutputStream",
"(",
"content",
",",
"new",
"FileOutputStream",
"(",
"file",
")",
")",
";",
"}"
] | Save a string to a file.
@param content the string to be written to file
@param file fhe file object | [
"Save",
"a",
"string",
"to",
"a",
"file",
"."
] | train | https://github.com/jaxio/celerio/blob/fbfacb639e286f9f3f3a18986f74ea275bebd887/celerio-engine/src/main/java/com/jaxio/celerio/util/IOUtil.java#L63-L65 |
vznet/mongo-jackson-mapper | src/main/java/net/vz/mongodb/jackson/DBUpdate.java | DBUpdate.pushAll | public static Builder pushAll(String field, List<?> values) {
"""
Add all of the given values to the array value at the specified field atomically
@param field The field to add the values to
@param values The values to add
@return this object
"""
return new Builder().pushAll(field, values);
} | java | public static Builder pushAll(String field, List<?> values) {
return new Builder().pushAll(field, values);
} | [
"public",
"static",
"Builder",
"pushAll",
"(",
"String",
"field",
",",
"List",
"<",
"?",
">",
"values",
")",
"{",
"return",
"new",
"Builder",
"(",
")",
".",
"pushAll",
"(",
"field",
",",
"values",
")",
";",
"}"
] | Add all of the given values to the array value at the specified field atomically
@param field The field to add the values to
@param values The values to add
@return this object | [
"Add",
"all",
"of",
"the",
"given",
"values",
"to",
"the",
"array",
"value",
"at",
"the",
"specified",
"field",
"atomically"
] | train | https://github.com/vznet/mongo-jackson-mapper/blob/ecd189aefa89636cddf70fb383f5d676be347976/src/main/java/net/vz/mongodb/jackson/DBUpdate.java#L112-L114 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.