repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 188 | func_name stringlengths 7 127 | whole_func_string stringlengths 77 3.91k | language stringclasses 1
value | func_code_string stringlengths 77 3.91k | func_code_tokens listlengths 20 745 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 477 | split_name stringclasses 1
value | func_code_url stringlengths 111 288 |
|---|---|---|---|---|---|---|---|---|---|---|
code4everything/util | src/main/java/com/zhazhapan/util/FileExecutor.java | FileExecutor.splitFile | public static void splitFile(File file, long[] splitPoints, String storageFolder) throws IOException {
splitPoints = ArrayUtils.concatArrays(new long[]{0}, splitPoints, new long[]{file.length()});
String[] fileName = file.getName().split("\\.", 2);
storageFolder += ValueConsts.SEPARATOR;
logger.info("start to split file '" + file.getAbsolutePath() + "'");
for (int i = 0; i < splitPoints.length - 1; i++) {
long start = splitPoints[i], end = splitPoints[i + 1];
long length = end - start;
String filePath = storageFolder + fileName[0] + "_" + (i + 1) + "." + fileName[1];
createNewFile(filePath);
while (length > Integer.MAX_VALUE) {
saveFile(filePath, readFile(file, start, Integer.MAX_VALUE), true);
start += Integer.MAX_VALUE;
length -= Integer.MAX_VALUE;
}
if (length > 0) {
saveFile(filePath, readFile(file, start, (int) length), true);
}
}
} | java | public static void splitFile(File file, long[] splitPoints, String storageFolder) throws IOException {
splitPoints = ArrayUtils.concatArrays(new long[]{0}, splitPoints, new long[]{file.length()});
String[] fileName = file.getName().split("\\.", 2);
storageFolder += ValueConsts.SEPARATOR;
logger.info("start to split file '" + file.getAbsolutePath() + "'");
for (int i = 0; i < splitPoints.length - 1; i++) {
long start = splitPoints[i], end = splitPoints[i + 1];
long length = end - start;
String filePath = storageFolder + fileName[0] + "_" + (i + 1) + "." + fileName[1];
createNewFile(filePath);
while (length > Integer.MAX_VALUE) {
saveFile(filePath, readFile(file, start, Integer.MAX_VALUE), true);
start += Integer.MAX_VALUE;
length -= Integer.MAX_VALUE;
}
if (length > 0) {
saveFile(filePath, readFile(file, start, (int) length), true);
}
}
} | [
"public",
"static",
"void",
"splitFile",
"(",
"File",
"file",
",",
"long",
"[",
"]",
"splitPoints",
",",
"String",
"storageFolder",
")",
"throws",
"IOException",
"{",
"splitPoints",
"=",
"ArrayUtils",
".",
"concatArrays",
"(",
"new",
"long",
"[",
"]",
"{",
... | 拆分文件
@param file 文件
@param splitPoints 拆分点数组(函数将根据拆分点来分割文件)
@param storageFolder 保存路径
@throws IOException 异常 | [
"拆分文件"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/FileExecutor.java#L566-L585 |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java | DebugUtil.printDebug | public static void printDebug(final Enumeration pEnumeration, final String pMethodName, final PrintStream pPrintStream) {
if (pPrintStream == null) {
System.err.println(PRINTSTREAM_IS_NULL_ERROR_MESSAGE);
return;
}
if (pEnumeration == null) {
pPrintStream.println(ENUMERATION_IS_NULL_ERROR_MESSAGE);
return;
}
while (pEnumeration.hasMoreElements()) {
printDebug(pEnumeration.nextElement(), pMethodName, pPrintStream);
}
} | java | public static void printDebug(final Enumeration pEnumeration, final String pMethodName, final PrintStream pPrintStream) {
if (pPrintStream == null) {
System.err.println(PRINTSTREAM_IS_NULL_ERROR_MESSAGE);
return;
}
if (pEnumeration == null) {
pPrintStream.println(ENUMERATION_IS_NULL_ERROR_MESSAGE);
return;
}
while (pEnumeration.hasMoreElements()) {
printDebug(pEnumeration.nextElement(), pMethodName, pPrintStream);
}
} | [
"public",
"static",
"void",
"printDebug",
"(",
"final",
"Enumeration",
"pEnumeration",
",",
"final",
"String",
"pMethodName",
",",
"final",
"PrintStream",
"pPrintStream",
")",
"{",
"if",
"(",
"pPrintStream",
"==",
"null",
")",
"{",
"System",
".",
"err",
".",
... | Invokes a given method of every element in a {@code java.util.Enumeration} and prints the results to a {@code java.io.PrintStream}.
The method to be invoked must have no formal parameters.
<p>
If an exception is throwed during the method invocation, the element's {@code toString()} method is called.
For bulk data types, recursive invocations and invocations of other methods in this class, are used.
<p>
@param pEnumeration the {@code java.util.Enumeration} to be printed.
@param pMethodName a {@code java.lang.String} holding the name of the method to be invoked on each collection element.
@param pPrintStream the {@code java.io.PrintStream} for flushing the results.
@see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/util/Enumeration.html">{@code java.util.Enumeration}</a> | [
"Invokes",
"a",
"given",
"method",
"of",
"every",
"element",
"in",
"a",
"{"
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java#L425-L438 |
h2oai/h2o-3 | h2o-genmodel/src/main/java/hex/genmodel/easy/EasyPredictModelWrapper.java | EasyPredictModelWrapper.predictRegression | public RegressionModelPrediction predictRegression(RowData data, double offset) throws PredictException {
double[] preds = preamble(ModelCategory.Regression, data, offset);
RegressionModelPrediction p = new RegressionModelPrediction();
if (enableLeafAssignment) { // only get leaf node assignment if enabled
SharedTreeMojoModel.LeafNodeAssignments assignments = leafNodeAssignmentExtended(data);
p.leafNodeAssignments = assignments._paths;
p.leafNodeAssignmentIds = assignments._nodeIds;
}
p.value = preds[0];
if (enableStagedProbabilities) {
double[] rawData = nanArray(m.nfeatures());
rawData = fillRawData(data, rawData);
p.stageProbabilities = ((SharedTreeMojoModel) m).scoreStagedPredictions(rawData, preds.length);
}
if (enableContributions) {
double[] rawData = nanArray(m.nfeatures());
rawData = fillRawData(data, rawData);
p.contributions = predictContributions.calculateContributions(rawData);
}
return p;
} | java | public RegressionModelPrediction predictRegression(RowData data, double offset) throws PredictException {
double[] preds = preamble(ModelCategory.Regression, data, offset);
RegressionModelPrediction p = new RegressionModelPrediction();
if (enableLeafAssignment) { // only get leaf node assignment if enabled
SharedTreeMojoModel.LeafNodeAssignments assignments = leafNodeAssignmentExtended(data);
p.leafNodeAssignments = assignments._paths;
p.leafNodeAssignmentIds = assignments._nodeIds;
}
p.value = preds[0];
if (enableStagedProbabilities) {
double[] rawData = nanArray(m.nfeatures());
rawData = fillRawData(data, rawData);
p.stageProbabilities = ((SharedTreeMojoModel) m).scoreStagedPredictions(rawData, preds.length);
}
if (enableContributions) {
double[] rawData = nanArray(m.nfeatures());
rawData = fillRawData(data, rawData);
p.contributions = predictContributions.calculateContributions(rawData);
}
return p;
} | [
"public",
"RegressionModelPrediction",
"predictRegression",
"(",
"RowData",
"data",
",",
"double",
"offset",
")",
"throws",
"PredictException",
"{",
"double",
"[",
"]",
"preds",
"=",
"preamble",
"(",
"ModelCategory",
".",
"Regression",
",",
"data",
",",
"offset",
... | Make a prediction on a new data point using a Regression model.
@param data A new data point.
@param offset Prediction offset
@return The prediction.
@throws PredictException | [
"Make",
"a",
"prediction",
"on",
"a",
"new",
"data",
"point",
"using",
"a",
"Regression",
"model",
"."
] | train | https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-genmodel/src/main/java/hex/genmodel/easy/EasyPredictModelWrapper.java#L731-L752 |
algolia/algoliasearch-client-java | src/main/java/com/algolia/search/saas/Index.java | Index.clearSynonyms | public JSONObject clearSynonyms(boolean forwardToReplicas, RequestOptions requestOptions) throws AlgoliaException {
return client.postRequest("/1/indexes/" + encodedIndexName + "/synonyms/clear?forwardToReplicas=" + forwardToReplicas, "", true, false, requestOptions);
} | java | public JSONObject clearSynonyms(boolean forwardToReplicas, RequestOptions requestOptions) throws AlgoliaException {
return client.postRequest("/1/indexes/" + encodedIndexName + "/synonyms/clear?forwardToReplicas=" + forwardToReplicas, "", true, false, requestOptions);
} | [
"public",
"JSONObject",
"clearSynonyms",
"(",
"boolean",
"forwardToReplicas",
",",
"RequestOptions",
"requestOptions",
")",
"throws",
"AlgoliaException",
"{",
"return",
"client",
".",
"postRequest",
"(",
"\"/1/indexes/\"",
"+",
"encodedIndexName",
"+",
"\"/synonyms/clear?... | Delete all synonym set
@param forwardToReplicas Forward the operation to the replica indices
@param requestOptions Options to pass to this request | [
"Delete",
"all",
"synonym",
"set"
] | train | https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Index.java#L1544-L1546 |
relayrides/pushy | pushy/src/main/java/com/turo/pushy/apns/server/BaseHttp2ServerBuilder.java | BaseHttp2ServerBuilder.setServerCredentials | public BaseHttp2ServerBuilder setServerCredentials(final X509Certificate[] certificates, final PrivateKey privateKey, final String privateKeyPassword) {
this.certificateChain = certificates;
this.privateKey = privateKey;
this.certificateChainPemFile = null;
this.privateKeyPkcs8File = null;
this.certificateChainInputStream = null;
this.privateKeyPkcs8InputStream = null;
this.privateKeyPassword = privateKeyPassword;
return this;
} | java | public BaseHttp2ServerBuilder setServerCredentials(final X509Certificate[] certificates, final PrivateKey privateKey, final String privateKeyPassword) {
this.certificateChain = certificates;
this.privateKey = privateKey;
this.certificateChainPemFile = null;
this.privateKeyPkcs8File = null;
this.certificateChainInputStream = null;
this.privateKeyPkcs8InputStream = null;
this.privateKeyPassword = privateKeyPassword;
return this;
} | [
"public",
"BaseHttp2ServerBuilder",
"setServerCredentials",
"(",
"final",
"X509Certificate",
"[",
"]",
"certificates",
",",
"final",
"PrivateKey",
"privateKey",
",",
"final",
"String",
"privateKeyPassword",
")",
"{",
"this",
".",
"certificateChain",
"=",
"certificates",... | <p>Sets the credentials for the server under construction.</p>
@param certificates a certificate chain including the server's own certificate
@param privateKey the private key for the server's certificate
@param privateKeyPassword the password for the given private key, or {@code null} if the key is not
password-protected
@return a reference to this builder
@since 0.8 | [
"<p",
">",
"Sets",
"the",
"credentials",
"for",
"the",
"server",
"under",
"construction",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/relayrides/pushy/blob/1f6f9a0e07d785c815d74c2320a8d87c80231d36/pushy/src/main/java/com/turo/pushy/apns/server/BaseHttp2ServerBuilder.java#L139-L152 |
navnorth/LRJavaLib | src/com/navnorth/learningregistry/LRActivity.java | LRActivity.addObject | public boolean addObject(String objectType, String id, String content)
{
Map<String, Object> container = new HashMap<String, Object>();
if (objectType != null)
{
container.put("objectType", objectType);
}
if (id != null)
{
container.put("id", id);
}
if (content != null)
{
container.put("content", content);
}
return addChild("object", container, null);
} | java | public boolean addObject(String objectType, String id, String content)
{
Map<String, Object> container = new HashMap<String, Object>();
if (objectType != null)
{
container.put("objectType", objectType);
}
if (id != null)
{
container.put("id", id);
}
if (content != null)
{
container.put("content", content);
}
return addChild("object", container, null);
} | [
"public",
"boolean",
"addObject",
"(",
"String",
"objectType",
",",
"String",
"id",
",",
"String",
"content",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"container",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"if"... | Add an object to this activity
@param objectType The type of object (required)
@param id Id of the object
@param content String describing the content of the object
@return True if added, false if not | [
"Add",
"an",
"object",
"to",
"this",
"activity"
] | train | https://github.com/navnorth/LRJavaLib/blob/27af28b9f80d772273592414e7d0dccffaac09e1/src/com/navnorth/learningregistry/LRActivity.java#L375-L393 |
jmurty/java-xmlbuilder | src/main/java/com/jamesmurty/utils/BaseXMLBuilder.java | BaseXMLBuilder.xpathFindImpl | protected Node xpathFindImpl(String xpath, NamespaceContext nsContext)
throws XPathExpressionException
{
Node foundNode = (Node) this.xpathQuery(xpath, XPathConstants.NODE, nsContext);
if (foundNode == null || foundNode.getNodeType() != Node.ELEMENT_NODE) {
throw new XPathExpressionException("XPath expression \""
+ xpath + "\" does not resolve to an Element in context "
+ this.xmlNode + ": " + foundNode);
}
return foundNode;
} | java | protected Node xpathFindImpl(String xpath, NamespaceContext nsContext)
throws XPathExpressionException
{
Node foundNode = (Node) this.xpathQuery(xpath, XPathConstants.NODE, nsContext);
if (foundNode == null || foundNode.getNodeType() != Node.ELEMENT_NODE) {
throw new XPathExpressionException("XPath expression \""
+ xpath + "\" does not resolve to an Element in context "
+ this.xmlNode + ": " + foundNode);
}
return foundNode;
} | [
"protected",
"Node",
"xpathFindImpl",
"(",
"String",
"xpath",
",",
"NamespaceContext",
"nsContext",
")",
"throws",
"XPathExpressionException",
"{",
"Node",
"foundNode",
"=",
"(",
"Node",
")",
"this",
".",
"xpathQuery",
"(",
"xpath",
",",
"XPathConstants",
".",
"... | Find the first element in the builder's DOM matching the given
XPath expression, where the expression may include namespaces if
a {@link NamespaceContext} is provided.
@param xpath
An XPath expression that *must* resolve to an existing Element within
the document object model.
@param nsContext
a mapping of prefixes to namespace URIs that allows the XPath expression
to use namespaces.
@return
the first Element that matches the XPath expression.
@throws XPathExpressionException
If the XPath is invalid, or if does not resolve to at least one
{@link Node#ELEMENT_NODE}. | [
"Find",
"the",
"first",
"element",
"in",
"the",
"builder",
"s",
"DOM",
"matching",
"the",
"given",
"XPath",
"expression",
"where",
"the",
"expression",
"may",
"include",
"namespaces",
"if",
"a",
"{",
"@link",
"NamespaceContext",
"}",
"is",
"provided",
"."
] | train | https://github.com/jmurty/java-xmlbuilder/blob/7c224b8e8ed79808509322cb141dab5a88dd3cec/src/main/java/com/jamesmurty/utils/BaseXMLBuilder.java#L500-L510 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.restoreStorageAccountAsync | public ServiceFuture<StorageBundle> restoreStorageAccountAsync(String vaultBaseUrl, byte[] storageBundleBackup, final ServiceCallback<StorageBundle> serviceCallback) {
return ServiceFuture.fromResponse(restoreStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageBundleBackup), serviceCallback);
} | java | public ServiceFuture<StorageBundle> restoreStorageAccountAsync(String vaultBaseUrl, byte[] storageBundleBackup, final ServiceCallback<StorageBundle> serviceCallback) {
return ServiceFuture.fromResponse(restoreStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageBundleBackup), serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"StorageBundle",
">",
"restoreStorageAccountAsync",
"(",
"String",
"vaultBaseUrl",
",",
"byte",
"[",
"]",
"storageBundleBackup",
",",
"final",
"ServiceCallback",
"<",
"StorageBundle",
">",
"serviceCallback",
")",
"{",
"return",
"Service... | Restores a backed up storage account to a vault.
Restores a backed up storage account to a vault. This operation requires the storage/restore permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param storageBundleBackup The backup blob associated with a storage account.
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Restores",
"a",
"backed",
"up",
"storage",
"account",
"to",
"a",
"vault",
".",
"Restores",
"a",
"backed",
"up",
"storage",
"account",
"to",
"a",
"vault",
".",
"This",
"operation",
"requires",
"the",
"storage",
"/",
"restore",
"permission",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L9622-L9624 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/GitLabApiClient.java | GitLabApiClient.setupIgnoreCertificateErrors | private boolean setupIgnoreCertificateErrors() {
// Create a TrustManager that trusts all certificates
TrustManager[] trustAllCerts = new TrustManager[] { new X509ExtendedTrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
}
}};
// Ignore differences between given hostname and certificate hostname
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new SecureRandom());
openSslContext = sslContext;
openHostnameVerifier = hostnameVerifier;
} catch (GeneralSecurityException ex) {
openSslContext = null;
openHostnameVerifier = null;
return (false);
}
return (true);
} | java | private boolean setupIgnoreCertificateErrors() {
// Create a TrustManager that trusts all certificates
TrustManager[] trustAllCerts = new TrustManager[] { new X509ExtendedTrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
}
}};
// Ignore differences between given hostname and certificate hostname
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new SecureRandom());
openSslContext = sslContext;
openHostnameVerifier = hostnameVerifier;
} catch (GeneralSecurityException ex) {
openSslContext = null;
openHostnameVerifier = null;
return (false);
}
return (true);
} | [
"private",
"boolean",
"setupIgnoreCertificateErrors",
"(",
")",
"{",
"// Create a TrustManager that trusts all certificates",
"TrustManager",
"[",
"]",
"trustAllCerts",
"=",
"new",
"TrustManager",
"[",
"]",
"{",
"new",
"X509ExtendedTrustManager",
"(",
")",
"{",
"@",
"Ov... | Sets up Jersey client to ignore certificate errors.
@return true if successful at setting up to ignore certificate errors, otherwise returns false. | [
"Sets",
"up",
"Jersey",
"client",
"to",
"ignore",
"certificate",
"errors",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/GitLabApiClient.java#L808-L861 |
zaproxy/zaproxy | src/org/zaproxy/zap/utils/ApiUtils.java | ApiUtils.getContextByParamId | public static Context getContextByParamId(JSONObject params, String contextIdParamName)
throws ApiException {
int contextId = getIntParam(params, contextIdParamName);
Context context = Model.getSingleton().getSession().getContext(contextId);
if (context == null) {
throw new ApiException(Type.CONTEXT_NOT_FOUND, contextIdParamName);
}
return context;
} | java | public static Context getContextByParamId(JSONObject params, String contextIdParamName)
throws ApiException {
int contextId = getIntParam(params, contextIdParamName);
Context context = Model.getSingleton().getSession().getContext(contextId);
if (context == null) {
throw new ApiException(Type.CONTEXT_NOT_FOUND, contextIdParamName);
}
return context;
} | [
"public",
"static",
"Context",
"getContextByParamId",
"(",
"JSONObject",
"params",
",",
"String",
"contextIdParamName",
")",
"throws",
"ApiException",
"{",
"int",
"contextId",
"=",
"getIntParam",
"(",
"params",
",",
"contextIdParamName",
")",
";",
"Context",
"contex... | Gets the {@link Context} whose id is provided as a parameter with the given name. Throws an
exception accordingly if not found or valid.
@param params the params
@param contextIdParamName the context id param name
@return the context
@throws ApiException the api exception | [
"Gets",
"the",
"{",
"@link",
"Context",
"}",
"whose",
"id",
"is",
"provided",
"as",
"a",
"parameter",
"with",
"the",
"given",
"name",
".",
"Throws",
"an",
"exception",
"accordingly",
"if",
"not",
"found",
"or",
"valid",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/utils/ApiUtils.java#L149-L157 |
alibaba/jstorm | jstorm-core/src/main/java/com/alibaba/jstorm/metric/MetricUtils.java | MetricUtils.metricName | public static String metricName(String type, String topologyId, String componentId, int taskId, String streamId, String group, String name) {
return concat(type, topologyId, componentId, taskId, streamId, group, name);
} | java | public static String metricName(String type, String topologyId, String componentId, int taskId, String streamId, String group, String name) {
return concat(type, topologyId, componentId, taskId, streamId, group, name);
} | [
"public",
"static",
"String",
"metricName",
"(",
"String",
"type",
",",
"String",
"topologyId",
",",
"String",
"componentId",
",",
"int",
"taskId",
",",
"String",
"streamId",
",",
"String",
"group",
",",
"String",
"name",
")",
"{",
"return",
"concat",
"(",
... | a metric name composites of: type@topologyId@componentId@taskId@streamId@group@name for non-worker metrics
OR type@topologyId@host@port@group@name for worker metrics | [
"a",
"metric",
"name",
"composites",
"of",
":",
"type"
] | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/metric/MetricUtils.java#L93-L95 |
glyptodon/guacamole-client | extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/user/ModeledUser.java | ModeledUser.putRestrictedAttributes | private void putRestrictedAttributes(Map<String, String> attributes) {
// Set disabled attribute
attributes.put(DISABLED_ATTRIBUTE_NAME, getModel().isDisabled() ? "true" : null);
// Set password expired attribute
attributes.put(EXPIRED_ATTRIBUTE_NAME, getModel().isExpired() ? "true" : null);
// Set access window start time
attributes.put(ACCESS_WINDOW_START_ATTRIBUTE_NAME, TimeField.format(getModel().getAccessWindowStart()));
// Set access window end time
attributes.put(ACCESS_WINDOW_END_ATTRIBUTE_NAME, TimeField.format(getModel().getAccessWindowEnd()));
// Set account validity start date
attributes.put(VALID_FROM_ATTRIBUTE_NAME, DateField.format(getModel().getValidFrom()));
// Set account validity end date
attributes.put(VALID_UNTIL_ATTRIBUTE_NAME, DateField.format(getModel().getValidUntil()));
// Set timezone attribute
attributes.put(TIMEZONE_ATTRIBUTE_NAME, getModel().getTimeZone());
} | java | private void putRestrictedAttributes(Map<String, String> attributes) {
// Set disabled attribute
attributes.put(DISABLED_ATTRIBUTE_NAME, getModel().isDisabled() ? "true" : null);
// Set password expired attribute
attributes.put(EXPIRED_ATTRIBUTE_NAME, getModel().isExpired() ? "true" : null);
// Set access window start time
attributes.put(ACCESS_WINDOW_START_ATTRIBUTE_NAME, TimeField.format(getModel().getAccessWindowStart()));
// Set access window end time
attributes.put(ACCESS_WINDOW_END_ATTRIBUTE_NAME, TimeField.format(getModel().getAccessWindowEnd()));
// Set account validity start date
attributes.put(VALID_FROM_ATTRIBUTE_NAME, DateField.format(getModel().getValidFrom()));
// Set account validity end date
attributes.put(VALID_UNTIL_ATTRIBUTE_NAME, DateField.format(getModel().getValidUntil()));
// Set timezone attribute
attributes.put(TIMEZONE_ATTRIBUTE_NAME, getModel().getTimeZone());
} | [
"private",
"void",
"putRestrictedAttributes",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"attributes",
")",
"{",
"// Set disabled attribute",
"attributes",
".",
"put",
"(",
"DISABLED_ATTRIBUTE_NAME",
",",
"getModel",
"(",
")",
".",
"isDisabled",
"(",
")",
"?... | Stores all restricted (privileged) attributes within the given Map,
pulling the values of those attributes from the underlying user model.
If no value is yet defined for an attribute, that attribute will be set
to null.
@param attributes
The Map to store all restricted attributes within. | [
"Stores",
"all",
"restricted",
"(",
"privileged",
")",
"attributes",
"within",
"the",
"given",
"Map",
"pulling",
"the",
"values",
"of",
"those",
"attributes",
"from",
"the",
"underlying",
"user",
"model",
".",
"If",
"no",
"value",
"is",
"yet",
"defined",
"fo... | train | https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/user/ModeledUser.java#L304-L327 |
requery/requery | requery/src/main/java/io/requery/sql/SchemaModifier.java | SchemaModifier.createTables | public void createTables(Connection connection, TableCreationMode mode, boolean createIndexes) {
ArrayList<Type<?>> sorted = sortTypes();
try (Statement statement = connection.createStatement()) {
if (mode == TableCreationMode.DROP_CREATE) {
ArrayList<Type<?>> reversed = sortTypes();
Collections.reverse(reversed);
executeDropStatements(statement, reversed);
}
for (Type<?> type : sorted) {
String sql = tableCreateStatement(type, mode);
statementListeners.beforeExecuteUpdate(statement, sql, null);
statement.execute(sql);
statementListeners.afterExecuteUpdate(statement, 0);
}
if (createIndexes) {
for (Type<?> type : sorted) {
createIndexes(connection, mode, type);
}
}
} catch (SQLException e) {
throw new TableModificationException(e);
}
} | java | public void createTables(Connection connection, TableCreationMode mode, boolean createIndexes) {
ArrayList<Type<?>> sorted = sortTypes();
try (Statement statement = connection.createStatement()) {
if (mode == TableCreationMode.DROP_CREATE) {
ArrayList<Type<?>> reversed = sortTypes();
Collections.reverse(reversed);
executeDropStatements(statement, reversed);
}
for (Type<?> type : sorted) {
String sql = tableCreateStatement(type, mode);
statementListeners.beforeExecuteUpdate(statement, sql, null);
statement.execute(sql);
statementListeners.afterExecuteUpdate(statement, 0);
}
if (createIndexes) {
for (Type<?> type : sorted) {
createIndexes(connection, mode, type);
}
}
} catch (SQLException e) {
throw new TableModificationException(e);
}
} | [
"public",
"void",
"createTables",
"(",
"Connection",
"connection",
",",
"TableCreationMode",
"mode",
",",
"boolean",
"createIndexes",
")",
"{",
"ArrayList",
"<",
"Type",
"<",
"?",
">",
">",
"sorted",
"=",
"sortTypes",
"(",
")",
";",
"try",
"(",
"Statement",
... | Create the tables over the connection.
@param connection to use
@param mode creation mode.
@param createIndexes true to also create indexes, false otherwise | [
"Create",
"the",
"tables",
"over",
"the",
"connection",
"."
] | train | https://github.com/requery/requery/blob/3070590c2ef76bb7062570bf9df03cd482db024a/requery/src/main/java/io/requery/sql/SchemaModifier.java#L142-L164 |
carewebframework/carewebframework-vista | org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/BrokerSession.java | BrokerSession.authenticate | public AuthResult authenticate(String username, String password, String division) {
ensureConnection();
if (isAuthenticated()) {
return new AuthResult("0");
}
String av = username + ";" + password;
List<String> results = callRPCList("RGNETBRP AUTH:" + Constants.VERSION, null, connectionParams.getAppid(),
getLocalName(), "", // This is the pre-authentication token
";".equals(av) ? av : Security.encrypt(av, serverCaps.getCipherKey()), getLocalAddress(), division);
AuthResult authResult = new AuthResult(results.get(0));
if (authResult.status.succeeded()) {
setPostLoginMessage(results.subList(2, results.size()));
init(results.get(1));
}
return authResult;
} | java | public AuthResult authenticate(String username, String password, String division) {
ensureConnection();
if (isAuthenticated()) {
return new AuthResult("0");
}
String av = username + ";" + password;
List<String> results = callRPCList("RGNETBRP AUTH:" + Constants.VERSION, null, connectionParams.getAppid(),
getLocalName(), "", // This is the pre-authentication token
";".equals(av) ? av : Security.encrypt(av, serverCaps.getCipherKey()), getLocalAddress(), division);
AuthResult authResult = new AuthResult(results.get(0));
if (authResult.status.succeeded()) {
setPostLoginMessage(results.subList(2, results.size()));
init(results.get(1));
}
return authResult;
} | [
"public",
"AuthResult",
"authenticate",
"(",
"String",
"username",
",",
"String",
"password",
",",
"String",
"division",
")",
"{",
"ensureConnection",
"(",
")",
";",
"if",
"(",
"isAuthenticated",
"(",
")",
")",
"{",
"return",
"new",
"AuthResult",
"(",
"\"0\"... | Request authentication from the server.
@param username User name.
@param password Password.
@param division Login division (may be null).
@return Result of authentication. | [
"Request",
"authentication",
"from",
"the",
"server",
"."
] | train | https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/BrokerSession.java#L434-L453 |
brettwooldridge/HikariCP | src/main/java/com/zaxxer/hikari/pool/PoolBase.java | PoolBase.handleMBeans | void handleMBeans(final HikariPool hikariPool, final boolean register)
{
if (!config.isRegisterMbeans()) {
return;
}
try {
final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
final ObjectName beanConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + poolName + ")");
final ObjectName beanPoolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + poolName + ")");
if (register) {
if (!mBeanServer.isRegistered(beanConfigName)) {
mBeanServer.registerMBean(config, beanConfigName);
mBeanServer.registerMBean(hikariPool, beanPoolName);
} else {
logger.error("{} - JMX name ({}) is already registered.", poolName, poolName);
}
}
else if (mBeanServer.isRegistered(beanConfigName)) {
mBeanServer.unregisterMBean(beanConfigName);
mBeanServer.unregisterMBean(beanPoolName);
}
}
catch (Exception e) {
logger.warn("{} - Failed to {} management beans.", poolName, (register ? "register" : "unregister"), e);
}
} | java | void handleMBeans(final HikariPool hikariPool, final boolean register)
{
if (!config.isRegisterMbeans()) {
return;
}
try {
final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
final ObjectName beanConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + poolName + ")");
final ObjectName beanPoolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + poolName + ")");
if (register) {
if (!mBeanServer.isRegistered(beanConfigName)) {
mBeanServer.registerMBean(config, beanConfigName);
mBeanServer.registerMBean(hikariPool, beanPoolName);
} else {
logger.error("{} - JMX name ({}) is already registered.", poolName, poolName);
}
}
else if (mBeanServer.isRegistered(beanConfigName)) {
mBeanServer.unregisterMBean(beanConfigName);
mBeanServer.unregisterMBean(beanPoolName);
}
}
catch (Exception e) {
logger.warn("{} - Failed to {} management beans.", poolName, (register ? "register" : "unregister"), e);
}
} | [
"void",
"handleMBeans",
"(",
"final",
"HikariPool",
"hikariPool",
",",
"final",
"boolean",
"register",
")",
"{",
"if",
"(",
"!",
"config",
".",
"isRegisterMbeans",
"(",
")",
")",
"{",
"return",
";",
"}",
"try",
"{",
"final",
"MBeanServer",
"mBeanServer",
"... | Register MBeans for HikariConfig and HikariPool.
@param hikariPool a HikariPool instance | [
"Register",
"MBeans",
"for",
"HikariConfig",
"and",
"HikariPool",
"."
] | train | https://github.com/brettwooldridge/HikariCP/blob/c509ec1a3f1e19769ee69323972f339cf098ff4b/src/main/java/com/zaxxer/hikari/pool/PoolBase.java#L268-L295 |
rapidpro/expressions | java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java | CustomFunctions.format_location | public static String format_location(EvaluationContext ctx, Object text) {
String _text = Conversions.toString(text, ctx);
String[] splits = _text.split(">");
return splits[splits.length - 1].trim();
} | java | public static String format_location(EvaluationContext ctx, Object text) {
String _text = Conversions.toString(text, ctx);
String[] splits = _text.split(">");
return splits[splits.length - 1].trim();
} | [
"public",
"static",
"String",
"format_location",
"(",
"EvaluationContext",
"ctx",
",",
"Object",
"text",
")",
"{",
"String",
"_text",
"=",
"Conversions",
".",
"toString",
"(",
"text",
",",
"ctx",
")",
";",
"String",
"[",
"]",
"splits",
"=",
"_text",
".",
... | Takes a single parameter (administrative boundary as a string) and returns the name of the leaf boundary | [
"Takes",
"a",
"single",
"parameter",
"(",
"administrative",
"boundary",
"as",
"a",
"string",
")",
"and",
"returns",
"the",
"name",
"of",
"the",
"leaf",
"boundary"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L171-L175 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/metadata/FieldDescriptor.java | FieldDescriptor.getComparator | public static Comparator getComparator()
{
return new Comparator()
{
public int compare(Object o1, Object o2)
{
FieldDescriptor fmd1 = (FieldDescriptor) o1;
FieldDescriptor fmd2 = (FieldDescriptor) o2;
if (fmd1.getColNo() < fmd2.getColNo())
{
return -1;
}
else if (fmd1.getColNo() > fmd2.getColNo())
{
return 1;
}
else
{
return 0;
}
}
};
} | java | public static Comparator getComparator()
{
return new Comparator()
{
public int compare(Object o1, Object o2)
{
FieldDescriptor fmd1 = (FieldDescriptor) o1;
FieldDescriptor fmd2 = (FieldDescriptor) o2;
if (fmd1.getColNo() < fmd2.getColNo())
{
return -1;
}
else if (fmd1.getColNo() > fmd2.getColNo())
{
return 1;
}
else
{
return 0;
}
}
};
} | [
"public",
"static",
"Comparator",
"getComparator",
"(",
")",
"{",
"return",
"new",
"Comparator",
"(",
")",
"{",
"public",
"int",
"compare",
"(",
"Object",
"o1",
",",
"Object",
"o2",
")",
"{",
"FieldDescriptor",
"fmd1",
"=",
"(",
"FieldDescriptor",
")",
"o1... | returns a comparator that allows to sort a Vector of FieldMappingDecriptors
according to their m_Order entries. | [
"returns",
"a",
"comparator",
"that",
"allows",
"to",
"sort",
"a",
"Vector",
"of",
"FieldMappingDecriptors",
"according",
"to",
"their",
"m_Order",
"entries",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/metadata/FieldDescriptor.java#L79-L101 |
JRebirth/JRebirth | org.jrebirth.af/showcase/analyzer/src/main/java/org/jrebirth/af/showcase/analyzer/ui/editor/ball/BallModel.java | BallModel.doEventSelected | public void doEventSelected(final JRebirthEvent eventSelected, final Wave wave) {
// Same object (reference)
if (getEventModel() == eventSelected) {
view().getScaleTransition().play();
} else {
view().getScaleTransition().stop();
view().resetScale();
}
} | java | public void doEventSelected(final JRebirthEvent eventSelected, final Wave wave) {
// Same object (reference)
if (getEventModel() == eventSelected) {
view().getScaleTransition().play();
} else {
view().getScaleTransition().stop();
view().resetScale();
}
} | [
"public",
"void",
"doEventSelected",
"(",
"final",
"JRebirthEvent",
"eventSelected",
",",
"final",
"Wave",
"wave",
")",
"{",
"// Same object (reference)",
"if",
"(",
"getEventModel",
"(",
")",
"==",
"eventSelected",
")",
"{",
"view",
"(",
")",
".",
"getScaleTran... | Call when event previous button is pressed.
@param eventSelected the selected event
@param wave the wave received | [
"Call",
"when",
"event",
"previous",
"button",
"is",
"pressed",
"."
] | train | https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/showcase/analyzer/src/main/java/org/jrebirth/af/showcase/analyzer/ui/editor/ball/BallModel.java#L49-L57 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/batch/BatchClient.java | BatchClient.listJobs | public ListJobsResponse listJobs(String marker, int maxKeys) {
return listJobs(new ListJobsRequest().withMaxKeys(maxKeys).withMarker(marker));
} | java | public ListJobsResponse listJobs(String marker, int maxKeys) {
return listJobs(new ListJobsRequest().withMaxKeys(maxKeys).withMarker(marker));
} | [
"public",
"ListJobsResponse",
"listJobs",
"(",
"String",
"marker",
",",
"int",
"maxKeys",
")",
"{",
"return",
"listJobs",
"(",
"new",
"ListJobsRequest",
"(",
")",
".",
"withMaxKeys",
"(",
"maxKeys",
")",
".",
"withMarker",
"(",
"marker",
")",
")",
";",
"}"... | List Batch-Compute jobs owned by the authenticated user.
@param marker The start record of jobs.
@param maxKeys The maximum number of jobs returned.
@return The response containing a list of the Batch-Compute jobs owned by the authenticated sender of the
request.
The jobs' records start from the marker and the size of list is limited below maxKeys. | [
"List",
"Batch",
"-",
"Compute",
"jobs",
"owned",
"by",
"the",
"authenticated",
"user",
"."
] | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/batch/BatchClient.java#L141-L143 |
venkatramanm/swf-all | swf/src/main/java/com/venky/swf/path/Path.java | Path.getUser | public User getUser(String fieldName, String fieldValue){
Select q = new Select().from(User.class);
String nameColumn = ModelReflector.instance(User.class).getColumnDescriptor(fieldName).getName();
q.where(new Expression(q.getPool(),nameColumn,Operator.EQ,new BindVariable(q.getPool(),fieldValue)));
List<? extends User> users = q.execute(User.class);
if (users.size() == 1){
return users.get(0);
}
return null;
} | java | public User getUser(String fieldName, String fieldValue){
Select q = new Select().from(User.class);
String nameColumn = ModelReflector.instance(User.class).getColumnDescriptor(fieldName).getName();
q.where(new Expression(q.getPool(),nameColumn,Operator.EQ,new BindVariable(q.getPool(),fieldValue)));
List<? extends User> users = q.execute(User.class);
if (users.size() == 1){
return users.get(0);
}
return null;
} | [
"public",
"User",
"getUser",
"(",
"String",
"fieldName",
",",
"String",
"fieldValue",
")",
"{",
"Select",
"q",
"=",
"new",
"Select",
"(",
")",
".",
"from",
"(",
"User",
".",
"class",
")",
";",
"String",
"nameColumn",
"=",
"ModelReflector",
".",
"instance... | Can be cast to any user model class as the proxy implements all the user classes. | [
"Can",
"be",
"cast",
"to",
"any",
"user",
"model",
"class",
"as",
"the",
"proxy",
"implements",
"all",
"the",
"user",
"classes",
"."
] | train | https://github.com/venkatramanm/swf-all/blob/e6ca342df0645bf1122d81e302575014ad565b69/swf/src/main/java/com/venky/swf/path/Path.java#L677-L687 |
the-fascinator/plugin-roles-internal | src/main/java/com/googlecode/fascinator/roles/internal/InternalRoles.java | InternalRoles.renameRole | @Override
public void renameRole(String oldrole, String newrole) throws RolesException {
if (role_list.containsKey(oldrole)) {
List<String> users_with_role = role_list.get(oldrole);
for (String user : users_with_role) {
// Remove the role from this user
List<String> roles_of_user = user_list.get(user);
roles_of_user.remove(oldrole);
roles_of_user.add(newrole);
user_list.put(user, roles_of_user);
// Update our file_store
String roles = StringUtils.join(roles_of_user.toArray(new String[0]), ",");
file_store.setProperty(user, roles);
}
// Replace the role entry
role_list.remove(oldrole);
role_list.put(newrole, users_with_role);
// And commit the file_store to disk
try {
saveRoles();
} catch (IOException e) {
throw new RolesException(e);
}
} else {
throw new RolesException("Cannot find role '" + oldrole + "'!");
}
} | java | @Override
public void renameRole(String oldrole, String newrole) throws RolesException {
if (role_list.containsKey(oldrole)) {
List<String> users_with_role = role_list.get(oldrole);
for (String user : users_with_role) {
// Remove the role from this user
List<String> roles_of_user = user_list.get(user);
roles_of_user.remove(oldrole);
roles_of_user.add(newrole);
user_list.put(user, roles_of_user);
// Update our file_store
String roles = StringUtils.join(roles_of_user.toArray(new String[0]), ",");
file_store.setProperty(user, roles);
}
// Replace the role entry
role_list.remove(oldrole);
role_list.put(newrole, users_with_role);
// And commit the file_store to disk
try {
saveRoles();
} catch (IOException e) {
throw new RolesException(e);
}
} else {
throw new RolesException("Cannot find role '" + oldrole + "'!");
}
} | [
"@",
"Override",
"public",
"void",
"renameRole",
"(",
"String",
"oldrole",
",",
"String",
"newrole",
")",
"throws",
"RolesException",
"{",
"if",
"(",
"role_list",
".",
"containsKey",
"(",
"oldrole",
")",
")",
"{",
"List",
"<",
"String",
">",
"users_with_role... | Rename a role.
@param oldrole
The name role currently has.
@param newrole
The name role is changing to.
@throws RolesException
if there was an error during rename. | [
"Rename",
"a",
"role",
"."
] | train | https://github.com/the-fascinator/plugin-roles-internal/blob/5f75f802a92ef907acf030692d462aec4b4d3aae/src/main/java/com/googlecode/fascinator/roles/internal/InternalRoles.java#L435-L463 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsp/src/com/ibm/ws/jsp/taglib/GlobalTagLibraryCache.java | GlobalTagLibraryCache.addGlobalTagLibConfig | public void addGlobalTagLibConfig(GlobalTagLibConfig globalTagLibConfig) {
try {
TldParser tldParser = new TldParser(this, configManager, false, globalTagLibConfig.getClassloader());
if (globalTagLibConfig.getClassloader() == null)
loadTldFromJarInputStream(globalTagLibConfig, tldParser);
else
loadTldFromClassloader(globalTagLibConfig, tldParser);
globalTagLibConfigList.add(globalTagLibConfig);
}
catch (JspCoreException e) {
if(com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable(Level.SEVERE)){
logger.logp(Level.SEVERE, CLASS_NAME, "addGlobalTagLibConfig", "failed to create TldParser ", e);
}
}
} | java | public void addGlobalTagLibConfig(GlobalTagLibConfig globalTagLibConfig) {
try {
TldParser tldParser = new TldParser(this, configManager, false, globalTagLibConfig.getClassloader());
if (globalTagLibConfig.getClassloader() == null)
loadTldFromJarInputStream(globalTagLibConfig, tldParser);
else
loadTldFromClassloader(globalTagLibConfig, tldParser);
globalTagLibConfigList.add(globalTagLibConfig);
}
catch (JspCoreException e) {
if(com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable(Level.SEVERE)){
logger.logp(Level.SEVERE, CLASS_NAME, "addGlobalTagLibConfig", "failed to create TldParser ", e);
}
}
} | [
"public",
"void",
"addGlobalTagLibConfig",
"(",
"GlobalTagLibConfig",
"globalTagLibConfig",
")",
"{",
"try",
"{",
"TldParser",
"tldParser",
"=",
"new",
"TldParser",
"(",
"this",
",",
"configManager",
",",
"false",
",",
"globalTagLibConfig",
".",
"getClassloader",
"(... | add some GlobalTabLibConfig to the global tag libs we know about. If the provided
config provides a classloader, we will load the TLDs via that class loaders, otherwise the
JAR URL will be used to find the TLDs.
@param globalTagLibConfig The global tag lib config | [
"add",
"some",
"GlobalTabLibConfig",
"to",
"the",
"global",
"tag",
"libs",
"we",
"know",
"about",
".",
"If",
"the",
"provided",
"config",
"provides",
"a",
"classloader",
"we",
"will",
"load",
"the",
"TLDs",
"via",
"that",
"class",
"loaders",
"otherwise",
"th... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsp/src/com/ibm/ws/jsp/taglib/GlobalTagLibraryCache.java#L596-L612 |
vlingo/vlingo-actors | src/main/java/io/vlingo/actors/Stage.java | Stage.actorAs | public <T> T actorAs(final Actor actor, final Class<T> protocol) {
return actorProxyFor(protocol, actor, actor.lifeCycle.environment.mailbox);
} | java | public <T> T actorAs(final Actor actor, final Class<T> protocol) {
return actorProxyFor(protocol, actor, actor.lifeCycle.environment.mailbox);
} | [
"public",
"<",
"T",
">",
"T",
"actorAs",
"(",
"final",
"Actor",
"actor",
",",
"final",
"Class",
"<",
"T",
">",
"protocol",
")",
"{",
"return",
"actorProxyFor",
"(",
"protocol",
",",
"actor",
",",
"actor",
".",
"lifeCycle",
".",
"environment",
".",
"mai... | Answers the {@code T} protocol type as the means to message the backing {@code Actor}.
@param actor the {@code Actor} that implements the {@code Class<T>} protocol
@param protocol the {@code Class<T>} protocol
@param <T> the protocol type
@return T | [
"Answers",
"the",
"{"
] | train | https://github.com/vlingo/vlingo-actors/blob/c7d046fd139c0490cf0fd2588d7dc2f792f13493/src/main/java/io/vlingo/actors/Stage.java#L37-L39 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/SubscriptionMessageImpl.java | SubscriptionMessageImpl.getIntKeyForString | private int getIntKeyForString(ArrayList<String> uniqueStrings, Object value) {
String stringValue = String.valueOf(value);
int retval = uniqueStrings.indexOf(stringValue);
if (retval < 0) {
retval = uniqueStrings.size();
uniqueStrings.add(stringValue);
}
return retval;
} | java | private int getIntKeyForString(ArrayList<String> uniqueStrings, Object value) {
String stringValue = String.valueOf(value);
int retval = uniqueStrings.indexOf(stringValue);
if (retval < 0) {
retval = uniqueStrings.size();
uniqueStrings.add(stringValue);
}
return retval;
} | [
"private",
"int",
"getIntKeyForString",
"(",
"ArrayList",
"<",
"String",
">",
"uniqueStrings",
",",
"Object",
"value",
")",
"{",
"String",
"stringValue",
"=",
"String",
".",
"valueOf",
"(",
"value",
")",
";",
"int",
"retval",
"=",
"uniqueStrings",
".",
"inde... | Helper method to get, or assign, a unique key to a string,
from an ArrayList containing the unique keys.
@param uniqueStrings Current set of unique strings
@param value Object to convert to a string, and find/assign an number for
@return number associated with the unique string | [
"Helper",
"method",
"to",
"get",
"or",
"assign",
"a",
"unique",
"key",
"to",
"a",
"string",
"from",
"an",
"ArrayList",
"containing",
"the",
"unique",
"keys",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/SubscriptionMessageImpl.java#L185-L193 |
mailosaur/mailosaur-java | src/main/java/com/mailosaur/Messages.java | Messages.waitFor | public Message waitFor(String server, SearchCriteria criteria) throws IOException, MailosaurException {
HashMap<String, String> query = new HashMap<String, String>();
query.put("server", server);
return client.request("POST", "api/messages/await", criteria, query).parseAs(Message.class);
} | java | public Message waitFor(String server, SearchCriteria criteria) throws IOException, MailosaurException {
HashMap<String, String> query = new HashMap<String, String>();
query.put("server", server);
return client.request("POST", "api/messages/await", criteria, query).parseAs(Message.class);
} | [
"public",
"Message",
"waitFor",
"(",
"String",
"server",
",",
"SearchCriteria",
"criteria",
")",
"throws",
"IOException",
",",
"MailosaurException",
"{",
"HashMap",
"<",
"String",
",",
"String",
">",
"query",
"=",
"new",
"HashMap",
"<",
"String",
",",
"String"... | Wait for a specific message.
Returns as soon as an message matching the specified search criteria is found.
@param server The identifier of the server hosting the message.
@param criteria The search criteria to use in order to find a match.
@throws MailosaurException thrown if the request is rejected by server
@throws IOException
@return the Message object if successful. | [
"Wait",
"for",
"a",
"specific",
"message",
".",
"Returns",
"as",
"soon",
"as",
"an",
"message",
"matching",
"the",
"specified",
"search",
"criteria",
"is",
"found",
"."
] | train | https://github.com/mailosaur/mailosaur-java/blob/a580760f2eb41e034127d93104c7050639eced97/src/main/java/com/mailosaur/Messages.java#L106-L110 |
joniles/mpxj | src/main/java/net/sf/mpxj/planner/PlannerReader.java | PlannerReader.readCalendar | private void readCalendar(net.sf.mpxj.planner.schema.Calendar plannerCalendar, ProjectCalendar parentMpxjCalendar) throws MPXJException
{
//
// Create a calendar instance
//
ProjectCalendar mpxjCalendar = m_projectFile.addCalendar();
//
// Populate basic details
//
mpxjCalendar.setUniqueID(getInteger(plannerCalendar.getId()));
mpxjCalendar.setName(plannerCalendar.getName());
mpxjCalendar.setParent(parentMpxjCalendar);
//
// Set working and non working days
//
DefaultWeek dw = plannerCalendar.getDefaultWeek();
setWorkingDay(mpxjCalendar, Day.MONDAY, dw.getMon());
setWorkingDay(mpxjCalendar, Day.TUESDAY, dw.getTue());
setWorkingDay(mpxjCalendar, Day.WEDNESDAY, dw.getWed());
setWorkingDay(mpxjCalendar, Day.THURSDAY, dw.getThu());
setWorkingDay(mpxjCalendar, Day.FRIDAY, dw.getFri());
setWorkingDay(mpxjCalendar, Day.SATURDAY, dw.getSat());
setWorkingDay(mpxjCalendar, Day.SUNDAY, dw.getSun());
//
// Set working hours
//
processWorkingHours(mpxjCalendar, plannerCalendar);
//
// Process exception days
//
processExceptionDays(mpxjCalendar, plannerCalendar);
m_eventManager.fireCalendarReadEvent(mpxjCalendar);
//
// Process any derived calendars
//
List<net.sf.mpxj.planner.schema.Calendar> calendarList = plannerCalendar.getCalendar();
for (net.sf.mpxj.planner.schema.Calendar cal : calendarList)
{
readCalendar(cal, mpxjCalendar);
}
} | java | private void readCalendar(net.sf.mpxj.planner.schema.Calendar plannerCalendar, ProjectCalendar parentMpxjCalendar) throws MPXJException
{
//
// Create a calendar instance
//
ProjectCalendar mpxjCalendar = m_projectFile.addCalendar();
//
// Populate basic details
//
mpxjCalendar.setUniqueID(getInteger(plannerCalendar.getId()));
mpxjCalendar.setName(plannerCalendar.getName());
mpxjCalendar.setParent(parentMpxjCalendar);
//
// Set working and non working days
//
DefaultWeek dw = plannerCalendar.getDefaultWeek();
setWorkingDay(mpxjCalendar, Day.MONDAY, dw.getMon());
setWorkingDay(mpxjCalendar, Day.TUESDAY, dw.getTue());
setWorkingDay(mpxjCalendar, Day.WEDNESDAY, dw.getWed());
setWorkingDay(mpxjCalendar, Day.THURSDAY, dw.getThu());
setWorkingDay(mpxjCalendar, Day.FRIDAY, dw.getFri());
setWorkingDay(mpxjCalendar, Day.SATURDAY, dw.getSat());
setWorkingDay(mpxjCalendar, Day.SUNDAY, dw.getSun());
//
// Set working hours
//
processWorkingHours(mpxjCalendar, plannerCalendar);
//
// Process exception days
//
processExceptionDays(mpxjCalendar, plannerCalendar);
m_eventManager.fireCalendarReadEvent(mpxjCalendar);
//
// Process any derived calendars
//
List<net.sf.mpxj.planner.schema.Calendar> calendarList = plannerCalendar.getCalendar();
for (net.sf.mpxj.planner.schema.Calendar cal : calendarList)
{
readCalendar(cal, mpxjCalendar);
}
} | [
"private",
"void",
"readCalendar",
"(",
"net",
".",
"sf",
".",
"mpxj",
".",
"planner",
".",
"schema",
".",
"Calendar",
"plannerCalendar",
",",
"ProjectCalendar",
"parentMpxjCalendar",
")",
"throws",
"MPXJException",
"{",
"//",
"// Create a calendar instance",
"//",
... | This method extracts data for a single calendar from a Planner file.
@param plannerCalendar Calendar data
@param parentMpxjCalendar parent of derived calendar | [
"This",
"method",
"extracts",
"data",
"for",
"a",
"single",
"calendar",
"from",
"a",
"Planner",
"file",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/planner/PlannerReader.java#L229-L275 |
phax/ph-commons | ph-xml/src/main/java/com/helger/xml/xpath/XPathHelper.java | XPathHelper.createNewXPathExpression | @Nonnull
public static XPathExpression createNewXPathExpression (@Nullable final XPathVariableResolver aVariableResolver,
@Nullable final XPathFunctionResolver aFunctionResolver,
@Nullable final NamespaceContext aNamespaceContext,
@Nonnull @Nonempty final String sXPath)
{
return createNewXPathExpression (createNewXPath (aVariableResolver, aFunctionResolver, aNamespaceContext), sXPath);
} | java | @Nonnull
public static XPathExpression createNewXPathExpression (@Nullable final XPathVariableResolver aVariableResolver,
@Nullable final XPathFunctionResolver aFunctionResolver,
@Nullable final NamespaceContext aNamespaceContext,
@Nonnull @Nonempty final String sXPath)
{
return createNewXPathExpression (createNewXPath (aVariableResolver, aFunctionResolver, aNamespaceContext), sXPath);
} | [
"@",
"Nonnull",
"public",
"static",
"XPathExpression",
"createNewXPathExpression",
"(",
"@",
"Nullable",
"final",
"XPathVariableResolver",
"aVariableResolver",
",",
"@",
"Nullable",
"final",
"XPathFunctionResolver",
"aFunctionResolver",
",",
"@",
"Nullable",
"final",
"Nam... | Create a new XPath expression for evaluation using the default
{@link XPathFactory}.
@param aVariableResolver
Variable resolver to be used. May be <code>null</code>.
@param aFunctionResolver
Function resolver to be used. May be <code>null</code>.
@param aNamespaceContext
Namespace context to be used. May be <code>null</code>.
@param sXPath
The main XPath string to be evaluated
@return The {@link XPathExpression} object to be used.
@throws IllegalArgumentException
if the XPath cannot be compiled | [
"Create",
"a",
"new",
"XPath",
"expression",
"for",
"evaluation",
"using",
"the",
"default",
"{",
"@link",
"XPathFactory",
"}",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/xpath/XPathHelper.java#L321-L328 |
Azure/azure-sdk-for-java | kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/ClustersInner.java | ClustersInner.beginCreateOrUpdate | public ClusterInner beginCreateOrUpdate(String resourceGroupName, String clusterName, ClusterInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().single().body();
} | java | public ClusterInner beginCreateOrUpdate(String resourceGroupName, String clusterName, ClusterInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().single().body();
} | [
"public",
"ClusterInner",
"beginCreateOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
",",
"ClusterInner",
"parameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"clusterName",
",",
"param... | Create or update a Kusto cluster.
@param resourceGroupName The name of the resource group containing the Kusto cluster.
@param clusterName The name of the Kusto cluster.
@param parameters The Kusto cluster parameters supplied to the CreateOrUpdate operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ClusterInner object if successful. | [
"Create",
"or",
"update",
"a",
"Kusto",
"cluster",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/ClustersInner.java#L308-L310 |
voldemort/voldemort | src/java/voldemort/store/stats/ClientSocketStats.java | ClientSocketStats.recordSyncOpTimeNs | public void recordSyncOpTimeNs(SocketDestination dest, long opTimeNs) {
if(dest != null) {
getOrCreateNodeStats(dest).recordSyncOpTimeNs(null, opTimeNs);
recordSyncOpTimeNs(null, opTimeNs);
} else {
this.syncOpTimeRequestCounter.addRequest(opTimeNs);
}
} | java | public void recordSyncOpTimeNs(SocketDestination dest, long opTimeNs) {
if(dest != null) {
getOrCreateNodeStats(dest).recordSyncOpTimeNs(null, opTimeNs);
recordSyncOpTimeNs(null, opTimeNs);
} else {
this.syncOpTimeRequestCounter.addRequest(opTimeNs);
}
} | [
"public",
"void",
"recordSyncOpTimeNs",
"(",
"SocketDestination",
"dest",
",",
"long",
"opTimeNs",
")",
"{",
"if",
"(",
"dest",
"!=",
"null",
")",
"{",
"getOrCreateNodeStats",
"(",
"dest",
")",
".",
"recordSyncOpTimeNs",
"(",
"null",
",",
"opTimeNs",
")",
";... | Record operation for sync ops time
@param dest Destination of the socket to connect to. Will actually record
if null. Otherwise will call this on self and corresponding child
with this param null.
@param opTimeUs The number of us for the op to finish | [
"Record",
"operation",
"for",
"sync",
"ops",
"time"
] | train | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/ClientSocketStats.java#L213-L220 |
Azure/azure-sdk-for-java | mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingEndpointsInner.java | StreamingEndpointsInner.beginUpdateAsync | public Observable<StreamingEndpointInner> beginUpdateAsync(String resourceGroupName, String accountName, String streamingEndpointName, StreamingEndpointInner parameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, accountName, streamingEndpointName, parameters).map(new Func1<ServiceResponse<StreamingEndpointInner>, StreamingEndpointInner>() {
@Override
public StreamingEndpointInner call(ServiceResponse<StreamingEndpointInner> response) {
return response.body();
}
});
} | java | public Observable<StreamingEndpointInner> beginUpdateAsync(String resourceGroupName, String accountName, String streamingEndpointName, StreamingEndpointInner parameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, accountName, streamingEndpointName, parameters).map(new Func1<ServiceResponse<StreamingEndpointInner>, StreamingEndpointInner>() {
@Override
public StreamingEndpointInner call(ServiceResponse<StreamingEndpointInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"StreamingEndpointInner",
">",
"beginUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"String",
"streamingEndpointName",
",",
"StreamingEndpointInner",
"parameters",
")",
"{",
"return",
"beginUpdateWithService... | Update StreamingEndpoint.
Updates a existing StreamingEndpoint.
@param resourceGroupName The name of the resource group within the Azure subscription.
@param accountName The Media Services account name.
@param streamingEndpointName The name of the StreamingEndpoint.
@param parameters StreamingEndpoint properties needed for creation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the StreamingEndpointInner object | [
"Update",
"StreamingEndpoint",
".",
"Updates",
"a",
"existing",
"StreamingEndpoint",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingEndpointsInner.java#L876-L883 |
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.getImageRegionProposals | public ImageRegionProposal getImageRegionProposals(UUID projectId, UUID imageId) {
return getImageRegionProposalsWithServiceResponseAsync(projectId, imageId).toBlocking().single().body();
} | java | public ImageRegionProposal getImageRegionProposals(UUID projectId, UUID imageId) {
return getImageRegionProposalsWithServiceResponseAsync(projectId, imageId).toBlocking().single().body();
} | [
"public",
"ImageRegionProposal",
"getImageRegionProposals",
"(",
"UUID",
"projectId",
",",
"UUID",
"imageId",
")",
"{",
"return",
"getImageRegionProposalsWithServiceResponseAsync",
"(",
"projectId",
",",
"imageId",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",... | Get region proposals for an image. Returns empty array if no proposals are found.
This API will get region proposals for an image along with confidences for the region. It returns an empty array if no proposals are found.
@param projectId The project id
@param imageId The image id
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ImageRegionProposal object if successful. | [
"Get",
"region",
"proposals",
"for",
"an",
"image",
".",
"Returns",
"empty",
"array",
"if",
"no",
"proposals",
"are",
"found",
".",
"This",
"API",
"will",
"get",
"region",
"proposals",
"for",
"an",
"image",
"along",
"with",
"confidences",
"for",
"the",
"re... | 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#L3172-L3174 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPPrefixesInner.java | PublicIPPrefixesInner.getByResourceGroup | public PublicIPPrefixInner getByResourceGroup(String resourceGroupName, String publicIpPrefixName, String expand) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, publicIpPrefixName, expand).toBlocking().single().body();
} | java | public PublicIPPrefixInner getByResourceGroup(String resourceGroupName, String publicIpPrefixName, String expand) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, publicIpPrefixName, expand).toBlocking().single().body();
} | [
"public",
"PublicIPPrefixInner",
"getByResourceGroup",
"(",
"String",
"resourceGroupName",
",",
"String",
"publicIpPrefixName",
",",
"String",
"expand",
")",
"{",
"return",
"getByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"publicIpPrefixName",
",",... | Gets the specified public IP prefix in a specified resource group.
@param resourceGroupName The name of the resource group.
@param publicIpPrefixName The name of the PublicIPPrefx.
@param expand Expands referenced resources.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the PublicIPPrefixInner object if successful. | [
"Gets",
"the",
"specified",
"public",
"IP",
"prefix",
"in",
"a",
"specified",
"resource",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPPrefixesInner.java#L356-L358 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/DFSClient.java | DFSClient.reportChecksumFailure | void reportChecksumFailure(String file, LocatedBlock lblocks[]) {
try {
reportBadBlocks(lblocks);
} catch (IOException ie) {
LOG.info("Found corruption while reading " + file
+ ". Error repairing corrupt blocks. Bad blocks remain. "
+ StringUtils.stringifyException(ie));
}
} | java | void reportChecksumFailure(String file, LocatedBlock lblocks[]) {
try {
reportBadBlocks(lblocks);
} catch (IOException ie) {
LOG.info("Found corruption while reading " + file
+ ". Error repairing corrupt blocks. Bad blocks remain. "
+ StringUtils.stringifyException(ie));
}
} | [
"void",
"reportChecksumFailure",
"(",
"String",
"file",
",",
"LocatedBlock",
"lblocks",
"[",
"]",
")",
"{",
"try",
"{",
"reportBadBlocks",
"(",
"lblocks",
")",
";",
"}",
"catch",
"(",
"IOException",
"ie",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Found corrupt... | just reports checksum failure and ignores any exception during the report. | [
"just",
"reports",
"checksum",
"failure",
"and",
"ignores",
"any",
"exception",
"during",
"the",
"report",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/DFSClient.java#L3051-L3059 |
Whiley/WhileyCompiler | src/main/java/wyil/interpreter/Interpreter.java | Interpreter.executeQuantifier | private boolean executeQuantifier(int index, Expr.Quantifier expr, CallStack frame) {
Tuple<Decl.Variable> vars = expr.getParameters();
if (index == vars.size()) {
// This is the base case where we evaluate the condition itself.
RValue.Bool r = executeExpression(BOOL_T, expr.getOperand(), frame);
boolean q = (expr instanceof Expr.UniversalQuantifier);
// If this evaluates to true, then we will continue executing the
// quantifier.
return r.boolValue() == q;
} else {
Decl.Variable var = vars.get(index);
RValue.Array range = executeExpression(ARRAY_T, var.getInitialiser(), frame);
RValue[] elements = range.getElements();
for (int i = 0; i != elements.length; ++i) {
frame.putLocal(var.getName(), elements[i]);
boolean r = executeQuantifier(index + 1, expr, frame);
if (!r) {
// early termination
return r;
}
}
return true;
}
} | java | private boolean executeQuantifier(int index, Expr.Quantifier expr, CallStack frame) {
Tuple<Decl.Variable> vars = expr.getParameters();
if (index == vars.size()) {
// This is the base case where we evaluate the condition itself.
RValue.Bool r = executeExpression(BOOL_T, expr.getOperand(), frame);
boolean q = (expr instanceof Expr.UniversalQuantifier);
// If this evaluates to true, then we will continue executing the
// quantifier.
return r.boolValue() == q;
} else {
Decl.Variable var = vars.get(index);
RValue.Array range = executeExpression(ARRAY_T, var.getInitialiser(), frame);
RValue[] elements = range.getElements();
for (int i = 0; i != elements.length; ++i) {
frame.putLocal(var.getName(), elements[i]);
boolean r = executeQuantifier(index + 1, expr, frame);
if (!r) {
// early termination
return r;
}
}
return true;
}
} | [
"private",
"boolean",
"executeQuantifier",
"(",
"int",
"index",
",",
"Expr",
".",
"Quantifier",
"expr",
",",
"CallStack",
"frame",
")",
"{",
"Tuple",
"<",
"Decl",
".",
"Variable",
">",
"vars",
"=",
"expr",
".",
"getParameters",
"(",
")",
";",
"if",
"(",
... | Execute one range of the quantifier, or the body if no ranges remain.
@param index
@param expr
@param frame
@param context
@return | [
"Execute",
"one",
"range",
"of",
"the",
"quantifier",
"or",
"the",
"body",
"if",
"no",
"ranges",
"remain",
"."
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/interpreter/Interpreter.java#L777-L800 |
groovy/groovy-core | subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java | Sql.eachRow | public void eachRow(String sql, List<Object> params, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws SQLException {
Connection connection = createConnection();
PreparedStatement statement = null;
ResultSet results = null;
try {
statement = getPreparedStatement(connection, sql, params);
results = statement.executeQuery();
if (metaClosure != null) metaClosure.call(results.getMetaData());
boolean cursorAtRow = moveCursor(results, offset);
if (!cursorAtRow) return;
GroovyResultSet groovyRS = new GroovyResultSetProxy(results).getImpl();
int i = 0;
while ((maxRows <= 0 || i++ < maxRows) && groovyRS.next()) {
rowClosure.call(groovyRS);
}
} catch (SQLException e) {
LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage());
throw e;
} finally {
closeResources(connection, statement, results);
}
} | java | public void eachRow(String sql, List<Object> params, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws SQLException {
Connection connection = createConnection();
PreparedStatement statement = null;
ResultSet results = null;
try {
statement = getPreparedStatement(connection, sql, params);
results = statement.executeQuery();
if (metaClosure != null) metaClosure.call(results.getMetaData());
boolean cursorAtRow = moveCursor(results, offset);
if (!cursorAtRow) return;
GroovyResultSet groovyRS = new GroovyResultSetProxy(results).getImpl();
int i = 0;
while ((maxRows <= 0 || i++ < maxRows) && groovyRS.next()) {
rowClosure.call(groovyRS);
}
} catch (SQLException e) {
LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage());
throw e;
} finally {
closeResources(connection, statement, results);
}
} | [
"public",
"void",
"eachRow",
"(",
"String",
"sql",
",",
"List",
"<",
"Object",
">",
"params",
",",
"Closure",
"metaClosure",
",",
"int",
"offset",
",",
"int",
"maxRows",
",",
"Closure",
"rowClosure",
")",
"throws",
"SQLException",
"{",
"Connection",
"connect... | Performs the given SQL query calling the given <code>rowClosure</code> with each row of the result set starting at
the provided <code>offset</code>, and including up to <code>maxRows</code> number of rows.
The row will be a <code>GroovyResultSet</code> which is a <code>ResultSet</code>
that supports accessing the fields using property style notation and ordinal index values.
<p>
In addition, the <code>metaClosure</code> will be called once passing in the
<code>ResultSetMetaData</code> as argument.
The query may contain placeholder question marks which match the given list of parameters.
<p>
Note that the underlying implementation is based on either invoking <code>ResultSet.absolute()</code>,
or if the ResultSet type is <code>ResultSet.TYPE_FORWARD_ONLY</code>, the <code>ResultSet.next()</code> method
is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect
on the initial positioning within the result set.
<p>
Note that different database and JDBC driver implementations may work differently with respect to this method.
Specifically, one should expect that <code>ResultSet.TYPE_FORWARD_ONLY</code> may be less efficient than a
"scrollable" type.
@param sql the sql statement
@param params a list of parameters
@param offset the 1-based offset for the first row to be processed
@param maxRows the maximum number of rows to be processed
@param metaClosure called for meta data (only once after sql execution)
@param rowClosure called for each row with a GroovyResultSet
@throws SQLException if a database access error occurs | [
"Performs",
"the",
"given",
"SQL",
"query",
"calling",
"the",
"given",
"<code",
">",
"rowClosure<",
"/",
"code",
">",
"with",
"each",
"row",
"of",
"the",
"result",
"set",
"starting",
"at",
"the",
"provided",
"<code",
">",
"offset<",
"/",
"code",
">",
"an... | train | https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java#L1244-L1266 |
VoltDB/voltdb | third_party/java/src/org/apache/jute_voltpatches/compiler/JFile.java | JFile.genCode | public void genCode(String language, File outputDirectory)
throws IOException {
if ("c++".equals(language)) {
CppGenerator gen = new CppGenerator(mName, mInclFiles, mRecords,
outputDirectory);
gen.genCode();
} else if ("java".equals(language)) {
JavaGenerator gen = new JavaGenerator(mName, mInclFiles, mRecords,
outputDirectory);
gen.genCode();
} else if ("c".equals(language)) {
CGenerator gen = new CGenerator(mName, mInclFiles, mRecords,
outputDirectory);
gen.genCode();
} else {
throw new IOException("Cannnot recognize language:" + language);
}
} | java | public void genCode(String language, File outputDirectory)
throws IOException {
if ("c++".equals(language)) {
CppGenerator gen = new CppGenerator(mName, mInclFiles, mRecords,
outputDirectory);
gen.genCode();
} else if ("java".equals(language)) {
JavaGenerator gen = new JavaGenerator(mName, mInclFiles, mRecords,
outputDirectory);
gen.genCode();
} else if ("c".equals(language)) {
CGenerator gen = new CGenerator(mName, mInclFiles, mRecords,
outputDirectory);
gen.genCode();
} else {
throw new IOException("Cannnot recognize language:" + language);
}
} | [
"public",
"void",
"genCode",
"(",
"String",
"language",
",",
"File",
"outputDirectory",
")",
"throws",
"IOException",
"{",
"if",
"(",
"\"c++\"",
".",
"equals",
"(",
"language",
")",
")",
"{",
"CppGenerator",
"gen",
"=",
"new",
"CppGenerator",
"(",
"mName",
... | Generate record code in given language. Language should be all lowercase.
@param outputDirectory | [
"Generate",
"record",
"code",
"in",
"given",
"language",
".",
"Language",
"should",
"be",
"all",
"lowercase",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/jute_voltpatches/compiler/JFile.java#L64-L81 |
phax/ph-masterdata | ph-masterdata/src/main/java/com/helger/masterdata/postal/PostalCodeManager.java | PostalCodeManager.isValidPostalCodeDefaultYes | public boolean isValidPostalCodeDefaultYes (@Nullable final Locale aCountry, @Nullable final String sPostalCode)
{
return isValidPostalCode (aCountry, sPostalCode).getAsBooleanValue (true);
} | java | public boolean isValidPostalCodeDefaultYes (@Nullable final Locale aCountry, @Nullable final String sPostalCode)
{
return isValidPostalCode (aCountry, sPostalCode).getAsBooleanValue (true);
} | [
"public",
"boolean",
"isValidPostalCodeDefaultYes",
"(",
"@",
"Nullable",
"final",
"Locale",
"aCountry",
",",
"@",
"Nullable",
"final",
"String",
"sPostalCode",
")",
"{",
"return",
"isValidPostalCode",
"(",
"aCountry",
",",
"sPostalCode",
")",
".",
"getAsBooleanValu... | Check if the passed postal code is valid for the passed country. If no
information for that specific country is defined, the postal code is
assumed valid!
@param aCountry
The country to check. May be <code>null</code>.
@param sPostalCode
The postal code to check. May be <code>null</code>.
@return <code>true</code> if the postal code is valid for the passed
country or if no information for that country are present,
<code>false</code> otherwise. | [
"Check",
"if",
"the",
"passed",
"postal",
"code",
"is",
"valid",
"for",
"the",
"passed",
"country",
".",
"If",
"no",
"information",
"for",
"that",
"specific",
"country",
"is",
"defined",
"the",
"postal",
"code",
"is",
"assumed",
"valid!"
] | train | https://github.com/phax/ph-masterdata/blob/ca5e0b03c735b30b47930c018bfb5e71f00d0ff4/ph-masterdata/src/main/java/com/helger/masterdata/postal/PostalCodeManager.java#L133-L136 |
OpenBEL/openbel-framework | org.openbel.framework.core/src/main/java/org/openbel/framework/core/df/cache/DefaultCacheableResourceService.java | DefaultCacheableResourceService.downloadResourceForUse | private File downloadResourceForUse(String resourceLocation,
ResourceType type)
throws ResourceDownloadError {
File downloadResource = downloadResource(resourceLocation, type);
return copyResource(downloadResource, resourceLocation);
} | java | private File downloadResourceForUse(String resourceLocation,
ResourceType type)
throws ResourceDownloadError {
File downloadResource = downloadResource(resourceLocation, type);
return copyResource(downloadResource, resourceLocation);
} | [
"private",
"File",
"downloadResourceForUse",
"(",
"String",
"resourceLocation",
",",
"ResourceType",
"type",
")",
"throws",
"ResourceDownloadError",
"{",
"File",
"downloadResource",
"=",
"downloadResource",
"(",
"resourceLocation",
",",
"type",
")",
";",
"return",
"co... | Download and copy the resource for use.
@param resourceLocation {@link String}, the resource location
@param type {@link ResourceType}, the type of resource
@return the resource copy {@link File} ready for processing
@throws ResourceDownloadError Throw if an error occurred resolving or
copying the resource | [
"Download",
"and",
"copy",
"the",
"resource",
"for",
"use",
"."
] | train | https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.core/src/main/java/org/openbel/framework/core/df/cache/DefaultCacheableResourceService.java#L196-L201 |
MTDdk/jawn | jawn-core/src/main/java/net/javapla/jawn/core/Controller.java | Controller.sendCookie | public void sendCookie(String name, String value) {
context.addCookie(Cookie.builder(name, value).build());
} | java | public void sendCookie(String name, String value) {
context.addCookie(Cookie.builder(name, value).build());
} | [
"public",
"void",
"sendCookie",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"context",
".",
"addCookie",
"(",
"Cookie",
".",
"builder",
"(",
"name",
",",
"value",
")",
".",
"build",
"(",
")",
")",
";",
"}"
] | Sends cookie to browse with response.
@param name name of cookie
@param value value of cookie. | [
"Sends",
"cookie",
"to",
"browse",
"with",
"response",
"."
] | train | https://github.com/MTDdk/jawn/blob/4ec2d09b97d413efdead7487e6075e5bfd13b925/jawn-core/src/main/java/net/javapla/jawn/core/Controller.java#L1273-L1275 |
Netflix/eureka | eureka-client/src/main/java/com/netflix/discovery/util/DeserializerStringCache.java | DeserializerStringCache.apply | public String apply(final String stringValue, CacheScope cacheScope) {
if (stringValue != null && (lengthLimit < 0 || stringValue.length() <= lengthLimit)) {
return (String) (cacheScope == CacheScope.GLOBAL_SCOPE ? globalCache : applicationCache)
.computeIfAbsent(CharBuffer.wrap(stringValue), s -> {
logger.trace(" (string) writing new interned value {} into {} cache scope", stringValue, cacheScope);
return stringValue;
});
}
return stringValue;
} | java | public String apply(final String stringValue, CacheScope cacheScope) {
if (stringValue != null && (lengthLimit < 0 || stringValue.length() <= lengthLimit)) {
return (String) (cacheScope == CacheScope.GLOBAL_SCOPE ? globalCache : applicationCache)
.computeIfAbsent(CharBuffer.wrap(stringValue), s -> {
logger.trace(" (string) writing new interned value {} into {} cache scope", stringValue, cacheScope);
return stringValue;
});
}
return stringValue;
} | [
"public",
"String",
"apply",
"(",
"final",
"String",
"stringValue",
",",
"CacheScope",
"cacheScope",
")",
"{",
"if",
"(",
"stringValue",
"!=",
"null",
"&&",
"(",
"lengthLimit",
"<",
"0",
"||",
"stringValue",
".",
"length",
"(",
")",
"<=",
"lengthLimit",
")... | returns a String that may be interned at the given scope to reduce heap
consumption
@param stringValue
@param cacheScope
@return a possibly interned String | [
"returns",
"a",
"String",
"that",
"may",
"be",
"interned",
"at",
"the",
"given",
"scope",
"to",
"reduce",
"heap",
"consumption"
] | train | https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-client/src/main/java/com/netflix/discovery/util/DeserializerStringCache.java#L270-L279 |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/tracker/tld/TldHelperFunctions.java | TldHelperFunctions.computeOverlap | public double computeOverlap( ImageRectangle a , ImageRectangle b ) {
if( !a.intersection(b,work) )
return 0;
int areaI = work.area();
int bottom = a.area() + b.area() - areaI;
return areaI/ (double)bottom;
} | java | public double computeOverlap( ImageRectangle a , ImageRectangle b ) {
if( !a.intersection(b,work) )
return 0;
int areaI = work.area();
int bottom = a.area() + b.area() - areaI;
return areaI/ (double)bottom;
} | [
"public",
"double",
"computeOverlap",
"(",
"ImageRectangle",
"a",
",",
"ImageRectangle",
"b",
")",
"{",
"if",
"(",
"!",
"a",
".",
"intersection",
"(",
"b",
",",
"work",
")",
")",
"return",
"0",
";",
"int",
"areaI",
"=",
"work",
".",
"area",
"(",
")",... | Computes the fractional area of intersection between the two regions.
@return number from 0 to 1. higher means more intersection | [
"Computes",
"the",
"fractional",
"area",
"of",
"intersection",
"between",
"the",
"two",
"regions",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/tracker/tld/TldHelperFunctions.java#L38-L47 |
micronaut-projects/micronaut-core | inject/src/main/java/io/micronaut/inject/beans/visitor/BeanIntrospectionWriter.java | BeanIntrospectionWriter.indexProperty | void indexProperty(AnnotationValue<?> annotation, String property, @Nullable String value) {
indexes.computeIfAbsent(property, s -> new HashSet<>(2)).add(new AnnotationValueIndex(annotation, property, value));
} | java | void indexProperty(AnnotationValue<?> annotation, String property, @Nullable String value) {
indexes.computeIfAbsent(property, s -> new HashSet<>(2)).add(new AnnotationValueIndex(annotation, property, value));
} | [
"void",
"indexProperty",
"(",
"AnnotationValue",
"<",
"?",
">",
"annotation",
",",
"String",
"property",
",",
"@",
"Nullable",
"String",
"value",
")",
"{",
"indexes",
".",
"computeIfAbsent",
"(",
"property",
",",
"s",
"->",
"new",
"HashSet",
"<>",
"(",
"2"... | Builds an index for the given property and annotation.
@param annotation The annotation
@param property The property
@param value the value of the annotation | [
"Builds",
"an",
"index",
"for",
"the",
"given",
"property",
"and",
"annotation",
"."
] | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/inject/beans/visitor/BeanIntrospectionWriter.java#L164-L166 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java | ApiOvhDedicatedCloud.serviceName_federation_activeDirectory_activeDirectoryId_DELETE | public OvhTask serviceName_federation_activeDirectory_activeDirectoryId_DELETE(String serviceName, Long activeDirectoryId) throws IOException {
String qPath = "/dedicatedCloud/{serviceName}/federation/activeDirectory/{activeDirectoryId}";
StringBuilder sb = path(qPath, serviceName, activeDirectoryId);
String resp = exec(qPath, "DELETE", sb.toString(), null);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask serviceName_federation_activeDirectory_activeDirectoryId_DELETE(String serviceName, Long activeDirectoryId) throws IOException {
String qPath = "/dedicatedCloud/{serviceName}/federation/activeDirectory/{activeDirectoryId}";
StringBuilder sb = path(qPath, serviceName, activeDirectoryId);
String resp = exec(qPath, "DELETE", sb.toString(), null);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"serviceName_federation_activeDirectory_activeDirectoryId_DELETE",
"(",
"String",
"serviceName",
",",
"Long",
"activeDirectoryId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicatedCloud/{serviceName}/federation/activeDirectory/{activeDirect... | Remove an option user access
REST: DELETE /dedicatedCloud/{serviceName}/federation/activeDirectory/{activeDirectoryId}
@param serviceName [required] Domain of the service
@param activeDirectoryId [required] Id of the Active Directory | [
"Remove",
"an",
"option",
"user",
"access"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L1150-L1155 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java | ApiOvhDedicatedserver.serviceName_boot_bootId_option_GET | public ArrayList<OvhBootOptionEnum> serviceName_boot_bootId_option_GET(String serviceName, Long bootId) throws IOException {
String qPath = "/dedicated/server/{serviceName}/boot/{bootId}/option";
StringBuilder sb = path(qPath, serviceName, bootId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t13);
} | java | public ArrayList<OvhBootOptionEnum> serviceName_boot_bootId_option_GET(String serviceName, Long bootId) throws IOException {
String qPath = "/dedicated/server/{serviceName}/boot/{bootId}/option";
StringBuilder sb = path(qPath, serviceName, bootId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t13);
} | [
"public",
"ArrayList",
"<",
"OvhBootOptionEnum",
">",
"serviceName_boot_bootId_option_GET",
"(",
"String",
"serviceName",
",",
"Long",
"bootId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicated/server/{serviceName}/boot/{bootId}/option\"",
";",
"Stri... | Option used on this netboot
REST: GET /dedicated/server/{serviceName}/boot/{bootId}/option
@param serviceName [required] The internal name of your dedicated server
@param bootId [required] boot id | [
"Option",
"used",
"on",
"this",
"netboot"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L1814-L1819 |
Bandwidth/java-bandwidth | src/main/java/com/bandwidth/sdk/model/Conference.java | Conference.getMembers | public List<ConferenceMember> getMembers() throws Exception {
final String membersPath = StringUtils.join(new String[]{
getUri(),
"members"
}, '/');
final JSONArray array = toJSONArray(client.get(membersPath, null));
final List<ConferenceMember> members = new ArrayList<ConferenceMember>();
for (final Object obj : array) {
members.add(new ConferenceMember(client, (JSONObject) obj));
}
return members;
} | java | public List<ConferenceMember> getMembers() throws Exception {
final String membersPath = StringUtils.join(new String[]{
getUri(),
"members"
}, '/');
final JSONArray array = toJSONArray(client.get(membersPath, null));
final List<ConferenceMember> members = new ArrayList<ConferenceMember>();
for (final Object obj : array) {
members.add(new ConferenceMember(client, (JSONObject) obj));
}
return members;
} | [
"public",
"List",
"<",
"ConferenceMember",
">",
"getMembers",
"(",
")",
"throws",
"Exception",
"{",
"final",
"String",
"membersPath",
"=",
"StringUtils",
".",
"join",
"(",
"new",
"String",
"[",
"]",
"{",
"getUri",
"(",
")",
",",
"\"members\"",
"}",
",",
... | Gets list all members from a conference. If a member had already hung up or removed from conference it will be displayed as completed.
@return list of members
@throws IOException unexpected error. | [
"Gets",
"list",
"all",
"members",
"from",
"a",
"conference",
".",
"If",
"a",
"member",
"had",
"already",
"hung",
"up",
"or",
"removed",
"from",
"conference",
"it",
"will",
"be",
"displayed",
"as",
"completed",
"."
] | train | https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/model/Conference.java#L165-L177 |
RestComm/sipunit | src/main/java/org/cafesip/sipunit/SipAssert.java | SipAssert.assertHeaderNotContains | public static void assertHeaderNotContains(SipMessage sipMessage, String header, String value) {
assertHeaderNotContains(null, sipMessage, header, value);
} | java | public static void assertHeaderNotContains(SipMessage sipMessage, String header, String value) {
assertHeaderNotContains(null, sipMessage, header, value);
} | [
"public",
"static",
"void",
"assertHeaderNotContains",
"(",
"SipMessage",
"sipMessage",
",",
"String",
"header",
",",
"String",
"value",
")",
"{",
"assertHeaderNotContains",
"(",
"null",
",",
"sipMessage",
",",
"header",
",",
"value",
")",
";",
"}"
] | Asserts that the given SIP message contains no occurrence of the specified header with the
value given, or that there is no occurrence of the header in the message. The assertion fails
if any occurrence of the header contains the value.
@param sipMessage the SIP message.
@param header the string identifying the header as specified in RFC-3261.
@param value the string value within the header to look for. An exact string match is done
against the entire contents of the header. The assertion will fail if any part of the
header matches the value given. | [
"Asserts",
"that",
"the",
"given",
"SIP",
"message",
"contains",
"no",
"occurrence",
"of",
"the",
"specified",
"header",
"with",
"the",
"value",
"given",
"or",
"that",
"there",
"is",
"no",
"occurrence",
"of",
"the",
"header",
"in",
"the",
"message",
".",
"... | train | https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/SipAssert.java#L207-L209 |
google/closure-compiler | src/com/google/javascript/jscomp/PeepholeReplaceKnownMethods.java | PeepholeReplaceKnownMethods.tryFoldKnownNumericMethods | private Node tryFoldKnownNumericMethods(Node subtree, Node callTarget) {
checkArgument(subtree.isCall());
if (isASTNormalized()) {
// check if this is a call on a string method
// then dispatch to specific folding method.
String functionNameString = callTarget.getString();
Node firstArgument = callTarget.getNext();
if ((firstArgument != null) && (firstArgument.isString() || firstArgument.isNumber())
&& (functionNameString.equals("parseInt") || functionNameString.equals("parseFloat"))) {
subtree = tryFoldParseNumber(subtree, functionNameString, firstArgument);
}
}
return subtree;
} | java | private Node tryFoldKnownNumericMethods(Node subtree, Node callTarget) {
checkArgument(subtree.isCall());
if (isASTNormalized()) {
// check if this is a call on a string method
// then dispatch to specific folding method.
String functionNameString = callTarget.getString();
Node firstArgument = callTarget.getNext();
if ((firstArgument != null) && (firstArgument.isString() || firstArgument.isNumber())
&& (functionNameString.equals("parseInt") || functionNameString.equals("parseFloat"))) {
subtree = tryFoldParseNumber(subtree, functionNameString, firstArgument);
}
}
return subtree;
} | [
"private",
"Node",
"tryFoldKnownNumericMethods",
"(",
"Node",
"subtree",
",",
"Node",
"callTarget",
")",
"{",
"checkArgument",
"(",
"subtree",
".",
"isCall",
"(",
")",
")",
";",
"if",
"(",
"isASTNormalized",
"(",
")",
")",
"{",
"// check if this is a call on a s... | Try to evaluate known Numeric methods
parseInt(), parseFloat() | [
"Try",
"to",
"evaluate",
"known",
"Numeric",
"methods",
"parseInt",
"()",
"parseFloat",
"()"
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeReplaceKnownMethods.java#L284-L298 |
NessComputing/components-ness-jms | src/main/java/com/nesscomputing/jms/JmsRunnableFactory.java | JmsRunnableFactory.createTopicTextMessageListener | public TopicConsumer createTopicTextMessageListener(final String topic, final ConsumerCallback<String> messageCallback)
{
Preconditions.checkState(connectionFactory != null, "connection factory was never injected!");
return new TopicConsumer(connectionFactory, jmsConfig, topic, new TextMessageConsumerCallback(messageCallback));
} | java | public TopicConsumer createTopicTextMessageListener(final String topic, final ConsumerCallback<String> messageCallback)
{
Preconditions.checkState(connectionFactory != null, "connection factory was never injected!");
return new TopicConsumer(connectionFactory, jmsConfig, topic, new TextMessageConsumerCallback(messageCallback));
} | [
"public",
"TopicConsumer",
"createTopicTextMessageListener",
"(",
"final",
"String",
"topic",
",",
"final",
"ConsumerCallback",
"<",
"String",
">",
"messageCallback",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"connectionFactory",
"!=",
"null",
",",
"\"connect... | Creates a new {@link TopicConsumer}. For every text message received, the callback
is invoked with the contents of the text message as string. | [
"Creates",
"a",
"new",
"{"
] | train | https://github.com/NessComputing/components-ness-jms/blob/29e0d320ada3a1a375483437a9f3ff629822b714/src/main/java/com/nesscomputing/jms/JmsRunnableFactory.java#L144-L148 |
alkacon/opencms-core | src-modules/org/opencms/workplace/list/A_CmsListDialog.java | A_CmsListDialog.getMetadata | public synchronized CmsListMetadata getMetadata(String listDialogName, String listId) {
getSettings();
String metaDataKey = listDialogName + listId;
if ((getMetadataCache().get(metaDataKey) == null) || getMetadataCache().get(metaDataKey).isVolatile()) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_START_METADATA_LIST_1, getListId()));
}
CmsListMetadata metadata = new CmsListMetadata(listId);
setColumns(metadata);
// always check the search action
setSearchAction(metadata, m_searchColId);
setIndependentActions(metadata);
metadata.addIndependentAction(new CmsListPrintIAction());
setMultiActions(metadata);
metadata.checkIds();
getMetadataCache().put(metaDataKey, metadata);
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_END_METADATA_LIST_1, getListId()));
}
}
return getMetadata(metaDataKey);
} | java | public synchronized CmsListMetadata getMetadata(String listDialogName, String listId) {
getSettings();
String metaDataKey = listDialogName + listId;
if ((getMetadataCache().get(metaDataKey) == null) || getMetadataCache().get(metaDataKey).isVolatile()) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_START_METADATA_LIST_1, getListId()));
}
CmsListMetadata metadata = new CmsListMetadata(listId);
setColumns(metadata);
// always check the search action
setSearchAction(metadata, m_searchColId);
setIndependentActions(metadata);
metadata.addIndependentAction(new CmsListPrintIAction());
setMultiActions(metadata);
metadata.checkIds();
getMetadataCache().put(metaDataKey, metadata);
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_END_METADATA_LIST_1, getListId()));
}
}
return getMetadata(metaDataKey);
} | [
"public",
"synchronized",
"CmsListMetadata",
"getMetadata",
"(",
"String",
"listDialogName",
",",
"String",
"listId",
")",
"{",
"getSettings",
"(",
")",
";",
"String",
"metaDataKey",
"=",
"listDialogName",
"+",
"listId",
";",
"if",
"(",
"(",
"getMetadataCache",
... | Should generate the metadata definition for the list, and return the
corresponding <code>{@link CmsListMetadata}</code> object.<p>
@param listDialogName the name of the class generating the list
@param listId the id of the list
@return The metadata for the given list | [
"Should",
"generate",
"the",
"metadata",
"definition",
"for",
"the",
"list",
"and",
"return",
"the",
"corresponding",
"<code",
">",
"{",
"@link",
"CmsListMetadata",
"}",
"<",
"/",
"code",
">",
"object",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/list/A_CmsListDialog.java#L539-L563 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/AuthenticateApi.java | AuthenticateApi.removeEntryFromAuthCache | private void removeEntryFromAuthCache(HttpServletRequest req, HttpServletResponse res, WebAppSecurityConfig config) {
/*
* TODO: we need to optimize this method... if the authCacheService.remove() method
* return true for successfully removed the entry in the authentication cache, then we
* do not have to call the second method for token. See defect 66015
*/
removeEntryFromAuthCacheForUser(req, res);
removeEntryFromAuthCacheForToken(req, res, config);
} | java | private void removeEntryFromAuthCache(HttpServletRequest req, HttpServletResponse res, WebAppSecurityConfig config) {
/*
* TODO: we need to optimize this method... if the authCacheService.remove() method
* return true for successfully removed the entry in the authentication cache, then we
* do not have to call the second method for token. See defect 66015
*/
removeEntryFromAuthCacheForUser(req, res);
removeEntryFromAuthCacheForToken(req, res, config);
} | [
"private",
"void",
"removeEntryFromAuthCache",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"res",
",",
"WebAppSecurityConfig",
"config",
")",
"{",
"/*\n * TODO: we need to optimize this method... if the authCacheService.remove() method\n * return true fo... | Remove entries in the authentication cache
@param req
@param res
@param config | [
"Remove",
"entries",
"in",
"the",
"authentication",
"cache"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/AuthenticateApi.java#L322-L330 |
windup/windup | rules-base/api/src/main/java/org/jboss/windup/rules/files/condition/FileContent.java | FileContent.fileNameInput | private void fileNameInput(List<FileModel> vertices, GraphRewrite event, ParameterStore store)
{
if (this.filenamePattern != null)
{
Pattern filenameRegex = filenamePattern.getCompiledPattern(store);
//in case the filename is the first operation generating result, we can use the graph regex index. That's why we distinguish that in this clause
if (vertices.isEmpty() && StringUtils.isBlank(getInputVariablesName()))
{
FileService fileService = new FileService(event.getGraphContext());
for (FileModel fileModel : fileService.findByFilenameRegex(filenameRegex.pattern()))
{
vertices.add(fileModel);
}
}
else
{
ListIterator<FileModel> fileModelIterator = vertices.listIterator();
vertices.removeIf(fileModel -> !filenameRegex.matcher(fileModel.getFileName()).matches());
}
}
} | java | private void fileNameInput(List<FileModel> vertices, GraphRewrite event, ParameterStore store)
{
if (this.filenamePattern != null)
{
Pattern filenameRegex = filenamePattern.getCompiledPattern(store);
//in case the filename is the first operation generating result, we can use the graph regex index. That's why we distinguish that in this clause
if (vertices.isEmpty() && StringUtils.isBlank(getInputVariablesName()))
{
FileService fileService = new FileService(event.getGraphContext());
for (FileModel fileModel : fileService.findByFilenameRegex(filenameRegex.pattern()))
{
vertices.add(fileModel);
}
}
else
{
ListIterator<FileModel> fileModelIterator = vertices.listIterator();
vertices.removeIf(fileModel -> !filenameRegex.matcher(fileModel.getFileName()).matches());
}
}
} | [
"private",
"void",
"fileNameInput",
"(",
"List",
"<",
"FileModel",
">",
"vertices",
",",
"GraphRewrite",
"event",
",",
"ParameterStore",
"store",
")",
"{",
"if",
"(",
"this",
".",
"filenamePattern",
"!=",
"null",
")",
"{",
"Pattern",
"filenameRegex",
"=",
"f... | Generating the input vertices is quite complex. Therefore there are multiple methods that handles the input vertices based on the attribute
specified in specific order. This method handles the {@link FileContent#inFileNamed(String)} attribute. | [
"Generating",
"the",
"input",
"vertices",
"is",
"quite",
"complex",
".",
"Therefore",
"there",
"are",
"multiple",
"methods",
"that",
"handles",
"the",
"input",
"vertices",
"based",
"on",
"the",
"attribute",
"specified",
"in",
"specific",
"order",
".",
"This",
... | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-base/api/src/main/java/org/jboss/windup/rules/files/condition/FileContent.java#L303-L323 |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Locales.java | Locales.getLocale | public static Locale getLocale(final String localeString) {
final String language = getLanguage(localeString);
final String country = getCountry(localeString);
// // XXX: variant
return new Locale(language, country);
} | java | public static Locale getLocale(final String localeString) {
final String language = getLanguage(localeString);
final String country = getCountry(localeString);
// // XXX: variant
return new Locale(language, country);
} | [
"public",
"static",
"Locale",
"getLocale",
"(",
"final",
"String",
"localeString",
")",
"{",
"final",
"String",
"language",
"=",
"getLanguage",
"(",
"localeString",
")",
";",
"final",
"String",
"country",
"=",
"getCountry",
"(",
"localeString",
")",
";",
"// /... | Gest a {@link java.util.Locale} with the specified locale string.
@param localeString the specified locale string
@return locale | [
"Gest",
"a",
"{",
"@link",
"java",
".",
"util",
".",
"Locale",
"}",
"with",
"the",
"specified",
"locale",
"string",
"."
] | train | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Locales.java#L223-L229 |
landawn/AbacusUtil | src/com/landawn/abacus/util/JdbcUtil.java | JdbcUtil.importData | public static <E extends Exception> long importData(final File file, final long offset, final long count, final PreparedStatement stmt, final int batchSize,
final int batchInterval, final Try.Function<String, Object[], E> func) throws UncheckedSQLException, E {
Reader reader = null;
try {
reader = new FileReader(file);
return importData(reader, offset, count, stmt, batchSize, batchInterval, func);
} catch (IOException e) {
throw new UncheckedIOException(e);
} finally {
IOUtil.close(reader);
}
} | java | public static <E extends Exception> long importData(final File file, final long offset, final long count, final PreparedStatement stmt, final int batchSize,
final int batchInterval, final Try.Function<String, Object[], E> func) throws UncheckedSQLException, E {
Reader reader = null;
try {
reader = new FileReader(file);
return importData(reader, offset, count, stmt, batchSize, batchInterval, func);
} catch (IOException e) {
throw new UncheckedIOException(e);
} finally {
IOUtil.close(reader);
}
} | [
"public",
"static",
"<",
"E",
"extends",
"Exception",
">",
"long",
"importData",
"(",
"final",
"File",
"file",
",",
"final",
"long",
"offset",
",",
"final",
"long",
"count",
",",
"final",
"PreparedStatement",
"stmt",
",",
"final",
"int",
"batchSize",
",",
... | Imports the data from file to database.
@param file
@param offset
@param count
@param stmt
@param batchSize
@param batchInterval
@param func convert line to the parameters for record insert. Returns a <code>null</code> array to skip the line.
@return
@throws UncheckedSQLException | [
"Imports",
"the",
"data",
"from",
"file",
"to",
"database",
"."
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/JdbcUtil.java#L2532-L2545 |
alkacon/opencms-core | src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java | CmsDefaultXmlContentHandler.initMappings | protected void initMappings(Element root, CmsXmlContentDefinition contentDefinition) throws CmsXmlException {
Iterator<Element> i = CmsXmlGenericWrapper.elementIterator(root, APPINFO_MAPPING);
while (i.hasNext()) {
// iterate all "mapping" elements in the "mappings" node
Element element = i.next();
// this is a mapping node
String elementName = element.attributeValue(APPINFO_ATTR_ELEMENT);
String maptoName = element.attributeValue(APPINFO_ATTR_MAPTO);
String useDefault = element.attributeValue(APPINFO_ATTR_USE_DEFAULT);
if ((elementName != null) && (maptoName != null)) {
// add the element mapping
addMapping(contentDefinition, elementName, maptoName, useDefault);
}
}
} | java | protected void initMappings(Element root, CmsXmlContentDefinition contentDefinition) throws CmsXmlException {
Iterator<Element> i = CmsXmlGenericWrapper.elementIterator(root, APPINFO_MAPPING);
while (i.hasNext()) {
// iterate all "mapping" elements in the "mappings" node
Element element = i.next();
// this is a mapping node
String elementName = element.attributeValue(APPINFO_ATTR_ELEMENT);
String maptoName = element.attributeValue(APPINFO_ATTR_MAPTO);
String useDefault = element.attributeValue(APPINFO_ATTR_USE_DEFAULT);
if ((elementName != null) && (maptoName != null)) {
// add the element mapping
addMapping(contentDefinition, elementName, maptoName, useDefault);
}
}
} | [
"protected",
"void",
"initMappings",
"(",
"Element",
"root",
",",
"CmsXmlContentDefinition",
"contentDefinition",
")",
"throws",
"CmsXmlException",
"{",
"Iterator",
"<",
"Element",
">",
"i",
"=",
"CmsXmlGenericWrapper",
".",
"elementIterator",
"(",
"root",
",",
"APP... | Initializes the element mappings for this content handler.<p>
Element mappings allow storing values from the XML content in other locations.
For example, if you have an element called "Title", it's likely a good idea to
store the value of this element also in the "Title" property of a XML content resource.<p>
@param root the "mappings" element from the appinfo node of the XML content definition
@param contentDefinition the content definition the mappings belong to
@throws CmsXmlException if something goes wrong | [
"Initializes",
"the",
"element",
"mappings",
"for",
"this",
"content",
"handler",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java#L2737-L2752 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/fs/FSOutputSummer.java | FSOutputSummer.write1 | private int write1(byte b[], int off, int len) throws IOException {
eventStartWrite();
try {
if(count==0 && bytesSentInChunk + len>=buf.length) {
// local buffer is empty and user data can fill the current chunk
// checksum and output data
final int length = buf.length - bytesSentInChunk;
sum.update(b, off, length);
writeChecksumChunk(b, off, length, false);
// start a new chunk
bytesSentInChunk = 0;
return length;
}
// copy user data to local buffer
int bytesToCopy = buf.length - bytesSentInChunk - count;
bytesToCopy = (len<bytesToCopy) ? len : bytesToCopy;
sum.update(b, off, bytesToCopy);
System.arraycopy(b, off, buf, count, bytesToCopy);
count += bytesToCopy;
if (count + bytesSentInChunk == buf.length) {
// local buffer is full
flushBuffer(true, shouldKeepPartialChunkData());
}
return bytesToCopy;
} finally {
eventEndWrite();
}
} | java | private int write1(byte b[], int off, int len) throws IOException {
eventStartWrite();
try {
if(count==0 && bytesSentInChunk + len>=buf.length) {
// local buffer is empty and user data can fill the current chunk
// checksum and output data
final int length = buf.length - bytesSentInChunk;
sum.update(b, off, length);
writeChecksumChunk(b, off, length, false);
// start a new chunk
bytesSentInChunk = 0;
return length;
}
// copy user data to local buffer
int bytesToCopy = buf.length - bytesSentInChunk - count;
bytesToCopy = (len<bytesToCopy) ? len : bytesToCopy;
sum.update(b, off, bytesToCopy);
System.arraycopy(b, off, buf, count, bytesToCopy);
count += bytesToCopy;
if (count + bytesSentInChunk == buf.length) {
// local buffer is full
flushBuffer(true, shouldKeepPartialChunkData());
}
return bytesToCopy;
} finally {
eventEndWrite();
}
} | [
"private",
"int",
"write1",
"(",
"byte",
"b",
"[",
"]",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"eventStartWrite",
"(",
")",
";",
"try",
"{",
"if",
"(",
"count",
"==",
"0",
"&&",
"bytesSentInChunk",
"+",
"len",
">=",
... | Write a portion of an array, flushing to the underlying
stream at most once if necessary. | [
"Write",
"a",
"portion",
"of",
"an",
"array",
"flushing",
"to",
"the",
"underlying",
"stream",
"at",
"most",
"once",
"if",
"necessary",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/FSOutputSummer.java#L118-L147 |
lestard/assertj-javafx | src/main/java/eu/lestard/assertj/javafx/api/ReadOnlyDoublePropertyAssert.java | ReadOnlyDoublePropertyAssert.hasValue | public ReadOnlyDoublePropertyAssert hasValue(Double expectedValue, Offset offset){
new ObservableNumberValueAssertions(actual).hasValue(expectedValue, offset);
return this;
} | java | public ReadOnlyDoublePropertyAssert hasValue(Double expectedValue, Offset offset){
new ObservableNumberValueAssertions(actual).hasValue(expectedValue, offset);
return this;
} | [
"public",
"ReadOnlyDoublePropertyAssert",
"hasValue",
"(",
"Double",
"expectedValue",
",",
"Offset",
"offset",
")",
"{",
"new",
"ObservableNumberValueAssertions",
"(",
"actual",
")",
".",
"hasValue",
"(",
"expectedValue",
",",
"offset",
")",
";",
"return",
"this",
... | Verifies that the actual observable number has a value that is close to the given one by less then the given offset.
@param expectedValue the given value to compare the actual observables value to.
@param offset the given positive offset.
@return {@code this} assertion object.
@throws java.lang.NullPointerException if the given offset is <code>null</code>.
@throws java.lang.AssertionError if the actual observables value is not equal to the expected one. | [
"Verifies",
"that",
"the",
"actual",
"observable",
"number",
"has",
"a",
"value",
"that",
"is",
"close",
"to",
"the",
"given",
"one",
"by",
"less",
"then",
"the",
"given",
"offset",
"."
] | train | https://github.com/lestard/assertj-javafx/blob/f6b4d22e542a5501c7c1c2fae8700b0f69b956c1/src/main/java/eu/lestard/assertj/javafx/api/ReadOnlyDoublePropertyAssert.java#L46-L50 |
litsec/swedish-eid-shibboleth-base | shibboleth-base/shibboleth-extensions/src/main/java/se/litsec/shibboleth/idp/authn/service/impl/ProxyIdpAuthnContextServiceImpl.java | ProxyIdpAuthnContextServiceImpl.isIssuedAuthnContextClassRefAccepted | protected boolean isIssuedAuthnContextClassRefAccepted(ProfileRequestContext<?, ?> context, String authnContextUri) {
try {
List<String> requested = this.getAuthnContextClassContext(context).getProxiedAuthnContextClassRefs();
if (requested == null || requested.isEmpty()) {
// If we did not request anything, we accept what we got.
return true;
}
return requested.contains(authnContextUri);
}
catch (ExternalAutenticationErrorCodeException e) {
// Will fail later
return false;
}
} | java | protected boolean isIssuedAuthnContextClassRefAccepted(ProfileRequestContext<?, ?> context, String authnContextUri) {
try {
List<String> requested = this.getAuthnContextClassContext(context).getProxiedAuthnContextClassRefs();
if (requested == null || requested.isEmpty()) {
// If we did not request anything, we accept what we got.
return true;
}
return requested.contains(authnContextUri);
}
catch (ExternalAutenticationErrorCodeException e) {
// Will fail later
return false;
}
} | [
"protected",
"boolean",
"isIssuedAuthnContextClassRefAccepted",
"(",
"ProfileRequestContext",
"<",
"?",
",",
"?",
">",
"context",
",",
"String",
"authnContextUri",
")",
"{",
"try",
"{",
"List",
"<",
"String",
">",
"requested",
"=",
"this",
".",
"getAuthnContextCla... | Depending on the type of matching of AuthnContextClassRef URI:s that is used we check whether an issued URI is what
we can accept (corresponds to what we requested).
<p>
The default implementation used "exact" matching.
</p>
@param context
the request context
@param authnContextUri
the URI received in the assertion from the remote IdP
@return if the URI is accepted {@code true} is returned, otherwise {@code false} | [
"Depending",
"on",
"the",
"type",
"of",
"matching",
"of",
"AuthnContextClassRef",
"URI",
":",
"s",
"that",
"is",
"used",
"we",
"check",
"whether",
"an",
"issued",
"URI",
"is",
"what",
"we",
"can",
"accept",
"(",
"corresponds",
"to",
"what",
"we",
"requeste... | train | https://github.com/litsec/swedish-eid-shibboleth-base/blob/aaaa467ff61f07d7dfa31627fb36851a37da6804/shibboleth-base/shibboleth-extensions/src/main/java/se/litsec/shibboleth/idp/authn/service/impl/ProxyIdpAuthnContextServiceImpl.java#L235-L249 |
citrusframework/citrus | modules/citrus-kafka/src/main/java/com/consol/citrus/kafka/embedded/EmbeddedKafkaServer.java | EmbeddedKafkaServer.createLogDir | protected File createLogDir() {
File logDir = Optional.ofNullable(logDirPath)
.map(Paths::get)
.map(Path::toFile)
.orElse(new File(System.getProperty("java.io.tmpdir")));
if (!logDir.exists()) {
if (!logDir.mkdirs()) {
log.warn("Unable to create log directory: " + logDir.getAbsolutePath());
logDir = new File(System.getProperty("java.io.tmpdir"));
log.info("Using default log directory: " + logDir.getAbsolutePath());
}
}
File logs = new File(logDir, "zookeeper" + System.currentTimeMillis()).getAbsoluteFile();
if (autoDeleteLogs) {
logs.deleteOnExit();
}
return logs;
} | java | protected File createLogDir() {
File logDir = Optional.ofNullable(logDirPath)
.map(Paths::get)
.map(Path::toFile)
.orElse(new File(System.getProperty("java.io.tmpdir")));
if (!logDir.exists()) {
if (!logDir.mkdirs()) {
log.warn("Unable to create log directory: " + logDir.getAbsolutePath());
logDir = new File(System.getProperty("java.io.tmpdir"));
log.info("Using default log directory: " + logDir.getAbsolutePath());
}
}
File logs = new File(logDir, "zookeeper" + System.currentTimeMillis()).getAbsoluteFile();
if (autoDeleteLogs) {
logs.deleteOnExit();
}
return logs;
} | [
"protected",
"File",
"createLogDir",
"(",
")",
"{",
"File",
"logDir",
"=",
"Optional",
".",
"ofNullable",
"(",
"logDirPath",
")",
".",
"map",
"(",
"Paths",
"::",
"get",
")",
".",
"map",
"(",
"Path",
"::",
"toFile",
")",
".",
"orElse",
"(",
"new",
"Fi... | Creates Zookeeper log directory. By default logs are created in Java temp directory.
By default directory is automatically deleted on exit.
@return | [
"Creates",
"Zookeeper",
"log",
"directory",
".",
"By",
"default",
"logs",
"are",
"created",
"in",
"Java",
"temp",
"directory",
".",
"By",
"default",
"directory",
"is",
"automatically",
"deleted",
"on",
"exit",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-kafka/src/main/java/com/consol/citrus/kafka/embedded/EmbeddedKafkaServer.java#L178-L199 |
lucee/Lucee | core/src/main/java/lucee/runtime/functions/conversion/SerializeJSON.java | SerializeJSON.call | public static String call(PageContext pc, Object var, boolean serializeQueryByColumns) throws PageException {
return _call(pc, var, serializeQueryByColumns, pc.getWebCharset());
} | java | public static String call(PageContext pc, Object var, boolean serializeQueryByColumns) throws PageException {
return _call(pc, var, serializeQueryByColumns, pc.getWebCharset());
} | [
"public",
"static",
"String",
"call",
"(",
"PageContext",
"pc",
",",
"Object",
"var",
",",
"boolean",
"serializeQueryByColumns",
")",
"throws",
"PageException",
"{",
"return",
"_call",
"(",
"pc",
",",
"var",
",",
"serializeQueryByColumns",
",",
"pc",
".",
"get... | FUTURE remove, this methods are only used by compiled code in archives older than 5.2.3 | [
"FUTURE",
"remove",
"this",
"methods",
"are",
"only",
"used",
"by",
"compiled",
"code",
"in",
"archives",
"older",
"than",
"5",
".",
"2",
".",
"3"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/functions/conversion/SerializeJSON.java#L56-L58 |
mojohaus/jaxb2-maven-plugin | src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/DomHelper.java | DomHelper.getMethodLocation | public static MethodLocation getMethodLocation(final Node aNode, final Set<MethodLocation> methodLocations) {
MethodLocation toReturn = null;
if (aNode != null && CLASS_FIELD_METHOD_ELEMENT_NAMES.contains(aNode.getLocalName().toLowerCase())) {
final MethodLocation validLocation = getFieldOrMethodLocationIfValid(aNode,
getContainingClassOrNull(aNode),
methodLocations);
// The MethodLocation should represent a normal getter; no arguments should be present.
if (validLocation != null
&& MethodLocation.NO_PARAMETERS.equalsIgnoreCase(validLocation.getParametersAsString())) {
toReturn = validLocation;
}
}
// All done.
return toReturn;
} | java | public static MethodLocation getMethodLocation(final Node aNode, final Set<MethodLocation> methodLocations) {
MethodLocation toReturn = null;
if (aNode != null && CLASS_FIELD_METHOD_ELEMENT_NAMES.contains(aNode.getLocalName().toLowerCase())) {
final MethodLocation validLocation = getFieldOrMethodLocationIfValid(aNode,
getContainingClassOrNull(aNode),
methodLocations);
// The MethodLocation should represent a normal getter; no arguments should be present.
if (validLocation != null
&& MethodLocation.NO_PARAMETERS.equalsIgnoreCase(validLocation.getParametersAsString())) {
toReturn = validLocation;
}
}
// All done.
return toReturn;
} | [
"public",
"static",
"MethodLocation",
"getMethodLocation",
"(",
"final",
"Node",
"aNode",
",",
"final",
"Set",
"<",
"MethodLocation",
">",
"methodLocations",
")",
"{",
"MethodLocation",
"toReturn",
"=",
"null",
";",
"if",
"(",
"aNode",
"!=",
"null",
"&&",
"CLA... | Finds the MethodLocation within the given Set, which corresponds to the supplied DOM Node.
@param aNode A DOM Node.
@param methodLocations The Set of all found/known MethodLocation instances.
@return The MethodLocation matching the supplied Node - or {@code null} if no match was found. | [
"Finds",
"the",
"MethodLocation",
"within",
"the",
"given",
"Set",
"which",
"corresponds",
"to",
"the",
"supplied",
"DOM",
"Node",
"."
] | train | https://github.com/mojohaus/jaxb2-maven-plugin/blob/e3c4e47943b15282e5a6e850bbfb1588d8452a0a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/DomHelper.java#L253-L272 |
percolate/caffeine | caffeine/src/main/java/com/percolate/caffeine/ActivityUtils.java | ActivityUtils.getExtraString | public static String getExtraString(Activity context, String key) {
String param = "";
Bundle bundle = context.getIntent().getExtras();
if (bundle != null) {
param = bundle.getString(key);
}
return param;
} | java | public static String getExtraString(Activity context, String key) {
String param = "";
Bundle bundle = context.getIntent().getExtras();
if (bundle != null) {
param = bundle.getString(key);
}
return param;
} | [
"public",
"static",
"String",
"getExtraString",
"(",
"Activity",
"context",
",",
"String",
"key",
")",
"{",
"String",
"param",
"=",
"\"\"",
";",
"Bundle",
"bundle",
"=",
"context",
".",
"getIntent",
"(",
")",
".",
"getExtras",
"(",
")",
";",
"if",
"(",
... | Used to get the parameter values passed into Activity via a Bundle.
@return param Parameter value | [
"Used",
"to",
"get",
"the",
"parameter",
"values",
"passed",
"into",
"Activity",
"via",
"a",
"Bundle",
"."
] | train | https://github.com/percolate/caffeine/blob/e2265cab474a6397f4d75b1ed928c356a7b9672e/caffeine/src/main/java/com/percolate/caffeine/ActivityUtils.java#L59-L66 |
fnklabs/draenei | src/main/java/com/fnklabs/draenei/orm/DataProvider.java | DataProvider.createBoundStatement | @NotNull
private BoundStatement createBoundStatement(@NotNull PreparedStatement prepare, @NotNull V entity, @NotNull List<ColumnMetadata> columns) {
BoundStatement boundStatement = new BoundStatement(prepare);
boundStatement.setConsistencyLevel(getEntityMetadata().getWriteConsistencyLevel());
for (int i = 0; i < columns.size(); i++) {
ColumnMetadata column = columns.get(i);
Object value = column.readValue(entity);
boundStatement.setBytesUnsafe(i, column.serialize(value));
}
return boundStatement;
} | java | @NotNull
private BoundStatement createBoundStatement(@NotNull PreparedStatement prepare, @NotNull V entity, @NotNull List<ColumnMetadata> columns) {
BoundStatement boundStatement = new BoundStatement(prepare);
boundStatement.setConsistencyLevel(getEntityMetadata().getWriteConsistencyLevel());
for (int i = 0; i < columns.size(); i++) {
ColumnMetadata column = columns.get(i);
Object value = column.readValue(entity);
boundStatement.setBytesUnsafe(i, column.serialize(value));
}
return boundStatement;
} | [
"@",
"NotNull",
"private",
"BoundStatement",
"createBoundStatement",
"(",
"@",
"NotNull",
"PreparedStatement",
"prepare",
",",
"@",
"NotNull",
"V",
"entity",
",",
"@",
"NotNull",
"List",
"<",
"ColumnMetadata",
">",
"columns",
")",
"{",
"BoundStatement",
"boundStat... | Create BoundStatement from PreparedStatement and bind parameter values from entity
@param prepare PreparedStatement
@param entity Entity from which will be read data
@param columns Bind columns
@return BoundStatement | [
"Create",
"BoundStatement",
"from",
"PreparedStatement",
"and",
"bind",
"parameter",
"values",
"from",
"entity"
] | train | https://github.com/fnklabs/draenei/blob/0a8cac54f1f635be3e2950375a23291d38453ae8/src/main/java/com/fnklabs/draenei/orm/DataProvider.java#L569-L583 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java | CommonOps_DDRM.multAddTransAB | public static void multAddTransAB(DMatrix1Row a , DMatrix1Row b , DMatrix1Row c )
{
if( b.numRows == 1 ) {
// there are significantly faster algorithms when dealing with vectors
if( a.numCols >= EjmlParameters.MULT_COLUMN_SWITCH ) {
MatrixVectorMult_DDRM.multAddTransA_reorder(a,b,c);
} else {
MatrixVectorMult_DDRM.multAddTransA_small(a,b,c);
}
} else if( a.numCols >= EjmlParameters.MULT_TRANAB_COLUMN_SWITCH ) {
MatrixMatrixMult_DDRM.multAddTransAB_aux(a,b,c,null);
} else {
MatrixMatrixMult_DDRM.multAddTransAB(a,b,c);
}
} | java | public static void multAddTransAB(DMatrix1Row a , DMatrix1Row b , DMatrix1Row c )
{
if( b.numRows == 1 ) {
// there are significantly faster algorithms when dealing with vectors
if( a.numCols >= EjmlParameters.MULT_COLUMN_SWITCH ) {
MatrixVectorMult_DDRM.multAddTransA_reorder(a,b,c);
} else {
MatrixVectorMult_DDRM.multAddTransA_small(a,b,c);
}
} else if( a.numCols >= EjmlParameters.MULT_TRANAB_COLUMN_SWITCH ) {
MatrixMatrixMult_DDRM.multAddTransAB_aux(a,b,c,null);
} else {
MatrixMatrixMult_DDRM.multAddTransAB(a,b,c);
}
} | [
"public",
"static",
"void",
"multAddTransAB",
"(",
"DMatrix1Row",
"a",
",",
"DMatrix1Row",
"b",
",",
"DMatrix1Row",
"c",
")",
"{",
"if",
"(",
"b",
".",
"numRows",
"==",
"1",
")",
"{",
"// there are significantly faster algorithms when dealing with vectors",
"if",
... | <p>
Performs the following operation:<br>
<br>
c = c + a<sup>T</sup> * b<sup>T</sup><br>
c<sub>ij</sub> = c<sub>ij</sub> + ∑<sub>k=1:n</sub> { a<sub>ki</sub> * b<sub>jk</sub>}
</p>
@param a The left matrix in the multiplication operation. Not Modified.
@param b The right matrix in the multiplication operation. Not Modified.
@param c Where the results of the operation are stored. Modified. | [
"<p",
">",
"Performs",
"the",
"following",
"operation",
":",
"<br",
">",
"<br",
">",
"c",
"=",
"c",
"+",
"a<sup",
">",
"T<",
"/",
"sup",
">",
"*",
"b<sup",
">",
"T<",
"/",
"sup",
">",
"<br",
">",
"c<sub",
">",
"ij<",
"/",
"sub",
">",
"=",
"c<... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L471-L485 |
structlogging/structlogger | structlogger/src/main/java/com/github/structlogging/processor/LogInvocationScanner.java | LogInvocationScanner.addToUsedVariables | private void addToUsedVariables(final java.util.List<VariableAndValue> usedVariables, final MethodAndParameter top, final Variable variable) {
VariableAndValue variableAndValue = new VariableAndValue(variable, top.getParameter());
if (!usedVariables.contains(variableAndValue)) {
usedVariables.add(variableAndValue);
} else {
int i = 0;
do {
i++;
variableAndValue = new VariableAndValue(
new Variable(
elementUtils.getName(variable.getName().toString() + i),
variable.getType()
),
top.getParameter()
);
} while (usedVariables.contains(variableAndValue));
usedVariables.add(variableAndValue);
}
} | java | private void addToUsedVariables(final java.util.List<VariableAndValue> usedVariables, final MethodAndParameter top, final Variable variable) {
VariableAndValue variableAndValue = new VariableAndValue(variable, top.getParameter());
if (!usedVariables.contains(variableAndValue)) {
usedVariables.add(variableAndValue);
} else {
int i = 0;
do {
i++;
variableAndValue = new VariableAndValue(
new Variable(
elementUtils.getName(variable.getName().toString() + i),
variable.getType()
),
top.getParameter()
);
} while (usedVariables.contains(variableAndValue));
usedVariables.add(variableAndValue);
}
} | [
"private",
"void",
"addToUsedVariables",
"(",
"final",
"java",
".",
"util",
".",
"List",
"<",
"VariableAndValue",
">",
"usedVariables",
",",
"final",
"MethodAndParameter",
"top",
",",
"final",
"Variable",
"variable",
")",
"{",
"VariableAndValue",
"variableAndValue",... | with incremented name, e.g. if used variables are A,B and we want to add A, it is added as A1 | [
"with",
"incremented",
"name",
"e",
".",
"g",
".",
"if",
"used",
"variables",
"are",
"A",
"B",
"and",
"we",
"want",
"to",
"add",
"A",
"it",
"is",
"added",
"as",
"A1"
] | train | https://github.com/structlogging/structlogger/blob/1fcca4e962ef53cbdb94bd72cb556de7f5f9469f/structlogger/src/main/java/com/github/structlogging/processor/LogInvocationScanner.java#L363-L381 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/paragraphvectors/ParagraphVectors.java | ParagraphVectors.inferVector | public INDArray inferVector(@NonNull List<VocabWord> document) {
return inferVector(document, this.learningRate.get(), this.minLearningRate,
this.numEpochs * this.numIterations);
} | java | public INDArray inferVector(@NonNull List<VocabWord> document) {
return inferVector(document, this.learningRate.get(), this.minLearningRate,
this.numEpochs * this.numIterations);
} | [
"public",
"INDArray",
"inferVector",
"(",
"@",
"NonNull",
"List",
"<",
"VocabWord",
">",
"document",
")",
"{",
"return",
"inferVector",
"(",
"document",
",",
"this",
".",
"learningRate",
".",
"get",
"(",
")",
",",
"this",
".",
"minLearningRate",
",",
"this... | This method calculates inferred vector for given list of words, with default parameters for learning rate and iterations
@param document
@return | [
"This",
"method",
"calculates",
"inferred",
"vector",
"for",
"given",
"list",
"of",
"words",
"with",
"default",
"parameters",
"for",
"learning",
"rate",
"and",
"iterations"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/paragraphvectors/ParagraphVectors.java#L313-L316 |
Metatavu/edelphi | edelphi-persistence/src/main/java/fi/metatavu/edelphi/dao/resources/GoogleImageDAO.java | GoogleImageDAO.updateName | public GoogleImage updateName(GoogleImage googleImage, String name, String urlName) {
googleImage.setName(name);
googleImage.setUrlName(urlName);
getEntityManager().persist(googleImage);
return googleImage;
} | java | public GoogleImage updateName(GoogleImage googleImage, String name, String urlName) {
googleImage.setName(name);
googleImage.setUrlName(urlName);
getEntityManager().persist(googleImage);
return googleImage;
} | [
"public",
"GoogleImage",
"updateName",
"(",
"GoogleImage",
"googleImage",
",",
"String",
"name",
",",
"String",
"urlName",
")",
"{",
"googleImage",
".",
"setName",
"(",
"name",
")",
";",
"googleImage",
".",
"setUrlName",
"(",
"urlName",
")",
";",
"getEntityMan... | Updates GoogleImage name. This method does not update lastModifier and lastModified fields and thus should
be called only by system operations (e.g. scheduler)
@param googleImage GoogleImage entity
@param name new resource name
@param urlName new resource urlName
@return Updated GoogleImage | [
"Updates",
"GoogleImage",
"name",
".",
"This",
"method",
"does",
"not",
"update",
"lastModifier",
"and",
"lastModified",
"fields",
"and",
"thus",
"should",
"be",
"called",
"only",
"by",
"system",
"operations",
"(",
"e",
".",
"g",
".",
"scheduler",
")"
] | train | https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi-persistence/src/main/java/fi/metatavu/edelphi/dao/resources/GoogleImageDAO.java#L73-L78 |
rundeck/rundeck | core/src/main/java/com/dtolabs/rundeck/core/execution/ExecArgList.java | ExecArgList.buildCommandForNode | @Deprecated
public ArrayList<String> buildCommandForNode(Map<String, Map<String, String>> dataContext, String osFamily) {
return buildCommandForNode(this, dataContext, osFamily);
} | java | @Deprecated
public ArrayList<String> buildCommandForNode(Map<String, Map<String, String>> dataContext, String osFamily) {
return buildCommandForNode(this, dataContext, osFamily);
} | [
"@",
"Deprecated",
"public",
"ArrayList",
"<",
"String",
">",
"buildCommandForNode",
"(",
"Map",
"<",
"String",
",",
"Map",
"<",
"String",
",",
"String",
">",
">",
"dataContext",
",",
"String",
"osFamily",
")",
"{",
"return",
"buildCommandForNode",
"(",
"thi... | Generate the quoted and expanded argument list, by expanding property values given the data context, and quoting
for the given OS
@param dataContext property value data context
@param osFamily OS family to determine quoting
@return list of strings | [
"Generate",
"the",
"quoted",
"and",
"expanded",
"argument",
"list",
"by",
"expanding",
"property",
"values",
"given",
"the",
"data",
"context",
"and",
"quoting",
"for",
"the",
"given",
"OS"
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/ExecArgList.java#L140-L143 |
apache/groovy | src/main/java/org/codehaus/groovy/reflection/ReflectionUtils.java | ReflectionUtils.getCallingClass | public static Class getCallingClass(int matchLevel, Collection<String> extraIgnoredPackages) {
Class[] classContext = HELPER.getClassContext();
int depth = 0;
try {
Class c;
// this super class stuff is for Java 1.4 support only
// it isn't needed on a 5.0 VM
Class sc;
do {
do {
c = classContext[depth++];
if (c != null) {
sc = c.getSuperclass();
} else {
sc = null;
}
} while (classShouldBeIgnored(c, extraIgnoredPackages)
|| superClassShouldBeIgnored(sc));
} while (c != null && matchLevel-- > 0 && depth<classContext.length);
return c;
} catch (Throwable t) {
return null;
}
} | java | public static Class getCallingClass(int matchLevel, Collection<String> extraIgnoredPackages) {
Class[] classContext = HELPER.getClassContext();
int depth = 0;
try {
Class c;
// this super class stuff is for Java 1.4 support only
// it isn't needed on a 5.0 VM
Class sc;
do {
do {
c = classContext[depth++];
if (c != null) {
sc = c.getSuperclass();
} else {
sc = null;
}
} while (classShouldBeIgnored(c, extraIgnoredPackages)
|| superClassShouldBeIgnored(sc));
} while (c != null && matchLevel-- > 0 && depth<classContext.length);
return c;
} catch (Throwable t) {
return null;
}
} | [
"public",
"static",
"Class",
"getCallingClass",
"(",
"int",
"matchLevel",
",",
"Collection",
"<",
"String",
">",
"extraIgnoredPackages",
")",
"{",
"Class",
"[",
"]",
"classContext",
"=",
"HELPER",
".",
"getClassContext",
"(",
")",
";",
"int",
"depth",
"=",
"... | Get the called that is matchLevel stack frames before the call,
ignoring MOP frames and desired exclude packages.
@param matchLevel how may call stacks down to look.
If it is less than 1 it is treated as though it was 1.
@param extraIgnoredPackages A collection of string names of packages to exclude
in addition to the MOP packages when counting stack frames.
@return The Class of the matched caller, or null if there aren't
enough stackframes to satisfy matchLevel | [
"Get",
"the",
"called",
"that",
"is",
"matchLevel",
"stack",
"frames",
"before",
"the",
"call",
"ignoring",
"MOP",
"frames",
"and",
"desired",
"exclude",
"packages",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/reflection/ReflectionUtils.java#L97-L121 |
eFaps/eFaps-Kernel | src/main/java/org/efaps/admin/AbstractAdminObject.java | AbstractAdminObject.readFromDB4Properties | protected void readFromDB4Properties()
throws CacheReloadException
{
Connection con = null;
try {
con = Context.getConnection();
final PreparedStatement stmt = con.prepareStatement(AbstractAdminObject.SELECT);
stmt.setObject(1, getId());
final ResultSet rs = stmt.executeQuery();
AbstractAdminObject.LOG.debug("Reading Properties for '{}'", getName());
while (rs.next()) {
final String nameStr = rs.getString(1).trim();
final String value = rs.getString(2).trim();
setProperty(nameStr, value);
AbstractAdminObject.LOG.debug(" Name: '{}' - Value: '{}'", new Object[] { nameStr, value });
}
rs.close();
stmt.close();
con.commit();
con.close();
} catch (final SQLException e) {
throw new CacheReloadException("could not read properties for " + "'" + getName() + "'", e);
} catch (final EFapsException e) {
throw new CacheReloadException("could not read properties for " + "'" + getName() + "'", e);
} finally {
try {
if (con != null && !con.isClosed()) {
con.close();
}
} catch (final SQLException e) {
throw new CacheReloadException("Cannot read a type for an attribute.", e);
}
}
} | java | protected void readFromDB4Properties()
throws CacheReloadException
{
Connection con = null;
try {
con = Context.getConnection();
final PreparedStatement stmt = con.prepareStatement(AbstractAdminObject.SELECT);
stmt.setObject(1, getId());
final ResultSet rs = stmt.executeQuery();
AbstractAdminObject.LOG.debug("Reading Properties for '{}'", getName());
while (rs.next()) {
final String nameStr = rs.getString(1).trim();
final String value = rs.getString(2).trim();
setProperty(nameStr, value);
AbstractAdminObject.LOG.debug(" Name: '{}' - Value: '{}'", new Object[] { nameStr, value });
}
rs.close();
stmt.close();
con.commit();
con.close();
} catch (final SQLException e) {
throw new CacheReloadException("could not read properties for " + "'" + getName() + "'", e);
} catch (final EFapsException e) {
throw new CacheReloadException("could not read properties for " + "'" + getName() + "'", e);
} finally {
try {
if (con != null && !con.isClosed()) {
con.close();
}
} catch (final SQLException e) {
throw new CacheReloadException("Cannot read a type for an attribute.", e);
}
}
} | [
"protected",
"void",
"readFromDB4Properties",
"(",
")",
"throws",
"CacheReloadException",
"{",
"Connection",
"con",
"=",
"null",
";",
"try",
"{",
"con",
"=",
"Context",
".",
"getConnection",
"(",
")",
";",
"final",
"PreparedStatement",
"stmt",
"=",
"con",
".",... | The instance method reads the properties for this administration object.
Each found property is set with instance method {@link #setProperty}.
@throws CacheReloadException on error
@see #setProperty | [
"The",
"instance",
"method",
"reads",
"the",
"properties",
"for",
"this",
"administration",
"object",
".",
"Each",
"found",
"property",
"is",
"set",
"with",
"instance",
"method",
"{",
"@link",
"#setProperty",
"}",
"."
] | train | https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/admin/AbstractAdminObject.java#L385-L418 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/util/AABBUtils.java | AABBUtils.readFromNBT | public static AxisAlignedBB readFromNBT(NBTTagCompound tag, String prefix)
{
prefix = prefix == null ? "" : prefix + ".";
return tag != null ? new AxisAlignedBB(tag.getDouble(prefix + "minX"),
tag.getDouble(prefix + "minY"),
tag.getDouble(prefix + "minZ"),
tag.getDouble(prefix + "maxX"),
tag.getDouble(prefix + "maxY"),
tag.getDouble(prefix + "maxZ"))
: null;
} | java | public static AxisAlignedBB readFromNBT(NBTTagCompound tag, String prefix)
{
prefix = prefix == null ? "" : prefix + ".";
return tag != null ? new AxisAlignedBB(tag.getDouble(prefix + "minX"),
tag.getDouble(prefix + "minY"),
tag.getDouble(prefix + "minZ"),
tag.getDouble(prefix + "maxX"),
tag.getDouble(prefix + "maxY"),
tag.getDouble(prefix + "maxZ"))
: null;
} | [
"public",
"static",
"AxisAlignedBB",
"readFromNBT",
"(",
"NBTTagCompound",
"tag",
",",
"String",
"prefix",
")",
"{",
"prefix",
"=",
"prefix",
"==",
"null",
"?",
"\"\"",
":",
"prefix",
"+",
"\".\"",
";",
"return",
"tag",
"!=",
"null",
"?",
"new",
"AxisAlign... | Reads a {@link AxisAlignedBB} from {@link NBTTagCompound} with the specified prefix.
@param tag the tag
@param prefix the prefix
@return the axis aligned bb | [
"Reads",
"a",
"{",
"@link",
"AxisAlignedBB",
"}",
"from",
"{",
"@link",
"NBTTagCompound",
"}",
"with",
"the",
"specified",
"prefix",
"."
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/util/AABBUtils.java#L236-L246 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java | ComputerVisionImpl.generateThumbnail | public InputStream generateThumbnail(int width, int height, String url, GenerateThumbnailOptionalParameter generateThumbnailOptionalParameter) {
return generateThumbnailWithServiceResponseAsync(width, height, url, generateThumbnailOptionalParameter).toBlocking().single().body();
} | java | public InputStream generateThumbnail(int width, int height, String url, GenerateThumbnailOptionalParameter generateThumbnailOptionalParameter) {
return generateThumbnailWithServiceResponseAsync(width, height, url, generateThumbnailOptionalParameter).toBlocking().single().body();
} | [
"public",
"InputStream",
"generateThumbnail",
"(",
"int",
"width",
",",
"int",
"height",
",",
"String",
"url",
",",
"GenerateThumbnailOptionalParameter",
"generateThumbnailOptionalParameter",
")",
"{",
"return",
"generateThumbnailWithServiceResponseAsync",
"(",
"width",
","... | This operation generates a thumbnail image with the user-specified width and height. By default, the service analyzes the image, identifies the region of interest (ROI), and generates smart cropping coordinates based on the ROI. Smart cropping helps when you specify an aspect ratio that differs from that of the input image. A successful response contains the thumbnail image binary. If the request failed, the response contains an error code and a message to help determine what went wrong.
@param width Width of the thumbnail. It must be between 1 and 1024. Recommended minimum of 50.
@param height Height of the thumbnail. It must be between 1 and 1024. Recommended minimum of 50.
@param url Publicly reachable URL of an image
@param generateThumbnailOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the InputStream object if successful. | [
"This",
"operation",
"generates",
"a",
"thumbnail",
"image",
"with",
"the",
"user",
"-",
"specified",
"width",
"and",
"height",
".",
"By",
"default",
"the",
"service",
"analyzes",
"the",
"image",
"identifies",
"the",
"region",
"of",
"interest",
"(",
"ROI",
"... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java#L2066-L2068 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/TypeVariableImpl.java | TypeVariableImpl.typeVarToString | static String typeVarToString(DocEnv env, TypeVar v, boolean full) {
StringBuilder s = new StringBuilder(v.toString());
List<Type> bounds = getBounds(v, env);
if (bounds.nonEmpty()) {
boolean first = true;
for (Type b : bounds) {
s.append(first ? " extends " : " & ");
s.append(TypeMaker.getTypeString(env, b, full));
first = false;
}
}
return s.toString();
} | java | static String typeVarToString(DocEnv env, TypeVar v, boolean full) {
StringBuilder s = new StringBuilder(v.toString());
List<Type> bounds = getBounds(v, env);
if (bounds.nonEmpty()) {
boolean first = true;
for (Type b : bounds) {
s.append(first ? " extends " : " & ");
s.append(TypeMaker.getTypeString(env, b, full));
first = false;
}
}
return s.toString();
} | [
"static",
"String",
"typeVarToString",
"(",
"DocEnv",
"env",
",",
"TypeVar",
"v",
",",
"boolean",
"full",
")",
"{",
"StringBuilder",
"s",
"=",
"new",
"StringBuilder",
"(",
"v",
".",
"toString",
"(",
")",
")",
";",
"List",
"<",
"Type",
">",
"bounds",
"=... | Return the string form of a type variable along with any
"extends" clause. Class names are qualified if "full" is true. | [
"Return",
"the",
"string",
"form",
"of",
"a",
"type",
"variable",
"along",
"with",
"any",
"extends",
"clause",
".",
"Class",
"names",
"are",
"qualified",
"if",
"full",
"is",
"true",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/TypeVariableImpl.java#L109-L121 |
UrielCh/ovh-java-sdk | ovh-java-sdk-supplymondialRelay/src/main/java/net/minidev/ovh/api/ApiOvhSupplymondialRelay.java | ApiOvhSupplymondialRelay.POST | public OvhMondialRelayReturn POST(String address, String city, OvhCountryEnum country, String zipcode) throws IOException {
String qPath = "/supply/mondialRelay";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "address", address);
addBody(o, "city", city);
addBody(o, "country", country);
addBody(o, "zipcode", zipcode);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhMondialRelayReturn.class);
} | java | public OvhMondialRelayReturn POST(String address, String city, OvhCountryEnum country, String zipcode) throws IOException {
String qPath = "/supply/mondialRelay";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "address", address);
addBody(o, "city", city);
addBody(o, "country", country);
addBody(o, "zipcode", zipcode);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhMondialRelayReturn.class);
} | [
"public",
"OvhMondialRelayReturn",
"POST",
"(",
"String",
"address",
",",
"String",
"city",
",",
"OvhCountryEnum",
"country",
",",
"String",
"zipcode",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/supply/mondialRelay\"",
";",
"StringBuilder",
"sb",... | Find the 10 nearest MondialRelay points from address or city.
REST: POST /supply/mondialRelay
@param city [required] City
@param address [required] Address
@param country [required] ISO country code
@param zipcode [required] Zip Code | [
"Find",
"the",
"10",
"nearest",
"MondialRelay",
"points",
"from",
"address",
"or",
"city",
"."
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-supplymondialRelay/src/main/java/net/minidev/ovh/api/ApiOvhSupplymondialRelay.java#L29-L39 |
jdillon/gshell | gshell-launcher/src/main/java/com/planet57/gshell/launcher/Configuration.java | Configuration.getProperty | @Nullable
private String getProperty(final String name) {
assert name != null;
ensureConfigured();
return evaluate(System.getProperty(name, props.getProperty(name)));
} | java | @Nullable
private String getProperty(final String name) {
assert name != null;
ensureConfigured();
return evaluate(System.getProperty(name, props.getProperty(name)));
} | [
"@",
"Nullable",
"private",
"String",
"getProperty",
"(",
"final",
"String",
"name",
")",
"{",
"assert",
"name",
"!=",
"null",
";",
"ensureConfigured",
"(",
")",
";",
"return",
"evaluate",
"(",
"System",
".",
"getProperty",
"(",
"name",
",",
"props",
".",
... | Get the value of a property, checking system properties, then configuration properties and evaluating the result. | [
"Get",
"the",
"value",
"of",
"a",
"property",
"checking",
"system",
"properties",
"then",
"configuration",
"properties",
"and",
"evaluating",
"the",
"result",
"."
] | train | https://github.com/jdillon/gshell/blob/b587c1a4672d2e4905871462fa3b38a1f7b94e90/gshell-launcher/src/main/java/com/planet57/gshell/launcher/Configuration.java#L141-L146 |
languagetool-org/languagetool | languagetool-core/src/main/java/org/languagetool/markup/AnnotatedTextBuilder.java | AnnotatedTextBuilder.build | public AnnotatedText build() {
int plainTextPosition = 0;
int totalPosition = 0;
Map<Integer,Integer> mapping = new HashMap<>();
mapping.put(0, 0);
for (TextPart part : parts) {
if (part.getType() == TextPart.Type.TEXT) {
plainTextPosition += part.getPart().length();
totalPosition += part.getPart().length();
} else if (part.getType() == TextPart.Type.MARKUP) {
totalPosition += part.getPart().length();
} else if (part.getType() == TextPart.Type.FAKE_CONTENT) {
plainTextPosition += part.getPart().length();
}
mapping.put(plainTextPosition, totalPosition);
}
return new AnnotatedText(parts, mapping, metaData, customMetaData);
} | java | public AnnotatedText build() {
int plainTextPosition = 0;
int totalPosition = 0;
Map<Integer,Integer> mapping = new HashMap<>();
mapping.put(0, 0);
for (TextPart part : parts) {
if (part.getType() == TextPart.Type.TEXT) {
plainTextPosition += part.getPart().length();
totalPosition += part.getPart().length();
} else if (part.getType() == TextPart.Type.MARKUP) {
totalPosition += part.getPart().length();
} else if (part.getType() == TextPart.Type.FAKE_CONTENT) {
plainTextPosition += part.getPart().length();
}
mapping.put(plainTextPosition, totalPosition);
}
return new AnnotatedText(parts, mapping, metaData, customMetaData);
} | [
"public",
"AnnotatedText",
"build",
"(",
")",
"{",
"int",
"plainTextPosition",
"=",
"0",
";",
"int",
"totalPosition",
"=",
"0",
";",
"Map",
"<",
"Integer",
",",
"Integer",
">",
"mapping",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"mapping",
".",
"put... | Create the annotated text to be passed into {@link org.languagetool.JLanguageTool#check(AnnotatedText)}. | [
"Create",
"the",
"annotated",
"text",
"to",
"be",
"passed",
"into",
"{"
] | train | https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/markup/AnnotatedTextBuilder.java#L113-L130 |
EMCECS/nfs-client-java | src/main/java/com/emc/ecs/nfsclient/rpc/RpcWrapper.java | RpcWrapper.callRpc | public Xdr callRpc(String serverIP, Xdr xdrRequest, boolean usePrivilegedPort) throws RpcException {
return NetMgr.getInstance().sendAndWait(serverIP, _port, usePrivilegedPort, xdrRequest, _rpcTimeout);
} | java | public Xdr callRpc(String serverIP, Xdr xdrRequest, boolean usePrivilegedPort) throws RpcException {
return NetMgr.getInstance().sendAndWait(serverIP, _port, usePrivilegedPort, xdrRequest, _rpcTimeout);
} | [
"public",
"Xdr",
"callRpc",
"(",
"String",
"serverIP",
",",
"Xdr",
"xdrRequest",
",",
"boolean",
"usePrivilegedPort",
")",
"throws",
"RpcException",
"{",
"return",
"NetMgr",
".",
"getInstance",
"(",
")",
".",
"sendAndWait",
"(",
"serverIP",
",",
"_port",
",",
... | Basic RPC call functionality only.
@param serverIP
The endpoint of the server being called.
@param xdrRequest
The Xdr data for the request.
@param usePrivilegedPort
<ul>
<li>If <code>true</code>, use a privileged local port (below
1024) for RPC communication.</li>
<li>If <code>false</code>, use any non-privileged local port
for RPC communication.</li>
</ul>
@return The Xdr data for the response.
@throws RpcException | [
"Basic",
"RPC",
"call",
"functionality",
"only",
"."
] | train | https://github.com/EMCECS/nfs-client-java/blob/7ba25bad5052b95cd286052745327729288b2843/src/main/java/com/emc/ecs/nfsclient/rpc/RpcWrapper.java#L227-L229 |
CODAIT/stocator | src/main/java/com/ibm/stocator/fs/cos/COSInputStream.java | COSInputStream.closeStream | private void closeStream(String reason, long length, boolean forceAbort) {
if (wrappedStream != null) {
// if the amount of data remaining in the current request is greater
// than the readahead value: abort.
long remaining = remainingInCurrentRequest();
LOG.debug("Closing stream {}: {}", reason,
forceAbort ? "abort" : "soft");
boolean shouldAbort = forceAbort || remaining > readahead;
if (!shouldAbort) {
try {
// clean close. This will read to the end of the stream,
// so, while cleaner, can be pathological on a multi-GB object
// explicitly drain the stream
long drained = 0;
while (wrappedStream.read() >= 0) {
drained++;
}
LOG.debug("Drained stream of {} bytes", drained);
// now close it
wrappedStream.close();
// this MUST come after the close, so that if the IO operations fail
// and an abort is triggered, the initial attempt's statistics
// aren't collected.
} catch (IOException e) {
// exception escalates to an abort
LOG.debug("When closing {} stream for {}", uri, reason, e);
shouldAbort = true;
}
}
if (shouldAbort) {
// Abort, rather than just close, the underlying stream. Otherwise, the
// remaining object payload is read from S3 while closing the stream.
LOG.debug("Aborting stream");
wrappedStream.abort();
}
LOG.debug("Stream {} {}: {}; remaining={} streamPos={},"
+ " nextReadPos={},"
+ " request range {}-{} length={}",
uri, (shouldAbort ? "aborted" : "closed"), reason,
remaining, pos, nextReadPos,
contentRangeStart, contentRangeFinish,
length);
wrappedStream = null;
}
} | java | private void closeStream(String reason, long length, boolean forceAbort) {
if (wrappedStream != null) {
// if the amount of data remaining in the current request is greater
// than the readahead value: abort.
long remaining = remainingInCurrentRequest();
LOG.debug("Closing stream {}: {}", reason,
forceAbort ? "abort" : "soft");
boolean shouldAbort = forceAbort || remaining > readahead;
if (!shouldAbort) {
try {
// clean close. This will read to the end of the stream,
// so, while cleaner, can be pathological on a multi-GB object
// explicitly drain the stream
long drained = 0;
while (wrappedStream.read() >= 0) {
drained++;
}
LOG.debug("Drained stream of {} bytes", drained);
// now close it
wrappedStream.close();
// this MUST come after the close, so that if the IO operations fail
// and an abort is triggered, the initial attempt's statistics
// aren't collected.
} catch (IOException e) {
// exception escalates to an abort
LOG.debug("When closing {} stream for {}", uri, reason, e);
shouldAbort = true;
}
}
if (shouldAbort) {
// Abort, rather than just close, the underlying stream. Otherwise, the
// remaining object payload is read from S3 while closing the stream.
LOG.debug("Aborting stream");
wrappedStream.abort();
}
LOG.debug("Stream {} {}: {}; remaining={} streamPos={},"
+ " nextReadPos={},"
+ " request range {}-{} length={}",
uri, (shouldAbort ? "aborted" : "closed"), reason,
remaining, pos, nextReadPos,
contentRangeStart, contentRangeFinish,
length);
wrappedStream = null;
}
} | [
"private",
"void",
"closeStream",
"(",
"String",
"reason",
",",
"long",
"length",
",",
"boolean",
"forceAbort",
")",
"{",
"if",
"(",
"wrappedStream",
"!=",
"null",
")",
"{",
"// if the amount of data remaining in the current request is greater",
"// than the readahead val... | Close a stream: decide whether to abort or close, based on
the length of the stream and the current position.
If a close() is attempted and fails, the operation escalates to
an abort.
This does not set the {@link #closed} flag.
@param reason reason for stream being closed; used in messages
@param length length of the stream
@param forceAbort force an abort; used if explicitly requested | [
"Close",
"a",
"stream",
":",
"decide",
"whether",
"to",
"abort",
"or",
"close",
"based",
"on",
"the",
"length",
"of",
"the",
"stream",
"and",
"the",
"current",
"position",
".",
"If",
"a",
"close",
"()",
"is",
"attempted",
"and",
"fails",
"the",
"operatio... | train | https://github.com/CODAIT/stocator/blob/35969cadd2e8faa6fdac45e8bec1799fdd3d8299/src/main/java/com/ibm/stocator/fs/cos/COSInputStream.java#L390-L437 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/WorldToCameraToPixel.java | WorldToCameraToPixel.transform | public boolean transform( Point3D_F64 worldPt , Point2D_F64 pixelPt ) {
SePointOps_F64.transform(worldToCamera,worldPt,cameraPt);
// can't see the point
if( cameraPt.z <= 0 )
return false;
normToPixel.compute(cameraPt.x/cameraPt.z, cameraPt.y/cameraPt.z, pixelPt);
return true;
} | java | public boolean transform( Point3D_F64 worldPt , Point2D_F64 pixelPt ) {
SePointOps_F64.transform(worldToCamera,worldPt,cameraPt);
// can't see the point
if( cameraPt.z <= 0 )
return false;
normToPixel.compute(cameraPt.x/cameraPt.z, cameraPt.y/cameraPt.z, pixelPt);
return true;
} | [
"public",
"boolean",
"transform",
"(",
"Point3D_F64",
"worldPt",
",",
"Point2D_F64",
"pixelPt",
")",
"{",
"SePointOps_F64",
".",
"transform",
"(",
"worldToCamera",
",",
"worldPt",
",",
"cameraPt",
")",
";",
"// can't see the point",
"if",
"(",
"cameraPt",
".",
"... | Computes the observed location of the specified point in world coordinates in the camera pixel. If
the object can't be viewed because it is behind the camera then false is returned.
@param worldPt Location of point in world frame
@param pixelPt Pixel observation of point.
@return True if visible (+z) or false if not visible (-z) | [
"Computes",
"the",
"observed",
"location",
"of",
"the",
"specified",
"point",
"in",
"world",
"coordinates",
"in",
"the",
"camera",
"pixel",
".",
"If",
"the",
"object",
"can",
"t",
"be",
"viewed",
"because",
"it",
"is",
"behind",
"the",
"camera",
"then",
"f... | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/WorldToCameraToPixel.java#L80-L89 |
atomix/copycat | server/src/main/java/io/atomix/copycat/server/storage/Storage.java | Storage.openMetaStore | public MetaStore openMetaStore(String name) {
return new MetaStore(name, this, ThreadContext.currentContextOrThrow().serializer().clone());
} | java | public MetaStore openMetaStore(String name) {
return new MetaStore(name, this, ThreadContext.currentContextOrThrow().serializer().clone());
} | [
"public",
"MetaStore",
"openMetaStore",
"(",
"String",
"name",
")",
"{",
"return",
"new",
"MetaStore",
"(",
"name",
",",
"this",
",",
"ThreadContext",
".",
"currentContextOrThrow",
"(",
")",
".",
"serializer",
"(",
")",
".",
"clone",
"(",
")",
")",
";",
... | Opens a new {@link MetaStore}, recovering metadata from disk if it exists.
<p>
The meta store will be loaded using based on the configured {@link StorageLevel}. If the storage level is persistent
then the meta store will be loaded from disk, otherwise a new meta store will be created.
@param name The metastore name.
@return The metastore. | [
"Opens",
"a",
"new",
"{",
"@link",
"MetaStore",
"}",
"recovering",
"metadata",
"from",
"disk",
"if",
"it",
"exists",
".",
"<p",
">",
"The",
"meta",
"store",
"will",
"be",
"loaded",
"using",
"based",
"on",
"the",
"configured",
"{",
"@link",
"StorageLevel",
... | train | https://github.com/atomix/copycat/blob/c90b88ccd5c63d6ea0b49fb77c25e2f3272a7b10/server/src/main/java/io/atomix/copycat/server/storage/Storage.java#L264-L266 |
tvesalainen/lpg | src/main/java/org/vesalainen/grammar/state/NFAState.java | NFAState.hasTransitionTo | public boolean hasTransitionTo(CharRange condition, NFAState<T> state)
{
Set<Transition<NFAState<T>>> set = transitions.get(condition);
if (set != null)
{
for (Transition<NFAState<T>> tr : set)
{
if (state.equals(tr.getTo()))
{
return true;
}
}
}
return false;
} | java | public boolean hasTransitionTo(CharRange condition, NFAState<T> state)
{
Set<Transition<NFAState<T>>> set = transitions.get(condition);
if (set != null)
{
for (Transition<NFAState<T>> tr : set)
{
if (state.equals(tr.getTo()))
{
return true;
}
}
}
return false;
} | [
"public",
"boolean",
"hasTransitionTo",
"(",
"CharRange",
"condition",
",",
"NFAState",
"<",
"T",
">",
"state",
")",
"{",
"Set",
"<",
"Transition",
"<",
"NFAState",
"<",
"T",
">>>",
"set",
"=",
"transitions",
".",
"get",
"(",
"condition",
")",
";",
"if",... | Returns true if transition with condition to state exists
@param condition
@param state
@return | [
"Returns",
"true",
"if",
"transition",
"with",
"condition",
"to",
"state",
"exists"
] | train | https://github.com/tvesalainen/lpg/blob/0917b8d295e9772b9f8a0affc258a08530cd567a/src/main/java/org/vesalainen/grammar/state/NFAState.java#L126-L140 |
Guichaguri/MinimalFTP | src/main/java/com/guichaguri/minimalftp/FTPServer.java | FTPServer.listenSync | public void listenSync(InetAddress address, int port) throws IOException {
if(auth == null) throw new NullPointerException("The Authenticator is null");
if(socket != null) throw new IOException("Server already started");
socket = Utils.createServer(port, 50, address, ssl, !explicitSecurity);
while(!socket.isClosed()) {
update();
}
} | java | public void listenSync(InetAddress address, int port) throws IOException {
if(auth == null) throw new NullPointerException("The Authenticator is null");
if(socket != null) throw new IOException("Server already started");
socket = Utils.createServer(port, 50, address, ssl, !explicitSecurity);
while(!socket.isClosed()) {
update();
}
} | [
"public",
"void",
"listenSync",
"(",
"InetAddress",
"address",
",",
"int",
"port",
")",
"throws",
"IOException",
"{",
"if",
"(",
"auth",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
"(",
"\"The Authenticator is null\"",
")",
";",
"if",
"(",
"sock... | Starts the FTP server synchronously, blocking the current thread.
Connections to the server will still create new threads.
@param address The server address or {@code null} for a local address
@param port The server port or {@code 0} to automatically allocate the port
@throws IOException When an error occurs while starting the server | [
"Starts",
"the",
"FTP",
"server",
"synchronously",
"blocking",
"the",
"current",
"thread",
"."
] | train | https://github.com/Guichaguri/MinimalFTP/blob/ddd81e26ec88079ee4c37fe53d8efe420996e9b1/src/main/java/com/guichaguri/minimalftp/FTPServer.java#L229-L238 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/convert/Convert.java | Convert.toEnum | public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value, E defaultValue) {
return (new GenericEnumConverter<>(clazz)).convert(value, defaultValue);
} | java | public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value, E defaultValue) {
return (new GenericEnumConverter<>(clazz)).convert(value, defaultValue);
} | [
"public",
"static",
"<",
"E",
"extends",
"Enum",
"<",
"E",
">",
">",
"E",
"toEnum",
"(",
"Class",
"<",
"E",
">",
"clazz",
",",
"Object",
"value",
",",
"E",
"defaultValue",
")",
"{",
"return",
"(",
"new",
"GenericEnumConverter",
"<>",
"(",
"clazz",
")... | 转换为Enum对象<br>
如果给定的值为空,或者转换失败,返回默认值<br>
@param <E> 枚举类型
@param clazz Enum的Class
@param value 值
@param defaultValue 默认值
@return Enum | [
"转换为Enum对象<br",
">",
"如果给定的值为空,或者转换失败,返回默认值<br",
">"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/convert/Convert.java#L474-L476 |
apache/incubator-gobblin | gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanAjaxAPIClient.java | AzkabanAjaxAPIClient.getScheduledTimeInAzkabanFormat | @edu.umd.cs.findbugs.annotations.SuppressWarnings(
value = "DMI_RANDOM_USED_ONLY_ONCE",
justification = "As expected for randomization")
public static String getScheduledTimeInAzkabanFormat(int windowStartHour, int windowEndHour, int delayMinutes) {
// Validate
if (windowStartHour < 0 || windowEndHour > 23 || windowStartHour >= windowEndHour) {
throw new IllegalArgumentException("Window start should be less than window end, and both should be between "
+ "0 and 23");
}
if (delayMinutes < 0 || delayMinutes > 59) {
throw new IllegalArgumentException("Delay in minutes should be between 0 and 59 (inclusive)");
}
// Setup window
Calendar windowStartTime = Calendar.getInstance();
windowStartTime.set(Calendar.HOUR_OF_DAY, windowStartHour);
windowStartTime.set(Calendar.MINUTE, 0);
windowStartTime.set(Calendar.SECOND, 0);
Calendar windowEndTime = Calendar.getInstance();
windowEndTime.set(Calendar.HOUR_OF_DAY, windowEndHour);
windowEndTime.set(Calendar.MINUTE, 0);
windowEndTime.set(Calendar.SECOND, 0);
// Check if current time is between windowStartTime and windowEndTime, then let the execution happen
// after delayMinutes minutes
Calendar now = Calendar.getInstance();
if (now.after(windowStartTime) && now.before(windowEndTime)) {
// Azkaban takes a few seconds / a minute to bootstrap,
// so extra few minutes get the first execution to run instantly
now.add(Calendar.MINUTE, delayMinutes);
return new SimpleDateFormat("hh,mm,a,z").format(now.getTime());
}
// Current time is not between windowStartTime and windowEndTime, so get random execution time for next day
int allowedSchedulingWindow = (int)((windowEndTime.getTimeInMillis() - windowStartTime.getTimeInMillis()) /
MILLISECONDS_IN_HOUR);
int randomHourInWindow = new Random(System.currentTimeMillis()).nextInt(allowedSchedulingWindow);
int randomMinute = new Random(System.currentTimeMillis()).nextInt(60);
windowStartTime.add(Calendar.HOUR, randomHourInWindow);
windowStartTime.set(Calendar.MINUTE, randomMinute);
return new SimpleDateFormat("hh,mm,a,z").format(windowStartTime.getTime());
} | java | @edu.umd.cs.findbugs.annotations.SuppressWarnings(
value = "DMI_RANDOM_USED_ONLY_ONCE",
justification = "As expected for randomization")
public static String getScheduledTimeInAzkabanFormat(int windowStartHour, int windowEndHour, int delayMinutes) {
// Validate
if (windowStartHour < 0 || windowEndHour > 23 || windowStartHour >= windowEndHour) {
throw new IllegalArgumentException("Window start should be less than window end, and both should be between "
+ "0 and 23");
}
if (delayMinutes < 0 || delayMinutes > 59) {
throw new IllegalArgumentException("Delay in minutes should be between 0 and 59 (inclusive)");
}
// Setup window
Calendar windowStartTime = Calendar.getInstance();
windowStartTime.set(Calendar.HOUR_OF_DAY, windowStartHour);
windowStartTime.set(Calendar.MINUTE, 0);
windowStartTime.set(Calendar.SECOND, 0);
Calendar windowEndTime = Calendar.getInstance();
windowEndTime.set(Calendar.HOUR_OF_DAY, windowEndHour);
windowEndTime.set(Calendar.MINUTE, 0);
windowEndTime.set(Calendar.SECOND, 0);
// Check if current time is between windowStartTime and windowEndTime, then let the execution happen
// after delayMinutes minutes
Calendar now = Calendar.getInstance();
if (now.after(windowStartTime) && now.before(windowEndTime)) {
// Azkaban takes a few seconds / a minute to bootstrap,
// so extra few minutes get the first execution to run instantly
now.add(Calendar.MINUTE, delayMinutes);
return new SimpleDateFormat("hh,mm,a,z").format(now.getTime());
}
// Current time is not between windowStartTime and windowEndTime, so get random execution time for next day
int allowedSchedulingWindow = (int)((windowEndTime.getTimeInMillis() - windowStartTime.getTimeInMillis()) /
MILLISECONDS_IN_HOUR);
int randomHourInWindow = new Random(System.currentTimeMillis()).nextInt(allowedSchedulingWindow);
int randomMinute = new Random(System.currentTimeMillis()).nextInt(60);
windowStartTime.add(Calendar.HOUR, randomHourInWindow);
windowStartTime.set(Calendar.MINUTE, randomMinute);
return new SimpleDateFormat("hh,mm,a,z").format(windowStartTime.getTime());
} | [
"@",
"edu",
".",
"umd",
".",
"cs",
".",
"findbugs",
".",
"annotations",
".",
"SuppressWarnings",
"(",
"value",
"=",
"\"DMI_RANDOM_USED_ONLY_ONCE\"",
",",
"justification",
"=",
"\"As expected for randomization\"",
")",
"public",
"static",
"String",
"getScheduledTimeInA... | *
Generate a random scheduled time between specified execution time window in the Azkaban compatible format
which is: hh,mm,a,z Eg. ScheduleTime=12,00,PM,PDT
@param windowStartHour Window start hour in 24 hr (HH) format (inclusive)
@param windowEndHour Window end hour in 24 hr (HH) format (exclusive)
@param delayMinutes If current time is within window, then additional delay for bootstrapping if desired
@return Scheduled time string of the format hh,mm,a,z | [
"*",
"Generate",
"a",
"random",
"scheduled",
"time",
"between",
"specified",
"execution",
"time",
"window",
"in",
"the",
"Azkaban",
"compatible",
"format",
"which",
"is",
":",
"hh",
"mm",
"a",
"z",
"Eg",
".",
"ScheduleTime",
"=",
"12",
"00",
"PM",
"PDT"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanAjaxAPIClient.java#L427-L471 |
dmurph/jgoogleanalyticstracker | src/main/java/com/dmurph/tracking/JGoogleAnalyticsTracker.java | JGoogleAnalyticsTracker.trackPageViewFromSearch | public void trackPageViewFromSearch(String argPageURL, String argPageTitle, String argHostName, String argSearchSource, String argSearchKeywords) {
if (argPageURL == null) {
throw new IllegalArgumentException("Page URL cannot be null, Google will not track the data.");
}
AnalyticsRequestData data = new AnalyticsRequestData();
data.setHostName(argHostName);
data.setPageTitle(argPageTitle);
data.setPageURL(argPageURL);
data.setSearchReferrer(argSearchSource, argSearchKeywords);
makeCustomRequest(data);
} | java | public void trackPageViewFromSearch(String argPageURL, String argPageTitle, String argHostName, String argSearchSource, String argSearchKeywords) {
if (argPageURL == null) {
throw new IllegalArgumentException("Page URL cannot be null, Google will not track the data.");
}
AnalyticsRequestData data = new AnalyticsRequestData();
data.setHostName(argHostName);
data.setPageTitle(argPageTitle);
data.setPageURL(argPageURL);
data.setSearchReferrer(argSearchSource, argSearchKeywords);
makeCustomRequest(data);
} | [
"public",
"void",
"trackPageViewFromSearch",
"(",
"String",
"argPageURL",
",",
"String",
"argPageTitle",
",",
"String",
"argHostName",
",",
"String",
"argSearchSource",
",",
"String",
"argSearchKeywords",
")",
"{",
"if",
"(",
"argPageURL",
"==",
"null",
")",
"{",
... | Tracks a page view.
@param argPageURL
required, Google won't track without it. Ex:
<code>"org/me/javaclass.java"</code>, or anything you want as
the page url.
@param argPageTitle
content title
@param argHostName
the host name for the url
@param argSearchSource
source of the search engine. ex: google
@param argSearchKeywords
the keywords of the search. ex: java google analytics tracking
utility | [
"Tracks",
"a",
"page",
"view",
"."
] | train | https://github.com/dmurph/jgoogleanalyticstracker/blob/69f68caf8e09a53e6f6076477bf05b84bc80e386/src/main/java/com/dmurph/tracking/JGoogleAnalyticsTracker.java#L345-L355 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PermissionsImpl.java | PermissionsImpl.addAsync | public Observable<OperationStatus> addAsync(UUID appId, AddPermissionsOptionalParameter addOptionalParameter) {
return addWithServiceResponseAsync(appId, addOptionalParameter).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
} | java | public Observable<OperationStatus> addAsync(UUID appId, AddPermissionsOptionalParameter addOptionalParameter) {
return addWithServiceResponseAsync(appId, addOptionalParameter).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"OperationStatus",
">",
"addAsync",
"(",
"UUID",
"appId",
",",
"AddPermissionsOptionalParameter",
"addOptionalParameter",
")",
"{",
"return",
"addWithServiceResponseAsync",
"(",
"appId",
",",
"addOptionalParameter",
")",
".",
"map",
"(",
"... | Adds a user to the allowed list of users to access this LUIS application. Users are added using their email address.
@param appId The application ID.
@param addOptionalParameter 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 OperationStatus object | [
"Adds",
"a",
"user",
"to",
"the",
"allowed",
"list",
"of",
"users",
"to",
"access",
"this",
"LUIS",
"application",
".",
"Users",
"are",
"added",
"using",
"their",
"email",
"address",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PermissionsImpl.java#L200-L207 |
graphql-java/graphql-java | src/main/java/graphql/util/FpKit.java | FpKit.getByName | public static <T> Map<String, T> getByName(List<T> namedObjects, Function<T, String> nameFn) {
return getByName(namedObjects, nameFn, mergeFirst());
} | java | public static <T> Map<String, T> getByName(List<T> namedObjects, Function<T, String> nameFn) {
return getByName(namedObjects, nameFn, mergeFirst());
} | [
"public",
"static",
"<",
"T",
">",
"Map",
"<",
"String",
",",
"T",
">",
"getByName",
"(",
"List",
"<",
"T",
">",
"namedObjects",
",",
"Function",
"<",
"T",
",",
"String",
">",
"nameFn",
")",
"{",
"return",
"getByName",
"(",
"namedObjects",
",",
"name... | From a list of named things, get a map of them by name, merging them first one added | [
"From",
"a",
"list",
"of",
"named",
"things",
"get",
"a",
"map",
"of",
"them",
"by",
"name",
"merging",
"them",
"first",
"one",
"added"
] | train | https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/util/FpKit.java#L47-L49 |
Azure/azure-sdk-for-java | network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java | NetworkWatchersInner.beginListAvailableProvidersAsync | public Observable<AvailableProvidersListInner> beginListAvailableProvidersAsync(String resourceGroupName, String networkWatcherName, AvailableProvidersListParameters parameters) {
return beginListAvailableProvidersWithServiceResponseAsync(resourceGroupName, networkWatcherName, parameters).map(new Func1<ServiceResponse<AvailableProvidersListInner>, AvailableProvidersListInner>() {
@Override
public AvailableProvidersListInner call(ServiceResponse<AvailableProvidersListInner> response) {
return response.body();
}
});
} | java | public Observable<AvailableProvidersListInner> beginListAvailableProvidersAsync(String resourceGroupName, String networkWatcherName, AvailableProvidersListParameters parameters) {
return beginListAvailableProvidersWithServiceResponseAsync(resourceGroupName, networkWatcherName, parameters).map(new Func1<ServiceResponse<AvailableProvidersListInner>, AvailableProvidersListInner>() {
@Override
public AvailableProvidersListInner call(ServiceResponse<AvailableProvidersListInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"AvailableProvidersListInner",
">",
"beginListAvailableProvidersAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"networkWatcherName",
",",
"AvailableProvidersListParameters",
"parameters",
")",
"{",
"return",
"beginListAvailableProvidersWit... | Lists all available internet service providers for a specified Azure region.
@param resourceGroupName The name of the network watcher resource group.
@param networkWatcherName The name of the network watcher resource.
@param parameters Parameters that scope the list of available providers.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the AvailableProvidersListInner object | [
"Lists",
"all",
"available",
"internet",
"service",
"providers",
"for",
"a",
"specified",
"Azure",
"region",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java#L2578-L2585 |
OpenLiberty/open-liberty | dev/com.ibm.ws.concurrent.persistent/src/com/ibm/ws/concurrent/persistent/internal/ApplicationTracker.java | ApplicationTracker.deferTask | void deferTask(Runnable task, String appName, PersistentExecutorImpl persistentExecutor) {
ApplicationState state;
ExecutorService executor;
lock.writeLock().lock();
try {
executor = this.executor;
state = appStates.get(appName);
if (state != ApplicationState.STARTED) {
Set<Runnable> taskSet = deferredTasks.get(appName);
if (taskSet == null) {
deferredTasks.put(appName, taskSet = new HashSet<Runnable>());
// Avoid the warning if the application is in the process of starting
if (state != ApplicationState.STARTING && !persistentExecutor.deactivated)
Tr.warning(tc, "CWWKC1556.task.exec.deferred", appName);
}
taskSet.add(task);
}
} finally {
lock.writeLock().unlock();
}
// No need to defer, the app has started
if (state == ApplicationState.STARTED)
executor.submit(task);
} | java | void deferTask(Runnable task, String appName, PersistentExecutorImpl persistentExecutor) {
ApplicationState state;
ExecutorService executor;
lock.writeLock().lock();
try {
executor = this.executor;
state = appStates.get(appName);
if (state != ApplicationState.STARTED) {
Set<Runnable> taskSet = deferredTasks.get(appName);
if (taskSet == null) {
deferredTasks.put(appName, taskSet = new HashSet<Runnable>());
// Avoid the warning if the application is in the process of starting
if (state != ApplicationState.STARTING && !persistentExecutor.deactivated)
Tr.warning(tc, "CWWKC1556.task.exec.deferred", appName);
}
taskSet.add(task);
}
} finally {
lock.writeLock().unlock();
}
// No need to defer, the app has started
if (state == ApplicationState.STARTED)
executor.submit(task);
} | [
"void",
"deferTask",
"(",
"Runnable",
"task",
",",
"String",
"appName",
",",
"PersistentExecutorImpl",
"persistentExecutor",
")",
"{",
"ApplicationState",
"state",
";",
"ExecutorService",
"executor",
";",
"lock",
".",
"writeLock",
"(",
")",
".",
"lock",
"(",
")"... | Defer task execution until the application/module becomes available.
If, upon attempting to defer the task, we discover that the app has started,
we submit the task for execution instead of deferring. | [
"Defer",
"task",
"execution",
"until",
"the",
"application",
"/",
"module",
"becomes",
"available",
".",
"If",
"upon",
"attempting",
"to",
"defer",
"the",
"task",
"we",
"discover",
"that",
"the",
"app",
"has",
"started",
"we",
"submit",
"the",
"task",
"for",... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.concurrent.persistent/src/com/ibm/ws/concurrent/persistent/internal/ApplicationTracker.java#L120-L144 |
astrapi69/jaulp-wicket | jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/link/LinkUtils.java | LinkUtils.newBookmarkablePageLink | public static BookmarkablePageLink<String> newBookmarkablePageLink(final String linkId,
final Class<? extends Page> pageClass, final String labelId,
final ResourceBundleKey resourceModelKey, final Component component)
{
final BookmarkablePageLink<String> bookmarkablePageLink = new BookmarkablePageLink<>(linkId,
pageClass);
bookmarkablePageLink.add(
new Label(labelId, ResourceModelFactory.newResourceModel(resourceModelKey, component)));
return bookmarkablePageLink;
} | java | public static BookmarkablePageLink<String> newBookmarkablePageLink(final String linkId,
final Class<? extends Page> pageClass, final String labelId,
final ResourceBundleKey resourceModelKey, final Component component)
{
final BookmarkablePageLink<String> bookmarkablePageLink = new BookmarkablePageLink<>(linkId,
pageClass);
bookmarkablePageLink.add(
new Label(labelId, ResourceModelFactory.newResourceModel(resourceModelKey, component)));
return bookmarkablePageLink;
} | [
"public",
"static",
"BookmarkablePageLink",
"<",
"String",
">",
"newBookmarkablePageLink",
"(",
"final",
"String",
"linkId",
",",
"final",
"Class",
"<",
"?",
"extends",
"Page",
">",
"pageClass",
",",
"final",
"String",
"labelId",
",",
"final",
"ResourceBundleKey",... | Creates the bookmarkable page link.
@param linkId
the link id
@param pageClass
the page class
@param labelId
the label id
@param resourceModelKey
the resource model key
@param component
the component
@return the bookmarkable page link | [
"Creates",
"the",
"bookmarkable",
"page",
"link",
"."
] | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/link/LinkUtils.java#L52-L61 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/override/RawResolvedFeatures.java | RawResolvedFeatures.createTypeReference | private static LightweightTypeReference createTypeReference(JvmDeclaredType type, CommonTypeComputationServices services) {
StandardTypeReferenceOwner owner = new StandardTypeReferenceOwner(services, type);
return owner.newParameterizedTypeReference(type);
} | java | private static LightweightTypeReference createTypeReference(JvmDeclaredType type, CommonTypeComputationServices services) {
StandardTypeReferenceOwner owner = new StandardTypeReferenceOwner(services, type);
return owner.newParameterizedTypeReference(type);
} | [
"private",
"static",
"LightweightTypeReference",
"createTypeReference",
"(",
"JvmDeclaredType",
"type",
",",
"CommonTypeComputationServices",
"services",
")",
"{",
"StandardTypeReferenceOwner",
"owner",
"=",
"new",
"StandardTypeReferenceOwner",
"(",
"services",
",",
"type",
... | Static helper method that is used from within the super call in the constructor of
{@link RawResolvedFeatures}. | [
"Static",
"helper",
"method",
"that",
"is",
"used",
"from",
"within",
"the",
"super",
"call",
"in",
"the",
"constructor",
"of",
"{"
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/override/RawResolvedFeatures.java#L111-L114 |
spring-projects/spring-social | spring-social-web/src/main/java/org/springframework/social/connect/web/ConnectController.java | ConnectController.oauth2ErrorCallback | @RequestMapping(value="/{providerId}", method=RequestMethod.GET, params="error")
public RedirectView oauth2ErrorCallback(@PathVariable String providerId,
@RequestParam("error") String error,
@RequestParam(value="error_description", required=false) String errorDescription,
@RequestParam(value="error_uri", required=false) String errorUri,
NativeWebRequest request) {
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put("error", error);
if (errorDescription != null) { errorMap.put("errorDescription", errorDescription); }
if (errorUri != null) { errorMap.put("errorUri", errorUri); }
sessionStrategy.setAttribute(request, AUTHORIZATION_ERROR_ATTRIBUTE, errorMap);
return connectionStatusRedirect(providerId, request);
} | java | @RequestMapping(value="/{providerId}", method=RequestMethod.GET, params="error")
public RedirectView oauth2ErrorCallback(@PathVariable String providerId,
@RequestParam("error") String error,
@RequestParam(value="error_description", required=false) String errorDescription,
@RequestParam(value="error_uri", required=false) String errorUri,
NativeWebRequest request) {
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put("error", error);
if (errorDescription != null) { errorMap.put("errorDescription", errorDescription); }
if (errorUri != null) { errorMap.put("errorUri", errorUri); }
sessionStrategy.setAttribute(request, AUTHORIZATION_ERROR_ATTRIBUTE, errorMap);
return connectionStatusRedirect(providerId, request);
} | [
"@",
"RequestMapping",
"(",
"value",
"=",
"\"/{providerId}\"",
",",
"method",
"=",
"RequestMethod",
".",
"GET",
",",
"params",
"=",
"\"error\"",
")",
"public",
"RedirectView",
"oauth2ErrorCallback",
"(",
"@",
"PathVariable",
"String",
"providerId",
",",
"@",
"Re... | Process an error callback from an OAuth 2 authorization as described at https://tools.ietf.org/html/rfc6749#section-4.1.2.1.
Called after upon redirect from an OAuth 2 provider when there is some sort of error during authorization, typically because the user denied authorization.
@param providerId the provider ID that the connection was attempted for
@param error the error parameter sent from the provider
@param errorDescription the error_description parameter sent from the provider
@param errorUri the error_uri parameter sent from the provider
@param request the request
@return a RedirectView to the connection status page | [
"Process",
"an",
"error",
"callback",
"from",
"an",
"OAuth",
"2",
"authorization",
"as",
"described",
"at",
"https",
":",
"//",
"tools",
".",
"ietf",
".",
"org",
"/",
"html",
"/",
"rfc6749#section",
"-",
"4",
".",
"1",
".",
"2",
".",
"1",
".",
"Calle... | train | https://github.com/spring-projects/spring-social/blob/e41cfecb288022b83c79413b58f52511c3c9d4fc/spring-social-web/src/main/java/org/springframework/social/connect/web/ConnectController.java#L310-L322 |
Netflix/conductor | mysql-persistence/src/main/java/com/netflix/conductor/dao/mysql/MySQLMetadataDAO.java | MySQLMetadataDAO.findAllTaskDefs | private List<TaskDef> findAllTaskDefs(Connection tx) {
final String READ_ALL_TASKDEF_QUERY = "SELECT json_data FROM meta_task_def";
return query(tx, READ_ALL_TASKDEF_QUERY, q -> q.executeAndFetch(TaskDef.class));
} | java | private List<TaskDef> findAllTaskDefs(Connection tx) {
final String READ_ALL_TASKDEF_QUERY = "SELECT json_data FROM meta_task_def";
return query(tx, READ_ALL_TASKDEF_QUERY, q -> q.executeAndFetch(TaskDef.class));
} | [
"private",
"List",
"<",
"TaskDef",
">",
"findAllTaskDefs",
"(",
"Connection",
"tx",
")",
"{",
"final",
"String",
"READ_ALL_TASKDEF_QUERY",
"=",
"\"SELECT json_data FROM meta_task_def\"",
";",
"return",
"query",
"(",
"tx",
",",
"READ_ALL_TASKDEF_QUERY",
",",
"q",
"->... | Query persistence for all defined {@link TaskDef} data.
@param tx The {@link Connection} to use for queries.
@return A new {@code List<TaskDef>} with all the {@code TaskDef} data that was retrieved. | [
"Query",
"persistence",
"for",
"all",
"defined",
"{",
"@link",
"TaskDef",
"}",
"data",
"."
] | train | https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/mysql-persistence/src/main/java/com/netflix/conductor/dao/mysql/MySQLMetadataDAO.java#L410-L414 |
Azure/azure-sdk-for-java | automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/DscCompilationJobsInner.java | DscCompilationJobsInner.get | public DscCompilationJobInner get(String resourceGroupName, String automationAccountName, UUID compilationJobId) {
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, compilationJobId).toBlocking().single().body();
} | java | public DscCompilationJobInner get(String resourceGroupName, String automationAccountName, UUID compilationJobId) {
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, compilationJobId).toBlocking().single().body();
} | [
"public",
"DscCompilationJobInner",
"get",
"(",
"String",
"resourceGroupName",
",",
"String",
"automationAccountName",
",",
"UUID",
"compilationJobId",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"automationAccountName",
",",
"compilati... | Retrieve the Dsc configuration compilation job identified by job id.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param compilationJobId The Dsc configuration compilation job id.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DscCompilationJobInner object if successful. | [
"Retrieve",
"the",
"Dsc",
"configuration",
"compilation",
"job",
"identified",
"by",
"job",
"id",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/DscCompilationJobsInner.java#L197-L199 |
appium/java-client | src/main/java/io/appium/java_client/events/EventFiringObjectFactory.java | EventFiringObjectFactory.getEventFiringObject | @SuppressWarnings("unchecked")
public static <T> T getEventFiringObject(T t, WebDriver driver, Collection<Listener> listeners) {
final List<Listener> listenerList = new ArrayList<>();
for (Listener listener : ServiceLoader.load(
Listener.class)) {
listenerList.add(listener);
}
listeners.stream().filter(listener -> !listenerList.contains(listener)).forEach(listenerList::add);
AbstractApplicationContext context = new AnnotationConfigApplicationContext(
DefaultBeanConfiguration.class);
return (T) context.getBean(
DefaultBeanConfiguration.LISTENABLE_OBJECT, t, driver, listenerList, context);
} | java | @SuppressWarnings("unchecked")
public static <T> T getEventFiringObject(T t, WebDriver driver, Collection<Listener> listeners) {
final List<Listener> listenerList = new ArrayList<>();
for (Listener listener : ServiceLoader.load(
Listener.class)) {
listenerList.add(listener);
}
listeners.stream().filter(listener -> !listenerList.contains(listener)).forEach(listenerList::add);
AbstractApplicationContext context = new AnnotationConfigApplicationContext(
DefaultBeanConfiguration.class);
return (T) context.getBean(
DefaultBeanConfiguration.LISTENABLE_OBJECT, t, driver, listenerList, context);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"T",
"getEventFiringObject",
"(",
"T",
"t",
",",
"WebDriver",
"driver",
",",
"Collection",
"<",
"Listener",
">",
"listeners",
")",
"{",
"final",
"List",
"<",
"Listener",
... | This method makes an event firing object.
@param t an original {@link Object} that is
supposed to be listenable
@param driver an instance of {@link org.openqa.selenium.WebDriver}
@param listeners is a collection of {@link io.appium.java_client.events.api.Listener} that
is supposed to be used for the event firing
@param <T> T
@return an {@link Object} that fires events | [
"This",
"method",
"makes",
"an",
"event",
"firing",
"object",
"."
] | train | https://github.com/appium/java-client/blob/5a17759b05d6fda8ef425b3ab6e766c73ed2e8df/src/main/java/io/appium/java_client/events/EventFiringObjectFactory.java#L28-L43 |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/ReferenceEntityLockService.java | ReferenceEntityLockService.convert | @Override
public void convert(IEntityLock lock, int newType, int newDuration) throws LockingException {
if (lock.getLockType() == newType) {
throw new LockingException(
"Could not convert " + lock + " : old and new lock TYPEs are the same.");
}
if (!isValidLockType(newType)) {
throw new LockingException(
"Could not convert " + lock + " : lock TYPE " + newType + " is invalid.");
}
if (!isValid(lock)) {
throw new LockingException("Could not convert " + lock + " : lock is invalid.");
}
if (newType == WRITE_LOCK
&& retrieveLocks(lock.getEntityType(), lock.getEntityKey(), null).length > 1) {
throw new LockingException(
"Could not convert " + lock + " : another lock already exists.");
}
if (newType == READ_LOCK) {
/* Can always convert to READ */
}
Date newExpiration = getNewExpiration(newDuration);
getLockStore().update(lock, newExpiration, newType);
((EntityLockImpl) lock).setLockType(newType);
((EntityLockImpl) lock).setExpirationTime(newExpiration);
} | java | @Override
public void convert(IEntityLock lock, int newType, int newDuration) throws LockingException {
if (lock.getLockType() == newType) {
throw new LockingException(
"Could not convert " + lock + " : old and new lock TYPEs are the same.");
}
if (!isValidLockType(newType)) {
throw new LockingException(
"Could not convert " + lock + " : lock TYPE " + newType + " is invalid.");
}
if (!isValid(lock)) {
throw new LockingException("Could not convert " + lock + " : lock is invalid.");
}
if (newType == WRITE_LOCK
&& retrieveLocks(lock.getEntityType(), lock.getEntityKey(), null).length > 1) {
throw new LockingException(
"Could not convert " + lock + " : another lock already exists.");
}
if (newType == READ_LOCK) {
/* Can always convert to READ */
}
Date newExpiration = getNewExpiration(newDuration);
getLockStore().update(lock, newExpiration, newType);
((EntityLockImpl) lock).setLockType(newType);
((EntityLockImpl) lock).setExpirationTime(newExpiration);
} | [
"@",
"Override",
"public",
"void",
"convert",
"(",
"IEntityLock",
"lock",
",",
"int",
"newType",
",",
"int",
"newDuration",
")",
"throws",
"LockingException",
"{",
"if",
"(",
"lock",
".",
"getLockType",
"(",
")",
"==",
"newType",
")",
"{",
"throw",
"new",
... | Attempts to change the lock's <code>lockType</code> to <code>newType</code>.
@param lock IEntityLock
@param newType int
@param newDuration int
@exception org.apereo.portal.concurrency.LockingException | [
"Attempts",
"to",
"change",
"the",
"lock",
"s",
"<code",
">",
"lockType<",
"/",
"code",
">",
"to",
"<code",
">",
"newType<",
"/",
"code",
">",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/ReferenceEntityLockService.java#L75-L105 |
knowm/XChange | xchange-cryptonit/src/main/java/org/knowm/xchange/cryptonit2/CryptonitAdapters.java | CryptonitAdapters.adaptAccountInfo | public static AccountInfo adaptAccountInfo(CryptonitBalance cryptonitBalance, String userName) {
// Adapt to XChange DTOs
List<Balance> balances = new ArrayList<>();
for (CryptonitBalance.Balance b : cryptonitBalance.getBalances()) {
Balance xchangeBalance =
new Balance(
Currency.getInstance(b.getCurrency().toUpperCase()),
b.getBalance(),
b.getAvailable(),
b.getReserved(),
ZERO,
ZERO,
b.getBalance().subtract(b.getAvailable()).subtract(b.getReserved()),
ZERO);
balances.add(xchangeBalance);
}
return new AccountInfo(userName, cryptonitBalance.getFee(), new Wallet(balances));
} | java | public static AccountInfo adaptAccountInfo(CryptonitBalance cryptonitBalance, String userName) {
// Adapt to XChange DTOs
List<Balance> balances = new ArrayList<>();
for (CryptonitBalance.Balance b : cryptonitBalance.getBalances()) {
Balance xchangeBalance =
new Balance(
Currency.getInstance(b.getCurrency().toUpperCase()),
b.getBalance(),
b.getAvailable(),
b.getReserved(),
ZERO,
ZERO,
b.getBalance().subtract(b.getAvailable()).subtract(b.getReserved()),
ZERO);
balances.add(xchangeBalance);
}
return new AccountInfo(userName, cryptonitBalance.getFee(), new Wallet(balances));
} | [
"public",
"static",
"AccountInfo",
"adaptAccountInfo",
"(",
"CryptonitBalance",
"cryptonitBalance",
",",
"String",
"userName",
")",
"{",
"// Adapt to XChange DTOs",
"List",
"<",
"Balance",
">",
"balances",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
... | Adapts a CryptonitBalance to an AccountInfo
@param cryptonitBalance The Cryptonit balance
@param userName The user name
@return The account info | [
"Adapts",
"a",
"CryptonitBalance",
"to",
"an",
"AccountInfo"
] | train | https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-cryptonit/src/main/java/org/knowm/xchange/cryptonit2/CryptonitAdapters.java#L54-L72 |
albfernandez/itext2 | src/main/java/com/lowagie/text/factories/ElementFactory.java | ElementFactory.getSection | public static Section getSection(Section parent, Properties attributes) {
Section section = parent.addSection("");
setSectionParameters(section, attributes);
return section;
} | java | public static Section getSection(Section parent, Properties attributes) {
Section section = parent.addSection("");
setSectionParameters(section, attributes);
return section;
} | [
"public",
"static",
"Section",
"getSection",
"(",
"Section",
"parent",
",",
"Properties",
"attributes",
")",
"{",
"Section",
"section",
"=",
"parent",
".",
"addSection",
"(",
"\"\"",
")",
";",
"setSectionParameters",
"(",
"section",
",",
"attributes",
")",
";"... | Creates a Section object based on a list of properties.
@param attributes
@return a Section | [
"Creates",
"a",
"Section",
"object",
"based",
"on",
"a",
"list",
"of",
"properties",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/factories/ElementFactory.java#L485-L489 |
ModeShape/modeshape | modeshape-jcr/src/main/java/org/modeshape/jcr/AbstractJcrNode.java | AbstractJcrNode.findBestPropertyDefinition | final JcrPropertyDefinition findBestPropertyDefinition( Name primaryTypeNameOfParent,
Collection<Name> mixinTypeNamesOfParent,
org.modeshape.jcr.value.Property property,
boolean isSingle,
boolean skipProtected,
boolean skipConstraints,
NodeTypes nodeTypes ) {
JcrPropertyDefinition definition = null;
int propertyType = PropertyTypeUtil.jcrPropertyTypeFor(property);
// If single-valued ...
ValueFactories factories = context().getValueFactories();
if (isSingle) {
// Create a value for the ModeShape property value ...
Object value = property.getFirstValue();
Value jcrValue = new JcrValue(factories, propertyType, value);
definition = nodeTypes.findPropertyDefinition(session, primaryTypeNameOfParent, mixinTypeNamesOfParent,
property.getName(), jcrValue, true, skipProtected);
} else {
// Create values for the ModeShape property value ...
Value[] jcrValues = new Value[property.size()];
int index = 0;
for (Object value : property) {
jcrValues[index++] = new JcrValue(factories, propertyType, value);
}
definition = nodeTypes.findPropertyDefinition(session, primaryTypeNameOfParent, mixinTypeNamesOfParent,
property.getName(), jcrValues, skipProtected);
}
if (definition != null) return definition;
// No definition that allowed the values ...
return null;
} | java | final JcrPropertyDefinition findBestPropertyDefinition( Name primaryTypeNameOfParent,
Collection<Name> mixinTypeNamesOfParent,
org.modeshape.jcr.value.Property property,
boolean isSingle,
boolean skipProtected,
boolean skipConstraints,
NodeTypes nodeTypes ) {
JcrPropertyDefinition definition = null;
int propertyType = PropertyTypeUtil.jcrPropertyTypeFor(property);
// If single-valued ...
ValueFactories factories = context().getValueFactories();
if (isSingle) {
// Create a value for the ModeShape property value ...
Object value = property.getFirstValue();
Value jcrValue = new JcrValue(factories, propertyType, value);
definition = nodeTypes.findPropertyDefinition(session, primaryTypeNameOfParent, mixinTypeNamesOfParent,
property.getName(), jcrValue, true, skipProtected);
} else {
// Create values for the ModeShape property value ...
Value[] jcrValues = new Value[property.size()];
int index = 0;
for (Object value : property) {
jcrValues[index++] = new JcrValue(factories, propertyType, value);
}
definition = nodeTypes.findPropertyDefinition(session, primaryTypeNameOfParent, mixinTypeNamesOfParent,
property.getName(), jcrValues, skipProtected);
}
if (definition != null) return definition;
// No definition that allowed the values ...
return null;
} | [
"final",
"JcrPropertyDefinition",
"findBestPropertyDefinition",
"(",
"Name",
"primaryTypeNameOfParent",
",",
"Collection",
"<",
"Name",
">",
"mixinTypeNamesOfParent",
",",
"org",
".",
"modeshape",
".",
"jcr",
".",
"value",
".",
"Property",
"property",
",",
"boolean",
... | Find the best property definition in this node's primary type and mixin types.
@param primaryTypeNameOfParent the name of the primary type for the parent node; may not be null
@param mixinTypeNamesOfParent the names of the mixin types for the parent node; may be null or empty if there are no mixins
to include in the search
@param property the property
@param isSingle true if the property definition should be single-valued, or false if the property definition should allow
multiple values
@param skipProtected true if this operation is being done from within the public JCR node and property API, or false if
this operation is being done from within internal implementations
@param skipConstraints true if any constraints on the potential property definitions should be skipped; usually this is
true for the first attempt but then 'false' for a subsequent attempt when figuring out an appropriate error message
@param nodeTypes the node types cache to use; may not be null
@return the property definition that allows setting this property, or null if there is no such definition | [
"Find",
"the",
"best",
"property",
"definition",
"in",
"this",
"node",
"s",
"primary",
"type",
"and",
"mixin",
"types",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/AbstractJcrNode.java#L495-L528 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/parser/lexparser/Options.java | Options.setOptionOrWarn | public int setOptionOrWarn(String[] flags, int i) {
int j = setOptionFlag(flags, i);
if (j == i) {
j = tlpParams.setOptionFlag(flags, i);
}
if (j == i) {
System.err.println("WARNING! lexparser.Options: Unknown option ignored: " + flags[i]);
j++;
}
return j;
} | java | public int setOptionOrWarn(String[] flags, int i) {
int j = setOptionFlag(flags, i);
if (j == i) {
j = tlpParams.setOptionFlag(flags, i);
}
if (j == i) {
System.err.println("WARNING! lexparser.Options: Unknown option ignored: " + flags[i]);
j++;
}
return j;
} | [
"public",
"int",
"setOptionOrWarn",
"(",
"String",
"[",
"]",
"flags",
",",
"int",
"i",
")",
"{",
"int",
"j",
"=",
"setOptionFlag",
"(",
"flags",
",",
"i",
")",
";",
"if",
"(",
"j",
"==",
"i",
")",
"{",
"j",
"=",
"tlpParams",
".",
"setOptionFlag",
... | Set an option based on a String array in the style of
commandline flags. The option may
be either one known by the Options object, or one recognized by the
TreebankLangParserParams which has already been set up inside the Options
object, and then the option is set in the language-particular
TreebankLangParserParams.
Note that despite this method being an instance method, many flags
are actually set as static class variables in the Train and Test
classes (this should be fixed some day).
Some options (there are many others; see the source code):
<ul>
<li> <code>-maxLength n</code> set the maximum length sentence to parse (inclusively)
<li> <code>-printTT</code> print the training trees in raw, annotated, and annotated+binarized form. Useful for debugging and other miscellany.
<li> <code>-printAnnotated filename</code> use only in conjunction with -printTT. Redirects printing of annotated training trees to <code>filename</code>.
<li> <code>-forceTags</code> when the parser is tested against a set of gold standard trees, use the tagged yield, instead of just the yield, as input.
</ul>
@param flags An array of options arguments, command-line style. E.g. {"-maxLength", "50"}.
@param i The index in flags to start at when processing an option
@return The index in flags of the position after the last element used in
processing this option. If the current array position cannot be processed as a valid
option, then a warning message is printed to stderr and the return value is <code>i+1</code> | [
"Set",
"an",
"option",
"based",
"on",
"a",
"String",
"array",
"in",
"the",
"style",
"of",
"commandline",
"flags",
".",
"The",
"option",
"may",
"be",
"either",
"one",
"known",
"by",
"the",
"Options",
"object",
"or",
"one",
"recognized",
"by",
"the",
"Tree... | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/parser/lexparser/Options.java#L130-L140 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java | FileUtil.getWriter | public static BufferedWriter getWriter(File file, Charset charset, boolean isAppend) throws IORuntimeException {
return FileWriter.create(file, charset).getWriter(isAppend);
} | java | public static BufferedWriter getWriter(File file, Charset charset, boolean isAppend) throws IORuntimeException {
return FileWriter.create(file, charset).getWriter(isAppend);
} | [
"public",
"static",
"BufferedWriter",
"getWriter",
"(",
"File",
"file",
",",
"Charset",
"charset",
",",
"boolean",
"isAppend",
")",
"throws",
"IORuntimeException",
"{",
"return",
"FileWriter",
".",
"create",
"(",
"file",
",",
"charset",
")",
".",
"getWriter",
... | 获得一个带缓存的写入对象
@param file 输出文件
@param charset 字符集
@param isAppend 是否追加
@return BufferedReader对象
@throws IORuntimeException IO异常 | [
"获得一个带缓存的写入对象"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L2624-L2626 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.