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
|
---|---|---|---|---|---|---|---|---|---|---|
anotheria/moskito | moskito-extensions/moskito-monitoring-plugin/src/main/java/net/anotheria/moskito/extensions/monitoring/fetcher/HttpHelper.java | HttpHelper.areSame | private static boolean areSame(Credentials c1, Credentials c2) {
"""
Compare two instances of Credentials.
@param c1 instance of Credentials
@param c2 another instance of Credentials
@return comparison result. {@code true} if both are null or contain same user/password pairs, false otherwise.
"""
if (c1 == null) {
return c2 == null;
} else {
return StringUtils.equals(c1.getUserPrincipal().getName(), c1.getUserPrincipal().getName()) &&
StringUtils.equals(c1.getPassword(), c1.getPassword());
}
} | java | private static boolean areSame(Credentials c1, Credentials c2) {
if (c1 == null) {
return c2 == null;
} else {
return StringUtils.equals(c1.getUserPrincipal().getName(), c1.getUserPrincipal().getName()) &&
StringUtils.equals(c1.getPassword(), c1.getPassword());
}
} | [
"private",
"static",
"boolean",
"areSame",
"(",
"Credentials",
"c1",
",",
"Credentials",
"c2",
")",
"{",
"if",
"(",
"c1",
"==",
"null",
")",
"{",
"return",
"c2",
"==",
"null",
";",
"}",
"else",
"{",
"return",
"StringUtils",
".",
"equals",
"(",
"c1",
".",
"getUserPrincipal",
"(",
")",
".",
"getName",
"(",
")",
",",
"c1",
".",
"getUserPrincipal",
"(",
")",
".",
"getName",
"(",
")",
")",
"&&",
"StringUtils",
".",
"equals",
"(",
"c1",
".",
"getPassword",
"(",
")",
",",
"c1",
".",
"getPassword",
"(",
")",
")",
";",
"}",
"}"
] | Compare two instances of Credentials.
@param c1 instance of Credentials
@param c2 another instance of Credentials
@return comparison result. {@code true} if both are null or contain same user/password pairs, false otherwise. | [
"Compare",
"two",
"instances",
"of",
"Credentials",
"."
] | train | https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-extensions/moskito-monitoring-plugin/src/main/java/net/anotheria/moskito/extensions/monitoring/fetcher/HttpHelper.java#L114-L121 |
Stratio/deep-spark | deep-cassandra/src/main/java/com/stratio/deep/cassandra/thrift/ThriftRangeUtils.java | ThriftRangeUtils.getRanges | public List<DeepTokenRange> getRanges() {
"""
Returns the token ranges of the Cassandra ring that will be mapped to Spark partitions.
The returned ranges are the Cassandra's physical ones, without any splitting.
@return the list of Cassandra ring token ranges.
"""
try {
List<TokenRange> tokenRanges;
ThriftClient client = ThriftClient.build(host, rpcPort);
try {
tokenRanges = client.describe_local_ring(keyspace);
} catch (TApplicationException e) {
if (e.getType() == TApplicationException.UNKNOWN_METHOD) {
tokenRanges = client.describe_ring(keyspace);
} else {
throw new DeepGenericException("Unknown server error", e);
}
}
client.close();
List<DeepTokenRange> deepTokenRanges = new ArrayList<>(tokenRanges.size());
for (TokenRange tokenRange : tokenRanges) {
Comparable start = tokenAsComparable(tokenRange.getStart_token());
Comparable end = tokenAsComparable(tokenRange.getEnd_token());
deepTokenRanges.add(new DeepTokenRange(start, end, tokenRange.getEndpoints()));
}
return deepTokenRanges;
} catch (TException e) {
throw new DeepGenericException("No available replicas for get ring token ranges", e);
}
} | java | public List<DeepTokenRange> getRanges() {
try {
List<TokenRange> tokenRanges;
ThriftClient client = ThriftClient.build(host, rpcPort);
try {
tokenRanges = client.describe_local_ring(keyspace);
} catch (TApplicationException e) {
if (e.getType() == TApplicationException.UNKNOWN_METHOD) {
tokenRanges = client.describe_ring(keyspace);
} else {
throw new DeepGenericException("Unknown server error", e);
}
}
client.close();
List<DeepTokenRange> deepTokenRanges = new ArrayList<>(tokenRanges.size());
for (TokenRange tokenRange : tokenRanges) {
Comparable start = tokenAsComparable(tokenRange.getStart_token());
Comparable end = tokenAsComparable(tokenRange.getEnd_token());
deepTokenRanges.add(new DeepTokenRange(start, end, tokenRange.getEndpoints()));
}
return deepTokenRanges;
} catch (TException e) {
throw new DeepGenericException("No available replicas for get ring token ranges", e);
}
} | [
"public",
"List",
"<",
"DeepTokenRange",
">",
"getRanges",
"(",
")",
"{",
"try",
"{",
"List",
"<",
"TokenRange",
">",
"tokenRanges",
";",
"ThriftClient",
"client",
"=",
"ThriftClient",
".",
"build",
"(",
"host",
",",
"rpcPort",
")",
";",
"try",
"{",
"tokenRanges",
"=",
"client",
".",
"describe_local_ring",
"(",
"keyspace",
")",
";",
"}",
"catch",
"(",
"TApplicationException",
"e",
")",
"{",
"if",
"(",
"e",
".",
"getType",
"(",
")",
"==",
"TApplicationException",
".",
"UNKNOWN_METHOD",
")",
"{",
"tokenRanges",
"=",
"client",
".",
"describe_ring",
"(",
"keyspace",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"DeepGenericException",
"(",
"\"Unknown server error\"",
",",
"e",
")",
";",
"}",
"}",
"client",
".",
"close",
"(",
")",
";",
"List",
"<",
"DeepTokenRange",
">",
"deepTokenRanges",
"=",
"new",
"ArrayList",
"<>",
"(",
"tokenRanges",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"TokenRange",
"tokenRange",
":",
"tokenRanges",
")",
"{",
"Comparable",
"start",
"=",
"tokenAsComparable",
"(",
"tokenRange",
".",
"getStart_token",
"(",
")",
")",
";",
"Comparable",
"end",
"=",
"tokenAsComparable",
"(",
"tokenRange",
".",
"getEnd_token",
"(",
")",
")",
";",
"deepTokenRanges",
".",
"add",
"(",
"new",
"DeepTokenRange",
"(",
"start",
",",
"end",
",",
"tokenRange",
".",
"getEndpoints",
"(",
")",
")",
")",
";",
"}",
"return",
"deepTokenRanges",
";",
"}",
"catch",
"(",
"TException",
"e",
")",
"{",
"throw",
"new",
"DeepGenericException",
"(",
"\"No available replicas for get ring token ranges\"",
",",
"e",
")",
";",
"}",
"}"
] | Returns the token ranges of the Cassandra ring that will be mapped to Spark partitions.
The returned ranges are the Cassandra's physical ones, without any splitting.
@return the list of Cassandra ring token ranges. | [
"Returns",
"the",
"token",
"ranges",
"of",
"the",
"Cassandra",
"ring",
"that",
"will",
"be",
"mapped",
"to",
"Spark",
"partitions",
".",
"The",
"returned",
"ranges",
"are",
"the",
"Cassandra",
"s",
"physical",
"ones",
"without",
"any",
"splitting",
"."
] | train | https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-cassandra/src/main/java/com/stratio/deep/cassandra/thrift/ThriftRangeUtils.java#L125-L152 |
jamesagnew/hapi-fhir | hapi-fhir-utilities/src/main/java/org/hl7/fhir/utilities/IniFile.java | IniFile.getIntegerProperty | public Integer getIntegerProperty(String pstrSection, String pstrProp) {
"""
Returns the specified integer property from the specified section.
@param pstrSection the INI section name.
@param pstrProp the property to be retrieved.
@return the integer property value.
"""
Integer intRet = null;
String strVal = null;
INIProperty objProp = null;
INISection objSec = null;
objSec = (INISection) this.mhmapSections.get(pstrSection);
if (objSec != null)
{
objProp = objSec.getProperty(pstrProp);
try
{
if (objProp != null)
{
strVal = objProp.getPropValue();
if (strVal != null) intRet = new Integer(strVal);
}
}
catch (NumberFormatException NFExIgnore)
{
}
finally
{
if (objProp != null) objProp = null;
}
objSec = null;
}
return intRet;
} | java | public Integer getIntegerProperty(String pstrSection, String pstrProp)
{
Integer intRet = null;
String strVal = null;
INIProperty objProp = null;
INISection objSec = null;
objSec = (INISection) this.mhmapSections.get(pstrSection);
if (objSec != null)
{
objProp = objSec.getProperty(pstrProp);
try
{
if (objProp != null)
{
strVal = objProp.getPropValue();
if (strVal != null) intRet = new Integer(strVal);
}
}
catch (NumberFormatException NFExIgnore)
{
}
finally
{
if (objProp != null) objProp = null;
}
objSec = null;
}
return intRet;
} | [
"public",
"Integer",
"getIntegerProperty",
"(",
"String",
"pstrSection",
",",
"String",
"pstrProp",
")",
"{",
"Integer",
"intRet",
"=",
"null",
";",
"String",
"strVal",
"=",
"null",
";",
"INIProperty",
"objProp",
"=",
"null",
";",
"INISection",
"objSec",
"=",
"null",
";",
"objSec",
"=",
"(",
"INISection",
")",
"this",
".",
"mhmapSections",
".",
"get",
"(",
"pstrSection",
")",
";",
"if",
"(",
"objSec",
"!=",
"null",
")",
"{",
"objProp",
"=",
"objSec",
".",
"getProperty",
"(",
"pstrProp",
")",
";",
"try",
"{",
"if",
"(",
"objProp",
"!=",
"null",
")",
"{",
"strVal",
"=",
"objProp",
".",
"getPropValue",
"(",
")",
";",
"if",
"(",
"strVal",
"!=",
"null",
")",
"intRet",
"=",
"new",
"Integer",
"(",
"strVal",
")",
";",
"}",
"}",
"catch",
"(",
"NumberFormatException",
"NFExIgnore",
")",
"{",
"}",
"finally",
"{",
"if",
"(",
"objProp",
"!=",
"null",
")",
"objProp",
"=",
"null",
";",
"}",
"objSec",
"=",
"null",
";",
"}",
"return",
"intRet",
";",
"}"
] | Returns the specified integer property from the specified section.
@param pstrSection the INI section name.
@param pstrProp the property to be retrieved.
@return the integer property value. | [
"Returns",
"the",
"specified",
"integer",
"property",
"from",
"the",
"specified",
"section",
"."
] | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-utilities/src/main/java/org/hl7/fhir/utilities/IniFile.java#L180-L209 |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareGraph.java | SquareGraph.acuteAngle | public double acuteAngle( SquareNode a , int sideA , SquareNode b , int sideB ) {
"""
Returns an angle between 0 and PI/4 which describes the difference in slope
between the two sides
"""
Point2D_F64 a0 = a.square.get(sideA);
Point2D_F64 a1 = a.square.get(add(sideA, 1));
Point2D_F64 b0 = b.square.get(sideB);
Point2D_F64 b1 = b.square.get(add(sideB, 1));
vector0.set(a1.x - a0.x, a1.y - a0.y);
vector1.set(b1.x - b0.x, b1.y - b0.y);
double acute = vector0.acute(vector1);
return Math.min(UtilAngle.dist(Math.PI, acute), acute);
} | java | public double acuteAngle( SquareNode a , int sideA , SquareNode b , int sideB ) {
Point2D_F64 a0 = a.square.get(sideA);
Point2D_F64 a1 = a.square.get(add(sideA, 1));
Point2D_F64 b0 = b.square.get(sideB);
Point2D_F64 b1 = b.square.get(add(sideB, 1));
vector0.set(a1.x - a0.x, a1.y - a0.y);
vector1.set(b1.x - b0.x, b1.y - b0.y);
double acute = vector0.acute(vector1);
return Math.min(UtilAngle.dist(Math.PI, acute), acute);
} | [
"public",
"double",
"acuteAngle",
"(",
"SquareNode",
"a",
",",
"int",
"sideA",
",",
"SquareNode",
"b",
",",
"int",
"sideB",
")",
"{",
"Point2D_F64",
"a0",
"=",
"a",
".",
"square",
".",
"get",
"(",
"sideA",
")",
";",
"Point2D_F64",
"a1",
"=",
"a",
".",
"square",
".",
"get",
"(",
"add",
"(",
"sideA",
",",
"1",
")",
")",
";",
"Point2D_F64",
"b0",
"=",
"b",
".",
"square",
".",
"get",
"(",
"sideB",
")",
";",
"Point2D_F64",
"b1",
"=",
"b",
".",
"square",
".",
"get",
"(",
"add",
"(",
"sideB",
",",
"1",
")",
")",
";",
"vector0",
".",
"set",
"(",
"a1",
".",
"x",
"-",
"a0",
".",
"x",
",",
"a1",
".",
"y",
"-",
"a0",
".",
"y",
")",
";",
"vector1",
".",
"set",
"(",
"b1",
".",
"x",
"-",
"b0",
".",
"x",
",",
"b1",
".",
"y",
"-",
"b0",
".",
"y",
")",
";",
"double",
"acute",
"=",
"vector0",
".",
"acute",
"(",
"vector1",
")",
";",
"return",
"Math",
".",
"min",
"(",
"UtilAngle",
".",
"dist",
"(",
"Math",
".",
"PI",
",",
"acute",
")",
",",
"acute",
")",
";",
"}"
] | Returns an angle between 0 and PI/4 which describes the difference in slope
between the two sides | [
"Returns",
"an",
"angle",
"between",
"0",
"and",
"PI",
"/",
"4",
"which",
"describes",
"the",
"difference",
"in",
"slope",
"between",
"the",
"two",
"sides"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareGraph.java#L166-L178 |
rythmengine/rythmengine | src/main/java/org/rythmengine/toString/ToStringOption.java | ToStringOption.setAppendTransient | public ToStringOption setAppendTransient(boolean appendTransient) {
"""
Return a <code>ToStringOption</code> instance with {@link #appendTransient} option set.
if the current instance is not {@link #DEFAULT_OPTION default instance} then set
on the current instance and return the current instance. Otherwise, clone the default
instance and set on the clone and return the clone
@param appendTransient
@return this option instance or clone if this is the {@link #DEFAULT_OPTION}
"""
ToStringOption op = this;
if (this == DEFAULT_OPTION) {
op = new ToStringOption(this.appendStatic, this.appendTransient);
}
op.appendTransient = appendTransient;
return op;
} | java | public ToStringOption setAppendTransient(boolean appendTransient) {
ToStringOption op = this;
if (this == DEFAULT_OPTION) {
op = new ToStringOption(this.appendStatic, this.appendTransient);
}
op.appendTransient = appendTransient;
return op;
} | [
"public",
"ToStringOption",
"setAppendTransient",
"(",
"boolean",
"appendTransient",
")",
"{",
"ToStringOption",
"op",
"=",
"this",
";",
"if",
"(",
"this",
"==",
"DEFAULT_OPTION",
")",
"{",
"op",
"=",
"new",
"ToStringOption",
"(",
"this",
".",
"appendStatic",
",",
"this",
".",
"appendTransient",
")",
";",
"}",
"op",
".",
"appendTransient",
"=",
"appendTransient",
";",
"return",
"op",
";",
"}"
] | Return a <code>ToStringOption</code> instance with {@link #appendTransient} option set.
if the current instance is not {@link #DEFAULT_OPTION default instance} then set
on the current instance and return the current instance. Otherwise, clone the default
instance and set on the clone and return the clone
@param appendTransient
@return this option instance or clone if this is the {@link #DEFAULT_OPTION} | [
"Return",
"a",
"<code",
">",
"ToStringOption<",
"/",
"code",
">",
"instance",
"with",
"{",
"@link",
"#appendTransient",
"}",
"option",
"set",
".",
"if",
"the",
"current",
"instance",
"is",
"not",
"{",
"@link",
"#DEFAULT_OPTION",
"default",
"instance",
"}",
"then",
"set",
"on",
"the",
"current",
"instance",
"and",
"return",
"the",
"current",
"instance",
".",
"Otherwise",
"clone",
"the",
"default",
"instance",
"and",
"set",
"on",
"the",
"clone",
"and",
"return",
"the",
"clone"
] | train | https://github.com/rythmengine/rythmengine/blob/064b565f08d9da07378bf77a9dd856ea5831cc92/src/main/java/org/rythmengine/toString/ToStringOption.java#L89-L96 |
lessthanoptimal/ejml | main/ejml-core/src/org/ejml/ops/ComplexMath_F64.java | ComplexMath_F64.minus | public static void minus(Complex_F64 a , Complex_F64 b , Complex_F64 result ) {
"""
<p>
Subtraction: result = a - b
</p>
@param a Complex number. Not modified.
@param b Complex number. Not modified.
@param result Storage for output
"""
result.real = a.real - b.real;
result.imaginary = a.imaginary - b.imaginary;
} | java | public static void minus(Complex_F64 a , Complex_F64 b , Complex_F64 result ) {
result.real = a.real - b.real;
result.imaginary = a.imaginary - b.imaginary;
} | [
"public",
"static",
"void",
"minus",
"(",
"Complex_F64",
"a",
",",
"Complex_F64",
"b",
",",
"Complex_F64",
"result",
")",
"{",
"result",
".",
"real",
"=",
"a",
".",
"real",
"-",
"b",
".",
"real",
";",
"result",
".",
"imaginary",
"=",
"a",
".",
"imaginary",
"-",
"b",
".",
"imaginary",
";",
"}"
] | <p>
Subtraction: result = a - b
</p>
@param a Complex number. Not modified.
@param b Complex number. Not modified.
@param result Storage for output | [
"<p",
">",
"Subtraction",
":",
"result",
"=",
"a",
"-",
"b",
"<",
"/",
"p",
">"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-core/src/org/ejml/ops/ComplexMath_F64.java#L66-L69 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/util/selenium/SeleniumHelper.java | SeleniumHelper.dragAndDrop | public void dragAndDrop(WebElement source, WebElement target) {
"""
Simulates a drag from source element and drop to target element
@param source element to start the drag
@param target element to end the drag
"""
getActions().dragAndDrop(source, target).perform();
} | java | public void dragAndDrop(WebElement source, WebElement target) {
getActions().dragAndDrop(source, target).perform();
} | [
"public",
"void",
"dragAndDrop",
"(",
"WebElement",
"source",
",",
"WebElement",
"target",
")",
"{",
"getActions",
"(",
")",
".",
"dragAndDrop",
"(",
"source",
",",
"target",
")",
".",
"perform",
"(",
")",
";",
"}"
] | Simulates a drag from source element and drop to target element
@param source element to start the drag
@param target element to end the drag | [
"Simulates",
"a",
"drag",
"from",
"source",
"element",
"and",
"drop",
"to",
"target",
"element"
] | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/selenium/SeleniumHelper.java#L582-L584 |
lessthanoptimal/ejml | main/ejml-dsparse/src/org/ejml/sparse/csc/decomposition/qr/QrHelperFunctions_DSCC.java | QrHelperFunctions_DSCC.computeHouseholder | public static double computeHouseholder(double []x , int xStart , int xEnd , double max , DScalar gamma ) {
"""
Creates a householder reflection.
(I-gamma*v*v')*x = tau*e1
<p>NOTE: Same as cs_house in csparse</p>
@param x (Input) Vector x (Output) Vector v. Modified.
@param xStart First index in X that is to be processed
@param xEnd Last + 1 index in x that is to be processed.
@param gamma (Output) Storage for computed gamma
@return variable tau
"""
double tau = 0;
for (int i = xStart; i < xEnd ; i++) {
double val = x[i] /= max;
tau += val*val;
}
tau = Math.sqrt(tau);
if( x[xStart] < 0 ) {
tau = -tau;
}
double u_0 = x[xStart] + tau;
gamma.value = u_0/tau;
x[xStart] = 1;
for (int i = xStart+1; i < xEnd ; i++) {
x[i] /= u_0;
}
return -tau*max;
} | java | public static double computeHouseholder(double []x , int xStart , int xEnd , double max , DScalar gamma ) {
double tau = 0;
for (int i = xStart; i < xEnd ; i++) {
double val = x[i] /= max;
tau += val*val;
}
tau = Math.sqrt(tau);
if( x[xStart] < 0 ) {
tau = -tau;
}
double u_0 = x[xStart] + tau;
gamma.value = u_0/tau;
x[xStart] = 1;
for (int i = xStart+1; i < xEnd ; i++) {
x[i] /= u_0;
}
return -tau*max;
} | [
"public",
"static",
"double",
"computeHouseholder",
"(",
"double",
"[",
"]",
"x",
",",
"int",
"xStart",
",",
"int",
"xEnd",
",",
"double",
"max",
",",
"DScalar",
"gamma",
")",
"{",
"double",
"tau",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"xStart",
";",
"i",
"<",
"xEnd",
";",
"i",
"++",
")",
"{",
"double",
"val",
"=",
"x",
"[",
"i",
"]",
"/=",
"max",
";",
"tau",
"+=",
"val",
"*",
"val",
";",
"}",
"tau",
"=",
"Math",
".",
"sqrt",
"(",
"tau",
")",
";",
"if",
"(",
"x",
"[",
"xStart",
"]",
"<",
"0",
")",
"{",
"tau",
"=",
"-",
"tau",
";",
"}",
"double",
"u_0",
"=",
"x",
"[",
"xStart",
"]",
"+",
"tau",
";",
"gamma",
".",
"value",
"=",
"u_0",
"/",
"tau",
";",
"x",
"[",
"xStart",
"]",
"=",
"1",
";",
"for",
"(",
"int",
"i",
"=",
"xStart",
"+",
"1",
";",
"i",
"<",
"xEnd",
";",
"i",
"++",
")",
"{",
"x",
"[",
"i",
"]",
"/=",
"u_0",
";",
"}",
"return",
"-",
"tau",
"*",
"max",
";",
"}"
] | Creates a householder reflection.
(I-gamma*v*v')*x = tau*e1
<p>NOTE: Same as cs_house in csparse</p>
@param x (Input) Vector x (Output) Vector v. Modified.
@param xStart First index in X that is to be processed
@param xEnd Last + 1 index in x that is to be processed.
@param gamma (Output) Storage for computed gamma
@return variable tau | [
"Creates",
"a",
"householder",
"reflection",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/decomposition/qr/QrHelperFunctions_DSCC.java#L110-L128 |
jtrfp/javamod | src/main/java/de/quippy/javamod/multimedia/mp3/id3/ID3v1Tag.java | ID3v1Tag.readTag | private void readTag(RandomAccessInputStream raf) throws FileNotFoundException, IOException {
"""
Reads the data from the id3v1 tag
@exception FileNotFoundException if an error occurs
@exception IOException if an error occurs
"""
raf.seek(raf.length() - TAG_SIZE);
byte[] buf = new byte[TAG_SIZE];
raf.read(buf, 0, TAG_SIZE);
String tag = new String(buf, 0, TAG_SIZE, ENC_TYPE);
int start = TAG_START.length();
title = tag.substring(start, start += TITLE_SIZE);
artist = tag.substring(start, start += ARTIST_SIZE);
album = tag.substring(start, start += ALBUM_SIZE);
year = tag.substring(start, start += YEAR_SIZE);
comment = tag.substring(start, start += COMMENT_SIZE);
track = (int) tag.charAt(TRACK_LOCATION);
genre = (int) tag.charAt(GENRE_LOCATION);
} | java | private void readTag(RandomAccessInputStream raf) throws FileNotFoundException, IOException
{
raf.seek(raf.length() - TAG_SIZE);
byte[] buf = new byte[TAG_SIZE];
raf.read(buf, 0, TAG_SIZE);
String tag = new String(buf, 0, TAG_SIZE, ENC_TYPE);
int start = TAG_START.length();
title = tag.substring(start, start += TITLE_SIZE);
artist = tag.substring(start, start += ARTIST_SIZE);
album = tag.substring(start, start += ALBUM_SIZE);
year = tag.substring(start, start += YEAR_SIZE);
comment = tag.substring(start, start += COMMENT_SIZE);
track = (int) tag.charAt(TRACK_LOCATION);
genre = (int) tag.charAt(GENRE_LOCATION);
} | [
"private",
"void",
"readTag",
"(",
"RandomAccessInputStream",
"raf",
")",
"throws",
"FileNotFoundException",
",",
"IOException",
"{",
"raf",
".",
"seek",
"(",
"raf",
".",
"length",
"(",
")",
"-",
"TAG_SIZE",
")",
";",
"byte",
"[",
"]",
"buf",
"=",
"new",
"byte",
"[",
"TAG_SIZE",
"]",
";",
"raf",
".",
"read",
"(",
"buf",
",",
"0",
",",
"TAG_SIZE",
")",
";",
"String",
"tag",
"=",
"new",
"String",
"(",
"buf",
",",
"0",
",",
"TAG_SIZE",
",",
"ENC_TYPE",
")",
";",
"int",
"start",
"=",
"TAG_START",
".",
"length",
"(",
")",
";",
"title",
"=",
"tag",
".",
"substring",
"(",
"start",
",",
"start",
"+=",
"TITLE_SIZE",
")",
";",
"artist",
"=",
"tag",
".",
"substring",
"(",
"start",
",",
"start",
"+=",
"ARTIST_SIZE",
")",
";",
"album",
"=",
"tag",
".",
"substring",
"(",
"start",
",",
"start",
"+=",
"ALBUM_SIZE",
")",
";",
"year",
"=",
"tag",
".",
"substring",
"(",
"start",
",",
"start",
"+=",
"YEAR_SIZE",
")",
";",
"comment",
"=",
"tag",
".",
"substring",
"(",
"start",
",",
"start",
"+=",
"COMMENT_SIZE",
")",
";",
"track",
"=",
"(",
"int",
")",
"tag",
".",
"charAt",
"(",
"TRACK_LOCATION",
")",
";",
"genre",
"=",
"(",
"int",
")",
"tag",
".",
"charAt",
"(",
"GENRE_LOCATION",
")",
";",
"}"
] | Reads the data from the id3v1 tag
@exception FileNotFoundException if an error occurs
@exception IOException if an error occurs | [
"Reads",
"the",
"data",
"from",
"the",
"id3v1",
"tag"
] | train | https://github.com/jtrfp/javamod/blob/cda4fe943a589dc49415f4413453e2eece72076a/src/main/java/de/quippy/javamod/multimedia/mp3/id3/ID3v1Tag.java#L136-L150 |
snowflakedb/snowflake-jdbc | src/main/java/net/snowflake/client/jdbc/cloud/storage/SnowflakeAzureClient.java | SnowflakeAzureClient.listObjects | @Override
public StorageObjectSummaryCollection listObjects(String remoteStorageLocation, String prefix)
throws StorageProviderException {
"""
For a set of remote storage objects under a remote location and a given prefix/path
returns their properties wrapped in ObjectSummary objects
@param remoteStorageLocation location, i.e. container for Azure
@param prefix the prefix/path to list under
@return a collection of storage summary objects
@throws StorageProviderException Azure storage exception
"""
StorageObjectSummaryCollection storageObjectSummaries;
try
{
CloudBlobContainer container = azStorageClient.getContainerReference(remoteStorageLocation);
Iterable<ListBlobItem> listBlobItemIterable = container.listBlobs(
prefix, // List the BLOBs under this prefix
true // List the BLOBs as a flat list, i.e. do not list directories
);
storageObjectSummaries = new StorageObjectSummaryCollection(listBlobItemIterable);
}
catch (URISyntaxException | StorageException ex)
{
logger.debug("Failed to list objects: {}", ex);
throw new StorageProviderException(ex);
}
return storageObjectSummaries;
} | java | @Override
public StorageObjectSummaryCollection listObjects(String remoteStorageLocation, String prefix)
throws StorageProviderException
{
StorageObjectSummaryCollection storageObjectSummaries;
try
{
CloudBlobContainer container = azStorageClient.getContainerReference(remoteStorageLocation);
Iterable<ListBlobItem> listBlobItemIterable = container.listBlobs(
prefix, // List the BLOBs under this prefix
true // List the BLOBs as a flat list, i.e. do not list directories
);
storageObjectSummaries = new StorageObjectSummaryCollection(listBlobItemIterable);
}
catch (URISyntaxException | StorageException ex)
{
logger.debug("Failed to list objects: {}", ex);
throw new StorageProviderException(ex);
}
return storageObjectSummaries;
} | [
"@",
"Override",
"public",
"StorageObjectSummaryCollection",
"listObjects",
"(",
"String",
"remoteStorageLocation",
",",
"String",
"prefix",
")",
"throws",
"StorageProviderException",
"{",
"StorageObjectSummaryCollection",
"storageObjectSummaries",
";",
"try",
"{",
"CloudBlobContainer",
"container",
"=",
"azStorageClient",
".",
"getContainerReference",
"(",
"remoteStorageLocation",
")",
";",
"Iterable",
"<",
"ListBlobItem",
">",
"listBlobItemIterable",
"=",
"container",
".",
"listBlobs",
"(",
"prefix",
",",
"// List the BLOBs under this prefix",
"true",
"// List the BLOBs as a flat list, i.e. do not list directories",
")",
";",
"storageObjectSummaries",
"=",
"new",
"StorageObjectSummaryCollection",
"(",
"listBlobItemIterable",
")",
";",
"}",
"catch",
"(",
"URISyntaxException",
"|",
"StorageException",
"ex",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Failed to list objects: {}\"",
",",
"ex",
")",
";",
"throw",
"new",
"StorageProviderException",
"(",
"ex",
")",
";",
"}",
"return",
"storageObjectSummaries",
";",
"}"
] | For a set of remote storage objects under a remote location and a given prefix/path
returns their properties wrapped in ObjectSummary objects
@param remoteStorageLocation location, i.e. container for Azure
@param prefix the prefix/path to list under
@return a collection of storage summary objects
@throws StorageProviderException Azure storage exception | [
"For",
"a",
"set",
"of",
"remote",
"storage",
"objects",
"under",
"a",
"remote",
"location",
"and",
"a",
"given",
"prefix",
"/",
"path",
"returns",
"their",
"properties",
"wrapped",
"in",
"ObjectSummary",
"objects"
] | train | https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/cloud/storage/SnowflakeAzureClient.java#L228-L249 |
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/models/BoxFile.java | BoxFile.createFromIdAndName | public static BoxFile createFromIdAndName(String fileId, String name) {
"""
A convenience method to create an empty file with just the id and type fields set. This allows
the ability to interact with the content sdk in a more descriptive and type safe manner
@param fileId the id of file to create
@param name the name of the file to create
@return an empty BoxFile object that only contains id and type information
"""
JsonObject object = new JsonObject();
object.add(BoxItem.FIELD_ID, fileId);
object.add(BoxItem.FIELD_TYPE, BoxFile.TYPE);
if (!TextUtils.isEmpty(name)) {
object.add(BoxItem.FIELD_NAME, name);
}
return new BoxFile(object);
} | java | public static BoxFile createFromIdAndName(String fileId, String name) {
JsonObject object = new JsonObject();
object.add(BoxItem.FIELD_ID, fileId);
object.add(BoxItem.FIELD_TYPE, BoxFile.TYPE);
if (!TextUtils.isEmpty(name)) {
object.add(BoxItem.FIELD_NAME, name);
}
return new BoxFile(object);
} | [
"public",
"static",
"BoxFile",
"createFromIdAndName",
"(",
"String",
"fileId",
",",
"String",
"name",
")",
"{",
"JsonObject",
"object",
"=",
"new",
"JsonObject",
"(",
")",
";",
"object",
".",
"add",
"(",
"BoxItem",
".",
"FIELD_ID",
",",
"fileId",
")",
";",
"object",
".",
"add",
"(",
"BoxItem",
".",
"FIELD_TYPE",
",",
"BoxFile",
".",
"TYPE",
")",
";",
"if",
"(",
"!",
"TextUtils",
".",
"isEmpty",
"(",
"name",
")",
")",
"{",
"object",
".",
"add",
"(",
"BoxItem",
".",
"FIELD_NAME",
",",
"name",
")",
";",
"}",
"return",
"new",
"BoxFile",
"(",
"object",
")",
";",
"}"
] | A convenience method to create an empty file with just the id and type fields set. This allows
the ability to interact with the content sdk in a more descriptive and type safe manner
@param fileId the id of file to create
@param name the name of the file to create
@return an empty BoxFile object that only contains id and type information | [
"A",
"convenience",
"method",
"to",
"create",
"an",
"empty",
"file",
"with",
"just",
"the",
"id",
"and",
"type",
"fields",
"set",
".",
"This",
"allows",
"the",
"ability",
"to",
"interact",
"with",
"the",
"content",
"sdk",
"in",
"a",
"more",
"descriptive",
"and",
"type",
"safe",
"manner"
] | train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/models/BoxFile.java#L103-L111 |
pravega/pravega | shared/protocol/src/main/java/io/pravega/shared/segment/StreamSegmentNameUtils.java | StreamSegmentNameUtils.getQualifiedTableName | public static String getQualifiedTableName(String scope, String... tokens) {
"""
Method to generate Fully Qualified table name using scope, and other tokens to be used to compose the table name.
The composed name has following format \<scope\>/_tables/\<tokens[0]\>/\<tokens[1]\>...
@param scope scope in which table segment to create
@param tokens tokens used for composing table segment name
@return Fully qualified table segment name composed of supplied tokens.
"""
Preconditions.checkArgument(tokens != null && tokens.length > 0);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%s/%s", scope, TABLES));
for (String token : tokens) {
sb.append('/');
sb.append(token);
}
return sb.toString();
} | java | public static String getQualifiedTableName(String scope, String... tokens) {
Preconditions.checkArgument(tokens != null && tokens.length > 0);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%s/%s", scope, TABLES));
for (String token : tokens) {
sb.append('/');
sb.append(token);
}
return sb.toString();
} | [
"public",
"static",
"String",
"getQualifiedTableName",
"(",
"String",
"scope",
",",
"String",
"...",
"tokens",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"tokens",
"!=",
"null",
"&&",
"tokens",
".",
"length",
">",
"0",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"String",
".",
"format",
"(",
"\"%s/%s\"",
",",
"scope",
",",
"TABLES",
")",
")",
";",
"for",
"(",
"String",
"token",
":",
"tokens",
")",
"{",
"sb",
".",
"append",
"(",
"'",
"'",
")",
";",
"sb",
".",
"append",
"(",
"token",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | Method to generate Fully Qualified table name using scope, and other tokens to be used to compose the table name.
The composed name has following format \<scope\>/_tables/\<tokens[0]\>/\<tokens[1]\>...
@param scope scope in which table segment to create
@param tokens tokens used for composing table segment name
@return Fully qualified table segment name composed of supplied tokens. | [
"Method",
"to",
"generate",
"Fully",
"Qualified",
"table",
"name",
"using",
"scope",
"and",
"other",
"tokens",
"to",
"be",
"used",
"to",
"compose",
"the",
"table",
"name",
".",
"The",
"composed",
"name",
"has",
"following",
"format",
"\\",
"<scope",
"\\",
">",
"/",
"_tables",
"/",
"\\",
"<tokens",
"[",
"0",
"]",
"\\",
">",
"/",
"\\",
"<tokens",
"[",
"1",
"]",
"\\",
">",
"..."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/shared/protocol/src/main/java/io/pravega/shared/segment/StreamSegmentNameUtils.java#L322-L331 |
alkacon/opencms-core | src/org/opencms/jsp/CmsJspTagDecorate.java | CmsJspTagDecorate.decorateTagAction | public String decorateTagAction(String content, String configFile, String locale, ServletRequest req) {
"""
Internal action method.<p>
DEcorates a HTMl content block.<p>
@param content the content to be decorated
@param configFile the config file
@param locale the locale to use for decoration or NOLOCALE if not locale should be used
@param req the current request
@return the decorated content
"""
try {
Locale loc = null;
CmsFlexController controller = CmsFlexController.getController(req);
if (CmsStringUtil.isEmpty(locale)) {
loc = controller.getCmsObject().getRequestContext().getLocale();
} else {
loc = CmsLocaleManager.getLocale(locale);
}
// read the decorator configurator class
CmsProperty decoratorClass = controller.getCmsObject().readPropertyObject(
configFile,
PROPERTY_CATEGORY,
false);
String decoratorClassName = decoratorClass.getValue();
if (CmsStringUtil.isEmpty(decoratorClassName)) {
decoratorClassName = DEFAULT_DECORATOR_CONFIGURATION;
}
String encoding = controller.getCmsObject().getRequestContext().getEncoding();
// use the correct decorator configurator and initialize it
I_CmsDecoratorConfiguration config = (I_CmsDecoratorConfiguration)Class.forName(
decoratorClassName).newInstance();
config.init(controller.getCmsObject(), configFile, loc);
CmsHtmlDecorator decorator = new CmsHtmlDecorator(controller.getCmsObject(), config);
decorator.setNoAutoCloseTags(m_noAutoCloseTags);
return decorator.doDecoration(content, encoding);
} catch (Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error(Messages.get().getBundle().key(Messages.ERR_PROCESS_TAG_1, "decoration"), e);
}
return content;
}
} | java | public String decorateTagAction(String content, String configFile, String locale, ServletRequest req) {
try {
Locale loc = null;
CmsFlexController controller = CmsFlexController.getController(req);
if (CmsStringUtil.isEmpty(locale)) {
loc = controller.getCmsObject().getRequestContext().getLocale();
} else {
loc = CmsLocaleManager.getLocale(locale);
}
// read the decorator configurator class
CmsProperty decoratorClass = controller.getCmsObject().readPropertyObject(
configFile,
PROPERTY_CATEGORY,
false);
String decoratorClassName = decoratorClass.getValue();
if (CmsStringUtil.isEmpty(decoratorClassName)) {
decoratorClassName = DEFAULT_DECORATOR_CONFIGURATION;
}
String encoding = controller.getCmsObject().getRequestContext().getEncoding();
// use the correct decorator configurator and initialize it
I_CmsDecoratorConfiguration config = (I_CmsDecoratorConfiguration)Class.forName(
decoratorClassName).newInstance();
config.init(controller.getCmsObject(), configFile, loc);
CmsHtmlDecorator decorator = new CmsHtmlDecorator(controller.getCmsObject(), config);
decorator.setNoAutoCloseTags(m_noAutoCloseTags);
return decorator.doDecoration(content, encoding);
} catch (Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error(Messages.get().getBundle().key(Messages.ERR_PROCESS_TAG_1, "decoration"), e);
}
return content;
}
} | [
"public",
"String",
"decorateTagAction",
"(",
"String",
"content",
",",
"String",
"configFile",
",",
"String",
"locale",
",",
"ServletRequest",
"req",
")",
"{",
"try",
"{",
"Locale",
"loc",
"=",
"null",
";",
"CmsFlexController",
"controller",
"=",
"CmsFlexController",
".",
"getController",
"(",
"req",
")",
";",
"if",
"(",
"CmsStringUtil",
".",
"isEmpty",
"(",
"locale",
")",
")",
"{",
"loc",
"=",
"controller",
".",
"getCmsObject",
"(",
")",
".",
"getRequestContext",
"(",
")",
".",
"getLocale",
"(",
")",
";",
"}",
"else",
"{",
"loc",
"=",
"CmsLocaleManager",
".",
"getLocale",
"(",
"locale",
")",
";",
"}",
"// read the decorator configurator class",
"CmsProperty",
"decoratorClass",
"=",
"controller",
".",
"getCmsObject",
"(",
")",
".",
"readPropertyObject",
"(",
"configFile",
",",
"PROPERTY_CATEGORY",
",",
"false",
")",
";",
"String",
"decoratorClassName",
"=",
"decoratorClass",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"CmsStringUtil",
".",
"isEmpty",
"(",
"decoratorClassName",
")",
")",
"{",
"decoratorClassName",
"=",
"DEFAULT_DECORATOR_CONFIGURATION",
";",
"}",
"String",
"encoding",
"=",
"controller",
".",
"getCmsObject",
"(",
")",
".",
"getRequestContext",
"(",
")",
".",
"getEncoding",
"(",
")",
";",
"// use the correct decorator configurator and initialize it",
"I_CmsDecoratorConfiguration",
"config",
"=",
"(",
"I_CmsDecoratorConfiguration",
")",
"Class",
".",
"forName",
"(",
"decoratorClassName",
")",
".",
"newInstance",
"(",
")",
";",
"config",
".",
"init",
"(",
"controller",
".",
"getCmsObject",
"(",
")",
",",
"configFile",
",",
"loc",
")",
";",
"CmsHtmlDecorator",
"decorator",
"=",
"new",
"CmsHtmlDecorator",
"(",
"controller",
".",
"getCmsObject",
"(",
")",
",",
"config",
")",
";",
"decorator",
".",
"setNoAutoCloseTags",
"(",
"m_noAutoCloseTags",
")",
";",
"return",
"decorator",
".",
"doDecoration",
"(",
"content",
",",
"encoding",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"if",
"(",
"LOG",
".",
"isErrorEnabled",
"(",
")",
")",
"{",
"LOG",
".",
"error",
"(",
"Messages",
".",
"get",
"(",
")",
".",
"getBundle",
"(",
")",
".",
"key",
"(",
"Messages",
".",
"ERR_PROCESS_TAG_1",
",",
"\"decoration\"",
")",
",",
"e",
")",
";",
"}",
"return",
"content",
";",
"}",
"}"
] | Internal action method.<p>
DEcorates a HTMl content block.<p>
@param content the content to be decorated
@param configFile the config file
@param locale the locale to use for decoration or NOLOCALE if not locale should be used
@param req the current request
@return the decorated content | [
"Internal",
"action",
"method",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspTagDecorate.java#L92-L129 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/util/NDArrayMath.java | NDArrayMath.sliceOffsetForTensor | public static long sliceOffsetForTensor(int index, INDArray arr, int[] tensorShape) {
"""
calculates the offset for a tensor
@param index
@param arr
@param tensorShape
@return
"""
long tensorLength = ArrayUtil.prodLong(tensorShape);
long lengthPerSlice = NDArrayMath.lengthPerSlice(arr);
long offset = index * tensorLength / lengthPerSlice;
return offset;
} | java | public static long sliceOffsetForTensor(int index, INDArray arr, int[] tensorShape) {
long tensorLength = ArrayUtil.prodLong(tensorShape);
long lengthPerSlice = NDArrayMath.lengthPerSlice(arr);
long offset = index * tensorLength / lengthPerSlice;
return offset;
} | [
"public",
"static",
"long",
"sliceOffsetForTensor",
"(",
"int",
"index",
",",
"INDArray",
"arr",
",",
"int",
"[",
"]",
"tensorShape",
")",
"{",
"long",
"tensorLength",
"=",
"ArrayUtil",
".",
"prodLong",
"(",
"tensorShape",
")",
";",
"long",
"lengthPerSlice",
"=",
"NDArrayMath",
".",
"lengthPerSlice",
"(",
"arr",
")",
";",
"long",
"offset",
"=",
"index",
"*",
"tensorLength",
"/",
"lengthPerSlice",
";",
"return",
"offset",
";",
"}"
] | calculates the offset for a tensor
@param index
@param arr
@param tensorShape
@return | [
"calculates",
"the",
"offset",
"for",
"a",
"tensor"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/util/NDArrayMath.java#L160-L165 |
google/truth | extensions/proto/src/main/java/com/google/common/truth/extensions/proto/MultimapWithProtoValuesSubject.java | MultimapWithProtoValuesSubject.ignoringFieldAbsenceOfFieldsForValues | public MultimapWithProtoValuesFluentAssertion<M> ignoringFieldAbsenceOfFieldsForValues(
int firstFieldNumber, int... rest) {
"""
Specifies that the 'has' bit of these explicitly specified top-level field numbers should be
ignored when comparing for equality. Sub-fields must be specified explicitly (via {@link
FieldDescriptor}) if they are to be ignored as well.
<p>Use {@link #ignoringFieldAbsenceForValues()} instead to ignore the 'has' bit for all fields.
@see #ignoringFieldAbsenceForValues() for details
"""
return usingConfig(config.ignoringFieldAbsenceOfFields(asList(firstFieldNumber, rest)));
} | java | public MultimapWithProtoValuesFluentAssertion<M> ignoringFieldAbsenceOfFieldsForValues(
int firstFieldNumber, int... rest) {
return usingConfig(config.ignoringFieldAbsenceOfFields(asList(firstFieldNumber, rest)));
} | [
"public",
"MultimapWithProtoValuesFluentAssertion",
"<",
"M",
">",
"ignoringFieldAbsenceOfFieldsForValues",
"(",
"int",
"firstFieldNumber",
",",
"int",
"...",
"rest",
")",
"{",
"return",
"usingConfig",
"(",
"config",
".",
"ignoringFieldAbsenceOfFields",
"(",
"asList",
"(",
"firstFieldNumber",
",",
"rest",
")",
")",
")",
";",
"}"
] | Specifies that the 'has' bit of these explicitly specified top-level field numbers should be
ignored when comparing for equality. Sub-fields must be specified explicitly (via {@link
FieldDescriptor}) if they are to be ignored as well.
<p>Use {@link #ignoringFieldAbsenceForValues()} instead to ignore the 'has' bit for all fields.
@see #ignoringFieldAbsenceForValues() for details | [
"Specifies",
"that",
"the",
"has",
"bit",
"of",
"these",
"explicitly",
"specified",
"top",
"-",
"level",
"field",
"numbers",
"should",
"be",
"ignored",
"when",
"comparing",
"for",
"equality",
".",
"Sub",
"-",
"fields",
"must",
"be",
"specified",
"explicitly",
"(",
"via",
"{",
"@link",
"FieldDescriptor",
"}",
")",
"if",
"they",
"are",
"to",
"be",
"ignored",
"as",
"well",
"."
] | train | https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/MultimapWithProtoValuesSubject.java#L291-L294 |
enasequence/sequencetools | src/main/java/uk/ac/ebi/embl/api/validation/helper/ByteBufferUtils.java | ByteBufferUtils.lastIndexOf | public static int lastIndexOf(ByteBuffer buffer, byte valueToFind, int startIndex) {
"""
ByteBuffer adaptation of org.apache.commons.lang.ArrayUtils.lastIndexOf method
@param buffer the array to traverse for looking for the object, may be <code>null</code>
@param valueToFind the value to find
@param startIndex the start index (i.e. BB position) to travers backwards from
@return the last index (i.e. BB position) of the value within the array
[between buffer.position() and buffer.limit()]; <code>-1</code> if not found.
"""
assert buffer != null;
if (startIndex < buffer.position())
{
return -1;
}
else if (startIndex >= buffer.limit())
{
startIndex = buffer.limit() - 1;
}
for (int i = startIndex; i >= buffer.position(); i--)
{
if (valueToFind == buffer.get(i))
return i;
}
return -1;
} | java | public static int lastIndexOf(ByteBuffer buffer, byte valueToFind, int startIndex)
{
assert buffer != null;
if (startIndex < buffer.position())
{
return -1;
}
else if (startIndex >= buffer.limit())
{
startIndex = buffer.limit() - 1;
}
for (int i = startIndex; i >= buffer.position(); i--)
{
if (valueToFind == buffer.get(i))
return i;
}
return -1;
} | [
"public",
"static",
"int",
"lastIndexOf",
"(",
"ByteBuffer",
"buffer",
",",
"byte",
"valueToFind",
",",
"int",
"startIndex",
")",
"{",
"assert",
"buffer",
"!=",
"null",
";",
"if",
"(",
"startIndex",
"<",
"buffer",
".",
"position",
"(",
")",
")",
"{",
"return",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"startIndex",
">=",
"buffer",
".",
"limit",
"(",
")",
")",
"{",
"startIndex",
"=",
"buffer",
".",
"limit",
"(",
")",
"-",
"1",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"startIndex",
";",
"i",
">=",
"buffer",
".",
"position",
"(",
")",
";",
"i",
"--",
")",
"{",
"if",
"(",
"valueToFind",
"==",
"buffer",
".",
"get",
"(",
"i",
")",
")",
"return",
"i",
";",
"}",
"return",
"-",
"1",
";",
"}"
] | ByteBuffer adaptation of org.apache.commons.lang.ArrayUtils.lastIndexOf method
@param buffer the array to traverse for looking for the object, may be <code>null</code>
@param valueToFind the value to find
@param startIndex the start index (i.e. BB position) to travers backwards from
@return the last index (i.e. BB position) of the value within the array
[between buffer.position() and buffer.limit()]; <code>-1</code> if not found. | [
"ByteBuffer",
"adaptation",
"of",
"org",
".",
"apache",
".",
"commons",
".",
"lang",
".",
"ArrayUtils",
".",
"lastIndexOf",
"method"
] | train | https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/api/validation/helper/ByteBufferUtils.java#L103-L123 |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.getXteaSignature | public final static void getXteaSignature(byte[] array, int offset, int keyid) {
"""
RTMPE type 8 uses XTEA on the regular signature http://en.wikipedia.org/wiki/XTEA
@param array array to get signature
@param offset offset to start from
@param keyid ID of XTEA key
"""
int num_rounds = 32;
int v0, v1, sum = 0, delta = 0x9E3779B9;
int[] k = XTEA_KEYS[keyid];
v0 = ByteBuffer.wrap(array, offset, 4).getInt();
v1 = ByteBuffer.wrap(array, offset + 4, 4).getInt();
for (int i = 0; i < num_rounds; i++) {
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
sum += delta;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum >> 11) & 3]);
}
ByteBuffer tmp = ByteBuffer.allocate(4);
tmp.putInt(v0);
tmp.flip();
System.arraycopy(tmp.array(), 0, array, offset, 4);
tmp.clear();
tmp.putInt(v1);
tmp.flip();
System.arraycopy(tmp.array(), 0, array, offset + 4, 4);
} | java | public final static void getXteaSignature(byte[] array, int offset, int keyid) {
int num_rounds = 32;
int v0, v1, sum = 0, delta = 0x9E3779B9;
int[] k = XTEA_KEYS[keyid];
v0 = ByteBuffer.wrap(array, offset, 4).getInt();
v1 = ByteBuffer.wrap(array, offset + 4, 4).getInt();
for (int i = 0; i < num_rounds; i++) {
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
sum += delta;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum >> 11) & 3]);
}
ByteBuffer tmp = ByteBuffer.allocate(4);
tmp.putInt(v0);
tmp.flip();
System.arraycopy(tmp.array(), 0, array, offset, 4);
tmp.clear();
tmp.putInt(v1);
tmp.flip();
System.arraycopy(tmp.array(), 0, array, offset + 4, 4);
} | [
"public",
"final",
"static",
"void",
"getXteaSignature",
"(",
"byte",
"[",
"]",
"array",
",",
"int",
"offset",
",",
"int",
"keyid",
")",
"{",
"int",
"num_rounds",
"=",
"32",
";",
"int",
"v0",
",",
"v1",
",",
"sum",
"=",
"0",
",",
"delta",
"=",
"0x9E3779B9",
";",
"int",
"[",
"]",
"k",
"=",
"XTEA_KEYS",
"[",
"keyid",
"]",
";",
"v0",
"=",
"ByteBuffer",
".",
"wrap",
"(",
"array",
",",
"offset",
",",
"4",
")",
".",
"getInt",
"(",
")",
";",
"v1",
"=",
"ByteBuffer",
".",
"wrap",
"(",
"array",
",",
"offset",
"+",
"4",
",",
"4",
")",
".",
"getInt",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"num_rounds",
";",
"i",
"++",
")",
"{",
"v0",
"+=",
"(",
"(",
"(",
"v1",
"<<",
"4",
")",
"^",
"(",
"v1",
">>",
"5",
")",
")",
"+",
"v1",
")",
"^",
"(",
"sum",
"+",
"k",
"[",
"sum",
"&",
"3",
"]",
")",
";",
"sum",
"+=",
"delta",
";",
"v1",
"+=",
"(",
"(",
"(",
"v0",
"<<",
"4",
")",
"^",
"(",
"v0",
">>",
"5",
")",
")",
"+",
"v0",
")",
"^",
"(",
"sum",
"+",
"k",
"[",
"(",
"sum",
">>",
"11",
")",
"&",
"3",
"]",
")",
";",
"}",
"ByteBuffer",
"tmp",
"=",
"ByteBuffer",
".",
"allocate",
"(",
"4",
")",
";",
"tmp",
".",
"putInt",
"(",
"v0",
")",
";",
"tmp",
".",
"flip",
"(",
")",
";",
"System",
".",
"arraycopy",
"(",
"tmp",
".",
"array",
"(",
")",
",",
"0",
",",
"array",
",",
"offset",
",",
"4",
")",
";",
"tmp",
".",
"clear",
"(",
")",
";",
"tmp",
".",
"putInt",
"(",
"v1",
")",
";",
"tmp",
".",
"flip",
"(",
")",
";",
"System",
".",
"arraycopy",
"(",
"tmp",
".",
"array",
"(",
")",
",",
"0",
",",
"array",
",",
"offset",
"+",
"4",
",",
"4",
")",
";",
"}"
] | RTMPE type 8 uses XTEA on the regular signature http://en.wikipedia.org/wiki/XTEA
@param array array to get signature
@param offset offset to start from
@param keyid ID of XTEA key | [
"RTMPE",
"type",
"8",
"uses",
"XTEA",
"on",
"the",
"regular",
"signature",
"http",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"XTEA"
] | train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L554-L573 |
RestComm/sip-servlets | containers/tomcat-7/src/main/java/org/mobicents/servlet/sip/startup/SipNamingContextListener.java | SipNamingContextListener.removeAppNameSubContext | public static void removeAppNameSubContext(Context envCtx, String appName) {
"""
Removes the app name subcontext from the jndi mapping
@param appName sub context Name
"""
if(envCtx != null) {
try {
javax.naming.Context sipContext = (javax.naming.Context)envCtx.lookup(SIP_SUBCONTEXT);
sipContext.destroySubcontext(appName);
} catch (NamingException e) {
logger.error(sm.getString("naming.unbindFailed", e));
}
}
} | java | public static void removeAppNameSubContext(Context envCtx, String appName) {
if(envCtx != null) {
try {
javax.naming.Context sipContext = (javax.naming.Context)envCtx.lookup(SIP_SUBCONTEXT);
sipContext.destroySubcontext(appName);
} catch (NamingException e) {
logger.error(sm.getString("naming.unbindFailed", e));
}
}
} | [
"public",
"static",
"void",
"removeAppNameSubContext",
"(",
"Context",
"envCtx",
",",
"String",
"appName",
")",
"{",
"if",
"(",
"envCtx",
"!=",
"null",
")",
"{",
"try",
"{",
"javax",
".",
"naming",
".",
"Context",
"sipContext",
"=",
"(",
"javax",
".",
"naming",
".",
"Context",
")",
"envCtx",
".",
"lookup",
"(",
"SIP_SUBCONTEXT",
")",
";",
"sipContext",
".",
"destroySubcontext",
"(",
"appName",
")",
";",
"}",
"catch",
"(",
"NamingException",
"e",
")",
"{",
"logger",
".",
"error",
"(",
"sm",
".",
"getString",
"(",
"\"naming.unbindFailed\"",
",",
"e",
")",
")",
";",
"}",
"}",
"}"
] | Removes the app name subcontext from the jndi mapping
@param appName sub context Name | [
"Removes",
"the",
"app",
"name",
"subcontext",
"from",
"the",
"jndi",
"mapping"
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/containers/tomcat-7/src/main/java/org/mobicents/servlet/sip/startup/SipNamingContextListener.java#L198-L207 |
ineunetOS/knife-commons | knife-commons-utils/src/main/java/com/ineunet/knife/util/sql/SqlStrUtils.java | SqlStrUtils.getSelectColumns | public static String[] getSelectColumns(String sql) {
"""
Example:<br>
<code>new String[] {"id", "code", "name"} equals SqlStrUtils.getSelectColumns("select id, code,name from user ")</code>
"""
Asserts.notBlank(sql);
sql = sql.trim();
if (sql.startsWith("select ") || sql.startsWith("SELECT ")) {
sql = sql.substring(7).trim();
int idxFrom = sql.indexOf(" from ");
if (idxFrom == -1)
idxFrom = sql.indexOf(" FROM ");
if (idxFrom == -1)
throw new IllegalArgumentException("Bad sql, no from ");
sql = sql.substring(0, idxFrom).trim();
String[] columns = sql.split(",");
for (int i = 0; i < columns.length; i++) {
columns[i] = columns[i].trim();
}
return columns;
} else {
throw new IllegalArgumentException("Not a select sql");
}
} | java | public static String[] getSelectColumns(String sql) {
Asserts.notBlank(sql);
sql = sql.trim();
if (sql.startsWith("select ") || sql.startsWith("SELECT ")) {
sql = sql.substring(7).trim();
int idxFrom = sql.indexOf(" from ");
if (idxFrom == -1)
idxFrom = sql.indexOf(" FROM ");
if (idxFrom == -1)
throw new IllegalArgumentException("Bad sql, no from ");
sql = sql.substring(0, idxFrom).trim();
String[] columns = sql.split(",");
for (int i = 0; i < columns.length; i++) {
columns[i] = columns[i].trim();
}
return columns;
} else {
throw new IllegalArgumentException("Not a select sql");
}
} | [
"public",
"static",
"String",
"[",
"]",
"getSelectColumns",
"(",
"String",
"sql",
")",
"{",
"Asserts",
".",
"notBlank",
"(",
"sql",
")",
";",
"sql",
"=",
"sql",
".",
"trim",
"(",
")",
";",
"if",
"(",
"sql",
".",
"startsWith",
"(",
"\"select \"",
")",
"||",
"sql",
".",
"startsWith",
"(",
"\"SELECT \"",
")",
")",
"{",
"sql",
"=",
"sql",
".",
"substring",
"(",
"7",
")",
".",
"trim",
"(",
")",
";",
"int",
"idxFrom",
"=",
"sql",
".",
"indexOf",
"(",
"\" from \"",
")",
";",
"if",
"(",
"idxFrom",
"==",
"-",
"1",
")",
"idxFrom",
"=",
"sql",
".",
"indexOf",
"(",
"\" FROM \"",
")",
";",
"if",
"(",
"idxFrom",
"==",
"-",
"1",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Bad sql, no from \"",
")",
";",
"sql",
"=",
"sql",
".",
"substring",
"(",
"0",
",",
"idxFrom",
")",
".",
"trim",
"(",
")",
";",
"String",
"[",
"]",
"columns",
"=",
"sql",
".",
"split",
"(",
"\",\"",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"columns",
".",
"length",
";",
"i",
"++",
")",
"{",
"columns",
"[",
"i",
"]",
"=",
"columns",
"[",
"i",
"]",
".",
"trim",
"(",
")",
";",
"}",
"return",
"columns",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Not a select sql\"",
")",
";",
"}",
"}"
] | Example:<br>
<code>new String[] {"id", "code", "name"} equals SqlStrUtils.getSelectColumns("select id, code,name from user ")</code> | [
"Example",
":",
"<br",
">",
"<code",
">",
"new",
"String",
"[]",
"{",
"id",
"code",
"name",
"}",
"equals",
"SqlStrUtils",
".",
"getSelectColumns",
"(",
"select",
"id",
"code",
"name",
"from",
"user",
")",
"<",
"/",
"code",
">"
] | train | https://github.com/ineunetOS/knife-commons/blob/eae9e59afa020a00ae8977c10d43ac8ae46ae236/knife-commons-utils/src/main/java/com/ineunet/knife/util/sql/SqlStrUtils.java#L20-L39 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/kml/ST_AsKml.java | ST_AsKml.toKml | public static String toKml(Geometry geometry, boolean extrude, int altitudeModeEnum) throws SQLException {
"""
Generates a KML geometry. Specifies the extrude and altitudeMode.
Available extrude values are true, false or none.
Supported altitude mode :
For KML profil
CLAMPTOGROUND = 1; RELATIVETOGROUND = 2; ABSOLUTE = 4;
For GX profil CLAMPTOSEAFLOOR = 8; RELATIVETOSEAFLOOR = 16;
No altitude : NONE = 0;
@param geometry
@param altitudeModeEnum
@param extrude
@return
@throws SQLException
"""
StringBuilder sb = new StringBuilder();
if (extrude) {
KMLGeometry.toKMLGeometry(geometry, ExtrudeMode.TRUE, altitudeModeEnum, sb);
} else {
KMLGeometry.toKMLGeometry(geometry, ExtrudeMode.FALSE, altitudeModeEnum, sb);
}
return sb.toString();
} | java | public static String toKml(Geometry geometry, boolean extrude, int altitudeModeEnum) throws SQLException {
StringBuilder sb = new StringBuilder();
if (extrude) {
KMLGeometry.toKMLGeometry(geometry, ExtrudeMode.TRUE, altitudeModeEnum, sb);
} else {
KMLGeometry.toKMLGeometry(geometry, ExtrudeMode.FALSE, altitudeModeEnum, sb);
}
return sb.toString();
} | [
"public",
"static",
"String",
"toKml",
"(",
"Geometry",
"geometry",
",",
"boolean",
"extrude",
",",
"int",
"altitudeModeEnum",
")",
"throws",
"SQLException",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"if",
"(",
"extrude",
")",
"{",
"KMLGeometry",
".",
"toKMLGeometry",
"(",
"geometry",
",",
"ExtrudeMode",
".",
"TRUE",
",",
"altitudeModeEnum",
",",
"sb",
")",
";",
"}",
"else",
"{",
"KMLGeometry",
".",
"toKMLGeometry",
"(",
"geometry",
",",
"ExtrudeMode",
".",
"FALSE",
",",
"altitudeModeEnum",
",",
"sb",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | Generates a KML geometry. Specifies the extrude and altitudeMode.
Available extrude values are true, false or none.
Supported altitude mode :
For KML profil
CLAMPTOGROUND = 1; RELATIVETOGROUND = 2; ABSOLUTE = 4;
For GX profil CLAMPTOSEAFLOOR = 8; RELATIVETOSEAFLOOR = 16;
No altitude : NONE = 0;
@param geometry
@param altitudeModeEnum
@param extrude
@return
@throws SQLException | [
"Generates",
"a",
"KML",
"geometry",
".",
"Specifies",
"the",
"extrude",
"and",
"altitudeMode",
"."
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/kml/ST_AsKml.java#L84-L92 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ULocale.java | ULocale.parseTagString | private static int parseTagString(String localeID, String tags[]) {
"""
Parse the language, script, and region subtags from a tag string, and return the results.
This function does not return the canonical strings for the unknown script and region.
@param localeID The locale ID to parse.
@param tags An array of three String references to return the subtag strings.
@return The number of chars of the localeID parameter consumed.
"""
LocaleIDParser parser = new LocaleIDParser(localeID);
String lang = parser.getLanguage();
String script = parser.getScript();
String region = parser.getCountry();
if (isEmptyString(lang)) {
tags[0] = UNDEFINED_LANGUAGE;
}
else {
tags[0] = lang;
}
if (script.equals(UNDEFINED_SCRIPT)) {
tags[1] = "";
}
else {
tags[1] = script;
}
if (region.equals(UNDEFINED_REGION)) {
tags[2] = "";
}
else {
tags[2] = region;
}
/*
* Search for the variant. If there is one, then return the index of
* the preceeding separator.
* If there's no variant, search for the keyword delimiter,
* and return its index. Otherwise, return the length of the
* string.
*
* $TOTO(dbertoni) we need to take into account that we might
* find a part of the language as the variant, since it can
* can have a variant portion that is long enough to contain
* the same characters as the variant.
*/
String variant = parser.getVariant();
if (!isEmptyString(variant)){
int index = localeID.indexOf(variant);
return index > 0 ? index - 1 : index;
}
else
{
int index = localeID.indexOf('@');
return index == -1 ? localeID.length() : index;
}
} | java | private static int parseTagString(String localeID, String tags[]) {
LocaleIDParser parser = new LocaleIDParser(localeID);
String lang = parser.getLanguage();
String script = parser.getScript();
String region = parser.getCountry();
if (isEmptyString(lang)) {
tags[0] = UNDEFINED_LANGUAGE;
}
else {
tags[0] = lang;
}
if (script.equals(UNDEFINED_SCRIPT)) {
tags[1] = "";
}
else {
tags[1] = script;
}
if (region.equals(UNDEFINED_REGION)) {
tags[2] = "";
}
else {
tags[2] = region;
}
/*
* Search for the variant. If there is one, then return the index of
* the preceeding separator.
* If there's no variant, search for the keyword delimiter,
* and return its index. Otherwise, return the length of the
* string.
*
* $TOTO(dbertoni) we need to take into account that we might
* find a part of the language as the variant, since it can
* can have a variant portion that is long enough to contain
* the same characters as the variant.
*/
String variant = parser.getVariant();
if (!isEmptyString(variant)){
int index = localeID.indexOf(variant);
return index > 0 ? index - 1 : index;
}
else
{
int index = localeID.indexOf('@');
return index == -1 ? localeID.length() : index;
}
} | [
"private",
"static",
"int",
"parseTagString",
"(",
"String",
"localeID",
",",
"String",
"tags",
"[",
"]",
")",
"{",
"LocaleIDParser",
"parser",
"=",
"new",
"LocaleIDParser",
"(",
"localeID",
")",
";",
"String",
"lang",
"=",
"parser",
".",
"getLanguage",
"(",
")",
";",
"String",
"script",
"=",
"parser",
".",
"getScript",
"(",
")",
";",
"String",
"region",
"=",
"parser",
".",
"getCountry",
"(",
")",
";",
"if",
"(",
"isEmptyString",
"(",
"lang",
")",
")",
"{",
"tags",
"[",
"0",
"]",
"=",
"UNDEFINED_LANGUAGE",
";",
"}",
"else",
"{",
"tags",
"[",
"0",
"]",
"=",
"lang",
";",
"}",
"if",
"(",
"script",
".",
"equals",
"(",
"UNDEFINED_SCRIPT",
")",
")",
"{",
"tags",
"[",
"1",
"]",
"=",
"\"\"",
";",
"}",
"else",
"{",
"tags",
"[",
"1",
"]",
"=",
"script",
";",
"}",
"if",
"(",
"region",
".",
"equals",
"(",
"UNDEFINED_REGION",
")",
")",
"{",
"tags",
"[",
"2",
"]",
"=",
"\"\"",
";",
"}",
"else",
"{",
"tags",
"[",
"2",
"]",
"=",
"region",
";",
"}",
"/*\n * Search for the variant. If there is one, then return the index of\n * the preceeding separator.\n * If there's no variant, search for the keyword delimiter,\n * and return its index. Otherwise, return the length of the\n * string.\n *\n * $TOTO(dbertoni) we need to take into account that we might\n * find a part of the language as the variant, since it can\n * can have a variant portion that is long enough to contain\n * the same characters as the variant.\n */",
"String",
"variant",
"=",
"parser",
".",
"getVariant",
"(",
")",
";",
"if",
"(",
"!",
"isEmptyString",
"(",
"variant",
")",
")",
"{",
"int",
"index",
"=",
"localeID",
".",
"indexOf",
"(",
"variant",
")",
";",
"return",
"index",
">",
"0",
"?",
"index",
"-",
"1",
":",
"index",
";",
"}",
"else",
"{",
"int",
"index",
"=",
"localeID",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"return",
"index",
"==",
"-",
"1",
"?",
"localeID",
".",
"length",
"(",
")",
":",
"index",
";",
"}",
"}"
] | Parse the language, script, and region subtags from a tag string, and return the results.
This function does not return the canonical strings for the unknown script and region.
@param localeID The locale ID to parse.
@param tags An array of three String references to return the subtag strings.
@return The number of chars of the localeID parameter consumed. | [
"Parse",
"the",
"language",
"script",
"and",
"region",
"subtags",
"from",
"a",
"tag",
"string",
"and",
"return",
"the",
"results",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ULocale.java#L2779-L2833 |
lucee/Lucee | core/src/main/java/lucee/runtime/converter/ScriptConverter.java | ScriptConverter._serializeList | private void _serializeList(List list, StringBuilder sb, Set<Object> done) throws ConverterException {
"""
serialize a List (as Array)
@param list List to serialize
@param sb
@param done
@throws ConverterException
"""
sb.append(goIn());
sb.append("[");
boolean doIt = false;
ListIterator it = list.listIterator();
while (it.hasNext()) {
if (doIt) sb.append(',');
doIt = true;
_serialize(it.next(), sb, done);
}
sb.append(']');
} | java | private void _serializeList(List list, StringBuilder sb, Set<Object> done) throws ConverterException {
sb.append(goIn());
sb.append("[");
boolean doIt = false;
ListIterator it = list.listIterator();
while (it.hasNext()) {
if (doIt) sb.append(',');
doIt = true;
_serialize(it.next(), sb, done);
}
sb.append(']');
} | [
"private",
"void",
"_serializeList",
"(",
"List",
"list",
",",
"StringBuilder",
"sb",
",",
"Set",
"<",
"Object",
">",
"done",
")",
"throws",
"ConverterException",
"{",
"sb",
".",
"append",
"(",
"goIn",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"[\"",
")",
";",
"boolean",
"doIt",
"=",
"false",
";",
"ListIterator",
"it",
"=",
"list",
".",
"listIterator",
"(",
")",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{",
"if",
"(",
"doIt",
")",
"sb",
".",
"append",
"(",
"'",
"'",
")",
";",
"doIt",
"=",
"true",
";",
"_serialize",
"(",
"it",
".",
"next",
"(",
")",
",",
"sb",
",",
"done",
")",
";",
"}",
"sb",
".",
"append",
"(",
"'",
"'",
")",
";",
"}"
] | serialize a List (as Array)
@param list List to serialize
@param sb
@param done
@throws ConverterException | [
"serialize",
"a",
"List",
"(",
"as",
"Array",
")"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/converter/ScriptConverter.java#L163-L176 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/dispatcher/internal/HttpDispatcher.java | HttpDispatcher.isTrusted | public boolean isTrusted(String hostAddr, String headerName) {
"""
Check to see if the source host address is one we allow for specification of private headers
This takes into account the hosts defined in trustedHeaderOrigin and trustedSensitiveHeaderOrigin. Note,
trustedSensitiveHeaderOrigin takes precedence over trustedHeaderOrigin; so if trustedHeaderOrigin="none"
while trustedSensitiveHeaderOrigin="*", non-sensitive headers will still be trusted for all hosts.
@param hostAddr The source host address
@return true if hostAddr is a trusted source of private headers
"""
if (!wcTrusted) {
return false;
}
if (HttpHeaderKeys.isSensitivePrivateHeader(headerName)) {
// if this is a sensitive private header, check trustedSensitiveHeaderOrigin values
return isTrustedForSensitiveHeaders(hostAddr);
}
if (!usePrivateHeaders) {
// trustedHeaderOrigin list is explicitly set to "none"
return isTrustedForSensitiveHeaders(hostAddr);
}
if (restrictPrivateHeaderOrigin == null) {
// trustedHeaderOrigin list is set to "*"
return true;
} else {
// check trustedHeaderOrigin for given host IP
boolean trustedOrigin = restrictPrivateHeaderOrigin.contains(hostAddr.toLowerCase());
if (!trustedOrigin) {
// if hostAddr is not in trustedHeaderOrigin, allow trustedSensitiveHeaderOrigin to override trust
trustedOrigin = isTrustedForSensitiveHeaders(hostAddr);
}
return trustedOrigin;
}
} | java | public boolean isTrusted(String hostAddr, String headerName) {
if (!wcTrusted) {
return false;
}
if (HttpHeaderKeys.isSensitivePrivateHeader(headerName)) {
// if this is a sensitive private header, check trustedSensitiveHeaderOrigin values
return isTrustedForSensitiveHeaders(hostAddr);
}
if (!usePrivateHeaders) {
// trustedHeaderOrigin list is explicitly set to "none"
return isTrustedForSensitiveHeaders(hostAddr);
}
if (restrictPrivateHeaderOrigin == null) {
// trustedHeaderOrigin list is set to "*"
return true;
} else {
// check trustedHeaderOrigin for given host IP
boolean trustedOrigin = restrictPrivateHeaderOrigin.contains(hostAddr.toLowerCase());
if (!trustedOrigin) {
// if hostAddr is not in trustedHeaderOrigin, allow trustedSensitiveHeaderOrigin to override trust
trustedOrigin = isTrustedForSensitiveHeaders(hostAddr);
}
return trustedOrigin;
}
} | [
"public",
"boolean",
"isTrusted",
"(",
"String",
"hostAddr",
",",
"String",
"headerName",
")",
"{",
"if",
"(",
"!",
"wcTrusted",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"HttpHeaderKeys",
".",
"isSensitivePrivateHeader",
"(",
"headerName",
")",
")",
"{",
"// if this is a sensitive private header, check trustedSensitiveHeaderOrigin values",
"return",
"isTrustedForSensitiveHeaders",
"(",
"hostAddr",
")",
";",
"}",
"if",
"(",
"!",
"usePrivateHeaders",
")",
"{",
"// trustedHeaderOrigin list is explicitly set to \"none\"",
"return",
"isTrustedForSensitiveHeaders",
"(",
"hostAddr",
")",
";",
"}",
"if",
"(",
"restrictPrivateHeaderOrigin",
"==",
"null",
")",
"{",
"// trustedHeaderOrigin list is set to \"*\"",
"return",
"true",
";",
"}",
"else",
"{",
"// check trustedHeaderOrigin for given host IP",
"boolean",
"trustedOrigin",
"=",
"restrictPrivateHeaderOrigin",
".",
"contains",
"(",
"hostAddr",
".",
"toLowerCase",
"(",
")",
")",
";",
"if",
"(",
"!",
"trustedOrigin",
")",
"{",
"// if hostAddr is not in trustedHeaderOrigin, allow trustedSensitiveHeaderOrigin to override trust",
"trustedOrigin",
"=",
"isTrustedForSensitiveHeaders",
"(",
"hostAddr",
")",
";",
"}",
"return",
"trustedOrigin",
";",
"}",
"}"
] | Check to see if the source host address is one we allow for specification of private headers
This takes into account the hosts defined in trustedHeaderOrigin and trustedSensitiveHeaderOrigin. Note,
trustedSensitiveHeaderOrigin takes precedence over trustedHeaderOrigin; so if trustedHeaderOrigin="none"
while trustedSensitiveHeaderOrigin="*", non-sensitive headers will still be trusted for all hosts.
@param hostAddr The source host address
@return true if hostAddr is a trusted source of private headers | [
"Check",
"to",
"see",
"if",
"the",
"source",
"host",
"address",
"is",
"one",
"we",
"allow",
"for",
"specification",
"of",
"private",
"headers"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/dispatcher/internal/HttpDispatcher.java#L442-L466 |
ginere/ginere-base | src/main/java/eu/ginere/base/util/properties/GlobalFileProperties.java | GlobalFileProperties.getFilePath | private static String getFilePath(String defaultPath, String filePath) {
"""
Crea el path para el fichero a partir del path por defecto
@param defaultPath
@param filePath
@return
"""
return defaultPath+File.separator+filePath;
} | java | private static String getFilePath(String defaultPath, String filePath) {
return defaultPath+File.separator+filePath;
} | [
"private",
"static",
"String",
"getFilePath",
"(",
"String",
"defaultPath",
",",
"String",
"filePath",
")",
"{",
"return",
"defaultPath",
"+",
"File",
".",
"separator",
"+",
"filePath",
";",
"}"
] | Crea el path para el fichero a partir del path por defecto
@param defaultPath
@param filePath
@return | [
"Crea",
"el",
"path",
"para",
"el",
"fichero",
"a",
"partir",
"del",
"path",
"por",
"defecto"
] | train | https://github.com/ginere/ginere-base/blob/b1cc1c5834bd8a31df475c6f3fc0ee51273c5a24/src/main/java/eu/ginere/base/util/properties/GlobalFileProperties.java#L468-L470 |
JodaOrg/joda-time | src/main/java/org/joda/time/YearMonthDay.java | YearMonthDay.withField | public YearMonthDay withField(DateTimeFieldType fieldType, int value) {
"""
Returns a copy of this date with the specified field set to a new value.
<p>
For example, if the field type is <code>dayOfMonth</code> then the day
would be changed in the returned instance.
<p>
These three lines are equivalent:
<pre>
YearMonthDay updated = ymd.withField(DateTimeFieldType.dayOfMonth(), 6);
YearMonthDay updated = ymd.dayOfMonth().setCopy(6);
YearMonthDay updated = ymd.property(DateTimeFieldType.dayOfMonth()).setCopy(6);
</pre>
@param fieldType the field type to set, not null
@param value the value to set
@return a copy of this instance with the field set
@throws IllegalArgumentException if the value is null or invalid
"""
int index = indexOfSupported(fieldType);
if (value == getValue(index)) {
return this;
}
int[] newValues = getValues();
newValues = getField(index).set(this, index, newValues, value);
return new YearMonthDay(this, newValues);
} | java | public YearMonthDay withField(DateTimeFieldType fieldType, int value) {
int index = indexOfSupported(fieldType);
if (value == getValue(index)) {
return this;
}
int[] newValues = getValues();
newValues = getField(index).set(this, index, newValues, value);
return new YearMonthDay(this, newValues);
} | [
"public",
"YearMonthDay",
"withField",
"(",
"DateTimeFieldType",
"fieldType",
",",
"int",
"value",
")",
"{",
"int",
"index",
"=",
"indexOfSupported",
"(",
"fieldType",
")",
";",
"if",
"(",
"value",
"==",
"getValue",
"(",
"index",
")",
")",
"{",
"return",
"this",
";",
"}",
"int",
"[",
"]",
"newValues",
"=",
"getValues",
"(",
")",
";",
"newValues",
"=",
"getField",
"(",
"index",
")",
".",
"set",
"(",
"this",
",",
"index",
",",
"newValues",
",",
"value",
")",
";",
"return",
"new",
"YearMonthDay",
"(",
"this",
",",
"newValues",
")",
";",
"}"
] | Returns a copy of this date with the specified field set to a new value.
<p>
For example, if the field type is <code>dayOfMonth</code> then the day
would be changed in the returned instance.
<p>
These three lines are equivalent:
<pre>
YearMonthDay updated = ymd.withField(DateTimeFieldType.dayOfMonth(), 6);
YearMonthDay updated = ymd.dayOfMonth().setCopy(6);
YearMonthDay updated = ymd.property(DateTimeFieldType.dayOfMonth()).setCopy(6);
</pre>
@param fieldType the field type to set, not null
@param value the value to set
@return a copy of this instance with the field set
@throws IllegalArgumentException if the value is null or invalid | [
"Returns",
"a",
"copy",
"of",
"this",
"date",
"with",
"the",
"specified",
"field",
"set",
"to",
"a",
"new",
"value",
".",
"<p",
">",
"For",
"example",
"if",
"the",
"field",
"type",
"is",
"<code",
">",
"dayOfMonth<",
"/",
"code",
">",
"then",
"the",
"day",
"would",
"be",
"changed",
"in",
"the",
"returned",
"instance",
".",
"<p",
">",
"These",
"three",
"lines",
"are",
"equivalent",
":",
"<pre",
">",
"YearMonthDay",
"updated",
"=",
"ymd",
".",
"withField",
"(",
"DateTimeFieldType",
".",
"dayOfMonth",
"()",
"6",
")",
";",
"YearMonthDay",
"updated",
"=",
"ymd",
".",
"dayOfMonth",
"()",
".",
"setCopy",
"(",
"6",
")",
";",
"YearMonthDay",
"updated",
"=",
"ymd",
".",
"property",
"(",
"DateTimeFieldType",
".",
"dayOfMonth",
"()",
")",
".",
"setCopy",
"(",
"6",
")",
";",
"<",
"/",
"pre",
">"
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/YearMonthDay.java#L410-L418 |
molgenis/molgenis | molgenis-data-postgresql/src/main/java/org/molgenis/data/postgresql/PostgreSqlRepositoryCollection.java | PostgreSqlRepositoryCollection.addAttributeInternal | private void addAttributeInternal(EntityType entityType, Attribute attr) {
"""
Add attribute to entityType.
@param entityType the {@link EntityType} to add attribute to
@param attr attribute to add
"""
if (!isPersisted(attr)) {
return;
}
if (isMultipleReferenceType(attr)) {
createJunctionTable(entityType, attr);
if (attr.getDefaultValue() != null && !attr.isNillable()) {
@SuppressWarnings("unchecked")
Iterable<Entity> defaultRefEntities =
(Iterable<Entity>) AttributeUtils.getDefaultTypedValue(attr);
if (!Iterables.isEmpty(defaultRefEntities)) {
createJunctionTableRows(entityType, attr, defaultRefEntities);
}
}
} else {
createColumn(entityType, attr);
}
} | java | private void addAttributeInternal(EntityType entityType, Attribute attr) {
if (!isPersisted(attr)) {
return;
}
if (isMultipleReferenceType(attr)) {
createJunctionTable(entityType, attr);
if (attr.getDefaultValue() != null && !attr.isNillable()) {
@SuppressWarnings("unchecked")
Iterable<Entity> defaultRefEntities =
(Iterable<Entity>) AttributeUtils.getDefaultTypedValue(attr);
if (!Iterables.isEmpty(defaultRefEntities)) {
createJunctionTableRows(entityType, attr, defaultRefEntities);
}
}
} else {
createColumn(entityType, attr);
}
} | [
"private",
"void",
"addAttributeInternal",
"(",
"EntityType",
"entityType",
",",
"Attribute",
"attr",
")",
"{",
"if",
"(",
"!",
"isPersisted",
"(",
"attr",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"isMultipleReferenceType",
"(",
"attr",
")",
")",
"{",
"createJunctionTable",
"(",
"entityType",
",",
"attr",
")",
";",
"if",
"(",
"attr",
".",
"getDefaultValue",
"(",
")",
"!=",
"null",
"&&",
"!",
"attr",
".",
"isNillable",
"(",
")",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Iterable",
"<",
"Entity",
">",
"defaultRefEntities",
"=",
"(",
"Iterable",
"<",
"Entity",
">",
")",
"AttributeUtils",
".",
"getDefaultTypedValue",
"(",
"attr",
")",
";",
"if",
"(",
"!",
"Iterables",
".",
"isEmpty",
"(",
"defaultRefEntities",
")",
")",
"{",
"createJunctionTableRows",
"(",
"entityType",
",",
"attr",
",",
"defaultRefEntities",
")",
";",
"}",
"}",
"}",
"else",
"{",
"createColumn",
"(",
"entityType",
",",
"attr",
")",
";",
"}",
"}"
] | Add attribute to entityType.
@param entityType the {@link EntityType} to add attribute to
@param attr attribute to add | [
"Add",
"attribute",
"to",
"entityType",
"."
] | train | https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-data-postgresql/src/main/java/org/molgenis/data/postgresql/PostgreSqlRepositoryCollection.java#L287-L306 |
finmath/finmath-lib | src/main/java/net/finmath/time/SchedulePrototype.java | SchedulePrototype.generateSchedule | public Schedule generateSchedule(LocalDate referenceDate, int maturity, int termination) {
"""
Generate a schedule with start / end date determined by an offset in months from the reference date.
@param referenceDate The reference date (corresponds to \( t = 0 \).
@param maturity Offset of the start date to the reference date in months
@param termination Offset of the end date to the start date
@return The schedule
"""
return generateSchedule(referenceDate, maturity, termination, OffsetUnit.MONTHS);
} | java | public Schedule generateSchedule(LocalDate referenceDate, int maturity, int termination) {
return generateSchedule(referenceDate, maturity, termination, OffsetUnit.MONTHS);
} | [
"public",
"Schedule",
"generateSchedule",
"(",
"LocalDate",
"referenceDate",
",",
"int",
"maturity",
",",
"int",
"termination",
")",
"{",
"return",
"generateSchedule",
"(",
"referenceDate",
",",
"maturity",
",",
"termination",
",",
"OffsetUnit",
".",
"MONTHS",
")",
";",
"}"
] | Generate a schedule with start / end date determined by an offset in months from the reference date.
@param referenceDate The reference date (corresponds to \( t = 0 \).
@param maturity Offset of the start date to the reference date in months
@param termination Offset of the end date to the start date
@return The schedule | [
"Generate",
"a",
"schedule",
"with",
"start",
"/",
"end",
"date",
"determined",
"by",
"an",
"offset",
"in",
"months",
"from",
"the",
"reference",
"date",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/time/SchedulePrototype.java#L152-L154 |
ksclarke/vertx-pairtree | src/main/java/info/freelibrary/pairtree/PairtreeUtils.java | PairtreeUtils.mapToPtPath | public static String mapToPtPath(final String aBasePath, final String aID, final String aEncapsulatedName) {
"""
Maps the supplied ID to a Pairtree path using the supplied base path.
@param aID An ID to map to a Pairtree path
@param aBasePath The base path to use in the mapping
@param aEncapsulatedName The name of the encapsulating directory
@return The Pairtree path for the supplied ID
"""
final String ptPath;
Objects.requireNonNull(aID);
if (aEncapsulatedName == null) {
ptPath = concat(aBasePath, mapToPtPath(aID));
} else {
ptPath = concat(aBasePath, mapToPtPath(aID), encodeID(aEncapsulatedName));
}
return ptPath;
} | java | public static String mapToPtPath(final String aBasePath, final String aID, final String aEncapsulatedName) {
final String ptPath;
Objects.requireNonNull(aID);
if (aEncapsulatedName == null) {
ptPath = concat(aBasePath, mapToPtPath(aID));
} else {
ptPath = concat(aBasePath, mapToPtPath(aID), encodeID(aEncapsulatedName));
}
return ptPath;
} | [
"public",
"static",
"String",
"mapToPtPath",
"(",
"final",
"String",
"aBasePath",
",",
"final",
"String",
"aID",
",",
"final",
"String",
"aEncapsulatedName",
")",
"{",
"final",
"String",
"ptPath",
";",
"Objects",
".",
"requireNonNull",
"(",
"aID",
")",
";",
"if",
"(",
"aEncapsulatedName",
"==",
"null",
")",
"{",
"ptPath",
"=",
"concat",
"(",
"aBasePath",
",",
"mapToPtPath",
"(",
"aID",
")",
")",
";",
"}",
"else",
"{",
"ptPath",
"=",
"concat",
"(",
"aBasePath",
",",
"mapToPtPath",
"(",
"aID",
")",
",",
"encodeID",
"(",
"aEncapsulatedName",
")",
")",
";",
"}",
"return",
"ptPath",
";",
"}"
] | Maps the supplied ID to a Pairtree path using the supplied base path.
@param aID An ID to map to a Pairtree path
@param aBasePath The base path to use in the mapping
@param aEncapsulatedName The name of the encapsulating directory
@return The Pairtree path for the supplied ID | [
"Maps",
"the",
"supplied",
"ID",
"to",
"a",
"Pairtree",
"path",
"using",
"the",
"supplied",
"base",
"path",
"."
] | train | https://github.com/ksclarke/vertx-pairtree/blob/b2ea1e32057e5df262e9265540d346a732b718df/src/main/java/info/freelibrary/pairtree/PairtreeUtils.java#L176-L188 |
iipc/openwayback | wayback-core/src/main/java/org/archive/wayback/util/ByteOp.java | ByteOp.discardStream | public static void discardStream(InputStream is,int size) throws IOException {
"""
throw away all bytes from stream argument
@param is InputStream to read and discard
@param size number of bytes to read at once from the stream
@throws IOException when is throws one
"""
byte[] buffer = new byte[size];
while(is.read(buffer, 0, size) != -1) {
}
} | java | public static void discardStream(InputStream is,int size) throws IOException {
byte[] buffer = new byte[size];
while(is.read(buffer, 0, size) != -1) {
}
} | [
"public",
"static",
"void",
"discardStream",
"(",
"InputStream",
"is",
",",
"int",
"size",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"size",
"]",
";",
"while",
"(",
"is",
".",
"read",
"(",
"buffer",
",",
"0",
",",
"size",
")",
"!=",
"-",
"1",
")",
"{",
"}",
"}"
] | throw away all bytes from stream argument
@param is InputStream to read and discard
@param size number of bytes to read at once from the stream
@throws IOException when is throws one | [
"throw",
"away",
"all",
"bytes",
"from",
"stream",
"argument"
] | train | https://github.com/iipc/openwayback/blob/da74c3a59a5b5a5c365bd4702dcb45d263535794/wayback-core/src/main/java/org/archive/wayback/util/ByteOp.java#L88-L92 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpd/MPDUtility.java | MPDUtility.dumpRow | public static void dumpRow(Map<String, Object> row) {
"""
Dump the contents of a row from an MPD file.
@param row row data
"""
for (Entry<String, Object> entry : row.entrySet())
{
Object value = entry.getValue();
System.out.println(entry.getKey() + " = " + value + " ( " + (value == null ? "" : value.getClass().getName()) + ")");
}
} | java | public static void dumpRow(Map<String, Object> row)
{
for (Entry<String, Object> entry : row.entrySet())
{
Object value = entry.getValue();
System.out.println(entry.getKey() + " = " + value + " ( " + (value == null ? "" : value.getClass().getName()) + ")");
}
} | [
"public",
"static",
"void",
"dumpRow",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"row",
")",
"{",
"for",
"(",
"Entry",
"<",
"String",
",",
"Object",
">",
"entry",
":",
"row",
".",
"entrySet",
"(",
")",
")",
"{",
"Object",
"value",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"entry",
".",
"getKey",
"(",
")",
"+",
"\" = \"",
"+",
"value",
"+",
"\" ( \"",
"+",
"(",
"value",
"==",
"null",
"?",
"\"\"",
":",
"value",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
")",
"+",
"\")\"",
")",
";",
"}",
"}"
] | Dump the contents of a row from an MPD file.
@param row row data | [
"Dump",
"the",
"contents",
"of",
"a",
"row",
"from",
"an",
"MPD",
"file",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpd/MPDUtility.java#L341-L348 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/io/StreamThrottler.java | StreamThrottler.doThrottleInputStream | @Builder(builderMethodName = "throttleInputStream", builderClassName = "InputStreamThrottler")
private ThrottledInputStream doThrottleInputStream(InputStream inputStream, URI sourceURI, URI targetURI) {
"""
Throttles an {@link InputStream} if throttling is configured.
@param inputStream {@link InputStream} to throttle.
@param sourceURI used for selecting the throttling policy.
@param targetURI used for selecting the throttling policy.
"""
Preconditions.checkNotNull(inputStream, "InputStream cannot be null.");
Limiter limiter = new NoopLimiter();
if (sourceURI != null && targetURI != null) {
StreamCopierSharedLimiterKey key = new StreamCopierSharedLimiterKey(sourceURI, targetURI);
try {
limiter = new MultiLimiter(limiter, this.broker.getSharedResource(new SharedLimiterFactory<S>(),
key));
} catch (NotConfiguredException nce) {
log.warn("Could not create a Limiter for key " + key, nce);
}
} else {
log.info("Not throttling input stream because source or target URIs are not defined.");
}
Optional<MeteredInputStream> meteredStream = MeteredInputStream.findWrappedMeteredInputStream(inputStream);
if (!meteredStream.isPresent()) {
meteredStream = Optional.of(MeteredInputStream.builder().in(inputStream).build());
inputStream = meteredStream.get();
}
return new ThrottledInputStream(inputStream, limiter, meteredStream.get());
} | java | @Builder(builderMethodName = "throttleInputStream", builderClassName = "InputStreamThrottler")
private ThrottledInputStream doThrottleInputStream(InputStream inputStream, URI sourceURI, URI targetURI) {
Preconditions.checkNotNull(inputStream, "InputStream cannot be null.");
Limiter limiter = new NoopLimiter();
if (sourceURI != null && targetURI != null) {
StreamCopierSharedLimiterKey key = new StreamCopierSharedLimiterKey(sourceURI, targetURI);
try {
limiter = new MultiLimiter(limiter, this.broker.getSharedResource(new SharedLimiterFactory<S>(),
key));
} catch (NotConfiguredException nce) {
log.warn("Could not create a Limiter for key " + key, nce);
}
} else {
log.info("Not throttling input stream because source or target URIs are not defined.");
}
Optional<MeteredInputStream> meteredStream = MeteredInputStream.findWrappedMeteredInputStream(inputStream);
if (!meteredStream.isPresent()) {
meteredStream = Optional.of(MeteredInputStream.builder().in(inputStream).build());
inputStream = meteredStream.get();
}
return new ThrottledInputStream(inputStream, limiter, meteredStream.get());
} | [
"@",
"Builder",
"(",
"builderMethodName",
"=",
"\"throttleInputStream\"",
",",
"builderClassName",
"=",
"\"InputStreamThrottler\"",
")",
"private",
"ThrottledInputStream",
"doThrottleInputStream",
"(",
"InputStream",
"inputStream",
",",
"URI",
"sourceURI",
",",
"URI",
"targetURI",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"inputStream",
",",
"\"InputStream cannot be null.\"",
")",
";",
"Limiter",
"limiter",
"=",
"new",
"NoopLimiter",
"(",
")",
";",
"if",
"(",
"sourceURI",
"!=",
"null",
"&&",
"targetURI",
"!=",
"null",
")",
"{",
"StreamCopierSharedLimiterKey",
"key",
"=",
"new",
"StreamCopierSharedLimiterKey",
"(",
"sourceURI",
",",
"targetURI",
")",
";",
"try",
"{",
"limiter",
"=",
"new",
"MultiLimiter",
"(",
"limiter",
",",
"this",
".",
"broker",
".",
"getSharedResource",
"(",
"new",
"SharedLimiterFactory",
"<",
"S",
">",
"(",
")",
",",
"key",
")",
")",
";",
"}",
"catch",
"(",
"NotConfiguredException",
"nce",
")",
"{",
"log",
".",
"warn",
"(",
"\"Could not create a Limiter for key \"",
"+",
"key",
",",
"nce",
")",
";",
"}",
"}",
"else",
"{",
"log",
".",
"info",
"(",
"\"Not throttling input stream because source or target URIs are not defined.\"",
")",
";",
"}",
"Optional",
"<",
"MeteredInputStream",
">",
"meteredStream",
"=",
"MeteredInputStream",
".",
"findWrappedMeteredInputStream",
"(",
"inputStream",
")",
";",
"if",
"(",
"!",
"meteredStream",
".",
"isPresent",
"(",
")",
")",
"{",
"meteredStream",
"=",
"Optional",
".",
"of",
"(",
"MeteredInputStream",
".",
"builder",
"(",
")",
".",
"in",
"(",
"inputStream",
")",
".",
"build",
"(",
")",
")",
";",
"inputStream",
"=",
"meteredStream",
".",
"get",
"(",
")",
";",
"}",
"return",
"new",
"ThrottledInputStream",
"(",
"inputStream",
",",
"limiter",
",",
"meteredStream",
".",
"get",
"(",
")",
")",
";",
"}"
] | Throttles an {@link InputStream} if throttling is configured.
@param inputStream {@link InputStream} to throttle.
@param sourceURI used for selecting the throttling policy.
@param targetURI used for selecting the throttling policy. | [
"Throttles",
"an",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/io/StreamThrottler.java#L84-L108 |
line/armeria | zookeeper/src/main/java/com/linecorp/armeria/server/zookeeper/ZooKeeperUpdatingListenerBuilder.java | ZooKeeperUpdatingListenerBuilder.build | public ZooKeeperUpdatingListener build() {
"""
Returns a newly-created {@link ZooKeeperUpdatingListener} instance that registers the server to
ZooKeeper when the server starts.
"""
final boolean internalClient;
if (client == null) {
client = CuratorFrameworkFactory.builder()
.connectString(connectionStr)
.retryPolicy(ZooKeeperDefaults.DEFAULT_RETRY_POLICY)
.connectionTimeoutMs(connectTimeoutMillis)
.sessionTimeoutMs(sessionTimeoutMillis)
.build();
internalClient = true;
} else {
internalClient = false;
}
return new ZooKeeperUpdatingListener(client, zNodePath, nodeValueCodec, endpoint, internalClient);
} | java | public ZooKeeperUpdatingListener build() {
final boolean internalClient;
if (client == null) {
client = CuratorFrameworkFactory.builder()
.connectString(connectionStr)
.retryPolicy(ZooKeeperDefaults.DEFAULT_RETRY_POLICY)
.connectionTimeoutMs(connectTimeoutMillis)
.sessionTimeoutMs(sessionTimeoutMillis)
.build();
internalClient = true;
} else {
internalClient = false;
}
return new ZooKeeperUpdatingListener(client, zNodePath, nodeValueCodec, endpoint, internalClient);
} | [
"public",
"ZooKeeperUpdatingListener",
"build",
"(",
")",
"{",
"final",
"boolean",
"internalClient",
";",
"if",
"(",
"client",
"==",
"null",
")",
"{",
"client",
"=",
"CuratorFrameworkFactory",
".",
"builder",
"(",
")",
".",
"connectString",
"(",
"connectionStr",
")",
".",
"retryPolicy",
"(",
"ZooKeeperDefaults",
".",
"DEFAULT_RETRY_POLICY",
")",
".",
"connectionTimeoutMs",
"(",
"connectTimeoutMillis",
")",
".",
"sessionTimeoutMs",
"(",
"sessionTimeoutMillis",
")",
".",
"build",
"(",
")",
";",
"internalClient",
"=",
"true",
";",
"}",
"else",
"{",
"internalClient",
"=",
"false",
";",
"}",
"return",
"new",
"ZooKeeperUpdatingListener",
"(",
"client",
",",
"zNodePath",
",",
"nodeValueCodec",
",",
"endpoint",
",",
"internalClient",
")",
";",
"}"
] | Returns a newly-created {@link ZooKeeperUpdatingListener} instance that registers the server to
ZooKeeper when the server starts. | [
"Returns",
"a",
"newly",
"-",
"created",
"{"
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/zookeeper/src/main/java/com/linecorp/armeria/server/zookeeper/ZooKeeperUpdatingListenerBuilder.java#L192-L207 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/dom2dtm/DOM2DTM.java | DOM2DTM.dispatchToEvents | public void dispatchToEvents(int nodeHandle, org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException {
"""
Directly create SAX parser events from a subtree.
@param nodeHandle The node ID.
@param ch A non-null reference to a ContentHandler.
@throws org.xml.sax.SAXException
"""
TreeWalker treeWalker = m_walker;
ContentHandler prevCH = treeWalker.getContentHandler();
if(null != prevCH)
{
treeWalker = new TreeWalker(null);
}
treeWalker.setContentHandler(ch);
try
{
Node node = getNode(nodeHandle);
treeWalker.traverseFragment(node);
}
finally
{
treeWalker.setContentHandler(null);
}
} | java | public void dispatchToEvents(int nodeHandle, org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException
{
TreeWalker treeWalker = m_walker;
ContentHandler prevCH = treeWalker.getContentHandler();
if(null != prevCH)
{
treeWalker = new TreeWalker(null);
}
treeWalker.setContentHandler(ch);
try
{
Node node = getNode(nodeHandle);
treeWalker.traverseFragment(node);
}
finally
{
treeWalker.setContentHandler(null);
}
} | [
"public",
"void",
"dispatchToEvents",
"(",
"int",
"nodeHandle",
",",
"org",
".",
"xml",
".",
"sax",
".",
"ContentHandler",
"ch",
")",
"throws",
"org",
".",
"xml",
".",
"sax",
".",
"SAXException",
"{",
"TreeWalker",
"treeWalker",
"=",
"m_walker",
";",
"ContentHandler",
"prevCH",
"=",
"treeWalker",
".",
"getContentHandler",
"(",
")",
";",
"if",
"(",
"null",
"!=",
"prevCH",
")",
"{",
"treeWalker",
"=",
"new",
"TreeWalker",
"(",
"null",
")",
";",
"}",
"treeWalker",
".",
"setContentHandler",
"(",
"ch",
")",
";",
"try",
"{",
"Node",
"node",
"=",
"getNode",
"(",
"nodeHandle",
")",
";",
"treeWalker",
".",
"traverseFragment",
"(",
"node",
")",
";",
"}",
"finally",
"{",
"treeWalker",
".",
"setContentHandler",
"(",
"null",
")",
";",
"}",
"}"
] | Directly create SAX parser events from a subtree.
@param nodeHandle The node ID.
@param ch A non-null reference to a ContentHandler.
@throws org.xml.sax.SAXException | [
"Directly",
"create",
"SAX",
"parser",
"events",
"from",
"a",
"subtree",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/dom2dtm/DOM2DTM.java#L1712-L1733 |
edwardcapriolo/teknek-core | src/main/java/io/teknek/driver/DriverFactory.java | DriverFactory.createDriver | public static Driver createDriver(FeedPartition feedPartition, Plan plan, MetricRegistry metricRegistry) {
"""
Given a FeedParition and Plan create a Driver that will consume from the feed partition
and execute the plan.
@param feedPartition
@param plan
@return an uninitialized Driver
"""
populateFeedMetricInfo(plan, feedPartition, metricRegistry);
OperatorDesc desc = plan.getRootOperator();
Operator oper = buildOperator(desc, metricRegistry, plan.getName(), feedPartition);
OffsetStorage offsetStorage = null;
OffsetStorageDesc offsetDesc = plan.getOffsetStorageDesc();
if (offsetDesc != null && feedPartition.supportsOffsetManagement()){
offsetStorage = buildOffsetStorage(feedPartition, plan, offsetDesc);
Offset offset = offsetStorage.findLatestPersistedOffset();
if (offset != null){
feedPartition.setOffset(new String(offset.serialize(), Charsets.UTF_8));
}
}
CollectorProcessor cp = new CollectorProcessor();
cp.setTupleRetry(plan.getTupleRetry());
int offsetCommitInterval = plan.getOffsetCommitInterval();
Driver driver = new Driver(feedPartition, oper, offsetStorage, cp, offsetCommitInterval, metricRegistry, plan.getName());
recurseOperatorAndDriverNode(desc, driver.getDriverNode(), metricRegistry, feedPartition);
return driver;
} | java | public static Driver createDriver(FeedPartition feedPartition, Plan plan, MetricRegistry metricRegistry){
populateFeedMetricInfo(plan, feedPartition, metricRegistry);
OperatorDesc desc = plan.getRootOperator();
Operator oper = buildOperator(desc, metricRegistry, plan.getName(), feedPartition);
OffsetStorage offsetStorage = null;
OffsetStorageDesc offsetDesc = plan.getOffsetStorageDesc();
if (offsetDesc != null && feedPartition.supportsOffsetManagement()){
offsetStorage = buildOffsetStorage(feedPartition, plan, offsetDesc);
Offset offset = offsetStorage.findLatestPersistedOffset();
if (offset != null){
feedPartition.setOffset(new String(offset.serialize(), Charsets.UTF_8));
}
}
CollectorProcessor cp = new CollectorProcessor();
cp.setTupleRetry(plan.getTupleRetry());
int offsetCommitInterval = plan.getOffsetCommitInterval();
Driver driver = new Driver(feedPartition, oper, offsetStorage, cp, offsetCommitInterval, metricRegistry, plan.getName());
recurseOperatorAndDriverNode(desc, driver.getDriverNode(), metricRegistry, feedPartition);
return driver;
} | [
"public",
"static",
"Driver",
"createDriver",
"(",
"FeedPartition",
"feedPartition",
",",
"Plan",
"plan",
",",
"MetricRegistry",
"metricRegistry",
")",
"{",
"populateFeedMetricInfo",
"(",
"plan",
",",
"feedPartition",
",",
"metricRegistry",
")",
";",
"OperatorDesc",
"desc",
"=",
"plan",
".",
"getRootOperator",
"(",
")",
";",
"Operator",
"oper",
"=",
"buildOperator",
"(",
"desc",
",",
"metricRegistry",
",",
"plan",
".",
"getName",
"(",
")",
",",
"feedPartition",
")",
";",
"OffsetStorage",
"offsetStorage",
"=",
"null",
";",
"OffsetStorageDesc",
"offsetDesc",
"=",
"plan",
".",
"getOffsetStorageDesc",
"(",
")",
";",
"if",
"(",
"offsetDesc",
"!=",
"null",
"&&",
"feedPartition",
".",
"supportsOffsetManagement",
"(",
")",
")",
"{",
"offsetStorage",
"=",
"buildOffsetStorage",
"(",
"feedPartition",
",",
"plan",
",",
"offsetDesc",
")",
";",
"Offset",
"offset",
"=",
"offsetStorage",
".",
"findLatestPersistedOffset",
"(",
")",
";",
"if",
"(",
"offset",
"!=",
"null",
")",
"{",
"feedPartition",
".",
"setOffset",
"(",
"new",
"String",
"(",
"offset",
".",
"serialize",
"(",
")",
",",
"Charsets",
".",
"UTF_8",
")",
")",
";",
"}",
"}",
"CollectorProcessor",
"cp",
"=",
"new",
"CollectorProcessor",
"(",
")",
";",
"cp",
".",
"setTupleRetry",
"(",
"plan",
".",
"getTupleRetry",
"(",
")",
")",
";",
"int",
"offsetCommitInterval",
"=",
"plan",
".",
"getOffsetCommitInterval",
"(",
")",
";",
"Driver",
"driver",
"=",
"new",
"Driver",
"(",
"feedPartition",
",",
"oper",
",",
"offsetStorage",
",",
"cp",
",",
"offsetCommitInterval",
",",
"metricRegistry",
",",
"plan",
".",
"getName",
"(",
")",
")",
";",
"recurseOperatorAndDriverNode",
"(",
"desc",
",",
"driver",
".",
"getDriverNode",
"(",
")",
",",
"metricRegistry",
",",
"feedPartition",
")",
";",
"return",
"driver",
";",
"}"
] | Given a FeedParition and Plan create a Driver that will consume from the feed partition
and execute the plan.
@param feedPartition
@param plan
@return an uninitialized Driver | [
"Given",
"a",
"FeedParition",
"and",
"Plan",
"create",
"a",
"Driver",
"that",
"will",
"consume",
"from",
"the",
"feed",
"partition",
"and",
"execute",
"the",
"plan",
"."
] | train | https://github.com/edwardcapriolo/teknek-core/blob/4fa972d11044dee2954c0cc5e1b53b18fba319b9/src/main/java/io/teknek/driver/DriverFactory.java#L60-L79 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/ba/BasicBlock.java | BasicBlock.setExceptionGen | public void setExceptionGen(@Nullable TypeMerger m, CodeExceptionGen exceptionGen) {
"""
Set the CodeExceptionGen object. Marks this basic block as the entry
point of an exception handler.
@param exceptionGen
the CodeExceptionGen object for the block
"""
if (this.exceptionGen != null) {
AnalysisContext.logError("Multiple exception handlers");
}
this.exceptionGen = exceptionGen;
} | java | public void setExceptionGen(@Nullable TypeMerger m, CodeExceptionGen exceptionGen) {
if (this.exceptionGen != null) {
AnalysisContext.logError("Multiple exception handlers");
}
this.exceptionGen = exceptionGen;
} | [
"public",
"void",
"setExceptionGen",
"(",
"@",
"Nullable",
"TypeMerger",
"m",
",",
"CodeExceptionGen",
"exceptionGen",
")",
"{",
"if",
"(",
"this",
".",
"exceptionGen",
"!=",
"null",
")",
"{",
"AnalysisContext",
".",
"logError",
"(",
"\"Multiple exception handlers\"",
")",
";",
"}",
"this",
".",
"exceptionGen",
"=",
"exceptionGen",
";",
"}"
] | Set the CodeExceptionGen object. Marks this basic block as the entry
point of an exception handler.
@param exceptionGen
the CodeExceptionGen object for the block | [
"Set",
"the",
"CodeExceptionGen",
"object",
".",
"Marks",
"this",
"basic",
"block",
"as",
"the",
"entry",
"point",
"of",
"an",
"exception",
"handler",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/BasicBlock.java#L415-L421 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypesBuilder.java | JvmTypesBuilder.setInitializer | public void setInitializer(/* @Nullable */ JvmField field, /* @Nullable */ XExpression expr) {
"""
Sets the given {@link JvmField} as the logical container for the given {@link XExpression}.
This defines the context and the scope for the given expression.
@param field
the {@link JvmField} that is initialized by the expression. If <code>null</code> this method does nothing.
@param expr
the initialization expression. Can be <code>null</code> in which case this function does nothing.
"""
if (field == null || expr == null)
return;
removeExistingBody(field);
associator.associateLogicalContainer(expr, field);
} | java | public void setInitializer(/* @Nullable */ JvmField field, /* @Nullable */ XExpression expr) {
if (field == null || expr == null)
return;
removeExistingBody(field);
associator.associateLogicalContainer(expr, field);
} | [
"public",
"void",
"setInitializer",
"(",
"/* @Nullable */",
"JvmField",
"field",
",",
"/* @Nullable */",
"XExpression",
"expr",
")",
"{",
"if",
"(",
"field",
"==",
"null",
"||",
"expr",
"==",
"null",
")",
"return",
";",
"removeExistingBody",
"(",
"field",
")",
";",
"associator",
".",
"associateLogicalContainer",
"(",
"expr",
",",
"field",
")",
";",
"}"
] | Sets the given {@link JvmField} as the logical container for the given {@link XExpression}.
This defines the context and the scope for the given expression.
@param field
the {@link JvmField} that is initialized by the expression. If <code>null</code> this method does nothing.
@param expr
the initialization expression. Can be <code>null</code> in which case this function does nothing. | [
"Sets",
"the",
"given",
"{",
"@link",
"JvmField",
"}",
"as",
"the",
"logical",
"container",
"for",
"the",
"given",
"{",
"@link",
"XExpression",
"}",
".",
"This",
"defines",
"the",
"context",
"and",
"the",
"scope",
"for",
"the",
"given",
"expression",
"."
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypesBuilder.java#L1260-L1265 |
beangle/beangle3 | struts/s2/src/main/java/org/beangle/struts2/view/component/Component.java | Component.fieldError | protected StrutsException fieldError(String field, String errorMsg, Exception e) {
"""
Constructs a <code>RuntimeException</code> based on the given
information.
<p/>
A message is constructed and logged at ERROR level before being returned as a
<code>RuntimeException</code>.
@param field
field name used when throwing <code>RuntimeException</code>.
@param errorMsg
error message used when throwing <code>RuntimeException</code> .
@param e
the caused exception, can be <tt>null</tt>.
@return the constructed <code>StrutsException</code>.
"""
String msg = "tag '" + getComponentName() + "', field '" + field
+ (parameters != null && parameters.containsKey("name") ? "', name '" + parameters.get("name") : "")
+ "': " + errorMsg;
throw new StrutsException(msg, e);
} | java | protected StrutsException fieldError(String field, String errorMsg, Exception e) {
String msg = "tag '" + getComponentName() + "', field '" + field
+ (parameters != null && parameters.containsKey("name") ? "', name '" + parameters.get("name") : "")
+ "': " + errorMsg;
throw new StrutsException(msg, e);
} | [
"protected",
"StrutsException",
"fieldError",
"(",
"String",
"field",
",",
"String",
"errorMsg",
",",
"Exception",
"e",
")",
"{",
"String",
"msg",
"=",
"\"tag '\"",
"+",
"getComponentName",
"(",
")",
"+",
"\"', field '\"",
"+",
"field",
"+",
"(",
"parameters",
"!=",
"null",
"&&",
"parameters",
".",
"containsKey",
"(",
"\"name\"",
")",
"?",
"\"', name '\"",
"+",
"parameters",
".",
"get",
"(",
"\"name\"",
")",
":",
"\"\"",
")",
"+",
"\"': \"",
"+",
"errorMsg",
";",
"throw",
"new",
"StrutsException",
"(",
"msg",
",",
"e",
")",
";",
"}"
] | Constructs a <code>RuntimeException</code> based on the given
information.
<p/>
A message is constructed and logged at ERROR level before being returned as a
<code>RuntimeException</code>.
@param field
field name used when throwing <code>RuntimeException</code>.
@param errorMsg
error message used when throwing <code>RuntimeException</code> .
@param e
the caused exception, can be <tt>null</tt>.
@return the constructed <code>StrutsException</code>. | [
"Constructs",
"a",
"<code",
">",
"RuntimeException<",
"/",
"code",
">",
"based",
"on",
"the",
"given",
"information",
".",
"<p",
"/",
">",
"A",
"message",
"is",
"constructed",
"and",
"logged",
"at",
"ERROR",
"level",
"before",
"being",
"returned",
"as",
"a",
"<code",
">",
"RuntimeException<",
"/",
"code",
">",
"."
] | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/struts/s2/src/main/java/org/beangle/struts2/view/component/Component.java#L207-L212 |
snowflakedb/snowflake-jdbc | src/main/java/net/snowflake/client/core/SessionUtil.java | SessionUtil.federatedFlowStep1 | private static JsonNode federatedFlowStep1(LoginInput loginInput)
throws SnowflakeSQLException {
"""
Query Snowflake to obtain IDP token url and IDP SSO url
@param loginInput
@throws SnowflakeSQLException
"""
JsonNode dataNode = null;
try
{
URIBuilder fedUriBuilder = new URIBuilder(loginInput.getServerUrl());
fedUriBuilder.setPath(SF_PATH_AUTHENTICATOR_REQUEST);
URI fedUrlUri = fedUriBuilder.build();
Map<String, Object> data = new HashMap<>();
data.put(ClientAuthnParameter.ACCOUNT_NAME.name(),
loginInput.getAccountName());
data.put(ClientAuthnParameter.AUTHENTICATOR.name(),
loginInput.getAuthenticator());
data.put(ClientAuthnParameter.CLIENT_APP_ID.name(), loginInput.getAppId());
data.put(ClientAuthnParameter.CLIENT_APP_VERSION.name(),
loginInput.getAppVersion());
ClientAuthnDTO authnData = new ClientAuthnDTO();
authnData.setData(data);
String json = mapper.writeValueAsString(authnData);
// attach the login info json body to the post request
StringEntity input = new StringEntity(json, Charset.forName("UTF-8"));
input.setContentType("application/json");
HttpPost postRequest = new HttpPost(fedUrlUri);
postRequest.setEntity(input);
postRequest.addHeader("accept", "application/json");
final String gsResponse = HttpUtil.executeRequest(postRequest,
loginInput.getLoginTimeout(), 0, null);
logger.debug("authenticator-request response: {}", gsResponse);
JsonNode jsonNode = mapper.readTree(gsResponse);
// check the success field first
if (!jsonNode.path("success").asBoolean())
{
logger.debug("response = {}", gsResponse);
String errorCode = jsonNode.path("code").asText();
throw new SnowflakeSQLException(
SqlState.SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION,
ErrorCode.CONNECTION_ERROR.getMessageCode(),
errorCode, jsonNode.path("message").asText());
}
// session token is in the data field of the returned json response
dataNode = jsonNode.path("data");
}
catch (IOException | URISyntaxException ex)
{
handleFederatedFlowError(loginInput, ex);
}
return dataNode;
} | java | private static JsonNode federatedFlowStep1(LoginInput loginInput)
throws SnowflakeSQLException
{
JsonNode dataNode = null;
try
{
URIBuilder fedUriBuilder = new URIBuilder(loginInput.getServerUrl());
fedUriBuilder.setPath(SF_PATH_AUTHENTICATOR_REQUEST);
URI fedUrlUri = fedUriBuilder.build();
Map<String, Object> data = new HashMap<>();
data.put(ClientAuthnParameter.ACCOUNT_NAME.name(),
loginInput.getAccountName());
data.put(ClientAuthnParameter.AUTHENTICATOR.name(),
loginInput.getAuthenticator());
data.put(ClientAuthnParameter.CLIENT_APP_ID.name(), loginInput.getAppId());
data.put(ClientAuthnParameter.CLIENT_APP_VERSION.name(),
loginInput.getAppVersion());
ClientAuthnDTO authnData = new ClientAuthnDTO();
authnData.setData(data);
String json = mapper.writeValueAsString(authnData);
// attach the login info json body to the post request
StringEntity input = new StringEntity(json, Charset.forName("UTF-8"));
input.setContentType("application/json");
HttpPost postRequest = new HttpPost(fedUrlUri);
postRequest.setEntity(input);
postRequest.addHeader("accept", "application/json");
final String gsResponse = HttpUtil.executeRequest(postRequest,
loginInput.getLoginTimeout(), 0, null);
logger.debug("authenticator-request response: {}", gsResponse);
JsonNode jsonNode = mapper.readTree(gsResponse);
// check the success field first
if (!jsonNode.path("success").asBoolean())
{
logger.debug("response = {}", gsResponse);
String errorCode = jsonNode.path("code").asText();
throw new SnowflakeSQLException(
SqlState.SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION,
ErrorCode.CONNECTION_ERROR.getMessageCode(),
errorCode, jsonNode.path("message").asText());
}
// session token is in the data field of the returned json response
dataNode = jsonNode.path("data");
}
catch (IOException | URISyntaxException ex)
{
handleFederatedFlowError(loginInput, ex);
}
return dataNode;
} | [
"private",
"static",
"JsonNode",
"federatedFlowStep1",
"(",
"LoginInput",
"loginInput",
")",
"throws",
"SnowflakeSQLException",
"{",
"JsonNode",
"dataNode",
"=",
"null",
";",
"try",
"{",
"URIBuilder",
"fedUriBuilder",
"=",
"new",
"URIBuilder",
"(",
"loginInput",
".",
"getServerUrl",
"(",
")",
")",
";",
"fedUriBuilder",
".",
"setPath",
"(",
"SF_PATH_AUTHENTICATOR_REQUEST",
")",
";",
"URI",
"fedUrlUri",
"=",
"fedUriBuilder",
".",
"build",
"(",
")",
";",
"Map",
"<",
"String",
",",
"Object",
">",
"data",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"data",
".",
"put",
"(",
"ClientAuthnParameter",
".",
"ACCOUNT_NAME",
".",
"name",
"(",
")",
",",
"loginInput",
".",
"getAccountName",
"(",
")",
")",
";",
"data",
".",
"put",
"(",
"ClientAuthnParameter",
".",
"AUTHENTICATOR",
".",
"name",
"(",
")",
",",
"loginInput",
".",
"getAuthenticator",
"(",
")",
")",
";",
"data",
".",
"put",
"(",
"ClientAuthnParameter",
".",
"CLIENT_APP_ID",
".",
"name",
"(",
")",
",",
"loginInput",
".",
"getAppId",
"(",
")",
")",
";",
"data",
".",
"put",
"(",
"ClientAuthnParameter",
".",
"CLIENT_APP_VERSION",
".",
"name",
"(",
")",
",",
"loginInput",
".",
"getAppVersion",
"(",
")",
")",
";",
"ClientAuthnDTO",
"authnData",
"=",
"new",
"ClientAuthnDTO",
"(",
")",
";",
"authnData",
".",
"setData",
"(",
"data",
")",
";",
"String",
"json",
"=",
"mapper",
".",
"writeValueAsString",
"(",
"authnData",
")",
";",
"// attach the login info json body to the post request",
"StringEntity",
"input",
"=",
"new",
"StringEntity",
"(",
"json",
",",
"Charset",
".",
"forName",
"(",
"\"UTF-8\"",
")",
")",
";",
"input",
".",
"setContentType",
"(",
"\"application/json\"",
")",
";",
"HttpPost",
"postRequest",
"=",
"new",
"HttpPost",
"(",
"fedUrlUri",
")",
";",
"postRequest",
".",
"setEntity",
"(",
"input",
")",
";",
"postRequest",
".",
"addHeader",
"(",
"\"accept\"",
",",
"\"application/json\"",
")",
";",
"final",
"String",
"gsResponse",
"=",
"HttpUtil",
".",
"executeRequest",
"(",
"postRequest",
",",
"loginInput",
".",
"getLoginTimeout",
"(",
")",
",",
"0",
",",
"null",
")",
";",
"logger",
".",
"debug",
"(",
"\"authenticator-request response: {}\"",
",",
"gsResponse",
")",
";",
"JsonNode",
"jsonNode",
"=",
"mapper",
".",
"readTree",
"(",
"gsResponse",
")",
";",
"// check the success field first",
"if",
"(",
"!",
"jsonNode",
".",
"path",
"(",
"\"success\"",
")",
".",
"asBoolean",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"response = {}\"",
",",
"gsResponse",
")",
";",
"String",
"errorCode",
"=",
"jsonNode",
".",
"path",
"(",
"\"code\"",
")",
".",
"asText",
"(",
")",
";",
"throw",
"new",
"SnowflakeSQLException",
"(",
"SqlState",
".",
"SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION",
",",
"ErrorCode",
".",
"CONNECTION_ERROR",
".",
"getMessageCode",
"(",
")",
",",
"errorCode",
",",
"jsonNode",
".",
"path",
"(",
"\"message\"",
")",
".",
"asText",
"(",
")",
")",
";",
"}",
"// session token is in the data field of the returned json response",
"dataNode",
"=",
"jsonNode",
".",
"path",
"(",
"\"data\"",
")",
";",
"}",
"catch",
"(",
"IOException",
"|",
"URISyntaxException",
"ex",
")",
"{",
"handleFederatedFlowError",
"(",
"loginInput",
",",
"ex",
")",
";",
"}",
"return",
"dataNode",
";",
"}"
] | Query Snowflake to obtain IDP token url and IDP SSO url
@param loginInput
@throws SnowflakeSQLException | [
"Query",
"Snowflake",
"to",
"obtain",
"IDP",
"token",
"url",
"and",
"IDP",
"SSO",
"url"
] | train | https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtil.java#L1287-L1341 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/DatabasesInner.java | DatabasesInner.pauseAsync | public Observable<DatabaseInner> pauseAsync(String resourceGroupName, String serverName, String databaseName) {
"""
Pauses a database.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database to be paused.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return pauseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<DatabaseInner>, DatabaseInner>() {
@Override
public DatabaseInner call(ServiceResponse<DatabaseInner> response) {
return response.body();
}
});
} | java | public Observable<DatabaseInner> pauseAsync(String resourceGroupName, String serverName, String databaseName) {
return pauseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<DatabaseInner>, DatabaseInner>() {
@Override
public DatabaseInner call(ServiceResponse<DatabaseInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DatabaseInner",
">",
"pauseAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
")",
"{",
"return",
"pauseWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
"databaseName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"DatabaseInner",
">",
",",
"DatabaseInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"DatabaseInner",
"call",
"(",
"ServiceResponse",
"<",
"DatabaseInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Pauses a database.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database to be paused.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Pauses",
"a",
"database",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/DatabasesInner.java#L1125-L1132 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/db/event/UpdateOnCloseHandler.java | UpdateOnCloseHandler.doRecordChange | public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) {
"""
Called when a change in 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 changeType The type of change that occurred.
@param bDisplayOption If true, display any changes.
@return an error code.
Synchronize records after an update or add.
""" // Read a valid record
int iErrorCode = super.doRecordChange(field, iChangeType, bDisplayOption); // Initialize the record
if (iErrorCode != DBConstants.NORMAL_RETURN)
return iErrorCode;
if (m_bUpdateOnUpdate)
if ((iChangeType == DBConstants.AFTER_UPDATE_TYPE)
|| (iChangeType == DBConstants.AFTER_ADD_TYPE))
return this.writeAndRefresh();
if (iChangeType == DBConstants.BEFORE_FREE_TYPE)
if (m_bUpdateOnClose)
this.writeAndRefresh();
return iErrorCode;
} | java | public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption)
{ // Read a valid record
int iErrorCode = super.doRecordChange(field, iChangeType, bDisplayOption); // Initialize the record
if (iErrorCode != DBConstants.NORMAL_RETURN)
return iErrorCode;
if (m_bUpdateOnUpdate)
if ((iChangeType == DBConstants.AFTER_UPDATE_TYPE)
|| (iChangeType == DBConstants.AFTER_ADD_TYPE))
return this.writeAndRefresh();
if (iChangeType == DBConstants.BEFORE_FREE_TYPE)
if (m_bUpdateOnClose)
this.writeAndRefresh();
return iErrorCode;
} | [
"public",
"int",
"doRecordChange",
"(",
"FieldInfo",
"field",
",",
"int",
"iChangeType",
",",
"boolean",
"bDisplayOption",
")",
"{",
"// Read a valid record",
"int",
"iErrorCode",
"=",
"super",
".",
"doRecordChange",
"(",
"field",
",",
"iChangeType",
",",
"bDisplayOption",
")",
";",
"// Initialize the record",
"if",
"(",
"iErrorCode",
"!=",
"DBConstants",
".",
"NORMAL_RETURN",
")",
"return",
"iErrorCode",
";",
"if",
"(",
"m_bUpdateOnUpdate",
")",
"if",
"(",
"(",
"iChangeType",
"==",
"DBConstants",
".",
"AFTER_UPDATE_TYPE",
")",
"||",
"(",
"iChangeType",
"==",
"DBConstants",
".",
"AFTER_ADD_TYPE",
")",
")",
"return",
"this",
".",
"writeAndRefresh",
"(",
")",
";",
"if",
"(",
"iChangeType",
"==",
"DBConstants",
".",
"BEFORE_FREE_TYPE",
")",
"if",
"(",
"m_bUpdateOnClose",
")",
"this",
".",
"writeAndRefresh",
"(",
")",
";",
"return",
"iErrorCode",
";",
"}"
] | Called when a change in 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 changeType The type of change that occurred.
@param bDisplayOption If true, display any changes.
@return an error code.
Synchronize records after an update or add. | [
"Called",
"when",
"a",
"change",
"in",
"the",
"record",
"status",
"is",
"about",
"to",
"happen",
"/",
"has",
"happened",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/event/UpdateOnCloseHandler.java#L143-L156 |
PawelAdamski/HttpClientMock | src/main/java/com/github/paweladamski/httpclientmock/HttpClientResponseBuilder.java | HttpClientResponseBuilder.withCookie | public HttpClientResponseBuilder withCookie(String cookieName, String cookieValue) {
"""
Sets response cookie
@param cookieName cookie name
@param cookieValue cookie value
@return response builder
"""
Action lastAction = newRule.getLastAction();
CookieAction cookieAction = new CookieAction(lastAction, cookieName, cookieValue);
newRule.overrideLastAction(cookieAction);
return this;
} | java | public HttpClientResponseBuilder withCookie(String cookieName, String cookieValue) {
Action lastAction = newRule.getLastAction();
CookieAction cookieAction = new CookieAction(lastAction, cookieName, cookieValue);
newRule.overrideLastAction(cookieAction);
return this;
} | [
"public",
"HttpClientResponseBuilder",
"withCookie",
"(",
"String",
"cookieName",
",",
"String",
"cookieValue",
")",
"{",
"Action",
"lastAction",
"=",
"newRule",
".",
"getLastAction",
"(",
")",
";",
"CookieAction",
"cookieAction",
"=",
"new",
"CookieAction",
"(",
"lastAction",
",",
"cookieName",
",",
"cookieValue",
")",
";",
"newRule",
".",
"overrideLastAction",
"(",
"cookieAction",
")",
";",
"return",
"this",
";",
"}"
] | Sets response cookie
@param cookieName cookie name
@param cookieValue cookie value
@return response builder | [
"Sets",
"response",
"cookie"
] | train | https://github.com/PawelAdamski/HttpClientMock/blob/0205498434bbc0c78c187a51181cac9b266a28fb/src/main/java/com/github/paweladamski/httpclientmock/HttpClientResponseBuilder.java#L54-L59 |
xcesco/kripton | kripton/src/main/java/com/abubusoft/kripton/xml/XMLSerializer.java | XMLSerializer.setProperty | public void setProperty(String name, Object value) throws IllegalArgumentException, IllegalStateException {
"""
Sets the property.
@param name the name
@param value the value
@throws IllegalArgumentException the illegal argument exception
@throws IllegalStateException the illegal state exception
"""
if (name == null) {
throw new IllegalArgumentException("property name can not be null");
}
if (PROPERTY_SERIALIZER_INDENTATION.equals(name)) {
indentationString = (String) value;
} else if (PROPERTY_SERIALIZER_LINE_SEPARATOR.equals(name)) {
lineSeparator = (String) value;
} else if (PROPERTY_LOCATION.equals(name)) {
location = (String) value;
} else {
throw new IllegalStateException("unsupported property " + name);
}
writeLineSepartor = lineSeparator != null && lineSeparator.length() > 0;
writeIndentation = indentationString != null && indentationString.length() > 0;
// optimize - do not write when nothing to write ...
doIndent = indentationString != null && (writeLineSepartor || writeIndentation);
// NOTE: when indentationString == null there is no indentation
// (even though writeLineSeparator may be true ...)
rebuildIndentationBuf();
seenTag = false; // for consistency
} | java | public void setProperty(String name, Object value) throws IllegalArgumentException, IllegalStateException {
if (name == null) {
throw new IllegalArgumentException("property name can not be null");
}
if (PROPERTY_SERIALIZER_INDENTATION.equals(name)) {
indentationString = (String) value;
} else if (PROPERTY_SERIALIZER_LINE_SEPARATOR.equals(name)) {
lineSeparator = (String) value;
} else if (PROPERTY_LOCATION.equals(name)) {
location = (String) value;
} else {
throw new IllegalStateException("unsupported property " + name);
}
writeLineSepartor = lineSeparator != null && lineSeparator.length() > 0;
writeIndentation = indentationString != null && indentationString.length() > 0;
// optimize - do not write when nothing to write ...
doIndent = indentationString != null && (writeLineSepartor || writeIndentation);
// NOTE: when indentationString == null there is no indentation
// (even though writeLineSeparator may be true ...)
rebuildIndentationBuf();
seenTag = false; // for consistency
} | [
"public",
"void",
"setProperty",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"throws",
"IllegalArgumentException",
",",
"IllegalStateException",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"property name can not be null\"",
")",
";",
"}",
"if",
"(",
"PROPERTY_SERIALIZER_INDENTATION",
".",
"equals",
"(",
"name",
")",
")",
"{",
"indentationString",
"=",
"(",
"String",
")",
"value",
";",
"}",
"else",
"if",
"(",
"PROPERTY_SERIALIZER_LINE_SEPARATOR",
".",
"equals",
"(",
"name",
")",
")",
"{",
"lineSeparator",
"=",
"(",
"String",
")",
"value",
";",
"}",
"else",
"if",
"(",
"PROPERTY_LOCATION",
".",
"equals",
"(",
"name",
")",
")",
"{",
"location",
"=",
"(",
"String",
")",
"value",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"unsupported property \"",
"+",
"name",
")",
";",
"}",
"writeLineSepartor",
"=",
"lineSeparator",
"!=",
"null",
"&&",
"lineSeparator",
".",
"length",
"(",
")",
">",
"0",
";",
"writeIndentation",
"=",
"indentationString",
"!=",
"null",
"&&",
"indentationString",
".",
"length",
"(",
")",
">",
"0",
";",
"// optimize - do not write when nothing to write ...",
"doIndent",
"=",
"indentationString",
"!=",
"null",
"&&",
"(",
"writeLineSepartor",
"||",
"writeIndentation",
")",
";",
"// NOTE: when indentationString == null there is no indentation",
"// (even though writeLineSeparator may be true ...)",
"rebuildIndentationBuf",
"(",
")",
";",
"seenTag",
"=",
"false",
";",
"// for consistency",
"}"
] | Sets the property.
@param name the name
@param value the value
@throws IllegalArgumentException the illegal argument exception
@throws IllegalStateException the illegal state exception | [
"Sets",
"the",
"property",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton/src/main/java/com/abubusoft/kripton/xml/XMLSerializer.java#L440-L461 |
kiegroup/droolsjbpm-integration | kie-server-parent/kie-server-controller/kie-server-controller-client/src/main/java/org/kie/server/controller/client/KieServerControllerClientFactory.java | KieServerControllerClientFactory.newRestClient | public static KieServerControllerClient newRestClient(final String controllerUrl,
final String login,
final String password) {
"""
Creates a new Kie Controller Client using REST based service
@param controllerUrl the URL to the server (e.g.: "http://localhost:8080/kie-server-controller/rest/controller")
@param login user login
@param password user password
@return client instance
"""
return new RestKieServerControllerClient(controllerUrl,
login,
password);
} | java | public static KieServerControllerClient newRestClient(final String controllerUrl,
final String login,
final String password) {
return new RestKieServerControllerClient(controllerUrl,
login,
password);
} | [
"public",
"static",
"KieServerControllerClient",
"newRestClient",
"(",
"final",
"String",
"controllerUrl",
",",
"final",
"String",
"login",
",",
"final",
"String",
"password",
")",
"{",
"return",
"new",
"RestKieServerControllerClient",
"(",
"controllerUrl",
",",
"login",
",",
"password",
")",
";",
"}"
] | Creates a new Kie Controller Client using REST based service
@param controllerUrl the URL to the server (e.g.: "http://localhost:8080/kie-server-controller/rest/controller")
@param login user login
@param password user password
@return client instance | [
"Creates",
"a",
"new",
"Kie",
"Controller",
"Client",
"using",
"REST",
"based",
"service"
] | train | https://github.com/kiegroup/droolsjbpm-integration/blob/6c26200ab03855dbb92b56ca0c6363cdec0eaf2c/kie-server-parent/kie-server-controller/kie-server-controller-client/src/main/java/org/kie/server/controller/client/KieServerControllerClientFactory.java#L38-L44 |
apache/groovy | src/main/java/org/apache/groovy/ast/tools/ClassNodeUtils.java | ClassNodeUtils.addDeclaredMethodsFromInterfaces | public static void addDeclaredMethodsFromInterfaces(ClassNode cNode, Map<String, MethodNode> methodsMap) {
"""
Add in methods from all interfaces. Existing entries in the methods map take precedence.
Methods from interfaces visited early take precedence over later ones.
@param cNode The ClassNode
@param methodsMap A map of existing methods to alter
"""
// add in unimplemented abstract methods from the interfaces
for (ClassNode iface : cNode.getInterfaces()) {
Map<String, MethodNode> ifaceMethodsMap = iface.getDeclaredMethodsMap();
for (Map.Entry<String, MethodNode> entry : ifaceMethodsMap.entrySet()) {
String methSig = entry.getKey();
if (!methodsMap.containsKey(methSig)) {
methodsMap.put(methSig, entry.getValue());
}
}
}
} | java | public static void addDeclaredMethodsFromInterfaces(ClassNode cNode, Map<String, MethodNode> methodsMap) {
// add in unimplemented abstract methods from the interfaces
for (ClassNode iface : cNode.getInterfaces()) {
Map<String, MethodNode> ifaceMethodsMap = iface.getDeclaredMethodsMap();
for (Map.Entry<String, MethodNode> entry : ifaceMethodsMap.entrySet()) {
String methSig = entry.getKey();
if (!methodsMap.containsKey(methSig)) {
methodsMap.put(methSig, entry.getValue());
}
}
}
} | [
"public",
"static",
"void",
"addDeclaredMethodsFromInterfaces",
"(",
"ClassNode",
"cNode",
",",
"Map",
"<",
"String",
",",
"MethodNode",
">",
"methodsMap",
")",
"{",
"// add in unimplemented abstract methods from the interfaces",
"for",
"(",
"ClassNode",
"iface",
":",
"cNode",
".",
"getInterfaces",
"(",
")",
")",
"{",
"Map",
"<",
"String",
",",
"MethodNode",
">",
"ifaceMethodsMap",
"=",
"iface",
".",
"getDeclaredMethodsMap",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"MethodNode",
">",
"entry",
":",
"ifaceMethodsMap",
".",
"entrySet",
"(",
")",
")",
"{",
"String",
"methSig",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"if",
"(",
"!",
"methodsMap",
".",
"containsKey",
"(",
"methSig",
")",
")",
"{",
"methodsMap",
".",
"put",
"(",
"methSig",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"}",
"}"
] | Add in methods from all interfaces. Existing entries in the methods map take precedence.
Methods from interfaces visited early take precedence over later ones.
@param cNode The ClassNode
@param methodsMap A map of existing methods to alter | [
"Add",
"in",
"methods",
"from",
"all",
"interfaces",
".",
"Existing",
"entries",
"in",
"the",
"methods",
"map",
"take",
"precedence",
".",
"Methods",
"from",
"interfaces",
"visited",
"early",
"take",
"precedence",
"over",
"later",
"ones",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/apache/groovy/ast/tools/ClassNodeUtils.java#L158-L169 |
kiegroup/jbpm | jbpm-bpmn2-emfextmodel/src/main/java/org/omg/spec/bpmn/non/normative/color/util/ColorValidator.java | ColorValidator.validateHexColor_Pattern | public boolean validateHexColor_Pattern(String hexColor, DiagnosticChain diagnostics, Map<Object, Object> context) {
"""
Validates the Pattern constraint of '<em>Hex Color</em>'.
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated
"""
return validatePattern(ColorPackage.Literals.HEX_COLOR, hexColor, HEX_COLOR__PATTERN__VALUES, diagnostics, context);
} | java | public boolean validateHexColor_Pattern(String hexColor, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validatePattern(ColorPackage.Literals.HEX_COLOR, hexColor, HEX_COLOR__PATTERN__VALUES, diagnostics, context);
} | [
"public",
"boolean",
"validateHexColor_Pattern",
"(",
"String",
"hexColor",
",",
"DiagnosticChain",
"diagnostics",
",",
"Map",
"<",
"Object",
",",
"Object",
">",
"context",
")",
"{",
"return",
"validatePattern",
"(",
"ColorPackage",
".",
"Literals",
".",
"HEX_COLOR",
",",
"hexColor",
",",
"HEX_COLOR__PATTERN__VALUES",
",",
"diagnostics",
",",
"context",
")",
";",
"}"
] | Validates the Pattern constraint of '<em>Hex Color</em>'.
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated | [
"Validates",
"the",
"Pattern",
"constraint",
"of",
"<em",
">",
"Hex",
"Color<",
"/",
"em",
">",
".",
"<!",
"--",
"begin",
"-",
"user",
"-",
"doc",
"--",
">",
"<!",
"--",
"end",
"-",
"user",
"-",
"doc",
"--",
">"
] | train | https://github.com/kiegroup/jbpm/blob/c3473c728aa382ebbea01e380c5e754a96647b82/jbpm-bpmn2-emfextmodel/src/main/java/org/omg/spec/bpmn/non/normative/color/util/ColorValidator.java#L162-L164 |
threerings/gwt-utils | src/main/java/com/threerings/gwt/ui/Bindings.java | Bindings.bindText | public static void bindText (final Value<String> value, final TextBoxBase text) {
"""
Binds the contents of the supplied text box to the supplied string value. The binding is
multidirectional, i.e. changes to the value will update the text box and changes to the text
box will update the value. The value is updated on key up as well as on change so that both
keyboard initiated changes and non-keyboard initiated changes (paste) are handled.
"""
text.addKeyUpHandler(new KeyUpHandler() {
public void onKeyUp (KeyUpEvent event) {
value.updateIf(((TextBoxBase)event.getSource()).getText());
}
});
text.addChangeHandler(new ChangeHandler() {
public void onChange (ChangeEvent event) {
value.updateIf(((TextBoxBase)event.getSource()).getText());
}
});
bindLabel(value, text);
} | java | public static void bindText (final Value<String> value, final TextBoxBase text)
{
text.addKeyUpHandler(new KeyUpHandler() {
public void onKeyUp (KeyUpEvent event) {
value.updateIf(((TextBoxBase)event.getSource()).getText());
}
});
text.addChangeHandler(new ChangeHandler() {
public void onChange (ChangeEvent event) {
value.updateIf(((TextBoxBase)event.getSource()).getText());
}
});
bindLabel(value, text);
} | [
"public",
"static",
"void",
"bindText",
"(",
"final",
"Value",
"<",
"String",
">",
"value",
",",
"final",
"TextBoxBase",
"text",
")",
"{",
"text",
".",
"addKeyUpHandler",
"(",
"new",
"KeyUpHandler",
"(",
")",
"{",
"public",
"void",
"onKeyUp",
"(",
"KeyUpEvent",
"event",
")",
"{",
"value",
".",
"updateIf",
"(",
"(",
"(",
"TextBoxBase",
")",
"event",
".",
"getSource",
"(",
")",
")",
".",
"getText",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"text",
".",
"addChangeHandler",
"(",
"new",
"ChangeHandler",
"(",
")",
"{",
"public",
"void",
"onChange",
"(",
"ChangeEvent",
"event",
")",
"{",
"value",
".",
"updateIf",
"(",
"(",
"(",
"TextBoxBase",
")",
"event",
".",
"getSource",
"(",
")",
")",
".",
"getText",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"bindLabel",
"(",
"value",
",",
"text",
")",
";",
"}"
] | Binds the contents of the supplied text box to the supplied string value. The binding is
multidirectional, i.e. changes to the value will update the text box and changes to the text
box will update the value. The value is updated on key up as well as on change so that both
keyboard initiated changes and non-keyboard initiated changes (paste) are handled. | [
"Binds",
"the",
"contents",
"of",
"the",
"supplied",
"text",
"box",
"to",
"the",
"supplied",
"string",
"value",
".",
"The",
"binding",
"is",
"multidirectional",
"i",
".",
"e",
".",
"changes",
"to",
"the",
"value",
"will",
"update",
"the",
"text",
"box",
"and",
"changes",
"to",
"the",
"text",
"box",
"will",
"update",
"the",
"value",
".",
"The",
"value",
"is",
"updated",
"on",
"key",
"up",
"as",
"well",
"as",
"on",
"change",
"so",
"that",
"both",
"keyboard",
"initiated",
"changes",
"and",
"non",
"-",
"keyboard",
"initiated",
"changes",
"(",
"paste",
")",
"are",
"handled",
"."
] | train | https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/Bindings.java#L162-L175 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java | ReviewsImpl.getVideoFrames | public Frames getVideoFrames(String teamName, String reviewId, GetVideoFramesOptionalParameter getVideoFramesOptionalParameter) {
"""
The reviews created would show up for Reviewers on your team. As Reviewers complete reviewing, results of the Review would be POSTED (i.e. HTTP POST) on the specified CallBackEndpoint.
<h3>CallBack Schemas </h3>
<h4>Review Completion CallBack Sample</h4>
<p>
{<br/>
"ReviewId": "<Review Id>",<br/>
"ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/>
"ModifiedBy": "<Name of the Reviewer>",<br/>
"CallBackType": "Review",<br/>
"ContentId": "<The ContentId that was specified input>",<br/>
"Metadata": {<br/>
"adultscore": "0.xxx",<br/>
"a": "False",<br/>
"racyscore": "0.xxx",<br/>
"r": "True"<br/>
},<br/>
"ReviewerResultTags": {<br/>
"a": "False",<br/>
"r": "True"<br/>
}<br/>
}<br/>
</p>.
@param teamName Your team name.
@param reviewId Id of the review.
@param getVideoFramesOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@throws APIErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the Frames object if successful.
"""
return getVideoFramesWithServiceResponseAsync(teamName, reviewId, getVideoFramesOptionalParameter).toBlocking().single().body();
} | java | public Frames getVideoFrames(String teamName, String reviewId, GetVideoFramesOptionalParameter getVideoFramesOptionalParameter) {
return getVideoFramesWithServiceResponseAsync(teamName, reviewId, getVideoFramesOptionalParameter).toBlocking().single().body();
} | [
"public",
"Frames",
"getVideoFrames",
"(",
"String",
"teamName",
",",
"String",
"reviewId",
",",
"GetVideoFramesOptionalParameter",
"getVideoFramesOptionalParameter",
")",
"{",
"return",
"getVideoFramesWithServiceResponseAsync",
"(",
"teamName",
",",
"reviewId",
",",
"getVideoFramesOptionalParameter",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | The reviews created would show up for Reviewers on your team. As Reviewers complete reviewing, results of the Review would be POSTED (i.e. HTTP POST) on the specified CallBackEndpoint.
<h3>CallBack Schemas </h3>
<h4>Review Completion CallBack Sample</h4>
<p>
{<br/>
"ReviewId": "<Review Id>",<br/>
"ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/>
"ModifiedBy": "<Name of the Reviewer>",<br/>
"CallBackType": "Review",<br/>
"ContentId": "<The ContentId that was specified input>",<br/>
"Metadata": {<br/>
"adultscore": "0.xxx",<br/>
"a": "False",<br/>
"racyscore": "0.xxx",<br/>
"r": "True"<br/>
},<br/>
"ReviewerResultTags": {<br/>
"a": "False",<br/>
"r": "True"<br/>
}<br/>
}<br/>
</p>.
@param teamName Your team name.
@param reviewId Id of the review.
@param getVideoFramesOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@throws APIErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the Frames object if successful. | [
"The",
"reviews",
"created",
"would",
"show",
"up",
"for",
"Reviewers",
"on",
"your",
"team",
".",
"As",
"Reviewers",
"complete",
"reviewing",
"results",
"of",
"the",
"Review",
"would",
"be",
"POSTED",
"(",
"i",
".",
"e",
".",
"HTTP",
"POST",
")",
"on",
"the",
"specified",
"CallBackEndpoint",
".",
"<",
";",
"h3>",
";",
"CallBack",
"Schemas",
"<",
";",
"/",
"h3>",
";",
"<",
";",
"h4>",
";",
"Review",
"Completion",
"CallBack",
"Sample<",
";",
"/",
"h4>",
";",
"<",
";",
"p>",
";",
"{",
"<",
";",
"br",
"/",
">",
";",
"ReviewId",
":",
"<",
";",
"Review",
"Id>",
";",
"<",
";",
"br",
"/",
">",
";",
"ModifiedOn",
":",
"2016",
"-",
"10",
"-",
"11T22",
":",
"36",
":",
"32",
".",
"9934851Z",
"<",
";",
"br",
"/",
">",
";",
"ModifiedBy",
":",
"<",
";",
"Name",
"of",
"the",
"Reviewer>",
";",
"<",
";",
"br",
"/",
">",
";",
"CallBackType",
":",
"Review",
"<",
";",
"br",
"/",
">",
";",
"ContentId",
":",
"<",
";",
"The",
"ContentId",
"that",
"was",
"specified",
"input>",
";",
"<",
";",
"br",
"/",
">",
";",
"Metadata",
":",
"{",
"<",
";",
"br",
"/",
">",
";",
"adultscore",
":",
"0",
".",
"xxx",
"<",
";",
"br",
"/",
">",
";",
"a",
":",
"False",
"<",
";",
"br",
"/",
">",
";",
"racyscore",
":",
"0",
".",
"xxx",
"<",
";",
"br",
"/",
">",
";",
"r",
":",
"True",
"<",
";",
"br",
"/",
">",
";",
"}",
"<",
";",
"br",
"/",
">",
";",
"ReviewerResultTags",
":",
"{",
"<",
";",
"br",
"/",
">",
";",
"a",
":",
"False",
"<",
";",
"br",
"/",
">",
";",
"r",
":",
"True",
"<",
";",
"br",
"/",
">",
";",
"}",
"<",
";",
"br",
"/",
">",
";",
"}",
"<",
";",
"br",
"/",
">",
";",
"<",
";",
"/",
"p>",
";",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java#L1342-L1344 |
codelibs/fess | src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java | FessMessages.addErrorsPropertyTypeDouble | public FessMessages addErrorsPropertyTypeDouble(String property, String arg0) {
"""
Add the created action message for the key 'errors.property_type_double' with parameters.
<pre>
message: {0} should be numeric.
</pre>
@param property The property name for the message. (NotNull)
@param arg0 The parameter arg0 for message. (NotNull)
@return this. (NotNull)
"""
assertPropertyNotNull(property);
add(property, new UserMessage(ERRORS_property_type_double, arg0));
return this;
} | java | public FessMessages addErrorsPropertyTypeDouble(String property, String arg0) {
assertPropertyNotNull(property);
add(property, new UserMessage(ERRORS_property_type_double, arg0));
return this;
} | [
"public",
"FessMessages",
"addErrorsPropertyTypeDouble",
"(",
"String",
"property",
",",
"String",
"arg0",
")",
"{",
"assertPropertyNotNull",
"(",
"property",
")",
";",
"add",
"(",
"property",
",",
"new",
"UserMessage",
"(",
"ERRORS_property_type_double",
",",
"arg0",
")",
")",
";",
"return",
"this",
";",
"}"
] | Add the created action message for the key 'errors.property_type_double' with parameters.
<pre>
message: {0} should be numeric.
</pre>
@param property The property name for the message. (NotNull)
@param arg0 The parameter arg0 for message. (NotNull)
@return this. (NotNull) | [
"Add",
"the",
"created",
"action",
"message",
"for",
"the",
"key",
"errors",
".",
"property_type_double",
"with",
"parameters",
".",
"<pre",
">",
"message",
":",
"{",
"0",
"}",
"should",
"be",
"numeric",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L2245-L2249 |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/util/BooleanExpressionParser.java | BooleanExpressionParser.parseNonDigits | private static String parseNonDigits(final String expression, final int startIndex) {
"""
This method reads non-digit characters from a given string, starting at a given index.
It will read till the end of the string or up until it encounters
<p>
- a digit
- a separator token
@param expression The string to parse
@param startIndex The start index from where to parse
@return The parsed substring
"""
final StringBuilder operatorBuffer = new StringBuilder();
char currentCharacter = expression.charAt(startIndex);
int subExpressionIndex = startIndex;
do {
operatorBuffer.append(currentCharacter);
subExpressionIndex++;
if (subExpressionIndex < expression.length()) {
currentCharacter = expression.charAt(subExpressionIndex);
}
} while (subExpressionIndex < expression.length() && !Character.isDigit(currentCharacter) && !isSeparatorToken(currentCharacter));
return operatorBuffer.toString();
} | java | private static String parseNonDigits(final String expression, final int startIndex) {
final StringBuilder operatorBuffer = new StringBuilder();
char currentCharacter = expression.charAt(startIndex);
int subExpressionIndex = startIndex;
do {
operatorBuffer.append(currentCharacter);
subExpressionIndex++;
if (subExpressionIndex < expression.length()) {
currentCharacter = expression.charAt(subExpressionIndex);
}
} while (subExpressionIndex < expression.length() && !Character.isDigit(currentCharacter) && !isSeparatorToken(currentCharacter));
return operatorBuffer.toString();
} | [
"private",
"static",
"String",
"parseNonDigits",
"(",
"final",
"String",
"expression",
",",
"final",
"int",
"startIndex",
")",
"{",
"final",
"StringBuilder",
"operatorBuffer",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"char",
"currentCharacter",
"=",
"expression",
".",
"charAt",
"(",
"startIndex",
")",
";",
"int",
"subExpressionIndex",
"=",
"startIndex",
";",
"do",
"{",
"operatorBuffer",
".",
"append",
"(",
"currentCharacter",
")",
";",
"subExpressionIndex",
"++",
";",
"if",
"(",
"subExpressionIndex",
"<",
"expression",
".",
"length",
"(",
")",
")",
"{",
"currentCharacter",
"=",
"expression",
".",
"charAt",
"(",
"subExpressionIndex",
")",
";",
"}",
"}",
"while",
"(",
"subExpressionIndex",
"<",
"expression",
".",
"length",
"(",
")",
"&&",
"!",
"Character",
".",
"isDigit",
"(",
"currentCharacter",
")",
"&&",
"!",
"isSeparatorToken",
"(",
"currentCharacter",
")",
")",
";",
"return",
"operatorBuffer",
".",
"toString",
"(",
")",
";",
"}"
] | This method reads non-digit characters from a given string, starting at a given index.
It will read till the end of the string or up until it encounters
<p>
- a digit
- a separator token
@param expression The string to parse
@param startIndex The start index from where to parse
@return The parsed substring | [
"This",
"method",
"reads",
"non",
"-",
"digit",
"characters",
"from",
"a",
"given",
"string",
"starting",
"at",
"a",
"given",
"index",
".",
"It",
"will",
"read",
"till",
"the",
"end",
"of",
"the",
"string",
"or",
"up",
"until",
"it",
"encounters",
"<p",
">",
"-",
"a",
"digit",
"-",
"a",
"separator",
"token"
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/util/BooleanExpressionParser.java#L207-L222 |
looly/hutool | hutool-extra/src/main/java/cn/hutool/extra/template/engine/thymeleaf/ThymeleafTemplate.java | ThymeleafTemplate.wrap | public static ThymeleafTemplate wrap(TemplateEngine engine, String template, Charset charset) {
"""
包装Thymeleaf模板
@param engine Thymeleaf的模板引擎对象 {@link TemplateEngine}
@param template 模板路径或模板内容
@param charset 编码
@return {@link ThymeleafTemplate}
"""
return (null == engine) ? null : new ThymeleafTemplate(engine, template, charset);
} | java | public static ThymeleafTemplate wrap(TemplateEngine engine, String template, Charset charset) {
return (null == engine) ? null : new ThymeleafTemplate(engine, template, charset);
} | [
"public",
"static",
"ThymeleafTemplate",
"wrap",
"(",
"TemplateEngine",
"engine",
",",
"String",
"template",
",",
"Charset",
"charset",
")",
"{",
"return",
"(",
"null",
"==",
"engine",
")",
"?",
"null",
":",
"new",
"ThymeleafTemplate",
"(",
"engine",
",",
"template",
",",
"charset",
")",
";",
"}"
] | 包装Thymeleaf模板
@param engine Thymeleaf的模板引擎对象 {@link TemplateEngine}
@param template 模板路径或模板内容
@param charset 编码
@return {@link ThymeleafTemplate} | [
"包装Thymeleaf模板"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/template/engine/thymeleaf/ThymeleafTemplate.java#L41-L43 |
antopen/alipay-sdk-java | src/main/java/com/alipay/api/internal/util/XmlUtils.java | XmlUtils.saveToXml | public static void saveToXml(Node doc, File file) throws AlipayApiException {
"""
Saves the node/document/element as XML file.
@param doc the XML node/document/element to save
@param file the XML file to save
@throws ApiException problem persisting XML file
"""
OutputStream out = null;
try {
Transformer tf = TransformerFactory.newInstance().newTransformer();
Properties props = tf.getOutputProperties();
props.setProperty(OutputKeys.METHOD, XMLConstants.XML_NS_PREFIX);
props.setProperty(OutputKeys.INDENT, LOGIC_YES);
tf.setOutputProperties(props);
DOMSource dom = new DOMSource(doc);
out = getOutputStream(file);
Result result = new StreamResult(out);
tf.transform(dom, result);
} catch (TransformerException e) {
throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// nothing to do
}
}
}
} | java | public static void saveToXml(Node doc, File file) throws AlipayApiException {
OutputStream out = null;
try {
Transformer tf = TransformerFactory.newInstance().newTransformer();
Properties props = tf.getOutputProperties();
props.setProperty(OutputKeys.METHOD, XMLConstants.XML_NS_PREFIX);
props.setProperty(OutputKeys.INDENT, LOGIC_YES);
tf.setOutputProperties(props);
DOMSource dom = new DOMSource(doc);
out = getOutputStream(file);
Result result = new StreamResult(out);
tf.transform(dom, result);
} catch (TransformerException e) {
throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// nothing to do
}
}
}
} | [
"public",
"static",
"void",
"saveToXml",
"(",
"Node",
"doc",
",",
"File",
"file",
")",
"throws",
"AlipayApiException",
"{",
"OutputStream",
"out",
"=",
"null",
";",
"try",
"{",
"Transformer",
"tf",
"=",
"TransformerFactory",
".",
"newInstance",
"(",
")",
".",
"newTransformer",
"(",
")",
";",
"Properties",
"props",
"=",
"tf",
".",
"getOutputProperties",
"(",
")",
";",
"props",
".",
"setProperty",
"(",
"OutputKeys",
".",
"METHOD",
",",
"XMLConstants",
".",
"XML_NS_PREFIX",
")",
";",
"props",
".",
"setProperty",
"(",
"OutputKeys",
".",
"INDENT",
",",
"LOGIC_YES",
")",
";",
"tf",
".",
"setOutputProperties",
"(",
"props",
")",
";",
"DOMSource",
"dom",
"=",
"new",
"DOMSource",
"(",
"doc",
")",
";",
"out",
"=",
"getOutputStream",
"(",
"file",
")",
";",
"Result",
"result",
"=",
"new",
"StreamResult",
"(",
"out",
")",
";",
"tf",
".",
"transform",
"(",
"dom",
",",
"result",
")",
";",
"}",
"catch",
"(",
"TransformerException",
"e",
")",
"{",
"throw",
"new",
"AlipayApiException",
"(",
"\"XML_TRANSFORM_ERROR\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"out",
"!=",
"null",
")",
"{",
"try",
"{",
"out",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"// nothing to do",
"}",
"}",
"}",
"}"
] | Saves the node/document/element as XML file.
@param doc the XML node/document/element to save
@param file the XML file to save
@throws ApiException problem persisting XML file | [
"Saves",
"the",
"node",
"/",
"document",
"/",
"element",
"as",
"XML",
"file",
"."
] | train | https://github.com/antopen/alipay-sdk-java/blob/e82aeac7d0239330ee173c7e393596e51e41c1cd/src/main/java/com/alipay/api/internal/util/XmlUtils.java#L489-L515 |
jeremybrooks/jinx | src/main/java/net/jeremybrooks/jinx/api/PlacesApi.java | PlacesApi.getChildrenWithPhotosPublic | public Places getChildrenWithPhotosPublic(String placeId, String woeId) throws JinxException {
"""
Return a list of locations with public photos that are parented by a Where on Earth (WOE) or Places ID.
Authentication
<p>
This method does not require authentication.
<p>
You must provide a valid placesId or woeId. If you provide both, the placesId will be used.
<p>
@param placeId a Flickr places Id.
@param woeId a Where On Earth (WOE) id.
@return places with public photos in the specified area.
@throws JinxException if required parameters are missing, or if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.places.getChildrenWithPhotosPublic.html">flickr.places.getChildrenWithPhotosPublic</a>
"""
if (JinxUtils.isNullOrEmpty(placeId)) {
JinxUtils.validateParams(woeId);
}
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.places.getChildrenWithPhotosPublic");
if (JinxUtils.isNullOrEmpty(placeId)) {
params.put("woe_id", woeId);
} else {
params.put("place_id", placeId);
}
return jinx.flickrGet(params, Places.class, false);
} | java | public Places getChildrenWithPhotosPublic(String placeId, String woeId) throws JinxException {
if (JinxUtils.isNullOrEmpty(placeId)) {
JinxUtils.validateParams(woeId);
}
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.places.getChildrenWithPhotosPublic");
if (JinxUtils.isNullOrEmpty(placeId)) {
params.put("woe_id", woeId);
} else {
params.put("place_id", placeId);
}
return jinx.flickrGet(params, Places.class, false);
} | [
"public",
"Places",
"getChildrenWithPhotosPublic",
"(",
"String",
"placeId",
",",
"String",
"woeId",
")",
"throws",
"JinxException",
"{",
"if",
"(",
"JinxUtils",
".",
"isNullOrEmpty",
"(",
"placeId",
")",
")",
"{",
"JinxUtils",
".",
"validateParams",
"(",
"woeId",
")",
";",
"}",
"Map",
"<",
"String",
",",
"String",
">",
"params",
"=",
"new",
"TreeMap",
"<>",
"(",
")",
";",
"params",
".",
"put",
"(",
"\"method\"",
",",
"\"flickr.places.getChildrenWithPhotosPublic\"",
")",
";",
"if",
"(",
"JinxUtils",
".",
"isNullOrEmpty",
"(",
"placeId",
")",
")",
"{",
"params",
".",
"put",
"(",
"\"woe_id\"",
",",
"woeId",
")",
";",
"}",
"else",
"{",
"params",
".",
"put",
"(",
"\"place_id\"",
",",
"placeId",
")",
";",
"}",
"return",
"jinx",
".",
"flickrGet",
"(",
"params",
",",
"Places",
".",
"class",
",",
"false",
")",
";",
"}"
] | Return a list of locations with public photos that are parented by a Where on Earth (WOE) or Places ID.
Authentication
<p>
This method does not require authentication.
<p>
You must provide a valid placesId or woeId. If you provide both, the placesId will be used.
<p>
@param placeId a Flickr places Id.
@param woeId a Where On Earth (WOE) id.
@return places with public photos in the specified area.
@throws JinxException if required parameters are missing, or if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.places.getChildrenWithPhotosPublic.html">flickr.places.getChildrenWithPhotosPublic</a> | [
"Return",
"a",
"list",
"of",
"locations",
"with",
"public",
"photos",
"that",
"are",
"parented",
"by",
"a",
"Where",
"on",
"Earth",
"(",
"WOE",
")",
"or",
"Places",
"ID",
".",
"Authentication",
"<p",
">",
"This",
"method",
"does",
"not",
"require",
"authentication",
".",
"<p",
">",
"You",
"must",
"provide",
"a",
"valid",
"placesId",
"or",
"woeId",
".",
"If",
"you",
"provide",
"both",
"the",
"placesId",
"will",
"be",
"used",
".",
"<p",
">"
] | train | https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/PlacesApi.java#L128-L140 |
kiegroup/drools | drools-core/src/main/java/org/drools/core/reteoo/TraitObjectTypeNode.java | TraitObjectTypeNode.sameAndNotCoveredByDescendants | private boolean sameAndNotCoveredByDescendants( TraitProxy proxy, BitSet typeMask ) {
"""
Edge case: due to the way traits are encoded, consider this hierarchy:
A B
C
D
On don/insertion of C, C may be vetoed by its parents, but might have been
already covered by one of its descendants (D)
"""
boolean isSameType = typeMask.equals( proxy._getTypeCode() );
if ( isSameType ) {
TraitTypeMap<String,Thing<?>,?> ttm = (TraitTypeMap<String,Thing<?>,?>) proxy.getObject()._getTraitMap();
Collection<Thing<?>> descs = ttm.lowerDescendants( typeMask );
// we have to exclude the "mock" bottom proxy
if ( descs == null || descs.isEmpty() ) {
return true;
} else {
for ( Thing sub : descs ) {
TraitType tt = (TraitType) sub;
if ( tt != proxy && tt._hasTypeCode( typeMask ) ) {
return false;
}
}
return true;
}
} else {
return false;
}
} | java | private boolean sameAndNotCoveredByDescendants( TraitProxy proxy, BitSet typeMask ) {
boolean isSameType = typeMask.equals( proxy._getTypeCode() );
if ( isSameType ) {
TraitTypeMap<String,Thing<?>,?> ttm = (TraitTypeMap<String,Thing<?>,?>) proxy.getObject()._getTraitMap();
Collection<Thing<?>> descs = ttm.lowerDescendants( typeMask );
// we have to exclude the "mock" bottom proxy
if ( descs == null || descs.isEmpty() ) {
return true;
} else {
for ( Thing sub : descs ) {
TraitType tt = (TraitType) sub;
if ( tt != proxy && tt._hasTypeCode( typeMask ) ) {
return false;
}
}
return true;
}
} else {
return false;
}
} | [
"private",
"boolean",
"sameAndNotCoveredByDescendants",
"(",
"TraitProxy",
"proxy",
",",
"BitSet",
"typeMask",
")",
"{",
"boolean",
"isSameType",
"=",
"typeMask",
".",
"equals",
"(",
"proxy",
".",
"_getTypeCode",
"(",
")",
")",
";",
"if",
"(",
"isSameType",
")",
"{",
"TraitTypeMap",
"<",
"String",
",",
"Thing",
"<",
"?",
">",
",",
"?",
">",
"ttm",
"=",
"(",
"TraitTypeMap",
"<",
"String",
",",
"Thing",
"<",
"?",
">",
",",
"?",
">",
")",
"proxy",
".",
"getObject",
"(",
")",
".",
"_getTraitMap",
"(",
")",
";",
"Collection",
"<",
"Thing",
"<",
"?",
">",
">",
"descs",
"=",
"ttm",
".",
"lowerDescendants",
"(",
"typeMask",
")",
";",
"// we have to exclude the \"mock\" bottom proxy",
"if",
"(",
"descs",
"==",
"null",
"||",
"descs",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"else",
"{",
"for",
"(",
"Thing",
"sub",
":",
"descs",
")",
"{",
"TraitType",
"tt",
"=",
"(",
"TraitType",
")",
"sub",
";",
"if",
"(",
"tt",
"!=",
"proxy",
"&&",
"tt",
".",
"_hasTypeCode",
"(",
"typeMask",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Edge case: due to the way traits are encoded, consider this hierarchy:
A B
C
D
On don/insertion of C, C may be vetoed by its parents, but might have been
already covered by one of its descendants (D) | [
"Edge",
"case",
":",
"due",
"to",
"the",
"way",
"traits",
"are",
"encoded",
"consider",
"this",
"hierarchy",
":",
"A",
"B",
"C",
"D",
"On",
"don",
"/",
"insertion",
"of",
"C",
"C",
"may",
"be",
"vetoed",
"by",
"its",
"parents",
"but",
"might",
"have",
"been",
"already",
"covered",
"by",
"one",
"of",
"its",
"descendants",
"(",
"D",
")"
] | train | https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-core/src/main/java/org/drools/core/reteoo/TraitObjectTypeNode.java#L98-L118 |
jcuda/jcudnn | JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java | JCudnn.cudnnRestoreDropoutDescriptor | public static int cudnnRestoreDropoutDescriptor(
cudnnDropoutDescriptor dropoutDesc,
cudnnHandle handle,
float dropout,
Pointer states,
long stateSizeInBytes,
long seed) {
"""
Restores the dropout descriptor to a previously saved-off state
"""
return checkResult(cudnnRestoreDropoutDescriptorNative(dropoutDesc, handle, dropout, states, stateSizeInBytes, seed));
} | java | public static int cudnnRestoreDropoutDescriptor(
cudnnDropoutDescriptor dropoutDesc,
cudnnHandle handle,
float dropout,
Pointer states,
long stateSizeInBytes,
long seed)
{
return checkResult(cudnnRestoreDropoutDescriptorNative(dropoutDesc, handle, dropout, states, stateSizeInBytes, seed));
} | [
"public",
"static",
"int",
"cudnnRestoreDropoutDescriptor",
"(",
"cudnnDropoutDescriptor",
"dropoutDesc",
",",
"cudnnHandle",
"handle",
",",
"float",
"dropout",
",",
"Pointer",
"states",
",",
"long",
"stateSizeInBytes",
",",
"long",
"seed",
")",
"{",
"return",
"checkResult",
"(",
"cudnnRestoreDropoutDescriptorNative",
"(",
"dropoutDesc",
",",
"handle",
",",
"dropout",
",",
"states",
",",
"stateSizeInBytes",
",",
"seed",
")",
")",
";",
"}"
] | Restores the dropout descriptor to a previously saved-off state | [
"Restores",
"the",
"dropout",
"descriptor",
"to",
"a",
"previously",
"saved",
"-",
"off",
"state"
] | train | https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L2802-L2811 |
GoogleCloudPlatform/bigdata-interop | bigquery/src/main/java/com/google/cloud/hadoop/io/bigquery/BigQueryFactory.java | BigQueryFactory.getBigQuery | public Bigquery getBigQuery(Configuration config)
throws GeneralSecurityException, IOException {
"""
Constructs a BigQuery from the credential constructed from the environment.
@throws IOException on IO Error.
@throws GeneralSecurityException on General Security Error.
"""
logger.atInfo().log("Creating BigQuery from default credential.");
Credential credential = createBigQueryCredential(config);
// Use the credential to create an authorized BigQuery client
return getBigQueryFromCredential(credential, BQC_ID);
} | java | public Bigquery getBigQuery(Configuration config)
throws GeneralSecurityException, IOException {
logger.atInfo().log("Creating BigQuery from default credential.");
Credential credential = createBigQueryCredential(config);
// Use the credential to create an authorized BigQuery client
return getBigQueryFromCredential(credential, BQC_ID);
} | [
"public",
"Bigquery",
"getBigQuery",
"(",
"Configuration",
"config",
")",
"throws",
"GeneralSecurityException",
",",
"IOException",
"{",
"logger",
".",
"atInfo",
"(",
")",
".",
"log",
"(",
"\"Creating BigQuery from default credential.\"",
")",
";",
"Credential",
"credential",
"=",
"createBigQueryCredential",
"(",
"config",
")",
";",
"// Use the credential to create an authorized BigQuery client",
"return",
"getBigQueryFromCredential",
"(",
"credential",
",",
"BQC_ID",
")",
";",
"}"
] | Constructs a BigQuery from the credential constructed from the environment.
@throws IOException on IO Error.
@throws GeneralSecurityException on General Security Error. | [
"Constructs",
"a",
"BigQuery",
"from",
"the",
"credential",
"constructed",
"from",
"the",
"environment",
"."
] | train | https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/bigquery/src/main/java/com/google/cloud/hadoop/io/bigquery/BigQueryFactory.java#L118-L124 |
anotheria/configureme | src/main/java/org/configureme/repository/IncludeValue.java | IncludeValue.getConfigName | public ConfigurationSourceKey getConfigName() {
"""
Get configuration name of the linked config
@return configuration name of the linked config
"""
return new ConfigurationSourceKey(ConfigurationSourceKey.Type.FILE, ConfigurationSourceKey.Format.JSON, configurationName);
} | java | public ConfigurationSourceKey getConfigName() {
return new ConfigurationSourceKey(ConfigurationSourceKey.Type.FILE, ConfigurationSourceKey.Format.JSON, configurationName);
} | [
"public",
"ConfigurationSourceKey",
"getConfigName",
"(",
")",
"{",
"return",
"new",
"ConfigurationSourceKey",
"(",
"ConfigurationSourceKey",
".",
"Type",
".",
"FILE",
",",
"ConfigurationSourceKey",
".",
"Format",
".",
"JSON",
",",
"configurationName",
")",
";",
"}"
] | Get configuration name of the linked config
@return configuration name of the linked config | [
"Get",
"configuration",
"name",
"of",
"the",
"linked",
"config"
] | train | https://github.com/anotheria/configureme/blob/1f52dd9109349623190586bdf5a592de8016e1fa/src/main/java/org/configureme/repository/IncludeValue.java#L45-L47 |
javamelody/javamelody | javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MXmlWriter.java | MXmlWriter.writeXml | protected void writeXml(MListTable<?> table, OutputStream outputStream) throws IOException {
"""
Exporte une MListTable dans un fichier au format xml.
@param table MListTable
@param outputStream OutputStream
@throws IOException Erreur disque
"""
final List<?> list = table.getList();
TransportFormatAdapter.writeXml((Serializable) list, outputStream);
} | java | protected void writeXml(MListTable<?> table, OutputStream outputStream) throws IOException {
final List<?> list = table.getList();
TransportFormatAdapter.writeXml((Serializable) list, outputStream);
} | [
"protected",
"void",
"writeXml",
"(",
"MListTable",
"<",
"?",
">",
"table",
",",
"OutputStream",
"outputStream",
")",
"throws",
"IOException",
"{",
"final",
"List",
"<",
"?",
">",
"list",
"=",
"table",
".",
"getList",
"(",
")",
";",
"TransportFormatAdapter",
".",
"writeXml",
"(",
"(",
"Serializable",
")",
"list",
",",
"outputStream",
")",
";",
"}"
] | Exporte une MListTable dans un fichier au format xml.
@param table MListTable
@param outputStream OutputStream
@throws IOException Erreur disque | [
"Exporte",
"une",
"MListTable",
"dans",
"un",
"fichier",
"au",
"format",
"xml",
"."
] | train | https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MXmlWriter.java#L73-L76 |
Talend/tesb-rt-se | examples/cxf/jaxrs-attachments/client/src/main/java/client/RESTClient.java | RESTClient.createMultipartBody | private MultipartBody createMultipartBody() throws Exception {
"""
Creates MultipartBody. It contains 3 parts, "book1", "book2" and "image".
These individual parts have their Content-Type set to application/xml,
application/json and application/octet-stream
MultipartBody will use the Content-Type value of the individual
part to write its data by delegating to a matching JAX-RS MessageBodyWriter
provider
@return
@throws Exception
"""
List<Attachment> atts = new LinkedList<Attachment>();
atts.add(new Attachment("book1", "application/xml", new Book("JAXB", 1L)));
atts.add(new Attachment("book2", "application/json", new Book("JSON", 2L)));
atts.add(new Attachment("image", "application/octet-stream",
getClass().getResourceAsStream("/java.jpg")));
return new MultipartBody(atts, true);
} | java | private MultipartBody createMultipartBody() throws Exception {
List<Attachment> atts = new LinkedList<Attachment>();
atts.add(new Attachment("book1", "application/xml", new Book("JAXB", 1L)));
atts.add(new Attachment("book2", "application/json", new Book("JSON", 2L)));
atts.add(new Attachment("image", "application/octet-stream",
getClass().getResourceAsStream("/java.jpg")));
return new MultipartBody(atts, true);
} | [
"private",
"MultipartBody",
"createMultipartBody",
"(",
")",
"throws",
"Exception",
"{",
"List",
"<",
"Attachment",
">",
"atts",
"=",
"new",
"LinkedList",
"<",
"Attachment",
">",
"(",
")",
";",
"atts",
".",
"add",
"(",
"new",
"Attachment",
"(",
"\"book1\"",
",",
"\"application/xml\"",
",",
"new",
"Book",
"(",
"\"JAXB\"",
",",
"1L",
")",
")",
")",
";",
"atts",
".",
"add",
"(",
"new",
"Attachment",
"(",
"\"book2\"",
",",
"\"application/json\"",
",",
"new",
"Book",
"(",
"\"JSON\"",
",",
"2L",
")",
")",
")",
";",
"atts",
".",
"add",
"(",
"new",
"Attachment",
"(",
"\"image\"",
",",
"\"application/octet-stream\"",
",",
"getClass",
"(",
")",
".",
"getResourceAsStream",
"(",
"\"/java.jpg\"",
")",
")",
")",
";",
"return",
"new",
"MultipartBody",
"(",
"atts",
",",
"true",
")",
";",
"}"
] | Creates MultipartBody. It contains 3 parts, "book1", "book2" and "image".
These individual parts have their Content-Type set to application/xml,
application/json and application/octet-stream
MultipartBody will use the Content-Type value of the individual
part to write its data by delegating to a matching JAX-RS MessageBodyWriter
provider
@return
@throws Exception | [
"Creates",
"MultipartBody",
".",
"It",
"contains",
"3",
"parts",
"book1",
"book2",
"and",
"image",
".",
"These",
"individual",
"parts",
"have",
"their",
"Content",
"-",
"Type",
"set",
"to",
"application",
"/",
"xml",
"application",
"/",
"json",
"and",
"application",
"/",
"octet",
"-",
"stream"
] | train | https://github.com/Talend/tesb-rt-se/blob/0a151a6d91ffff65ac4b5ee0c5b2c882ac28d886/examples/cxf/jaxrs-attachments/client/src/main/java/client/RESTClient.java#L243-L253 |
eclipse/xtext-lib | org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/IteratorExtensions.java | IteratorExtensions.findLast | public static <T> T findLast(Iterator<T> iterator, Functions.Function1<? super T, Boolean> predicate) {
"""
Finds the last element in the given iterator that fulfills the predicate. If none is found or the iterator is
empty, <code>null</code> is returned.
@param iterator
the iterator. May not be <code>null</code>.
@param predicate
the predicate. May not be <code>null</code>.
@return the last element in the iterator for which the given predicate returns <code>true</code>, returns
<code>null</code> if no element matches the predicate or the iterator is empty.
"""
if (predicate == null)
throw new NullPointerException("predicate");
T result = null;
while(iterator.hasNext()) {
T t = iterator.next();
if (predicate.apply(t))
result = t;
}
return result;
} | java | public static <T> T findLast(Iterator<T> iterator, Functions.Function1<? super T, Boolean> predicate) {
if (predicate == null)
throw new NullPointerException("predicate");
T result = null;
while(iterator.hasNext()) {
T t = iterator.next();
if (predicate.apply(t))
result = t;
}
return result;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"findLast",
"(",
"Iterator",
"<",
"T",
">",
"iterator",
",",
"Functions",
".",
"Function1",
"<",
"?",
"super",
"T",
",",
"Boolean",
">",
"predicate",
")",
"{",
"if",
"(",
"predicate",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
"(",
"\"predicate\"",
")",
";",
"T",
"result",
"=",
"null",
";",
"while",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"T",
"t",
"=",
"iterator",
".",
"next",
"(",
")",
";",
"if",
"(",
"predicate",
".",
"apply",
"(",
"t",
")",
")",
"result",
"=",
"t",
";",
"}",
"return",
"result",
";",
"}"
] | Finds the last element in the given iterator that fulfills the predicate. If none is found or the iterator is
empty, <code>null</code> is returned.
@param iterator
the iterator. May not be <code>null</code>.
@param predicate
the predicate. May not be <code>null</code>.
@return the last element in the iterator for which the given predicate returns <code>true</code>, returns
<code>null</code> if no element matches the predicate or the iterator is empty. | [
"Finds",
"the",
"last",
"element",
"in",
"the",
"given",
"iterator",
"that",
"fulfills",
"the",
"predicate",
".",
"If",
"none",
"is",
"found",
"or",
"the",
"iterator",
"is",
"empty",
"<code",
">",
"null<",
"/",
"code",
">",
"is",
"returned",
"."
] | train | https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/IteratorExtensions.java#L125-L135 |
geomajas/geomajas-project-client-gwt2 | plugin/tilebasedlayer/impl/src/main/java/org/geomajas/gwt2/plugin/tilebasedlayer/client/TileBasedLayerClient.java | TileBasedLayerClient.createLayer | public TileBasedLayer createLayer(String id, TileConfiguration conf, String url) {
"""
Create a new tile based layer with an URL to a tile service.
<p/>
The URL should have placeholders for the x- and y-coordinate and tile level in the form of {x}, {y}, {z}.
The Y-coordinate can be inverted by specifying {-y} instead of {y}.
The file extension of the tiles should be part of the URL.
@param id The unique ID of the layer.
@param conf The tile configuration.
@param url The URL to the tile service.
@return A new tile based layer.
"""
List<String> urls = new ArrayList<String>();
urls.add(url);
return createLayer(id, conf, urls);
} | java | public TileBasedLayer createLayer(String id, TileConfiguration conf, String url) {
List<String> urls = new ArrayList<String>();
urls.add(url);
return createLayer(id, conf, urls);
} | [
"public",
"TileBasedLayer",
"createLayer",
"(",
"String",
"id",
",",
"TileConfiguration",
"conf",
",",
"String",
"url",
")",
"{",
"List",
"<",
"String",
">",
"urls",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"urls",
".",
"add",
"(",
"url",
")",
";",
"return",
"createLayer",
"(",
"id",
",",
"conf",
",",
"urls",
")",
";",
"}"
] | Create a new tile based layer with an URL to a tile service.
<p/>
The URL should have placeholders for the x- and y-coordinate and tile level in the form of {x}, {y}, {z}.
The Y-coordinate can be inverted by specifying {-y} instead of {y}.
The file extension of the tiles should be part of the URL.
@param id The unique ID of the layer.
@param conf The tile configuration.
@param url The URL to the tile service.
@return A new tile based layer. | [
"Create",
"a",
"new",
"tile",
"based",
"layer",
"with",
"an",
"URL",
"to",
"a",
"tile",
"service",
".",
"<p",
"/",
">",
"The",
"URL",
"should",
"have",
"placeholders",
"for",
"the",
"x",
"-",
"and",
"y",
"-",
"coordinate",
"and",
"tile",
"level",
"in",
"the",
"form",
"of",
"{",
"x",
"}",
"{",
"y",
"}",
"{",
"z",
"}",
".",
"The",
"Y",
"-",
"coordinate",
"can",
"be",
"inverted",
"by",
"specifying",
"{",
"-",
"y",
"}",
"instead",
"of",
"{",
"y",
"}",
".",
"The",
"file",
"extension",
"of",
"the",
"tiles",
"should",
"be",
"part",
"of",
"the",
"URL",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/plugin/tilebasedlayer/impl/src/main/java/org/geomajas/gwt2/plugin/tilebasedlayer/client/TileBasedLayerClient.java#L225-L229 |
elki-project/elki | elki-index-preprocessed/src/main/java/de/lmu/ifi/dbs/elki/index/preprocessed/knn/MaterializeKNNAndRKNNPreprocessor.java | MaterializeKNNAndRKNNPreprocessor.affectedkNN | protected ArrayDBIDs affectedkNN(List<? extends KNNList> extract, DBIDs remove) {
"""
Extracts and removes the DBIDs in the given collections.
@param extract a list of lists of DistanceResultPair to extract
@param remove the ids to remove
@return the DBIDs in the given collection
"""
HashSetModifiableDBIDs ids = DBIDUtil.newHashSet();
for(KNNList drps : extract) {
for(DBIDIter iter = drps.iter(); iter.valid(); iter.advance()) {
ids.add(iter);
}
}
ids.removeDBIDs(remove);
// Convert back to array
return DBIDUtil.newArray(ids);
} | java | protected ArrayDBIDs affectedkNN(List<? extends KNNList> extract, DBIDs remove) {
HashSetModifiableDBIDs ids = DBIDUtil.newHashSet();
for(KNNList drps : extract) {
for(DBIDIter iter = drps.iter(); iter.valid(); iter.advance()) {
ids.add(iter);
}
}
ids.removeDBIDs(remove);
// Convert back to array
return DBIDUtil.newArray(ids);
} | [
"protected",
"ArrayDBIDs",
"affectedkNN",
"(",
"List",
"<",
"?",
"extends",
"KNNList",
">",
"extract",
",",
"DBIDs",
"remove",
")",
"{",
"HashSetModifiableDBIDs",
"ids",
"=",
"DBIDUtil",
".",
"newHashSet",
"(",
")",
";",
"for",
"(",
"KNNList",
"drps",
":",
"extract",
")",
"{",
"for",
"(",
"DBIDIter",
"iter",
"=",
"drps",
".",
"iter",
"(",
")",
";",
"iter",
".",
"valid",
"(",
")",
";",
"iter",
".",
"advance",
"(",
")",
")",
"{",
"ids",
".",
"add",
"(",
"iter",
")",
";",
"}",
"}",
"ids",
".",
"removeDBIDs",
"(",
"remove",
")",
";",
"// Convert back to array",
"return",
"DBIDUtil",
".",
"newArray",
"(",
"ids",
")",
";",
"}"
] | Extracts and removes the DBIDs in the given collections.
@param extract a list of lists of DistanceResultPair to extract
@param remove the ids to remove
@return the DBIDs in the given collection | [
"Extracts",
"and",
"removes",
"the",
"DBIDs",
"in",
"the",
"given",
"collections",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-preprocessed/src/main/java/de/lmu/ifi/dbs/elki/index/preprocessed/knn/MaterializeKNNAndRKNNPreprocessor.java#L288-L298 |
apache/incubator-gobblin | gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/hive/HiveDataset.java | HiveDataset.resolveConfig | @VisibleForTesting
protected static Config resolveConfig(Config datasetConfig, DbAndTable realDbAndTable, DbAndTable logicalDbAndTable) {
"""
*
Replace various tokens (DB, TABLE, LOGICAL_DB, LOGICAL_TABLE) with their values.
@param datasetConfig The config object that needs to be resolved with final values.
@param realDbAndTable Real DB and Table .
@param logicalDbAndTable Logical DB and Table.
@return Resolved config object.
"""
Preconditions.checkNotNull(datasetConfig, "Dataset config should not be null");
Preconditions.checkNotNull(realDbAndTable, "Real DB and table should not be null");
Preconditions.checkNotNull(logicalDbAndTable, "Logical DB and table should not be null");
Properties resolvedProperties = new Properties();
Config resolvedConfig = datasetConfig.resolve();
for (Map.Entry<String, ConfigValue> entry : resolvedConfig.entrySet()) {
if (ConfigValueType.LIST.equals(entry.getValue().valueType())) {
List<String> rawValueList = resolvedConfig.getStringList(entry.getKey());
List<String> resolvedValueList = Lists.newArrayList();
for (String rawValue : rawValueList) {
String resolvedValue = StringUtils.replaceEach(rawValue,
new String[] { DATABASE_TOKEN, TABLE_TOKEN, LOGICAL_DB_TOKEN, LOGICAL_TABLE_TOKEN },
new String[] { realDbAndTable.getDb(), realDbAndTable.getTable(), logicalDbAndTable.getDb(), logicalDbAndTable.getTable() });
resolvedValueList.add(resolvedValue);
}
StringBuilder listToStringWithQuotes = new StringBuilder();
for (String resolvedValueStr : resolvedValueList) {
if (listToStringWithQuotes.length() > 0) {
listToStringWithQuotes.append(",");
}
listToStringWithQuotes.append("\"").append(resolvedValueStr).append("\"");
}
resolvedProperties.setProperty(entry.getKey(), listToStringWithQuotes.toString());
} else {
String resolvedValue = StringUtils.replaceEach(resolvedConfig.getString(entry.getKey()),
new String[] { DATABASE_TOKEN, TABLE_TOKEN, LOGICAL_DB_TOKEN, LOGICAL_TABLE_TOKEN },
new String[] { realDbAndTable.getDb(), realDbAndTable.getTable(), logicalDbAndTable.getDb(), logicalDbAndTable.getTable() });
resolvedProperties.setProperty(entry.getKey(), resolvedValue);
}
}
return ConfigUtils.propertiesToConfig(resolvedProperties);
} | java | @VisibleForTesting
protected static Config resolveConfig(Config datasetConfig, DbAndTable realDbAndTable, DbAndTable logicalDbAndTable) {
Preconditions.checkNotNull(datasetConfig, "Dataset config should not be null");
Preconditions.checkNotNull(realDbAndTable, "Real DB and table should not be null");
Preconditions.checkNotNull(logicalDbAndTable, "Logical DB and table should not be null");
Properties resolvedProperties = new Properties();
Config resolvedConfig = datasetConfig.resolve();
for (Map.Entry<String, ConfigValue> entry : resolvedConfig.entrySet()) {
if (ConfigValueType.LIST.equals(entry.getValue().valueType())) {
List<String> rawValueList = resolvedConfig.getStringList(entry.getKey());
List<String> resolvedValueList = Lists.newArrayList();
for (String rawValue : rawValueList) {
String resolvedValue = StringUtils.replaceEach(rawValue,
new String[] { DATABASE_TOKEN, TABLE_TOKEN, LOGICAL_DB_TOKEN, LOGICAL_TABLE_TOKEN },
new String[] { realDbAndTable.getDb(), realDbAndTable.getTable(), logicalDbAndTable.getDb(), logicalDbAndTable.getTable() });
resolvedValueList.add(resolvedValue);
}
StringBuilder listToStringWithQuotes = new StringBuilder();
for (String resolvedValueStr : resolvedValueList) {
if (listToStringWithQuotes.length() > 0) {
listToStringWithQuotes.append(",");
}
listToStringWithQuotes.append("\"").append(resolvedValueStr).append("\"");
}
resolvedProperties.setProperty(entry.getKey(), listToStringWithQuotes.toString());
} else {
String resolvedValue = StringUtils.replaceEach(resolvedConfig.getString(entry.getKey()),
new String[] { DATABASE_TOKEN, TABLE_TOKEN, LOGICAL_DB_TOKEN, LOGICAL_TABLE_TOKEN },
new String[] { realDbAndTable.getDb(), realDbAndTable.getTable(), logicalDbAndTable.getDb(), logicalDbAndTable.getTable() });
resolvedProperties.setProperty(entry.getKey(), resolvedValue);
}
}
return ConfigUtils.propertiesToConfig(resolvedProperties);
} | [
"@",
"VisibleForTesting",
"protected",
"static",
"Config",
"resolveConfig",
"(",
"Config",
"datasetConfig",
",",
"DbAndTable",
"realDbAndTable",
",",
"DbAndTable",
"logicalDbAndTable",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"datasetConfig",
",",
"\"Dataset config should not be null\"",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"realDbAndTable",
",",
"\"Real DB and table should not be null\"",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"logicalDbAndTable",
",",
"\"Logical DB and table should not be null\"",
")",
";",
"Properties",
"resolvedProperties",
"=",
"new",
"Properties",
"(",
")",
";",
"Config",
"resolvedConfig",
"=",
"datasetConfig",
".",
"resolve",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"ConfigValue",
">",
"entry",
":",
"resolvedConfig",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"ConfigValueType",
".",
"LIST",
".",
"equals",
"(",
"entry",
".",
"getValue",
"(",
")",
".",
"valueType",
"(",
")",
")",
")",
"{",
"List",
"<",
"String",
">",
"rawValueList",
"=",
"resolvedConfig",
".",
"getStringList",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
";",
"List",
"<",
"String",
">",
"resolvedValueList",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"for",
"(",
"String",
"rawValue",
":",
"rawValueList",
")",
"{",
"String",
"resolvedValue",
"=",
"StringUtils",
".",
"replaceEach",
"(",
"rawValue",
",",
"new",
"String",
"[",
"]",
"{",
"DATABASE_TOKEN",
",",
"TABLE_TOKEN",
",",
"LOGICAL_DB_TOKEN",
",",
"LOGICAL_TABLE_TOKEN",
"}",
",",
"new",
"String",
"[",
"]",
"{",
"realDbAndTable",
".",
"getDb",
"(",
")",
",",
"realDbAndTable",
".",
"getTable",
"(",
")",
",",
"logicalDbAndTable",
".",
"getDb",
"(",
")",
",",
"logicalDbAndTable",
".",
"getTable",
"(",
")",
"}",
")",
";",
"resolvedValueList",
".",
"add",
"(",
"resolvedValue",
")",
";",
"}",
"StringBuilder",
"listToStringWithQuotes",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"String",
"resolvedValueStr",
":",
"resolvedValueList",
")",
"{",
"if",
"(",
"listToStringWithQuotes",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"listToStringWithQuotes",
".",
"append",
"(",
"\",\"",
")",
";",
"}",
"listToStringWithQuotes",
".",
"append",
"(",
"\"\\\"\"",
")",
".",
"append",
"(",
"resolvedValueStr",
")",
".",
"append",
"(",
"\"\\\"\"",
")",
";",
"}",
"resolvedProperties",
".",
"setProperty",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"listToStringWithQuotes",
".",
"toString",
"(",
")",
")",
";",
"}",
"else",
"{",
"String",
"resolvedValue",
"=",
"StringUtils",
".",
"replaceEach",
"(",
"resolvedConfig",
".",
"getString",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
",",
"new",
"String",
"[",
"]",
"{",
"DATABASE_TOKEN",
",",
"TABLE_TOKEN",
",",
"LOGICAL_DB_TOKEN",
",",
"LOGICAL_TABLE_TOKEN",
"}",
",",
"new",
"String",
"[",
"]",
"{",
"realDbAndTable",
".",
"getDb",
"(",
")",
",",
"realDbAndTable",
".",
"getTable",
"(",
")",
",",
"logicalDbAndTable",
".",
"getDb",
"(",
")",
",",
"logicalDbAndTable",
".",
"getTable",
"(",
")",
"}",
")",
";",
"resolvedProperties",
".",
"setProperty",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"resolvedValue",
")",
";",
"}",
"}",
"return",
"ConfigUtils",
".",
"propertiesToConfig",
"(",
"resolvedProperties",
")",
";",
"}"
] | *
Replace various tokens (DB, TABLE, LOGICAL_DB, LOGICAL_TABLE) with their values.
@param datasetConfig The config object that needs to be resolved with final values.
@param realDbAndTable Real DB and Table .
@param logicalDbAndTable Logical DB and Table.
@return Resolved config object. | [
"*",
"Replace",
"various",
"tokens",
"(",
"DB",
"TABLE",
"LOGICAL_DB",
"LOGICAL_TABLE",
")",
"with",
"their",
"values",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/hive/HiveDataset.java#L263-L298 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLLiteralImplBoolean_CustomFieldSerializer.java | OWLLiteralImplBoolean_CustomFieldSerializer.serializeInstance | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLLiteralImplBoolean instance) throws SerializationException {
"""
Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful
"""
serialize(streamWriter, instance);
} | java | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLLiteralImplBoolean instance) throws SerializationException {
serialize(streamWriter, instance);
} | [
"@",
"Override",
"public",
"void",
"serializeInstance",
"(",
"SerializationStreamWriter",
"streamWriter",
",",
"OWLLiteralImplBoolean",
"instance",
")",
"throws",
"SerializationException",
"{",
"serialize",
"(",
"streamWriter",
",",
"instance",
")",
";",
"}"
] | Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful | [
"Serializes",
"the",
"content",
"of",
"the",
"object",
"into",
"the",
"{"
] | train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLLiteralImplBoolean_CustomFieldSerializer.java#L64-L67 |
dropbox/dropbox-sdk-java | src/main/java/com/dropbox/core/v1/DbxClientV1.java | DbxClientV1.getDelta | public DbxDelta<DbxEntry> getDelta(/*@Nullable*/String cursor, boolean includeMediaInfo)
throws DbxException {
"""
Return "delta" entries for the contents of a user's Dropbox. This lets you
efficiently keep up with the latest state of the files and folders. See
{@link DbxDelta} for more documentation on what each entry means.
<p>
To start, pass in {@code null} for {@code cursor}. For subsequent calls
To get the next set of delta entries, pass in the {@link DbxDelta#cursor cursor} returned
by the previous call.
</p>
<p>
To catch up to the current state, keep calling this method until the returned
object's {@link DbxDelta#hasMore hasMore} field is {@code false}.
</p>
<p>
If your app is a "Full Dropbox" app, this will return all entries for the user's entire
Dropbox folder. If your app is an "App Folder" app, this will only return entries
for the App Folder's contents.
</p>
"""
return _getDelta(cursor, null, includeMediaInfo);
} | java | public DbxDelta<DbxEntry> getDelta(/*@Nullable*/String cursor, boolean includeMediaInfo)
throws DbxException
{
return _getDelta(cursor, null, includeMediaInfo);
} | [
"public",
"DbxDelta",
"<",
"DbxEntry",
">",
"getDelta",
"(",
"/*@Nullable*/",
"String",
"cursor",
",",
"boolean",
"includeMediaInfo",
")",
"throws",
"DbxException",
"{",
"return",
"_getDelta",
"(",
"cursor",
",",
"null",
",",
"includeMediaInfo",
")",
";",
"}"
] | Return "delta" entries for the contents of a user's Dropbox. This lets you
efficiently keep up with the latest state of the files and folders. See
{@link DbxDelta} for more documentation on what each entry means.
<p>
To start, pass in {@code null} for {@code cursor}. For subsequent calls
To get the next set of delta entries, pass in the {@link DbxDelta#cursor cursor} returned
by the previous call.
</p>
<p>
To catch up to the current state, keep calling this method until the returned
object's {@link DbxDelta#hasMore hasMore} field is {@code false}.
</p>
<p>
If your app is a "Full Dropbox" app, this will return all entries for the user's entire
Dropbox folder. If your app is an "App Folder" app, this will only return entries
for the App Folder's contents.
</p> | [
"Return",
"delta",
"entries",
"for",
"the",
"contents",
"of",
"a",
"user",
"s",
"Dropbox",
".",
"This",
"lets",
"you",
"efficiently",
"keep",
"up",
"with",
"the",
"latest",
"state",
"of",
"the",
"files",
"and",
"folders",
".",
"See",
"{",
"@link",
"DbxDelta",
"}",
"for",
"more",
"documentation",
"on",
"what",
"each",
"entry",
"means",
"."
] | train | https://github.com/dropbox/dropbox-sdk-java/blob/d86157005fad6233c18b4b0f10f00b8d9d56ae92/src/main/java/com/dropbox/core/v1/DbxClientV1.java#L1479-L1483 |
google/j2objc | translator/src/main/java/com/google/devtools/j2objc/javac/JavadocConverter.java | JavadocConverter.setPos | private TreeNode setPos(TreeNode newNode, int pos, int endPos) {
"""
Set a TreeNode's position using begin and end source offsets. Its line number
is unchanged.
"""
return newNode.setPosition(new SourcePosition(pos, endPos - pos, lineNumber(pos)));
} | java | private TreeNode setPos(TreeNode newNode, int pos, int endPos) {
return newNode.setPosition(new SourcePosition(pos, endPos - pos, lineNumber(pos)));
} | [
"private",
"TreeNode",
"setPos",
"(",
"TreeNode",
"newNode",
",",
"int",
"pos",
",",
"int",
"endPos",
")",
"{",
"return",
"newNode",
".",
"setPosition",
"(",
"new",
"SourcePosition",
"(",
"pos",
",",
"endPos",
"-",
"pos",
",",
"lineNumber",
"(",
"pos",
")",
")",
")",
";",
"}"
] | Set a TreeNode's position using begin and end source offsets. Its line number
is unchanged. | [
"Set",
"a",
"TreeNode",
"s",
"position",
"using",
"begin",
"and",
"end",
"source",
"offsets",
".",
"Its",
"line",
"number",
"is",
"unchanged",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/translator/src/main/java/com/google/devtools/j2objc/javac/JavadocConverter.java#L338-L340 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/dbinfo/DatabaseInformationFull.java | DatabaseInformationFull.SYSTEM_VERSIONCOLUMNS | Table SYSTEM_VERSIONCOLUMNS() {
"""
Retrieves a <code>Table</code> object describing the accessible
columns that are automatically updated when any value in a row
is updated. <p>
Each row is a version column description with the following columns: <p>
<OL>
<LI><B>SCOPE</B> <code>SMALLINT</code> => is not used
<LI><B>COLUMN_NAME</B> <code>VARCHAR</code> => column name
<LI><B>DATA_TYPE</B> <code>SMALLINT</code> =>
SQL data type from java.sql.Types
<LI><B>TYPE_NAME</B> <code>SMALLINT</code> =>
Data source dependent type name
<LI><B>COLUMN_SIZE</B> <code>INTEGER</code> => precision
<LI><B>BUFFER_LENGTH</B> <code>INTEGER</code> =>
length of column value in bytes
<LI><B>DECIMAL_DIGITS</B> <code>SMALLINT</code> => scale
<LI><B>PSEUDO_COLUMN</B> <code>SMALLINT</code> =>
is this a pseudo column like an Oracle <code>ROWID</code>:<BR>
(as defined in <code>java.sql.DatabaseMetadata</code>)
<UL>
<LI><code>versionColumnUnknown</code> - may or may not be
pseudo column
<LI><code>versionColumnNotPseudo</code> - is NOT a pseudo column
<LI><code>versionColumnPseudo</code> - is a pseudo column
</UL>
</OL> <p>
<B>Note:</B> Currently, the HSQLDB engine does not support version
columns, so an empty table is returned. <p>
@return a <code>Table</code> object describing the columns
that are automatically updated when any value
in a row is updated
"""
Table t = sysTables[SYSTEM_VERSIONCOLUMNS];
if (t == null) {
t = createBlankTable(sysTableHsqlNames[SYSTEM_VERSIONCOLUMNS]);
// ----------------------------------------------------------------
// required by DatabaseMetaData.getVersionColumns result set
// ----------------------------------------------------------------
addColumn(t, "SCOPE", Type.SQL_INTEGER);
addColumn(t, "COLUMN_NAME", SQL_IDENTIFIER); // not null
addColumn(t, "DATA_TYPE", Type.SQL_SMALLINT); // not null
addColumn(t, "TYPE_NAME", SQL_IDENTIFIER); // not null
addColumn(t, "COLUMN_SIZE", Type.SQL_SMALLINT);
addColumn(t, "BUFFER_LENGTH", Type.SQL_INTEGER);
addColumn(t, "DECIMAL_DIGITS", Type.SQL_SMALLINT);
addColumn(t, "PSEUDO_COLUMN", Type.SQL_SMALLINT); // not null
// -----------------------------------------------------------------
// required by DatabaseMetaData.getVersionColumns filter parameters
// -----------------------------------------------------------------
addColumn(t, "TABLE_CAT", SQL_IDENTIFIER);
addColumn(t, "TABLE_SCHEM", SQL_IDENTIFIER);
addColumn(t, "TABLE_NAME", SQL_IDENTIFIER); // not null
// -----------------------------------------------------------------
HsqlName name = HsqlNameManager.newInfoSchemaObjectName(
sysTableHsqlNames[SYSTEM_VERSIONCOLUMNS].name, false,
SchemaObject.INDEX);
t.createPrimaryKey(name, null, false);
return t;
}
return t;
} | java | Table SYSTEM_VERSIONCOLUMNS() {
Table t = sysTables[SYSTEM_VERSIONCOLUMNS];
if (t == null) {
t = createBlankTable(sysTableHsqlNames[SYSTEM_VERSIONCOLUMNS]);
// ----------------------------------------------------------------
// required by DatabaseMetaData.getVersionColumns result set
// ----------------------------------------------------------------
addColumn(t, "SCOPE", Type.SQL_INTEGER);
addColumn(t, "COLUMN_NAME", SQL_IDENTIFIER); // not null
addColumn(t, "DATA_TYPE", Type.SQL_SMALLINT); // not null
addColumn(t, "TYPE_NAME", SQL_IDENTIFIER); // not null
addColumn(t, "COLUMN_SIZE", Type.SQL_SMALLINT);
addColumn(t, "BUFFER_LENGTH", Type.SQL_INTEGER);
addColumn(t, "DECIMAL_DIGITS", Type.SQL_SMALLINT);
addColumn(t, "PSEUDO_COLUMN", Type.SQL_SMALLINT); // not null
// -----------------------------------------------------------------
// required by DatabaseMetaData.getVersionColumns filter parameters
// -----------------------------------------------------------------
addColumn(t, "TABLE_CAT", SQL_IDENTIFIER);
addColumn(t, "TABLE_SCHEM", SQL_IDENTIFIER);
addColumn(t, "TABLE_NAME", SQL_IDENTIFIER); // not null
// -----------------------------------------------------------------
HsqlName name = HsqlNameManager.newInfoSchemaObjectName(
sysTableHsqlNames[SYSTEM_VERSIONCOLUMNS].name, false,
SchemaObject.INDEX);
t.createPrimaryKey(name, null, false);
return t;
}
return t;
} | [
"Table",
"SYSTEM_VERSIONCOLUMNS",
"(",
")",
"{",
"Table",
"t",
"=",
"sysTables",
"[",
"SYSTEM_VERSIONCOLUMNS",
"]",
";",
"if",
"(",
"t",
"==",
"null",
")",
"{",
"t",
"=",
"createBlankTable",
"(",
"sysTableHsqlNames",
"[",
"SYSTEM_VERSIONCOLUMNS",
"]",
")",
";",
"// ----------------------------------------------------------------",
"// required by DatabaseMetaData.getVersionColumns result set",
"// ----------------------------------------------------------------",
"addColumn",
"(",
"t",
",",
"\"SCOPE\"",
",",
"Type",
".",
"SQL_INTEGER",
")",
";",
"addColumn",
"(",
"t",
",",
"\"COLUMN_NAME\"",
",",
"SQL_IDENTIFIER",
")",
";",
"// not null",
"addColumn",
"(",
"t",
",",
"\"DATA_TYPE\"",
",",
"Type",
".",
"SQL_SMALLINT",
")",
";",
"// not null",
"addColumn",
"(",
"t",
",",
"\"TYPE_NAME\"",
",",
"SQL_IDENTIFIER",
")",
";",
"// not null",
"addColumn",
"(",
"t",
",",
"\"COLUMN_SIZE\"",
",",
"Type",
".",
"SQL_SMALLINT",
")",
";",
"addColumn",
"(",
"t",
",",
"\"BUFFER_LENGTH\"",
",",
"Type",
".",
"SQL_INTEGER",
")",
";",
"addColumn",
"(",
"t",
",",
"\"DECIMAL_DIGITS\"",
",",
"Type",
".",
"SQL_SMALLINT",
")",
";",
"addColumn",
"(",
"t",
",",
"\"PSEUDO_COLUMN\"",
",",
"Type",
".",
"SQL_SMALLINT",
")",
";",
"// not null",
"// -----------------------------------------------------------------",
"// required by DatabaseMetaData.getVersionColumns filter parameters",
"// -----------------------------------------------------------------",
"addColumn",
"(",
"t",
",",
"\"TABLE_CAT\"",
",",
"SQL_IDENTIFIER",
")",
";",
"addColumn",
"(",
"t",
",",
"\"TABLE_SCHEM\"",
",",
"SQL_IDENTIFIER",
")",
";",
"addColumn",
"(",
"t",
",",
"\"TABLE_NAME\"",
",",
"SQL_IDENTIFIER",
")",
";",
"// not null",
"// -----------------------------------------------------------------",
"HsqlName",
"name",
"=",
"HsqlNameManager",
".",
"newInfoSchemaObjectName",
"(",
"sysTableHsqlNames",
"[",
"SYSTEM_VERSIONCOLUMNS",
"]",
".",
"name",
",",
"false",
",",
"SchemaObject",
".",
"INDEX",
")",
";",
"t",
".",
"createPrimaryKey",
"(",
"name",
",",
"null",
",",
"false",
")",
";",
"return",
"t",
";",
"}",
"return",
"t",
";",
"}"
] | Retrieves a <code>Table</code> object describing the accessible
columns that are automatically updated when any value in a row
is updated. <p>
Each row is a version column description with the following columns: <p>
<OL>
<LI><B>SCOPE</B> <code>SMALLINT</code> => is not used
<LI><B>COLUMN_NAME</B> <code>VARCHAR</code> => column name
<LI><B>DATA_TYPE</B> <code>SMALLINT</code> =>
SQL data type from java.sql.Types
<LI><B>TYPE_NAME</B> <code>SMALLINT</code> =>
Data source dependent type name
<LI><B>COLUMN_SIZE</B> <code>INTEGER</code> => precision
<LI><B>BUFFER_LENGTH</B> <code>INTEGER</code> =>
length of column value in bytes
<LI><B>DECIMAL_DIGITS</B> <code>SMALLINT</code> => scale
<LI><B>PSEUDO_COLUMN</B> <code>SMALLINT</code> =>
is this a pseudo column like an Oracle <code>ROWID</code>:<BR>
(as defined in <code>java.sql.DatabaseMetadata</code>)
<UL>
<LI><code>versionColumnUnknown</code> - may or may not be
pseudo column
<LI><code>versionColumnNotPseudo</code> - is NOT a pseudo column
<LI><code>versionColumnPseudo</code> - is a pseudo column
</UL>
</OL> <p>
<B>Note:</B> Currently, the HSQLDB engine does not support version
columns, so an empty table is returned. <p>
@return a <code>Table</code> object describing the columns
that are automatically updated when any value
in a row is updated | [
"Retrieves",
"a",
"<code",
">",
"Table<",
"/",
"code",
">",
"object",
"describing",
"the",
"accessible",
"columns",
"that",
"are",
"automatically",
"updated",
"when",
"any",
"value",
"in",
"a",
"row",
"is",
"updated",
".",
"<p",
">"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/dbinfo/DatabaseInformationFull.java#L1128-L1165 |
jOOQ/jOOL | jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java | Unchecked.toLongFunction | public static <T> ToLongFunction<T> toLongFunction(CheckedToLongFunction<T> function, Consumer<Throwable> handler) {
"""
Wrap a {@link CheckedToLongFunction} in a {@link ToLongFunction} with a custom handler for checked exceptions.
<p>
Example:
<code><pre>
map.forEach(Unchecked.toLongFunction(
k -> {
if (k.length() > 10)
throw new Exception("Only short strings allowed");
return 42L;
},
e -> {
throw new IllegalStateException(e);
}
));
</pre></code>
"""
return t -> {
try {
return function.applyAsLong(t);
}
catch (Throwable e) {
handler.accept(e);
throw new IllegalStateException("Exception handler must throw a RuntimeException", e);
}
};
} | java | public static <T> ToLongFunction<T> toLongFunction(CheckedToLongFunction<T> function, Consumer<Throwable> handler) {
return t -> {
try {
return function.applyAsLong(t);
}
catch (Throwable e) {
handler.accept(e);
throw new IllegalStateException("Exception handler must throw a RuntimeException", e);
}
};
} | [
"public",
"static",
"<",
"T",
">",
"ToLongFunction",
"<",
"T",
">",
"toLongFunction",
"(",
"CheckedToLongFunction",
"<",
"T",
">",
"function",
",",
"Consumer",
"<",
"Throwable",
">",
"handler",
")",
"{",
"return",
"t",
"->",
"{",
"try",
"{",
"return",
"function",
".",
"applyAsLong",
"(",
"t",
")",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"handler",
".",
"accept",
"(",
"e",
")",
";",
"throw",
"new",
"IllegalStateException",
"(",
"\"Exception handler must throw a RuntimeException\"",
",",
"e",
")",
";",
"}",
"}",
";",
"}"
] | Wrap a {@link CheckedToLongFunction} in a {@link ToLongFunction} with a custom handler for checked exceptions.
<p>
Example:
<code><pre>
map.forEach(Unchecked.toLongFunction(
k -> {
if (k.length() > 10)
throw new Exception("Only short strings allowed");
return 42L;
},
e -> {
throw new IllegalStateException(e);
}
));
</pre></code> | [
"Wrap",
"a",
"{",
"@link",
"CheckedToLongFunction",
"}",
"in",
"a",
"{",
"@link",
"ToLongFunction",
"}",
"with",
"a",
"custom",
"handler",
"for",
"checked",
"exceptions",
".",
"<p",
">",
"Example",
":",
"<code",
">",
"<pre",
">",
"map",
".",
"forEach",
"(",
"Unchecked",
".",
"toLongFunction",
"(",
"k",
"-",
">",
"{",
"if",
"(",
"k",
".",
"length",
"()",
">",
"10",
")",
"throw",
"new",
"Exception",
"(",
"Only",
"short",
"strings",
"allowed",
")",
";"
] | train | https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L971-L982 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/asynchronous/AsyncBitmapTexture.java | AsyncBitmapTexture.getScreenSize | private static Point getScreenSize(Context context, Point p) {
"""
Returns screen height and width
@param context
Any non-null Android Context
@param p
Optional Point to reuse. If null, a new Point will be created.
@return .x is screen width; .y is screen height.
"""
if (p == null) {
p = new Point();
}
WindowManager windowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
display.getSize(p);
return p;
} | java | private static Point getScreenSize(Context context, Point p) {
if (p == null) {
p = new Point();
}
WindowManager windowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
display.getSize(p);
return p;
} | [
"private",
"static",
"Point",
"getScreenSize",
"(",
"Context",
"context",
",",
"Point",
"p",
")",
"{",
"if",
"(",
"p",
"==",
"null",
")",
"{",
"p",
"=",
"new",
"Point",
"(",
")",
";",
"}",
"WindowManager",
"windowManager",
"=",
"(",
"WindowManager",
")",
"context",
".",
"getSystemService",
"(",
"Context",
".",
"WINDOW_SERVICE",
")",
";",
"Display",
"display",
"=",
"windowManager",
".",
"getDefaultDisplay",
"(",
")",
";",
"display",
".",
"getSize",
"(",
"p",
")",
";",
"return",
"p",
";",
"}"
] | Returns screen height and width
@param context
Any non-null Android Context
@param p
Optional Point to reuse. If null, a new Point will be created.
@return .x is screen width; .y is screen height. | [
"Returns",
"screen",
"height",
"and",
"width"
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/asynchronous/AsyncBitmapTexture.java#L229-L238 |
sawano/java-commons | src/main/java/se/sawano/java/commons/lang/validate/Validate.java | Validate.inclusiveBetween | public static <T, V extends Comparable<T>> V inclusiveBetween(final T start, final T end, final V value) {
"""
<p>Validate that the specified argument object fall between the two inclusive values specified; otherwise, throws an exception.</p>
<pre>Validate.inclusiveBetween(0, 2, 1);</pre>
@param <T>
the type of the start and end values
@param <V>
the type of the object to validate
@param start
the inclusive start value, not null
@param end
the inclusive end value, not null
@param value
the object to validate, not null
@return the object
@throws IllegalArgumentValidationException
if the value falls outside the boundaries
@see #inclusiveBetween(Object, Object, Comparable, String, Object...)
"""
return INSTANCE.inclusiveBetween(start, end, value);
} | java | public static <T, V extends Comparable<T>> V inclusiveBetween(final T start, final T end, final V value) {
return INSTANCE.inclusiveBetween(start, end, value);
} | [
"public",
"static",
"<",
"T",
",",
"V",
"extends",
"Comparable",
"<",
"T",
">",
">",
"V",
"inclusiveBetween",
"(",
"final",
"T",
"start",
",",
"final",
"T",
"end",
",",
"final",
"V",
"value",
")",
"{",
"return",
"INSTANCE",
".",
"inclusiveBetween",
"(",
"start",
",",
"end",
",",
"value",
")",
";",
"}"
] | <p>Validate that the specified argument object fall between the two inclusive values specified; otherwise, throws an exception.</p>
<pre>Validate.inclusiveBetween(0, 2, 1);</pre>
@param <T>
the type of the start and end values
@param <V>
the type of the object to validate
@param start
the inclusive start value, not null
@param end
the inclusive end value, not null
@param value
the object to validate, not null
@return the object
@throws IllegalArgumentValidationException
if the value falls outside the boundaries
@see #inclusiveBetween(Object, Object, Comparable, String, Object...) | [
"<p",
">",
"Validate",
"that",
"the",
"specified",
"argument",
"object",
"fall",
"between",
"the",
"two",
"inclusive",
"values",
"specified",
";",
"otherwise",
"throws",
"an",
"exception",
".",
"<",
"/",
"p",
">",
"<pre",
">",
"Validate",
".",
"inclusiveBetween",
"(",
"0",
"2",
"1",
")",
";",
"<",
"/",
"pre",
">"
] | train | https://github.com/sawano/java-commons/blob/6f219c9e8dec4401dbe528d17ae6ec1ef9c0d284/src/main/java/se/sawano/java/commons/lang/validate/Validate.java#L1430-L1432 |
dihedron/dihedron-commons | src/main/java/org/dihedron/patterns/activities/engine/javaee/ServiceLocator.java | ServiceLocator.getService | public static <T> T getService(String name, Class<T> clazz) throws NamingException {
"""
Locates a service given its JNDI name and automatically casts its reference
to the appropriate class, as specified by the caller.
@param name
the JNDI name of the resource to lookup.
@param clazz
the type to be used for casting the reference.
@return
the type-cast resource reference, or null if no resource found.
@throws NamingException
if there was a problem with the JNDI lookup.
"""
Object object = SingletonHolder.locator.context.lookup(name);
if(object != null) {
return clazz.cast(object);
}
return null;
} | java | public static <T> T getService(String name, Class<T> clazz) throws NamingException {
Object object = SingletonHolder.locator.context.lookup(name);
if(object != null) {
return clazz.cast(object);
}
return null;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"getService",
"(",
"String",
"name",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"throws",
"NamingException",
"{",
"Object",
"object",
"=",
"SingletonHolder",
".",
"locator",
".",
"context",
".",
"lookup",
"(",
"name",
")",
";",
"if",
"(",
"object",
"!=",
"null",
")",
"{",
"return",
"clazz",
".",
"cast",
"(",
"object",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Locates a service given its JNDI name and automatically casts its reference
to the appropriate class, as specified by the caller.
@param name
the JNDI name of the resource to lookup.
@param clazz
the type to be used for casting the reference.
@return
the type-cast resource reference, or null if no resource found.
@throws NamingException
if there was a problem with the JNDI lookup. | [
"Locates",
"a",
"service",
"given",
"its",
"JNDI",
"name",
"and",
"automatically",
"casts",
"its",
"reference",
"to",
"the",
"appropriate",
"class",
"as",
"specified",
"by",
"the",
"caller",
"."
] | train | https://github.com/dihedron/dihedron-commons/blob/a5194cdaa0d6417ef4aade6ea407a1cad6e8458e/src/main/java/org/dihedron/patterns/activities/engine/javaee/ServiceLocator.java#L55-L61 |
wildfly/wildfly-core | host-controller/src/main/java/org/jboss/as/host/controller/ManagedServer.java | ManagedServer.finishTransition | private synchronized void finishTransition(final InternalState current, final InternalState next) {
"""
Finish a state transition from a notification.
@param current
@param next
"""
internalSetState(getTransitionTask(next), current, next);
transition();
} | java | private synchronized void finishTransition(final InternalState current, final InternalState next) {
internalSetState(getTransitionTask(next), current, next);
transition();
} | [
"private",
"synchronized",
"void",
"finishTransition",
"(",
"final",
"InternalState",
"current",
",",
"final",
"InternalState",
"next",
")",
"{",
"internalSetState",
"(",
"getTransitionTask",
"(",
"next",
")",
",",
"current",
",",
"next",
")",
";",
"transition",
"(",
")",
";",
"}"
] | Finish a state transition from a notification.
@param current
@param next | [
"Finish",
"a",
"state",
"transition",
"from",
"a",
"notification",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/host/controller/ManagedServer.java#L600-L603 |
qiujiayu/AutoLoadCache | src/main/java/com/jarvis/cache/CacheHandler.java | CacheHandler.getCacheKey | private CacheKeyTO getCacheKey(CacheAopProxyChain pjp, Object[] arguments, ExCache exCache, Object result) {
"""
生成缓存 Key
@param pjp
@param arguments
@param exCache
@param result 执行结果值
@return 缓存Key
"""
Object target = pjp.getTarget();
String methodName = pjp.getMethod().getName();
String keyExpression = exCache.key();
if (null == keyExpression || keyExpression.trim().length() == 0) {
return null;
}
String hfieldExpression = exCache.hfield();
return getCacheKey(target, methodName, arguments, keyExpression, hfieldExpression, result, true);
} | java | private CacheKeyTO getCacheKey(CacheAopProxyChain pjp, Object[] arguments, ExCache exCache, Object result) {
Object target = pjp.getTarget();
String methodName = pjp.getMethod().getName();
String keyExpression = exCache.key();
if (null == keyExpression || keyExpression.trim().length() == 0) {
return null;
}
String hfieldExpression = exCache.hfield();
return getCacheKey(target, methodName, arguments, keyExpression, hfieldExpression, result, true);
} | [
"private",
"CacheKeyTO",
"getCacheKey",
"(",
"CacheAopProxyChain",
"pjp",
",",
"Object",
"[",
"]",
"arguments",
",",
"ExCache",
"exCache",
",",
"Object",
"result",
")",
"{",
"Object",
"target",
"=",
"pjp",
".",
"getTarget",
"(",
")",
";",
"String",
"methodName",
"=",
"pjp",
".",
"getMethod",
"(",
")",
".",
"getName",
"(",
")",
";",
"String",
"keyExpression",
"=",
"exCache",
".",
"key",
"(",
")",
";",
"if",
"(",
"null",
"==",
"keyExpression",
"||",
"keyExpression",
".",
"trim",
"(",
")",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
"null",
";",
"}",
"String",
"hfieldExpression",
"=",
"exCache",
".",
"hfield",
"(",
")",
";",
"return",
"getCacheKey",
"(",
"target",
",",
"methodName",
",",
"arguments",
",",
"keyExpression",
",",
"hfieldExpression",
",",
"result",
",",
"true",
")",
";",
"}"
] | 生成缓存 Key
@param pjp
@param arguments
@param exCache
@param result 执行结果值
@return 缓存Key | [
"生成缓存",
"Key"
] | train | https://github.com/qiujiayu/AutoLoadCache/blob/8121c146f1a420fa6d6832e849acadb547c13622/src/main/java/com/jarvis/cache/CacheHandler.java#L503-L512 |
Baidu-AIP/java-sdk | src/main/java/com/baidu/aip/util/Util.java | Util.uriEncode | public static String uriEncode(String value, boolean encodeSlash) {
"""
Normalize a string for use in BCE web service APIs. The normalization algorithm is:
<ol>
<li>Convert the string into a UTF-8 byte array.</li>
<li>Encode all octets into percent-encoding, except all URI unreserved characters per the RFC 3986.</li>
</ol>
All letters used in the percent-encoding are in uppercase.
@param value the string to normalize.
@param encodeSlash if encode '/'
@return the normalized string.
"""
try {
StringBuilder builder = new StringBuilder();
for (byte b : value.getBytes(AipClientConst.DEFAULT_ENCODING)) {
if (URI_UNRESERVED_CHARACTERS.get(b & 0xFF)) {
builder.append((char) b);
} else {
builder.append(PERCENT_ENCODED_STRINGS[b & 0xFF]);
}
}
String encodeString = builder.toString();
if (!encodeSlash) {
return encodeString.replace("%2F", "/");
}
return encodeString;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} | java | public static String uriEncode(String value, boolean encodeSlash) {
try {
StringBuilder builder = new StringBuilder();
for (byte b : value.getBytes(AipClientConst.DEFAULT_ENCODING)) {
if (URI_UNRESERVED_CHARACTERS.get(b & 0xFF)) {
builder.append((char) b);
} else {
builder.append(PERCENT_ENCODED_STRINGS[b & 0xFF]);
}
}
String encodeString = builder.toString();
if (!encodeSlash) {
return encodeString.replace("%2F", "/");
}
return encodeString;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} | [
"public",
"static",
"String",
"uriEncode",
"(",
"String",
"value",
",",
"boolean",
"encodeSlash",
")",
"{",
"try",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"byte",
"b",
":",
"value",
".",
"getBytes",
"(",
"AipClientConst",
".",
"DEFAULT_ENCODING",
")",
")",
"{",
"if",
"(",
"URI_UNRESERVED_CHARACTERS",
".",
"get",
"(",
"b",
"&",
"0xFF",
")",
")",
"{",
"builder",
".",
"append",
"(",
"(",
"char",
")",
"b",
")",
";",
"}",
"else",
"{",
"builder",
".",
"append",
"(",
"PERCENT_ENCODED_STRINGS",
"[",
"b",
"&",
"0xFF",
"]",
")",
";",
"}",
"}",
"String",
"encodeString",
"=",
"builder",
".",
"toString",
"(",
")",
";",
"if",
"(",
"!",
"encodeSlash",
")",
"{",
"return",
"encodeString",
".",
"replace",
"(",
"\"%2F\"",
",",
"\"/\"",
")",
";",
"}",
"return",
"encodeString",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] | Normalize a string for use in BCE web service APIs. The normalization algorithm is:
<ol>
<li>Convert the string into a UTF-8 byte array.</li>
<li>Encode all octets into percent-encoding, except all URI unreserved characters per the RFC 3986.</li>
</ol>
All letters used in the percent-encoding are in uppercase.
@param value the string to normalize.
@param encodeSlash if encode '/'
@return the normalized string. | [
"Normalize",
"a",
"string",
"for",
"use",
"in",
"BCE",
"web",
"service",
"APIs",
".",
"The",
"normalization",
"algorithm",
"is",
":",
"<ol",
">",
"<li",
">",
"Convert",
"the",
"string",
"into",
"a",
"UTF",
"-",
"8",
"byte",
"array",
".",
"<",
"/",
"li",
">",
"<li",
">",
"Encode",
"all",
"octets",
"into",
"percent",
"-",
"encoding",
"except",
"all",
"URI",
"unreserved",
"characters",
"per",
"the",
"RFC",
"3986",
".",
"<",
"/",
"li",
">",
"<",
"/",
"ol",
">"
] | train | https://github.com/Baidu-AIP/java-sdk/blob/16bb8b7bb8f9bbcb7c8af62d0a67a1e79eecad90/src/main/java/com/baidu/aip/util/Util.java#L90-L108 |
windup/windup | graph/api/src/main/java/org/jboss/windup/graph/service/OrganizationService.java | OrganizationService.attachOrganization | public OrganizationModel attachOrganization(ArchiveModel archiveModel, String organizationName) {
"""
Attach a {@link OrganizationModel} with the given organization to the provided {@link ArchiveModel}. If an existing Model
exists with the provided organization, that one will be used instead.
"""
OrganizationModel model = getUnique(getQuery().traverse(g -> g.has(OrganizationModel.NAME, organizationName)).getRawTraversal());
if (model == null)
{
model = create();
model.setName(organizationName);
model.addArchiveModel(archiveModel);
}
else
{
return attachOrganization(model, archiveModel);
}
return model;
} | java | public OrganizationModel attachOrganization(ArchiveModel archiveModel, String organizationName)
{
OrganizationModel model = getUnique(getQuery().traverse(g -> g.has(OrganizationModel.NAME, organizationName)).getRawTraversal());
if (model == null)
{
model = create();
model.setName(organizationName);
model.addArchiveModel(archiveModel);
}
else
{
return attachOrganization(model, archiveModel);
}
return model;
} | [
"public",
"OrganizationModel",
"attachOrganization",
"(",
"ArchiveModel",
"archiveModel",
",",
"String",
"organizationName",
")",
"{",
"OrganizationModel",
"model",
"=",
"getUnique",
"(",
"getQuery",
"(",
")",
".",
"traverse",
"(",
"g",
"->",
"g",
".",
"has",
"(",
"OrganizationModel",
".",
"NAME",
",",
"organizationName",
")",
")",
".",
"getRawTraversal",
"(",
")",
")",
";",
"if",
"(",
"model",
"==",
"null",
")",
"{",
"model",
"=",
"create",
"(",
")",
";",
"model",
".",
"setName",
"(",
"organizationName",
")",
";",
"model",
".",
"addArchiveModel",
"(",
"archiveModel",
")",
";",
"}",
"else",
"{",
"return",
"attachOrganization",
"(",
"model",
",",
"archiveModel",
")",
";",
"}",
"return",
"model",
";",
"}"
] | Attach a {@link OrganizationModel} with the given organization to the provided {@link ArchiveModel}. If an existing Model
exists with the provided organization, that one will be used instead. | [
"Attach",
"a",
"{"
] | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/graph/api/src/main/java/org/jboss/windup/graph/service/OrganizationService.java#L26-L41 |
vlingo/vlingo-actors | src/main/java/io/vlingo/actors/Stage.java | Stage.actorFor | public <T> T actorFor(final Class<T> protocol, final Definition definition) {
"""
Answers the {@code T} protocol of the newly created {@code Actor} that implements the {@code protocol}.
@param <T> the protocol type
@param protocol the {@code Class<T>} protocol
@param definition the {@code Definition} used to initialize the newly created {@code Actor}
@return T
"""
return actorFor(
protocol,
definition,
definition.parentOr(world.defaultParent()),
definition.supervisor(),
definition.loggerOr(world.defaultLogger()));
} | java | public <T> T actorFor(final Class<T> protocol, final Definition definition) {
return actorFor(
protocol,
definition,
definition.parentOr(world.defaultParent()),
definition.supervisor(),
definition.loggerOr(world.defaultLogger()));
} | [
"public",
"<",
"T",
">",
"T",
"actorFor",
"(",
"final",
"Class",
"<",
"T",
">",
"protocol",
",",
"final",
"Definition",
"definition",
")",
"{",
"return",
"actorFor",
"(",
"protocol",
",",
"definition",
",",
"definition",
".",
"parentOr",
"(",
"world",
".",
"defaultParent",
"(",
")",
")",
",",
"definition",
".",
"supervisor",
"(",
")",
",",
"definition",
".",
"loggerOr",
"(",
"world",
".",
"defaultLogger",
"(",
")",
")",
")",
";",
"}"
] | Answers the {@code T} protocol of the newly created {@code Actor} that implements the {@code protocol}.
@param <T> the protocol type
@param protocol the {@code Class<T>} protocol
@param definition the {@code Definition} used to initialize the newly created {@code Actor}
@return T | [
"Answers",
"the",
"{"
] | train | https://github.com/vlingo/vlingo-actors/blob/c7d046fd139c0490cf0fd2588d7dc2f792f13493/src/main/java/io/vlingo/actors/Stage.java#L60-L67 |
apache/flink | flink-core/src/main/java/org/apache/flink/util/ExecutorUtils.java | ExecutorUtils.gracefulShutdown | public static void gracefulShutdown(long timeout, TimeUnit unit, ExecutorService... executorServices) {
"""
Gracefully shutdown the given {@link ExecutorService}. The call waits the given timeout that
all ExecutorServices terminate. If the ExecutorServices do not terminate in this time,
they will be shut down hard.
@param timeout to wait for the termination of all ExecutorServices
@param unit of the timeout
@param executorServices to shut down
"""
for (ExecutorService executorService: executorServices) {
executorService.shutdown();
}
boolean wasInterrupted = false;
final long endTime = unit.toMillis(timeout) + System.currentTimeMillis();
long timeLeft = unit.toMillis(timeout);
boolean hasTimeLeft = timeLeft > 0L;
for (ExecutorService executorService: executorServices) {
if (wasInterrupted || !hasTimeLeft) {
executorService.shutdownNow();
} else {
try {
if (!executorService.awaitTermination(timeLeft, TimeUnit.MILLISECONDS)) {
LOG.warn("ExecutorService did not terminate in time. Shutting it down now.");
executorService.shutdownNow();
}
} catch (InterruptedException e) {
LOG.warn("Interrupted while shutting down executor services. Shutting all " +
"remaining ExecutorServices down now.", e);
executorService.shutdownNow();
wasInterrupted = true;
Thread.currentThread().interrupt();
}
timeLeft = endTime - System.currentTimeMillis();
hasTimeLeft = timeLeft > 0L;
}
}
} | java | public static void gracefulShutdown(long timeout, TimeUnit unit, ExecutorService... executorServices) {
for (ExecutorService executorService: executorServices) {
executorService.shutdown();
}
boolean wasInterrupted = false;
final long endTime = unit.toMillis(timeout) + System.currentTimeMillis();
long timeLeft = unit.toMillis(timeout);
boolean hasTimeLeft = timeLeft > 0L;
for (ExecutorService executorService: executorServices) {
if (wasInterrupted || !hasTimeLeft) {
executorService.shutdownNow();
} else {
try {
if (!executorService.awaitTermination(timeLeft, TimeUnit.MILLISECONDS)) {
LOG.warn("ExecutorService did not terminate in time. Shutting it down now.");
executorService.shutdownNow();
}
} catch (InterruptedException e) {
LOG.warn("Interrupted while shutting down executor services. Shutting all " +
"remaining ExecutorServices down now.", e);
executorService.shutdownNow();
wasInterrupted = true;
Thread.currentThread().interrupt();
}
timeLeft = endTime - System.currentTimeMillis();
hasTimeLeft = timeLeft > 0L;
}
}
} | [
"public",
"static",
"void",
"gracefulShutdown",
"(",
"long",
"timeout",
",",
"TimeUnit",
"unit",
",",
"ExecutorService",
"...",
"executorServices",
")",
"{",
"for",
"(",
"ExecutorService",
"executorService",
":",
"executorServices",
")",
"{",
"executorService",
".",
"shutdown",
"(",
")",
";",
"}",
"boolean",
"wasInterrupted",
"=",
"false",
";",
"final",
"long",
"endTime",
"=",
"unit",
".",
"toMillis",
"(",
"timeout",
")",
"+",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"long",
"timeLeft",
"=",
"unit",
".",
"toMillis",
"(",
"timeout",
")",
";",
"boolean",
"hasTimeLeft",
"=",
"timeLeft",
">",
"0L",
";",
"for",
"(",
"ExecutorService",
"executorService",
":",
"executorServices",
")",
"{",
"if",
"(",
"wasInterrupted",
"||",
"!",
"hasTimeLeft",
")",
"{",
"executorService",
".",
"shutdownNow",
"(",
")",
";",
"}",
"else",
"{",
"try",
"{",
"if",
"(",
"!",
"executorService",
".",
"awaitTermination",
"(",
"timeLeft",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"ExecutorService did not terminate in time. Shutting it down now.\"",
")",
";",
"executorService",
".",
"shutdownNow",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"Interrupted while shutting down executor services. Shutting all \"",
"+",
"\"remaining ExecutorServices down now.\"",
",",
"e",
")",
";",
"executorService",
".",
"shutdownNow",
"(",
")",
";",
"wasInterrupted",
"=",
"true",
";",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"}",
"timeLeft",
"=",
"endTime",
"-",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"hasTimeLeft",
"=",
"timeLeft",
">",
"0L",
";",
"}",
"}",
"}"
] | Gracefully shutdown the given {@link ExecutorService}. The call waits the given timeout that
all ExecutorServices terminate. If the ExecutorServices do not terminate in this time,
they will be shut down hard.
@param timeout to wait for the termination of all ExecutorServices
@param unit of the timeout
@param executorServices to shut down | [
"Gracefully",
"shutdown",
"the",
"given",
"{",
"@link",
"ExecutorService",
"}",
".",
"The",
"call",
"waits",
"the",
"given",
"timeout",
"that",
"all",
"ExecutorServices",
"terminate",
".",
"If",
"the",
"ExecutorServices",
"do",
"not",
"terminate",
"in",
"this",
"time",
"they",
"will",
"be",
"shut",
"down",
"hard",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/ExecutorUtils.java#L44-L77 |
HubSpot/Singularity | SingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java | SingularityClient.getPendingSingularityRequests | public Collection<SingularityPendingRequest> getPendingSingularityRequests() {
"""
Get all requests that are pending to become ACTIVE
@return
A collection of {@link SingularityPendingRequest} instances that hold information about the singularity requests that are pending to become ACTIVE
"""
final Function<String, String> requestUri = (host) -> String.format(REQUESTS_GET_PENDING_FORMAT, getApiBase(host));
return getCollection(requestUri, "pending requests", PENDING_REQUESTS_COLLECTION);
} | java | public Collection<SingularityPendingRequest> getPendingSingularityRequests() {
final Function<String, String> requestUri = (host) -> String.format(REQUESTS_GET_PENDING_FORMAT, getApiBase(host));
return getCollection(requestUri, "pending requests", PENDING_REQUESTS_COLLECTION);
} | [
"public",
"Collection",
"<",
"SingularityPendingRequest",
">",
"getPendingSingularityRequests",
"(",
")",
"{",
"final",
"Function",
"<",
"String",
",",
"String",
">",
"requestUri",
"=",
"(",
"host",
")",
"-",
">",
"String",
".",
"format",
"(",
"REQUESTS_GET_PENDING_FORMAT",
",",
"getApiBase",
"(",
"host",
")",
")",
";",
"return",
"getCollection",
"(",
"requestUri",
",",
"\"pending requests\"",
",",
"PENDING_REQUESTS_COLLECTION",
")",
";",
"}"
] | Get all requests that are pending to become ACTIVE
@return
A collection of {@link SingularityPendingRequest} instances that hold information about the singularity requests that are pending to become ACTIVE | [
"Get",
"all",
"requests",
"that",
"are",
"pending",
"to",
"become",
"ACTIVE"
] | train | https://github.com/HubSpot/Singularity/blob/384a8c16a10aa076af5ca45c8dfcedab9e5122c8/SingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java#L802-L806 |
facebookarchive/hadoop-20 | src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/AvatarShell.java | AvatarShell.waitForLastTxIdNode | private void waitForLastTxIdNode(AvatarZooKeeperClient zk, Configuration conf)
throws Exception {
"""
Waits till the last txid node appears in Zookeeper, such that it matches
the ssid node.
"""
// Gather session id and transaction id data.
String address = conf.get(NameNode.DFS_NAMENODE_RPC_ADDRESS_KEY);
long maxWaitTime = this.getMaxWaitTimeForWaitTxid();
long start = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() - start > maxWaitTime) {
throw new IOException("No valid last txid znode found");
}
try {
long sessionId = zk.getPrimarySsId(address, false);
ZookeeperTxId zkTxId = zk.getPrimaryLastTxId(address, false);
if (sessionId != zkTxId.getSessionId()) {
LOG.warn("Session Id in the ssid node : " + sessionId
+ " does not match the session Id in the txid node : "
+ zkTxId.getSessionId() + " retrying...");
Thread.sleep(retrySleep);
continue;
}
} catch (Throwable e) {
LOG.warn("Caught exception : " + e + " retrying ...");
Thread.sleep(retrySleep);
continue;
}
break;
}
} | java | private void waitForLastTxIdNode(AvatarZooKeeperClient zk, Configuration conf)
throws Exception {
// Gather session id and transaction id data.
String address = conf.get(NameNode.DFS_NAMENODE_RPC_ADDRESS_KEY);
long maxWaitTime = this.getMaxWaitTimeForWaitTxid();
long start = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() - start > maxWaitTime) {
throw new IOException("No valid last txid znode found");
}
try {
long sessionId = zk.getPrimarySsId(address, false);
ZookeeperTxId zkTxId = zk.getPrimaryLastTxId(address, false);
if (sessionId != zkTxId.getSessionId()) {
LOG.warn("Session Id in the ssid node : " + sessionId
+ " does not match the session Id in the txid node : "
+ zkTxId.getSessionId() + " retrying...");
Thread.sleep(retrySleep);
continue;
}
} catch (Throwable e) {
LOG.warn("Caught exception : " + e + " retrying ...");
Thread.sleep(retrySleep);
continue;
}
break;
}
} | [
"private",
"void",
"waitForLastTxIdNode",
"(",
"AvatarZooKeeperClient",
"zk",
",",
"Configuration",
"conf",
")",
"throws",
"Exception",
"{",
"// Gather session id and transaction id data.",
"String",
"address",
"=",
"conf",
".",
"get",
"(",
"NameNode",
".",
"DFS_NAMENODE_RPC_ADDRESS_KEY",
")",
";",
"long",
"maxWaitTime",
"=",
"this",
".",
"getMaxWaitTimeForWaitTxid",
"(",
")",
";",
"long",
"start",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"while",
"(",
"true",
")",
"{",
"if",
"(",
"System",
".",
"currentTimeMillis",
"(",
")",
"-",
"start",
">",
"maxWaitTime",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"No valid last txid znode found\"",
")",
";",
"}",
"try",
"{",
"long",
"sessionId",
"=",
"zk",
".",
"getPrimarySsId",
"(",
"address",
",",
"false",
")",
";",
"ZookeeperTxId",
"zkTxId",
"=",
"zk",
".",
"getPrimaryLastTxId",
"(",
"address",
",",
"false",
")",
";",
"if",
"(",
"sessionId",
"!=",
"zkTxId",
".",
"getSessionId",
"(",
")",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"Session Id in the ssid node : \"",
"+",
"sessionId",
"+",
"\" does not match the session Id in the txid node : \"",
"+",
"zkTxId",
".",
"getSessionId",
"(",
")",
"+",
"\" retrying...\"",
")",
";",
"Thread",
".",
"sleep",
"(",
"retrySleep",
")",
";",
"continue",
";",
"}",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"Caught exception : \"",
"+",
"e",
"+",
"\" retrying ...\"",
")",
";",
"Thread",
".",
"sleep",
"(",
"retrySleep",
")",
";",
"continue",
";",
"}",
"break",
";",
"}",
"}"
] | Waits till the last txid node appears in Zookeeper, such that it matches
the ssid node. | [
"Waits",
"till",
"the",
"last",
"txid",
"node",
"appears",
"in",
"Zookeeper",
"such",
"that",
"it",
"matches",
"the",
"ssid",
"node",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/AvatarShell.java#L216-L243 |
TheHortonMachine/hortonmachine | dbs/src/main/java/org/hortonmachine/dbs/utils/CommonQueries.java | CommonQueries.getDistanceBetween | public static double getDistanceBetween( IHMConnection connection, Coordinate p1, Coordinate p2, int srid ) throws Exception {
"""
Calculates the GeodesicLength between to points.
@param connection the database connection.
@param p1 the first point.
@param p2 the second point.
@param srid the srid. If <0, 4326 will be used. This needs to be a geographic prj.
@return the distance.
@throws Exception
"""
if (srid < 0) {
srid = 4326;
}
GeometryFactory gf = new GeometryFactory();
LineString lineString = gf.createLineString(new Coordinate[]{p1, p2});
String sql = "select GeodesicLength(LineFromText(\"" + lineString.toText() + "\"," + srid + "));";
try (IHMStatement stmt = connection.createStatement(); IHMResultSet rs = stmt.executeQuery(sql);) {
if (rs.next()) {
double length = rs.getDouble(1);
return length;
}
throw new RuntimeException("Could not calculate distance.");
}
} | java | public static double getDistanceBetween( IHMConnection connection, Coordinate p1, Coordinate p2, int srid ) throws Exception {
if (srid < 0) {
srid = 4326;
}
GeometryFactory gf = new GeometryFactory();
LineString lineString = gf.createLineString(new Coordinate[]{p1, p2});
String sql = "select GeodesicLength(LineFromText(\"" + lineString.toText() + "\"," + srid + "));";
try (IHMStatement stmt = connection.createStatement(); IHMResultSet rs = stmt.executeQuery(sql);) {
if (rs.next()) {
double length = rs.getDouble(1);
return length;
}
throw new RuntimeException("Could not calculate distance.");
}
} | [
"public",
"static",
"double",
"getDistanceBetween",
"(",
"IHMConnection",
"connection",
",",
"Coordinate",
"p1",
",",
"Coordinate",
"p2",
",",
"int",
"srid",
")",
"throws",
"Exception",
"{",
"if",
"(",
"srid",
"<",
"0",
")",
"{",
"srid",
"=",
"4326",
";",
"}",
"GeometryFactory",
"gf",
"=",
"new",
"GeometryFactory",
"(",
")",
";",
"LineString",
"lineString",
"=",
"gf",
".",
"createLineString",
"(",
"new",
"Coordinate",
"[",
"]",
"{",
"p1",
",",
"p2",
"}",
")",
";",
"String",
"sql",
"=",
"\"select GeodesicLength(LineFromText(\\\"\"",
"+",
"lineString",
".",
"toText",
"(",
")",
"+",
"\"\\\",\"",
"+",
"srid",
"+",
"\"));\"",
";",
"try",
"(",
"IHMStatement",
"stmt",
"=",
"connection",
".",
"createStatement",
"(",
")",
";",
"IHMResultSet",
"rs",
"=",
"stmt",
".",
"executeQuery",
"(",
"sql",
")",
";",
")",
"{",
"if",
"(",
"rs",
".",
"next",
"(",
")",
")",
"{",
"double",
"length",
"=",
"rs",
".",
"getDouble",
"(",
"1",
")",
";",
"return",
"length",
";",
"}",
"throw",
"new",
"RuntimeException",
"(",
"\"Could not calculate distance.\"",
")",
";",
"}",
"}"
] | Calculates the GeodesicLength between to points.
@param connection the database connection.
@param p1 the first point.
@param p2 the second point.
@param srid the srid. If <0, 4326 will be used. This needs to be a geographic prj.
@return the distance.
@throws Exception | [
"Calculates",
"the",
"GeodesicLength",
"between",
"to",
"points",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/org/hortonmachine/dbs/utils/CommonQueries.java#L157-L172 |
JOML-CI/JOML | src/org/joml/Intersectionf.java | Intersectionf.intersectRayPlane | public static float intersectRayPlane(Vector3fc origin, Vector3fc dir, Vector3fc point, Vector3fc normal, float epsilon) {
"""
Test whether the ray with given <code>origin</code> and direction <code>dir</code> intersects the plane
containing the given <code>point</code> and having the given <code>normal</code>, and return the
value of the parameter <i>t</i> in the ray equation <i>p(t) = origin + t * dir</i> of the intersection point.
<p>
This method returns <code>-1.0</code> if the ray does not intersect the plane, because it is either parallel to the plane or its direction points
away from the plane or the ray's origin is on the <i>negative</i> side of the plane (i.e. the plane's normal points away from the ray's origin).
<p>
Reference: <a href="https://www.siggraph.org/education/materials/HyperGraph/raytrace/rayplane_intersection.htm">https://www.siggraph.org/</a>
@param origin
the ray's origin
@param dir
the ray's direction
@param point
a point on the plane
@param normal
the plane's normal
@param epsilon
some small epsilon for when the ray is parallel to the plane
@return the value of the parameter <i>t</i> in the ray equation <i>p(t) = origin + t * dir</i> of the intersection point, if the ray
intersects the plane; <code>-1.0</code> otherwise
"""
return intersectRayPlane(origin.x(), origin.y(), origin.z(), dir.x(), dir.y(), dir.z(), point.x(), point.y(), point.z(), normal.x(), normal.y(), normal.z(), epsilon);
} | java | public static float intersectRayPlane(Vector3fc origin, Vector3fc dir, Vector3fc point, Vector3fc normal, float epsilon) {
return intersectRayPlane(origin.x(), origin.y(), origin.z(), dir.x(), dir.y(), dir.z(), point.x(), point.y(), point.z(), normal.x(), normal.y(), normal.z(), epsilon);
} | [
"public",
"static",
"float",
"intersectRayPlane",
"(",
"Vector3fc",
"origin",
",",
"Vector3fc",
"dir",
",",
"Vector3fc",
"point",
",",
"Vector3fc",
"normal",
",",
"float",
"epsilon",
")",
"{",
"return",
"intersectRayPlane",
"(",
"origin",
".",
"x",
"(",
")",
",",
"origin",
".",
"y",
"(",
")",
",",
"origin",
".",
"z",
"(",
")",
",",
"dir",
".",
"x",
"(",
")",
",",
"dir",
".",
"y",
"(",
")",
",",
"dir",
".",
"z",
"(",
")",
",",
"point",
".",
"x",
"(",
")",
",",
"point",
".",
"y",
"(",
")",
",",
"point",
".",
"z",
"(",
")",
",",
"normal",
".",
"x",
"(",
")",
",",
"normal",
".",
"y",
"(",
")",
",",
"normal",
".",
"z",
"(",
")",
",",
"epsilon",
")",
";",
"}"
] | Test whether the ray with given <code>origin</code> and direction <code>dir</code> intersects the plane
containing the given <code>point</code> and having the given <code>normal</code>, and return the
value of the parameter <i>t</i> in the ray equation <i>p(t) = origin + t * dir</i> of the intersection point.
<p>
This method returns <code>-1.0</code> if the ray does not intersect the plane, because it is either parallel to the plane or its direction points
away from the plane or the ray's origin is on the <i>negative</i> side of the plane (i.e. the plane's normal points away from the ray's origin).
<p>
Reference: <a href="https://www.siggraph.org/education/materials/HyperGraph/raytrace/rayplane_intersection.htm">https://www.siggraph.org/</a>
@param origin
the ray's origin
@param dir
the ray's direction
@param point
a point on the plane
@param normal
the plane's normal
@param epsilon
some small epsilon for when the ray is parallel to the plane
@return the value of the parameter <i>t</i> in the ray equation <i>p(t) = origin + t * dir</i> of the intersection point, if the ray
intersects the plane; <code>-1.0</code> otherwise | [
"Test",
"whether",
"the",
"ray",
"with",
"given",
"<code",
">",
"origin<",
"/",
"code",
">",
"and",
"direction",
"<code",
">",
"dir<",
"/",
"code",
">",
"intersects",
"the",
"plane",
"containing",
"the",
"given",
"<code",
">",
"point<",
"/",
"code",
">",
"and",
"having",
"the",
"given",
"<code",
">",
"normal<",
"/",
"code",
">",
"and",
"return",
"the",
"value",
"of",
"the",
"parameter",
"<i",
">",
"t<",
"/",
"i",
">",
"in",
"the",
"ray",
"equation",
"<i",
">",
"p",
"(",
"t",
")",
"=",
"origin",
"+",
"t",
"*",
"dir<",
"/",
"i",
">",
"of",
"the",
"intersection",
"point",
".",
"<p",
">",
"This",
"method",
"returns",
"<code",
">",
"-",
"1",
".",
"0<",
"/",
"code",
">",
"if",
"the",
"ray",
"does",
"not",
"intersect",
"the",
"plane",
"because",
"it",
"is",
"either",
"parallel",
"to",
"the",
"plane",
"or",
"its",
"direction",
"points",
"away",
"from",
"the",
"plane",
"or",
"the",
"ray",
"s",
"origin",
"is",
"on",
"the",
"<i",
">",
"negative<",
"/",
"i",
">",
"side",
"of",
"the",
"plane",
"(",
"i",
".",
"e",
".",
"the",
"plane",
"s",
"normal",
"points",
"away",
"from",
"the",
"ray",
"s",
"origin",
")",
".",
"<p",
">",
"Reference",
":",
"<a",
"href",
"=",
"https",
":",
"//",
"www",
".",
"siggraph",
".",
"org",
"/",
"education",
"/",
"materials",
"/",
"HyperGraph",
"/",
"raytrace",
"/",
"rayplane_intersection",
".",
"htm",
">",
"https",
":",
"//",
"www",
".",
"siggraph",
".",
"org",
"/",
"<",
"/",
"a",
">"
] | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Intersectionf.java#L1084-L1086 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/modules/r/morpher/Thin.java | Thin.kernelMatch | private boolean kernelMatch( Point p, int[][] pixels, int w, int h, int[] kernel ) {
"""
Returns true if the 8 neighbours of p match the kernel
0 is background
1 is foreground
2 is don't care.
@param p the point at the centre of the
9 pixel neighbourhood
@param pixels the 2D array of the image
@param w the width of the image
@param h the height of the image
@param kernel the array of the kernel values
@return True if the kernel and image match.
"""
int matched = 0;
for( int j = -1; j < 2; ++j ) {
for( int i = -1; i < 2; ++i ) {
if (kernel[((j + 1) * 3) + (i + 1)] == 2) {
++matched;
} else if ((p.x + i >= 0)
&& (p.x + i < w)
&& (p.y + j >= 0)
&& (p.y + j < h)
&& (((pixels[p.x + i][p.y + j] == BinaryFast.FOREGROUND) && (kernel[((j + 1) * 3) + (i + 1)] == 1)) || ((pixels[p.x
+ i][p.y + j] == BinaryFast.BACKGROUND) && (kernel[((j + 1) * 3) + (i + 1)] == 0)))) {
++matched;
}
}
}
if (matched == 9) {
return true;
} else
return false;
} | java | private boolean kernelMatch( Point p, int[][] pixels, int w, int h, int[] kernel ) {
int matched = 0;
for( int j = -1; j < 2; ++j ) {
for( int i = -1; i < 2; ++i ) {
if (kernel[((j + 1) * 3) + (i + 1)] == 2) {
++matched;
} else if ((p.x + i >= 0)
&& (p.x + i < w)
&& (p.y + j >= 0)
&& (p.y + j < h)
&& (((pixels[p.x + i][p.y + j] == BinaryFast.FOREGROUND) && (kernel[((j + 1) * 3) + (i + 1)] == 1)) || ((pixels[p.x
+ i][p.y + j] == BinaryFast.BACKGROUND) && (kernel[((j + 1) * 3) + (i + 1)] == 0)))) {
++matched;
}
}
}
if (matched == 9) {
return true;
} else
return false;
} | [
"private",
"boolean",
"kernelMatch",
"(",
"Point",
"p",
",",
"int",
"[",
"]",
"[",
"]",
"pixels",
",",
"int",
"w",
",",
"int",
"h",
",",
"int",
"[",
"]",
"kernel",
")",
"{",
"int",
"matched",
"=",
"0",
";",
"for",
"(",
"int",
"j",
"=",
"-",
"1",
";",
"j",
"<",
"2",
";",
"++",
"j",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"-",
"1",
";",
"i",
"<",
"2",
";",
"++",
"i",
")",
"{",
"if",
"(",
"kernel",
"[",
"(",
"(",
"j",
"+",
"1",
")",
"*",
"3",
")",
"+",
"(",
"i",
"+",
"1",
")",
"]",
"==",
"2",
")",
"{",
"++",
"matched",
";",
"}",
"else",
"if",
"(",
"(",
"p",
".",
"x",
"+",
"i",
">=",
"0",
")",
"&&",
"(",
"p",
".",
"x",
"+",
"i",
"<",
"w",
")",
"&&",
"(",
"p",
".",
"y",
"+",
"j",
">=",
"0",
")",
"&&",
"(",
"p",
".",
"y",
"+",
"j",
"<",
"h",
")",
"&&",
"(",
"(",
"(",
"pixels",
"[",
"p",
".",
"x",
"+",
"i",
"]",
"[",
"p",
".",
"y",
"+",
"j",
"]",
"==",
"BinaryFast",
".",
"FOREGROUND",
")",
"&&",
"(",
"kernel",
"[",
"(",
"(",
"j",
"+",
"1",
")",
"*",
"3",
")",
"+",
"(",
"i",
"+",
"1",
")",
"]",
"==",
"1",
")",
")",
"||",
"(",
"(",
"pixels",
"[",
"p",
".",
"x",
"+",
"i",
"]",
"[",
"p",
".",
"y",
"+",
"j",
"]",
"==",
"BinaryFast",
".",
"BACKGROUND",
")",
"&&",
"(",
"kernel",
"[",
"(",
"(",
"j",
"+",
"1",
")",
"*",
"3",
")",
"+",
"(",
"i",
"+",
"1",
")",
"]",
"==",
"0",
")",
")",
")",
")",
"{",
"++",
"matched",
";",
"}",
"}",
"}",
"if",
"(",
"matched",
"==",
"9",
")",
"{",
"return",
"true",
";",
"}",
"else",
"return",
"false",
";",
"}"
] | Returns true if the 8 neighbours of p match the kernel
0 is background
1 is foreground
2 is don't care.
@param p the point at the centre of the
9 pixel neighbourhood
@param pixels the 2D array of the image
@param w the width of the image
@param h the height of the image
@param kernel the array of the kernel values
@return True if the kernel and image match. | [
"Returns",
"true",
"if",
"the",
"8",
"neighbours",
"of",
"p",
"match",
"the",
"kernel",
"0",
"is",
"background",
"1",
"is",
"foreground",
"2",
"is",
"don",
"t",
"care",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/modules/r/morpher/Thin.java#L137-L157 |
google/error-prone-javac | src/jdk.jshell/share/classes/jdk/internal/jshell/tool/Startup.java | Startup.readFile | private static StartupEntry readFile(String filename, String context, MessageHandler mh) {
"""
Read a external file or a resource.
@param filename file/resource to access
@param context printable non-natural language context for errors
@param mh handler for error messages
@return file as startup entry, or null when error (message has been printed)
"""
if (filename != null) {
try {
byte[] encoded = Files.readAllBytes(toPathResolvingUserHome(filename));
return new StartupEntry(false, filename, new String(encoded),
LocalDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)));
} catch (AccessDeniedException e) {
mh.errormsg("jshell.err.file.not.accessible", context, filename, e.getMessage());
} catch (NoSuchFileException e) {
String resource = getResource(filename);
if (resource != null) {
// Not found as file, but found as resource
return new StartupEntry(true, filename, resource);
}
mh.errormsg("jshell.err.file.not.found", context, filename);
} catch (Exception e) {
mh.errormsg("jshell.err.file.exception", context, filename, e);
}
} else {
mh.errormsg("jshell.err.file.filename", context);
}
return null;
} | java | private static StartupEntry readFile(String filename, String context, MessageHandler mh) {
if (filename != null) {
try {
byte[] encoded = Files.readAllBytes(toPathResolvingUserHome(filename));
return new StartupEntry(false, filename, new String(encoded),
LocalDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)));
} catch (AccessDeniedException e) {
mh.errormsg("jshell.err.file.not.accessible", context, filename, e.getMessage());
} catch (NoSuchFileException e) {
String resource = getResource(filename);
if (resource != null) {
// Not found as file, but found as resource
return new StartupEntry(true, filename, resource);
}
mh.errormsg("jshell.err.file.not.found", context, filename);
} catch (Exception e) {
mh.errormsg("jshell.err.file.exception", context, filename, e);
}
} else {
mh.errormsg("jshell.err.file.filename", context);
}
return null;
} | [
"private",
"static",
"StartupEntry",
"readFile",
"(",
"String",
"filename",
",",
"String",
"context",
",",
"MessageHandler",
"mh",
")",
"{",
"if",
"(",
"filename",
"!=",
"null",
")",
"{",
"try",
"{",
"byte",
"[",
"]",
"encoded",
"=",
"Files",
".",
"readAllBytes",
"(",
"toPathResolvingUserHome",
"(",
"filename",
")",
")",
";",
"return",
"new",
"StartupEntry",
"(",
"false",
",",
"filename",
",",
"new",
"String",
"(",
"encoded",
")",
",",
"LocalDateTime",
".",
"now",
"(",
")",
".",
"format",
"(",
"DateTimeFormatter",
".",
"ofLocalizedDateTime",
"(",
"FormatStyle",
".",
"MEDIUM",
")",
")",
")",
";",
"}",
"catch",
"(",
"AccessDeniedException",
"e",
")",
"{",
"mh",
".",
"errormsg",
"(",
"\"jshell.err.file.not.accessible\"",
",",
"context",
",",
"filename",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"catch",
"(",
"NoSuchFileException",
"e",
")",
"{",
"String",
"resource",
"=",
"getResource",
"(",
"filename",
")",
";",
"if",
"(",
"resource",
"!=",
"null",
")",
"{",
"// Not found as file, but found as resource",
"return",
"new",
"StartupEntry",
"(",
"true",
",",
"filename",
",",
"resource",
")",
";",
"}",
"mh",
".",
"errormsg",
"(",
"\"jshell.err.file.not.found\"",
",",
"context",
",",
"filename",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"mh",
".",
"errormsg",
"(",
"\"jshell.err.file.exception\"",
",",
"context",
",",
"filename",
",",
"e",
")",
";",
"}",
"}",
"else",
"{",
"mh",
".",
"errormsg",
"(",
"\"jshell.err.file.filename\"",
",",
"context",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Read a external file or a resource.
@param filename file/resource to access
@param context printable non-natural language context for errors
@param mh handler for error messages
@return file as startup entry, or null when error (message has been printed) | [
"Read",
"a",
"external",
"file",
"or",
"a",
"resource",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/Startup.java#L294-L317 |
hypfvieh/java-utils | src/main/java/com/github/hypfvieh/util/ConverterUtil.java | ConverterUtil.strToInt | public static Integer strToInt(String _str, Integer _default) {
"""
Convert given String to Integer, returns _default if String is not an integer.
@param _str
@param _default
@return _str as Integer or _default value
"""
if (_str == null) {
return _default;
}
if (TypeUtil.isInteger(_str, true)) {
return Integer.valueOf(_str);
} else {
return _default;
}
} | java | public static Integer strToInt(String _str, Integer _default) {
if (_str == null) {
return _default;
}
if (TypeUtil.isInteger(_str, true)) {
return Integer.valueOf(_str);
} else {
return _default;
}
} | [
"public",
"static",
"Integer",
"strToInt",
"(",
"String",
"_str",
",",
"Integer",
"_default",
")",
"{",
"if",
"(",
"_str",
"==",
"null",
")",
"{",
"return",
"_default",
";",
"}",
"if",
"(",
"TypeUtil",
".",
"isInteger",
"(",
"_str",
",",
"true",
")",
")",
"{",
"return",
"Integer",
".",
"valueOf",
"(",
"_str",
")",
";",
"}",
"else",
"{",
"return",
"_default",
";",
"}",
"}"
] | Convert given String to Integer, returns _default if String is not an integer.
@param _str
@param _default
@return _str as Integer or _default value | [
"Convert",
"given",
"String",
"to",
"Integer",
"returns",
"_default",
"if",
"String",
"is",
"not",
"an",
"integer",
"."
] | train | https://github.com/hypfvieh/java-utils/blob/407c32d6b485596d4d2b644f5f7fc7a02d0169c6/src/main/java/com/github/hypfvieh/util/ConverterUtil.java#L25-L34 |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.getDigestOffset | public int getDigestOffset(int algorithm, byte[] handshake, int bufferOffset) {
"""
Returns the digest offset using current validation scheme.
@param algorithm validation algorithm
@param handshake handshake sequence
@param bufferOffset buffer offset
@return digest offset
"""
switch (algorithm) {
case 1:
return getDigestOffset2(handshake, bufferOffset);
default:
case 0:
return getDigestOffset1(handshake, bufferOffset);
}
} | java | public int getDigestOffset(int algorithm, byte[] handshake, int bufferOffset) {
switch (algorithm) {
case 1:
return getDigestOffset2(handshake, bufferOffset);
default:
case 0:
return getDigestOffset1(handshake, bufferOffset);
}
} | [
"public",
"int",
"getDigestOffset",
"(",
"int",
"algorithm",
",",
"byte",
"[",
"]",
"handshake",
",",
"int",
"bufferOffset",
")",
"{",
"switch",
"(",
"algorithm",
")",
"{",
"case",
"1",
":",
"return",
"getDigestOffset2",
"(",
"handshake",
",",
"bufferOffset",
")",
";",
"default",
":",
"case",
"0",
":",
"return",
"getDigestOffset1",
"(",
"handshake",
",",
"bufferOffset",
")",
";",
"}",
"}"
] | Returns the digest offset using current validation scheme.
@param algorithm validation algorithm
@param handshake handshake sequence
@param bufferOffset buffer offset
@return digest offset | [
"Returns",
"the",
"digest",
"offset",
"using",
"current",
"validation",
"scheme",
"."
] | train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L491-L499 |
ios-driver/ios-driver | server/src/main/java/org/uiautomation/ios/application/APPIOSApplication.java | APPIOSApplication.setSafariBuiltinFavorites | public void setSafariBuiltinFavorites() {
"""
Modifies the BuiltinFavorites....plist in safariCopies/safari.app to contain only "about:blank"
"""
File[] files = app.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("BuiltinFavorites") && name.endsWith(".plist");
}
});
for (File plist : files) {
setSafariBuiltinFavories(plist);
}
} | java | public void setSafariBuiltinFavorites() {
File[] files = app.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("BuiltinFavorites") && name.endsWith(".plist");
}
});
for (File plist : files) {
setSafariBuiltinFavories(plist);
}
} | [
"public",
"void",
"setSafariBuiltinFavorites",
"(",
")",
"{",
"File",
"[",
"]",
"files",
"=",
"app",
".",
"listFiles",
"(",
"new",
"FilenameFilter",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"accept",
"(",
"File",
"dir",
",",
"String",
"name",
")",
"{",
"return",
"name",
".",
"startsWith",
"(",
"\"BuiltinFavorites\"",
")",
"&&",
"name",
".",
"endsWith",
"(",
"\".plist\"",
")",
";",
"}",
"}",
")",
";",
"for",
"(",
"File",
"plist",
":",
"files",
")",
"{",
"setSafariBuiltinFavories",
"(",
"plist",
")",
";",
"}",
"}"
] | Modifies the BuiltinFavorites....plist in safariCopies/safari.app to contain only "about:blank" | [
"Modifies",
"the",
"BuiltinFavorites",
"....",
"plist",
"in",
"safariCopies",
"/",
"safari",
".",
"app",
"to",
"contain",
"only",
"about",
":",
"blank"
] | train | https://github.com/ios-driver/ios-driver/blob/a9744419508d970fbb1ce18e4326cc624b237c8b/server/src/main/java/org/uiautomation/ios/application/APPIOSApplication.java#L385-L395 |
aws/aws-sdk-java | aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/CreateChannelRequest.java | CreateChannelRequest.withTags | public CreateChannelRequest withTags(java.util.Map<String, String> tags) {
"""
A collection of key-value pairs.
@param tags
A collection of key-value pairs.
@return Returns a reference to this object so that method calls can be chained together.
"""
setTags(tags);
return this;
} | java | public CreateChannelRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"CreateChannelRequest",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | A collection of key-value pairs.
@param tags
A collection of key-value pairs.
@return Returns a reference to this object so that method calls can be chained together. | [
"A",
"collection",
"of",
"key",
"-",
"value",
"pairs",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/CreateChannelRequest.java#L507-L510 |
eclipse/hawkbit | hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/colorpicker/ColorPickerHelper.java | ColorPickerHelper.rgbToColorConverter | public static Color rgbToColorConverter(final String value) {
"""
Covert RGB code to {@link Color}.
@param value
RGB vale
@return Color
"""
if (StringUtils.isEmpty(value) || (!StringUtils.isEmpty(value) && !value.startsWith("rgb"))) {
throw new IllegalArgumentException(
"String to convert is empty or of invalid format - value: '" + value + "'");
}
// RGB color format rgb/rgba(255,255,255,0.1)
final String[] colors = value.substring(value.indexOf('(') + 1, value.length() - 1).split(",");
final int red = Integer.parseInt(colors[0]);
final int green = Integer.parseInt(colors[1]);
final int blue = Integer.parseInt(colors[2]);
if (colors.length > 3) {
final int alpha = (int) (Double.parseDouble(colors[3]) * 255D);
return new Color(red, green, blue, alpha);
}
return new Color(red, green, blue);
} | java | public static Color rgbToColorConverter(final String value) {
if (StringUtils.isEmpty(value) || (!StringUtils.isEmpty(value) && !value.startsWith("rgb"))) {
throw new IllegalArgumentException(
"String to convert is empty or of invalid format - value: '" + value + "'");
}
// RGB color format rgb/rgba(255,255,255,0.1)
final String[] colors = value.substring(value.indexOf('(') + 1, value.length() - 1).split(",");
final int red = Integer.parseInt(colors[0]);
final int green = Integer.parseInt(colors[1]);
final int blue = Integer.parseInt(colors[2]);
if (colors.length > 3) {
final int alpha = (int) (Double.parseDouble(colors[3]) * 255D);
return new Color(red, green, blue, alpha);
}
return new Color(red, green, blue);
} | [
"public",
"static",
"Color",
"rgbToColorConverter",
"(",
"final",
"String",
"value",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"value",
")",
"||",
"(",
"!",
"StringUtils",
".",
"isEmpty",
"(",
"value",
")",
"&&",
"!",
"value",
".",
"startsWith",
"(",
"\"rgb\"",
")",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"String to convert is empty or of invalid format - value: '\"",
"+",
"value",
"+",
"\"'\"",
")",
";",
"}",
"// RGB color format rgb/rgba(255,255,255,0.1)",
"final",
"String",
"[",
"]",
"colors",
"=",
"value",
".",
"substring",
"(",
"value",
".",
"indexOf",
"(",
"'",
"'",
")",
"+",
"1",
",",
"value",
".",
"length",
"(",
")",
"-",
"1",
")",
".",
"split",
"(",
"\",\"",
")",
";",
"final",
"int",
"red",
"=",
"Integer",
".",
"parseInt",
"(",
"colors",
"[",
"0",
"]",
")",
";",
"final",
"int",
"green",
"=",
"Integer",
".",
"parseInt",
"(",
"colors",
"[",
"1",
"]",
")",
";",
"final",
"int",
"blue",
"=",
"Integer",
".",
"parseInt",
"(",
"colors",
"[",
"2",
"]",
")",
";",
"if",
"(",
"colors",
".",
"length",
">",
"3",
")",
"{",
"final",
"int",
"alpha",
"=",
"(",
"int",
")",
"(",
"Double",
".",
"parseDouble",
"(",
"colors",
"[",
"3",
"]",
")",
"*",
"255D",
")",
";",
"return",
"new",
"Color",
"(",
"red",
",",
"green",
",",
"blue",
",",
"alpha",
")",
";",
"}",
"return",
"new",
"Color",
"(",
"red",
",",
"green",
",",
"blue",
")",
";",
"}"
] | Covert RGB code to {@link Color}.
@param value
RGB vale
@return Color | [
"Covert",
"RGB",
"code",
"to",
"{",
"@link",
"Color",
"}",
"."
] | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/colorpicker/ColorPickerHelper.java#L51-L68 |
Hygieia/Hygieia | collectors/misc/score/src/main/java/com/capitalone/dashboard/widget/QualityWidgetScore.java | QualityWidgetScore.processQualityCCScore | private void processQualityCCScore(
ScoreComponentSettings qualityCCSettings,
Iterable<CodeQuality> codeQualityIterable,
List<ScoreWeight> categoryScores) {
"""
Process Code Coverage score
@param qualityCCSettings Code Coverage Param Settings
@param codeQualityIterable Quality values
@param categoryScores List of category scores
"""
ScoreWeight qualityCCScore = getCategoryScoreByIdName(categoryScores, WIDGET_QUALITY_CC_ID_NAME);
Double qualityCCRatio = fetchQualityValue(codeQualityIterable, QUALITY_PARAM_CC);
if (null == qualityCCRatio) {
qualityCCScore.setScore(
qualityCCSettings.getCriteria().getNoDataFound()
);
qualityCCScore.setMessage(Constants.SCORE_ERROR_NO_DATA_FOUND);
qualityCCScore.setState(ScoreWeight.ProcessingState.criteria_failed);
} else {
try {
//Check thresholds at widget level
checkPercentThresholds(qualityCCSettings, qualityCCRatio);
qualityCCScore.setScore(
new ScoreTypeValue(qualityCCRatio)
);
qualityCCScore.setState(ScoreWeight.ProcessingState.complete);
} catch (ThresholdException ex) {
setThresholdFailureWeight(ex, qualityCCScore);
}
}
} | java | private void processQualityCCScore(
ScoreComponentSettings qualityCCSettings,
Iterable<CodeQuality> codeQualityIterable,
List<ScoreWeight> categoryScores) {
ScoreWeight qualityCCScore = getCategoryScoreByIdName(categoryScores, WIDGET_QUALITY_CC_ID_NAME);
Double qualityCCRatio = fetchQualityValue(codeQualityIterable, QUALITY_PARAM_CC);
if (null == qualityCCRatio) {
qualityCCScore.setScore(
qualityCCSettings.getCriteria().getNoDataFound()
);
qualityCCScore.setMessage(Constants.SCORE_ERROR_NO_DATA_FOUND);
qualityCCScore.setState(ScoreWeight.ProcessingState.criteria_failed);
} else {
try {
//Check thresholds at widget level
checkPercentThresholds(qualityCCSettings, qualityCCRatio);
qualityCCScore.setScore(
new ScoreTypeValue(qualityCCRatio)
);
qualityCCScore.setState(ScoreWeight.ProcessingState.complete);
} catch (ThresholdException ex) {
setThresholdFailureWeight(ex, qualityCCScore);
}
}
} | [
"private",
"void",
"processQualityCCScore",
"(",
"ScoreComponentSettings",
"qualityCCSettings",
",",
"Iterable",
"<",
"CodeQuality",
">",
"codeQualityIterable",
",",
"List",
"<",
"ScoreWeight",
">",
"categoryScores",
")",
"{",
"ScoreWeight",
"qualityCCScore",
"=",
"getCategoryScoreByIdName",
"(",
"categoryScores",
",",
"WIDGET_QUALITY_CC_ID_NAME",
")",
";",
"Double",
"qualityCCRatio",
"=",
"fetchQualityValue",
"(",
"codeQualityIterable",
",",
"QUALITY_PARAM_CC",
")",
";",
"if",
"(",
"null",
"==",
"qualityCCRatio",
")",
"{",
"qualityCCScore",
".",
"setScore",
"(",
"qualityCCSettings",
".",
"getCriteria",
"(",
")",
".",
"getNoDataFound",
"(",
")",
")",
";",
"qualityCCScore",
".",
"setMessage",
"(",
"Constants",
".",
"SCORE_ERROR_NO_DATA_FOUND",
")",
";",
"qualityCCScore",
".",
"setState",
"(",
"ScoreWeight",
".",
"ProcessingState",
".",
"criteria_failed",
")",
";",
"}",
"else",
"{",
"try",
"{",
"//Check thresholds at widget level",
"checkPercentThresholds",
"(",
"qualityCCSettings",
",",
"qualityCCRatio",
")",
";",
"qualityCCScore",
".",
"setScore",
"(",
"new",
"ScoreTypeValue",
"(",
"qualityCCRatio",
")",
")",
";",
"qualityCCScore",
".",
"setState",
"(",
"ScoreWeight",
".",
"ProcessingState",
".",
"complete",
")",
";",
"}",
"catch",
"(",
"ThresholdException",
"ex",
")",
"{",
"setThresholdFailureWeight",
"(",
"ex",
",",
"qualityCCScore",
")",
";",
"}",
"}",
"}"
] | Process Code Coverage score
@param qualityCCSettings Code Coverage Param Settings
@param codeQualityIterable Quality values
@param categoryScores List of category scores | [
"Process",
"Code",
"Coverage",
"score"
] | train | https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/collectors/misc/score/src/main/java/com/capitalone/dashboard/widget/QualityWidgetScore.java#L151-L176 |
ModeShape/modeshape | modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java | CheckArg.isNotGreaterThan | public static void isNotGreaterThan( int argument,
int notGreaterThanValue,
String name ) {
"""
Check that the argument is not greater than the supplied value
@param argument The argument
@param notGreaterThanValue the value that is to be used to check the value
@param name The name of the argument
@throws IllegalArgumentException If argument is less than or equal to the supplied value
"""
if (argument > notGreaterThanValue) {
throw new IllegalArgumentException(CommonI18n.argumentMayNotBeGreaterThan.text(name, argument, notGreaterThanValue));
}
} | java | public static void isNotGreaterThan( int argument,
int notGreaterThanValue,
String name ) {
if (argument > notGreaterThanValue) {
throw new IllegalArgumentException(CommonI18n.argumentMayNotBeGreaterThan.text(name, argument, notGreaterThanValue));
}
} | [
"public",
"static",
"void",
"isNotGreaterThan",
"(",
"int",
"argument",
",",
"int",
"notGreaterThanValue",
",",
"String",
"name",
")",
"{",
"if",
"(",
"argument",
">",
"notGreaterThanValue",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"CommonI18n",
".",
"argumentMayNotBeGreaterThan",
".",
"text",
"(",
"name",
",",
"argument",
",",
"notGreaterThanValue",
")",
")",
";",
"}",
"}"
] | Check that the argument is not greater than the supplied value
@param argument The argument
@param notGreaterThanValue the value that is to be used to check the value
@param name The name of the argument
@throws IllegalArgumentException If argument is less than or equal to the supplied value | [
"Check",
"that",
"the",
"argument",
"is",
"not",
"greater",
"than",
"the",
"supplied",
"value"
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java#L57-L63 |
Azure/azure-sdk-for-java | network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java | NetworkWatchersInner.getVMSecurityRules | public SecurityGroupViewResultInner getVMSecurityRules(String resourceGroupName, String networkWatcherName, String targetResourceId) {
"""
Gets the configured and effective security group rules on the specified VM.
@param resourceGroupName The name of the resource group.
@param networkWatcherName The name of the network watcher.
@param targetResourceId ID of the target VM.
@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 SecurityGroupViewResultInner object if successful.
"""
return getVMSecurityRulesWithServiceResponseAsync(resourceGroupName, networkWatcherName, targetResourceId).toBlocking().last().body();
} | java | public SecurityGroupViewResultInner getVMSecurityRules(String resourceGroupName, String networkWatcherName, String targetResourceId) {
return getVMSecurityRulesWithServiceResponseAsync(resourceGroupName, networkWatcherName, targetResourceId).toBlocking().last().body();
} | [
"public",
"SecurityGroupViewResultInner",
"getVMSecurityRules",
"(",
"String",
"resourceGroupName",
",",
"String",
"networkWatcherName",
",",
"String",
"targetResourceId",
")",
"{",
"return",
"getVMSecurityRulesWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"networkWatcherName",
",",
"targetResourceId",
")",
".",
"toBlocking",
"(",
")",
".",
"last",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Gets the configured and effective security group rules on the specified VM.
@param resourceGroupName The name of the resource group.
@param networkWatcherName The name of the network watcher.
@param targetResourceId ID of the target VM.
@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 SecurityGroupViewResultInner object if successful. | [
"Gets",
"the",
"configured",
"and",
"effective",
"security",
"group",
"rules",
"on",
"the",
"specified",
"VM",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java#L1294-L1296 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPAddressesInner.java | PublicIPAddressesInner.beginUpdateTagsAsync | public Observable<PublicIPAddressInner> beginUpdateTagsAsync(String resourceGroupName, String publicIpAddressName) {
"""
Updates public IP address tags.
@param resourceGroupName The name of the resource group.
@param publicIpAddressName The name of the public IP address.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PublicIPAddressInner object
"""
return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, publicIpAddressName).map(new Func1<ServiceResponse<PublicIPAddressInner>, PublicIPAddressInner>() {
@Override
public PublicIPAddressInner call(ServiceResponse<PublicIPAddressInner> response) {
return response.body();
}
});
} | java | public Observable<PublicIPAddressInner> beginUpdateTagsAsync(String resourceGroupName, String publicIpAddressName) {
return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, publicIpAddressName).map(new Func1<ServiceResponse<PublicIPAddressInner>, PublicIPAddressInner>() {
@Override
public PublicIPAddressInner call(ServiceResponse<PublicIPAddressInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"PublicIPAddressInner",
">",
"beginUpdateTagsAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"publicIpAddressName",
")",
"{",
"return",
"beginUpdateTagsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"publicIpAddressName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"PublicIPAddressInner",
">",
",",
"PublicIPAddressInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"PublicIPAddressInner",
"call",
"(",
"ServiceResponse",
"<",
"PublicIPAddressInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Updates public IP address tags.
@param resourceGroupName The name of the resource group.
@param publicIpAddressName The name of the public IP address.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PublicIPAddressInner object | [
"Updates",
"public",
"IP",
"address",
"tags",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPAddressesInner.java#L799-L806 |
Netflix/eureka | eureka-client/src/main/java/com/netflix/discovery/shared/transport/EurekaHttpClients.java | EurekaHttpClients.failFastOnInitCheck | private static void failFastOnInitCheck(EurekaClientConfig clientConfig, String msg) {
"""
potential future feature, guarding with experimental flag for now
"""
if ("true".equals(clientConfig.getExperimental("clientTransportFailFastOnInit"))) {
throw new RuntimeException(msg);
}
} | java | private static void failFastOnInitCheck(EurekaClientConfig clientConfig, String msg) {
if ("true".equals(clientConfig.getExperimental("clientTransportFailFastOnInit"))) {
throw new RuntimeException(msg);
}
} | [
"private",
"static",
"void",
"failFastOnInitCheck",
"(",
"EurekaClientConfig",
"clientConfig",
",",
"String",
"msg",
")",
"{",
"if",
"(",
"\"true\"",
".",
"equals",
"(",
"clientConfig",
".",
"getExperimental",
"(",
"\"clientTransportFailFastOnInit\"",
")",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"msg",
")",
";",
"}",
"}"
] | potential future feature, guarding with experimental flag for now | [
"potential",
"future",
"feature",
"guarding",
"with",
"experimental",
"flag",
"for",
"now"
] | train | https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-client/src/main/java/com/netflix/discovery/shared/transport/EurekaHttpClients.java#L322-L326 |
Baidu-AIP/java-sdk | src/main/java/com/baidu/aip/kg/AipKnowledgeGraphic.java | AipKnowledgeGraphic.getTaskInfo | public JSONObject getTaskInfo(int id, HashMap<String, String> options) {
"""
获取任务详情接口
根据任务id获取单个任务的详细信息
@param id - 任务ID
@param options - 可选参数对象,key: value都为string类型
options - options列表:
@return JSONObject
"""
AipRequest request = new AipRequest();
preOperation(request);
request.addBody("id", id);
if (options != null) {
request.addBody(options);
}
request.setUri(KnowledgeGraphicConsts.TASK_INFO);
postOperation(request);
return requestServer(request);
} | java | public JSONObject getTaskInfo(int id, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
request.addBody("id", id);
if (options != null) {
request.addBody(options);
}
request.setUri(KnowledgeGraphicConsts.TASK_INFO);
postOperation(request);
return requestServer(request);
} | [
"public",
"JSONObject",
"getTaskInfo",
"(",
"int",
"id",
",",
"HashMap",
"<",
"String",
",",
"String",
">",
"options",
")",
"{",
"AipRequest",
"request",
"=",
"new",
"AipRequest",
"(",
")",
";",
"preOperation",
"(",
"request",
")",
";",
"request",
".",
"addBody",
"(",
"\"id\"",
",",
"id",
")",
";",
"if",
"(",
"options",
"!=",
"null",
")",
"{",
"request",
".",
"addBody",
"(",
"options",
")",
";",
"}",
"request",
".",
"setUri",
"(",
"KnowledgeGraphicConsts",
".",
"TASK_INFO",
")",
";",
"postOperation",
"(",
"request",
")",
";",
"return",
"requestServer",
"(",
"request",
")",
";",
"}"
] | 获取任务详情接口
根据任务id获取单个任务的详细信息
@param id - 任务ID
@param options - 可选参数对象,key: value都为string类型
options - options列表:
@return JSONObject | [
"获取任务详情接口",
"根据任务id获取单个任务的详细信息"
] | train | https://github.com/Baidu-AIP/java-sdk/blob/16bb8b7bb8f9bbcb7c8af62d0a67a1e79eecad90/src/main/java/com/baidu/aip/kg/AipKnowledgeGraphic.java#L99-L110 |
BioPAX/Paxtools | pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java | PatternBox.reactsWith | public static Pattern reactsWith(Blacklist blacklist) {
"""
Constructs a pattern where first and last small molecules are substrates to the same
biochemical reaction.
@param blacklist a skip-list of ubiquitous molecules
@return the pattern
"""
Pattern p = new Pattern(SmallMoleculeReference.class, "SMR1");
p.add(erToPE(), "SMR1", "SPE1");
p.add(notGeneric(), "SPE1");
p.add(linkToComplex(blacklist), "SPE1", "PE1");
p.add(new ParticipatesInConv(RelType.INPUT, blacklist), "PE1", "Conv");
p.add(type(BiochemicalReaction.class), "Conv");
p.add(new InterToPartER(InterToPartER.Direction.ONESIDERS), "Conv", "SMR1");
p.add(new ConversionSide(ConversionSide.Type.SAME_SIDE, blacklist, RelType.INPUT), "PE1", "Conv", "PE2");
p.add(type(SmallMolecule.class), "PE2");
p.add(linkToSpecific(), "PE2", "SPE2");
p.add(notGeneric(), "SPE2");
p.add(new PEChainsIntersect(false), "SPE1", "PE1", "SPE2", "PE2");
p.add(peToER(), "SPE2", "SMR2");
p.add(equal(false), "SMR1", "SMR2");
p.add(new InterToPartER(InterToPartER.Direction.ONESIDERS), "Conv", "SMR2");
return p;
} | java | public static Pattern reactsWith(Blacklist blacklist)
{
Pattern p = new Pattern(SmallMoleculeReference.class, "SMR1");
p.add(erToPE(), "SMR1", "SPE1");
p.add(notGeneric(), "SPE1");
p.add(linkToComplex(blacklist), "SPE1", "PE1");
p.add(new ParticipatesInConv(RelType.INPUT, blacklist), "PE1", "Conv");
p.add(type(BiochemicalReaction.class), "Conv");
p.add(new InterToPartER(InterToPartER.Direction.ONESIDERS), "Conv", "SMR1");
p.add(new ConversionSide(ConversionSide.Type.SAME_SIDE, blacklist, RelType.INPUT), "PE1", "Conv", "PE2");
p.add(type(SmallMolecule.class), "PE2");
p.add(linkToSpecific(), "PE2", "SPE2");
p.add(notGeneric(), "SPE2");
p.add(new PEChainsIntersect(false), "SPE1", "PE1", "SPE2", "PE2");
p.add(peToER(), "SPE2", "SMR2");
p.add(equal(false), "SMR1", "SMR2");
p.add(new InterToPartER(InterToPartER.Direction.ONESIDERS), "Conv", "SMR2");
return p;
} | [
"public",
"static",
"Pattern",
"reactsWith",
"(",
"Blacklist",
"blacklist",
")",
"{",
"Pattern",
"p",
"=",
"new",
"Pattern",
"(",
"SmallMoleculeReference",
".",
"class",
",",
"\"SMR1\"",
")",
";",
"p",
".",
"add",
"(",
"erToPE",
"(",
")",
",",
"\"SMR1\"",
",",
"\"SPE1\"",
")",
";",
"p",
".",
"add",
"(",
"notGeneric",
"(",
")",
",",
"\"SPE1\"",
")",
";",
"p",
".",
"add",
"(",
"linkToComplex",
"(",
"blacklist",
")",
",",
"\"SPE1\"",
",",
"\"PE1\"",
")",
";",
"p",
".",
"add",
"(",
"new",
"ParticipatesInConv",
"(",
"RelType",
".",
"INPUT",
",",
"blacklist",
")",
",",
"\"PE1\"",
",",
"\"Conv\"",
")",
";",
"p",
".",
"add",
"(",
"type",
"(",
"BiochemicalReaction",
".",
"class",
")",
",",
"\"Conv\"",
")",
";",
"p",
".",
"add",
"(",
"new",
"InterToPartER",
"(",
"InterToPartER",
".",
"Direction",
".",
"ONESIDERS",
")",
",",
"\"Conv\"",
",",
"\"SMR1\"",
")",
";",
"p",
".",
"add",
"(",
"new",
"ConversionSide",
"(",
"ConversionSide",
".",
"Type",
".",
"SAME_SIDE",
",",
"blacklist",
",",
"RelType",
".",
"INPUT",
")",
",",
"\"PE1\"",
",",
"\"Conv\"",
",",
"\"PE2\"",
")",
";",
"p",
".",
"add",
"(",
"type",
"(",
"SmallMolecule",
".",
"class",
")",
",",
"\"PE2\"",
")",
";",
"p",
".",
"add",
"(",
"linkToSpecific",
"(",
")",
",",
"\"PE2\"",
",",
"\"SPE2\"",
")",
";",
"p",
".",
"add",
"(",
"notGeneric",
"(",
")",
",",
"\"SPE2\"",
")",
";",
"p",
".",
"add",
"(",
"new",
"PEChainsIntersect",
"(",
"false",
")",
",",
"\"SPE1\"",
",",
"\"PE1\"",
",",
"\"SPE2\"",
",",
"\"PE2\"",
")",
";",
"p",
".",
"add",
"(",
"peToER",
"(",
")",
",",
"\"SPE2\"",
",",
"\"SMR2\"",
")",
";",
"p",
".",
"add",
"(",
"equal",
"(",
"false",
")",
",",
"\"SMR1\"",
",",
"\"SMR2\"",
")",
";",
"p",
".",
"add",
"(",
"new",
"InterToPartER",
"(",
"InterToPartER",
".",
"Direction",
".",
"ONESIDERS",
")",
",",
"\"Conv\"",
",",
"\"SMR2\"",
")",
";",
"return",
"p",
";",
"}"
] | Constructs a pattern where first and last small molecules are substrates to the same
biochemical reaction.
@param blacklist a skip-list of ubiquitous molecules
@return the pattern | [
"Constructs",
"a",
"pattern",
"where",
"first",
"and",
"last",
"small",
"molecules",
"are",
"substrates",
"to",
"the",
"same",
"biochemical",
"reaction",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java#L594-L612 |
azkaban/azkaban | az-hadoop-jobtype-plugin/src/main/java/azkaban/jobtype/HadoopJobUtils.java | HadoopJobUtils.addAdditionalNamenodesToProps | public static void addAdditionalNamenodesToProps(Props props, String additionalNamenodes) {
"""
Takes the list of other Namenodes from which to fetch delegation tokens,
the {@link #OTHER_NAMENODES_PROPERTY} property, from Props and inserts it
back with the addition of the the potentially JobType-specific Namenode URIs
from additionalNamenodes. Modifies props in-place.
@param props Props to add the new Namenode URIs to.
@param additionalNamenodes Comma-separated list of Namenode URIs from which to fetch
delegation tokens.
"""
String otherNamenodes = props.get(OTHER_NAMENODES_PROPERTY);
if (otherNamenodes != null && otherNamenodes.length() > 0) {
props.put(OTHER_NAMENODES_PROPERTY, otherNamenodes + "," + additionalNamenodes);
} else {
props.put(OTHER_NAMENODES_PROPERTY, additionalNamenodes);
}
} | java | public static void addAdditionalNamenodesToProps(Props props, String additionalNamenodes) {
String otherNamenodes = props.get(OTHER_NAMENODES_PROPERTY);
if (otherNamenodes != null && otherNamenodes.length() > 0) {
props.put(OTHER_NAMENODES_PROPERTY, otherNamenodes + "," + additionalNamenodes);
} else {
props.put(OTHER_NAMENODES_PROPERTY, additionalNamenodes);
}
} | [
"public",
"static",
"void",
"addAdditionalNamenodesToProps",
"(",
"Props",
"props",
",",
"String",
"additionalNamenodes",
")",
"{",
"String",
"otherNamenodes",
"=",
"props",
".",
"get",
"(",
"OTHER_NAMENODES_PROPERTY",
")",
";",
"if",
"(",
"otherNamenodes",
"!=",
"null",
"&&",
"otherNamenodes",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"props",
".",
"put",
"(",
"OTHER_NAMENODES_PROPERTY",
",",
"otherNamenodes",
"+",
"\",\"",
"+",
"additionalNamenodes",
")",
";",
"}",
"else",
"{",
"props",
".",
"put",
"(",
"OTHER_NAMENODES_PROPERTY",
",",
"additionalNamenodes",
")",
";",
"}",
"}"
] | Takes the list of other Namenodes from which to fetch delegation tokens,
the {@link #OTHER_NAMENODES_PROPERTY} property, from Props and inserts it
back with the addition of the the potentially JobType-specific Namenode URIs
from additionalNamenodes. Modifies props in-place.
@param props Props to add the new Namenode URIs to.
@param additionalNamenodes Comma-separated list of Namenode URIs from which to fetch
delegation tokens. | [
"Takes",
"the",
"list",
"of",
"other",
"Namenodes",
"from",
"which",
"to",
"fetch",
"delegation",
"tokens",
"the",
"{",
"@link",
"#OTHER_NAMENODES_PROPERTY",
"}",
"property",
"from",
"Props",
"and",
"inserts",
"it",
"back",
"with",
"the",
"addition",
"of",
"the",
"the",
"potentially",
"JobType",
"-",
"specific",
"Namenode",
"URIs",
"from",
"additionalNamenodes",
".",
"Modifies",
"props",
"in",
"-",
"place",
"."
] | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/az-hadoop-jobtype-plugin/src/main/java/azkaban/jobtype/HadoopJobUtils.java#L172-L179 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/internal/commands/ServerCommandClient.java | ServerCommandClient.introspectServer | public ReturnCode introspectServer(String dumpTimestamp, Set<JavaDumpAction> javaDumpActions) {
"""
Dump the server by issuing a "introspect" instruction to the server listener
"""
// Since "server dump" is used for diagnostics, we go out of our way to
// not send an unrecognized command to the server even if the user has
// broken their environment such that the client process supports java
// dumps but the server doesn't.
String command;
if (javaDumpActions.isEmpty()) {
command = INTROSPECT_COMMAND + DELIM + dumpTimestamp;
} else {
StringBuilder commandBuilder = new StringBuilder().append(INTROSPECT_JAVADUMP_COMMAND).append(DELIM).append(dumpTimestamp);
for (JavaDumpAction javaDumpAction : javaDumpActions) {
commandBuilder.append(',').append(javaDumpAction.name());
}
command = commandBuilder.toString();
}
return write(command,
ReturnCode.DUMP_ACTION,
ReturnCode.ERROR_SERVER_DUMP);
} | java | public ReturnCode introspectServer(String dumpTimestamp, Set<JavaDumpAction> javaDumpActions) {
// Since "server dump" is used for diagnostics, we go out of our way to
// not send an unrecognized command to the server even if the user has
// broken their environment such that the client process supports java
// dumps but the server doesn't.
String command;
if (javaDumpActions.isEmpty()) {
command = INTROSPECT_COMMAND + DELIM + dumpTimestamp;
} else {
StringBuilder commandBuilder = new StringBuilder().append(INTROSPECT_JAVADUMP_COMMAND).append(DELIM).append(dumpTimestamp);
for (JavaDumpAction javaDumpAction : javaDumpActions) {
commandBuilder.append(',').append(javaDumpAction.name());
}
command = commandBuilder.toString();
}
return write(command,
ReturnCode.DUMP_ACTION,
ReturnCode.ERROR_SERVER_DUMP);
} | [
"public",
"ReturnCode",
"introspectServer",
"(",
"String",
"dumpTimestamp",
",",
"Set",
"<",
"JavaDumpAction",
">",
"javaDumpActions",
")",
"{",
"// Since \"server dump\" is used for diagnostics, we go out of our way to",
"// not send an unrecognized command to the server even if the user has",
"// broken their environment such that the client process supports java",
"// dumps but the server doesn't.",
"String",
"command",
";",
"if",
"(",
"javaDumpActions",
".",
"isEmpty",
"(",
")",
")",
"{",
"command",
"=",
"INTROSPECT_COMMAND",
"+",
"DELIM",
"+",
"dumpTimestamp",
";",
"}",
"else",
"{",
"StringBuilder",
"commandBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
".",
"append",
"(",
"INTROSPECT_JAVADUMP_COMMAND",
")",
".",
"append",
"(",
"DELIM",
")",
".",
"append",
"(",
"dumpTimestamp",
")",
";",
"for",
"(",
"JavaDumpAction",
"javaDumpAction",
":",
"javaDumpActions",
")",
"{",
"commandBuilder",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"javaDumpAction",
".",
"name",
"(",
")",
")",
";",
"}",
"command",
"=",
"commandBuilder",
".",
"toString",
"(",
")",
";",
"}",
"return",
"write",
"(",
"command",
",",
"ReturnCode",
".",
"DUMP_ACTION",
",",
"ReturnCode",
".",
"ERROR_SERVER_DUMP",
")",
";",
"}"
] | Dump the server by issuing a "introspect" instruction to the server listener | [
"Dump",
"the",
"server",
"by",
"issuing",
"a",
"introspect",
"instruction",
"to",
"the",
"server",
"listener"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/internal/commands/ServerCommandClient.java#L245-L264 |
realtime-framework/RealtimeMessaging-Android | library/src/main/java/ibt/ortc/extensibility/ChannelSubscription.java | ChannelSubscription.runHandler | public void runHandler(OrtcClient sender, String channel, String message) {
"""
Fires the event handler that is associated the subscribed channel
@param channel
@param sender
@param message
"""
this.runHandler(sender, channel, message, false, null);
} | java | public void runHandler(OrtcClient sender, String channel, String message){
this.runHandler(sender, channel, message, false, null);
} | [
"public",
"void",
"runHandler",
"(",
"OrtcClient",
"sender",
",",
"String",
"channel",
",",
"String",
"message",
")",
"{",
"this",
".",
"runHandler",
"(",
"sender",
",",
"channel",
",",
"message",
",",
"false",
",",
"null",
")",
";",
"}"
] | Fires the event handler that is associated the subscribed channel
@param channel
@param sender
@param message | [
"Fires",
"the",
"event",
"handler",
"that",
"is",
"associated",
"the",
"subscribed",
"channel"
] | train | https://github.com/realtime-framework/RealtimeMessaging-Android/blob/f0d87b92ed7c591bcfe2b9cf45b947865570e061/library/src/main/java/ibt/ortc/extensibility/ChannelSubscription.java#L111-L113 |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/HttpServer.java | HttpServer.dispatchRequest | public void dispatchRequest(HttpRequest httpRequest) throws IOException {
"""
Dispatch a request to all handlers
@param httpRequest The request to dispatch
@throws IOException If an error occurs while sending the response from the
handler
"""
for (HttpRequestHandler handler : handlers) {
HttpResponse resp = handler.handleRequest(httpRequest);
if (resp != null) {
httpRequest.getSession().sendResponse(resp);
return;
}
}
if (!hasCapability(HttpCapability.THREADEDRESPONSE)) {
// If it's still here nothing handled it.
httpRequest.getSession().sendResponse(new HttpResponse(HttpStatus.NOT_FOUND, HttpStatus.NOT_FOUND.toString()));
}
} | java | public void dispatchRequest(HttpRequest httpRequest) throws IOException {
for (HttpRequestHandler handler : handlers) {
HttpResponse resp = handler.handleRequest(httpRequest);
if (resp != null) {
httpRequest.getSession().sendResponse(resp);
return;
}
}
if (!hasCapability(HttpCapability.THREADEDRESPONSE)) {
// If it's still here nothing handled it.
httpRequest.getSession().sendResponse(new HttpResponse(HttpStatus.NOT_FOUND, HttpStatus.NOT_FOUND.toString()));
}
} | [
"public",
"void",
"dispatchRequest",
"(",
"HttpRequest",
"httpRequest",
")",
"throws",
"IOException",
"{",
"for",
"(",
"HttpRequestHandler",
"handler",
":",
"handlers",
")",
"{",
"HttpResponse",
"resp",
"=",
"handler",
".",
"handleRequest",
"(",
"httpRequest",
")",
";",
"if",
"(",
"resp",
"!=",
"null",
")",
"{",
"httpRequest",
".",
"getSession",
"(",
")",
".",
"sendResponse",
"(",
"resp",
")",
";",
"return",
";",
"}",
"}",
"if",
"(",
"!",
"hasCapability",
"(",
"HttpCapability",
".",
"THREADEDRESPONSE",
")",
")",
"{",
"// If it's still here nothing handled it.",
"httpRequest",
".",
"getSession",
"(",
")",
".",
"sendResponse",
"(",
"new",
"HttpResponse",
"(",
"HttpStatus",
".",
"NOT_FOUND",
",",
"HttpStatus",
".",
"NOT_FOUND",
".",
"toString",
"(",
")",
")",
")",
";",
"}",
"}"
] | Dispatch a request to all handlers
@param httpRequest The request to dispatch
@throws IOException If an error occurs while sending the response from the
handler | [
"Dispatch",
"a",
"request",
"to",
"all",
"handlers"
] | train | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/HttpServer.java#L179-L191 |
JOML-CI/JOML | src/org/joml/Vector3d.java | Vector3d.fma | public Vector3d fma(Vector3dc a, Vector3dc b) {
"""
Add the component-wise multiplication of <code>a * b</code> to this vector.
@param a
the first multiplicand
@param b
the second multiplicand
@return a vector holding the result
"""
return fma(a, b, thisOrNew());
} | java | public Vector3d fma(Vector3dc a, Vector3dc b) {
return fma(a, b, thisOrNew());
} | [
"public",
"Vector3d",
"fma",
"(",
"Vector3dc",
"a",
",",
"Vector3dc",
"b",
")",
"{",
"return",
"fma",
"(",
"a",
",",
"b",
",",
"thisOrNew",
"(",
")",
")",
";",
"}"
] | Add the component-wise multiplication of <code>a * b</code> to this vector.
@param a
the first multiplicand
@param b
the second multiplicand
@return a vector holding the result | [
"Add",
"the",
"component",
"-",
"wise",
"multiplication",
"of",
"<code",
">",
"a",
"*",
"b<",
"/",
"code",
">",
"to",
"this",
"vector",
"."
] | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Vector3d.java#L666-L668 |
jenkinsci/jenkins | core/src/main/java/hudson/Util.java | Util.encodeRFC2396 | @Deprecated
public static String encodeRFC2396(String url) {
"""
Encodes the URL by RFC 2396.
I thought there's another spec that refers to UTF-8 as the encoding,
but don't remember it right now.
@since 1.204
@deprecated since 2008-05-13. This method is broken (see ISSUE#1666). It should probably
be removed but I'm not sure if it is considered part of the public API
that needs to be maintained for backwards compatibility.
Use {@link #encode(String)} instead.
"""
try {
return new URI(null,url,null).toASCIIString();
} catch (URISyntaxException e) {
LOGGER.log(Level.WARNING, "Failed to encode {0}", url); // could this ever happen?
return url;
}
} | java | @Deprecated
public static String encodeRFC2396(String url) {
try {
return new URI(null,url,null).toASCIIString();
} catch (URISyntaxException e) {
LOGGER.log(Level.WARNING, "Failed to encode {0}", url); // could this ever happen?
return url;
}
} | [
"@",
"Deprecated",
"public",
"static",
"String",
"encodeRFC2396",
"(",
"String",
"url",
")",
"{",
"try",
"{",
"return",
"new",
"URI",
"(",
"null",
",",
"url",
",",
"null",
")",
".",
"toASCIIString",
"(",
")",
";",
"}",
"catch",
"(",
"URISyntaxException",
"e",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"Failed to encode {0}\"",
",",
"url",
")",
";",
"// could this ever happen?",
"return",
"url",
";",
"}",
"}"
] | Encodes the URL by RFC 2396.
I thought there's another spec that refers to UTF-8 as the encoding,
but don't remember it right now.
@since 1.204
@deprecated since 2008-05-13. This method is broken (see ISSUE#1666). It should probably
be removed but I'm not sure if it is considered part of the public API
that needs to be maintained for backwards compatibility.
Use {@link #encode(String)} instead. | [
"Encodes",
"the",
"URL",
"by",
"RFC",
"2396",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/Util.java#L1292-L1300 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.