repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
google/closure-compiler | src/com/google/javascript/jscomp/PassConfig.java | PassConfig.patchGlobalTypedScope | void patchGlobalTypedScope(AbstractCompiler compiler, Node scriptRoot) {
checkNotNull(typedScopeCreator);
typedScopeCreator.patchGlobalScope(topScope, scriptRoot);
} | java | void patchGlobalTypedScope(AbstractCompiler compiler, Node scriptRoot) {
checkNotNull(typedScopeCreator);
typedScopeCreator.patchGlobalScope(topScope, scriptRoot);
} | [
"void",
"patchGlobalTypedScope",
"(",
"AbstractCompiler",
"compiler",
",",
"Node",
"scriptRoot",
")",
"{",
"checkNotNull",
"(",
"typedScopeCreator",
")",
";",
"typedScopeCreator",
".",
"patchGlobalScope",
"(",
"topScope",
",",
"scriptRoot",
")",
";",
"}"
] | Regenerates the top scope potentially only for a sub-tree of AST and then
copies information for the old global scope.
@param compiler The compiler for which the global scope is generated.
@param scriptRoot The root of the AST used to generate global scope. | [
"Regenerates",
"the",
"top",
"scope",
"potentially",
"only",
"for",
"a",
"sub",
"-",
"tree",
"of",
"AST",
"and",
"then",
"copies",
"information",
"for",
"the",
"old",
"global",
"scope",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PassConfig.java#L70-L73 |
albfernandez/itext2 | src/main/java/com/lowagie/text/rtf/headerfooter/RtfHeaderFooterGroup.java | RtfHeaderFooterGroup.setHasTitlePage | public void setHasTitlePage() {
if(this.mode == MODE_SINGLE) {
this.mode = MODE_MULTIPLE;
headerFirst = new RtfHeaderFooter(this.document, headerAll, RtfHeaderFooter.DISPLAY_FIRST_PAGE);
headerFirst.setType(this.type);
}
} | java | public void setHasTitlePage() {
if(this.mode == MODE_SINGLE) {
this.mode = MODE_MULTIPLE;
headerFirst = new RtfHeaderFooter(this.document, headerAll, RtfHeaderFooter.DISPLAY_FIRST_PAGE);
headerFirst.setType(this.type);
}
} | [
"public",
"void",
"setHasTitlePage",
"(",
")",
"{",
"if",
"(",
"this",
".",
"mode",
"==",
"MODE_SINGLE",
")",
"{",
"this",
".",
"mode",
"=",
"MODE_MULTIPLE",
";",
"headerFirst",
"=",
"new",
"RtfHeaderFooter",
"(",
"this",
".",
"document",
",",
"headerAll",... | Set that this RtfHeaderFooterGroup should have a title page. If only
a header / footer for all pages exists, then it will be copied to the
first page as well. | [
"Set",
"that",
"this",
"RtfHeaderFooterGroup",
"should",
"have",
"a",
"title",
"page",
".",
"If",
"only",
"a",
"header",
"/",
"footer",
"for",
"all",
"pages",
"exists",
"then",
"it",
"will",
"be",
"copied",
"to",
"the",
"first",
"page",
"as",
"well",
"."... | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/rtf/headerfooter/RtfHeaderFooterGroup.java#L297-L303 |
Waikato/moa | moa/src/main/java/moa/classifiers/core/attributeclassobservers/FIMTDDNumericAttributeClassObserver.java | FIMTDDNumericAttributeClassObserver.removeBadSplitNodes | private boolean removeBadSplitNodes(SplitCriterion criterion, Node currentNode, double lastCheckRatio, double lastCheckSDR, double lastCheckE) {
boolean isBad = false;
if (currentNode == null) {
return true;
}
if (currentNode.left != null) {
isBad = removeBadSplitNodes(criterion, currentNode.left, lastCheckRatio, lastCheckSDR, lastCheckE);
}
if (currentNode.right != null && isBad) {
isBad = removeBadSplitNodes(criterion, currentNode.left, lastCheckRatio, lastCheckSDR, lastCheckE);
}
if (isBad) {
double[][] postSplitDists = new double[][]{{currentNode.leftStatistics.getValue(0), currentNode.leftStatistics.getValue(1), currentNode.leftStatistics.getValue(2)}, {currentNode.rightStatistics.getValue(0), currentNode.rightStatistics.getValue(1), currentNode.rightStatistics.getValue(2)}};
double[] preSplitDist = new double[]{(currentNode.leftStatistics.getValue(0) + currentNode.rightStatistics.getValue(0)), (currentNode.leftStatistics.getValue(1) + currentNode.rightStatistics.getValue(1)), (currentNode.leftStatistics.getValue(2) + currentNode.rightStatistics.getValue(2))};
double merit = criterion.getMeritOfSplit(preSplitDist, postSplitDists);
if ((merit / lastCheckSDR) < (lastCheckRatio - (2 * lastCheckE))) {
currentNode = null;
return true;
}
}
return false;
} | java | private boolean removeBadSplitNodes(SplitCriterion criterion, Node currentNode, double lastCheckRatio, double lastCheckSDR, double lastCheckE) {
boolean isBad = false;
if (currentNode == null) {
return true;
}
if (currentNode.left != null) {
isBad = removeBadSplitNodes(criterion, currentNode.left, lastCheckRatio, lastCheckSDR, lastCheckE);
}
if (currentNode.right != null && isBad) {
isBad = removeBadSplitNodes(criterion, currentNode.left, lastCheckRatio, lastCheckSDR, lastCheckE);
}
if (isBad) {
double[][] postSplitDists = new double[][]{{currentNode.leftStatistics.getValue(0), currentNode.leftStatistics.getValue(1), currentNode.leftStatistics.getValue(2)}, {currentNode.rightStatistics.getValue(0), currentNode.rightStatistics.getValue(1), currentNode.rightStatistics.getValue(2)}};
double[] preSplitDist = new double[]{(currentNode.leftStatistics.getValue(0) + currentNode.rightStatistics.getValue(0)), (currentNode.leftStatistics.getValue(1) + currentNode.rightStatistics.getValue(1)), (currentNode.leftStatistics.getValue(2) + currentNode.rightStatistics.getValue(2))};
double merit = criterion.getMeritOfSplit(preSplitDist, postSplitDists);
if ((merit / lastCheckSDR) < (lastCheckRatio - (2 * lastCheckE))) {
currentNode = null;
return true;
}
}
return false;
} | [
"private",
"boolean",
"removeBadSplitNodes",
"(",
"SplitCriterion",
"criterion",
",",
"Node",
"currentNode",
",",
"double",
"lastCheckRatio",
",",
"double",
"lastCheckSDR",
",",
"double",
"lastCheckE",
")",
"{",
"boolean",
"isBad",
"=",
"false",
";",
"if",
"(",
... | Recursive method that first checks all of a node's children before
deciding if it is 'bad' and may be removed | [
"Recursive",
"method",
"that",
"first",
"checks",
"all",
"of",
"a",
"node",
"s",
"children",
"before",
"deciding",
"if",
"it",
"is",
"bad",
"and",
"may",
"be",
"removed"
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/core/attributeclassobservers/FIMTDDNumericAttributeClassObserver.java#L201-L229 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java | TrainingsImpl.exportIterationAsync | public Observable<Export> exportIterationAsync(UUID projectId, UUID iterationId, String platform, ExportIterationOptionalParameter exportIterationOptionalParameter) {
return exportIterationWithServiceResponseAsync(projectId, iterationId, platform, exportIterationOptionalParameter).map(new Func1<ServiceResponse<Export>, Export>() {
@Override
public Export call(ServiceResponse<Export> response) {
return response.body();
}
});
} | java | public Observable<Export> exportIterationAsync(UUID projectId, UUID iterationId, String platform, ExportIterationOptionalParameter exportIterationOptionalParameter) {
return exportIterationWithServiceResponseAsync(projectId, iterationId, platform, exportIterationOptionalParameter).map(new Func1<ServiceResponse<Export>, Export>() {
@Override
public Export call(ServiceResponse<Export> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Export",
">",
"exportIterationAsync",
"(",
"UUID",
"projectId",
",",
"UUID",
"iterationId",
",",
"String",
"platform",
",",
"ExportIterationOptionalParameter",
"exportIterationOptionalParameter",
")",
"{",
"return",
"exportIterationWithServiceR... | Export a trained iteration.
@param projectId The project id
@param iterationId The iteration id
@param platform The target platform (coreml or tensorflow). Possible values include: 'CoreML', 'TensorFlow', 'DockerFile', 'ONNX'
@param exportIterationOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the Export object | [
"Export",
"a",
"trained",
"iteration",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L975-L982 |
grails/grails-core | grails-bootstrap/src/main/groovy/org/grails/io/watch/DirectoryWatcher.java | DirectoryWatcher.addWatchDirectory | public void addWatchDirectory(File dir, String extension) {
extension = removeStartingDotIfPresent(extension);
List<String> fileExtensions = new ArrayList<String>();
if (extension != null && extension.length() > 0) {
int i = extension.lastIndexOf('.');
if(i > -1) {
extension = extension.substring(i + 1);
}
fileExtensions.add(extension);
}
else {
fileExtensions.add("*");
}
addWatchDirectory(dir, fileExtensions);
} | java | public void addWatchDirectory(File dir, String extension) {
extension = removeStartingDotIfPresent(extension);
List<String> fileExtensions = new ArrayList<String>();
if (extension != null && extension.length() > 0) {
int i = extension.lastIndexOf('.');
if(i > -1) {
extension = extension.substring(i + 1);
}
fileExtensions.add(extension);
}
else {
fileExtensions.add("*");
}
addWatchDirectory(dir, fileExtensions);
} | [
"public",
"void",
"addWatchDirectory",
"(",
"File",
"dir",
",",
"String",
"extension",
")",
"{",
"extension",
"=",
"removeStartingDotIfPresent",
"(",
"extension",
")",
";",
"List",
"<",
"String",
">",
"fileExtensions",
"=",
"new",
"ArrayList",
"<",
"String",
"... | Adds a directory to watch for the given file and extensions.
@param dir The directory
@param extension The extension | [
"Adds",
"a",
"directory",
"to",
"watch",
"for",
"the",
"given",
"file",
"and",
"extensions",
"."
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-bootstrap/src/main/groovy/org/grails/io/watch/DirectoryWatcher.java#L147-L161 |
kaazing/gateway | mina.core/core/src/main/java/org/apache/mina/proxy/handlers/http/ntlm/NTLMResponses.java | NTLMResponses.getLMResponse | public static byte[] getLMResponse(String password, byte[] challenge)
throws Exception {
byte[] lmHash = lmHash(password);
return lmResponse(lmHash, challenge);
} | java | public static byte[] getLMResponse(String password, byte[] challenge)
throws Exception {
byte[] lmHash = lmHash(password);
return lmResponse(lmHash, challenge);
} | [
"public",
"static",
"byte",
"[",
"]",
"getLMResponse",
"(",
"String",
"password",
",",
"byte",
"[",
"]",
"challenge",
")",
"throws",
"Exception",
"{",
"byte",
"[",
"]",
"lmHash",
"=",
"lmHash",
"(",
"password",
")",
";",
"return",
"lmResponse",
"(",
"lmH... | Calculates the LM Response for the given challenge, using the specified
password.
@param password The user's password.
@param challenge The Type 2 challenge from the server.
@return The LM Response. | [
"Calculates",
"the",
"LM",
"Response",
"for",
"the",
"given",
"challenge",
"using",
"the",
"specified",
"password",
"."
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.core/core/src/main/java/org/apache/mina/proxy/handlers/http/ntlm/NTLMResponses.java#L61-L65 |
opsmatters/opsmatters-core | src/main/java/com/opsmatters/core/util/StringUtilities.java | StringUtilities.isWildcardMatch | public static boolean isWildcardMatch(String str, String expr, boolean whole)
{
return getWildcardMatcher(str, expr, whole).find();
} | java | public static boolean isWildcardMatch(String str, String expr, boolean whole)
{
return getWildcardMatcher(str, expr, whole).find();
} | [
"public",
"static",
"boolean",
"isWildcardMatch",
"(",
"String",
"str",
",",
"String",
"expr",
",",
"boolean",
"whole",
")",
"{",
"return",
"getWildcardMatcher",
"(",
"str",
",",
"expr",
",",
"whole",
")",
".",
"find",
"(",
")",
";",
"}"
] | Returns <CODE>true</CODE> if the given string matches the given regular expression.
@param str The string against which the expression is to be matched
@param expr The regular expression to match with the input string
@param whole Indicates that a whole word match is required
@return <CODE>true</CODE> if a match was found | [
"Returns",
"<CODE",
">",
"true<",
"/",
"CODE",
">",
"if",
"the",
"given",
"string",
"matches",
"the",
"given",
"regular",
"expression",
"."
] | train | https://github.com/opsmatters/opsmatters-core/blob/c48904f7e8d029fd45357811ec38a735e261e3fd/src/main/java/com/opsmatters/core/util/StringUtilities.java#L346-L349 |
resilience4j/resilience4j | resilience4j-prometheus/src/main/java/io/github/resilience4j/prometheus/BulkheadExports.java | BulkheadExports.ofSupplier | public static BulkheadExports ofSupplier(String prefix, Supplier<Iterable<Bulkhead>> bulkheadSupplier) {
return new BulkheadExports(prefix, bulkheadSupplier);
} | java | public static BulkheadExports ofSupplier(String prefix, Supplier<Iterable<Bulkhead>> bulkheadSupplier) {
return new BulkheadExports(prefix, bulkheadSupplier);
} | [
"public",
"static",
"BulkheadExports",
"ofSupplier",
"(",
"String",
"prefix",
",",
"Supplier",
"<",
"Iterable",
"<",
"Bulkhead",
">",
">",
"bulkheadSupplier",
")",
"{",
"return",
"new",
"BulkheadExports",
"(",
"prefix",
",",
"bulkheadSupplier",
")",
";",
"}"
] | Creates a new instance of {@link BulkheadExports} with specified metrics names prefix and
{@link Supplier} of bulkheads
@param prefix the prefix of metrics names
@param bulkheadSupplier the supplier of bulkheads | [
"Creates",
"a",
"new",
"instance",
"of",
"{",
"@link",
"BulkheadExports",
"}",
"with",
"specified",
"metrics",
"names",
"prefix",
"and",
"{",
"@link",
"Supplier",
"}",
"of",
"bulkheads"
] | train | https://github.com/resilience4j/resilience4j/blob/fa843d30f531c00f0c3dc218b65a7f2bb51af336/resilience4j-prometheus/src/main/java/io/github/resilience4j/prometheus/BulkheadExports.java#L54-L56 |
lessthanoptimal/BoofCV | main/boofcv-calibration/src/main/java/boofcv/alg/geo/selfcalib/RefineDualQuadraticAlgebra.java | RefineDualQuadraticAlgebra.encodeK | public int encodeK( DMatrix3x3 K , int which, int offset, double params[] ) {
if( fixedAspectRatio ) {
K.a11 = params[offset++];
K.a22 = aspect.data[which]*K.a11;
} else {
K.a11 = params[offset++];
K.a22 = params[offset++];
}
if( !zeroSkew ) {
K.a12 = params[offset++];
}
if( !zeroPrinciplePoint ) {
K.a13 = params[offset++];
K.a23 = params[offset++];
}
K.a33 = 1;
return offset;
} | java | public int encodeK( DMatrix3x3 K , int which, int offset, double params[] ) {
if( fixedAspectRatio ) {
K.a11 = params[offset++];
K.a22 = aspect.data[which]*K.a11;
} else {
K.a11 = params[offset++];
K.a22 = params[offset++];
}
if( !zeroSkew ) {
K.a12 = params[offset++];
}
if( !zeroPrinciplePoint ) {
K.a13 = params[offset++];
K.a23 = params[offset++];
}
K.a33 = 1;
return offset;
} | [
"public",
"int",
"encodeK",
"(",
"DMatrix3x3",
"K",
",",
"int",
"which",
",",
"int",
"offset",
",",
"double",
"params",
"[",
"]",
")",
"{",
"if",
"(",
"fixedAspectRatio",
")",
"{",
"K",
".",
"a11",
"=",
"params",
"[",
"offset",
"++",
"]",
";",
"K",... | Encode the calibration as a 3x3 matrix. K is assumed to zero initially or at
least all non-zero elements will align with values that are written to. | [
"Encode",
"the",
"calibration",
"as",
"a",
"3x3",
"matrix",
".",
"K",
"is",
"assumed",
"to",
"zero",
"initially",
"or",
"at",
"least",
"all",
"non",
"-",
"zero",
"elements",
"will",
"align",
"with",
"values",
"that",
"are",
"written",
"to",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-calibration/src/main/java/boofcv/alg/geo/selfcalib/RefineDualQuadraticAlgebra.java#L230-L250 |
alkacon/opencms-core | src-modules/org/opencms/workplace/commons/CmsPublishProject.java | CmsPublishProject.buildLockConfirmationMessageJS | @Override
public String buildLockConfirmationMessageJS() {
StringBuffer html = new StringBuffer(512);
html.append("<script type='text/javascript'><!--\n");
html.append("function setConfirmationMessage(locks, blockinglocks) {\n");
html.append("\tvar confMsg = document.getElementById('conf-msg');\n");
html.append("\tif (locks > -1) {\n");
html.append("\t\tdocument.getElementById('butClose').className = 'hide';\n");
html.append("\t\tdocument.getElementById('butContinue').className = '';\n");
html.append("\t\tif (locks > 0) {\n");
html.append("\t\t\tshowAjaxReportContent();\n");
html.append("\t\t\tconfMsg.innerHTML = '");
html.append(key(Messages.GUI_PUBLISH_UNLOCK_CONFIRMATION_0));
html.append("';\n");
html.append("\t\t} else {\n");
html.append("\t\tshowAjaxOk();\n");
html.append("\t\t\tconfMsg.innerHTML = '");
html.append(key(Messages.GUI_PUBLISH_NO_LOCKS_CONFIRMATION_0));
html.append("';\n");
html.append("\t\t}\n");
html.append("\t} else {\n");
html.append("\t\tdocument.getElementById('butClose').className = '';\n");
html.append("\t\tdocument.getElementById('butContinue').className = 'hide';\n");
html.append("\t\tconfMsg.innerHTML = '");
html.append(key(org.opencms.workplace.Messages.GUI_AJAX_REPORT_WAIT_0));
html.append("';\n");
html.append("\t}\n");
html.append("}\n");
html.append("// -->\n");
html.append("</script>\n");
return html.toString();
} | java | @Override
public String buildLockConfirmationMessageJS() {
StringBuffer html = new StringBuffer(512);
html.append("<script type='text/javascript'><!--\n");
html.append("function setConfirmationMessage(locks, blockinglocks) {\n");
html.append("\tvar confMsg = document.getElementById('conf-msg');\n");
html.append("\tif (locks > -1) {\n");
html.append("\t\tdocument.getElementById('butClose').className = 'hide';\n");
html.append("\t\tdocument.getElementById('butContinue').className = '';\n");
html.append("\t\tif (locks > 0) {\n");
html.append("\t\t\tshowAjaxReportContent();\n");
html.append("\t\t\tconfMsg.innerHTML = '");
html.append(key(Messages.GUI_PUBLISH_UNLOCK_CONFIRMATION_0));
html.append("';\n");
html.append("\t\t} else {\n");
html.append("\t\tshowAjaxOk();\n");
html.append("\t\t\tconfMsg.innerHTML = '");
html.append(key(Messages.GUI_PUBLISH_NO_LOCKS_CONFIRMATION_0));
html.append("';\n");
html.append("\t\t}\n");
html.append("\t} else {\n");
html.append("\t\tdocument.getElementById('butClose').className = '';\n");
html.append("\t\tdocument.getElementById('butContinue').className = 'hide';\n");
html.append("\t\tconfMsg.innerHTML = '");
html.append(key(org.opencms.workplace.Messages.GUI_AJAX_REPORT_WAIT_0));
html.append("';\n");
html.append("\t}\n");
html.append("}\n");
html.append("// -->\n");
html.append("</script>\n");
return html.toString();
} | [
"@",
"Override",
"public",
"String",
"buildLockConfirmationMessageJS",
"(",
")",
"{",
"StringBuffer",
"html",
"=",
"new",
"StringBuffer",
"(",
"512",
")",
";",
"html",
".",
"append",
"(",
"\"<script type='text/javascript'><!--\\n\"",
")",
";",
"html",
".",
"append... | Returns the html code to build the confirmation messages.<p>
@return html code | [
"Returns",
"the",
"html",
"code",
"to",
"build",
"the",
"confirmation",
"messages",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsPublishProject.java#L237-L269 |
micronaut-projects/micronaut-core | cli/src/main/groovy/io/micronaut/cli/util/NameUtils.java | NameUtils.getLogicalName | public static String getLogicalName(Class<?> clazz, String trailingName) {
return getLogicalName(clazz.getName(), trailingName);
} | java | public static String getLogicalName(Class<?> clazz, String trailingName) {
return getLogicalName(clazz.getName(), trailingName);
} | [
"public",
"static",
"String",
"getLogicalName",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"trailingName",
")",
"{",
"return",
"getLogicalName",
"(",
"clazz",
".",
"getName",
"(",
")",
",",
"trailingName",
")",
";",
"}"
] | Retrieves the logical class name of a Micronaut artifact given the Micronaut class
and a specified trailing name.
@param clazz The class
@param trailingName The trailing name such as "Controller" or "Service"
@return The logical class name | [
"Retrieves",
"the",
"logical",
"class",
"name",
"of",
"a",
"Micronaut",
"artifact",
"given",
"the",
"Micronaut",
"class",
"and",
"a",
"specified",
"trailing",
"name",
"."
] | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/cli/src/main/groovy/io/micronaut/cli/util/NameUtils.java#L203-L205 |
undertow-io/undertow | core/src/main/java/io/undertow/protocols/ssl/SNISSLExplorer.java | SNISSLExplorer.exploreExtensions | private static ExtensionInfo exploreExtensions(ByteBuffer input)
throws SSLException {
List<SNIServerName> sni = Collections.emptyList();
List<String> alpn = Collections.emptyList();
int length = getInt16(input); // length of extensions
while (length > 0) {
int extType = getInt16(input); // extension type
int extLen = getInt16(input); // length of extension data
if (extType == 0x00) { // 0x00: type of server name indication
sni = exploreSNIExt(input, extLen);
} else if (extType == 0x10) { // 0x10: type of alpn
alpn = exploreALPN(input, extLen);
} else { // ignore other extensions
ignoreByteVector(input, extLen);
}
length -= extLen + 4;
}
return new ExtensionInfo(sni, alpn);
} | java | private static ExtensionInfo exploreExtensions(ByteBuffer input)
throws SSLException {
List<SNIServerName> sni = Collections.emptyList();
List<String> alpn = Collections.emptyList();
int length = getInt16(input); // length of extensions
while (length > 0) {
int extType = getInt16(input); // extension type
int extLen = getInt16(input); // length of extension data
if (extType == 0x00) { // 0x00: type of server name indication
sni = exploreSNIExt(input, extLen);
} else if (extType == 0x10) { // 0x10: type of alpn
alpn = exploreALPN(input, extLen);
} else { // ignore other extensions
ignoreByteVector(input, extLen);
}
length -= extLen + 4;
}
return new ExtensionInfo(sni, alpn);
} | [
"private",
"static",
"ExtensionInfo",
"exploreExtensions",
"(",
"ByteBuffer",
"input",
")",
"throws",
"SSLException",
"{",
"List",
"<",
"SNIServerName",
">",
"sni",
"=",
"Collections",
".",
"emptyList",
"(",
")",
";",
"List",
"<",
"String",
">",
"alpn",
"=",
... | /*
struct {
ExtensionType extension_type;
opaque extension_data<0..2^16-1>;
} Extension;
enum {
server_name(0), max_fragment_length(1),
client_certificate_url(2), trusted_ca_keys(3),
truncated_hmac(4), status_request(5), (65535)
} ExtensionType; | [
"/",
"*",
"struct",
"{",
"ExtensionType",
"extension_type",
";",
"opaque",
"extension_data<0",
"..",
"2^16",
"-",
"1",
">",
";",
"}",
"Extension",
";"
] | train | https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/ssl/SNISSLExplorer.java#L377-L400 |
maven-nar/nar-maven-plugin | src/main/java/com/github/maven_nar/cpptasks/borland/CBuilderXProjectWriter.java | CBuilderXProjectWriter.writeLinkOptions | private void writeLinkOptions(final String baseDir, final PropertyWriter writer, final TargetInfo linkTarget)
throws SAXException {
if (linkTarget != null) {
final ProcessorConfiguration config = linkTarget.getConfiguration();
if (config instanceof CommandLineLinkerConfiguration) {
final CommandLineLinkerConfiguration linkConfig = (CommandLineLinkerConfiguration) config;
if (linkConfig.getLinker() instanceof BorlandLinker) {
final String linkID = "win32.Debug_Build.win32b.ilink32";
writeIlinkArgs(writer, linkID, linkConfig.getPreArguments());
writeIlinkArgs(writer, linkID, linkConfig.getEndArguments());
writer.write(linkID, "param.libfiles.1", "cw32mt.lib");
writer.write(linkID, "param.libfiles.2", "import32.lib");
int libIndex = 3;
final String[] libNames = linkConfig.getLibraryNames();
for (final String libName : libNames) {
writer.write(linkID, "param.libfiles." + libIndex++, libName);
}
final String startup = linkConfig.getStartupObject();
if (startup != null) {
writer.write(linkID, "param.objfiles.1", startup);
}
} else {
final String linkID = "linux.Debug_Build.gnuc++.g++link";
writeLdArgs(writer, linkID, linkConfig.getPreArguments());
writeLdArgs(writer, linkID, linkConfig.getEndArguments());
}
}
}
} | java | private void writeLinkOptions(final String baseDir, final PropertyWriter writer, final TargetInfo linkTarget)
throws SAXException {
if (linkTarget != null) {
final ProcessorConfiguration config = linkTarget.getConfiguration();
if (config instanceof CommandLineLinkerConfiguration) {
final CommandLineLinkerConfiguration linkConfig = (CommandLineLinkerConfiguration) config;
if (linkConfig.getLinker() instanceof BorlandLinker) {
final String linkID = "win32.Debug_Build.win32b.ilink32";
writeIlinkArgs(writer, linkID, linkConfig.getPreArguments());
writeIlinkArgs(writer, linkID, linkConfig.getEndArguments());
writer.write(linkID, "param.libfiles.1", "cw32mt.lib");
writer.write(linkID, "param.libfiles.2", "import32.lib");
int libIndex = 3;
final String[] libNames = linkConfig.getLibraryNames();
for (final String libName : libNames) {
writer.write(linkID, "param.libfiles." + libIndex++, libName);
}
final String startup = linkConfig.getStartupObject();
if (startup != null) {
writer.write(linkID, "param.objfiles.1", startup);
}
} else {
final String linkID = "linux.Debug_Build.gnuc++.g++link";
writeLdArgs(writer, linkID, linkConfig.getPreArguments());
writeLdArgs(writer, linkID, linkConfig.getEndArguments());
}
}
}
} | [
"private",
"void",
"writeLinkOptions",
"(",
"final",
"String",
"baseDir",
",",
"final",
"PropertyWriter",
"writer",
",",
"final",
"TargetInfo",
"linkTarget",
")",
"throws",
"SAXException",
"{",
"if",
"(",
"linkTarget",
"!=",
"null",
")",
"{",
"final",
"Processor... | Writes elements corresponding to link options.
@param baseDir
String base directory
@param writer
PropertyWriter property writer
@param linkTarget
TargetInfo link target
@throws SAXException
if I/O error or illegal content | [
"Writes",
"elements",
"corresponding",
"to",
"link",
"options",
"."
] | train | https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/borland/CBuilderXProjectWriter.java#L329-L358 |
wstrange/GoogleAuth | src/main/java/com/warrenstrange/googleauth/GoogleAuthenticator.java | GoogleAuthenticator.calculateCode | int calculateCode(byte[] key, long tm)
{
// Allocating an array of bytes to represent the specified instant
// of time.
byte[] data = new byte[8];
long value = tm;
// Converting the instant of time from the long representation to a
// big-endian array of bytes (RFC4226, 5.2. Description).
for (int i = 8; i-- > 0; value >>>= 8)
{
data[i] = (byte) value;
}
// Building the secret key specification for the HmacSHA1 algorithm.
SecretKeySpec signKey = new SecretKeySpec(key, config.getHmacHashFunction().toString());
try
{
// Getting an HmacSHA1/HmacSHA256 algorithm implementation from the JCE.
Mac mac = Mac.getInstance(config.getHmacHashFunction().toString());
// Initializing the MAC algorithm.
mac.init(signKey);
// Processing the instant of time and getting the encrypted data.
byte[] hash = mac.doFinal(data);
// Building the validation code performing dynamic truncation
// (RFC4226, 5.3. Generating an HOTP value)
int offset = hash[hash.length - 1] & 0xF;
// We are using a long because Java hasn't got an unsigned integer type
// and we need 32 unsigned bits).
long truncatedHash = 0;
for (int i = 0; i < 4; ++i)
{
truncatedHash <<= 8;
// Java bytes are signed but we need an unsigned integer:
// cleaning off all but the LSB.
truncatedHash |= (hash[offset + i] & 0xFF);
}
// Clean bits higher than the 32nd (inclusive) and calculate the
// module with the maximum validation code value.
truncatedHash &= 0x7FFFFFFF;
truncatedHash %= config.getKeyModulus();
// Returning the validation code to the caller.
return (int) truncatedHash;
}
catch (NoSuchAlgorithmException | InvalidKeyException ex)
{
// Logging the exception.
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
// We're not disclosing internal error details to our clients.
throw new GoogleAuthenticatorException("The operation cannot be performed now.");
}
} | java | int calculateCode(byte[] key, long tm)
{
// Allocating an array of bytes to represent the specified instant
// of time.
byte[] data = new byte[8];
long value = tm;
// Converting the instant of time from the long representation to a
// big-endian array of bytes (RFC4226, 5.2. Description).
for (int i = 8; i-- > 0; value >>>= 8)
{
data[i] = (byte) value;
}
// Building the secret key specification for the HmacSHA1 algorithm.
SecretKeySpec signKey = new SecretKeySpec(key, config.getHmacHashFunction().toString());
try
{
// Getting an HmacSHA1/HmacSHA256 algorithm implementation from the JCE.
Mac mac = Mac.getInstance(config.getHmacHashFunction().toString());
// Initializing the MAC algorithm.
mac.init(signKey);
// Processing the instant of time and getting the encrypted data.
byte[] hash = mac.doFinal(data);
// Building the validation code performing dynamic truncation
// (RFC4226, 5.3. Generating an HOTP value)
int offset = hash[hash.length - 1] & 0xF;
// We are using a long because Java hasn't got an unsigned integer type
// and we need 32 unsigned bits).
long truncatedHash = 0;
for (int i = 0; i < 4; ++i)
{
truncatedHash <<= 8;
// Java bytes are signed but we need an unsigned integer:
// cleaning off all but the LSB.
truncatedHash |= (hash[offset + i] & 0xFF);
}
// Clean bits higher than the 32nd (inclusive) and calculate the
// module with the maximum validation code value.
truncatedHash &= 0x7FFFFFFF;
truncatedHash %= config.getKeyModulus();
// Returning the validation code to the caller.
return (int) truncatedHash;
}
catch (NoSuchAlgorithmException | InvalidKeyException ex)
{
// Logging the exception.
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
// We're not disclosing internal error details to our clients.
throw new GoogleAuthenticatorException("The operation cannot be performed now.");
}
} | [
"int",
"calculateCode",
"(",
"byte",
"[",
"]",
"key",
",",
"long",
"tm",
")",
"{",
"// Allocating an array of bytes to represent the specified instant",
"// of time.",
"byte",
"[",
"]",
"data",
"=",
"new",
"byte",
"[",
"8",
"]",
";",
"long",
"value",
"=",
"tm"... | Calculates the verification code of the provided key at the specified
instant of time using the algorithm specified in RFC 6238.
@param key the secret key in binary format.
@param tm the instant of time.
@return the validation code for the provided key at the specified instant
of time. | [
"Calculates",
"the",
"verification",
"code",
"of",
"the",
"provided",
"key",
"at",
"the",
"specified",
"instant",
"of",
"time",
"using",
"the",
"algorithm",
"specified",
"in",
"RFC",
"6238",
"."
] | train | https://github.com/wstrange/GoogleAuth/blob/03f37333f8b3e411e10e63a7c85c4d2155929321/src/main/java/com/warrenstrange/googleauth/GoogleAuthenticator.java#L209-L270 |
morimekta/utils | console-util/src/main/java/net/morimekta/console/args/ArgumentParser.java | ArgumentParser.printUsage | public void printUsage(PrintWriter writer, boolean showHidden) {
if (writer instanceof IndentedPrintWriter) {
printUsageInternal((IndentedPrintWriter) writer, showHidden);
} else {
printUsageInternal(new IndentedPrintWriter(writer), showHidden);
}
} | java | public void printUsage(PrintWriter writer, boolean showHidden) {
if (writer instanceof IndentedPrintWriter) {
printUsageInternal((IndentedPrintWriter) writer, showHidden);
} else {
printUsageInternal(new IndentedPrintWriter(writer), showHidden);
}
} | [
"public",
"void",
"printUsage",
"(",
"PrintWriter",
"writer",
",",
"boolean",
"showHidden",
")",
"{",
"if",
"(",
"writer",
"instanceof",
"IndentedPrintWriter",
")",
"{",
"printUsageInternal",
"(",
"(",
"IndentedPrintWriter",
")",
"writer",
",",
"showHidden",
")",
... | Print the option usage list. Essentially printed as a list of options
with the description indented where it overflows the available line
width.
@param writer The output printer.
@param showHidden Whether to show hidden options. | [
"Print",
"the",
"option",
"usage",
"list",
".",
"Essentially",
"printed",
"as",
"a",
"list",
"of",
"options",
"with",
"the",
"description",
"indented",
"where",
"it",
"overflows",
"the",
"available",
"line",
"width",
"."
] | train | https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/console-util/src/main/java/net/morimekta/console/args/ArgumentParser.java#L412-L418 |
javamelody/javamelody | javamelody-spring-boot-starter/src/main/java/net/bull/javamelody/JavaMelodyAutoConfiguration.java | JavaMelodyAutoConfiguration.monitoringFeignClientAdvisor | @SuppressWarnings("unchecked")
@Bean
@ConditionalOnClass(name = "org.springframework.cloud.openfeign.FeignClient")
@ConditionalOnProperty(prefix = JavaMelodyConfigurationProperties.PREFIX, name = "spring-monitoring-enabled", matchIfMissing = true)
// we check that the DefaultAdvisorAutoProxyCreator above is not enabled, because if it's enabled then feign calls are counted twice
@ConditionalOnMissingBean(DefaultAdvisorAutoProxyCreator.class)
public MonitoringSpringAdvisor monitoringFeignClientAdvisor() throws ClassNotFoundException {
final Class<? extends Annotation> feignClientClass = (Class<? extends Annotation>) Class
.forName("org.springframework.cloud.openfeign.FeignClient");
final MonitoringSpringAdvisor advisor = new MonitoringSpringAdvisor(
new AnnotationMatchingPointcut(feignClientClass, true));
advisor.setAdvice(new MonitoringSpringInterceptor() {
private static final long serialVersionUID = 1L;
@Override
protected String getRequestName(MethodInvocation invocation) {
final StringBuilder sb = new StringBuilder();
final Method method = invocation.getMethod();
final RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
if (requestMapping != null) {
String[] path = requestMapping.value();
if (path.length == 0) {
path = requestMapping.path();
}
if (path.length > 0) {
sb.append(path[0]);
sb.append(' ');
if (requestMapping.method().length > 0) {
sb.append(requestMapping.method()[0].name());
} else {
sb.append("GET");
}
sb.append('\n');
}
}
final Class<?> declaringClass = method.getDeclaringClass();
final String classPart = declaringClass.getSimpleName();
final String methodPart = method.getName();
sb.append(classPart).append('.').append(methodPart);
return sb.toString();
}
});
return advisor;
} | java | @SuppressWarnings("unchecked")
@Bean
@ConditionalOnClass(name = "org.springframework.cloud.openfeign.FeignClient")
@ConditionalOnProperty(prefix = JavaMelodyConfigurationProperties.PREFIX, name = "spring-monitoring-enabled", matchIfMissing = true)
// we check that the DefaultAdvisorAutoProxyCreator above is not enabled, because if it's enabled then feign calls are counted twice
@ConditionalOnMissingBean(DefaultAdvisorAutoProxyCreator.class)
public MonitoringSpringAdvisor monitoringFeignClientAdvisor() throws ClassNotFoundException {
final Class<? extends Annotation> feignClientClass = (Class<? extends Annotation>) Class
.forName("org.springframework.cloud.openfeign.FeignClient");
final MonitoringSpringAdvisor advisor = new MonitoringSpringAdvisor(
new AnnotationMatchingPointcut(feignClientClass, true));
advisor.setAdvice(new MonitoringSpringInterceptor() {
private static final long serialVersionUID = 1L;
@Override
protected String getRequestName(MethodInvocation invocation) {
final StringBuilder sb = new StringBuilder();
final Method method = invocation.getMethod();
final RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
if (requestMapping != null) {
String[] path = requestMapping.value();
if (path.length == 0) {
path = requestMapping.path();
}
if (path.length > 0) {
sb.append(path[0]);
sb.append(' ');
if (requestMapping.method().length > 0) {
sb.append(requestMapping.method()[0].name());
} else {
sb.append("GET");
}
sb.append('\n');
}
}
final Class<?> declaringClass = method.getDeclaringClass();
final String classPart = declaringClass.getSimpleName();
final String methodPart = method.getName();
sb.append(classPart).append('.').append(methodPart);
return sb.toString();
}
});
return advisor;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"@",
"Bean",
"@",
"ConditionalOnClass",
"(",
"name",
"=",
"\"org.springframework.cloud.openfeign.FeignClient\"",
")",
"@",
"ConditionalOnProperty",
"(",
"prefix",
"=",
"JavaMelodyConfigurationProperties",
".",
"PREFIX",
... | Monitoring of Feign clients.
@return MonitoringSpringAdvisor
@throws ClassNotFoundException should not happen | [
"Monitoring",
"of",
"Feign",
"clients",
"."
] | train | https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-spring-boot-starter/src/main/java/net/bull/javamelody/JavaMelodyAutoConfiguration.java#L279-L322 |
linkedin/dexmaker | dexmaker/src/main/java/com/android/dx/Code.java | Code.aput | public void aput(Local<?> array, Local<Integer> index, Local<?> source) {
addInstruction(new ThrowingInsn(Rops.opAput(source.type.ropType), sourcePosition,
RegisterSpecList.make(source.spec(), array.spec(), index.spec()), catches));
} | java | public void aput(Local<?> array, Local<Integer> index, Local<?> source) {
addInstruction(new ThrowingInsn(Rops.opAput(source.type.ropType), sourcePosition,
RegisterSpecList.make(source.spec(), array.spec(), index.spec()), catches));
} | [
"public",
"void",
"aput",
"(",
"Local",
"<",
"?",
">",
"array",
",",
"Local",
"<",
"Integer",
">",
"index",
",",
"Local",
"<",
"?",
">",
"source",
")",
"{",
"addInstruction",
"(",
"new",
"ThrowingInsn",
"(",
"Rops",
".",
"opAput",
"(",
"source",
".",... | Assigns {@code source} to the element at {@code index} in {@code array}. | [
"Assigns",
"{"
] | train | https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/Code.java#L812-L815 |
centic9/commons-dost | src/main/java/org/dstadler/commons/zip/ZipUtils.java | ZipUtils.replaceInZip | public static void replaceInZip(File zip, String file, String data, String encoding) throws IOException {
// open the output side
File zipOutFile = File.createTempFile("ZipReplace", ".zip");
try {
FileOutputStream fos = new FileOutputStream(zipOutFile);
try (ZipOutputStream zos = new ZipOutputStream(fos)) {
// open the input side
try (ZipFile zipFile = new ZipFile(zip)) {
boolean found = false;
// walk all entries and copy them into the new file
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
try {
if (entry.getName().equals(file)) {
zos.putNextEntry(new ZipEntry(entry.getName()));
IOUtils.write(data, zos, encoding);
found = true;
} else {
zos.putNextEntry(entry);
IOUtils.copy(zipFile.getInputStream(entry), zos);
}
} finally {
zos.closeEntry();
}
}
if(!found) {
zos.putNextEntry(new ZipEntry(file));
try {
IOUtils.write(data, zos, "UTF-8");
} finally {
zos.closeEntry();
}
}
}
}
// copy over the data
FileUtils.copyFile(zipOutFile, zip);
} finally {
if(!zipOutFile.delete()) {
//noinspection ThrowFromFinallyBlock
throw new IOException("Error deleting file: " + zipOutFile);
}
}
} | java | public static void replaceInZip(File zip, String file, String data, String encoding) throws IOException {
// open the output side
File zipOutFile = File.createTempFile("ZipReplace", ".zip");
try {
FileOutputStream fos = new FileOutputStream(zipOutFile);
try (ZipOutputStream zos = new ZipOutputStream(fos)) {
// open the input side
try (ZipFile zipFile = new ZipFile(zip)) {
boolean found = false;
// walk all entries and copy them into the new file
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
try {
if (entry.getName().equals(file)) {
zos.putNextEntry(new ZipEntry(entry.getName()));
IOUtils.write(data, zos, encoding);
found = true;
} else {
zos.putNextEntry(entry);
IOUtils.copy(zipFile.getInputStream(entry), zos);
}
} finally {
zos.closeEntry();
}
}
if(!found) {
zos.putNextEntry(new ZipEntry(file));
try {
IOUtils.write(data, zos, "UTF-8");
} finally {
zos.closeEntry();
}
}
}
}
// copy over the data
FileUtils.copyFile(zipOutFile, zip);
} finally {
if(!zipOutFile.delete()) {
//noinspection ThrowFromFinallyBlock
throw new IOException("Error deleting file: " + zipOutFile);
}
}
} | [
"public",
"static",
"void",
"replaceInZip",
"(",
"File",
"zip",
",",
"String",
"file",
",",
"String",
"data",
",",
"String",
"encoding",
")",
"throws",
"IOException",
"{",
"// open the output side",
"File",
"zipOutFile",
"=",
"File",
".",
"createTempFile",
"(",
... | Replaces the specified file in the provided ZIP file with the
provided content.
@param zip The zip-file to process
@param file The file to look for
@param data The string-data to replace
@param encoding The encoding that should be used when writing the string data to the file
@throws IOException Thrown if files can not be read or any other error occurs while handling the Zip-files | [
"Replaces",
"the",
"specified",
"file",
"in",
"the",
"provided",
"ZIP",
"file",
"with",
"the",
"provided",
"content",
"."
] | train | https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/zip/ZipUtils.java#L461-L509 |
liferay/com-liferay-commerce | commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java | CommerceCurrencyPersistenceImpl.findByGroupId | @Override
public List<CommerceCurrency> findByGroupId(long groupId) {
return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | java | @Override
public List<CommerceCurrency> findByGroupId(long groupId) {
return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceCurrency",
">",
"findByGroupId",
"(",
"long",
"groupId",
")",
"{",
"return",
"findByGroupId",
"(",
"groupId",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"null",
")",
";",
"}"
] | Returns all the commerce currencies where groupId = ?.
@param groupId the group ID
@return the matching commerce currencies | [
"Returns",
"all",
"the",
"commerce",
"currencies",
"where",
"groupId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java#L1514-L1517 |
paypal/SeLion | client/src/main/java/com/paypal/selion/internal/reports/runtimereport/JsonRuntimeReporterHelper.java | JsonRuntimeReporterHelper.generateHTMLReport | private void generateHTMLReport(BufferedWriter writer, BufferedReader templateReader, String jsonReport)
throws IOException {
logger.entering(new Object[] { writer, templateReader, jsonReport });
String readLine = null;
while ((readLine = templateReader.readLine()) != null) {
if (readLine.trim().equals("${reports}")) {
writer.write(jsonReport);
writer.newLine();
} else {
writer.write(readLine);
writer.newLine();
}
}
logger.exiting();
} | java | private void generateHTMLReport(BufferedWriter writer, BufferedReader templateReader, String jsonReport)
throws IOException {
logger.entering(new Object[] { writer, templateReader, jsonReport });
String readLine = null;
while ((readLine = templateReader.readLine()) != null) {
if (readLine.trim().equals("${reports}")) {
writer.write(jsonReport);
writer.newLine();
} else {
writer.write(readLine);
writer.newLine();
}
}
logger.exiting();
} | [
"private",
"void",
"generateHTMLReport",
"(",
"BufferedWriter",
"writer",
",",
"BufferedReader",
"templateReader",
",",
"String",
"jsonReport",
")",
"throws",
"IOException",
"{",
"logger",
".",
"entering",
"(",
"new",
"Object",
"[",
"]",
"{",
"writer",
",",
"tem... | Writing JSON content to HTML file
@param writer
@param templateReader
@param jsonReport
@throws IOException | [
"Writing",
"JSON",
"content",
"to",
"HTML",
"file"
] | train | https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/client/src/main/java/com/paypal/selion/internal/reports/runtimereport/JsonRuntimeReporterHelper.java#L349-L365 |
VoltDB/voltdb | src/frontend/org/voltdb/importer/ImporterLifeCycleManager.java | ImporterLifeCycleManager.configure | public final void configure(Properties props, FormatterBuilder formatterBuilder)
{
Map<URI, ImporterConfig> configs = m_factory.createImporterConfigurations(props, formatterBuilder);
m_configs = new ImmutableMap.Builder<URI, ImporterConfig>()
.putAll(configs)
.putAll(Maps.filterKeys(m_configs, not(in(configs.keySet()))))
.build();
} | java | public final void configure(Properties props, FormatterBuilder formatterBuilder)
{
Map<URI, ImporterConfig> configs = m_factory.createImporterConfigurations(props, formatterBuilder);
m_configs = new ImmutableMap.Builder<URI, ImporterConfig>()
.putAll(configs)
.putAll(Maps.filterKeys(m_configs, not(in(configs.keySet()))))
.build();
} | [
"public",
"final",
"void",
"configure",
"(",
"Properties",
"props",
",",
"FormatterBuilder",
"formatterBuilder",
")",
"{",
"Map",
"<",
"URI",
",",
"ImporterConfig",
">",
"configs",
"=",
"m_factory",
".",
"createImporterConfigurations",
"(",
"props",
",",
"formatte... | This will be called for every importer configuration section for this importer type.
@param props Properties defined in a configuration section for this importer | [
"This",
"will",
"be",
"called",
"for",
"every",
"importer",
"configuration",
"section",
"for",
"this",
"importer",
"type",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/importer/ImporterLifeCycleManager.java#L85-L92 |
samskivert/samskivert | src/main/java/com/samskivert/swing/RadialMenu.java | RadialMenu.addMenuItem | public RadialMenuItem addMenuItem (String command, String label, Image icon, Predicate predicate)
{
RadialMenuItem item = new RadialMenuItem(command, label, new ImageIcon(icon), predicate);
addMenuItem(item);
return item;
} | java | public RadialMenuItem addMenuItem (String command, String label, Image icon, Predicate predicate)
{
RadialMenuItem item = new RadialMenuItem(command, label, new ImageIcon(icon), predicate);
addMenuItem(item);
return item;
} | [
"public",
"RadialMenuItem",
"addMenuItem",
"(",
"String",
"command",
",",
"String",
"label",
",",
"Image",
"icon",
",",
"Predicate",
"predicate",
")",
"{",
"RadialMenuItem",
"item",
"=",
"new",
"RadialMenuItem",
"(",
"command",
",",
"label",
",",
"new",
"Image... | Adds a menu item to the menu. The menu should not currently be active.
@param command the command to be issued when the item is selected.
@param label the textual label to be displayed with the menu item.
@param icon the icon to display next to the menu text or null if no
icon is desired.
@param predicate a predicate that will be used to determine whether or not this menu item
should be included in the menu and enabled when it is shown.
@return the item that was added to the menu. It can be modified while the menu is not being
displayed. | [
"Adds",
"a",
"menu",
"item",
"to",
"the",
"menu",
".",
"The",
"menu",
"should",
"not",
"currently",
"be",
"active",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/RadialMenu.java#L123-L128 |
acromusashi/acromusashi-stream-ml | src/main/java/acromusashi/stream/ml/anomaly/lof/LofCalculator.java | LofCalculator.calculateLofNoIntermediate | public static double calculateLofNoIntermediate(int kn, LofPoint targetPoint, LofDataSet dataSet)
{
// 対象点のK距離、K距離近傍を算出する。
KDistanceResult kResult = calculateKDistance(kn, targetPoint, dataSet);
LofPoint tmpTargetPoint = targetPoint.deepCopy();
tmpTargetPoint.setkDistance(kResult.getkDistance());
tmpTargetPoint.setkDistanceNeighbor(kResult.getkDistanceNeighbor());
// データセット用の学習データモデルを一時的に生成する。
LofDataSet tmpDataSet = dataSet.deepCopy();
initDataSet(kn, tmpDataSet);
updateLrd(tmpTargetPoint, tmpDataSet);
// 対象の局所外れ係数を算出する。
double lof = calculateLof(tmpTargetPoint, tmpDataSet);
return lof;
} | java | public static double calculateLofNoIntermediate(int kn, LofPoint targetPoint, LofDataSet dataSet)
{
// 対象点のK距離、K距離近傍を算出する。
KDistanceResult kResult = calculateKDistance(kn, targetPoint, dataSet);
LofPoint tmpTargetPoint = targetPoint.deepCopy();
tmpTargetPoint.setkDistance(kResult.getkDistance());
tmpTargetPoint.setkDistanceNeighbor(kResult.getkDistanceNeighbor());
// データセット用の学習データモデルを一時的に生成する。
LofDataSet tmpDataSet = dataSet.deepCopy();
initDataSet(kn, tmpDataSet);
updateLrd(tmpTargetPoint, tmpDataSet);
// 対象の局所外れ係数を算出する。
double lof = calculateLof(tmpTargetPoint, tmpDataSet);
return lof;
} | [
"public",
"static",
"double",
"calculateLofNoIntermediate",
"(",
"int",
"kn",
",",
"LofPoint",
"targetPoint",
",",
"LofDataSet",
"dataSet",
")",
"{",
"// 対象点のK距離、K距離近傍を算出する。",
"KDistanceResult",
"kResult",
"=",
"calculateKDistance",
"(",
"kn",
",",
"targetPoint",
",",... | 指定したK値、対象点、データセットを基に局所外れ係数スコアを算出する。その際、データセットが中間データを使用せずに処理を行う。<br>
本メソッド呼び出しによってデータセットの更新は行われない。<br>
@param kn K値
@param targetPoint 対象点
@param dataSet 学習データセット
@return LOFスコア | [
"指定したK値、対象点、データセットを基に局所外れ係数スコアを算出する。その際、データセットが中間データを使用せずに処理を行う。<br",
">",
"本メソッド呼び出しによってデータセットの更新は行われない。<br",
">"
] | train | https://github.com/acromusashi/acromusashi-stream-ml/blob/26d6799a917cacda68e21d506c75cfeb17d832a6/src/main/java/acromusashi/stream/ml/anomaly/lof/LofCalculator.java#L56-L74 |
Sciss/abc4j | abc/src/main/java/abc/ui/swing/JScoreElementAbstract.java | JScoreElementAbstract.setColor | protected void setColor(Graphics2D g2, byte scoreElement) {
if (m_color != null)
g2.setColor(m_color);
else {
Color c = getTemplate().getElementColor(scoreElement);
Color d = getTemplate().getElementColor(ScoreElements._DEFAULT);
if ((c != null) && !c.equals(d))
g2.setColor(c);
}
} | java | protected void setColor(Graphics2D g2, byte scoreElement) {
if (m_color != null)
g2.setColor(m_color);
else {
Color c = getTemplate().getElementColor(scoreElement);
Color d = getTemplate().getElementColor(ScoreElements._DEFAULT);
if ((c != null) && !c.equals(d))
g2.setColor(c);
}
} | [
"protected",
"void",
"setColor",
"(",
"Graphics2D",
"g2",
",",
"byte",
"scoreElement",
")",
"{",
"if",
"(",
"m_color",
"!=",
"null",
")",
"g2",
".",
"setColor",
"(",
"m_color",
")",
";",
"else",
"{",
"Color",
"c",
"=",
"getTemplate",
"(",
")",
".",
"... | Set the color for renderer, get color value in the score
template, or apply the specified color for the current
element. | [
"Set",
"the",
"color",
"for",
"renderer",
"get",
"color",
"value",
"in",
"the",
"score",
"template",
"or",
"apply",
"the",
"specified",
"color",
"for",
"the",
"current",
"element",
"."
] | train | https://github.com/Sciss/abc4j/blob/117b405642c84a7bfca4e3e13668838258b90ca7/abc/src/main/java/abc/ui/swing/JScoreElementAbstract.java#L276-L285 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CharsTrieBuilder.java | CharsTrieBuilder.writeValueAndFinal | @Deprecated
@Override
protected int writeValueAndFinal(int i, boolean isFinal) {
if(0<=i && i<=CharsTrie.kMaxOneUnitValue) {
return write(i|(isFinal ? CharsTrie.kValueIsFinal : 0));
}
int length;
if(i<0 || i>CharsTrie.kMaxTwoUnitValue) {
intUnits[0]=(char)(CharsTrie.kThreeUnitValueLead);
intUnits[1]=(char)(i>>16);
intUnits[2]=(char)i;
length=3;
// } else if(i<=CharsTrie.kMaxOneUnitValue) {
// intUnits[0]=(char)(i);
// length=1;
} else {
intUnits[0]=(char)(CharsTrie.kMinTwoUnitValueLead+(i>>16));
intUnits[1]=(char)i;
length=2;
}
intUnits[0]=(char)(intUnits[0]|(isFinal ? CharsTrie.kValueIsFinal : 0));
return write(intUnits, length);
} | java | @Deprecated
@Override
protected int writeValueAndFinal(int i, boolean isFinal) {
if(0<=i && i<=CharsTrie.kMaxOneUnitValue) {
return write(i|(isFinal ? CharsTrie.kValueIsFinal : 0));
}
int length;
if(i<0 || i>CharsTrie.kMaxTwoUnitValue) {
intUnits[0]=(char)(CharsTrie.kThreeUnitValueLead);
intUnits[1]=(char)(i>>16);
intUnits[2]=(char)i;
length=3;
// } else if(i<=CharsTrie.kMaxOneUnitValue) {
// intUnits[0]=(char)(i);
// length=1;
} else {
intUnits[0]=(char)(CharsTrie.kMinTwoUnitValueLead+(i>>16));
intUnits[1]=(char)i;
length=2;
}
intUnits[0]=(char)(intUnits[0]|(isFinal ? CharsTrie.kValueIsFinal : 0));
return write(intUnits, length);
} | [
"@",
"Deprecated",
"@",
"Override",
"protected",
"int",
"writeValueAndFinal",
"(",
"int",
"i",
",",
"boolean",
"isFinal",
")",
"{",
"if",
"(",
"0",
"<=",
"i",
"&&",
"i",
"<=",
"CharsTrie",
".",
"kMaxOneUnitValue",
")",
"{",
"return",
"write",
"(",
"i",
... | {@inheritDoc}
@deprecated This API is ICU internal only.
@hide draft / provisional / internal are hidden on Android | [
"{"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CharsTrieBuilder.java#L195-L217 |
overturetool/overture | ide/debug/src/main/java/org/overture/ide/debug/utils/CharOperation.java | CharOperation.startsWith | public static final boolean startsWith(char[] array, char[] toBeFound)
{
int i = toBeFound.length;
if (array.length < i)
{
return false;
}
while (--i >= 0)
{
if (toBeFound[i] != array[i])
{
return false;
}
}
return true;
} | java | public static final boolean startsWith(char[] array, char[] toBeFound)
{
int i = toBeFound.length;
if (array.length < i)
{
return false;
}
while (--i >= 0)
{
if (toBeFound[i] != array[i])
{
return false;
}
}
return true;
} | [
"public",
"static",
"final",
"boolean",
"startsWith",
"(",
"char",
"[",
"]",
"array",
",",
"char",
"[",
"]",
"toBeFound",
")",
"{",
"int",
"i",
"=",
"toBeFound",
".",
"length",
";",
"if",
"(",
"array",
".",
"length",
"<",
"i",
")",
"{",
"return",
"... | Return <code>true</code> if array starts with the sequence of characters contained in toBeFound, otherwise
<code>false</code>.
@param array
@param toBeFound
@return | [
"Return",
"<code",
">",
"true<",
"/",
"code",
">",
"if",
"array",
"starts",
"with",
"the",
"sequence",
"of",
"characters",
"contained",
"in",
"toBeFound",
"otherwise",
"<code",
">",
"false<",
"/",
"code",
">",
"."
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/debug/src/main/java/org/overture/ide/debug/utils/CharOperation.java#L1302-L1317 |
sarl/sarl | contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyGenerator.java | PyGenerator._generate | protected void _generate(SarlAction action, PyAppendable it, IExtraLanguageGeneratorContext context) {
final String feature = getFeatureNameConverter(context).convertDeclarationName(action.getName(), action);
generateExecutable(feature, action, !action.isStatic(), action.isAbstract(),
action.getReturnType(),
getTypeBuilder().getDocumentation(action),
it, context);
} | java | protected void _generate(SarlAction action, PyAppendable it, IExtraLanguageGeneratorContext context) {
final String feature = getFeatureNameConverter(context).convertDeclarationName(action.getName(), action);
generateExecutable(feature, action, !action.isStatic(), action.isAbstract(),
action.getReturnType(),
getTypeBuilder().getDocumentation(action),
it, context);
} | [
"protected",
"void",
"_generate",
"(",
"SarlAction",
"action",
",",
"PyAppendable",
"it",
",",
"IExtraLanguageGeneratorContext",
"context",
")",
"{",
"final",
"String",
"feature",
"=",
"getFeatureNameConverter",
"(",
"context",
")",
".",
"convertDeclarationName",
"(",... | Generate the given object.
@param action the action.
@param it the target for the generated content.
@param context the context. | [
"Generate",
"the",
"given",
"object",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyGenerator.java#L955-L961 |
awin/rabbiteasy | rabbiteasy-core/src/main/java/com/zanox/rabbiteasy/MessageWriter.java | MessageWriter.writeBodyFromObject | public <T> void writeBodyFromObject(T bodyAsObject, Charset charset) {
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>)bodyAsObject.getClass();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Writer outputWriter = new OutputStreamWriter(outputStream, charset);
try {
Marshaller marshaller = JAXBContext.newInstance(clazz).createMarshaller();
if (clazz.isAnnotationPresent(XmlRootElement.class)) {
marshaller.marshal(bodyAsObject, outputWriter);
} else {
String tagName = unCapitalizedClassName(clazz);
JAXBElement<T> element = new JAXBElement<T>(new QName("", tagName), clazz, bodyAsObject);
marshaller.marshal(element, outputWriter);
}
} catch (JAXBException e) {
throw new RuntimeException(e);
}
byte[] bodyContent = outputStream.toByteArray();
message.contentType(Message.APPLICATION_XML)
.contentEncoding(charset.name());
message.body(bodyContent);
} | java | public <T> void writeBodyFromObject(T bodyAsObject, Charset charset) {
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>)bodyAsObject.getClass();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Writer outputWriter = new OutputStreamWriter(outputStream, charset);
try {
Marshaller marshaller = JAXBContext.newInstance(clazz).createMarshaller();
if (clazz.isAnnotationPresent(XmlRootElement.class)) {
marshaller.marshal(bodyAsObject, outputWriter);
} else {
String tagName = unCapitalizedClassName(clazz);
JAXBElement<T> element = new JAXBElement<T>(new QName("", tagName), clazz, bodyAsObject);
marshaller.marshal(element, outputWriter);
}
} catch (JAXBException e) {
throw new RuntimeException(e);
}
byte[] bodyContent = outputStream.toByteArray();
message.contentType(Message.APPLICATION_XML)
.contentEncoding(charset.name());
message.body(bodyContent);
} | [
"public",
"<",
"T",
">",
"void",
"writeBodyFromObject",
"(",
"T",
"bodyAsObject",
",",
"Charset",
"charset",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Class",
"<",
"T",
">",
"clazz",
"=",
"(",
"Class",
"<",
"T",
">",
")",
"bodyAsObje... | Writes the body by serializing the given object to XML.
@param bodyAsObject The body as object
@param <T> The object type | [
"Writes",
"the",
"body",
"by",
"serializing",
"the",
"given",
"object",
"to",
"XML",
"."
] | train | https://github.com/awin/rabbiteasy/blob/c161efda6c0f7ef319aedf09dfe40a4a90165510/rabbiteasy-core/src/main/java/com/zanox/rabbiteasy/MessageWriter.java#L80-L103 |
pushbit/sprockets | src/main/java/net/sf/sprockets/sql/Statements.java | Statements.setStrings | public static PreparedStatement setStrings(int index, PreparedStatement stmt, String... params)
throws SQLException {
return set(index, stmt, null, null, params);
} | java | public static PreparedStatement setStrings(int index, PreparedStatement stmt, String... params)
throws SQLException {
return set(index, stmt, null, null, params);
} | [
"public",
"static",
"PreparedStatement",
"setStrings",
"(",
"int",
"index",
",",
"PreparedStatement",
"stmt",
",",
"String",
"...",
"params",
")",
"throws",
"SQLException",
"{",
"return",
"set",
"(",
"index",
",",
"stmt",
",",
"null",
",",
"null",
",",
"para... | Set the statement parameters, starting at the index, in the order of the params.
@since 3.0.0 | [
"Set",
"the",
"statement",
"parameters",
"starting",
"at",
"the",
"index",
"in",
"the",
"order",
"of",
"the",
"params",
"."
] | train | https://github.com/pushbit/sprockets/blob/5d967317cbb2374c69d33271d3c7b7311e1ea4ac/src/main/java/net/sf/sprockets/sql/Statements.java#L100-L103 |
alkacon/opencms-core | src-gwt/org/opencms/ade/publish/client/CmsPublishSelectPanel.java | CmsPublishSelectPanel.setGroups | protected void setGroups(List<CmsPublishGroup> groups, boolean newData, String defaultWorkflow) {
m_model = new CmsPublishDataModel(groups, this);
m_model.setSelectionChangeAction(new Runnable() {
public void run() {
onChangePublishSelection();
}
});
m_currentGroupIndex = 0;
m_currentGroupPanel = null;
m_problemsPanel.clear();
if (newData) {
m_showProblemsOnly = false;
m_checkboxProblems.setChecked(false);
m_checkboxProblems.setVisible(false);
m_problemsPanel.setVisible(false);
}
m_groupPanels.clear();
m_groupPanelContainer.clear();
m_scrollPanel.onResizeDescendant();
enableActions(false);
int numGroups = groups.size();
setResourcesVisible(numGroups > 0);
if (numGroups == 0) {
return;
}
enableActions(true);
addMoreListItems();
showProblemCount(m_model.countProblems());
if (defaultWorkflow != null) {
m_workflowSelector.setFormValue(defaultWorkflow, false);
m_publishDialog.setWorkflowId(defaultWorkflow);
m_actions = m_publishDialog.getSelectedWorkflow().getActions();
m_publishDialog.setPanel(CmsPublishDialog.PANEL_SELECT);
}
} | java | protected void setGroups(List<CmsPublishGroup> groups, boolean newData, String defaultWorkflow) {
m_model = new CmsPublishDataModel(groups, this);
m_model.setSelectionChangeAction(new Runnable() {
public void run() {
onChangePublishSelection();
}
});
m_currentGroupIndex = 0;
m_currentGroupPanel = null;
m_problemsPanel.clear();
if (newData) {
m_showProblemsOnly = false;
m_checkboxProblems.setChecked(false);
m_checkboxProblems.setVisible(false);
m_problemsPanel.setVisible(false);
}
m_groupPanels.clear();
m_groupPanelContainer.clear();
m_scrollPanel.onResizeDescendant();
enableActions(false);
int numGroups = groups.size();
setResourcesVisible(numGroups > 0);
if (numGroups == 0) {
return;
}
enableActions(true);
addMoreListItems();
showProblemCount(m_model.countProblems());
if (defaultWorkflow != null) {
m_workflowSelector.setFormValue(defaultWorkflow, false);
m_publishDialog.setWorkflowId(defaultWorkflow);
m_actions = m_publishDialog.getSelectedWorkflow().getActions();
m_publishDialog.setPanel(CmsPublishDialog.PANEL_SELECT);
}
} | [
"protected",
"void",
"setGroups",
"(",
"List",
"<",
"CmsPublishGroup",
">",
"groups",
",",
"boolean",
"newData",
",",
"String",
"defaultWorkflow",
")",
"{",
"m_model",
"=",
"new",
"CmsPublishDataModel",
"(",
"groups",
",",
"this",
")",
";",
"m_model",
".",
"... | Sets the publish groups.<p>
@param groups the list of publish groups
@param newData true if the data is new
@param defaultWorkflow the default workflow id | [
"Sets",
"the",
"publish",
"groups",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/publish/client/CmsPublishSelectPanel.java#L968-L1008 |
apereo/cas | support/cas-server-support-pac4j-webflow/src/main/java/org/apereo/cas/web/flow/DelegatedClientAuthenticationAction.java | DelegatedClientAuthenticationAction.getCredentialsFromDelegatedClient | protected Credentials getCredentialsFromDelegatedClient(final J2EContext webContext, final BaseClient<Credentials, CommonProfile> client) {
val credentials = client.getCredentials(webContext);
LOGGER.debug("Retrieved credentials from client as [{}]", credentials);
if (credentials == null) {
throw new IllegalArgumentException("Unable to determine credentials from the context with client " + client.getName());
}
return credentials;
} | java | protected Credentials getCredentialsFromDelegatedClient(final J2EContext webContext, final BaseClient<Credentials, CommonProfile> client) {
val credentials = client.getCredentials(webContext);
LOGGER.debug("Retrieved credentials from client as [{}]", credentials);
if (credentials == null) {
throw new IllegalArgumentException("Unable to determine credentials from the context with client " + client.getName());
}
return credentials;
} | [
"protected",
"Credentials",
"getCredentialsFromDelegatedClient",
"(",
"final",
"J2EContext",
"webContext",
",",
"final",
"BaseClient",
"<",
"Credentials",
",",
"CommonProfile",
">",
"client",
")",
"{",
"val",
"credentials",
"=",
"client",
".",
"getCredentials",
"(",
... | Gets credentials from delegated client.
@param webContext the web context
@param client the client
@return the credentials from delegated client | [
"Gets",
"credentials",
"from",
"delegated",
"client",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-pac4j-webflow/src/main/java/org/apereo/cas/web/flow/DelegatedClientAuthenticationAction.java#L269-L276 |
oaqa/cse-framework | src/main/java/edu/cmu/lti/oaqa/framework/eval/TraceConsumer.java | TraceConsumer.process | @Override
public void process(CAS aCAS) throws AnalysisEngineProcessException {
try {
JCas jcas = aCAS.getJCas();
ExperimentUUID experiment = ProcessingStepUtils.getCurrentExperiment(jcas);
AnnotationIndex<Annotation> steps = jcas.getAnnotationIndex(ProcessingStep.type);
String uuid = experiment.getUuid();
Trace trace = ProcessingStepUtils.getTrace(steps);
Key key = new Key(uuid, trace, experiment.getStageId());
experiments.add(new ExperimentKey(key.getExperiment(), key.getStage()));
for (TraceListener listener : listeners) {
listener.process(key, jcas);
}
} catch (Exception e) {
throw new AnalysisEngineProcessException(e);
}
} | java | @Override
public void process(CAS aCAS) throws AnalysisEngineProcessException {
try {
JCas jcas = aCAS.getJCas();
ExperimentUUID experiment = ProcessingStepUtils.getCurrentExperiment(jcas);
AnnotationIndex<Annotation> steps = jcas.getAnnotationIndex(ProcessingStep.type);
String uuid = experiment.getUuid();
Trace trace = ProcessingStepUtils.getTrace(steps);
Key key = new Key(uuid, trace, experiment.getStageId());
experiments.add(new ExperimentKey(key.getExperiment(), key.getStage()));
for (TraceListener listener : listeners) {
listener.process(key, jcas);
}
} catch (Exception e) {
throw new AnalysisEngineProcessException(e);
}
} | [
"@",
"Override",
"public",
"void",
"process",
"(",
"CAS",
"aCAS",
")",
"throws",
"AnalysisEngineProcessException",
"{",
"try",
"{",
"JCas",
"jcas",
"=",
"aCAS",
".",
"getJCas",
"(",
")",
";",
"ExperimentUUID",
"experiment",
"=",
"ProcessingStepUtils",
".",
"ge... | Reads the results from the retrieval phase from the DOCUMENT and the DOCUEMNT_GS views of the
JCAs, and generates and evaluates them using the evaluate method from the FMeasureConsumer
class. | [
"Reads",
"the",
"results",
"from",
"the",
"retrieval",
"phase",
"from",
"the",
"DOCUMENT",
"and",
"the",
"DOCUEMNT_GS",
"views",
"of",
"the",
"JCAs",
"and",
"generates",
"and",
"evaluates",
"them",
"using",
"the",
"evaluate",
"method",
"from",
"the",
"FMeasure... | train | https://github.com/oaqa/cse-framework/blob/3a46b5828b3a33be4547345a0ac15e829c43c5ef/src/main/java/edu/cmu/lti/oaqa/framework/eval/TraceConsumer.java#L65-L81 |
apache/incubator-druid | extensions-contrib/materialized-view-maintenance/src/main/java/org/apache/druid/indexing/materializedview/MaterializedViewSupervisor.java | MaterializedViewSupervisor.hasEnoughLag | private boolean hasEnoughLag(Interval target, Interval maxInterval)
{
return minDataLagMs <= (maxInterval.getStartMillis() - target.getStartMillis());
} | java | private boolean hasEnoughLag(Interval target, Interval maxInterval)
{
return minDataLagMs <= (maxInterval.getStartMillis() - target.getStartMillis());
} | [
"private",
"boolean",
"hasEnoughLag",
"(",
"Interval",
"target",
",",
"Interval",
"maxInterval",
")",
"{",
"return",
"minDataLagMs",
"<=",
"(",
"maxInterval",
".",
"getStartMillis",
"(",
")",
"-",
"target",
".",
"getStartMillis",
"(",
")",
")",
";",
"}"
] | check whether the start millis of target interval is more than minDataLagMs lagging behind maxInterval's
minDataLag is required to prevent repeatedly building data because of delay data.
@param target
@param maxInterval
@return true if the start millis of target interval is more than minDataLagMs lagging behind maxInterval's | [
"check",
"whether",
"the",
"start",
"millis",
"of",
"target",
"interval",
"is",
"more",
"than",
"minDataLagMs",
"lagging",
"behind",
"maxInterval",
"s",
"minDataLag",
"is",
"required",
"to",
"prevent",
"repeatedly",
"building",
"data",
"because",
"of",
"delay",
... | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-contrib/materialized-view-maintenance/src/main/java/org/apache/druid/indexing/materializedview/MaterializedViewSupervisor.java#L456-L459 |
j-easy/easy-random | easy-random-core/src/main/java/org/jeasy/random/util/ReflectionUtils.java | ReflectionUtils.asRandomizer | @SuppressWarnings("unchecked")
public static <T> Randomizer<T> asRandomizer(final Supplier<T> supplier) {
class RandomizerProxy implements InvocationHandler {
private final Supplier<?> target;
private RandomizerProxy(final Supplier<?> target) {
this.target = target;
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
if ("getRandomValue".equals(method.getName())) {
Method getMethod = target.getClass().getMethod("get");
getMethod.setAccessible(true);
return getMethod.invoke(target);
}
return null;
}
}
return (Randomizer<T>) Proxy.newProxyInstance(
Randomizer.class.getClassLoader(),
new Class[]{Randomizer.class},
new RandomizerProxy(supplier));
} | java | @SuppressWarnings("unchecked")
public static <T> Randomizer<T> asRandomizer(final Supplier<T> supplier) {
class RandomizerProxy implements InvocationHandler {
private final Supplier<?> target;
private RandomizerProxy(final Supplier<?> target) {
this.target = target;
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
if ("getRandomValue".equals(method.getName())) {
Method getMethod = target.getClass().getMethod("get");
getMethod.setAccessible(true);
return getMethod.invoke(target);
}
return null;
}
}
return (Randomizer<T>) Proxy.newProxyInstance(
Randomizer.class.getClassLoader(),
new Class[]{Randomizer.class},
new RandomizerProxy(supplier));
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"Randomizer",
"<",
"T",
">",
"asRandomizer",
"(",
"final",
"Supplier",
"<",
"T",
">",
"supplier",
")",
"{",
"class",
"RandomizerProxy",
"implements",
"InvocationHandler",
"{... | Create a dynamic proxy that adapts the given {@link Supplier} to a {@link Randomizer}.
@param supplier to adapt
@param <T> target type
@return the proxy randomizer | [
"Create",
"a",
"dynamic",
"proxy",
"that",
"adapts",
"the",
"given",
"{"
] | train | https://github.com/j-easy/easy-random/blob/816b0d6a74c7288af111e70ae1b0b57d7fe3b59d/easy-random-core/src/main/java/org/jeasy/random/util/ReflectionUtils.java#L67-L93 |
loadimpact/loadimpact-sdk-java | src/main/java/com/loadimpact/ApiTokenClient.java | ApiTokenClient.createDataStore | public DataStore createDataStore(final File file, final String name, final int fromline, final DataStore.Separator separator, final DataStore.StringDelimiter delimiter) {
return invoke(DATA_STORES,
new RequestClosure<JsonObject>() {
@Override
public JsonObject call(Invocation.Builder request) {
MultiPart form = new FormDataMultiPart()
.field("name", name)
.field("fromline", Integer.toString(fromline))
.field("separator", separator.param())
.field("delimiter", delimiter.param())
.bodyPart(new FileDataBodyPart("file", file, new MediaType("text", "csv")));
return request.post(Entity.entity(form, form.getMediaType()), JsonObject.class);
}
},
new ResponseClosure<JsonObject, DataStore>() {
@Override
public DataStore call(JsonObject json) {
return new DataStore(json);
}
}
);
} | java | public DataStore createDataStore(final File file, final String name, final int fromline, final DataStore.Separator separator, final DataStore.StringDelimiter delimiter) {
return invoke(DATA_STORES,
new RequestClosure<JsonObject>() {
@Override
public JsonObject call(Invocation.Builder request) {
MultiPart form = new FormDataMultiPart()
.field("name", name)
.field("fromline", Integer.toString(fromline))
.field("separator", separator.param())
.field("delimiter", delimiter.param())
.bodyPart(new FileDataBodyPart("file", file, new MediaType("text", "csv")));
return request.post(Entity.entity(form, form.getMediaType()), JsonObject.class);
}
},
new ResponseClosure<JsonObject, DataStore>() {
@Override
public DataStore call(JsonObject json) {
return new DataStore(json);
}
}
);
} | [
"public",
"DataStore",
"createDataStore",
"(",
"final",
"File",
"file",
",",
"final",
"String",
"name",
",",
"final",
"int",
"fromline",
",",
"final",
"DataStore",
".",
"Separator",
"separator",
",",
"final",
"DataStore",
".",
"StringDelimiter",
"delimiter",
")"... | Creates a new data store.
@param file CSV file that should be uploaded (N.B. max 50MB)
@param name name to use in the Load Impact web-console
@param fromline Payload from this line (1st line is 1). Set to value 2, if the CSV file starts with a headings line
@param separator field separator, one of {@link com.loadimpact.resource.DataStore.Separator}
@param delimiter surround delimiter for text-strings, one of {@link com.loadimpact.resource.DataStore.StringDelimiter}
@return {@link com.loadimpact.resource.DataStore} | [
"Creates",
"a",
"new",
"data",
"store",
"."
] | train | https://github.com/loadimpact/loadimpact-sdk-java/blob/49af80b768c5453266414108b0d30a0fc01b8cef/src/main/java/com/loadimpact/ApiTokenClient.java#L788-L810 |
OpenLiberty/open-liberty | dev/com.ibm.ws.anno/src/com/ibm/ws/anno/info/internal/AnnotationInfoImpl.java | AnnotationInfoImpl.addAnnotationValue | public AnnotationValueImpl addAnnotationValue(String name, String enumClassName, String enumName) {
AnnotationValueImpl annotationValue = new AnnotationValueImpl(enumClassName, enumName);
addAnnotationValue(name, annotationValue);
return annotationValue;
} | java | public AnnotationValueImpl addAnnotationValue(String name, String enumClassName, String enumName) {
AnnotationValueImpl annotationValue = new AnnotationValueImpl(enumClassName, enumName);
addAnnotationValue(name, annotationValue);
return annotationValue;
} | [
"public",
"AnnotationValueImpl",
"addAnnotationValue",
"(",
"String",
"name",
",",
"String",
"enumClassName",
",",
"String",
"enumName",
")",
"{",
"AnnotationValueImpl",
"annotationValue",
"=",
"new",
"AnnotationValueImpl",
"(",
"enumClassName",
",",
"enumName",
")",
... | the enumeration class name and the enumeration literal value. | [
"the",
"enumeration",
"class",
"name",
"and",
"the",
"enumeration",
"literal",
"value",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.anno/src/com/ibm/ws/anno/info/internal/AnnotationInfoImpl.java#L237-L243 |
zaproxy/zaproxy | src/org/parosproxy/paros/view/WorkbenchPanel.java | WorkbenchPanel.getPaneWork | private JPanel getPaneWork() {
if (paneWork == null) {
paneWork = new JPanel();
paneWork.setLayout(new BorderLayout(0,0));
paneWork.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
paneWork.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
paneWork.add(getTabbedWork());
}
return paneWork;
} | java | private JPanel getPaneWork() {
if (paneWork == null) {
paneWork = new JPanel();
paneWork.setLayout(new BorderLayout(0,0));
paneWork.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
paneWork.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
paneWork.add(getTabbedWork());
}
return paneWork;
} | [
"private",
"JPanel",
"getPaneWork",
"(",
")",
"{",
"if",
"(",
"paneWork",
"==",
"null",
")",
"{",
"paneWork",
"=",
"new",
"JPanel",
"(",
")",
";",
"paneWork",
".",
"setLayout",
"(",
"new",
"BorderLayout",
"(",
"0",
",",
"0",
")",
")",
";",
"paneWork"... | This method initializes paneWork, which is used for request/response/break/script console.
@return JPanel | [
"This",
"method",
"initializes",
"paneWork",
"which",
"is",
"used",
"for",
"request",
"/",
"response",
"/",
"break",
"/",
"script",
"console",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/view/WorkbenchPanel.java#L653-L662 |
jnidzwetzki/bitfinex-v2-wss-api-java | src/main/java/com/github/jnidzwetzki/bitfinex/v2/symbol/BitfinexSymbols.java | BitfinexSymbols.orderBook | public static BitfinexOrderBookSymbol orderBook(final BitfinexCurrencyPair currencyPair,
final BitfinexOrderBookSymbol.Precision precision,
final BitfinexOrderBookSymbol.Frequency frequency, final int pricePoints) {
if (precision == BitfinexOrderBookSymbol.Precision.R0) {
throw new IllegalArgumentException("Use BitfinexSymbols#rawOrderBook() factory method instead");
}
return new BitfinexOrderBookSymbol(currencyPair, precision, frequency, pricePoints);
} | java | public static BitfinexOrderBookSymbol orderBook(final BitfinexCurrencyPair currencyPair,
final BitfinexOrderBookSymbol.Precision precision,
final BitfinexOrderBookSymbol.Frequency frequency, final int pricePoints) {
if (precision == BitfinexOrderBookSymbol.Precision.R0) {
throw new IllegalArgumentException("Use BitfinexSymbols#rawOrderBook() factory method instead");
}
return new BitfinexOrderBookSymbol(currencyPair, precision, frequency, pricePoints);
} | [
"public",
"static",
"BitfinexOrderBookSymbol",
"orderBook",
"(",
"final",
"BitfinexCurrencyPair",
"currencyPair",
",",
"final",
"BitfinexOrderBookSymbol",
".",
"Precision",
"precision",
",",
"final",
"BitfinexOrderBookSymbol",
".",
"Frequency",
"frequency",
",",
"final",
... | returns symbol for order book channel
@param currencyPair of order book channel
@param precision of order book
@param frequency of order book
@param pricePoints in initial snapshot
@return symbol | [
"returns",
"symbol",
"for",
"order",
"book",
"channel"
] | train | https://github.com/jnidzwetzki/bitfinex-v2-wss-api-java/blob/2e6adf1eb6f8cd4c8722f1619f78ab2cc3c600ee/src/main/java/com/github/jnidzwetzki/bitfinex/v2/symbol/BitfinexSymbols.java#L134-L143 |
rundeck/rundeck | core/src/main/java/com/dtolabs/utils/Mapper.java | Mapper.makeMap | public static Map makeMap(Mapper mapper, Collection c, boolean includeNull) {
return makeMap(mapper, c.iterator(), includeNull);
} | java | public static Map makeMap(Mapper mapper, Collection c, boolean includeNull) {
return makeMap(mapper, c.iterator(), includeNull);
} | [
"public",
"static",
"Map",
"makeMap",
"(",
"Mapper",
"mapper",
",",
"Collection",
"c",
",",
"boolean",
"includeNull",
")",
"{",
"return",
"makeMap",
"(",
"mapper",
",",
"c",
".",
"iterator",
"(",
")",
",",
"includeNull",
")",
";",
"}"
] | Create a new Map by using the collection objects as keys, and the mapping result as values.
@param mapper a Mapper to map the values
@param c Collection of items
@param includeNull true to include null
@return a new Map with values mapped | [
"Create",
"a",
"new",
"Map",
"by",
"using",
"the",
"collection",
"objects",
"as",
"keys",
"and",
"the",
"mapping",
"result",
"as",
"values",
"."
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/utils/Mapper.java#L535-L537 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java | TrainingsImpl.createImagesFromDataAsync | public Observable<ImageCreateSummary> createImagesFromDataAsync(UUID projectId, byte[] imageData, CreateImagesFromDataOptionalParameter createImagesFromDataOptionalParameter) {
return createImagesFromDataWithServiceResponseAsync(projectId, imageData, createImagesFromDataOptionalParameter).map(new Func1<ServiceResponse<ImageCreateSummary>, ImageCreateSummary>() {
@Override
public ImageCreateSummary call(ServiceResponse<ImageCreateSummary> response) {
return response.body();
}
});
} | java | public Observable<ImageCreateSummary> createImagesFromDataAsync(UUID projectId, byte[] imageData, CreateImagesFromDataOptionalParameter createImagesFromDataOptionalParameter) {
return createImagesFromDataWithServiceResponseAsync(projectId, imageData, createImagesFromDataOptionalParameter).map(new Func1<ServiceResponse<ImageCreateSummary>, ImageCreateSummary>() {
@Override
public ImageCreateSummary call(ServiceResponse<ImageCreateSummary> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ImageCreateSummary",
">",
"createImagesFromDataAsync",
"(",
"UUID",
"projectId",
",",
"byte",
"[",
"]",
"imageData",
",",
"CreateImagesFromDataOptionalParameter",
"createImagesFromDataOptionalParameter",
")",
"{",
"return",
"createImagesFromDataW... | Add the provided images to the set of training images.
This API accepts body content as multipart/form-data and application/octet-stream. When using multipart
multiple image files can be sent at once, with a maximum of 64 files.
@param projectId The project id
@param imageData the InputStream value
@param createImagesFromDataOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ImageCreateSummary object | [
"Add",
"the",
"provided",
"images",
"to",
"the",
"set",
"of",
"training",
"images",
".",
"This",
"API",
"accepts",
"body",
"content",
"as",
"multipart",
"/",
"form",
"-",
"data",
"and",
"application",
"/",
"octet",
"-",
"stream",
".",
"When",
"using",
"m... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L4134-L4141 |
geomajas/geomajas-project-client-gwt | plugin/widget-utility/utility-gwt/src/main/java/org/geomajas/widget/utility/gwt/client/ribbon/dropdown/DropDownPanel.java | DropDownPanel.getButton | private RibbonColumn getButton(ButtonAction action, ButtonLayoutStyle buttonButtonLayoutStyle) {
RibbonColumn column;
if (action instanceof ToolbarButtonCanvas) {
column = new RibbonColumnCanvas((ToolbarButtonCanvas) action);
} else {
// if no layout was given, use the one given by the group
if (null == action.getButtonLayoutStyle()) {
action.setButtonLayoutStyle(buttonButtonLayoutStyle);
}
RibbonButton button = new RibbonButton(action, 16, TitleAlignment.RIGHT);
if (ButtonLayoutStyle.ICON_AND_TITLE.equals(buttonButtonLayoutStyle)) {
button = new RibbonButton(action, GuwLayout.DropDown.ribbonBarDropDownButtonIconSize,
TitleAlignment.RIGHT);
button.setHeight(GuwLayout.DropDown.ribbonBarDropDownButtonIconSize + 4);
} else if (ButtonLayoutStyle.ICON_TITLE_AND_DESCRIPTION.equals(buttonButtonLayoutStyle)) {
button = new RibbonButton(action, GuwLayout.DropDown.ribbonBarDropDownButtonDescriptionIconSize,
TitleAlignment.RIGHT);
button.setHeight(GuwLayout.DropDown.ribbonBarDropDownButtonDescriptionIconSize + 4);
}
button.setOverflow(Overflow.VISIBLE);
button.setWidth100();
button.setMargin(2);
button.addClickHandler(new ClickHandler() {
public void onClick(
com.smartgwt.client.widgets.events.ClickEvent event) {
hide();
}
});
column = button;
}
return column;
} | java | private RibbonColumn getButton(ButtonAction action, ButtonLayoutStyle buttonButtonLayoutStyle) {
RibbonColumn column;
if (action instanceof ToolbarButtonCanvas) {
column = new RibbonColumnCanvas((ToolbarButtonCanvas) action);
} else {
// if no layout was given, use the one given by the group
if (null == action.getButtonLayoutStyle()) {
action.setButtonLayoutStyle(buttonButtonLayoutStyle);
}
RibbonButton button = new RibbonButton(action, 16, TitleAlignment.RIGHT);
if (ButtonLayoutStyle.ICON_AND_TITLE.equals(buttonButtonLayoutStyle)) {
button = new RibbonButton(action, GuwLayout.DropDown.ribbonBarDropDownButtonIconSize,
TitleAlignment.RIGHT);
button.setHeight(GuwLayout.DropDown.ribbonBarDropDownButtonIconSize + 4);
} else if (ButtonLayoutStyle.ICON_TITLE_AND_DESCRIPTION.equals(buttonButtonLayoutStyle)) {
button = new RibbonButton(action, GuwLayout.DropDown.ribbonBarDropDownButtonDescriptionIconSize,
TitleAlignment.RIGHT);
button.setHeight(GuwLayout.DropDown.ribbonBarDropDownButtonDescriptionIconSize + 4);
}
button.setOverflow(Overflow.VISIBLE);
button.setWidth100();
button.setMargin(2);
button.addClickHandler(new ClickHandler() {
public void onClick(
com.smartgwt.client.widgets.events.ClickEvent event) {
hide();
}
});
column = button;
}
return column;
} | [
"private",
"RibbonColumn",
"getButton",
"(",
"ButtonAction",
"action",
",",
"ButtonLayoutStyle",
"buttonButtonLayoutStyle",
")",
"{",
"RibbonColumn",
"column",
";",
"if",
"(",
"action",
"instanceof",
"ToolbarButtonCanvas",
")",
"{",
"column",
"=",
"new",
"RibbonColumn... | Converts the given action into a {@link RibbonColumn}.
@param action ButtonAction
@param buttonButtonLayoutStyle the layout of the group. Is used if the action does not contain one itself.
@return column RibbonColumn containing the button. | [
"Converts",
"the",
"given",
"action",
"into",
"a",
"{",
"@link",
"RibbonColumn",
"}",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/plugin/widget-utility/utility-gwt/src/main/java/org/geomajas/widget/utility/gwt/client/ribbon/dropdown/DropDownPanel.java#L110-L143 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/spatial/split/ST_Split.java | ST_Split.splitMultiLineStringWithLine | private static Geometry splitMultiLineStringWithLine(MultiLineString input, LineString cut) {
Geometry lines = input.difference(cut);
//Only to preserve SQL constrains
if (lines instanceof LineString) {
return FACTORY.createMultiLineString(new LineString[]{(LineString) lines.getGeometryN(0)});
}
return lines;
} | java | private static Geometry splitMultiLineStringWithLine(MultiLineString input, LineString cut) {
Geometry lines = input.difference(cut);
//Only to preserve SQL constrains
if (lines instanceof LineString) {
return FACTORY.createMultiLineString(new LineString[]{(LineString) lines.getGeometryN(0)});
}
return lines;
} | [
"private",
"static",
"Geometry",
"splitMultiLineStringWithLine",
"(",
"MultiLineString",
"input",
",",
"LineString",
"cut",
")",
"{",
"Geometry",
"lines",
"=",
"input",
".",
"difference",
"(",
"cut",
")",
";",
"//Only to preserve SQL constrains",
"if",
"(",
"lines",... | Splits the specified MultiLineString with another lineString.
@param MultiLineString
@param lineString | [
"Splits",
"the",
"specified",
"MultiLineString",
"with",
"another",
"lineString",
"."
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/split/ST_Split.java#L322-L329 |
elki-project/elki | elki-docutil/src/main/java/de/lmu/ifi/dbs/elki/application/internal/MarkdownDocStream.java | MarkdownDocStream.append | public MarkdownDocStream append(CharSequence p, int start, int end) {
for(int pos = start; pos < end; ++pos) {
final char c = p.charAt(pos);
if(c == '\r') {
continue;
}
append(c); // Uses \n magic.
}
return this;
} | java | public MarkdownDocStream append(CharSequence p, int start, int end) {
for(int pos = start; pos < end; ++pos) {
final char c = p.charAt(pos);
if(c == '\r') {
continue;
}
append(c); // Uses \n magic.
}
return this;
} | [
"public",
"MarkdownDocStream",
"append",
"(",
"CharSequence",
"p",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"for",
"(",
"int",
"pos",
"=",
"start",
";",
"pos",
"<",
"end",
";",
"++",
"pos",
")",
"{",
"final",
"char",
"c",
"=",
"p",
".",
... | Output part of a string.
@param p String
@param start Begin
@param end End
@return {@code this} | [
"Output",
"part",
"of",
"a",
"string",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-docutil/src/main/java/de/lmu/ifi/dbs/elki/application/internal/MarkdownDocStream.java#L124-L133 |
OpenLiberty/open-liberty | dev/com.ibm.json4j/src/com/ibm/json/xml/internal/JSONObject.java | JSONObject.writeTextOnlyObject | private void writeTextOnlyObject(Writer writer, int indentDepth, boolean contentOnly, boolean compact)
throws IOException
{
if (logger.isLoggable(Level.FINER)) logger.entering(className, "writeTextOnlyObject(Writer, int, boolean, boolean)");
if (!contentOnly)
{
writeAttribute(writer,this.objectName,this.tagText.trim(),indentDepth, compact);
}
else
{
if (!compact)
{
writeIndention(writer, indentDepth);
writer.write("\"" + escapeStringSpecialCharacters(this.tagText.trim()) + "\"");
}
else
{
writer.write("\"" + escapeStringSpecialCharacters(this.tagText.trim()) + "\"");
}
}
if (logger.isLoggable(Level.FINER)) logger.exiting(className, "writeTextOnlyObject(Writer, int, boolean, boolean)");
} | java | private void writeTextOnlyObject(Writer writer, int indentDepth, boolean contentOnly, boolean compact)
throws IOException
{
if (logger.isLoggable(Level.FINER)) logger.entering(className, "writeTextOnlyObject(Writer, int, boolean, boolean)");
if (!contentOnly)
{
writeAttribute(writer,this.objectName,this.tagText.trim(),indentDepth, compact);
}
else
{
if (!compact)
{
writeIndention(writer, indentDepth);
writer.write("\"" + escapeStringSpecialCharacters(this.tagText.trim()) + "\"");
}
else
{
writer.write("\"" + escapeStringSpecialCharacters(this.tagText.trim()) + "\"");
}
}
if (logger.isLoggable(Level.FINER)) logger.exiting(className, "writeTextOnlyObject(Writer, int, boolean, boolean)");
} | [
"private",
"void",
"writeTextOnlyObject",
"(",
"Writer",
"writer",
",",
"int",
"indentDepth",
",",
"boolean",
"contentOnly",
",",
"boolean",
"compact",
")",
"throws",
"IOException",
"{",
"if",
"(",
"logger",
".",
"isLoggable",
"(",
"Level",
".",
"FINER",
")",
... | Method to write a text ony XML tagset, like <F>FOO</F>
@param writer The writer object to render the XML to.
@param indentDepth How far to indent.
@param contentOnly Whether or not to write the object name as part of the output
@param compact Whether or not to write the ohject in compact form, or nice indent form.
@throws IOException Trhown if an error occurs on write. | [
"Method",
"to",
"write",
"a",
"text",
"ony",
"XML",
"tagset",
"like",
"<F",
">",
"FOO<",
"/",
"F",
">"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.json4j/src/com/ibm/json/xml/internal/JSONObject.java#L621-L644 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/ProcessGroovyMethods.java | ProcessGroovyMethods.consumeProcessOutput | public static void consumeProcessOutput(Process self, Appendable output, Appendable error) {
consumeProcessOutputStream(self, output);
consumeProcessErrorStream(self, error);
} | java | public static void consumeProcessOutput(Process self, Appendable output, Appendable error) {
consumeProcessOutputStream(self, output);
consumeProcessErrorStream(self, error);
} | [
"public",
"static",
"void",
"consumeProcessOutput",
"(",
"Process",
"self",
",",
"Appendable",
"output",
",",
"Appendable",
"error",
")",
"{",
"consumeProcessOutputStream",
"(",
"self",
",",
"output",
")",
";",
"consumeProcessErrorStream",
"(",
"self",
",",
"error... | Gets the output and error streams from a process and reads them
to keep the process from blocking due to a full output buffer.
The processed stream data is appended to the supplied Appendable.
For this, two Threads are started, so this method will return immediately.
The threads will not be join()ed, even if waitFor() is called. To wait
for the output to be fully consumed call waitForProcessOutput().
@param self a Process
@param output an Appendable to capture the process stdout
@param error an Appendable to capture the process stderr
@since 1.7.5 | [
"Gets",
"the",
"output",
"and",
"error",
"streams",
"from",
"a",
"process",
"and",
"reads",
"them",
"to",
"keep",
"the",
"process",
"from",
"blocking",
"due",
"to",
"a",
"full",
"output",
"buffer",
".",
"The",
"processed",
"stream",
"data",
"is",
"appended... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ProcessGroovyMethods.java#L187-L190 |
orhanobut/dialogplus | dialogplus/src/main/java/com/orhanobut/dialogplus/DialogPlusBuilder.java | DialogPlusBuilder.setOutMostMargin | public DialogPlusBuilder setOutMostMargin(int left, int top, int right, int bottom) {
this.outMostMargin[0] = left;
this.outMostMargin[1] = top;
this.outMostMargin[2] = right;
this.outMostMargin[3] = bottom;
return this;
} | java | public DialogPlusBuilder setOutMostMargin(int left, int top, int right, int bottom) {
this.outMostMargin[0] = left;
this.outMostMargin[1] = top;
this.outMostMargin[2] = right;
this.outMostMargin[3] = bottom;
return this;
} | [
"public",
"DialogPlusBuilder",
"setOutMostMargin",
"(",
"int",
"left",
",",
"int",
"top",
",",
"int",
"right",
",",
"int",
"bottom",
")",
"{",
"this",
".",
"outMostMargin",
"[",
"0",
"]",
"=",
"left",
";",
"this",
".",
"outMostMargin",
"[",
"1",
"]",
"... | Add margins to your outmost view which contains everything. As default they are 0
are applied | [
"Add",
"margins",
"to",
"your",
"outmost",
"view",
"which",
"contains",
"everything",
".",
"As",
"default",
"they",
"are",
"0",
"are",
"applied"
] | train | https://github.com/orhanobut/dialogplus/blob/291bf4daaa3c81bf5537125f547913beb8ee2c17/dialogplus/src/main/java/com/orhanobut/dialogplus/DialogPlusBuilder.java#L208-L214 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/animation/GVRAnimation.java | GVRAnimation.setDuration | public GVRAnimation setDuration(float start, float end)
{
if(start>end || start<0 || end>mDuration){
throw new IllegalArgumentException("start and end values are wrong");
}
animationOffset = start;
mDuration = end-start;
return this;
} | java | public GVRAnimation setDuration(float start, float end)
{
if(start>end || start<0 || end>mDuration){
throw new IllegalArgumentException("start and end values are wrong");
}
animationOffset = start;
mDuration = end-start;
return this;
} | [
"public",
"GVRAnimation",
"setDuration",
"(",
"float",
"start",
",",
"float",
"end",
")",
"{",
"if",
"(",
"start",
">",
"end",
"||",
"start",
"<",
"0",
"||",
"end",
">",
"mDuration",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"start and e... | Sets the duration for the animation to be played.
@param start the animation will start playing from the specified time
@param end the animation will stop playing at the specified time
@return {@code this}, so you can chain setProperty() calls.
@throws IllegalArgumentException
If {@code start} is either negative value, greater than
{@code end} value or {@code end} is greater than duration | [
"Sets",
"the",
"duration",
"for",
"the",
"animation",
"to",
"be",
"played",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/animation/GVRAnimation.java#L301-L309 |
lucee/Lucee | core/src/main/java/lucee/runtime/converter/XMLConverter.java | XMLConverter._serializeStruct | private String _serializeStruct(Struct struct, Map<Object, String> done, String id) throws ConverterException {
StringBuilder sb = new StringBuilder(goIn() + "<STRUCT ID=\"" + id + "\">");
Iterator<Key> it = struct.keyIterator();
deep++;
while (it.hasNext()) {
Key key = it.next();
// <ENTRY NAME="STRING" TYPE="STRING">hello</ENTRY>
String value = _serialize(struct.get(key, null), done);
sb.append(goIn() + "<ENTRY NAME=\"" + key.toString() + "\" TYPE=\"" + type + "\">");
sb.append(value);
sb.append(goIn() + "</ENTRY>");
}
deep--;
sb.append(goIn() + "</STRUCT>");
type = "STRUCT";
return sb.toString();
} | java | private String _serializeStruct(Struct struct, Map<Object, String> done, String id) throws ConverterException {
StringBuilder sb = new StringBuilder(goIn() + "<STRUCT ID=\"" + id + "\">");
Iterator<Key> it = struct.keyIterator();
deep++;
while (it.hasNext()) {
Key key = it.next();
// <ENTRY NAME="STRING" TYPE="STRING">hello</ENTRY>
String value = _serialize(struct.get(key, null), done);
sb.append(goIn() + "<ENTRY NAME=\"" + key.toString() + "\" TYPE=\"" + type + "\">");
sb.append(value);
sb.append(goIn() + "</ENTRY>");
}
deep--;
sb.append(goIn() + "</STRUCT>");
type = "STRUCT";
return sb.toString();
} | [
"private",
"String",
"_serializeStruct",
"(",
"Struct",
"struct",
",",
"Map",
"<",
"Object",
",",
"String",
">",
"done",
",",
"String",
"id",
")",
"throws",
"ConverterException",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"goIn",
"(",
")",... | serialize a Struct
@param struct Struct to serialize
@param done
@return serialized struct
@throws ConverterException | [
"serialize",
"a",
"Struct"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/converter/XMLConverter.java#L237-L256 |
OpenLiberty/open-liberty | dev/com.ibm.ws.serialization/src/com/ibm/ws/serialization/DeserializationObjectInputStream.java | DeserializationObjectInputStream.resolveProxyClass | @Override
protected Class<?> resolveProxyClass(String[] interfaceNames) throws ClassNotFoundException {
ClassLoader proxyClassLoader = classLoader;
Class<?>[] interfaces = new Class[interfaceNames.length];
Class<?> nonPublicInterface = null;
for (int i = 0; i < interfaceNames.length; i++) {
Class<?> intf = loadClass(interfaceNames[i]);
if (!Modifier.isPublic(intf.getModifiers())) {
ClassLoader classLoader = getClassLoader(intf);
if (nonPublicInterface != null) {
if (classLoader != proxyClassLoader) {
throw new IllegalAccessError(nonPublicInterface + " and " + intf + " both declared non-public in different class loaders");
}
} else {
nonPublicInterface = intf;
proxyClassLoader = classLoader;
}
}
interfaces[i] = intf;
}
try {
return Proxy.getProxyClass(proxyClassLoader, interfaces);
} catch (IllegalArgumentException ex) {
throw new ClassNotFoundException(null, ex);
}
} | java | @Override
protected Class<?> resolveProxyClass(String[] interfaceNames) throws ClassNotFoundException {
ClassLoader proxyClassLoader = classLoader;
Class<?>[] interfaces = new Class[interfaceNames.length];
Class<?> nonPublicInterface = null;
for (int i = 0; i < interfaceNames.length; i++) {
Class<?> intf = loadClass(interfaceNames[i]);
if (!Modifier.isPublic(intf.getModifiers())) {
ClassLoader classLoader = getClassLoader(intf);
if (nonPublicInterface != null) {
if (classLoader != proxyClassLoader) {
throw new IllegalAccessError(nonPublicInterface + " and " + intf + " both declared non-public in different class loaders");
}
} else {
nonPublicInterface = intf;
proxyClassLoader = classLoader;
}
}
interfaces[i] = intf;
}
try {
return Proxy.getProxyClass(proxyClassLoader, interfaces);
} catch (IllegalArgumentException ex) {
throw new ClassNotFoundException(null, ex);
}
} | [
"@",
"Override",
"protected",
"Class",
"<",
"?",
">",
"resolveProxyClass",
"(",
"String",
"[",
"]",
"interfaceNames",
")",
"throws",
"ClassNotFoundException",
"{",
"ClassLoader",
"proxyClassLoader",
"=",
"classLoader",
";",
"Class",
"<",
"?",
">",
"[",
"]",
"i... | Delegates class loading to the specified class loader.
<p>{@inheritDoc} | [
"Delegates",
"class",
"loading",
"to",
"the",
"specified",
"class",
"loader",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.serialization/src/com/ibm/ws/serialization/DeserializationObjectInputStream.java#L212-L241 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/operators/BatchTask.java | BatchTask.openUserCode | public static void openUserCode(Function stub, Configuration parameters) throws Exception {
try {
FunctionUtils.openFunction(stub, parameters);
} catch (Throwable t) {
throw new Exception("The user defined 'open(Configuration)' method in " + stub.getClass().toString() + " caused an exception: " + t.getMessage(), t);
}
} | java | public static void openUserCode(Function stub, Configuration parameters) throws Exception {
try {
FunctionUtils.openFunction(stub, parameters);
} catch (Throwable t) {
throw new Exception("The user defined 'open(Configuration)' method in " + stub.getClass().toString() + " caused an exception: " + t.getMessage(), t);
}
} | [
"public",
"static",
"void",
"openUserCode",
"(",
"Function",
"stub",
",",
"Configuration",
"parameters",
")",
"throws",
"Exception",
"{",
"try",
"{",
"FunctionUtils",
".",
"openFunction",
"(",
"stub",
",",
"parameters",
")",
";",
"}",
"catch",
"(",
"Throwable"... | Opens the given stub using its {@link org.apache.flink.api.common.functions.RichFunction#open(Configuration)} method. If the open call produces
an exception, a new exception with a standard error message is created, using the encountered exception
as its cause.
@param stub The user code instance to be opened.
@param parameters The parameters supplied to the user code.
@throws Exception Thrown, if the user code's open method produces an exception. | [
"Opens",
"the",
"given",
"stub",
"using",
"its",
"{",
"@link",
"org",
".",
"apache",
".",
"flink",
".",
"api",
".",
"common",
".",
"functions",
".",
"RichFunction#open",
"(",
"Configuration",
")",
"}",
"method",
".",
"If",
"the",
"open",
"call",
"produce... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/operators/BatchTask.java#L1347-L1353 |
jboss/jboss-servlet-api_spec | src/main/java/javax/servlet/http/HttpServletResponseWrapper.java | HttpServletResponseWrapper.setTrailerFields | @Override
public void setTrailerFields(Supplier<Map<String, String>> supplier) {
_getHttpServletResponse().setTrailerFields(supplier);
} | java | @Override
public void setTrailerFields(Supplier<Map<String, String>> supplier) {
_getHttpServletResponse().setTrailerFields(supplier);
} | [
"@",
"Override",
"public",
"void",
"setTrailerFields",
"(",
"Supplier",
"<",
"Map",
"<",
"String",
",",
"String",
">",
">",
"supplier",
")",
"{",
"_getHttpServletResponse",
"(",
")",
".",
"setTrailerFields",
"(",
"supplier",
")",
";",
"}"
] | The default behaviour of this method is to call
{@link HttpServletResponse#setTrailerFields} on the wrapped response
object.
@param supplier of trailer headers
@since Servlet 4.0 | [
"The",
"default",
"behaviour",
"of",
"this",
"method",
"is",
"to",
"call",
"{",
"@link",
"HttpServletResponse#setTrailerFields",
"}",
"on",
"the",
"wrapped",
"response",
"object",
"."
] | train | https://github.com/jboss/jboss-servlet-api_spec/blob/5bc96f2b833c072baff6eb8ae49bc7b5e503e9b2/src/main/java/javax/servlet/http/HttpServletResponseWrapper.java#L340-L343 |
xsonorg/xson | src/main/java/org/xson/core/asm/ClassWriter.java | ClassWriter.newDouble | Item newDouble(final double value) {
key.set(value);
Item result = get(key);
if (result == null) {
pool.putByte(DOUBLE).putLong(key.longVal);
result = new Item(index, key);
put(result);
index += 2;
}
return result;
} | java | Item newDouble(final double value) {
key.set(value);
Item result = get(key);
if (result == null) {
pool.putByte(DOUBLE).putLong(key.longVal);
result = new Item(index, key);
put(result);
index += 2;
}
return result;
} | [
"Item",
"newDouble",
"(",
"final",
"double",
"value",
")",
"{",
"key",
".",
"set",
"(",
"value",
")",
";",
"Item",
"result",
"=",
"get",
"(",
"key",
")",
";",
"if",
"(",
"result",
"==",
"null",
")",
"{",
"pool",
".",
"putByte",
"(",
"DOUBLE",
")"... | Adds a double to the constant pool of the class being build. Does nothing
if the constant pool already contains a similar item.
@param value the double value.
@return a new or already existing double item. | [
"Adds",
"a",
"double",
"to",
"the",
"constant",
"pool",
"of",
"the",
"class",
"being",
"build",
".",
"Does",
"nothing",
"if",
"the",
"constant",
"pool",
"already",
"contains",
"a",
"similar",
"item",
"."
] | train | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/ClassWriter.java#L1113-L1123 |
Impetus/Kundera | src/jpa-engine/core/src/main/java/com/impetus/kundera/graph/GraphGenerator.java | GraphGenerator.setLink | void setLink(Node node, Relation relation, Node childNode, NodeLink nodeLink)
{
nodeLink.setMultiplicity(relation.getType());
EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(node.getPersistenceDelegator()
.getKunderaMetadata(), node.getDataClass());
nodeLink.setLinkProperties(getLinkProperties(metadata, relation, node.getPersistenceDelegator()
.getKunderaMetadata()));
// Add Parent node to this child
childNode.addParentNode(nodeLink, node);
// Add child node to this node
node.addChildNode(nodeLink, childNode);
} | java | void setLink(Node node, Relation relation, Node childNode, NodeLink nodeLink)
{
nodeLink.setMultiplicity(relation.getType());
EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(node.getPersistenceDelegator()
.getKunderaMetadata(), node.getDataClass());
nodeLink.setLinkProperties(getLinkProperties(metadata, relation, node.getPersistenceDelegator()
.getKunderaMetadata()));
// Add Parent node to this child
childNode.addParentNode(nodeLink, node);
// Add child node to this node
node.addChildNode(nodeLink, childNode);
} | [
"void",
"setLink",
"(",
"Node",
"node",
",",
"Relation",
"relation",
",",
"Node",
"childNode",
",",
"NodeLink",
"nodeLink",
")",
"{",
"nodeLink",
".",
"setMultiplicity",
"(",
"relation",
".",
"getType",
"(",
")",
")",
";",
"EntityMetadata",
"metadata",
"=",
... | Set link property
@param node
node
@param relation
relation
@param childNode
target node
@param nodeLink
node link(bridge) | [
"Set",
"link",
"property"
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/graph/GraphGenerator.java#L297-L311 |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java | CalendarCodeGenerator.buildIntervalMethod | private MethodSpec buildIntervalMethod(Map<String, Map<String, String>> intervalFormats, String fallback) {
MethodSpec.Builder method = MethodSpec.methodBuilder("formatInterval")
.addAnnotation(Override.class)
.addModifiers(PUBLIC)
.addParameter(ZonedDateTime.class, "s")
.addParameter(ZonedDateTime.class, "e")
.addParameter(String.class, "k")
.addParameter(DateTimeField.class, "f")
.addParameter(StringBuilder.class, "b");
// Only enter the switches if both params are non-null.
method.beginControlFlow("if (k != null && f != null)");
// BEGIN switch (k)
method.beginControlFlow("switch (k)");
for (Map.Entry<String, Map<String, String>> format : intervalFormats.entrySet()) {
String skeleton = format.getKey();
// BEGIN "case skeleton:"
method.beginControlFlow("case $S:", skeleton);
method.beginControlFlow("switch (f)");
for (Map.Entry<String, String> entry : format.getValue().entrySet()) {
String field = entry.getKey();
// Split the interval pattern on the boundary. We end up with two patterns, one for
// start and end respectively.
Pair<List<Node>, List<Node>> patterns = DATETIME_PARSER.splitIntervalPattern(entry.getValue());
// BEGIN "case field:"
// Render this pair of patterns when the given field matches.
method.beginControlFlow("case $L:", DateTimeField.fromString(field));
method.addComment("$S", DateTimePatternParser.render(patterns._1));
addIntervalPattern(method, patterns._1, "s");
method.addComment("$S", DateTimePatternParser.render(patterns._2));
addIntervalPattern(method, patterns._2, "e");
method.addStatement("return");
method.endControlFlow();
// END "case field:"
}
method.addStatement("default: break");
method.endControlFlow(); // switch (f)
method.addStatement("break");
method.endControlFlow();
// END "case skeleton:"
}
method.addStatement("default: break");
method.endControlFlow();
// END switch (k)
// One of the parameters was null, or nothing matched, so render the
// fallback, e.g. format the start / end separately as "{0} - {1}"
addIntervalFallback(method, fallback);
method.endControlFlow();
return method.build();
} | java | private MethodSpec buildIntervalMethod(Map<String, Map<String, String>> intervalFormats, String fallback) {
MethodSpec.Builder method = MethodSpec.methodBuilder("formatInterval")
.addAnnotation(Override.class)
.addModifiers(PUBLIC)
.addParameter(ZonedDateTime.class, "s")
.addParameter(ZonedDateTime.class, "e")
.addParameter(String.class, "k")
.addParameter(DateTimeField.class, "f")
.addParameter(StringBuilder.class, "b");
// Only enter the switches if both params are non-null.
method.beginControlFlow("if (k != null && f != null)");
// BEGIN switch (k)
method.beginControlFlow("switch (k)");
for (Map.Entry<String, Map<String, String>> format : intervalFormats.entrySet()) {
String skeleton = format.getKey();
// BEGIN "case skeleton:"
method.beginControlFlow("case $S:", skeleton);
method.beginControlFlow("switch (f)");
for (Map.Entry<String, String> entry : format.getValue().entrySet()) {
String field = entry.getKey();
// Split the interval pattern on the boundary. We end up with two patterns, one for
// start and end respectively.
Pair<List<Node>, List<Node>> patterns = DATETIME_PARSER.splitIntervalPattern(entry.getValue());
// BEGIN "case field:"
// Render this pair of patterns when the given field matches.
method.beginControlFlow("case $L:", DateTimeField.fromString(field));
method.addComment("$S", DateTimePatternParser.render(patterns._1));
addIntervalPattern(method, patterns._1, "s");
method.addComment("$S", DateTimePatternParser.render(patterns._2));
addIntervalPattern(method, patterns._2, "e");
method.addStatement("return");
method.endControlFlow();
// END "case field:"
}
method.addStatement("default: break");
method.endControlFlow(); // switch (f)
method.addStatement("break");
method.endControlFlow();
// END "case skeleton:"
}
method.addStatement("default: break");
method.endControlFlow();
// END switch (k)
// One of the parameters was null, or nothing matched, so render the
// fallback, e.g. format the start / end separately as "{0} - {1}"
addIntervalFallback(method, fallback);
method.endControlFlow();
return method.build();
} | [
"private",
"MethodSpec",
"buildIntervalMethod",
"(",
"Map",
"<",
"String",
",",
"Map",
"<",
"String",
",",
"String",
">",
">",
"intervalFormats",
",",
"String",
"fallback",
")",
"{",
"MethodSpec",
".",
"Builder",
"method",
"=",
"MethodSpec",
".",
"methodBuilde... | Build methods to format date time intervals using the field of greatest difference. | [
"Build",
"methods",
"to",
"format",
"date",
"time",
"intervals",
"using",
"the",
"field",
"of",
"greatest",
"difference",
"."
] | train | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L416-L474 |
googleads/googleads-java-lib | examples/admanager_axis/src/main/java/admanager/axis/v201808/producttemplateservice/GetAllProductTemplates.java | GetAllProductTemplates.runExample | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
// Get the ProductTemplateService.
ProductTemplateServiceInterface productTemplateService =
adManagerServices.get(session, ProductTemplateServiceInterface.class);
// Create a statement to select all product templates.
StatementBuilder statementBuilder = new StatementBuilder()
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);
// Default for total result set size.
int totalResultSetSize = 0;
do {
// Get product templates by statement.
ProductTemplatePage page =
productTemplateService.getProductTemplatesByStatement(statementBuilder.toStatement());
if (page.getResults() != null) {
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (ProductTemplate productTemplate : page.getResults()) {
System.out.printf(
"%d) Product template with ID %d and name '%s' was found.%n", i++,
productTemplate.getId(), productTemplate.getName());
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} | java | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
// Get the ProductTemplateService.
ProductTemplateServiceInterface productTemplateService =
adManagerServices.get(session, ProductTemplateServiceInterface.class);
// Create a statement to select all product templates.
StatementBuilder statementBuilder = new StatementBuilder()
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);
// Default for total result set size.
int totalResultSetSize = 0;
do {
// Get product templates by statement.
ProductTemplatePage page =
productTemplateService.getProductTemplatesByStatement(statementBuilder.toStatement());
if (page.getResults() != null) {
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (ProductTemplate productTemplate : page.getResults()) {
System.out.printf(
"%d) Product template with ID %d and name '%s' was found.%n", i++,
productTemplate.getId(), productTemplate.getName());
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} | [
"public",
"static",
"void",
"runExample",
"(",
"AdManagerServices",
"adManagerServices",
",",
"AdManagerSession",
"session",
")",
"throws",
"RemoteException",
"{",
"// Get the ProductTemplateService.",
"ProductTemplateServiceInterface",
"productTemplateService",
"=",
"adManagerSe... | Runs the example.
@param adManagerServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors. | [
"Runs",
"the",
"example",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201808/producttemplateservice/GetAllProductTemplates.java#L52-L85 |
aws/aws-sdk-java | aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/APNSMessage.java | APNSMessage.withData | public APNSMessage withData(java.util.Map<String, String> data) {
setData(data);
return this;
} | java | public APNSMessage withData(java.util.Map<String, String> data) {
setData(data);
return this;
} | [
"public",
"APNSMessage",
"withData",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"data",
")",
"{",
"setData",
"(",
"data",
")",
";",
"return",
"this",
";",
"}"
] | The data payload used for a silent push. This payload is added to the notifications' data.pinpoint.jsonBody'
object
@param data
The data payload used for a silent push. This payload is added to the notifications'
data.pinpoint.jsonBody' object
@return Returns a reference to this object so that method calls can be chained together. | [
"The",
"data",
"payload",
"used",
"for",
"a",
"silent",
"push",
".",
"This",
"payload",
"is",
"added",
"to",
"the",
"notifications",
"data",
".",
"pinpoint",
".",
"jsonBody",
"object"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/APNSMessage.java#L412-L415 |
openbase/jul | exception/src/main/java/org/openbase/jul/exception/StackTracePrinter.java | StackTracePrinter.printStackTrace | public static void printStackTrace(final String message, final StackTraceElement[] stackTraces, final Logger logger, final LogLevel logLevel) {
String stackTraceString = "";
for (final StackTraceElement stackTrace : stackTraces) {
stackTraceString += stackTrace.toString() + "\n";
}
Printer.print((message == null ? "" : message) + "\n=== Stacktrace ===\n" + stackTraceString + "==================", logLevel, logger);
} | java | public static void printStackTrace(final String message, final StackTraceElement[] stackTraces, final Logger logger, final LogLevel logLevel) {
String stackTraceString = "";
for (final StackTraceElement stackTrace : stackTraces) {
stackTraceString += stackTrace.toString() + "\n";
}
Printer.print((message == null ? "" : message) + "\n=== Stacktrace ===\n" + stackTraceString + "==================", logLevel, logger);
} | [
"public",
"static",
"void",
"printStackTrace",
"(",
"final",
"String",
"message",
",",
"final",
"StackTraceElement",
"[",
"]",
"stackTraces",
",",
"final",
"Logger",
"logger",
",",
"final",
"LogLevel",
"logLevel",
")",
"{",
"String",
"stackTraceString",
"=",
"\"... | Method prints the given stack trace in a human readable way.
@param message the reason for printing the stack trace.
@param stackTraces the stack trace to print.
@param logger the logger used for printing.
@param logLevel the log level used for logging the stack trace. | [
"Method",
"prints",
"the",
"given",
"stack",
"trace",
"in",
"a",
"human",
"readable",
"way",
"."
] | train | https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/exception/src/main/java/org/openbase/jul/exception/StackTracePrinter.java#L101-L108 |
facebookarchive/hadoop-20 | src/mapred/org/apache/hadoop/mapred/TaskTracker.java | TaskTracker.reportTaskFinished | void reportTaskFinished(TaskAttemptID taskid, boolean commitPending) {
TaskInProgress tip;
synchronized (this) {
tip = tasks.get(taskid);
}
if (tip != null) {
tip.reportTaskFinished(commitPending);
} else {
LOG.warn("Unknown child task finished: "+taskid+". Ignored.");
}
} | java | void reportTaskFinished(TaskAttemptID taskid, boolean commitPending) {
TaskInProgress tip;
synchronized (this) {
tip = tasks.get(taskid);
}
if (tip != null) {
tip.reportTaskFinished(commitPending);
} else {
LOG.warn("Unknown child task finished: "+taskid+". Ignored.");
}
} | [
"void",
"reportTaskFinished",
"(",
"TaskAttemptID",
"taskid",
",",
"boolean",
"commitPending",
")",
"{",
"TaskInProgress",
"tip",
";",
"synchronized",
"(",
"this",
")",
"{",
"tip",
"=",
"tasks",
".",
"get",
"(",
"taskid",
")",
";",
"}",
"if",
"(",
"tip",
... | The task is no longer running. It may not have completed successfully | [
"The",
"task",
"is",
"no",
"longer",
"running",
".",
"It",
"may",
"not",
"have",
"completed",
"successfully"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/TaskTracker.java#L3772-L3782 |
hawkular/hawkular-agent | hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/CoreJBossASClient.java | CoreJBossASClient.getAppServerDefaultDeploymentDir | public String getAppServerDefaultDeploymentDir() throws Exception {
final String[] addressArr = { SUBSYSTEM, DEPLOYMENT_SCANNER, SCANNER, "default" };
final Address address = Address.root().add(addressArr);
final ModelNode resourceAttributes = readResource(address);
if (resourceAttributes == null) {
return null; // there is no default scanner
}
final String path = resourceAttributes.get("path").asString();
String relativeTo = null;
if (resourceAttributes.hasDefined("relative-to")) {
relativeTo = resourceAttributes.get("relative-to").asString();
}
// path = the actual filesystem path to be scanned. Treated as an absolute path,
// unless 'relative-to' is specified, in which case value is treated as relative to that path.
// relative-to = Reference to a filesystem path defined in the "paths" section of the server
// configuration, or one of the system properties specified on startup.
// NOTE: here we will assume that if specified, it is a system property name.
if (relativeTo != null) {
String syspropValue = System.getProperty(relativeTo);
if (syspropValue == null) {
throw new IllegalStateException("Cannot support relative-to that isn't a sysprop: " + relativeTo);
}
relativeTo = syspropValue;
}
final File dir = new File(relativeTo, path);
return dir.getAbsolutePath();
} | java | public String getAppServerDefaultDeploymentDir() throws Exception {
final String[] addressArr = { SUBSYSTEM, DEPLOYMENT_SCANNER, SCANNER, "default" };
final Address address = Address.root().add(addressArr);
final ModelNode resourceAttributes = readResource(address);
if (resourceAttributes == null) {
return null; // there is no default scanner
}
final String path = resourceAttributes.get("path").asString();
String relativeTo = null;
if (resourceAttributes.hasDefined("relative-to")) {
relativeTo = resourceAttributes.get("relative-to").asString();
}
// path = the actual filesystem path to be scanned. Treated as an absolute path,
// unless 'relative-to' is specified, in which case value is treated as relative to that path.
// relative-to = Reference to a filesystem path defined in the "paths" section of the server
// configuration, or one of the system properties specified on startup.
// NOTE: here we will assume that if specified, it is a system property name.
if (relativeTo != null) {
String syspropValue = System.getProperty(relativeTo);
if (syspropValue == null) {
throw new IllegalStateException("Cannot support relative-to that isn't a sysprop: " + relativeTo);
}
relativeTo = syspropValue;
}
final File dir = new File(relativeTo, path);
return dir.getAbsolutePath();
} | [
"public",
"String",
"getAppServerDefaultDeploymentDir",
"(",
")",
"throws",
"Exception",
"{",
"final",
"String",
"[",
"]",
"addressArr",
"=",
"{",
"SUBSYSTEM",
",",
"DEPLOYMENT_SCANNER",
",",
"SCANNER",
",",
"\"default\"",
"}",
";",
"final",
"Address",
"address",
... | Returns the location where the default deployment scanner is pointing to.
This is where EARs, WARs and the like are deployed to.
@return the default deployments directory - null if there is no deployment scanner
@throws Exception any error | [
"Returns",
"the",
"location",
"where",
"the",
"default",
"deployment",
"scanner",
"is",
"pointing",
"to",
".",
"This",
"is",
"where",
"EARs",
"WARs",
"and",
"the",
"like",
"are",
"deployed",
"to",
"."
] | train | https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/CoreJBossASClient.java#L200-L231 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/metadata/ConnectionRepository.java | ConnectionRepository.addDescriptor | public JdbcConnectionDescriptor addDescriptor(String jcdAlias, String jdbcDriver, String jdbcConnectionUrl, String username, String password)
{
JdbcConnectionDescriptor jcd = new JdbcConnectionDescriptor();
HashMap props = utils.parseConnectionUrl(jdbcConnectionUrl);
jcd.setJcdAlias(jcdAlias);
jcd.setProtocol((String)props.get(JdbcMetadataUtils.PROPERTY_PROTOCOL));
jcd.setSubProtocol((String)props.get(JdbcMetadataUtils.PROPERTY_SUBPROTOCOL));
jcd.setDbAlias((String)props.get(JdbcMetadataUtils.PROPERTY_DBALIAS));
String platform = utils.findPlatformFor(jcd.getSubProtocol(), jdbcDriver);
jcd.setDbms(platform);
jcd.setJdbcLevel(2.0);
jcd.setDriver(jdbcDriver);
if (username != null)
{
jcd.setUserName(username);
jcd.setPassWord(password);
}
if ("default".equals(jcdAlias))
{
jcd.setDefaultConnection(true);
// arminw: MM will search for the default key
// MetadataManager.getInstance().setDefaultPBKey(jcd.getPBKey());
}
addDescriptor(jcd);
return jcd;
} | java | public JdbcConnectionDescriptor addDescriptor(String jcdAlias, String jdbcDriver, String jdbcConnectionUrl, String username, String password)
{
JdbcConnectionDescriptor jcd = new JdbcConnectionDescriptor();
HashMap props = utils.parseConnectionUrl(jdbcConnectionUrl);
jcd.setJcdAlias(jcdAlias);
jcd.setProtocol((String)props.get(JdbcMetadataUtils.PROPERTY_PROTOCOL));
jcd.setSubProtocol((String)props.get(JdbcMetadataUtils.PROPERTY_SUBPROTOCOL));
jcd.setDbAlias((String)props.get(JdbcMetadataUtils.PROPERTY_DBALIAS));
String platform = utils.findPlatformFor(jcd.getSubProtocol(), jdbcDriver);
jcd.setDbms(platform);
jcd.setJdbcLevel(2.0);
jcd.setDriver(jdbcDriver);
if (username != null)
{
jcd.setUserName(username);
jcd.setPassWord(password);
}
if ("default".equals(jcdAlias))
{
jcd.setDefaultConnection(true);
// arminw: MM will search for the default key
// MetadataManager.getInstance().setDefaultPBKey(jcd.getPBKey());
}
addDescriptor(jcd);
return jcd;
} | [
"public",
"JdbcConnectionDescriptor",
"addDescriptor",
"(",
"String",
"jcdAlias",
",",
"String",
"jdbcDriver",
",",
"String",
"jdbcConnectionUrl",
",",
"String",
"username",
",",
"String",
"password",
")",
"{",
"JdbcConnectionDescriptor",
"jcd",
"=",
"new",
"JdbcConne... | Creates and adds a new connection descriptor for the given JDBC connection url.
This method tries to guess the platform to be used, but it should be checked
afterwards nonetheless using the {@link JdbcConnectionDescriptor#getDbms()} method.
For properties that are not part of the url, the following standard values are
explicitly set:
<ul>
<li>jdbc level = 2.0</li>
</ul>
@param jcdAlias The connection alias for the created connection; if 'default' is used,
then the new descriptor will become the default connection descriptor
@param jdbcDriver The fully qualified jdbc driver name
@param jdbcConnectionUrl The connection url of the form '[protocol]:[sub protocol]:{database-specific path]'
where protocol is usually 'jdbc'
@param username The user name (can be <code>null</code>)
@param password The password (can be <code>null</code>)
@return The created connection descriptor
@see JdbcConnectionDescriptor#getDbms() | [
"Creates",
"and",
"adds",
"a",
"new",
"connection",
"descriptor",
"for",
"the",
"given",
"JDBC",
"connection",
"url",
".",
"This",
"method",
"tries",
"to",
"guess",
"the",
"platform",
"to",
"be",
"used",
"but",
"it",
"should",
"be",
"checked",
"afterwards",
... | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/metadata/ConnectionRepository.java#L153-L182 |
joniles/mpxj | src/main/java/net/sf/mpxj/Duration.java | Duration.convertUnits | public Duration convertUnits(TimeUnit type, ProjectProperties defaults)
{
return (convertUnits(m_duration, m_units, type, defaults));
} | java | public Duration convertUnits(TimeUnit type, ProjectProperties defaults)
{
return (convertUnits(m_duration, m_units, type, defaults));
} | [
"public",
"Duration",
"convertUnits",
"(",
"TimeUnit",
"type",
",",
"ProjectProperties",
"defaults",
")",
"{",
"return",
"(",
"convertUnits",
"(",
"m_duration",
",",
"m_units",
",",
"type",
",",
"defaults",
")",
")",
";",
"}"
] | This method provides an <i>approximate</i> conversion between duration
units. It does take into account the project defaults for number of hours
in a day and a week, but it does not take account of calendar details.
The results obtained from it should therefore be treated with caution.
@param type target duration type
@param defaults project properties containing default values
@return new Duration instance | [
"This",
"method",
"provides",
"an",
"<i",
">",
"approximate<",
"/",
"i",
">",
"conversion",
"between",
"duration",
"units",
".",
"It",
"does",
"take",
"into",
"account",
"the",
"project",
"defaults",
"for",
"number",
"of",
"hours",
"in",
"a",
"day",
"and",... | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/Duration.java#L92-L95 |
before/quality-check | modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java | Check.notNegative | @Throws(IllegalNegativeArgumentException.class)
public static double notNegative(final double value, @Nullable final String name) {
if (value < 0.0) {
throw new IllegalNegativeArgumentException(name, value);
}
return value;
} | java | @Throws(IllegalNegativeArgumentException.class)
public static double notNegative(final double value, @Nullable final String name) {
if (value < 0.0) {
throw new IllegalNegativeArgumentException(name, value);
}
return value;
} | [
"@",
"Throws",
"(",
"IllegalNegativeArgumentException",
".",
"class",
")",
"public",
"static",
"double",
"notNegative",
"(",
"final",
"double",
"value",
",",
"@",
"Nullable",
"final",
"String",
"name",
")",
"{",
"if",
"(",
"value",
"<",
"0.0",
")",
"{",
"t... | Ensures that an double reference passed as a parameter to the calling method is not smaller than {@code 0}.
@param value
a number
@param name
name of the number reference (in source code)
@return the non-null reference that was validated
@throws IllegalNullArgumentException
if the given argument {@code reference} is smaller than {@code 0} | [
"Ensures",
"that",
"an",
"double",
"reference",
"passed",
"as",
"a",
"parameter",
"to",
"the",
"calling",
"method",
"is",
"not",
"smaller",
"than",
"{",
"@code",
"0",
"}",
"."
] | train | https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java#L2779-L2785 |
Jasig/uPortal | uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/layout/dlm/remoting/UpdatePreferencesServlet.java | UpdatePreferencesServlet.getMessage | protected String getMessage(String key, String defaultMessage, Locale locale) {
try {
return messageSource.getMessage(key, new Object[] {}, defaultMessage, locale);
} catch (Exception e) {
// sadly, messageSource.getMessage can throw e.g. when message is ill formatted.
logger.error("Error resolving message with key {}.", key, e);
return defaultMessage;
}
} | java | protected String getMessage(String key, String defaultMessage, Locale locale) {
try {
return messageSource.getMessage(key, new Object[] {}, defaultMessage, locale);
} catch (Exception e) {
// sadly, messageSource.getMessage can throw e.g. when message is ill formatted.
logger.error("Error resolving message with key {}.", key, e);
return defaultMessage;
}
} | [
"protected",
"String",
"getMessage",
"(",
"String",
"key",
",",
"String",
"defaultMessage",
",",
"Locale",
"locale",
")",
"{",
"try",
"{",
"return",
"messageSource",
".",
"getMessage",
"(",
"key",
",",
"new",
"Object",
"[",
"]",
"{",
"}",
",",
"defaultMess... | Syntactic sugar for safely resolving a no-args message from message bundle.
@param key Message bundle key
@param defaultMessage Ready-to-present message to fall back upon.
@param locale desired locale
@return Resolved interpolated message or defaultMessage. | [
"Syntactic",
"sugar",
"for",
"safely",
"resolving",
"a",
"no",
"-",
"args",
"message",
"from",
"message",
"bundle",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/layout/dlm/remoting/UpdatePreferencesServlet.java#L1424-L1432 |
jbundle/jbundle | base/screen/view/xml/src/main/java/org/jbundle/base/screen/view/xml/report/XReportBreakScreen.java | XReportBreakScreen.printDataStartForm | public void printDataStartForm(PrintWriter out, int iPrintOptions)
{
Record record = ((ReportBreakScreen)this.getScreenField()).getMainRecord();
String strFile = record.getTableNames(false);
if ((iPrintOptions & HtmlConstants.FOOTING_SCREEN) == HtmlConstants.FOOTING_SCREEN)
out.println(Utility.startTag(XMLTags.FOOTING));
else
out.println(Utility.startTag(XMLTags.HEADING));
out.println(Utility.startTag(XMLTags.FILE));
out.println(Utility.startTag(strFile));
} | java | public void printDataStartForm(PrintWriter out, int iPrintOptions)
{
Record record = ((ReportBreakScreen)this.getScreenField()).getMainRecord();
String strFile = record.getTableNames(false);
if ((iPrintOptions & HtmlConstants.FOOTING_SCREEN) == HtmlConstants.FOOTING_SCREEN)
out.println(Utility.startTag(XMLTags.FOOTING));
else
out.println(Utility.startTag(XMLTags.HEADING));
out.println(Utility.startTag(XMLTags.FILE));
out.println(Utility.startTag(strFile));
} | [
"public",
"void",
"printDataStartForm",
"(",
"PrintWriter",
"out",
",",
"int",
"iPrintOptions",
")",
"{",
"Record",
"record",
"=",
"(",
"(",
"ReportBreakScreen",
")",
"this",
".",
"getScreenField",
"(",
")",
")",
".",
"getMainRecord",
"(",
")",
";",
"String"... | Print this field's data in XML format.
@return true if default params were found for this form.
@param out The http output stream.
@exception DBException File exception. | [
"Print",
"this",
"field",
"s",
"data",
"in",
"XML",
"format",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/xml/src/main/java/org/jbundle/base/screen/view/xml/report/XReportBreakScreen.java#L93-L103 |
rterp/GMapsFX | GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/JavascriptRuntime.java | JavascriptRuntime.getFunction | @Override
public String getFunction(String variable, String function, Object... args) {
return getFunction(variable + "." + function, args);
} | java | @Override
public String getFunction(String variable, String function, Object... args) {
return getFunction(variable + "." + function, args);
} | [
"@",
"Override",
"public",
"String",
"getFunction",
"(",
"String",
"variable",
",",
"String",
"function",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"getFunction",
"(",
"variable",
"+",
"\".\"",
"+",
"function",
",",
"args",
")",
";",
"}"
] | Gets a function as a String, which then can be passed to the execute()
method.
@param variable The variable to invoke the function on.
@param function The function to invoke
@param args Arguments the function requires
@return A string which can be passed to the JavaScript environment to
invoke the function | [
"Gets",
"a",
"function",
"as",
"a",
"String",
"which",
"then",
"can",
"be",
"passed",
"to",
"the",
"execute",
"()",
"method",
"."
] | train | https://github.com/rterp/GMapsFX/blob/4623d3f768e8ad78fc50ee32dd204d236e01059f/GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/JavascriptRuntime.java#L109-L112 |
kiegroup/jbpm | jbpm-human-task/jbpm-human-task-audit/src/main/java/org/jbpm/services/task/audit/TaskAuditLoggerFactory.java | TaskAuditLoggerFactory.newJMSInstance | public static AsyncTaskLifeCycleEventProducer newJMSInstance(boolean transacted, ConnectionFactory connFactory, Queue queue) {
AsyncTaskLifeCycleEventProducer logger = new AsyncTaskLifeCycleEventProducer();
logger.setTransacted(transacted);
logger.setConnectionFactory(connFactory);
logger.setQueue(queue);
return logger;
} | java | public static AsyncTaskLifeCycleEventProducer newJMSInstance(boolean transacted, ConnectionFactory connFactory, Queue queue) {
AsyncTaskLifeCycleEventProducer logger = new AsyncTaskLifeCycleEventProducer();
logger.setTransacted(transacted);
logger.setConnectionFactory(connFactory);
logger.setQueue(queue);
return logger;
} | [
"public",
"static",
"AsyncTaskLifeCycleEventProducer",
"newJMSInstance",
"(",
"boolean",
"transacted",
",",
"ConnectionFactory",
"connFactory",
",",
"Queue",
"queue",
")",
"{",
"AsyncTaskLifeCycleEventProducer",
"logger",
"=",
"new",
"AsyncTaskLifeCycleEventProducer",
"(",
... | Creates new instance of JMS task audit logger based on given connection factory and queue.
@param transacted determines if JMS session is transacted or not
@param connFactory connection factory instance
@param queue JMS queue instance
@return new instance of JMS task audit logger | [
"Creates",
"new",
"instance",
"of",
"JMS",
"task",
"audit",
"logger",
"based",
"on",
"given",
"connection",
"factory",
"and",
"queue",
"."
] | train | https://github.com/kiegroup/jbpm/blob/c3473c728aa382ebbea01e380c5e754a96647b82/jbpm-human-task/jbpm-human-task-audit/src/main/java/org/jbpm/services/task/audit/TaskAuditLoggerFactory.java#L109-L116 |
jparsec/jparsec | jparsec/src/main/java/org/jparsec/SourceLocator.java | SourceLocator.binarySearch | @Private static int binarySearch(IntList ascendingInts, int value) {
for (int begin = 0, to = ascendingInts.size();;) {
if (begin == to) return begin;
int i = (begin + to) / 2;
int x = ascendingInts.get(i);
if (x == value) return i;
else if (x > value) to = i;
else begin = i + 1;
}
} | java | @Private static int binarySearch(IntList ascendingInts, int value) {
for (int begin = 0, to = ascendingInts.size();;) {
if (begin == to) return begin;
int i = (begin + to) / 2;
int x = ascendingInts.get(i);
if (x == value) return i;
else if (x > value) to = i;
else begin = i + 1;
}
} | [
"@",
"Private",
"static",
"int",
"binarySearch",
"(",
"IntList",
"ascendingInts",
",",
"int",
"value",
")",
"{",
"for",
"(",
"int",
"begin",
"=",
"0",
",",
"to",
"=",
"ascendingInts",
".",
"size",
"(",
")",
";",
";",
")",
"{",
"if",
"(",
"begin",
"... | Uses binary search to look up the index of the first element in {@code ascendingInts} that's
greater than or equal to {@code value}. If all elements are smaller than {@code value},
{@code ascendingInts.size()} is returned. | [
"Uses",
"binary",
"search",
"to",
"look",
"up",
"the",
"index",
"of",
"the",
"first",
"element",
"in",
"{"
] | train | https://github.com/jparsec/jparsec/blob/df1280259f5da9eb5ffc537437569dddba66cb94/jparsec/src/main/java/org/jparsec/SourceLocator.java#L148-L157 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/cluster/clusterinstance_clusternode_binding.java | clusterinstance_clusternode_binding.get_nitro_response | protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception{
clusterinstance_clusternode_binding_response result = (clusterinstance_clusternode_binding_response) service.get_payload_formatter().string_to_resource(clusterinstance_clusternode_binding_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
return result.clusterinstance_clusternode_binding;
} | java | protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception{
clusterinstance_clusternode_binding_response result = (clusterinstance_clusternode_binding_response) service.get_payload_formatter().string_to_resource(clusterinstance_clusternode_binding_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
return result.clusterinstance_clusternode_binding;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"clusterinstance_clusternode_binding_response",
"result",
"=",
"(",
"clusterinstance_clusternode_binding_response",
")",
... | <pre>
converts nitro response into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"converts",
"nitro",
"response",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/cluster/clusterinstance_clusternode_binding.java#L198-L215 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/GitlabAPI.java | GitlabAPI.deleteNote | public void deleteNote(GitlabIssue issue, GitlabNote noteToDelete) throws IOException {
deleteNote(String.valueOf(issue.getProjectId()), issue.getId(), noteToDelete);
} | java | public void deleteNote(GitlabIssue issue, GitlabNote noteToDelete) throws IOException {
deleteNote(String.valueOf(issue.getProjectId()), issue.getId(), noteToDelete);
} | [
"public",
"void",
"deleteNote",
"(",
"GitlabIssue",
"issue",
",",
"GitlabNote",
"noteToDelete",
")",
"throws",
"IOException",
"{",
"deleteNote",
"(",
"String",
".",
"valueOf",
"(",
"issue",
".",
"getProjectId",
"(",
")",
")",
",",
"issue",
".",
"getId",
"(",... | Delete an Issue Note
@param issue The issue
@param noteToDelete The note to delete
@throws IOException on gitlab api call error | [
"Delete",
"an",
"Issue",
"Note"
] | train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L2591-L2593 |
p6spy/p6spy | src/main/java/com/p6spy/engine/common/ConnectionInformation.java | ConnectionInformation.fromPooledConnection | public static ConnectionInformation fromPooledConnection(PooledConnection pooledConnection, Connection connection, long timeToGetConnectionNs) {
final ConnectionInformation connectionInformation = new ConnectionInformation();
connectionInformation.pooledConnection = pooledConnection;
connectionInformation.connection = connection;
connectionInformation.timeToGetConnectionNs = timeToGetConnectionNs;
return connectionInformation;
} | java | public static ConnectionInformation fromPooledConnection(PooledConnection pooledConnection, Connection connection, long timeToGetConnectionNs) {
final ConnectionInformation connectionInformation = new ConnectionInformation();
connectionInformation.pooledConnection = pooledConnection;
connectionInformation.connection = connection;
connectionInformation.timeToGetConnectionNs = timeToGetConnectionNs;
return connectionInformation;
} | [
"public",
"static",
"ConnectionInformation",
"fromPooledConnection",
"(",
"PooledConnection",
"pooledConnection",
",",
"Connection",
"connection",
",",
"long",
"timeToGetConnectionNs",
")",
"{",
"final",
"ConnectionInformation",
"connectionInformation",
"=",
"new",
"Connectio... | Creates a new {@link ConnectionInformation} instance for a {@link Connection} which has been obtained via a
{@link PooledConnection}
@param pooledConnection the {@link PooledConnection} which created the {@link #connection}
@param connection the {@link #connection} created by the {@link #pooledConnection}
@param timeToGetConnectionNs the time it took to obtain the connection in nanoseconds
@return a new {@link ConnectionInformation} instance | [
"Creates",
"a",
"new",
"{",
"@link",
"ConnectionInformation",
"}",
"instance",
"for",
"a",
"{",
"@link",
"Connection",
"}",
"which",
"has",
"been",
"obtained",
"via",
"a",
"{",
"@link",
"PooledConnection",
"}"
] | train | https://github.com/p6spy/p6spy/blob/c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2/src/main/java/com/p6spy/engine/common/ConnectionInformation.java#L89-L95 |
alkacon/opencms-core | src/org/opencms/util/CmsHtmlExtractor.java | CmsHtmlExtractor.extractText | public static String extractText(String content, String encoding)
throws ParserException, UnsupportedEncodingException {
if (CmsStringUtil.isEmpty(content)) {
// if there is no HTML, then we don't need to extract anything
return content;
}
// we must make sure that the content passed to the parser always is
// a "valid" HTML page, i.e. is surrounded by <html><body>...</body></html>
// otherwise you will get strange results for some specific HTML constructs
StringBuffer newContent = new StringBuffer(content.length() + 32);
newContent.append(CmsLinkProcessor.HTML_START);
newContent.append(content);
newContent.append(CmsLinkProcessor.HTML_END);
// make sure the Lexer uses the right encoding
InputStream in = new ByteArrayInputStream(newContent.toString().getBytes(encoding));
// use the stream based version to process the results
return extractText(in, encoding);
} | java | public static String extractText(String content, String encoding)
throws ParserException, UnsupportedEncodingException {
if (CmsStringUtil.isEmpty(content)) {
// if there is no HTML, then we don't need to extract anything
return content;
}
// we must make sure that the content passed to the parser always is
// a "valid" HTML page, i.e. is surrounded by <html><body>...</body></html>
// otherwise you will get strange results for some specific HTML constructs
StringBuffer newContent = new StringBuffer(content.length() + 32);
newContent.append(CmsLinkProcessor.HTML_START);
newContent.append(content);
newContent.append(CmsLinkProcessor.HTML_END);
// make sure the Lexer uses the right encoding
InputStream in = new ByteArrayInputStream(newContent.toString().getBytes(encoding));
// use the stream based version to process the results
return extractText(in, encoding);
} | [
"public",
"static",
"String",
"extractText",
"(",
"String",
"content",
",",
"String",
"encoding",
")",
"throws",
"ParserException",
",",
"UnsupportedEncodingException",
"{",
"if",
"(",
"CmsStringUtil",
".",
"isEmpty",
"(",
"content",
")",
")",
"{",
"// if there is... | Extract the text from a HTML page.<p>
@param content the html content
@param encoding the encoding of the content
@return the extracted text from the page
@throws ParserException if the parsing of the HTML failed
@throws UnsupportedEncodingException if the given encoding is not supported | [
"Extract",
"the",
"text",
"from",
"a",
"HTML",
"page",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsHtmlExtractor.java#L93-L115 |
google/gson | gson/src/main/java/com/google/gson/internal/bind/util/ISO8601Utils.java | ISO8601Utils.parseInt | private static int parseInt(String value, int beginIndex, int endIndex) throws NumberFormatException {
if (beginIndex < 0 || endIndex > value.length() || beginIndex > endIndex) {
throw new NumberFormatException(value);
}
// use same logic as in Integer.parseInt() but less generic we're not supporting negative values
int i = beginIndex;
int result = 0;
int digit;
if (i < endIndex) {
digit = Character.digit(value.charAt(i++), 10);
if (digit < 0) {
throw new NumberFormatException("Invalid number: " + value.substring(beginIndex, endIndex));
}
result = -digit;
}
while (i < endIndex) {
digit = Character.digit(value.charAt(i++), 10);
if (digit < 0) {
throw new NumberFormatException("Invalid number: " + value.substring(beginIndex, endIndex));
}
result *= 10;
result -= digit;
}
return -result;
} | java | private static int parseInt(String value, int beginIndex, int endIndex) throws NumberFormatException {
if (beginIndex < 0 || endIndex > value.length() || beginIndex > endIndex) {
throw new NumberFormatException(value);
}
// use same logic as in Integer.parseInt() but less generic we're not supporting negative values
int i = beginIndex;
int result = 0;
int digit;
if (i < endIndex) {
digit = Character.digit(value.charAt(i++), 10);
if (digit < 0) {
throw new NumberFormatException("Invalid number: " + value.substring(beginIndex, endIndex));
}
result = -digit;
}
while (i < endIndex) {
digit = Character.digit(value.charAt(i++), 10);
if (digit < 0) {
throw new NumberFormatException("Invalid number: " + value.substring(beginIndex, endIndex));
}
result *= 10;
result -= digit;
}
return -result;
} | [
"private",
"static",
"int",
"parseInt",
"(",
"String",
"value",
",",
"int",
"beginIndex",
",",
"int",
"endIndex",
")",
"throws",
"NumberFormatException",
"{",
"if",
"(",
"beginIndex",
"<",
"0",
"||",
"endIndex",
">",
"value",
".",
"length",
"(",
")",
"||",... | Parse an integer located between 2 given offsets in a string
@param value the string to parse
@param beginIndex the start index for the integer in the string
@param endIndex the end index for the integer in the string
@return the int
@throws NumberFormatException if the value is not a number | [
"Parse",
"an",
"integer",
"located",
"between",
"2",
"given",
"offsets",
"in",
"a",
"string"
] | train | https://github.com/google/gson/blob/63ee47cb642c8018e5cddd639aa2be143220ad4b/gson/src/main/java/com/google/gson/internal/bind/util/ISO8601Utils.java#L300-L324 |
Deep-Symmetry/beat-link | src/main/java/org/deepsymmetry/beatlink/data/MetadataFinder.java | MetadataFinder.getAutoAttachCacheFiles | public List<File> getAutoAttachCacheFiles() {
ArrayList<File> currentFiles = new ArrayList<File>(autoAttachCacheFiles);
Collections.sort(currentFiles, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName());
}
});
return Collections.unmodifiableList(currentFiles);
} | java | public List<File> getAutoAttachCacheFiles() {
ArrayList<File> currentFiles = new ArrayList<File>(autoAttachCacheFiles);
Collections.sort(currentFiles, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName());
}
});
return Collections.unmodifiableList(currentFiles);
} | [
"public",
"List",
"<",
"File",
">",
"getAutoAttachCacheFiles",
"(",
")",
"{",
"ArrayList",
"<",
"File",
">",
"currentFiles",
"=",
"new",
"ArrayList",
"<",
"File",
">",
"(",
"autoAttachCacheFiles",
")",
";",
"Collections",
".",
"sort",
"(",
"currentFiles",
",... | Get the metadata cache files that are currently configured to be automatically attached when matching media is
mounted in a player on the network.
@return the current auto-attache cache files, sorted by name | [
"Get",
"the",
"metadata",
"cache",
"files",
"that",
"are",
"currently",
"configured",
"to",
"be",
"automatically",
"attached",
"when",
"matching",
"media",
"is",
"mounted",
"in",
"a",
"player",
"on",
"the",
"network",
"."
] | train | https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/MetadataFinder.java#L665-L674 |
google/closure-templates | java/src/com/google/template/soy/pysrc/internal/GenPyCallExprVisitor.java | GenPyCallExprVisitor.escapeCall | private PyExpr escapeCall(String callExpr, ImmutableList<SoyPrintDirective> directives) {
PyExpr escapedExpr = new PyExpr(callExpr, Integer.MAX_VALUE);
if (directives.isEmpty()) {
return escapedExpr;
}
// Successively wrap each escapedExpr in various directives.
for (SoyPrintDirective directive : directives) {
Preconditions.checkState(
directive instanceof SoyPySrcPrintDirective,
"Autoescaping produced a bogus directive: %s",
directive.getName());
escapedExpr =
((SoyPySrcPrintDirective) directive).applyForPySrc(escapedExpr, ImmutableList.of());
}
return escapedExpr;
} | java | private PyExpr escapeCall(String callExpr, ImmutableList<SoyPrintDirective> directives) {
PyExpr escapedExpr = new PyExpr(callExpr, Integer.MAX_VALUE);
if (directives.isEmpty()) {
return escapedExpr;
}
// Successively wrap each escapedExpr in various directives.
for (SoyPrintDirective directive : directives) {
Preconditions.checkState(
directive instanceof SoyPySrcPrintDirective,
"Autoescaping produced a bogus directive: %s",
directive.getName());
escapedExpr =
((SoyPySrcPrintDirective) directive).applyForPySrc(escapedExpr, ImmutableList.of());
}
return escapedExpr;
} | [
"private",
"PyExpr",
"escapeCall",
"(",
"String",
"callExpr",
",",
"ImmutableList",
"<",
"SoyPrintDirective",
">",
"directives",
")",
"{",
"PyExpr",
"escapedExpr",
"=",
"new",
"PyExpr",
"(",
"callExpr",
",",
"Integer",
".",
"MAX_VALUE",
")",
";",
"if",
"(",
... | Escaping directives might apply to the output of the call node, so wrap the output with all
required directives.
@param callExpr The expression text of the call itself.
@param directives The list of the directives to be applied to the call.
@return A PyExpr containing the call expression with all directives applied. | [
"Escaping",
"directives",
"might",
"apply",
"to",
"the",
"output",
"of",
"the",
"call",
"node",
"so",
"wrap",
"the",
"output",
"with",
"all",
"required",
"directives",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/GenPyCallExprVisitor.java#L280-L296 |
jbundle/jbundle | thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/BaseApplet.java | BaseApplet.setStatus | public Object setStatus(int iStatus, Object comp, Object cursor)
{
Cursor oldCursor = null;
if (comp instanceof Component)
if (SwingUtilities.isEventDispatchThread()) // Just being careful
{
oldCursor = ((Component)comp).getCursor();
if (cursor == null)
cursor = (Cursor)Cursor.getPredefinedCursor(iStatus);
((Component)comp).setCursor((Cursor)cursor);
}
if (m_statusbar != null)
m_statusbar.setStatus(iStatus);
return oldCursor;
} | java | public Object setStatus(int iStatus, Object comp, Object cursor)
{
Cursor oldCursor = null;
if (comp instanceof Component)
if (SwingUtilities.isEventDispatchThread()) // Just being careful
{
oldCursor = ((Component)comp).getCursor();
if (cursor == null)
cursor = (Cursor)Cursor.getPredefinedCursor(iStatus);
((Component)comp).setCursor((Cursor)cursor);
}
if (m_statusbar != null)
m_statusbar.setStatus(iStatus);
return oldCursor;
} | [
"public",
"Object",
"setStatus",
"(",
"int",
"iStatus",
",",
"Object",
"comp",
",",
"Object",
"cursor",
")",
"{",
"Cursor",
"oldCursor",
"=",
"null",
";",
"if",
"(",
"comp",
"instanceof",
"Component",
")",
"if",
"(",
"SwingUtilities",
".",
"isEventDispatchTh... | Display the status text.
@param strMessage The message to display. | [
"Display",
"the",
"status",
"text",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/BaseApplet.java#L1541-L1555 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/BingImagesImpl.java | BingImagesImpl.visualSearchAsync | public ServiceFuture<ImageKnowledge> visualSearchAsync(VisualSearchOptionalParameter visualSearchOptionalParameter, final ServiceCallback<ImageKnowledge> serviceCallback) {
return ServiceFuture.fromResponse(visualSearchWithServiceResponseAsync(visualSearchOptionalParameter), serviceCallback);
} | java | public ServiceFuture<ImageKnowledge> visualSearchAsync(VisualSearchOptionalParameter visualSearchOptionalParameter, final ServiceCallback<ImageKnowledge> serviceCallback) {
return ServiceFuture.fromResponse(visualSearchWithServiceResponseAsync(visualSearchOptionalParameter), serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"ImageKnowledge",
">",
"visualSearchAsync",
"(",
"VisualSearchOptionalParameter",
"visualSearchOptionalParameter",
",",
"final",
"ServiceCallback",
"<",
"ImageKnowledge",
">",
"serviceCallback",
")",
"{",
"return",
"ServiceFuture",
".",
"from... | Visual Search API lets you discover insights about an image such as visually similar images, shopping sources, and related searches. The API can also perform text recognition, identify entities (people, places, things), return other topical content for the user to explore, and more. For more information, see [Visual Search Overview](https://docs.microsoft.com/azure/cognitive-services/bing-visual-search/overview).
@param visualSearchOptionalParameter the object representing the optional parameters to be set before calling this API
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Visual",
"Search",
"API",
"lets",
"you",
"discover",
"insights",
"about",
"an",
"image",
"such",
"as",
"visually",
"similar",
"images",
"shopping",
"sources",
"and",
"related",
"searches",
".",
"The",
"API",
"can",
"also",
"perform",
"text",
"recognition",
"i... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/BingImagesImpl.java#L86-L88 |
hawkular/hawkular-inventory | hawkular-inventory-api/src/main/java/org/hawkular/inventory/base/Traversal.java | Traversal.inTx | protected <R> R inTx(TransactionPayload<R, BE> payload) {
return inTx(context, payload);
} | java | protected <R> R inTx(TransactionPayload<R, BE> payload) {
return inTx(context, payload);
} | [
"protected",
"<",
"R",
">",
"R",
"inTx",
"(",
"TransactionPayload",
"<",
"R",
",",
"BE",
">",
"payload",
")",
"{",
"return",
"inTx",
"(",
"context",
",",
"payload",
")",
";",
"}"
] | Runs the payload in transaction. It is the payload's responsibility to commit the transaction at some point
during its execution. If the payload throws an exception the transaction is automatically rolled back and
the exception rethrown.
<p>
<p><b>WARNING:</b> the payload might be called multiple times if the transaction it runs within fails. It is
therefore dangerous to keep any mutable state outside of the payload function that the function depends on.
@param payload the payload to execute in transaction
@param <R> the return type
@return the return value provided by the payload | [
"Runs",
"the",
"payload",
"in",
"transaction",
".",
"It",
"is",
"the",
"payload",
"s",
"responsibility",
"to",
"commit",
"the",
"transaction",
"at",
"some",
"point",
"during",
"its",
"execution",
".",
"If",
"the",
"payload",
"throws",
"an",
"exception",
"the... | train | https://github.com/hawkular/hawkular-inventory/blob/f56dc10323dca21777feb5b609a9e9cc70ffaf62/hawkular-inventory-api/src/main/java/org/hawkular/inventory/base/Traversal.java#L78-L80 |
pietermartin/sqlg | sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/AbstractLabel.java | AbstractLabel.removeIndex | void removeIndex(Index idx, boolean preserveData) {
this.getSchema().getTopology().lock();
if (!uncommittedRemovedIndexes.contains(idx.getName())) {
uncommittedRemovedIndexes.add(idx.getName());
TopologyManager.removeIndex(this.sqlgGraph, idx);
if (!preserveData) {
idx.delete(sqlgGraph);
}
this.getSchema().getTopology().fire(idx, "", TopologyChangeAction.DELETE);
}
} | java | void removeIndex(Index idx, boolean preserveData) {
this.getSchema().getTopology().lock();
if (!uncommittedRemovedIndexes.contains(idx.getName())) {
uncommittedRemovedIndexes.add(idx.getName());
TopologyManager.removeIndex(this.sqlgGraph, idx);
if (!preserveData) {
idx.delete(sqlgGraph);
}
this.getSchema().getTopology().fire(idx, "", TopologyChangeAction.DELETE);
}
} | [
"void",
"removeIndex",
"(",
"Index",
"idx",
",",
"boolean",
"preserveData",
")",
"{",
"this",
".",
"getSchema",
"(",
")",
".",
"getTopology",
"(",
")",
".",
"lock",
"(",
")",
";",
"if",
"(",
"!",
"uncommittedRemovedIndexes",
".",
"contains",
"(",
"idx",
... | remove a given index that was on this label
@param idx the index
@param preserveData should we keep the SQL data | [
"remove",
"a",
"given",
"index",
"that",
"was",
"on",
"this",
"label"
] | train | https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/AbstractLabel.java#L1032-L1042 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/classfile/analysis/FieldInfo.java | FieldInfo.createUnresolvedFieldInfo | public static FieldInfo createUnresolvedFieldInfo(String className, String name, String signature, boolean isStatic) {
className = ClassName.toSlashedClassName(className);
return new FieldInfo(className, name, signature, null, // without seeing
// the definition
// we don't know
// if it has a
// generic type
isStatic ? Const.ACC_STATIC : 0, new HashMap<ClassDescriptor, AnnotationValue>(), false);
} | java | public static FieldInfo createUnresolvedFieldInfo(String className, String name, String signature, boolean isStatic) {
className = ClassName.toSlashedClassName(className);
return new FieldInfo(className, name, signature, null, // without seeing
// the definition
// we don't know
// if it has a
// generic type
isStatic ? Const.ACC_STATIC : 0, new HashMap<ClassDescriptor, AnnotationValue>(), false);
} | [
"public",
"static",
"FieldInfo",
"createUnresolvedFieldInfo",
"(",
"String",
"className",
",",
"String",
"name",
",",
"String",
"signature",
",",
"boolean",
"isStatic",
")",
"{",
"className",
"=",
"ClassName",
".",
"toSlashedClassName",
"(",
"className",
")",
";",... | Create a FieldInfo object to represent an unresolved field.
<em>Don't call this directly - use XFactory instead.</em>
@param className
name of class containing the field
@param name
name of field
@param signature
field signature
@param isStatic
true if field is static, false otherwise
@return FieldInfo object representing the unresolved field | [
"Create",
"a",
"FieldInfo",
"object",
"to",
"represent",
"an",
"unresolved",
"field",
".",
"<em",
">",
"Don",
"t",
"call",
"this",
"directly",
"-",
"use",
"XFactory",
"instead",
".",
"<",
"/",
"em",
">"
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/classfile/analysis/FieldInfo.java#L308-L316 |
dustin/java-memcached-client | src/main/java/net/spy/memcached/MemcachedConnection.java | MemcachedConnection.addOperation | protected void addOperation(final MemcachedNode node, final Operation o) {
if (!node.isAuthenticated()) {
retryOperation(o);
return;
}
o.setHandlingNode(node);
o.initialize();
node.addOp(o);
addedQueue.offer(node);
metrics.markMeter(OVERALL_REQUEST_METRIC);
Selector s = selector.wakeup();
assert s == selector : "Wakeup returned the wrong selector.";
getLogger().debug("Added %s to %s", o, node);
} | java | protected void addOperation(final MemcachedNode node, final Operation o) {
if (!node.isAuthenticated()) {
retryOperation(o);
return;
}
o.setHandlingNode(node);
o.initialize();
node.addOp(o);
addedQueue.offer(node);
metrics.markMeter(OVERALL_REQUEST_METRIC);
Selector s = selector.wakeup();
assert s == selector : "Wakeup returned the wrong selector.";
getLogger().debug("Added %s to %s", o, node);
} | [
"protected",
"void",
"addOperation",
"(",
"final",
"MemcachedNode",
"node",
",",
"final",
"Operation",
"o",
")",
"{",
"if",
"(",
"!",
"node",
".",
"isAuthenticated",
"(",
")",
")",
"{",
"retryOperation",
"(",
"o",
")",
";",
"return",
";",
"}",
"o",
"."... | Enqueue an operation on the given node.
@param node the node where to enqueue the {@link Operation}.
@param o the operation to add. | [
"Enqueue",
"an",
"operation",
"on",
"the",
"given",
"node",
"."
] | train | https://github.com/dustin/java-memcached-client/blob/c232307ad8e0c7ccc926e495dd7d5aad2d713318/src/main/java/net/spy/memcached/MemcachedConnection.java#L1274-L1288 |
kuali/ojb-1.0.4 | src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java | OjbTagsHandler.forAllForeignkeys | public void forAllForeignkeys(String template, Properties attributes) throws XDocletException
{
for (Iterator it = _curTableDef.getForeignkeys(); it.hasNext(); )
{
_curForeignkeyDef = (ForeignkeyDef)it.next();
generate(template);
}
_curForeignkeyDef = null;
} | java | public void forAllForeignkeys(String template, Properties attributes) throws XDocletException
{
for (Iterator it = _curTableDef.getForeignkeys(); it.hasNext(); )
{
_curForeignkeyDef = (ForeignkeyDef)it.next();
generate(template);
}
_curForeignkeyDef = null;
} | [
"public",
"void",
"forAllForeignkeys",
"(",
"String",
"template",
",",
"Properties",
"attributes",
")",
"throws",
"XDocletException",
"{",
"for",
"(",
"Iterator",
"it",
"=",
"_curTableDef",
".",
"getForeignkeys",
"(",
")",
";",
"it",
".",
"hasNext",
"(",
")",
... | Processes the template for all foreignkeys of the current table.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException if an error occurs
@doc.tag type="block" | [
"Processes",
"the",
"template",
"for",
"all",
"foreignkeys",
"of",
"the",
"current",
"table",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java#L1362-L1370 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/management/CapturingClassTransformer.java | CapturingClassTransformer.initialize | private void initialize(final File logDirectory, final String aaplName) {
if (logDirectory == null) {
captureEnabled = false;
return;
}
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
// Create a new or reuse an existing base capture directory
String captureDirStr = "JPATransform" + "/" + ((aaplName != null) ? aaplName : "unknownapp");
captureRootDir = new File(logDirectory, captureDirStr);
captureEnabled = captureRootDir.mkdirs() || captureRootDir.isDirectory();
if (!captureEnabled) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Cannot create server instance capture directory, so enhanced entity bytecode will not be captured.");
}
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Capturing enhanced bytecode for JPA entities to " + captureRootDir.getAbsolutePath());
}
}
return null;
}
});
} | java | private void initialize(final File logDirectory, final String aaplName) {
if (logDirectory == null) {
captureEnabled = false;
return;
}
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
// Create a new or reuse an existing base capture directory
String captureDirStr = "JPATransform" + "/" + ((aaplName != null) ? aaplName : "unknownapp");
captureRootDir = new File(logDirectory, captureDirStr);
captureEnabled = captureRootDir.mkdirs() || captureRootDir.isDirectory();
if (!captureEnabled) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Cannot create server instance capture directory, so enhanced entity bytecode will not be captured.");
}
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Capturing enhanced bytecode for JPA entities to " + captureRootDir.getAbsolutePath());
}
}
return null;
}
});
} | [
"private",
"void",
"initialize",
"(",
"final",
"File",
"logDirectory",
",",
"final",
"String",
"aaplName",
")",
"{",
"if",
"(",
"logDirectory",
"==",
"null",
")",
"{",
"captureEnabled",
"=",
"false",
";",
"return",
";",
"}",
"AccessController",
".",
"doPrivi... | Determines the existence of the server log directory, and attempts to create a capture
directory within the log directory. If this can be accomplished, the field captureEnabled
is set to true. Otherwise, it is left to its default value false if the capture directory
cannot be used.
@param logDirectory | [
"Determines",
"the",
"existence",
"of",
"the",
"server",
"log",
"directory",
"and",
"attempts",
"to",
"create",
"a",
"capture",
"directory",
"within",
"the",
"log",
"directory",
".",
"If",
"this",
"can",
"be",
"accomplished",
"the",
"field",
"captureEnabled",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/management/CapturingClassTransformer.java#L128-L155 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/CopiedOverriddenMethod.java | CopiedOverriddenMethod.visitCode | @Override
public void visitCode(Code obj) {
try {
Method m = getMethod();
if ((!m.isPublic() && !m.isProtected()) || m.isAbstract() || m.isSynthetic()) {
return;
}
CodeInfo superCode = superclassCode.remove(curMethodInfo);
if (superCode != null) {
if (sameAccess(getMethod().getAccessFlags(), superCode.getAccess()) && codeEquals(obj, superCode.getCode())) {
bugReporter.reportBug(new BugInstance(this, BugType.COM_COPIED_OVERRIDDEN_METHOD.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
.addSourceLine(classContext, this, getPC()));
return;
}
if ((getMethod().getAccessFlags() & Const.ACC_SYNCHRONIZED) != (superCode.getAccess() & Const.ACC_SYNCHRONIZED)) {
return;
}
parmTypes = getMethod().getArgumentTypes();
nextParmIndex = 0;
nextParmOffset = getMethod().isStatic() ? 0 : 1;
sawAload0 = nextParmOffset == 0;
sawParentCall = false;
super.visitCode(obj);
}
} catch (StopOpcodeParsingException e) {
// method is unique
}
} | java | @Override
public void visitCode(Code obj) {
try {
Method m = getMethod();
if ((!m.isPublic() && !m.isProtected()) || m.isAbstract() || m.isSynthetic()) {
return;
}
CodeInfo superCode = superclassCode.remove(curMethodInfo);
if (superCode != null) {
if (sameAccess(getMethod().getAccessFlags(), superCode.getAccess()) && codeEquals(obj, superCode.getCode())) {
bugReporter.reportBug(new BugInstance(this, BugType.COM_COPIED_OVERRIDDEN_METHOD.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
.addSourceLine(classContext, this, getPC()));
return;
}
if ((getMethod().getAccessFlags() & Const.ACC_SYNCHRONIZED) != (superCode.getAccess() & Const.ACC_SYNCHRONIZED)) {
return;
}
parmTypes = getMethod().getArgumentTypes();
nextParmIndex = 0;
nextParmOffset = getMethod().isStatic() ? 0 : 1;
sawAload0 = nextParmOffset == 0;
sawParentCall = false;
super.visitCode(obj);
}
} catch (StopOpcodeParsingException e) {
// method is unique
}
} | [
"@",
"Override",
"public",
"void",
"visitCode",
"(",
"Code",
"obj",
")",
"{",
"try",
"{",
"Method",
"m",
"=",
"getMethod",
"(",
")",
";",
"if",
"(",
"(",
"!",
"m",
".",
"isPublic",
"(",
")",
"&&",
"!",
"m",
".",
"isProtected",
"(",
")",
")",
"|... | overrides the visitor to find code blocks of methods that are the same as its parents
@param obj
the code object of the currently parsed method | [
"overrides",
"the",
"visitor",
"to",
"find",
"code",
"blocks",
"of",
"methods",
"that",
"are",
"the",
"same",
"as",
"its",
"parents"
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/CopiedOverriddenMethod.java#L132-L163 |
Pkmmte/PkRSS | pkrss/src/main/java/com/pkmmte/pkrss/Utils.java | Utils.deleteDir | public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
if (!deleteDir(new File(dir, children[i])))
return false;
}
}
return dir.delete();
} | java | public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
if (!deleteDir(new File(dir, children[i])))
return false;
}
}
return dir.delete();
} | [
"public",
"static",
"boolean",
"deleteDir",
"(",
"File",
"dir",
")",
"{",
"if",
"(",
"dir",
"!=",
"null",
"&&",
"dir",
".",
"isDirectory",
"(",
")",
")",
"{",
"String",
"[",
"]",
"children",
"=",
"dir",
".",
"list",
"(",
")",
";",
"for",
"(",
"in... | Deletes the specified directory. Returns true if successful, false if not.
@param dir Directory to delete.
@return {@code true} if successful, {@code false} if otherwise. | [
"Deletes",
"the",
"specified",
"directory",
".",
"Returns",
"true",
"if",
"successful",
"false",
"if",
"not",
"."
] | train | https://github.com/Pkmmte/PkRSS/blob/0bc536d3bad1dade4538616f71c3a8f068eac89a/pkrss/src/main/java/com/pkmmte/pkrss/Utils.java#L20-L29 |
RoaringBitmap/RoaringBitmap | roaringbitmap/src/main/java/org/roaringbitmap/Util.java | Util.resetBitmapRange | public static void resetBitmapRange(long[] bitmap, int start, int end) {
if (start == end) {
return;
}
int firstword = start / 64;
int endword = (end - 1) / 64;
if (firstword == endword) {
bitmap[firstword] &= ~((~0L << start) & (~0L >>> -end));
return;
}
bitmap[firstword] &= ~(~0L << start);
for (int i = firstword + 1; i < endword; i++) {
bitmap[i] = 0;
}
bitmap[endword] &= ~(~0L >>> -end);
} | java | public static void resetBitmapRange(long[] bitmap, int start, int end) {
if (start == end) {
return;
}
int firstword = start / 64;
int endword = (end - 1) / 64;
if (firstword == endword) {
bitmap[firstword] &= ~((~0L << start) & (~0L >>> -end));
return;
}
bitmap[firstword] &= ~(~0L << start);
for (int i = firstword + 1; i < endword; i++) {
bitmap[i] = 0;
}
bitmap[endword] &= ~(~0L >>> -end);
} | [
"public",
"static",
"void",
"resetBitmapRange",
"(",
"long",
"[",
"]",
"bitmap",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"if",
"(",
"start",
"==",
"end",
")",
"{",
"return",
";",
"}",
"int",
"firstword",
"=",
"start",
"/",
"64",
";",
"int... | clear bits at start, start+1,..., end-1
@param bitmap array of words to be modified
@param start first index to be modified (inclusive)
@param end last index to be modified (exclusive) | [
"clear",
"bits",
"at",
"start",
"start",
"+",
"1",
"...",
"end",
"-",
"1"
] | train | https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/Util.java#L423-L440 |
VoltDB/voltdb | src/frontend/org/voltcore/utils/CoreUtils.java | CoreUtils.printAsciiArtLog | public static void printAsciiArtLog(VoltLogger vLogger, String msg, Level level)
{
if (vLogger == null || msg == null || level == Level.OFF) { return; }
// 80 stars in a line
StringBuilder starBuilder = new StringBuilder();
for (int i = 0; i < 80; i++) {
starBuilder.append("*");
}
String stars = starBuilder.toString();
// Wrap the message with 2 lines of stars
switch (level) {
case DEBUG:
vLogger.debug(stars);
vLogger.debug("* " + msg + " *");
vLogger.debug(stars);
break;
case WARN:
vLogger.warn(stars);
vLogger.warn("* " + msg + " *");
vLogger.warn(stars);
break;
case ERROR:
vLogger.error(stars);
vLogger.error("* " + msg + " *");
vLogger.error(stars);
break;
case FATAL:
vLogger.fatal(stars);
vLogger.fatal("* " + msg + " *");
vLogger.fatal(stars);
break;
case INFO:
vLogger.info(stars);
vLogger.info("* " + msg + " *");
vLogger.info(stars);
break;
case TRACE:
vLogger.trace(stars);
vLogger.trace("* " + msg + " *");
vLogger.trace(stars);
break;
default:
break;
}
} | java | public static void printAsciiArtLog(VoltLogger vLogger, String msg, Level level)
{
if (vLogger == null || msg == null || level == Level.OFF) { return; }
// 80 stars in a line
StringBuilder starBuilder = new StringBuilder();
for (int i = 0; i < 80; i++) {
starBuilder.append("*");
}
String stars = starBuilder.toString();
// Wrap the message with 2 lines of stars
switch (level) {
case DEBUG:
vLogger.debug(stars);
vLogger.debug("* " + msg + " *");
vLogger.debug(stars);
break;
case WARN:
vLogger.warn(stars);
vLogger.warn("* " + msg + " *");
vLogger.warn(stars);
break;
case ERROR:
vLogger.error(stars);
vLogger.error("* " + msg + " *");
vLogger.error(stars);
break;
case FATAL:
vLogger.fatal(stars);
vLogger.fatal("* " + msg + " *");
vLogger.fatal(stars);
break;
case INFO:
vLogger.info(stars);
vLogger.info("* " + msg + " *");
vLogger.info(stars);
break;
case TRACE:
vLogger.trace(stars);
vLogger.trace("* " + msg + " *");
vLogger.trace(stars);
break;
default:
break;
}
} | [
"public",
"static",
"void",
"printAsciiArtLog",
"(",
"VoltLogger",
"vLogger",
",",
"String",
"msg",
",",
"Level",
"level",
")",
"{",
"if",
"(",
"vLogger",
"==",
"null",
"||",
"msg",
"==",
"null",
"||",
"level",
"==",
"Level",
".",
"OFF",
")",
"{",
"ret... | Print beautiful logs surrounded by stars. This function handles long lines (wrapping
into multiple lines) as well. Please use only spaces and newline characters for word
separation.
@param vLogger The provided VoltLogger
@param msg Message to be printed out beautifully
@param level Logging level | [
"Print",
"beautiful",
"logs",
"surrounded",
"by",
"stars",
".",
"This",
"function",
"handles",
"long",
"lines",
"(",
"wrapping",
"into",
"multiple",
"lines",
")",
"as",
"well",
".",
"Please",
"use",
"only",
"spaces",
"and",
"newline",
"characters",
"for",
"w... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltcore/utils/CoreUtils.java#L1233-L1279 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/dns/dnspolicy64_binding.java | dnspolicy64_binding.get | public static dnspolicy64_binding get(nitro_service service, String name) throws Exception{
dnspolicy64_binding obj = new dnspolicy64_binding();
obj.set_name(name);
dnspolicy64_binding response = (dnspolicy64_binding) obj.get_resource(service);
return response;
} | java | public static dnspolicy64_binding get(nitro_service service, String name) throws Exception{
dnspolicy64_binding obj = new dnspolicy64_binding();
obj.set_name(name);
dnspolicy64_binding response = (dnspolicy64_binding) obj.get_resource(service);
return response;
} | [
"public",
"static",
"dnspolicy64_binding",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"name",
")",
"throws",
"Exception",
"{",
"dnspolicy64_binding",
"obj",
"=",
"new",
"dnspolicy64_binding",
"(",
")",
";",
"obj",
".",
"set_name",
"(",
"name",
")",
... | Use this API to fetch dnspolicy64_binding resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"dnspolicy64_binding",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/dns/dnspolicy64_binding.java#L103-L108 |
EvidentSolutions/dalesbred | dalesbred/src/main/java/org/dalesbred/Database.java | Database.findOptional | public @NotNull <T> Optional<T> findOptional(@NotNull RowMapper<T> rowMapper, @NotNull @SQL String sql, Object... args) {
return findOptional(rowMapper, SqlQuery.query(sql, args));
} | java | public @NotNull <T> Optional<T> findOptional(@NotNull RowMapper<T> rowMapper, @NotNull @SQL String sql, Object... args) {
return findOptional(rowMapper, SqlQuery.query(sql, args));
} | [
"public",
"@",
"NotNull",
"<",
"T",
">",
"Optional",
"<",
"T",
">",
"findOptional",
"(",
"@",
"NotNull",
"RowMapper",
"<",
"T",
">",
"rowMapper",
",",
"@",
"NotNull",
"@",
"SQL",
"String",
"sql",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"fin... | Find a unique result from database, using given {@link RowMapper} to convert row. Returns empty if
there are no results or if single null result is returned.
@throws NonUniqueResultException if there are multiple result rows | [
"Find",
"a",
"unique",
"result",
"from",
"database",
"using",
"given",
"{",
"@link",
"RowMapper",
"}",
"to",
"convert",
"row",
".",
"Returns",
"empty",
"if",
"there",
"are",
"no",
"results",
"or",
"if",
"single",
"null",
"result",
"is",
"returned",
"."
] | train | https://github.com/EvidentSolutions/dalesbred/blob/713f5b6e152d97e1672ca68b9ff9c7c6c288ceb1/dalesbred/src/main/java/org/dalesbred/Database.java#L382-L384 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/handler/impl/CudaZeroHandler.java | CudaZeroHandler.purgeZeroObject | @Override
public void purgeZeroObject(Long bucketId, Long objectId, AllocationPoint point, boolean copyback) {
forget(point, AllocationStatus.HOST);
flowController.waitTillReleased(point);
// we call for caseless deallocation here
//JCudaDriver.cuCtxSetCurrent(contextPool.getCuContextForDevice(0));
free(point, AllocationStatus.HOST);
point.setAllocationStatus(AllocationStatus.DEALLOCATED);
long reqMem = AllocationUtils.getRequiredMemory(point.getShape()) * -1;
zeroUseCounter.addAndGet(reqMem);
} | java | @Override
public void purgeZeroObject(Long bucketId, Long objectId, AllocationPoint point, boolean copyback) {
forget(point, AllocationStatus.HOST);
flowController.waitTillReleased(point);
// we call for caseless deallocation here
//JCudaDriver.cuCtxSetCurrent(contextPool.getCuContextForDevice(0));
free(point, AllocationStatus.HOST);
point.setAllocationStatus(AllocationStatus.DEALLOCATED);
long reqMem = AllocationUtils.getRequiredMemory(point.getShape()) * -1;
zeroUseCounter.addAndGet(reqMem);
} | [
"@",
"Override",
"public",
"void",
"purgeZeroObject",
"(",
"Long",
"bucketId",
",",
"Long",
"objectId",
",",
"AllocationPoint",
"point",
",",
"boolean",
"copyback",
")",
"{",
"forget",
"(",
"point",
",",
"AllocationStatus",
".",
"HOST",
")",
";",
"flowControll... | This method explicitly removes object from zero-copy memory.
@param bucketId
@param objectId
@param copyback if TRUE, corresponding memory block on JVM side will be updated, if FALSE - memory will be just discarded | [
"This",
"method",
"explicitly",
"removes",
"object",
"from",
"zero",
"-",
"copy",
"memory",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/handler/impl/CudaZeroHandler.java#L1178-L1192 |
berkesa/datatree | src/main/java/io/datatree/Tree.java | Tree.getMeta | public Tree getMeta(boolean createIfNotExists) {
Tree root = getRoot();
if (root.meta == null) {
if (createIfNotExists) {
root.meta = new LinkedHashMap<String, Object>();
} else {
return null;
}
}
return new Tree(root, Config.META, root.meta);
} | java | public Tree getMeta(boolean createIfNotExists) {
Tree root = getRoot();
if (root.meta == null) {
if (createIfNotExists) {
root.meta = new LinkedHashMap<String, Object>();
} else {
return null;
}
}
return new Tree(root, Config.META, root.meta);
} | [
"public",
"Tree",
"getMeta",
"(",
"boolean",
"createIfNotExists",
")",
"{",
"Tree",
"root",
"=",
"getRoot",
"(",
")",
";",
"if",
"(",
"root",
".",
"meta",
"==",
"null",
")",
"{",
"if",
"(",
"createIfNotExists",
")",
"{",
"root",
".",
"meta",
"=",
"ne... | Returns the metadata node (or null, if it doesn't exist and the
"createIfNotExists" parameter is false).
@param createIfNotExists
create metadata node, if it doesn't exist
@return metadata node | [
"Returns",
"the",
"metadata",
"node",
"(",
"or",
"null",
"if",
"it",
"doesn",
"t",
"exist",
"and",
"the",
"createIfNotExists",
"parameter",
"is",
"false",
")",
"."
] | train | https://github.com/berkesa/datatree/blob/79aea9b45c7b46ab28af0a09310bc01c421c6b3a/src/main/java/io/datatree/Tree.java#L511-L521 |
aerogear/aerogear-android-push | library/src/main/java/org/jboss/aerogear/android/unifiedpush/fcm/UnifiedPushConfig.java | UnifiedPushConfig.validateCategories | private static void validateCategories(String... categories) {
for (String category : categories) {
if (!category.matches(FCM_TOPIC_PATTERN)) {
throw new IllegalArgumentException(String.format("%s does not match %s", category, FCM_TOPIC_PATTERN));
}
}
} | java | private static void validateCategories(String... categories) {
for (String category : categories) {
if (!category.matches(FCM_TOPIC_PATTERN)) {
throw new IllegalArgumentException(String.format("%s does not match %s", category, FCM_TOPIC_PATTERN));
}
}
} | [
"private",
"static",
"void",
"validateCategories",
"(",
"String",
"...",
"categories",
")",
"{",
"for",
"(",
"String",
"category",
":",
"categories",
")",
"{",
"if",
"(",
"!",
"category",
".",
"matches",
"(",
"FCM_TOPIC_PATTERN",
")",
")",
"{",
"throw",
"n... | Validates categories against Google's pattern.
@param categories a group of Strings each will be validated.
@throws IllegalArgumentException if a category fails to match [a-zA-Z0-9-_.~%]+ | [
"Validates",
"categories",
"against",
"Google",
"s",
"pattern",
"."
] | train | https://github.com/aerogear/aerogear-android-push/blob/f21f93393a9f4590e9a8d6d045ab9aabca3d211f/library/src/main/java/org/jboss/aerogear/android/unifiedpush/fcm/UnifiedPushConfig.java#L310-L317 |
openengsb/openengsb | components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/operation/InstantiateOperation.java | InstantiateOperation.tryInitiatingObject | private Object tryInitiatingObject(String targetType, String initMethodName, List<Object> fieldObjects)
throws TransformationOperationException {
Class<?> targetClass = loadClassByName(targetType);
try {
if (initMethodName == null) {
return initiateByConstructor(targetClass, fieldObjects);
} else {
return initiateByMethodName(targetClass, initMethodName, fieldObjects);
}
} catch (Exception e) {
String message = "Unable to create the desired object. The instantiate operation will be ignored.";
message = String.format(message, targetType);
getLogger().error(message);
throw new TransformationOperationException(message, e);
}
} | java | private Object tryInitiatingObject(String targetType, String initMethodName, List<Object> fieldObjects)
throws TransformationOperationException {
Class<?> targetClass = loadClassByName(targetType);
try {
if (initMethodName == null) {
return initiateByConstructor(targetClass, fieldObjects);
} else {
return initiateByMethodName(targetClass, initMethodName, fieldObjects);
}
} catch (Exception e) {
String message = "Unable to create the desired object. The instantiate operation will be ignored.";
message = String.format(message, targetType);
getLogger().error(message);
throw new TransformationOperationException(message, e);
}
} | [
"private",
"Object",
"tryInitiatingObject",
"(",
"String",
"targetType",
",",
"String",
"initMethodName",
",",
"List",
"<",
"Object",
">",
"fieldObjects",
")",
"throws",
"TransformationOperationException",
"{",
"Class",
"<",
"?",
">",
"targetClass",
"=",
"loadClassB... | Try to perform the actual initiating of the target class object. Returns the target class object or throws a
TransformationOperationException if something went wrong. | [
"Try",
"to",
"perform",
"the",
"actual",
"initiating",
"of",
"the",
"target",
"class",
"object",
".",
"Returns",
"the",
"target",
"class",
"object",
"or",
"throws",
"a",
"TransformationOperationException",
"if",
"something",
"went",
"wrong",
"."
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/operation/InstantiateOperation.java#L82-L97 |
lemire/JavaFastPFOR | src/main/java/me/lemire/integercompression/Util.java | Util.maxdiffbits | public static int maxdiffbits(int initoffset, int[] i, int pos, int length) {
int mask = 0;
mask |= (i[pos] - initoffset);
for (int k = pos + 1; k < pos + length; ++k) {
mask |= i[k] - i[k - 1];
}
return bits(mask);
} | java | public static int maxdiffbits(int initoffset, int[] i, int pos, int length) {
int mask = 0;
mask |= (i[pos] - initoffset);
for (int k = pos + 1; k < pos + length; ++k) {
mask |= i[k] - i[k - 1];
}
return bits(mask);
} | [
"public",
"static",
"int",
"maxdiffbits",
"(",
"int",
"initoffset",
",",
"int",
"[",
"]",
"i",
",",
"int",
"pos",
",",
"int",
"length",
")",
"{",
"int",
"mask",
"=",
"0",
";",
"mask",
"|=",
"(",
"i",
"[",
"pos",
"]",
"-",
"initoffset",
")",
";",
... | Compute the maximum of the integer logarithms (ceil(log(x+1)) of a the
successive differences (deltas) of a range of value
@param initoffset
initial vallue for the computation of the deltas
@param i
source array
@param pos
starting position
@param length
number of integers to consider
@return integer logarithm | [
"Compute",
"the",
"maximum",
"of",
"the",
"integer",
"logarithms",
"(",
"ceil",
"(",
"log",
"(",
"x",
"+",
"1",
"))",
"of",
"a",
"the",
"successive",
"differences",
"(",
"deltas",
")",
"of",
"a",
"range",
"of",
"value"
] | train | https://github.com/lemire/JavaFastPFOR/blob/ffeea61ab2fdb3854da7b0a557f8d22d674477f4/src/main/java/me/lemire/integercompression/Util.java#L93-L100 |
cdk/cdk | tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java | MolecularFormulaManipulator.getString | public static String getString(IMolecularFormula formula, boolean setOne) {
if (containsElement(formula, formula.getBuilder().newInstance(IElement.class, "C")))
return getString(formula, generateOrderEle_Hill_WithCarbons(), setOne, false);
else
return getString(formula, generateOrderEle_Hill_NoCarbons(), setOne, false);
} | java | public static String getString(IMolecularFormula formula, boolean setOne) {
if (containsElement(formula, formula.getBuilder().newInstance(IElement.class, "C")))
return getString(formula, generateOrderEle_Hill_WithCarbons(), setOne, false);
else
return getString(formula, generateOrderEle_Hill_NoCarbons(), setOne, false);
} | [
"public",
"static",
"String",
"getString",
"(",
"IMolecularFormula",
"formula",
",",
"boolean",
"setOne",
")",
"{",
"if",
"(",
"containsElement",
"(",
"formula",
",",
"formula",
".",
"getBuilder",
"(",
")",
".",
"newInstance",
"(",
"IElement",
".",
"class",
... | Returns the string representation of the molecular formula.
Based on Hill System. The Hill system is a system of writing
chemical formulas such that the number of carbon atoms in a
molecule is indicated first, the number of hydrogen atoms next,
and then the number of all other chemical elements subsequently,
in alphabetical order. When the formula contains no carbon, all
the elements, including hydrogen, are listed alphabetically.
@param formula The IMolecularFormula Object
@param setOne True, when must be set the value 1 for elements with
one atom
@return A String containing the molecular formula
@see #getHTML(IMolecularFormula) | [
"Returns",
"the",
"string",
"representation",
"of",
"the",
"molecular",
"formula",
".",
"Based",
"on",
"Hill",
"System",
".",
"The",
"Hill",
"system",
"is",
"a",
"system",
"of",
"writing",
"chemical",
"formulas",
"such",
"that",
"the",
"number",
"of",
"carbo... | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java#L363-L369 |
joniles/mpxj | src/main/java/net/sf/mpxj/Task.java | Task.setOutlineCode | public void setOutlineCode(int index, String value)
{
set(selectField(TaskFieldLists.CUSTOM_OUTLINE_CODE, index), value);
} | java | public void setOutlineCode(int index, String value)
{
set(selectField(TaskFieldLists.CUSTOM_OUTLINE_CODE, index), value);
} | [
"public",
"void",
"setOutlineCode",
"(",
"int",
"index",
",",
"String",
"value",
")",
"{",
"set",
"(",
"selectField",
"(",
"TaskFieldLists",
".",
"CUSTOM_OUTLINE_CODE",
",",
"index",
")",
",",
"value",
")",
";",
"}"
] | Set an outline code value.
@param index outline code index (1-10)
@param value outline code value | [
"Set",
"an",
"outline",
"code",
"value",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/Task.java#L2617-L2620 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/trees/EnglishGrammaticalRelations.java | EnglishGrammaticalRelations.getPrep | public static GrammaticalRelation getPrep(String prepositionString) {
GrammaticalRelation result = preps.get(prepositionString);
if (result == null) {
synchronized(preps) {
result = preps.get(prepositionString);
if (result == null) {
result = new GrammaticalRelation(Language.English, "prep", "prep_collapsed", null, PREPOSITIONAL_MODIFIER, prepositionString);
preps.put(prepositionString, result);
threadSafeAddRelation(result);
}
}
}
return result;
} | java | public static GrammaticalRelation getPrep(String prepositionString) {
GrammaticalRelation result = preps.get(prepositionString);
if (result == null) {
synchronized(preps) {
result = preps.get(prepositionString);
if (result == null) {
result = new GrammaticalRelation(Language.English, "prep", "prep_collapsed", null, PREPOSITIONAL_MODIFIER, prepositionString);
preps.put(prepositionString, result);
threadSafeAddRelation(result);
}
}
}
return result;
} | [
"public",
"static",
"GrammaticalRelation",
"getPrep",
"(",
"String",
"prepositionString",
")",
"{",
"GrammaticalRelation",
"result",
"=",
"preps",
".",
"get",
"(",
"prepositionString",
")",
";",
"if",
"(",
"result",
"==",
"null",
")",
"{",
"synchronized",
"(",
... | The "prep" grammatical relation. Used to collapse prepositions.<p>
They will be turned into prep_word, where "word" is a preposition
NOTE: Because these relations lack associated GrammaticalRelationAnnotations,
they cannot be arcs of a TreeGraphNode.
@param prepositionString The preposition to make a GrammaticalRelation out of
@return A grammatical relation for this preposition | [
"The",
"prep",
"grammatical",
"relation",
".",
"Used",
"to",
"collapse",
"prepositions",
".",
"<p",
">",
"They",
"will",
"be",
"turned",
"into",
"prep_word",
"where",
"word",
"is",
"a",
"preposition"
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/trees/EnglishGrammaticalRelations.java#L1628-L1641 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/time/DateUtils.java | DateUtils.setMinutes | public static Date setMinutes(final Date date, final int amount) {
return set(date, Calendar.MINUTE, amount);
} | java | public static Date setMinutes(final Date date, final int amount) {
return set(date, Calendar.MINUTE, amount);
} | [
"public",
"static",
"Date",
"setMinutes",
"(",
"final",
"Date",
"date",
",",
"final",
"int",
"amount",
")",
"{",
"return",
"set",
"(",
"date",
",",
"Calendar",
".",
"MINUTE",
",",
"amount",
")",
";",
"}"
] | Sets the minute field to a date returning a new object.
The original {@code Date} is unchanged.
@param date the date, not null
@param amount the amount to set
@return a new {@code Date} set with the specified value
@throws IllegalArgumentException if the date is null
@since 2.4 | [
"Sets",
"the",
"minute",
"field",
"to",
"a",
"date",
"returning",
"a",
"new",
"object",
".",
"The",
"original",
"{",
"@code",
"Date",
"}",
"is",
"unchanged",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L601-L603 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/fs/ChecksumFileSystem.java | ChecksumFileSystem.setReplication | public boolean setReplication(Path src, short replication) throws IOException {
boolean value = fs.setReplication(src, replication);
if (!value)
return false;
Path checkFile = getChecksumFile(src);
if (exists(checkFile))
fs.setReplication(checkFile, replication);
return true;
} | java | public boolean setReplication(Path src, short replication) throws IOException {
boolean value = fs.setReplication(src, replication);
if (!value)
return false;
Path checkFile = getChecksumFile(src);
if (exists(checkFile))
fs.setReplication(checkFile, replication);
return true;
} | [
"public",
"boolean",
"setReplication",
"(",
"Path",
"src",
",",
"short",
"replication",
")",
"throws",
"IOException",
"{",
"boolean",
"value",
"=",
"fs",
".",
"setReplication",
"(",
"src",
",",
"replication",
")",
";",
"if",
"(",
"!",
"value",
")",
"return... | Set replication for an existing file.
Implement the abstract <tt>setReplication</tt> of <tt>FileSystem</tt>
@param src file name
@param replication new replication
@throws IOException
@return true if successful;
false if file does not exist or is a directory | [
"Set",
"replication",
"for",
"an",
"existing",
"file",
".",
"Implement",
"the",
"abstract",
"<tt",
">",
"setReplication<",
"/",
"tt",
">",
"of",
"<tt",
">",
"FileSystem<",
"/",
"tt",
">"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/ChecksumFileSystem.java#L431-L441 |
SteelBridgeLabs/neo4j-gremlin-bolt | src/main/java/com/steelbridgelabs/oss/neo4j/structure/Neo4JVertex.java | Neo4JVertex.matchStatement | public String matchStatement(String alias, String idParameterName) {
Objects.requireNonNull(alias, "alias cannot be null");
Objects.requireNonNull(idParameterName, "idParameterName cannot be null");
// create statement
return "MATCH " + matchPattern(alias) + " WHERE " + matchPredicate(alias, idParameterName);
} | java | public String matchStatement(String alias, String idParameterName) {
Objects.requireNonNull(alias, "alias cannot be null");
Objects.requireNonNull(idParameterName, "idParameterName cannot be null");
// create statement
return "MATCH " + matchPattern(alias) + " WHERE " + matchPredicate(alias, idParameterName);
} | [
"public",
"String",
"matchStatement",
"(",
"String",
"alias",
",",
"String",
"idParameterName",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"alias",
",",
"\"alias cannot be null\"",
")",
";",
"Objects",
".",
"requireNonNull",
"(",
"idParameterName",
",",
"\"i... | Generates a Cypher MATCH statement for the vertex, example:
<p>
MATCH (alias) WHERE alias.id = {id} AND (alias:Label1 OR alias:Label2)
</p>
@param alias The node alias.
@param idParameterName The name of the parameter that contains the vertex id.
@return the Cypher MATCH predicate or <code>null</code> if not required to MATCH the vertex. | [
"Generates",
"a",
"Cypher",
"MATCH",
"statement",
"for",
"the",
"vertex",
"example",
":",
"<p",
">",
"MATCH",
"(",
"alias",
")",
"WHERE",
"alias",
".",
"id",
"=",
"{",
"id",
"}",
"AND",
"(",
"alias",
":",
"Label1",
"OR",
"alias",
":",
"Label2",
")",
... | train | https://github.com/SteelBridgeLabs/neo4j-gremlin-bolt/blob/df3ab429e0c83affae6cd43d41edd90de80c032e/src/main/java/com/steelbridgelabs/oss/neo4j/structure/Neo4JVertex.java#L399-L404 |
looly/hutool | hutool-poi/src/main/java/cn/hutool/poi/excel/cell/CellUtil.java | CellUtil.mergingCells | public static int mergingCells(Sheet sheet, int firstRow, int lastRow, int firstColumn, int lastColumn, CellStyle cellStyle) {
final CellRangeAddress cellRangeAddress = new CellRangeAddress(//
firstRow, // first row (0-based)
lastRow, // last row (0-based)
firstColumn, // first column (0-based)
lastColumn // last column (0-based)
);
if (null != cellStyle) {
RegionUtil.setBorderTop(cellStyle.getBorderTopEnum(), cellRangeAddress, sheet);
RegionUtil.setBorderRight(cellStyle.getBorderRightEnum(), cellRangeAddress, sheet);
RegionUtil.setBorderBottom(cellStyle.getBorderBottomEnum(), cellRangeAddress, sheet);
RegionUtil.setBorderLeft(cellStyle.getBorderLeftEnum(), cellRangeAddress, sheet);
}
return sheet.addMergedRegion(cellRangeAddress);
} | java | public static int mergingCells(Sheet sheet, int firstRow, int lastRow, int firstColumn, int lastColumn, CellStyle cellStyle) {
final CellRangeAddress cellRangeAddress = new CellRangeAddress(//
firstRow, // first row (0-based)
lastRow, // last row (0-based)
firstColumn, // first column (0-based)
lastColumn // last column (0-based)
);
if (null != cellStyle) {
RegionUtil.setBorderTop(cellStyle.getBorderTopEnum(), cellRangeAddress, sheet);
RegionUtil.setBorderRight(cellStyle.getBorderRightEnum(), cellRangeAddress, sheet);
RegionUtil.setBorderBottom(cellStyle.getBorderBottomEnum(), cellRangeAddress, sheet);
RegionUtil.setBorderLeft(cellStyle.getBorderLeftEnum(), cellRangeAddress, sheet);
}
return sheet.addMergedRegion(cellRangeAddress);
} | [
"public",
"static",
"int",
"mergingCells",
"(",
"Sheet",
"sheet",
",",
"int",
"firstRow",
",",
"int",
"lastRow",
",",
"int",
"firstColumn",
",",
"int",
"lastColumn",
",",
"CellStyle",
"cellStyle",
")",
"{",
"final",
"CellRangeAddress",
"cellRangeAddress",
"=",
... | 合并单元格,可以根据设置的值来合并行和列
@param sheet 表对象
@param firstRow 起始行,0开始
@param lastRow 结束行,0开始
@param firstColumn 起始列,0开始
@param lastColumn 结束列,0开始
@param cellStyle 单元格样式,只提取边框样式
@return 合并后的单元格号 | [
"合并单元格,可以根据设置的值来合并行和列"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-poi/src/main/java/cn/hutool/poi/excel/cell/CellUtil.java#L204-L219 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.