repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
code4everything/util | src/main/java/com/zhazhapan/util/FileExecutor.java | FileExecutor.copyFiles | public static void copyFiles(String[] files, String storageFolder) throws IOException {
copyFiles(getFiles(files), storageFolder);
} | java | public static void copyFiles(String[] files, String storageFolder) throws IOException {
copyFiles(getFiles(files), storageFolder);
} | [
"public",
"static",
"void",
"copyFiles",
"(",
"String",
"[",
"]",
"files",
",",
"String",
"storageFolder",
")",
"throws",
"IOException",
"{",
"copyFiles",
"(",
"getFiles",
"(",
"files",
")",
",",
"storageFolder",
")",
";",
"}"
] | 批量复制文件,使用原文件名
@param files 文件路径数组
@param storageFolder 存储目录
@throws IOException 异常 | [
"批量复制文件,使用原文件名"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/FileExecutor.java#L436-L438 |
JakeWharton/ActionBarSherlock | actionbarsherlock/src/com/actionbarsherlock/widget/SuggestionsAdapter.java | SuggestionsAdapter.getView | @Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
return super.getView(position, convertView, parent);
} catch (RuntimeException e) {
Log.w(LOG_TAG, "Search suggestions cursor threw exception.", e);
// Put exception string in item title
View v = newView(mContext, mCursor, parent);
if (v != null) {
ChildViewCache views = (ChildViewCache) v.getTag();
TextView tv = views.mText1;
tv.setText(e.toString());
}
return v;
}
} | java | @Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
return super.getView(position, convertView, parent);
} catch (RuntimeException e) {
Log.w(LOG_TAG, "Search suggestions cursor threw exception.", e);
// Put exception string in item title
View v = newView(mContext, mCursor, parent);
if (v != null) {
ChildViewCache views = (ChildViewCache) v.getTag();
TextView tv = views.mText1;
tv.setText(e.toString());
}
return v;
}
} | [
"@",
"Override",
"public",
"View",
"getView",
"(",
"int",
"position",
",",
"View",
"convertView",
",",
"ViewGroup",
"parent",
")",
"{",
"try",
"{",
"return",
"super",
".",
"getView",
"(",
"position",
",",
"convertView",
",",
"parent",
")",
";",
"}",
"cat... | This method is overridden purely to provide a bit of protection against
flaky content providers.
@see android.widget.ListAdapter#getView(int, View, ViewGroup) | [
"This",
"method",
"is",
"overridden",
"purely",
"to",
"provide",
"a",
"bit",
"of",
"protection",
"against",
"flaky",
"content",
"providers",
"."
] | train | https://github.com/JakeWharton/ActionBarSherlock/blob/2c71339e756bcc0b1424c4525680549ba3a2dc97/actionbarsherlock/src/com/actionbarsherlock/widget/SuggestionsAdapter.java#L508-L523 |
GCRC/nunaliit | nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/client/impl/ConnectionUtils.java | ConnectionUtils.captureReponseErrors | static public void captureReponseErrors(Object response, String errorMessage) throws Exception {
if( null == response ) {
throw new Exception("Capturing errors from null response");
}
if( false == (response instanceof JSONObject) ) {
// Not an error
return;
}
JSONObject obj = (JSONObject)response;
if( JSONSupport.containsKey(obj,"error") ) {
String serverMessage;
try {
serverMessage = obj.getString("error");
} catch (Exception e) {
serverMessage = "Unable to parse error response";
}
if( null == errorMessage ) {
errorMessage = "Error returned by database: ";
}
throw new Exception(errorMessage+serverMessage);
}
} | java | static public void captureReponseErrors(Object response, String errorMessage) throws Exception {
if( null == response ) {
throw new Exception("Capturing errors from null response");
}
if( false == (response instanceof JSONObject) ) {
// Not an error
return;
}
JSONObject obj = (JSONObject)response;
if( JSONSupport.containsKey(obj,"error") ) {
String serverMessage;
try {
serverMessage = obj.getString("error");
} catch (Exception e) {
serverMessage = "Unable to parse error response";
}
if( null == errorMessage ) {
errorMessage = "Error returned by database: ";
}
throw new Exception(errorMessage+serverMessage);
}
} | [
"static",
"public",
"void",
"captureReponseErrors",
"(",
"Object",
"response",
",",
"String",
"errorMessage",
")",
"throws",
"Exception",
"{",
"if",
"(",
"null",
"==",
"response",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Capturing errors from null response\"",... | Analyze a CouchDb response and raises an exception if an error was returned
in the response.
@param response JSON response sent by server
@param errorMessage Message of top exception
@throws Exception If error is returned in response | [
"Analyze",
"a",
"CouchDb",
"response",
"and",
"raises",
"an",
"exception",
"if",
"an",
"error",
"was",
"returned",
"in",
"the",
"response",
"."
] | train | https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/client/impl/ConnectionUtils.java#L427-L449 |
UrielCh/ovh-java-sdk | ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java | ApiOvhTelephony.billingAccount_miniPabx_serviceName_hunting_PUT | public void billingAccount_miniPabx_serviceName_hunting_PUT(String billingAccount, String serviceName, OvhMiniPabxHunting body) throws IOException {
String qPath = "/telephony/{billingAccount}/miniPabx/{serviceName}/hunting";
StringBuilder sb = path(qPath, billingAccount, serviceName);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void billingAccount_miniPabx_serviceName_hunting_PUT(String billingAccount, String serviceName, OvhMiniPabxHunting body) throws IOException {
String qPath = "/telephony/{billingAccount}/miniPabx/{serviceName}/hunting";
StringBuilder sb = path(qPath, billingAccount, serviceName);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"billingAccount_miniPabx_serviceName_hunting_PUT",
"(",
"String",
"billingAccount",
",",
"String",
"serviceName",
",",
"OvhMiniPabxHunting",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/telephony/{billingAccount}/miniPabx/{serviceName... | Alter this object properties
REST: PUT /telephony/{billingAccount}/miniPabx/{serviceName}/hunting
@param body [required] New object properties
@param billingAccount [required] The name of your billingAccount
@param serviceName [required] | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L5188-L5192 |
mongodb/stitch-android-sdk | server/services/aws-s3/src/main/java/com/mongodb/stitch/server/services/aws/s3/internal/AwsS3ServiceClientImpl.java | AwsS3ServiceClientImpl.signPolicy | public AwsS3SignPolicyResult signPolicy(
@Nonnull final String bucket,
@Nonnull final String key,
@Nonnull final String acl,
@Nonnull final String contentType
) {
return proxy.signPolicy(bucket, key, acl, contentType);
} | java | public AwsS3SignPolicyResult signPolicy(
@Nonnull final String bucket,
@Nonnull final String key,
@Nonnull final String acl,
@Nonnull final String contentType
) {
return proxy.signPolicy(bucket, key, acl, contentType);
} | [
"public",
"AwsS3SignPolicyResult",
"signPolicy",
"(",
"@",
"Nonnull",
"final",
"String",
"bucket",
",",
"@",
"Nonnull",
"final",
"String",
"key",
",",
"@",
"Nonnull",
"final",
"String",
"acl",
",",
"@",
"Nonnull",
"final",
"String",
"contentType",
")",
"{",
... | Signs an AWS S3 security policy for a future put object request. This future request would
be made outside of the Stitch SDK. This is typically used for large requests that are better
sent directly to AWS.
@see <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html">Uploading a File to Amazon S3 Using HTTP POST</a>
@param bucket the bucket to put the future object in.
@param key the key (or name) of the future object.
@param acl the ACL to apply to the future object (e.g. private).
@param contentType the content type of the object (e.g. application/json).
@return the signed policy details. | [
"Signs",
"an",
"AWS",
"S3",
"security",
"policy",
"for",
"a",
"future",
"put",
"object",
"request",
".",
"This",
"future",
"request",
"would",
"be",
"made",
"outside",
"of",
"the",
"Stitch",
"SDK",
".",
"This",
"is",
"typically",
"used",
"for",
"large",
... | train | https://github.com/mongodb/stitch-android-sdk/blob/159b9334b1f1a827285544be5ee20cdf7b04e4cc/server/services/aws-s3/src/main/java/com/mongodb/stitch/server/services/aws/s3/internal/AwsS3ServiceClientImpl.java#L128-L135 |
sriharshachilakapati/WebGL4J | webgl4j/src/main/java/com/shc/webgl4j/client/WebGL10.java | WebGL10.glBlendColor | public static void glBlendColor(float r, float g, float b, float a)
{
checkContextCompatibility();
nglBlendColor(r, g, b, a);
} | java | public static void glBlendColor(float r, float g, float b, float a)
{
checkContextCompatibility();
nglBlendColor(r, g, b, a);
} | [
"public",
"static",
"void",
"glBlendColor",
"(",
"float",
"r",
",",
"float",
"g",
",",
"float",
"b",
",",
"float",
"a",
")",
"{",
"checkContextCompatibility",
"(",
")",
";",
"nglBlendColor",
"(",
"r",
",",
"g",
",",
"b",
",",
"a",
")",
";",
"}"
] | The {@link #GL_BLEND_COLOR} may be used to calculate the source and destination blending factors. The color
components are clamped to the range {@code [0,1]} before being stored. See {@link #glBlendFunc(int, int)} for a
complete description of the blending operations. Initially the {@link #GL_BLEND_COLOR} is set to {@code (0, 0, 0,
0)}.
@param r Specifies the red component of {@link #GL_BLEND_COLOR}.
@param g Specifies the green component of {@link #GL_BLEND_COLOR}.
@param b Specifies the blue component of {@link #GL_BLEND_COLOR}.
@param a Specifies the alpha component of {@link #GL_BLEND_COLOR}. | [
"The",
"{",
"@link",
"#GL_BLEND_COLOR",
"}",
"may",
"be",
"used",
"to",
"calculate",
"the",
"source",
"and",
"destination",
"blending",
"factors",
".",
"The",
"color",
"components",
"are",
"clamped",
"to",
"the",
"range",
"{",
"@code",
"[",
"0",
"1",
"]",
... | train | https://github.com/sriharshachilakapati/WebGL4J/blob/7daa425300b08b338b50cef2935289849c92d415/webgl4j/src/main/java/com/shc/webgl4j/client/WebGL10.java#L659-L663 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/JsMsgObject.java | JsMsgObject.encodeHeaderPartToSlice | private final DataSlice encodeHeaderPartToSlice(JsMsgPart jsPart) throws MessageEncodeFailedException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "encodeHeaderPartToSlice", jsPart);
// We hope that it is already encoded so we can just get it from JMF.....
DataSlice slice = ((JMFMessage)jsPart.jmfPart).getAssembledContent();
// ... if not, then we have to encode it now
if (slice == null) {
byte[] buff;
// We need to ensure noone updates any vital aspects of the message part
// between the calls to getEncodedLength() and toByteArray() d364050
synchronized (getPartLockArtefact(jsPart)) {
buff = encodePart(jsPart);
}
slice = new DataSlice(buff, 0, buff.length);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "encodeHeaderPartToSlice", slice);
return slice;
} | java | private final DataSlice encodeHeaderPartToSlice(JsMsgPart jsPart) throws MessageEncodeFailedException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "encodeHeaderPartToSlice", jsPart);
// We hope that it is already encoded so we can just get it from JMF.....
DataSlice slice = ((JMFMessage)jsPart.jmfPart).getAssembledContent();
// ... if not, then we have to encode it now
if (slice == null) {
byte[] buff;
// We need to ensure noone updates any vital aspects of the message part
// between the calls to getEncodedLength() and toByteArray() d364050
synchronized (getPartLockArtefact(jsPart)) {
buff = encodePart(jsPart);
}
slice = new DataSlice(buff, 0, buff.length);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "encodeHeaderPartToSlice", slice);
return slice;
} | [
"private",
"final",
"DataSlice",
"encodeHeaderPartToSlice",
"(",
"JsMsgPart",
"jsPart",
")",
"throws",
"MessageEncodeFailedException",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
... | Encode the header, or only, a message part into a DataSlice for transmitting
over the wire, or flattening for persistence.
If the message part is already 'assembled' the contents are simply be
wrapped in a DataSlice by the JMFMessage & returned.
If the message part is not already assembled, the part is encoded into a
new byte array which is wrapped by a DataSlice.
@param jsPart The message part to be encoded.
@return DataSlice The DataSlice containing the encoded message part
@exception MessageEncodeFailedException is thrown if the message part failed to encode. | [
"Encode",
"the",
"header",
"or",
"only",
"a",
"message",
"part",
"into",
"a",
"DataSlice",
"for",
"transmitting",
"over",
"the",
"wire",
"or",
"flattening",
"for",
"persistence",
".",
"If",
"the",
"message",
"part",
"is",
"already",
"assembled",
"the",
"cont... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/JsMsgObject.java#L1146-L1166 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/appfw/appfwhtmlerrorpage.java | appfwhtmlerrorpage.get | public static appfwhtmlerrorpage get(nitro_service service, String name) throws Exception{
appfwhtmlerrorpage obj = new appfwhtmlerrorpage();
obj.set_name(name);
appfwhtmlerrorpage response = (appfwhtmlerrorpage) obj.get_resource(service);
return response;
} | java | public static appfwhtmlerrorpage get(nitro_service service, String name) throws Exception{
appfwhtmlerrorpage obj = new appfwhtmlerrorpage();
obj.set_name(name);
appfwhtmlerrorpage response = (appfwhtmlerrorpage) obj.get_resource(service);
return response;
} | [
"public",
"static",
"appfwhtmlerrorpage",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"name",
")",
"throws",
"Exception",
"{",
"appfwhtmlerrorpage",
"obj",
"=",
"new",
"appfwhtmlerrorpage",
"(",
")",
";",
"obj",
".",
"set_name",
"(",
"name",
")",
";... | Use this API to fetch appfwhtmlerrorpage resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"appfwhtmlerrorpage",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/appfw/appfwhtmlerrorpage.java#L134-L139 |
apereo/cas | support/cas-server-support-saml-idp-metadata/src/main/java/org/apereo/cas/support/saml/services/idp/metadata/cache/resolver/UrlResourceMetadataResolver.java | UrlResourceMetadataResolver.getMetadataResolverFromResponse | protected AbstractMetadataResolver getMetadataResolverFromResponse(final HttpResponse response, final File backupFile) throws Exception {
val entity = response.getEntity();
val result = IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8);
val path = backupFile.toPath();
LOGGER.trace("Writing metadata to file at [{}]", path);
try (val output = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
IOUtils.write(result, output);
output.flush();
}
EntityUtils.consume(entity);
return new InMemoryResourceMetadataResolver(backupFile, configBean);
} | java | protected AbstractMetadataResolver getMetadataResolverFromResponse(final HttpResponse response, final File backupFile) throws Exception {
val entity = response.getEntity();
val result = IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8);
val path = backupFile.toPath();
LOGGER.trace("Writing metadata to file at [{}]", path);
try (val output = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
IOUtils.write(result, output);
output.flush();
}
EntityUtils.consume(entity);
return new InMemoryResourceMetadataResolver(backupFile, configBean);
} | [
"protected",
"AbstractMetadataResolver",
"getMetadataResolverFromResponse",
"(",
"final",
"HttpResponse",
"response",
",",
"final",
"File",
"backupFile",
")",
"throws",
"Exception",
"{",
"val",
"entity",
"=",
"response",
".",
"getEntity",
"(",
")",
";",
"val",
"resu... | Gets metadata resolver from response.
@param response the response
@param backupFile the backup file
@return the metadata resolver from response
@throws Exception the exception | [
"Gets",
"metadata",
"resolver",
"from",
"response",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml-idp-metadata/src/main/java/org/apereo/cas/support/saml/services/idp/metadata/cache/resolver/UrlResourceMetadataResolver.java#L126-L137 |
spring-projects/spring-retry | src/main/java/org/springframework/retry/backoff/ExponentialBackOffPolicy.java | ExponentialBackOffPolicy.backOff | public void backOff(BackOffContext backOffContext)
throws BackOffInterruptedException {
ExponentialBackOffContext context = (ExponentialBackOffContext) backOffContext;
try {
long sleepTime = context.getSleepAndIncrement();
if (logger.isDebugEnabled()) {
logger.debug("Sleeping for " + sleepTime);
}
sleeper.sleep(sleepTime);
}
catch (InterruptedException e) {
throw new BackOffInterruptedException("Thread interrupted while sleeping", e);
}
} | java | public void backOff(BackOffContext backOffContext)
throws BackOffInterruptedException {
ExponentialBackOffContext context = (ExponentialBackOffContext) backOffContext;
try {
long sleepTime = context.getSleepAndIncrement();
if (logger.isDebugEnabled()) {
logger.debug("Sleeping for " + sleepTime);
}
sleeper.sleep(sleepTime);
}
catch (InterruptedException e) {
throw new BackOffInterruptedException("Thread interrupted while sleeping", e);
}
} | [
"public",
"void",
"backOff",
"(",
"BackOffContext",
"backOffContext",
")",
"throws",
"BackOffInterruptedException",
"{",
"ExponentialBackOffContext",
"context",
"=",
"(",
"ExponentialBackOffContext",
")",
"backOffContext",
";",
"try",
"{",
"long",
"sleepTime",
"=",
"con... | Pause for a length of time equal to ' <code>exp(backOffContext.expSeed)</code>'. | [
"Pause",
"for",
"a",
"length",
"of",
"time",
"equal",
"to",
"<code",
">",
"exp",
"(",
"backOffContext",
".",
"expSeed",
")",
"<",
"/",
"code",
">",
"."
] | train | https://github.com/spring-projects/spring-retry/blob/e2b0555f96594c2321990d0deeac45fc44d4f123/src/main/java/org/springframework/retry/backoff/ExponentialBackOffPolicy.java#L170-L183 |
aoindustries/aocode-public | src/main/java/com/aoindustries/servlet/http/LastModifiedServlet.java | LastModifiedServlet.getLastModified | public static long getLastModified(ServletContext servletContext, HttpServletRequest request, String path) {
return getLastModified(
servletContext,
request,
path,
FileUtils.getExtension(path)
);
} | java | public static long getLastModified(ServletContext servletContext, HttpServletRequest request, String path) {
return getLastModified(
servletContext,
request,
path,
FileUtils.getExtension(path)
);
} | [
"public",
"static",
"long",
"getLastModified",
"(",
"ServletContext",
"servletContext",
",",
"HttpServletRequest",
"request",
",",
"String",
"path",
")",
"{",
"return",
"getLastModified",
"(",
"servletContext",
",",
"request",
",",
"path",
",",
"FileUtils",
".",
"... | Automatically determines extension from path.
@see #getLastModified(javax.servlet.ServletContext, java.lang.String, java.lang.String) | [
"Automatically",
"determines",
"extension",
"from",
"path",
"."
] | train | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/servlet/http/LastModifiedServlet.java#L421-L428 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/util/search/support/BinarySearch.java | BinarySearch.doSearch | protected <E> E doSearch(final List<E> list) {
if (!list.isEmpty()) {
int matchIndex = (list.size() / 2);
E element = list.get(matchIndex);
int matchResult = getMatcher().match(element);
if (matchResult == 0) {
return element;
}
else if (matchResult < 0) {
return doSearch(list.subList(0, matchIndex));
}
else {
return doSearch(list.subList(matchIndex + 1, list.size()));
}
}
return null;
} | java | protected <E> E doSearch(final List<E> list) {
if (!list.isEmpty()) {
int matchIndex = (list.size() / 2);
E element = list.get(matchIndex);
int matchResult = getMatcher().match(element);
if (matchResult == 0) {
return element;
}
else if (matchResult < 0) {
return doSearch(list.subList(0, matchIndex));
}
else {
return doSearch(list.subList(matchIndex + 1, list.size()));
}
}
return null;
} | [
"protected",
"<",
"E",
">",
"E",
"doSearch",
"(",
"final",
"List",
"<",
"E",
">",
"list",
")",
"{",
"if",
"(",
"!",
"list",
".",
"isEmpty",
"(",
")",
")",
"{",
"int",
"matchIndex",
"=",
"(",
"list",
".",
"size",
"(",
")",
"/",
"2",
")",
";",
... | Performs the actual (binary) search of an ordered collection (List) of elements in search of a single element
matching the criteria defined by the Matcher.
@param <E> the Class type of the elements in the List.
@param list the List of elements to search.
@return a single element of the List matching the criteria defined by the Matcher or null if no element in the List
matches the criteria defined by the Matcher.
@see #getMatcher()
@see #search(java.util.Collection)
@see java.util.List | [
"Performs",
"the",
"actual",
"(",
"binary",
")",
"search",
"of",
"an",
"ordered",
"collection",
"(",
"List",
")",
"of",
"elements",
"in",
"search",
"of",
"a",
"single",
"element",
"matching",
"the",
"criteria",
"defined",
"by",
"the",
"Matcher",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/util/search/support/BinarySearch.java#L73-L91 |
jpkrohling/secret-store | common/src/main/java/org/keycloak/secretstore/common/AuthServerRequestExecutor.java | AuthServerRequestExecutor.execute | public String execute(String url, String urlParameters, String clientId, String secret, String method) throws
Exception {
HttpURLConnection connection;
String credentials = clientId + ":" + secret;
String authorizationHeader = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());
if ("POST".equalsIgnoreCase(method)) {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", authorizationHeader);
connection.setDoInput(true);
connection.setDoOutput(true);
if (null != urlParameters) {
try (PrintWriter out = new PrintWriter(connection.getOutputStream())) {
out.print(urlParameters);
}
}
} else {
connection = (HttpURLConnection) new URL(url + "?" + urlParameters).openConnection();
connection.setRequestMethod(method);
connection.setRequestProperty("Authorization", authorizationHeader);
}
int timeout = Integer.parseInt(System.getProperty("org.hawkular.accounts.http.timeout", "5000"));
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
StringBuilder response = new StringBuilder();
int statusCode;
try {
statusCode = connection.getResponseCode();
} catch (SocketTimeoutException timeoutException) {
throw new UsernamePasswordConversionException("Timed out when trying to contact the Keycloak server.");
}
InputStream inputStream;
if (statusCode < 300) {
inputStream = connection.getInputStream();
} else {
inputStream = connection.getErrorStream();
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
for (String line; (line = reader.readLine()) != null; ) {
response.append(line);
}
}
return response.toString();
} | java | public String execute(String url, String urlParameters, String clientId, String secret, String method) throws
Exception {
HttpURLConnection connection;
String credentials = clientId + ":" + secret;
String authorizationHeader = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());
if ("POST".equalsIgnoreCase(method)) {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", authorizationHeader);
connection.setDoInput(true);
connection.setDoOutput(true);
if (null != urlParameters) {
try (PrintWriter out = new PrintWriter(connection.getOutputStream())) {
out.print(urlParameters);
}
}
} else {
connection = (HttpURLConnection) new URL(url + "?" + urlParameters).openConnection();
connection.setRequestMethod(method);
connection.setRequestProperty("Authorization", authorizationHeader);
}
int timeout = Integer.parseInt(System.getProperty("org.hawkular.accounts.http.timeout", "5000"));
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
StringBuilder response = new StringBuilder();
int statusCode;
try {
statusCode = connection.getResponseCode();
} catch (SocketTimeoutException timeoutException) {
throw new UsernamePasswordConversionException("Timed out when trying to contact the Keycloak server.");
}
InputStream inputStream;
if (statusCode < 300) {
inputStream = connection.getInputStream();
} else {
inputStream = connection.getErrorStream();
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
for (String line; (line = reader.readLine()) != null; ) {
response.append(line);
}
}
return response.toString();
} | [
"public",
"String",
"execute",
"(",
"String",
"url",
",",
"String",
"urlParameters",
",",
"String",
"clientId",
",",
"String",
"secret",
",",
"String",
"method",
")",
"throws",
"Exception",
"{",
"HttpURLConnection",
"connection",
";",
"String",
"credentials",
"=... | Performs an HTTP call to the Keycloak server, returning the server's response as String.
@param url the full URL to call, including protocol, host, port and path.
@param urlParameters the HTTP Query Parameters properly encoded and without the leading "?".
@param clientId the OAuth client ID.
@param secret the OAuth client secret.
@param method the HTTP method to use (GET or POST). If anything other than POST is sent, GET is used.
@return a String with the response from the Keycloak server, in both success and error scenarios
@throws Exception if communication problems with the Keycloak server occurs. | [
"Performs",
"an",
"HTTP",
"call",
"to",
"the",
"Keycloak",
"server",
"returning",
"the",
"server",
"s",
"response",
"as",
"String",
"."
] | train | https://github.com/jpkrohling/secret-store/blob/f136ea6286a6919cc767d0b4a5e84f333c33f483/common/src/main/java/org/keycloak/secretstore/common/AuthServerRequestExecutor.java#L66-L120 |
looly/hutool | hutool-db/src/main/java/cn/hutool/db/sql/SqlExecutor.java | SqlExecutor.executeBatch | public static int[] executeBatch(Connection conn, String sql, Object[]... paramsBatch) throws SQLException {
return executeBatch(conn, sql, new ArrayIter<Object[]>(paramsBatch));
} | java | public static int[] executeBatch(Connection conn, String sql, Object[]... paramsBatch) throws SQLException {
return executeBatch(conn, sql, new ArrayIter<Object[]>(paramsBatch));
} | [
"public",
"static",
"int",
"[",
"]",
"executeBatch",
"(",
"Connection",
"conn",
",",
"String",
"sql",
",",
"Object",
"[",
"]",
"...",
"paramsBatch",
")",
"throws",
"SQLException",
"{",
"return",
"executeBatch",
"(",
"conn",
",",
"sql",
",",
"new",
"ArrayIt... | 批量执行非查询语句<br>
语句包括 插入、更新、删除<br>
此方法不会关闭Connection
@param conn 数据库连接对象
@param sql SQL
@param paramsBatch 批量的参数
@return 每个SQL执行影响的行数
@throws SQLException SQL执行异常 | [
"批量执行非查询语句<br",
">",
"语句包括",
"插入、更新、删除<br",
">",
"此方法不会关闭Connection"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/sql/SqlExecutor.java#L164-L166 |
Azure/autorest-clientruntime-for-java | azure-client-runtime/src/main/java/com/microsoft/azure/AzureAsyncOperation.java | AzureAsyncOperation.fromResponse | static AzureAsyncOperation fromResponse(SerializerAdapter<?> serializerAdapter, Response<ResponseBody> response) throws CloudException {
AzureAsyncOperation asyncOperation = null;
String rawString = null;
if (response.body() != null) {
try {
rawString = response.body().string();
asyncOperation = serializerAdapter.deserialize(rawString, AzureAsyncOperation.class);
} catch (IOException exception) {
// Exception will be handled below
} finally {
response.body().close();
}
}
if (asyncOperation == null || asyncOperation.status() == null) {
throw new CloudException("polling response does not contain a valid body: " + rawString, response);
}
else {
asyncOperation.rawString = rawString;
}
return asyncOperation;
} | java | static AzureAsyncOperation fromResponse(SerializerAdapter<?> serializerAdapter, Response<ResponseBody> response) throws CloudException {
AzureAsyncOperation asyncOperation = null;
String rawString = null;
if (response.body() != null) {
try {
rawString = response.body().string();
asyncOperation = serializerAdapter.deserialize(rawString, AzureAsyncOperation.class);
} catch (IOException exception) {
// Exception will be handled below
} finally {
response.body().close();
}
}
if (asyncOperation == null || asyncOperation.status() == null) {
throw new CloudException("polling response does not contain a valid body: " + rawString, response);
}
else {
asyncOperation.rawString = rawString;
}
return asyncOperation;
} | [
"static",
"AzureAsyncOperation",
"fromResponse",
"(",
"SerializerAdapter",
"<",
"?",
">",
"serializerAdapter",
",",
"Response",
"<",
"ResponseBody",
">",
"response",
")",
"throws",
"CloudException",
"{",
"AzureAsyncOperation",
"asyncOperation",
"=",
"null",
";",
"Stri... | Creates AzureAsyncOperation from the given HTTP response.
@param serializerAdapter the adapter to use for deserialization
@param response the response
@return the async operation object
@throws CloudException if the deserialization fails or response contains invalid body | [
"Creates",
"AzureAsyncOperation",
"from",
"the",
"given",
"HTTP",
"response",
"."
] | train | https://github.com/Azure/autorest-clientruntime-for-java/blob/04621e07dbb0456dd5459dd641f06a9fd4f3abad/azure-client-runtime/src/main/java/com/microsoft/azure/AzureAsyncOperation.java#L134-L154 |
strator-dev/greenpepper | greenpepper-open/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/velocity/ConfluenceGreenPepper.java | ConfluenceGreenPepper.saveExecutionResult | public void saveExecutionResult(Page page, String sut, XmlReport xmlReport) throws GreenPepperServerException {
Specification specification = getSpecification(page);
List<SystemUnderTest> systemUnderTests = getSystemsUnderTests(page.getSpaceKey());
SystemUnderTest systemUnderTest = null;
for (SystemUnderTest s : systemUnderTests) {
if (s.getName().equals(sut)) {
systemUnderTest = s;
break;
}
}
if (systemUnderTest == null) {
throw new GreenPepperServerException(GreenPepperServerErrorKey.SUT_NOT_FOUND, sut);
}
getGPServerService().createExecution(systemUnderTest, specification, xmlReport);
} | java | public void saveExecutionResult(Page page, String sut, XmlReport xmlReport) throws GreenPepperServerException {
Specification specification = getSpecification(page);
List<SystemUnderTest> systemUnderTests = getSystemsUnderTests(page.getSpaceKey());
SystemUnderTest systemUnderTest = null;
for (SystemUnderTest s : systemUnderTests) {
if (s.getName().equals(sut)) {
systemUnderTest = s;
break;
}
}
if (systemUnderTest == null) {
throw new GreenPepperServerException(GreenPepperServerErrorKey.SUT_NOT_FOUND, sut);
}
getGPServerService().createExecution(systemUnderTest, specification, xmlReport);
} | [
"public",
"void",
"saveExecutionResult",
"(",
"Page",
"page",
",",
"String",
"sut",
",",
"XmlReport",
"xmlReport",
")",
"throws",
"GreenPepperServerException",
"{",
"Specification",
"specification",
"=",
"getSpecification",
"(",
"page",
")",
";",
"List",
"<",
"Sys... | <p>saveExecutionResult.</p>
@param page a {@link com.atlassian.confluence.pages.Page} object.
@param sut a {@link java.lang.String} object.
@param xmlReport a {@link com.greenpepper.report.XmlReport} object.
@throws com.greenpepper.server.GreenPepperServerException if any. | [
"<p",
">",
"saveExecutionResult",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper-open/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/velocity/ConfluenceGreenPepper.java#L1231-L1250 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/db/entitymanager/DbEntityManager.java | DbEntityManager.isOptimisticLockingException | private boolean isOptimisticLockingException(DbOperation failedOperation, Throwable cause) {
boolean isConstraintViolation = ExceptionUtil.checkForeignKeyConstraintViolation(cause);
boolean isVariableIntegrityViolation = ExceptionUtil.checkVariableIntegrityViolation(cause);
if (isVariableIntegrityViolation) {
return true;
} else if (
isConstraintViolation
&& failedOperation instanceof DbEntityOperation
&& ((DbEntityOperation) failedOperation).getEntity() instanceof HasDbReferences
&& (failedOperation.getOperationType().equals(DbOperationType.INSERT)
|| failedOperation.getOperationType().equals(DbOperationType.UPDATE))
) {
DbEntity entity = ((DbEntityOperation) failedOperation).getEntity();
for (Map.Entry<String, Class> reference : ((HasDbReferences)entity).getReferencedEntitiesIdAndClass().entrySet()) {
DbEntity referencedEntity = this.persistenceSession.selectById(reference.getValue(), reference.getKey());
if (referencedEntity == null) {
return true;
}
}
}
return false;
} | java | private boolean isOptimisticLockingException(DbOperation failedOperation, Throwable cause) {
boolean isConstraintViolation = ExceptionUtil.checkForeignKeyConstraintViolation(cause);
boolean isVariableIntegrityViolation = ExceptionUtil.checkVariableIntegrityViolation(cause);
if (isVariableIntegrityViolation) {
return true;
} else if (
isConstraintViolation
&& failedOperation instanceof DbEntityOperation
&& ((DbEntityOperation) failedOperation).getEntity() instanceof HasDbReferences
&& (failedOperation.getOperationType().equals(DbOperationType.INSERT)
|| failedOperation.getOperationType().equals(DbOperationType.UPDATE))
) {
DbEntity entity = ((DbEntityOperation) failedOperation).getEntity();
for (Map.Entry<String, Class> reference : ((HasDbReferences)entity).getReferencedEntitiesIdAndClass().entrySet()) {
DbEntity referencedEntity = this.persistenceSession.selectById(reference.getValue(), reference.getKey());
if (referencedEntity == null) {
return true;
}
}
}
return false;
} | [
"private",
"boolean",
"isOptimisticLockingException",
"(",
"DbOperation",
"failedOperation",
",",
"Throwable",
"cause",
")",
"{",
"boolean",
"isConstraintViolation",
"=",
"ExceptionUtil",
".",
"checkForeignKeyConstraintViolation",
"(",
"cause",
")",
";",
"boolean",
"isVar... | Checks if the reason for a persistence exception was the foreign-key referencing of a (currently)
non-existing entity. This might happen with concurrent transactions, leading to an
OptimisticLockingException.
@param failedOperation
@return | [
"Checks",
"if",
"the",
"reason",
"for",
"a",
"persistence",
"exception",
"was",
"the",
"foreign",
"-",
"key",
"referencing",
"of",
"a",
"(",
"currently",
")",
"non",
"-",
"existing",
"entity",
".",
"This",
"might",
"happen",
"with",
"concurrent",
"transactio... | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/db/entitymanager/DbEntityManager.java#L405-L432 |
samskivert/samskivert | src/main/java/com/samskivert/util/ProcessLogger.java | ProcessLogger.copyMergedOutput | public static void copyMergedOutput (Logger target, String name, Process process)
{
new StreamReader(target, name + " output", process.getInputStream()).start();
} | java | public static void copyMergedOutput (Logger target, String name, Process process)
{
new StreamReader(target, name + " output", process.getInputStream()).start();
} | [
"public",
"static",
"void",
"copyMergedOutput",
"(",
"Logger",
"target",
",",
"String",
"name",
",",
"Process",
"process",
")",
"{",
"new",
"StreamReader",
"(",
"target",
",",
"name",
"+",
"\" output\"",
",",
"process",
".",
"getInputStream",
"(",
")",
")",
... | Starts a thread to copy the output of the supplied process's stdout stream to the supplied
target logger (it assumes the process was created with a ProcessBuilder and the stdout and
stderr streams have been merged).
@see #copyOutput | [
"Starts",
"a",
"thread",
"to",
"copy",
"the",
"output",
"of",
"the",
"supplied",
"process",
"s",
"stdout",
"stream",
"to",
"the",
"supplied",
"target",
"logger",
"(",
"it",
"assumes",
"the",
"process",
"was",
"created",
"with",
"a",
"ProcessBuilder",
"and",
... | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/ProcessLogger.java#L42-L45 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java | AsynchronousRequest.getWvWMatchStat | public void getWvWMatchStat(int worldID, Callback<WvWMatchStat> callback) throws NullPointerException {
gw2API.getWvWMatchStatUsingWorld(Integer.toString(worldID)).enqueue(callback);
} | java | public void getWvWMatchStat(int worldID, Callback<WvWMatchStat> callback) throws NullPointerException {
gw2API.getWvWMatchStatUsingWorld(Integer.toString(worldID)).enqueue(callback);
} | [
"public",
"void",
"getWvWMatchStat",
"(",
"int",
"worldID",
",",
"Callback",
"<",
"WvWMatchStat",
">",
"callback",
")",
"throws",
"NullPointerException",
"{",
"gw2API",
".",
"getWvWMatchStatUsingWorld",
"(",
"Integer",
".",
"toString",
"(",
"worldID",
")",
")",
... | For more info on WvW matches API go <a href="https://wiki.guildwars2.com/wiki/API:2/wvw/matches">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param worldID {@link World#id}
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws NullPointerException if given {@link Callback} is empty
@see WvWMatchStat WvW match stat info | [
"For",
"more",
"info",
"on",
"WvW",
"matches",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"wvw",
"/",
"matches",
">",
"here<",
"/",
"a",
">",
"<br",
"/",
">... | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L2694-L2696 |
Azure/azure-sdk-for-java | mediaservices/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/implementation/LiveEventsInner.java | LiveEventsInner.listAsync | public Observable<Page<LiveEventInner>> listAsync(final String resourceGroupName, final String accountName) {
return listWithServiceResponseAsync(resourceGroupName, accountName)
.map(new Func1<ServiceResponse<Page<LiveEventInner>>, Page<LiveEventInner>>() {
@Override
public Page<LiveEventInner> call(ServiceResponse<Page<LiveEventInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<LiveEventInner>> listAsync(final String resourceGroupName, final String accountName) {
return listWithServiceResponseAsync(resourceGroupName, accountName)
.map(new Func1<ServiceResponse<Page<LiveEventInner>>, Page<LiveEventInner>>() {
@Override
public Page<LiveEventInner> call(ServiceResponse<Page<LiveEventInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"LiveEventInner",
">",
">",
"listAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"accountName",
")",
"{",
"return",
"listWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
"... | List Live Events.
Lists the Live Events in the account.
@param resourceGroupName The name of the resource group within the Azure subscription.
@param accountName The Media Services account name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<LiveEventInner> object | [
"List",
"Live",
"Events",
".",
"Lists",
"the",
"Live",
"Events",
"in",
"the",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/implementation/LiveEventsInner.java#L181-L189 |
pravega/pravega | common/src/main/java/io/pravega/common/util/btree/BTreeIndex.java | BTreeIndex.get | public CompletableFuture<ByteArraySegment> get(@NonNull ByteArraySegment key, @NonNull Duration timeout) {
ensureInitialized();
TimeoutTimer timer = new TimeoutTimer(timeout);
// Lookup the page where the Key should exist (if at all).
PageCollection pageCollection = new PageCollection(this.state.get().length);
return locatePage(key, pageCollection, timer)
.thenApplyAsync(page -> page.getPage().searchExact(key), this.executor);
} | java | public CompletableFuture<ByteArraySegment> get(@NonNull ByteArraySegment key, @NonNull Duration timeout) {
ensureInitialized();
TimeoutTimer timer = new TimeoutTimer(timeout);
// Lookup the page where the Key should exist (if at all).
PageCollection pageCollection = new PageCollection(this.state.get().length);
return locatePage(key, pageCollection, timer)
.thenApplyAsync(page -> page.getPage().searchExact(key), this.executor);
} | [
"public",
"CompletableFuture",
"<",
"ByteArraySegment",
">",
"get",
"(",
"@",
"NonNull",
"ByteArraySegment",
"key",
",",
"@",
"NonNull",
"Duration",
"timeout",
")",
"{",
"ensureInitialized",
"(",
")",
";",
"TimeoutTimer",
"timer",
"=",
"new",
"TimeoutTimer",
"("... | Looks up the value of a single key.
@param key A ByteArraySegment representing the key to look up.
@param timeout Timeout for the operation.
@return A CompletableFuture that, when completed normally, will contain the value associated with the given key.
If no value is associated with this key, the Future will complete with null. If the operation failed, the Future
will be completed with the appropriate exception. | [
"Looks",
"up",
"the",
"value",
"of",
"a",
"single",
"key",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/util/btree/BTreeIndex.java#L231-L239 |
playn/playn | scene/src/playn/scene/LayerUtil.java | LayerUtil.bind | public static void bind (Layer layer, final Signal<Clock> paint, final Slot<Clock> onPaint) {
layer.state.connectNotify(new Slot<Layer.State>() {
public void onEmit (Layer.State state) {
_pcon = Closeable.Util.close(_pcon);
if (state == Layer.State.ADDED) _pcon = paint.connect(onPaint);
}
private Closeable _pcon = Closeable.Util.NOOP;
});
} | java | public static void bind (Layer layer, final Signal<Clock> paint, final Slot<Clock> onPaint) {
layer.state.connectNotify(new Slot<Layer.State>() {
public void onEmit (Layer.State state) {
_pcon = Closeable.Util.close(_pcon);
if (state == Layer.State.ADDED) _pcon = paint.connect(onPaint);
}
private Closeable _pcon = Closeable.Util.NOOP;
});
} | [
"public",
"static",
"void",
"bind",
"(",
"Layer",
"layer",
",",
"final",
"Signal",
"<",
"Clock",
">",
"paint",
",",
"final",
"Slot",
"<",
"Clock",
">",
"onPaint",
")",
"{",
"layer",
".",
"state",
".",
"connectNotify",
"(",
"new",
"Slot",
"<",
"Layer",
... | Automatically connects {@code onPaint} to {@code paint} when {@code layer} is added to a scene
graph, and disconnects it when {@code layer} is removed. | [
"Automatically",
"connects",
"{"
] | train | https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/scene/src/playn/scene/LayerUtil.java#L183-L191 |
elki-project/elki | elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/DWOF.java | DWOF.updateSizes | private int updateSizes(DBIDs ids, WritableDataStore<ModifiableDBIDs> labels, WritableIntegerDataStore newSizes) {
// to count the unclustered all over
int countUnmerged = 0;
for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) {
// checking the point's new cluster size after the clustering step
int newClusterSize = labels.get(iter).size();
newSizes.putInt(iter, newClusterSize);
// the point is alone in the cluster --> not merged with other points
if(newClusterSize == 1) {
countUnmerged++;
}
}
return countUnmerged;
} | java | private int updateSizes(DBIDs ids, WritableDataStore<ModifiableDBIDs> labels, WritableIntegerDataStore newSizes) {
// to count the unclustered all over
int countUnmerged = 0;
for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) {
// checking the point's new cluster size after the clustering step
int newClusterSize = labels.get(iter).size();
newSizes.putInt(iter, newClusterSize);
// the point is alone in the cluster --> not merged with other points
if(newClusterSize == 1) {
countUnmerged++;
}
}
return countUnmerged;
} | [
"private",
"int",
"updateSizes",
"(",
"DBIDs",
"ids",
",",
"WritableDataStore",
"<",
"ModifiableDBIDs",
">",
"labels",
",",
"WritableIntegerDataStore",
"newSizes",
")",
"{",
"// to count the unclustered all over",
"int",
"countUnmerged",
"=",
"0",
";",
"for",
"(",
"... | This method updates each object's cluster size after the clustering step.
@param ids Object IDs to process
@param labels references for each object's cluster
@param newSizes the sizes container to be updated
@return the number of unclustered objects | [
"This",
"method",
"updates",
"each",
"object",
"s",
"cluster",
"size",
"after",
"the",
"clustering",
"step",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/DWOF.java#L293-L306 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java | ReviewsImpl.getReviewAsync | public Observable<Review> getReviewAsync(String teamName, String reviewId) {
return getReviewWithServiceResponseAsync(teamName, reviewId).map(new Func1<ServiceResponse<Review>, Review>() {
@Override
public Review call(ServiceResponse<Review> response) {
return response.body();
}
});
} | java | public Observable<Review> getReviewAsync(String teamName, String reviewId) {
return getReviewWithServiceResponseAsync(teamName, reviewId).map(new Func1<ServiceResponse<Review>, Review>() {
@Override
public Review call(ServiceResponse<Review> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Review",
">",
"getReviewAsync",
"(",
"String",
"teamName",
",",
"String",
"reviewId",
")",
"{",
"return",
"getReviewWithServiceResponseAsync",
"(",
"teamName",
",",
"reviewId",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResp... | Returns review details for the review Id passed.
@param teamName Your Team Name.
@param reviewId Id of the review.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the Review object | [
"Returns",
"review",
"details",
"for",
"the",
"review",
"Id",
"passed",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java#L166-L173 |
lucee/Lucee | core/src/main/java/lucee/runtime/converter/WDDXConverter.java | WDDXConverter._serializeList | private String _serializeList(List list, Set<Object> done) throws ConverterException {
StringBuilder sb = new StringBuilder(goIn() + "<array length=" + del + list.size() + del + ">");
ListIterator it = list.listIterator();
while (it.hasNext()) {
sb.append(_serialize(it.next(), done));
}
sb.append(goIn() + "</array>");
return sb.toString();
} | java | private String _serializeList(List list, Set<Object> done) throws ConverterException {
StringBuilder sb = new StringBuilder(goIn() + "<array length=" + del + list.size() + del + ">");
ListIterator it = list.listIterator();
while (it.hasNext()) {
sb.append(_serialize(it.next(), done));
}
sb.append(goIn() + "</array>");
return sb.toString();
} | [
"private",
"String",
"_serializeList",
"(",
"List",
"list",
",",
"Set",
"<",
"Object",
">",
"done",
")",
"throws",
"ConverterException",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"goIn",
"(",
")",
"+",
"\"<array length=\"",
"+",
"del",
"+... | serialize a List (as Array)
@param list List to serialize
@param done
@return serialized list
@throws ConverterException | [
"serialize",
"a",
"List",
"(",
"as",
"Array",
")"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/converter/WDDXConverter.java#L189-L199 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java | AppServicePlansInner.beginCreateOrUpdateAsync | public Observable<AppServicePlanInner> beginCreateOrUpdateAsync(String resourceGroupName, String name, AppServicePlanInner appServicePlan) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, name, appServicePlan).map(new Func1<ServiceResponse<AppServicePlanInner>, AppServicePlanInner>() {
@Override
public AppServicePlanInner call(ServiceResponse<AppServicePlanInner> response) {
return response.body();
}
});
} | java | public Observable<AppServicePlanInner> beginCreateOrUpdateAsync(String resourceGroupName, String name, AppServicePlanInner appServicePlan) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, name, appServicePlan).map(new Func1<ServiceResponse<AppServicePlanInner>, AppServicePlanInner>() {
@Override
public AppServicePlanInner call(ServiceResponse<AppServicePlanInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"AppServicePlanInner",
">",
"beginCreateOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
",",
"AppServicePlanInner",
"appServicePlan",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resourceGroup... | Creates or updates an App Service Plan.
Creates or updates an App Service Plan.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service plan.
@param appServicePlan Details of the App Service plan.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the AppServicePlanInner object | [
"Creates",
"or",
"updates",
"an",
"App",
"Service",
"Plan",
".",
"Creates",
"or",
"updates",
"an",
"App",
"Service",
"Plan",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java#L785-L792 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/NetworkInterfacesInner.java | NetworkInterfacesInner.getVirtualMachineScaleSetNetworkInterface | public NetworkInterfaceInner getVirtualMachineScaleSetNetworkInterface(String resourceGroupName, String virtualMachineScaleSetName, String virtualmachineIndex, String networkInterfaceName, String expand) {
return getVirtualMachineScaleSetNetworkInterfaceWithServiceResponseAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand).toBlocking().single().body();
} | java | public NetworkInterfaceInner getVirtualMachineScaleSetNetworkInterface(String resourceGroupName, String virtualMachineScaleSetName, String virtualmachineIndex, String networkInterfaceName, String expand) {
return getVirtualMachineScaleSetNetworkInterfaceWithServiceResponseAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand).toBlocking().single().body();
} | [
"public",
"NetworkInterfaceInner",
"getVirtualMachineScaleSetNetworkInterface",
"(",
"String",
"resourceGroupName",
",",
"String",
"virtualMachineScaleSetName",
",",
"String",
"virtualmachineIndex",
",",
"String",
"networkInterfaceName",
",",
"String",
"expand",
")",
"{",
"re... | Get the specified network interface in a virtual machine scale set.
@param resourceGroupName The name of the resource group.
@param virtualMachineScaleSetName The name of the virtual machine scale set.
@param virtualmachineIndex The virtual machine index.
@param networkInterfaceName The name of the network interface.
@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 NetworkInterfaceInner object if successful. | [
"Get",
"the",
"specified",
"network",
"interface",
"in",
"a",
"virtual",
"machine",
"scale",
"set",
"."
] | 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/NetworkInterfacesInner.java#L1841-L1843 |
haraldk/TwelveMonkeys | common/common-image/src/main/java/com/twelvemonkeys/image/CopyDither.java | CopyDither.filter | public final BufferedImage filter(BufferedImage pSource, BufferedImage pDest) {
// Create destination image, if none provided
if (pDest == null) {
pDest = createCompatibleDestImage(pSource, getICM(pSource));
}
else if (!(pDest.getColorModel() instanceof IndexColorModel)) {
throw new ImageFilterException("Only IndexColorModel allowed.");
}
// Filter rasters
filter(pSource.getRaster(), pDest.getRaster(), (IndexColorModel) pDest.getColorModel());
return pDest;
} | java | public final BufferedImage filter(BufferedImage pSource, BufferedImage pDest) {
// Create destination image, if none provided
if (pDest == null) {
pDest = createCompatibleDestImage(pSource, getICM(pSource));
}
else if (!(pDest.getColorModel() instanceof IndexColorModel)) {
throw new ImageFilterException("Only IndexColorModel allowed.");
}
// Filter rasters
filter(pSource.getRaster(), pDest.getRaster(), (IndexColorModel) pDest.getColorModel());
return pDest;
} | [
"public",
"final",
"BufferedImage",
"filter",
"(",
"BufferedImage",
"pSource",
",",
"BufferedImage",
"pDest",
")",
"{",
"// Create destination image, if none provided\r",
"if",
"(",
"pDest",
"==",
"null",
")",
"{",
"pDest",
"=",
"createCompatibleDestImage",
"(",
"pSou... | Performs a single-input/single-output dither operation, applying basic
Floyd-Steinberg error-diffusion to the image.
@param pSource the source image
@param pDest the destiantion image
@return the destination image, or a new image, if {@code pDest} was
{@code null}. | [
"Performs",
"a",
"single",
"-",
"input",
"/",
"single",
"-",
"output",
"dither",
"operation",
"applying",
"basic",
"Floyd",
"-",
"Steinberg",
"error",
"-",
"diffusion",
"to",
"the",
"image",
"."
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/CopyDither.java#L195-L208 |
Azure/azure-sdk-for-java | automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/CredentialsInner.java | CredentialsInner.listByAutomationAccountAsync | public Observable<Page<CredentialInner>> listByAutomationAccountAsync(final String resourceGroupName, final String automationAccountName) {
return listByAutomationAccountWithServiceResponseAsync(resourceGroupName, automationAccountName)
.map(new Func1<ServiceResponse<Page<CredentialInner>>, Page<CredentialInner>>() {
@Override
public Page<CredentialInner> call(ServiceResponse<Page<CredentialInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<CredentialInner>> listByAutomationAccountAsync(final String resourceGroupName, final String automationAccountName) {
return listByAutomationAccountWithServiceResponseAsync(resourceGroupName, automationAccountName)
.map(new Func1<ServiceResponse<Page<CredentialInner>>, Page<CredentialInner>>() {
@Override
public Page<CredentialInner> call(ServiceResponse<Page<CredentialInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"CredentialInner",
">",
">",
"listByAutomationAccountAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"automationAccountName",
")",
"{",
"return",
"listByAutomationAccountWithServiceResponseAsync",
"(",
... | Retrieve a list of credentials.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<CredentialInner> object | [
"Retrieve",
"a",
"list",
"of",
"credentials",
"."
] | 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/CredentialsInner.java#L523-L531 |
aws/aws-sdk-java | aws-java-sdk-greengrass/src/main/java/com/amazonaws/services/greengrass/model/CreateConnectorDefinitionRequest.java | CreateConnectorDefinitionRequest.withTags | public CreateConnectorDefinitionRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | java | public CreateConnectorDefinitionRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"CreateConnectorDefinitionRequest",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | Tag(s) to add to the new resource
@param tags
Tag(s) to add to the new resource
@return Returns a reference to this object so that method calls can be chained together. | [
"Tag",
"(",
"s",
")",
"to",
"add",
"to",
"the",
"new",
"resource"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-greengrass/src/main/java/com/amazonaws/services/greengrass/model/CreateConnectorDefinitionRequest.java#L168-L171 |
snowflakedb/snowflake-jdbc | src/main/java/net/snowflake/client/core/SessionUtilExternalBrowser.java | SessionUtilExternalBrowser.getSSOUrl | private String getSSOUrl(int port) throws SFException, SnowflakeSQLException
{
try
{
String serverUrl = loginInput.getServerUrl();
String authenticator = loginInput.getAuthenticator();
URIBuilder fedUriBuilder = new URIBuilder(serverUrl);
fedUriBuilder.setPath(SessionUtil.SF_PATH_AUTHENTICATOR_REQUEST);
URI fedUrlUri = fedUriBuilder.build();
HttpPost postRequest = this.handlers.build(fedUrlUri);
ClientAuthnDTO authnData = new ClientAuthnDTO();
Map<String, Object> data = new HashMap<>();
data.put(ClientAuthnParameter.AUTHENTICATOR.name(), authenticator);
data.put(ClientAuthnParameter.ACCOUNT_NAME.name(),
loginInput.getAccountName());
data.put(ClientAuthnParameter.LOGIN_NAME.name(),
loginInput.getUserName());
data.put(ClientAuthnParameter.BROWSER_MODE_REDIRECT_PORT.name(),
Integer.toString(port));
data.put(ClientAuthnParameter.CLIENT_APP_ID.name(), loginInput.getAppId());
data.put(ClientAuthnParameter.CLIENT_APP_VERSION.name(),
loginInput.getAppVersion());
authnData.setData(data);
String json = mapper.writeValueAsString(authnData);
// attach the login info json body to the post request
StringEntity input = new StringEntity(json, Charset.forName("UTF-8"));
input.setContentType("application/json");
postRequest.setEntity(input);
postRequest.addHeader("accept", "application/json");
String theString = HttpUtil.executeRequest(postRequest,
loginInput.getLoginTimeout(), 0, null);
logger.debug("authenticator-request response: {}", theString);
// general method, same as with data binding
JsonNode jsonNode = mapper.readTree(theString);
// check the success field first
if (!jsonNode.path("success").asBoolean())
{
logger.debug("response = {}", theString);
String errorCode = jsonNode.path("code").asText();
throw new SnowflakeSQLException(
SqlState.SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION,
new Integer(errorCode),
jsonNode.path("message").asText());
}
JsonNode dataNode = jsonNode.path("data");
// session token is in the data field of the returned json response
this.proofKey = dataNode.path("proofKey").asText();
return dataNode.path("ssoUrl").asText();
}
catch (IOException | URISyntaxException ex)
{
throw new SFException(ex, ErrorCode.NETWORK_ERROR, ex.getMessage());
}
} | java | private String getSSOUrl(int port) throws SFException, SnowflakeSQLException
{
try
{
String serverUrl = loginInput.getServerUrl();
String authenticator = loginInput.getAuthenticator();
URIBuilder fedUriBuilder = new URIBuilder(serverUrl);
fedUriBuilder.setPath(SessionUtil.SF_PATH_AUTHENTICATOR_REQUEST);
URI fedUrlUri = fedUriBuilder.build();
HttpPost postRequest = this.handlers.build(fedUrlUri);
ClientAuthnDTO authnData = new ClientAuthnDTO();
Map<String, Object> data = new HashMap<>();
data.put(ClientAuthnParameter.AUTHENTICATOR.name(), authenticator);
data.put(ClientAuthnParameter.ACCOUNT_NAME.name(),
loginInput.getAccountName());
data.put(ClientAuthnParameter.LOGIN_NAME.name(),
loginInput.getUserName());
data.put(ClientAuthnParameter.BROWSER_MODE_REDIRECT_PORT.name(),
Integer.toString(port));
data.put(ClientAuthnParameter.CLIENT_APP_ID.name(), loginInput.getAppId());
data.put(ClientAuthnParameter.CLIENT_APP_VERSION.name(),
loginInput.getAppVersion());
authnData.setData(data);
String json = mapper.writeValueAsString(authnData);
// attach the login info json body to the post request
StringEntity input = new StringEntity(json, Charset.forName("UTF-8"));
input.setContentType("application/json");
postRequest.setEntity(input);
postRequest.addHeader("accept", "application/json");
String theString = HttpUtil.executeRequest(postRequest,
loginInput.getLoginTimeout(), 0, null);
logger.debug("authenticator-request response: {}", theString);
// general method, same as with data binding
JsonNode jsonNode = mapper.readTree(theString);
// check the success field first
if (!jsonNode.path("success").asBoolean())
{
logger.debug("response = {}", theString);
String errorCode = jsonNode.path("code").asText();
throw new SnowflakeSQLException(
SqlState.SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION,
new Integer(errorCode),
jsonNode.path("message").asText());
}
JsonNode dataNode = jsonNode.path("data");
// session token is in the data field of the returned json response
this.proofKey = dataNode.path("proofKey").asText();
return dataNode.path("ssoUrl").asText();
}
catch (IOException | URISyntaxException ex)
{
throw new SFException(ex, ErrorCode.NETWORK_ERROR, ex.getMessage());
}
} | [
"private",
"String",
"getSSOUrl",
"(",
"int",
"port",
")",
"throws",
"SFException",
",",
"SnowflakeSQLException",
"{",
"try",
"{",
"String",
"serverUrl",
"=",
"loginInput",
".",
"getServerUrl",
"(",
")",
";",
"String",
"authenticator",
"=",
"loginInput",
".",
... | Gets SSO URL and proof key
@return SSO URL.
@throws SFException if Snowflake error occurs
@throws SnowflakeSQLException if Snowflake SQL error occurs | [
"Gets",
"SSO",
"URL",
"and",
"proof",
"key"
] | train | https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtilExternalBrowser.java#L188-L254 |
wildfly/wildfly-core | logging/src/main/java/org/jboss/as/logging/LoggingOperations.java | LoggingOperations.addCommitStep | static void addCommitStep(final OperationContext context, final ConfigurationPersistence configurationPersistence) {
// This should only check that it's a server for the commit step. The logging.properties may need to be written
// in ADMIN_ONLY mode
if (context.getProcessType().isServer()) {
context.addStep(new CommitOperationStepHandler(configurationPersistence), Stage.RUNTIME);
}
} | java | static void addCommitStep(final OperationContext context, final ConfigurationPersistence configurationPersistence) {
// This should only check that it's a server for the commit step. The logging.properties may need to be written
// in ADMIN_ONLY mode
if (context.getProcessType().isServer()) {
context.addStep(new CommitOperationStepHandler(configurationPersistence), Stage.RUNTIME);
}
} | [
"static",
"void",
"addCommitStep",
"(",
"final",
"OperationContext",
"context",
",",
"final",
"ConfigurationPersistence",
"configurationPersistence",
")",
"{",
"// This should only check that it's a server for the commit step. The logging.properties may need to be written",
"// in ADMIN_... | Adds a {@link Stage#RUNTIME runtime} step to the context that will commit or rollback any logging changes. Also
if not a logging profile writes the {@code logging.properties} file.
<p>
Note the commit step will only be added if process type is a
{@linkplain org.jboss.as.controller.ProcessType#isServer() server}.
</p>
@param context the context to add the step to
@param configurationPersistence the configuration to commit | [
"Adds",
"a",
"{",
"@link",
"Stage#RUNTIME",
"runtime",
"}",
"step",
"to",
"the",
"context",
"that",
"will",
"commit",
"or",
"rollback",
"any",
"logging",
"changes",
".",
"Also",
"if",
"not",
"a",
"logging",
"profile",
"writes",
"the",
"{",
"@code",
"loggin... | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/logging/src/main/java/org/jboss/as/logging/LoggingOperations.java#L62-L68 |
JOML-CI/JOML | src/org/joml/Intersectionf.java | Intersectionf.intersectSphereSphere | public static boolean intersectSphereSphere(Vector3fc centerA, float radiusSquaredA, Vector3fc centerB, float radiusSquaredB, Vector4f centerAndRadiusOfIntersectionCircle) {
return intersectSphereSphere(centerA.x(), centerA.y(), centerA.z(), radiusSquaredA, centerB.x(), centerB.y(), centerB.z(), radiusSquaredB, centerAndRadiusOfIntersectionCircle);
} | java | public static boolean intersectSphereSphere(Vector3fc centerA, float radiusSquaredA, Vector3fc centerB, float radiusSquaredB, Vector4f centerAndRadiusOfIntersectionCircle) {
return intersectSphereSphere(centerA.x(), centerA.y(), centerA.z(), radiusSquaredA, centerB.x(), centerB.y(), centerB.z(), radiusSquaredB, centerAndRadiusOfIntersectionCircle);
} | [
"public",
"static",
"boolean",
"intersectSphereSphere",
"(",
"Vector3fc",
"centerA",
",",
"float",
"radiusSquaredA",
",",
"Vector3fc",
"centerB",
",",
"float",
"radiusSquaredB",
",",
"Vector4f",
"centerAndRadiusOfIntersectionCircle",
")",
"{",
"return",
"intersectSphereSp... | Test whether the one sphere with center <code>centerA</code> and square radius <code>radiusSquaredA</code> intersects the other
sphere with center <code>centerB</code> and square radius <code>radiusSquaredB</code>, and store the center of the circle of
intersection in the <code>(x, y, z)</code> components of the supplied vector and the radius of that circle in the w component.
<p>
The normal vector of the circle of intersection can simply be obtained by subtracting the center of either sphere from the other.
<p>
Reference: <a href="http://gamedev.stackexchange.com/questions/75756/sphere-sphere-intersection-and-circle-sphere-intersection">http://gamedev.stackexchange.com</a>
@param centerA
the first sphere's center
@param radiusSquaredA
the square of the first sphere's radius
@param centerB
the second sphere's center
@param radiusSquaredB
the square of the second sphere's radius
@param centerAndRadiusOfIntersectionCircle
will hold the center of the circle of intersection in the <code>(x, y, z)</code> components and the radius in the w component
@return <code>true</code> iff both spheres intersect; <code>false</code> otherwise | [
"Test",
"whether",
"the",
"one",
"sphere",
"with",
"center",
"<code",
">",
"centerA<",
"/",
"code",
">",
"and",
"square",
"radius",
"<code",
">",
"radiusSquaredA<",
"/",
"code",
">",
"intersects",
"the",
"other",
"sphere",
"with",
"center",
"<code",
">",
"... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Intersectionf.java#L805-L807 |
exoplatform/jcr | applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupClientImpl.java | BackupClientImpl.getWorkspaceEntry | private WorkspaceEntry getWorkspaceEntry(InputStream wEntryStream, String repositoryName, String workspaceName)
throws FileNotFoundException, JiBXException, RepositoryConfigurationException
{
RepositoryEntry rEntry = getRepositoryEntry(wEntryStream, repositoryName);
WorkspaceEntry wsEntry = null;
for (WorkspaceEntry wEntry : rEntry.getWorkspaceEntries())
if (wEntry.getName().equals(workspaceName))
wsEntry = wEntry;
if (wsEntry == null)
{
throw new IllegalStateException("Can not find the workspace '" + workspaceName + "' in configuration.");
}
return wsEntry;
} | java | private WorkspaceEntry getWorkspaceEntry(InputStream wEntryStream, String repositoryName, String workspaceName)
throws FileNotFoundException, JiBXException, RepositoryConfigurationException
{
RepositoryEntry rEntry = getRepositoryEntry(wEntryStream, repositoryName);
WorkspaceEntry wsEntry = null;
for (WorkspaceEntry wEntry : rEntry.getWorkspaceEntries())
if (wEntry.getName().equals(workspaceName))
wsEntry = wEntry;
if (wsEntry == null)
{
throw new IllegalStateException("Can not find the workspace '" + workspaceName + "' in configuration.");
}
return wsEntry;
} | [
"private",
"WorkspaceEntry",
"getWorkspaceEntry",
"(",
"InputStream",
"wEntryStream",
",",
"String",
"repositoryName",
",",
"String",
"workspaceName",
")",
"throws",
"FileNotFoundException",
",",
"JiBXException",
",",
"RepositoryConfigurationException",
"{",
"RepositoryEntry"... | getWorkspaceEntry.
@param wEntryStream
InputStream, the workspace configuration
@param workspaceName
String, the workspace name
@return WorkspaceEntry
return the workspace entry
@throws FileNotFoundException
will be generated the FileNotFoundException
@throws JiBXException
will be generated the JiBXException
@throws RepositoryConfigurationException
will be generated the RepositoryConfigurationException | [
"getWorkspaceEntry",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupClientImpl.java#L1214-L1231 |
fcrepo3/fcrepo | fcrepo-server/src/main/java/org/fcrepo/server/journal/readerwriter/multicast/rmi/RmiTransport.java | RmiTransport.openFile | @Override
public void openFile(String repositoryHash,
String filename,
Date currentDate) throws JournalException {
try {
super.testStateChange(State.FILE_OPEN);
writer = new RmiTransportWriter(receiver, repositoryHash, filename);
xmlWriter =
new IndentingXMLEventWriter(XMLOutputFactory
.newInstance()
.createXMLEventWriter(new BufferedWriter(writer,
bufferSize)));
parent.writeDocumentHeader(xmlWriter, repositoryHash, currentDate);
super.setState(State.FILE_OPEN);
} catch (XMLStreamException e) {
throw new JournalException(e);
} catch (FactoryConfigurationError e) {
throw new JournalException(e);
}
} | java | @Override
public void openFile(String repositoryHash,
String filename,
Date currentDate) throws JournalException {
try {
super.testStateChange(State.FILE_OPEN);
writer = new RmiTransportWriter(receiver, repositoryHash, filename);
xmlWriter =
new IndentingXMLEventWriter(XMLOutputFactory
.newInstance()
.createXMLEventWriter(new BufferedWriter(writer,
bufferSize)));
parent.writeDocumentHeader(xmlWriter, repositoryHash, currentDate);
super.setState(State.FILE_OPEN);
} catch (XMLStreamException e) {
throw new JournalException(e);
} catch (FactoryConfigurationError e) {
throw new JournalException(e);
}
} | [
"@",
"Override",
"public",
"void",
"openFile",
"(",
"String",
"repositoryHash",
",",
"String",
"filename",
",",
"Date",
"currentDate",
")",
"throws",
"JournalException",
"{",
"try",
"{",
"super",
".",
"testStateChange",
"(",
"State",
".",
"FILE_OPEN",
")",
";"... | check state, send the open request, open a very special writer, write the
file opening, set state | [
"check",
"state",
"send",
"the",
"open",
"request",
"open",
"a",
"very",
"special",
"writer",
"write",
"the",
"file",
"opening",
"set",
"state"
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/readerwriter/multicast/rmi/RmiTransport.java#L169-L191 |
elki-project/elki | elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/optionhandling/OptionUtil.java | OptionUtil.println | private static void println(StringBuilder buf, int width, String data) {
for(String line : FormatUtil.splitAtLastBlank(data, width)) {
buf.append(line);
if(!line.endsWith(FormatUtil.NEWLINE)) {
buf.append(FormatUtil.NEWLINE);
}
}
} | java | private static void println(StringBuilder buf, int width, String data) {
for(String line : FormatUtil.splitAtLastBlank(data, width)) {
buf.append(line);
if(!line.endsWith(FormatUtil.NEWLINE)) {
buf.append(FormatUtil.NEWLINE);
}
}
} | [
"private",
"static",
"void",
"println",
"(",
"StringBuilder",
"buf",
",",
"int",
"width",
",",
"String",
"data",
")",
"{",
"for",
"(",
"String",
"line",
":",
"FormatUtil",
".",
"splitAtLastBlank",
"(",
"data",
",",
"width",
")",
")",
"{",
"buf",
".",
"... | Simple writing helper with no indentation.
@param buf Buffer to write to
@param width Width to use for linewraps
@param data Data to write. | [
"Simple",
"writing",
"helper",
"with",
"no",
"indentation",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/optionhandling/OptionUtil.java#L107-L114 |
strator-dev/greenpepper | greenpepper/core/src/main/java/com/greenpepper/reflect/AbstractFixture.java | AbstractFixture.getGetter | protected Method getGetter(Class type, String name)
{
return introspector(type).getGetter( toJavaIdentifierForm(name));
} | java | protected Method getGetter(Class type, String name)
{
return introspector(type).getGetter( toJavaIdentifierForm(name));
} | [
"protected",
"Method",
"getGetter",
"(",
"Class",
"type",
",",
"String",
"name",
")",
"{",
"return",
"introspector",
"(",
"type",
")",
".",
"getGetter",
"(",
"toJavaIdentifierForm",
"(",
"name",
")",
")",
";",
"}"
] | <p>getGetter.</p>
@param type a {@link java.lang.Class} object.
@param name a {@link java.lang.String} object.
@return a {@link java.lang.reflect.Method} object. | [
"<p",
">",
"getGetter",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/core/src/main/java/com/greenpepper/reflect/AbstractFixture.java#L130-L133 |
apereo/cas | support/cas-server-support-surrogate-authentication-couchdb/src/main/java/org/apereo/cas/couchdb/surrogate/SurrogateAuthorizationCouchDbRepository.java | SurrogateAuthorizationCouchDbRepository.findBySurrogatePrincipal | @View(name = "by_surrogate_principal", map = "function(doc) { if(doc.surrogate && doc.principal) { emit([doc.principal, doc.surrogate], doc) } }")
public List<CouchDbSurrogateAuthorization> findBySurrogatePrincipal(final String surrogate, final String principal) {
return queryView("by_surrogate_principal", ComplexKey.of(principal, surrogate));
} | java | @View(name = "by_surrogate_principal", map = "function(doc) { if(doc.surrogate && doc.principal) { emit([doc.principal, doc.surrogate], doc) } }")
public List<CouchDbSurrogateAuthorization> findBySurrogatePrincipal(final String surrogate, final String principal) {
return queryView("by_surrogate_principal", ComplexKey.of(principal, surrogate));
} | [
"@",
"View",
"(",
"name",
"=",
"\"by_surrogate_principal\"",
",",
"map",
"=",
"\"function(doc) { if(doc.surrogate && doc.principal) { emit([doc.principal, doc.surrogate], doc) } }\"",
")",
"public",
"List",
"<",
"CouchDbSurrogateAuthorization",
">",
"findBySurrogatePrincipal",
"(",... | Find by surrogate, principal, service touple for authorization check.
@param surrogate Surrogate user to validate access.
@param principal Principal to validate the surrogate can access.
@return Surrogate/principal if authorized | [
"Find",
"by",
"surrogate",
"principal",
"service",
"touple",
"for",
"authorization",
"check",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-surrogate-authentication-couchdb/src/main/java/org/apereo/cas/couchdb/surrogate/SurrogateAuthorizationCouchDbRepository.java#L40-L43 |
srikalyc/Sql4D | Sql4Ddriver/src/main/java/com/yahoo/sql4d/sql4ddriver/BaseJoiner.java | BaseJoiner.dataItemAt | protected JSONObject dataItemAt(JSONObject jsonItem, RequestType requestType, ActionType action) {
JSONObject eachRow = null;
if (requestType == RequestType.GROUPBY) {
eachRow = jsonItem.getJSONObject("event");
} else if (requestType == RequestType.TIMESERIES) {
eachRow = jsonItem.getJSONObject("result");
} else if (requestType == RequestType.TOPN) {
eachRow = jsonItem;
}
return eachRow;
} | java | protected JSONObject dataItemAt(JSONObject jsonItem, RequestType requestType, ActionType action) {
JSONObject eachRow = null;
if (requestType == RequestType.GROUPBY) {
eachRow = jsonItem.getJSONObject("event");
} else if (requestType == RequestType.TIMESERIES) {
eachRow = jsonItem.getJSONObject("result");
} else if (requestType == RequestType.TOPN) {
eachRow = jsonItem;
}
return eachRow;
} | [
"protected",
"JSONObject",
"dataItemAt",
"(",
"JSONObject",
"jsonItem",
",",
"RequestType",
"requestType",
",",
"ActionType",
"action",
")",
"{",
"JSONObject",
"eachRow",
"=",
"null",
";",
"if",
"(",
"requestType",
"==",
"RequestType",
".",
"GROUPBY",
")",
"{",
... | Extract the data item from json(based on the request type) and also fill in the
headers as a side affect.
@param jsonItem
@param requestType
@param action
@return | [
"Extract",
"the",
"data",
"item",
"from",
"json",
"(",
"based",
"on",
"the",
"request",
"type",
")",
"and",
"also",
"fill",
"in",
"the",
"headers",
"as",
"a",
"side",
"affect",
"."
] | train | https://github.com/srikalyc/Sql4D/blob/2c052fe60ead5a16277c798a3440de7d4f6f24f6/Sql4Ddriver/src/main/java/com/yahoo/sql4d/sql4ddriver/BaseJoiner.java#L71-L81 |
jfinal/jfinal | src/main/java/com/jfinal/plugin/activerecord/Model.java | Model.getSqlPara | public SqlPara getSqlPara(String key, Model model) {
return getSqlPara(key, model.attrs);
} | java | public SqlPara getSqlPara(String key, Model model) {
return getSqlPara(key, model.attrs);
} | [
"public",
"SqlPara",
"getSqlPara",
"(",
"String",
"key",
",",
"Model",
"model",
")",
"{",
"return",
"getSqlPara",
"(",
"key",
",",
"model",
".",
"attrs",
")",
";",
"}"
] | 可以在模板中利用 Model 自身的属性参与动态生成 sql,例如:
select * from user where nickName = #(nickName)
new Account().setNickName("James").getSqlPara(...)
注意:由于 dao 对象上的 attrs 不允许读写,不要调用其 getSqlPara(String) 方法
public SqlPara getSqlPara(String key) {
return getSqlPara(key, this.attrs);
} | [
"可以在模板中利用",
"Model",
"自身的属性参与动态生成",
"sql,例如:",
"select",
"*",
"from",
"user",
"where",
"nickName",
"=",
"#",
"(",
"nickName",
")",
"new",
"Account",
"()",
".",
"setNickName",
"(",
"James",
")",
".",
"getSqlPara",
"(",
"...",
")"
] | train | https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/plugin/activerecord/Model.java#L1038-L1040 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/application/config/support/UIManagerConfigurer.java | UIManagerConfigurer.installPrePackagedUIManagerDefaults | private void installPrePackagedUIManagerDefaults() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
UIManager.put("Tree.line", "Angled");
UIManager.put("Tree.leafIcon", null);
UIManager.put("Tree.closedIcon", null);
UIManager.put("Tree.openIcon", null);
UIManager.put("Tree.rightChildIndent", new Integer(10));
} catch (Exception e) {
throw new ApplicationException("Unable to set defaults", e);
}
} | java | private void installPrePackagedUIManagerDefaults() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
UIManager.put("Tree.line", "Angled");
UIManager.put("Tree.leafIcon", null);
UIManager.put("Tree.closedIcon", null);
UIManager.put("Tree.openIcon", null);
UIManager.put("Tree.rightChildIndent", new Integer(10));
} catch (Exception e) {
throw new ApplicationException("Unable to set defaults", e);
}
} | [
"private",
"void",
"installPrePackagedUIManagerDefaults",
"(",
")",
"{",
"try",
"{",
"UIManager",
".",
"setLookAndFeel",
"(",
"UIManager",
".",
"getSystemLookAndFeelClassName",
"(",
")",
")",
";",
"UIManager",
".",
"put",
"(",
"\"Tree.line\"",
",",
"\"Angled\"",
"... | Initializes the UIManager defaults to values based on recommended,
best-practices user interface design. This should generally be called
once by an initializing application class. | [
"Initializes",
"the",
"UIManager",
"defaults",
"to",
"values",
"based",
"on",
"recommended",
"best",
"-",
"practices",
"user",
"interface",
"design",
".",
"This",
"should",
"generally",
"be",
"called",
"once",
"by",
"an",
"initializing",
"application",
"class",
... | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/application/config/support/UIManagerConfigurer.java#L82-L93 |
voldemort/voldemort | src/java/voldemort/utils/RebalanceUtils.java | RebalanceUtils.validateClusterZonesSame | public static void validateClusterZonesSame(final Cluster lhs, final Cluster rhs) {
Set<Zone> lhsSet = new HashSet<Zone>(lhs.getZones());
Set<Zone> rhsSet = new HashSet<Zone>(rhs.getZones());
if(!lhsSet.equals(rhsSet))
throw new VoldemortException("Zones are not the same [ lhs cluster zones ("
+ lhs.getZones() + ") not equal to rhs cluster zones ("
+ rhs.getZones() + ") ]");
} | java | public static void validateClusterZonesSame(final Cluster lhs, final Cluster rhs) {
Set<Zone> lhsSet = new HashSet<Zone>(lhs.getZones());
Set<Zone> rhsSet = new HashSet<Zone>(rhs.getZones());
if(!lhsSet.equals(rhsSet))
throw new VoldemortException("Zones are not the same [ lhs cluster zones ("
+ lhs.getZones() + ") not equal to rhs cluster zones ("
+ rhs.getZones() + ") ]");
} | [
"public",
"static",
"void",
"validateClusterZonesSame",
"(",
"final",
"Cluster",
"lhs",
",",
"final",
"Cluster",
"rhs",
")",
"{",
"Set",
"<",
"Zone",
">",
"lhsSet",
"=",
"new",
"HashSet",
"<",
"Zone",
">",
"(",
"lhs",
".",
"getZones",
"(",
")",
")",
";... | Confirms that both clusters have the same set of zones defined.
@param lhs
@param rhs | [
"Confirms",
"that",
"both",
"clusters",
"have",
"the",
"same",
"set",
"of",
"zones",
"defined",
"."
] | train | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L205-L212 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/cluster/api/RestBuilder.java | RestBuilder.withParam | public RestBuilder withParam(String key, String value) {
delegate.withParam(key, value);
return this;
} | java | public RestBuilder withParam(String key, String value) {
delegate.withParam(key, value);
return this;
} | [
"public",
"RestBuilder",
"withParam",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"delegate",
".",
"withParam",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Adds an URL query parameter to the request. Using a key twice will
result in the last call being taken into account.
@param key the parameter key.
@param value the parameter value. | [
"Adds",
"an",
"URL",
"query",
"parameter",
"to",
"the",
"request",
".",
"Using",
"a",
"key",
"twice",
"will",
"result",
"in",
"the",
"last",
"call",
"being",
"taken",
"into",
"account",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/cluster/api/RestBuilder.java#L66-L69 |
getsentry/sentry-java | sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java | DefaultSentryClientFactory.createHttpConnection | protected Connection createHttpConnection(Dsn dsn) {
URL sentryApiUrl = HttpConnection.getSentryApiUrl(dsn.getUri(), dsn.getProjectId());
String proxyHost = getProxyHost(dsn);
String proxyUser = getProxyUser(dsn);
String proxyPass = getProxyPass(dsn);
int proxyPort = getProxyPort(dsn);
Proxy proxy = null;
if (proxyHost != null) {
InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
if (proxyUser != null && proxyPass != null) {
Authenticator.setDefault(new ProxyAuthenticator(proxyUser, proxyPass));
}
}
Double sampleRate = getSampleRate(dsn);
EventSampler eventSampler = null;
if (sampleRate != null) {
eventSampler = new RandomEventSampler(sampleRate);
}
HttpConnection httpConnection = new HttpConnection(sentryApiUrl, dsn.getPublicKey(),
dsn.getSecretKey(), proxy, eventSampler);
Marshaller marshaller = createMarshaller(dsn);
httpConnection.setMarshaller(marshaller);
int timeout = getTimeout(dsn);
httpConnection.setConnectionTimeout(timeout);
boolean bypassSecurityEnabled = getBypassSecurityEnabled(dsn);
httpConnection.setBypassSecurity(bypassSecurityEnabled);
return httpConnection;
} | java | protected Connection createHttpConnection(Dsn dsn) {
URL sentryApiUrl = HttpConnection.getSentryApiUrl(dsn.getUri(), dsn.getProjectId());
String proxyHost = getProxyHost(dsn);
String proxyUser = getProxyUser(dsn);
String proxyPass = getProxyPass(dsn);
int proxyPort = getProxyPort(dsn);
Proxy proxy = null;
if (proxyHost != null) {
InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
if (proxyUser != null && proxyPass != null) {
Authenticator.setDefault(new ProxyAuthenticator(proxyUser, proxyPass));
}
}
Double sampleRate = getSampleRate(dsn);
EventSampler eventSampler = null;
if (sampleRate != null) {
eventSampler = new RandomEventSampler(sampleRate);
}
HttpConnection httpConnection = new HttpConnection(sentryApiUrl, dsn.getPublicKey(),
dsn.getSecretKey(), proxy, eventSampler);
Marshaller marshaller = createMarshaller(dsn);
httpConnection.setMarshaller(marshaller);
int timeout = getTimeout(dsn);
httpConnection.setConnectionTimeout(timeout);
boolean bypassSecurityEnabled = getBypassSecurityEnabled(dsn);
httpConnection.setBypassSecurity(bypassSecurityEnabled);
return httpConnection;
} | [
"protected",
"Connection",
"createHttpConnection",
"(",
"Dsn",
"dsn",
")",
"{",
"URL",
"sentryApiUrl",
"=",
"HttpConnection",
".",
"getSentryApiUrl",
"(",
"dsn",
".",
"getUri",
"(",
")",
",",
"dsn",
".",
"getProjectId",
"(",
")",
")",
";",
"String",
"proxyHo... | Creates an HTTP connection to the Sentry server.
@param dsn Data Source Name of the Sentry server.
@return an {@link HttpConnection} to the server. | [
"Creates",
"an",
"HTTP",
"connection",
"to",
"the",
"Sentry",
"server",
"."
] | train | https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java#L401-L437 |
Pi4J/pi4j | pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java | TemperatureConversion.convertFromRankine | public static double convertFromRankine(TemperatureScale to, double temperature) {
switch(to) {
case FARENHEIT:
return convertRankineToFarenheit(temperature);
case CELSIUS:
return convertRankineToCelsius(temperature);
case KELVIN:
return convertRankineToKelvin(temperature);
case RANKINE:
return temperature;
default:
throw(new RuntimeException("Invalid termpature conversion"));
}
} | java | public static double convertFromRankine(TemperatureScale to, double temperature) {
switch(to) {
case FARENHEIT:
return convertRankineToFarenheit(temperature);
case CELSIUS:
return convertRankineToCelsius(temperature);
case KELVIN:
return convertRankineToKelvin(temperature);
case RANKINE:
return temperature;
default:
throw(new RuntimeException("Invalid termpature conversion"));
}
} | [
"public",
"static",
"double",
"convertFromRankine",
"(",
"TemperatureScale",
"to",
",",
"double",
"temperature",
")",
"{",
"switch",
"(",
"to",
")",
"{",
"case",
"FARENHEIT",
":",
"return",
"convertRankineToFarenheit",
"(",
"temperature",
")",
";",
"case",
"CELS... | Convert a temperature value from the Rankine temperature scale to another.
@param to TemperatureScale
@param temperature value in degrees Rankine
@return converted temperature value in the requested to scale | [
"Convert",
"a",
"temperature",
"value",
"from",
"the",
"Rankine",
"temperature",
"scale",
"to",
"another",
"."
] | train | https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java#L217-L232 |
osmdroid/osmdroid | OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/data/HeatMap.java | HeatMap.createPolygon | private Overlay createPolygon(BoundingBox key, Integer value, int redthreshold, int orangethreshold) {
Polygon polygon = new Polygon(mMapView);
if (value < orangethreshold)
polygon.setFillColor(Color.parseColor(alpha + yellow));
else if (value < redthreshold)
polygon.setFillColor(Color.parseColor(alpha + orange));
else if (value >= redthreshold)
polygon.setFillColor(Color.parseColor(alpha + red));
else {
//no polygon
}
polygon.setStrokeColor(polygon.getFillColor());
//if you set this to something like 20f and have a low alpha setting,
// you'll end with a gaussian blur like effect
polygon.setStrokeWidth(0f);
List<GeoPoint> pts = new ArrayList<GeoPoint>();
pts.add(new GeoPoint(key.getLatNorth(), key.getLonWest()));
pts.add(new GeoPoint(key.getLatNorth(), key.getLonEast()));
pts.add(new GeoPoint(key.getLatSouth(), key.getLonEast()));
pts.add(new GeoPoint(key.getLatSouth(), key.getLonWest()));
polygon.setPoints(pts);
return polygon;
} | java | private Overlay createPolygon(BoundingBox key, Integer value, int redthreshold, int orangethreshold) {
Polygon polygon = new Polygon(mMapView);
if (value < orangethreshold)
polygon.setFillColor(Color.parseColor(alpha + yellow));
else if (value < redthreshold)
polygon.setFillColor(Color.parseColor(alpha + orange));
else if (value >= redthreshold)
polygon.setFillColor(Color.parseColor(alpha + red));
else {
//no polygon
}
polygon.setStrokeColor(polygon.getFillColor());
//if you set this to something like 20f and have a low alpha setting,
// you'll end with a gaussian blur like effect
polygon.setStrokeWidth(0f);
List<GeoPoint> pts = new ArrayList<GeoPoint>();
pts.add(new GeoPoint(key.getLatNorth(), key.getLonWest()));
pts.add(new GeoPoint(key.getLatNorth(), key.getLonEast()));
pts.add(new GeoPoint(key.getLatSouth(), key.getLonEast()));
pts.add(new GeoPoint(key.getLatSouth(), key.getLonWest()));
polygon.setPoints(pts);
return polygon;
} | [
"private",
"Overlay",
"createPolygon",
"(",
"BoundingBox",
"key",
",",
"Integer",
"value",
",",
"int",
"redthreshold",
",",
"int",
"orangethreshold",
")",
"{",
"Polygon",
"polygon",
"=",
"new",
"Polygon",
"(",
"mMapView",
")",
";",
"if",
"(",
"value",
"<",
... | converts the bounding box into a color filled polygon
@param key
@param value
@param redthreshold
@param orangethreshold
@return | [
"converts",
"the",
"bounding",
"box",
"into",
"a",
"color",
"filled",
"polygon"
] | train | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/data/HeatMap.java#L289-L312 |
Appendium/objectlabkit | utils/src/main/java/net/objectlab/kit/util/BigDecimalUtil.java | BigDecimalUtil.setScale | public static BigDecimal setScale(final BigDecimal bd, final int scale) {
return setScale(bd, scale, BigDecimal.ROUND_HALF_UP);
} | java | public static BigDecimal setScale(final BigDecimal bd, final int scale) {
return setScale(bd, scale, BigDecimal.ROUND_HALF_UP);
} | [
"public",
"static",
"BigDecimal",
"setScale",
"(",
"final",
"BigDecimal",
"bd",
",",
"final",
"int",
"scale",
")",
"{",
"return",
"setScale",
"(",
"bd",
",",
"scale",
",",
"BigDecimal",
".",
"ROUND_HALF_UP",
")",
";",
"}"
] | returns a new BigDecimal with correct scale.
@param bd
@return new bd or null | [
"returns",
"a",
"new",
"BigDecimal",
"with",
"correct",
"scale",
"."
] | train | https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/utils/src/main/java/net/objectlab/kit/util/BigDecimalUtil.java#L407-L409 |
BlueBrain/bluima | modules/bluima_utils/src/main/java/ds/tree/RadixTreeImpl.java | RadixTreeImpl.formatTo | @Override
public void formatTo(Formatter formatter, int flags, int width, int precision) {
formatNodeTo(formatter, 0, root);
} | java | @Override
public void formatTo(Formatter formatter, int flags, int width, int precision) {
formatNodeTo(formatter, 0, root);
} | [
"@",
"Override",
"public",
"void",
"formatTo",
"(",
"Formatter",
"formatter",
",",
"int",
"flags",
",",
"int",
"width",
",",
"int",
"precision",
")",
"{",
"formatNodeTo",
"(",
"formatter",
",",
"0",
",",
"root",
")",
";",
"}"
] | Writes a textual representation of this tree to the given formatter.
Currently, all options are simply ignored.
WARNING! Do not use this for a large Trie, it's for testing purpose only. | [
"Writes",
"a",
"textual",
"representation",
"of",
"this",
"tree",
"to",
"the",
"given",
"formatter",
"."
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_utils/src/main/java/ds/tree/RadixTreeImpl.java#L400-L403 |
camunda/camunda-commons | logging/src/main/java/org/camunda/commons/logging/BaseLogger.java | BaseLogger.formatMessageTemplate | protected String formatMessageTemplate(String id, String messageTemplate) {
return projectCode + "-" + componentId + id + " " + messageTemplate;
} | java | protected String formatMessageTemplate(String id, String messageTemplate) {
return projectCode + "-" + componentId + id + " " + messageTemplate;
} | [
"protected",
"String",
"formatMessageTemplate",
"(",
"String",
"id",
",",
"String",
"messageTemplate",
")",
"{",
"return",
"projectCode",
"+",
"\"-\"",
"+",
"componentId",
"+",
"id",
"+",
"\" \"",
"+",
"messageTemplate",
";",
"}"
] | Formats a message template
@param id the id of the message
@param messageTemplate the message template to use
@return the formatted template | [
"Formats",
"a",
"message",
"template"
] | train | https://github.com/camunda/camunda-commons/blob/bd3195db47c92c25717288fe9e6735f8e882f247/logging/src/main/java/org/camunda/commons/logging/BaseLogger.java#L200-L202 |
facebookarchive/hadoop-20 | src/contrib/streaming/src/java/org/apache/hadoop/streaming/UTF8ByteArrayUtils.java | UTF8ByteArrayUtils.findByte | @Deprecated
public static int findByte(byte [] utf, int start, int end, byte b) {
return org.apache.hadoop.util.UTF8ByteArrayUtils.findByte(utf, start, end, b);
} | java | @Deprecated
public static int findByte(byte [] utf, int start, int end, byte b) {
return org.apache.hadoop.util.UTF8ByteArrayUtils.findByte(utf, start, end, b);
} | [
"@",
"Deprecated",
"public",
"static",
"int",
"findByte",
"(",
"byte",
"[",
"]",
"utf",
",",
"int",
"start",
",",
"int",
"end",
",",
"byte",
"b",
")",
"{",
"return",
"org",
".",
"apache",
".",
"hadoop",
".",
"util",
".",
"UTF8ByteArrayUtils",
".",
"f... | Find the first occurrence of the given byte b in a UTF-8 encoded string
@param utf a byte array containing a UTF-8 encoded string
@param start starting offset
@param end ending position
@param b the byte to find
@return position that first byte occures otherwise -1
@deprecated use
{@link org.apache.hadoop.util.UTF8ByteArrayUtils#findByte(byte[], int,
int, byte)} | [
"Find",
"the",
"first",
"occurrence",
"of",
"the",
"given",
"byte",
"b",
"in",
"a",
"UTF",
"-",
"8",
"encoded",
"string"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/streaming/src/java/org/apache/hadoop/streaming/UTF8ByteArrayUtils.java#L57-L60 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachinesInner.java | VirtualMachinesInner.convertToManagedDisks | public OperationStatusResponseInner convertToManagedDisks(String resourceGroupName, String vmName) {
return convertToManagedDisksWithServiceResponseAsync(resourceGroupName, vmName).toBlocking().last().body();
} | java | public OperationStatusResponseInner convertToManagedDisks(String resourceGroupName, String vmName) {
return convertToManagedDisksWithServiceResponseAsync(resourceGroupName, vmName).toBlocking().last().body();
} | [
"public",
"OperationStatusResponseInner",
"convertToManagedDisks",
"(",
"String",
"resourceGroupName",
",",
"String",
"vmName",
")",
"{",
"return",
"convertToManagedDisksWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"vmName",
")",
".",
"toBlocking",
"(",
")",
... | Converts virtual machine disks from blob-based to managed disks. Virtual machine must be stop-deallocated before invoking this operation.
@param resourceGroupName The name of the resource group.
@param vmName The name of the virtual machine.
@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 OperationStatusResponseInner object if successful. | [
"Converts",
"virtual",
"machine",
"disks",
"from",
"blob",
"-",
"based",
"to",
"managed",
"disks",
".",
"Virtual",
"machine",
"must",
"be",
"stop",
"-",
"deallocated",
"before",
"invoking",
"this",
"operation",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachinesInner.java#L1134-L1136 |
icode/ameba | src/main/java/ameba/core/Addon.java | Addon.subscribeSystemEvent | protected static <E extends Event> void subscribeSystemEvent(Class<E> eventClass, final Listener<E> listener) {
SystemEventBus.subscribe(eventClass, listener);
} | java | protected static <E extends Event> void subscribeSystemEvent(Class<E> eventClass, final Listener<E> listener) {
SystemEventBus.subscribe(eventClass, listener);
} | [
"protected",
"static",
"<",
"E",
"extends",
"Event",
">",
"void",
"subscribeSystemEvent",
"(",
"Class",
"<",
"E",
">",
"eventClass",
",",
"final",
"Listener",
"<",
"E",
">",
"listener",
")",
"{",
"SystemEventBus",
".",
"subscribe",
"(",
"eventClass",
",",
... | <p>subscribeSystemEvent.</p>
@param eventClass a {@link java.lang.Class} object.
@param listener a {@link ameba.event.Listener} object.
@param <E> a E object. | [
"<p",
">",
"subscribeSystemEvent",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/core/Addon.java#L83-L85 |
Alexey1Gavrilov/ExpectIt | expectit-core/src/main/java/net/sf/expectit/filter/Filters.java | Filters.replaceInString | public static Filter replaceInString(final String regexp, final String replacement) {
return replaceInString(Pattern.compile(regexp), replacement, DEFAULT_FILTER_OVERLAP);
} | java | public static Filter replaceInString(final String regexp, final String replacement) {
return replaceInString(Pattern.compile(regexp), replacement, DEFAULT_FILTER_OVERLAP);
} | [
"public",
"static",
"Filter",
"replaceInString",
"(",
"final",
"String",
"regexp",
",",
"final",
"String",
"replacement",
")",
"{",
"return",
"replaceInString",
"(",
"Pattern",
".",
"compile",
"(",
"regexp",
")",
",",
"replacement",
",",
"DEFAULT_FILTER_OVERLAP",
... | Equivalent to {@link #replaceInString(java.util.regex.Pattern,
String)} but takes the regular expression
as string and default overlap in 80 characters.
@param regexp the regular expression
@param replacement the string to be substituted for each match
@return the filter | [
"Equivalent",
"to",
"{",
"@link",
"#replaceInString",
"(",
"java",
".",
"util",
".",
"regex",
".",
"Pattern",
"String",
")",
"}",
"but",
"takes",
"the",
"regular",
"expression",
"as",
"string",
"and",
"default",
"overlap",
"in",
"80",
"characters",
"."
] | train | https://github.com/Alexey1Gavrilov/ExpectIt/blob/5acbe1f8f895fe1dbd63e29bf3ab8e5bbf0873c3/expectit-core/src/main/java/net/sf/expectit/filter/Filters.java#L114-L116 |
aws/aws-sdk-java | aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/CreateJobTemplateRequest.java | CreateJobTemplateRequest.withTags | public CreateJobTemplateRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | java | public CreateJobTemplateRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"CreateJobTemplateRequest",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | The tags that you want to add to the resource. You can tag resources with a key-value pair or with only a key.
@param tags
The tags that you want to add to the resource. You can tag resources with a key-value pair or with only a
key.
@return Returns a reference to this object so that method calls can be chained together. | [
"The",
"tags",
"that",
"you",
"want",
"to",
"add",
"to",
"the",
"resource",
".",
"You",
"can",
"tag",
"resources",
"with",
"a",
"key",
"-",
"value",
"pair",
"or",
"with",
"only",
"a",
"key",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/CreateJobTemplateRequest.java#L370-L373 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java | ServerParams.getModuleParam | public Object getModuleParam(String moduleName, String paramName) {
Map<String, Object> moduleParams = getModuleParams(moduleName);
if (moduleParams == null) {
return null;
}
return moduleParams.get(paramName);
} | java | public Object getModuleParam(String moduleName, String paramName) {
Map<String, Object> moduleParams = getModuleParams(moduleName);
if (moduleParams == null) {
return null;
}
return moduleParams.get(paramName);
} | [
"public",
"Object",
"getModuleParam",
"(",
"String",
"moduleName",
",",
"String",
"paramName",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"moduleParams",
"=",
"getModuleParams",
"(",
"moduleName",
")",
";",
"if",
"(",
"moduleParams",
"==",
"null",
"... | Get the value of the given parameter name belonging to the given module name. If
no such module/parameter name is known, null is returned. Otherwise, the parsed
parameter is returned as an Object. This may be a String, Map, or List depending
on the parameter's structure.
@param moduleName Name of module to get parameter for.
@param paramName Name of parameter to get value of.
@return Parameter value as an Object or null if unknown. | [
"Get",
"the",
"value",
"of",
"the",
"given",
"parameter",
"name",
"belonging",
"to",
"the",
"given",
"module",
"name",
".",
"If",
"no",
"such",
"module",
"/",
"parameter",
"name",
"is",
"known",
"null",
"is",
"returned",
".",
"Otherwise",
"the",
"parsed",
... | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java#L295-L301 |
lessthanoptimal/BoofCV | integration/boofcv-ffmpeg/src/main/java/org/bytedeco/copiedstuff/Java2DFrameConverter.java | Java2DFrameConverter.getFrame | public Frame getFrame(BufferedImage image, double gamma, boolean flipChannels) {
if (image == null) {
return null;
}
SampleModel sm = image.getSampleModel();
int depth = 0, numChannels = sm.getNumBands();
switch (image.getType()) {
case BufferedImage.TYPE_INT_RGB:
case BufferedImage.TYPE_INT_ARGB:
case BufferedImage.TYPE_INT_ARGB_PRE:
case BufferedImage.TYPE_INT_BGR:
depth = Frame.DEPTH_UBYTE;
numChannels = 4;
break;
}
if (depth == 0 || numChannels == 0) {
switch (sm.getDataType()) {
case DataBuffer.TYPE_BYTE: depth = Frame.DEPTH_UBYTE; break;
case DataBuffer.TYPE_USHORT: depth = Frame.DEPTH_USHORT; break;
case DataBuffer.TYPE_SHORT: depth = Frame.DEPTH_SHORT; break;
case DataBuffer.TYPE_INT: depth = Frame.DEPTH_INT; break;
case DataBuffer.TYPE_FLOAT: depth = Frame.DEPTH_FLOAT; break;
case DataBuffer.TYPE_DOUBLE: depth = Frame.DEPTH_DOUBLE; break;
default: assert false;
}
}
if (frame == null || frame.imageWidth != image.getWidth() || frame.imageHeight != image.getHeight()
|| frame.imageDepth != depth || frame.imageChannels != numChannels) {
frame = new Frame(image.getWidth(), image.getHeight(), depth, numChannels);
}
copy(image, frame, gamma, flipChannels, null);
return frame;
} | java | public Frame getFrame(BufferedImage image, double gamma, boolean flipChannels) {
if (image == null) {
return null;
}
SampleModel sm = image.getSampleModel();
int depth = 0, numChannels = sm.getNumBands();
switch (image.getType()) {
case BufferedImage.TYPE_INT_RGB:
case BufferedImage.TYPE_INT_ARGB:
case BufferedImage.TYPE_INT_ARGB_PRE:
case BufferedImage.TYPE_INT_BGR:
depth = Frame.DEPTH_UBYTE;
numChannels = 4;
break;
}
if (depth == 0 || numChannels == 0) {
switch (sm.getDataType()) {
case DataBuffer.TYPE_BYTE: depth = Frame.DEPTH_UBYTE; break;
case DataBuffer.TYPE_USHORT: depth = Frame.DEPTH_USHORT; break;
case DataBuffer.TYPE_SHORT: depth = Frame.DEPTH_SHORT; break;
case DataBuffer.TYPE_INT: depth = Frame.DEPTH_INT; break;
case DataBuffer.TYPE_FLOAT: depth = Frame.DEPTH_FLOAT; break;
case DataBuffer.TYPE_DOUBLE: depth = Frame.DEPTH_DOUBLE; break;
default: assert false;
}
}
if (frame == null || frame.imageWidth != image.getWidth() || frame.imageHeight != image.getHeight()
|| frame.imageDepth != depth || frame.imageChannels != numChannels) {
frame = new Frame(image.getWidth(), image.getHeight(), depth, numChannels);
}
copy(image, frame, gamma, flipChannels, null);
return frame;
} | [
"public",
"Frame",
"getFrame",
"(",
"BufferedImage",
"image",
",",
"double",
"gamma",
",",
"boolean",
"flipChannels",
")",
"{",
"if",
"(",
"image",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"SampleModel",
"sm",
"=",
"image",
".",
"getSampleModel"... | Returns a Frame based on a BufferedImage, given gamma, and inverted channels flag. | [
"Returns",
"a",
"Frame",
"based",
"on",
"a",
"BufferedImage",
"given",
"gamma",
"and",
"inverted",
"channels",
"flag",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-ffmpeg/src/main/java/org/bytedeco/copiedstuff/Java2DFrameConverter.java#L680-L712 |
grpc/grpc-java | stub/src/main/java/io/grpc/stub/MetadataUtils.java | MetadataUtils.attachHeaders | @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1789")
public static <T extends AbstractStub<T>> T attachHeaders(T stub, Metadata extraHeaders) {
return stub.withInterceptors(newAttachHeadersInterceptor(extraHeaders));
} | java | @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1789")
public static <T extends AbstractStub<T>> T attachHeaders(T stub, Metadata extraHeaders) {
return stub.withInterceptors(newAttachHeadersInterceptor(extraHeaders));
} | [
"@",
"ExperimentalApi",
"(",
"\"https://github.com/grpc/grpc-java/issues/1789\"",
")",
"public",
"static",
"<",
"T",
"extends",
"AbstractStub",
"<",
"T",
">",
">",
"T",
"attachHeaders",
"(",
"T",
"stub",
",",
"Metadata",
"extraHeaders",
")",
"{",
"return",
"stub",... | Attaches a set of request headers to a stub.
@param stub to bind the headers to.
@param extraHeaders the headers to be passed by each call on the returned stub.
@return an implementation of the stub with {@code extraHeaders} bound to each call. | [
"Attaches",
"a",
"set",
"of",
"request",
"headers",
"to",
"a",
"stub",
"."
] | train | https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/stub/src/main/java/io/grpc/stub/MetadataUtils.java#L47-L50 |
openbase/jul | extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/LabelProcessor.java | LabelProcessor.getLabelByLanguage | public static String getLabelByLanguage(final String languageCode, final LabelOrBuilder label) throws NotAvailableException {
final List<String> labelList = getLabelListByLanguage(languageCode, label);
if (labelList.isEmpty()) {
throw new NotAvailableException("Label for Language[" + languageCode + "]");
}
return labelList.get(0);
} | java | public static String getLabelByLanguage(final String languageCode, final LabelOrBuilder label) throws NotAvailableException {
final List<String> labelList = getLabelListByLanguage(languageCode, label);
if (labelList.isEmpty()) {
throw new NotAvailableException("Label for Language[" + languageCode + "]");
}
return labelList.get(0);
} | [
"public",
"static",
"String",
"getLabelByLanguage",
"(",
"final",
"String",
"languageCode",
",",
"final",
"LabelOrBuilder",
"label",
")",
"throws",
"NotAvailableException",
"{",
"final",
"List",
"<",
"String",
">",
"labelList",
"=",
"getLabelListByLanguage",
"(",
"l... | Get the first label for a languageCode from a label type.
This method will call {@link #getLabelListByLanguage(String, LabelOrBuilder)} to extract the list of labels
for the languageCode and then return its first entry.
@param languageCode the languageCode which is checked
@param label the label type which is searched for labels in the language
@return the first label from the label type for the language code.
@throws NotAvailableException if no label list for the language code exists or if the list is empty | [
"Get",
"the",
"first",
"label",
"for",
"a",
"languageCode",
"from",
"a",
"label",
"type",
".",
"This",
"method",
"will",
"call",
"{",
"@link",
"#getLabelListByLanguage",
"(",
"String",
"LabelOrBuilder",
")",
"}",
"to",
"extract",
"the",
"list",
"of",
"labels... | train | https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/LabelProcessor.java#L291-L297 |
evant/binding-collection-adapter | bindingcollectionadapter-recyclerview/src/main/java/me/tatarka/bindingcollectionadapter2/collections/DiffObservableList.java | DiffObservableList.calculateDiff | @NonNull
public DiffUtil.DiffResult calculateDiff(@NonNull final List<T> newItems) {
final ArrayList<T> frozenList;
synchronized (LIST_LOCK) {
frozenList = new ArrayList<>(list);
}
return doCalculateDiff(frozenList, newItems);
} | java | @NonNull
public DiffUtil.DiffResult calculateDiff(@NonNull final List<T> newItems) {
final ArrayList<T> frozenList;
synchronized (LIST_LOCK) {
frozenList = new ArrayList<>(list);
}
return doCalculateDiff(frozenList, newItems);
} | [
"@",
"NonNull",
"public",
"DiffUtil",
".",
"DiffResult",
"calculateDiff",
"(",
"@",
"NonNull",
"final",
"List",
"<",
"T",
">",
"newItems",
")",
"{",
"final",
"ArrayList",
"<",
"T",
">",
"frozenList",
";",
"synchronized",
"(",
"LIST_LOCK",
")",
"{",
"frozen... | Calculates the list of update operations that can convert this list into the given one.
@param newItems The items that this list will be set to.
@return A DiffResult that contains the information about the edit sequence to covert this
list into the given one. | [
"Calculates",
"the",
"list",
"of",
"update",
"operations",
"that",
"can",
"convert",
"this",
"list",
"into",
"the",
"given",
"one",
"."
] | train | https://github.com/evant/binding-collection-adapter/blob/f669eda0a7002128bb504dcba012c51531f1bedd/bindingcollectionadapter-recyclerview/src/main/java/me/tatarka/bindingcollectionadapter2/collections/DiffObservableList.java#L82-L89 |
OpenLiberty/open-liberty | dev/com.ibm.ws.concurrent.mp.1.0/src/com/ibm/ws/concurrent/mp/ThreadContextBuilderImpl.java | ThreadContextBuilderImpl.failOnOverlapOfClearedPropagatedUnchanged | private void failOnOverlapOfClearedPropagatedUnchanged(Set<String> cleared, Set<String> propagated, Set<String> unchanged) {
HashSet<String> overlap = new HashSet<String>(cleared);
overlap.retainAll(propagated);
HashSet<String> s = new HashSet<String>(cleared);
s.retainAll(unchanged);
overlap.addAll(s);
s = new HashSet<String>(propagated);
s.retainAll(unchanged);
overlap.addAll(s);
if (overlap.isEmpty()) // only possible if builder is concurrently modified during build
throw new ConcurrentModificationException();
throw new IllegalStateException(Tr.formatMessage(tc, "CWWKC1152.context.lists.overlap", overlap));
} | java | private void failOnOverlapOfClearedPropagatedUnchanged(Set<String> cleared, Set<String> propagated, Set<String> unchanged) {
HashSet<String> overlap = new HashSet<String>(cleared);
overlap.retainAll(propagated);
HashSet<String> s = new HashSet<String>(cleared);
s.retainAll(unchanged);
overlap.addAll(s);
s = new HashSet<String>(propagated);
s.retainAll(unchanged);
overlap.addAll(s);
if (overlap.isEmpty()) // only possible if builder is concurrently modified during build
throw new ConcurrentModificationException();
throw new IllegalStateException(Tr.formatMessage(tc, "CWWKC1152.context.lists.overlap", overlap));
} | [
"private",
"void",
"failOnOverlapOfClearedPropagatedUnchanged",
"(",
"Set",
"<",
"String",
">",
"cleared",
",",
"Set",
"<",
"String",
">",
"propagated",
",",
"Set",
"<",
"String",
">",
"unchanged",
")",
"{",
"HashSet",
"<",
"String",
">",
"overlap",
"=",
"ne... | Fail with error identifying the overlap(s) in context types between any two of:
cleared, propagated, unchanged.
@throws IllegalStateException identifying the overlap. | [
"Fail",
"with",
"error",
"identifying",
"the",
"overlap",
"(",
"s",
")",
"in",
"context",
"types",
"between",
"any",
"two",
"of",
":",
"cleared",
"propagated",
"unchanged",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.concurrent.mp.1.0/src/com/ibm/ws/concurrent/mp/ThreadContextBuilderImpl.java#L136-L148 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/jfapchannel/impl/octracker/ConnectionDataGroup.java | ConnectionDataGroup.connectOverNetwork | private NetworkConnection connectOverNetwork(JFapAddressHolder addressHolder, NetworkConnectionFactoryHolder factoryHolder) throws JFapConnectFailedException, FrameworkException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "connectOverNetwork", new Object[] { addressHolder, factoryHolder });
NetworkConnectionFactory vcf = factoryHolder.getFactory();
NetworkConnection vc = vcf.createConnection();
Semaphore sem = new Semaphore();
ClientConnectionReadyCallback callback = new ClientConnectionReadyCallback(sem);
vc.connectAsynch(addressHolder.getAddress(), callback);
sem.waitOnIgnoringInterruptions();
if (!callback.connectionSucceeded())
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(this, tc, "Connect has failed due to ", callback.getException());
String failureKey;
Object[] failureInserts;
if (addressHolder.getAddress() != null)
{
failureKey = "CONNDATAGROUP_CONNFAILED_SICJ0063";
failureInserts = addressHolder.getErrorInserts();
}
else
{
failureKey = "CONNDATAGROUP_CONNFAILED_SICJ0080";
failureInserts = new Object[] {};
}
String message = nls.getFormattedMessage(failureKey, failureInserts, failureKey);
throw new JFapConnectFailedException(message, callback.getException());
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "connectOverNetwork", vc);
return vc;
} | java | private NetworkConnection connectOverNetwork(JFapAddressHolder addressHolder, NetworkConnectionFactoryHolder factoryHolder) throws JFapConnectFailedException, FrameworkException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "connectOverNetwork", new Object[] { addressHolder, factoryHolder });
NetworkConnectionFactory vcf = factoryHolder.getFactory();
NetworkConnection vc = vcf.createConnection();
Semaphore sem = new Semaphore();
ClientConnectionReadyCallback callback = new ClientConnectionReadyCallback(sem);
vc.connectAsynch(addressHolder.getAddress(), callback);
sem.waitOnIgnoringInterruptions();
if (!callback.connectionSucceeded())
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(this, tc, "Connect has failed due to ", callback.getException());
String failureKey;
Object[] failureInserts;
if (addressHolder.getAddress() != null)
{
failureKey = "CONNDATAGROUP_CONNFAILED_SICJ0063";
failureInserts = addressHolder.getErrorInserts();
}
else
{
failureKey = "CONNDATAGROUP_CONNFAILED_SICJ0080";
failureInserts = new Object[] {};
}
String message = nls.getFormattedMessage(failureKey, failureInserts, failureKey);
throw new JFapConnectFailedException(message, callback.getException());
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "connectOverNetwork", vc);
return vc;
} | [
"private",
"NetworkConnection",
"connectOverNetwork",
"(",
"JFapAddressHolder",
"addressHolder",
",",
"NetworkConnectionFactoryHolder",
"factoryHolder",
")",
"throws",
"JFapConnectFailedException",
",",
"FrameworkException",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingE... | Create a new connection over the network
@param addressHolder The holder from which to obtain the jfap address (if any) over which to connect
@param factoryHolder The holder from which to get the a network connection factory (from which the virtual connection can be obtained)
@return NetworkConnection the network connection that was created
@throws FrameworkException if no network connection can be created
@throws JFapConnectFailedException if the connection fail | [
"Create",
"a",
"new",
"connection",
"over",
"the",
"network"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/jfapchannel/impl/octracker/ConnectionDataGroup.java#L752-L791 |
JodaOrg/joda-time | src/main/java/org/joda/time/field/FieldUtils.java | FieldUtils.safeSubtract | public static long safeSubtract(long val1, long val2) {
long diff = val1 - val2;
// If there is a sign change, but the two values have different signs...
if ((val1 ^ diff) < 0 && (val1 ^ val2) < 0) {
throw new ArithmeticException
("The calculation caused an overflow: " + val1 + " - " + val2);
}
return diff;
} | java | public static long safeSubtract(long val1, long val2) {
long diff = val1 - val2;
// If there is a sign change, but the two values have different signs...
if ((val1 ^ diff) < 0 && (val1 ^ val2) < 0) {
throw new ArithmeticException
("The calculation caused an overflow: " + val1 + " - " + val2);
}
return diff;
} | [
"public",
"static",
"long",
"safeSubtract",
"(",
"long",
"val1",
",",
"long",
"val2",
")",
"{",
"long",
"diff",
"=",
"val1",
"-",
"val2",
";",
"// If there is a sign change, but the two values have different signs...",
"if",
"(",
"(",
"val1",
"^",
"diff",
")",
"... | Subtracts two values throwing an exception if overflow occurs.
@param val1 the first value, to be taken away from
@param val2 the second value, the amount to take away
@return the new total
@throws ArithmeticException if the value is too big or too small | [
"Subtracts",
"two",
"values",
"throwing",
"an",
"exception",
"if",
"overflow",
"occurs",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/field/FieldUtils.java#L102-L110 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/store/itemstreams/PubSubMessageItemStream.java | PubSubMessageItemStream.setWatermarks | @Override
protected void setWatermarks(long nextLowWatermark, long nextHighWatermark)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "setWatermarks",
new Object[] { new Long(nextLowWatermark), new Long(nextHighWatermark), new Long(referenceStreamCount) });
super.setWatermarks(nextLowWatermark + referenceStreamCount, nextHighWatermark + referenceStreamCount);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "setWatermarks");
} | java | @Override
protected void setWatermarks(long nextLowWatermark, long nextHighWatermark)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "setWatermarks",
new Object[] { new Long(nextLowWatermark), new Long(nextHighWatermark), new Long(referenceStreamCount) });
super.setWatermarks(nextLowWatermark + referenceStreamCount, nextHighWatermark + referenceStreamCount);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "setWatermarks");
} | [
"@",
"Override",
"protected",
"void",
"setWatermarks",
"(",
"long",
"nextLowWatermark",
",",
"long",
"nextHighWatermark",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".... | Include the referenceStreamCount when setting the watermarks (called by
BaseMessageItemStream.updateWaterMarks() (which has no concept of referenceStreams)
(510343)
@param nextLowWatermark
@param nextHighWatermark
@throws SevereMessageStoreException | [
"Include",
"the",
"referenceStreamCount",
"when",
"setting",
"the",
"watermarks",
"(",
"called",
"by",
"BaseMessageItemStream",
".",
"updateWaterMarks",
"()",
"(",
"which",
"has",
"no",
"concept",
"of",
"referenceStreams",
")"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/store/itemstreams/PubSubMessageItemStream.java#L922-L933 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/jql/JQLChecker.java | JQLChecker.prepareParser | protected Pair<ParserRuleContext, CommonTokenStream> prepareParser(final JQLContext jqlContext, final String jql) {
JqlLexer lexer = new JqlLexer(CharStreams.fromString(jql));
CommonTokenStream tokens = new CommonTokenStream(lexer);
JqlParser parser = new JqlParser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(new JQLBaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
AssertKripton.assertTrue(false, jqlContext.getContextDescription() + ": unespected char at pos %s of SQL '%s'", charPositionInLine, jql);
}
});
ParserRuleContext context = parser.parse();
return new Pair<>(context, tokens);
} | java | protected Pair<ParserRuleContext, CommonTokenStream> prepareParser(final JQLContext jqlContext, final String jql) {
JqlLexer lexer = new JqlLexer(CharStreams.fromString(jql));
CommonTokenStream tokens = new CommonTokenStream(lexer);
JqlParser parser = new JqlParser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(new JQLBaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
AssertKripton.assertTrue(false, jqlContext.getContextDescription() + ": unespected char at pos %s of SQL '%s'", charPositionInLine, jql);
}
});
ParserRuleContext context = parser.parse();
return new Pair<>(context, tokens);
} | [
"protected",
"Pair",
"<",
"ParserRuleContext",
",",
"CommonTokenStream",
">",
"prepareParser",
"(",
"final",
"JQLContext",
"jqlContext",
",",
"final",
"String",
"jql",
")",
"{",
"JqlLexer",
"lexer",
"=",
"new",
"JqlLexer",
"(",
"CharStreams",
".",
"fromString",
... | Prepare parser.
@param jqlContext
the jql context
@param jql
the jql
@return the pair | [
"Prepare",
"parser",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/jql/JQLChecker.java#L160-L175 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java | KeyVaultClientCustomImpl.listSecretVersions | public PagedList<SecretItem> listSecretVersions(final String vaultBaseUrl, final String secretName) {
return getSecretVersions(vaultBaseUrl, secretName);
} | java | public PagedList<SecretItem> listSecretVersions(final String vaultBaseUrl, final String secretName) {
return getSecretVersions(vaultBaseUrl, secretName);
} | [
"public",
"PagedList",
"<",
"SecretItem",
">",
"listSecretVersions",
"(",
"final",
"String",
"vaultBaseUrl",
",",
"final",
"String",
"secretName",
")",
"{",
"return",
"getSecretVersions",
"(",
"vaultBaseUrl",
",",
"secretName",
")",
";",
"}"
] | List the versions of the specified secret.
@param vaultBaseUrl
The vault name, e.g. https://myvault.vault.azure.net
@param secretName
The name of the secret in the given vault
@return the PagedList<SecretItem> if successful. | [
"List",
"the",
"versions",
"of",
"the",
"specified",
"secret",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java#L1229-L1231 |
mlhartme/sushi | src/main/java/net/oneandone/sushi/util/IntBitRelation.java | IntBitRelation.composeRightLeft | public void composeRightLeft(IntBitRelation left, IntBitRelation right) {
int i, ele;
IntBitSet li;
for (i = 0; i < left.line.length; i++) {
li = left.line[i];
if (li != null) {
for (ele = li.first(); ele != -1; ele = li.next(ele)) {
if (right.line[ele] != null) {
add(i, right.line[ele]);
}
}
}
}
} | java | public void composeRightLeft(IntBitRelation left, IntBitRelation right) {
int i, ele;
IntBitSet li;
for (i = 0; i < left.line.length; i++) {
li = left.line[i];
if (li != null) {
for (ele = li.first(); ele != -1; ele = li.next(ele)) {
if (right.line[ele] != null) {
add(i, right.line[ele]);
}
}
}
}
} | [
"public",
"void",
"composeRightLeft",
"(",
"IntBitRelation",
"left",
",",
"IntBitRelation",
"right",
")",
"{",
"int",
"i",
",",
"ele",
";",
"IntBitSet",
"li",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"left",
".",
"line",
".",
"length",
";",
"i"... | If (a,b) is element of left and (b,c) is element of right,
then (a,c) is added to this relation.
@param left left relation
@param right right relation. | [
"If",
"(",
"a",
"b",
")",
"is",
"element",
"of",
"left",
"and",
"(",
"b",
"c",
")",
"is",
"element",
"of",
"right",
"then",
"(",
"a",
"c",
")",
"is",
"added",
"to",
"this",
"relation",
"."
] | train | https://github.com/mlhartme/sushi/blob/4af33414b04bd58584d4febe5cc63ef6c7346a75/src/main/java/net/oneandone/sushi/util/IntBitRelation.java#L148-L162 |
btrplace/scheduler | btrpsl/src/main/java/org/btrplace/btrpsl/constraint/AmongBuilder.java | AmongBuilder.buildConstraint | @Override
public List<? extends SatConstraint> buildConstraint(BtrPlaceTree t, List<BtrpOperand> args) {
if (checkConformance(t, args)) {
@SuppressWarnings("unchecked")
List<VM> vms = (List<VM>) params[0].transform(this, t, args.get(0));
@SuppressWarnings("unchecked")
Collection<Collection<Node>> nss = (Collection<Collection<Node>>) params[1].transform(this, t, args.get(1));
return vms != null && nss != null ? Collections.singletonList(new Among(vms, nss)) : Collections.emptyList();
}
return Collections.emptyList();
} | java | @Override
public List<? extends SatConstraint> buildConstraint(BtrPlaceTree t, List<BtrpOperand> args) {
if (checkConformance(t, args)) {
@SuppressWarnings("unchecked")
List<VM> vms = (List<VM>) params[0].transform(this, t, args.get(0));
@SuppressWarnings("unchecked")
Collection<Collection<Node>> nss = (Collection<Collection<Node>>) params[1].transform(this, t, args.get(1));
return vms != null && nss != null ? Collections.singletonList(new Among(vms, nss)) : Collections.emptyList();
}
return Collections.emptyList();
} | [
"@",
"Override",
"public",
"List",
"<",
"?",
"extends",
"SatConstraint",
">",
"buildConstraint",
"(",
"BtrPlaceTree",
"t",
",",
"List",
"<",
"BtrpOperand",
">",
"args",
")",
"{",
"if",
"(",
"checkConformance",
"(",
"t",
",",
"args",
")",
")",
"{",
"@",
... | Build a constraint.
@param t the current tree
@param args the argument. Must be a non-empty set of virtual machines and a multiset of nodes with
at least two non-empty sets. If the multi set contains only one set, a {@code Fence} constraint is created
@return the constraint | [
"Build",
"a",
"constraint",
"."
] | train | https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/btrpsl/src/main/java/org/btrplace/btrpsl/constraint/AmongBuilder.java#L54-L64 |
kiswanij/jk-util | src/main/java/com/jk/util/model/table/JKDefaultTableModel.java | JKDefaultTableModel.setValueAt | @Override
public void setValueAt(final Object aValue, final int row, final int column) {
final Vector rowVector = (Vector) this.dataVector.elementAt(row);
rowVector.setElementAt(aValue, column);
fireTableCellUpdated(row, column);
} | java | @Override
public void setValueAt(final Object aValue, final int row, final int column) {
final Vector rowVector = (Vector) this.dataVector.elementAt(row);
rowVector.setElementAt(aValue, column);
fireTableCellUpdated(row, column);
} | [
"@",
"Override",
"public",
"void",
"setValueAt",
"(",
"final",
"Object",
"aValue",
",",
"final",
"int",
"row",
",",
"final",
"int",
"column",
")",
"{",
"final",
"Vector",
"rowVector",
"=",
"(",
"Vector",
")",
"this",
".",
"dataVector",
".",
"elementAt",
... | Sets the object value for the cell at <code>column</code> and
<code>row</code>. <code>aValue</code> is the new value. This method will
generate a <code>tableChanged</code> notification.
@param aValue the new value; this can be null
@param row the row whose value is to be changed
@param column the column whose value is to be changed
@exception ArrayIndexOutOfBoundsException if an invalid row or column was
given | [
"Sets",
"the",
"object",
"value",
"for",
"the",
"cell",
"at",
"<code",
">",
"column<",
"/",
"code",
">",
"and",
"<code",
">",
"row<",
"/",
"code",
">",
".",
"<code",
">",
"aValue<",
"/",
"code",
">",
"is",
"the",
"new",
"value",
".",
"This",
"metho... | train | https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/model/table/JKDefaultTableModel.java#L726-L731 |
FedericoPecora/meta-csp-framework | src/main/java/org/metacsp/multi/spatioTemporal/paths/TrajectoryEnvelope.java | TrajectoryEnvelope.getPartialEnvelopeGeometry | public Geometry getPartialEnvelopeGeometry(int indexFrom, int indexTo) {
Geometry onePoly = null;
Geometry prevPoly = null;
if (indexFrom > indexTo || indexFrom < 0 || indexFrom > this.trajectory.getPoseSteering().length-1 || indexTo < 0 || indexTo >= this.trajectory.getPoseSteering().length) throw new Error("Indices incorrect!");
for (int i = indexFrom; i <= indexTo; i++) {
PoseSteering ps = this.trajectory.getPoseSteering()[i];
Geometry rect = makeFootprint(ps);
if (onePoly == null) {
onePoly = rect;
prevPoly = rect;
}
else {
Geometry auxPoly = prevPoly.union(rect);
onePoly = onePoly.union(auxPoly.convexHull());
prevPoly = rect;
}
}
return onePoly;
} | java | public Geometry getPartialEnvelopeGeometry(int indexFrom, int indexTo) {
Geometry onePoly = null;
Geometry prevPoly = null;
if (indexFrom > indexTo || indexFrom < 0 || indexFrom > this.trajectory.getPoseSteering().length-1 || indexTo < 0 || indexTo >= this.trajectory.getPoseSteering().length) throw new Error("Indices incorrect!");
for (int i = indexFrom; i <= indexTo; i++) {
PoseSteering ps = this.trajectory.getPoseSteering()[i];
Geometry rect = makeFootprint(ps);
if (onePoly == null) {
onePoly = rect;
prevPoly = rect;
}
else {
Geometry auxPoly = prevPoly.union(rect);
onePoly = onePoly.union(auxPoly.convexHull());
prevPoly = rect;
}
}
return onePoly;
} | [
"public",
"Geometry",
"getPartialEnvelopeGeometry",
"(",
"int",
"indexFrom",
",",
"int",
"indexTo",
")",
"{",
"Geometry",
"onePoly",
"=",
"null",
";",
"Geometry",
"prevPoly",
"=",
"null",
";",
"if",
"(",
"indexFrom",
">",
"indexTo",
"||",
"indexFrom",
"<",
"... | Get a {@link Geometry} representing the spatial envelope between two given indices.
@param indexFrom The starting index (inclusive).
@param indexTo The ending index (inclusive).
@return A {@link Geometry} representing the spatial envelope between two given indices. | [
"Get",
"a",
"{"
] | train | https://github.com/FedericoPecora/meta-csp-framework/blob/42aaef2e2b76d0f738427f0dd9653c4f62b40517/src/main/java/org/metacsp/multi/spatioTemporal/paths/TrajectoryEnvelope.java#L695-L713 |
baratine/baratine | framework/src/main/java/com/caucho/v5/ramp/hamp/InHamp.java | InHamp.readMessage | public boolean readMessage(InputStream is, OutboxAmp outbox)
throws IOException
{
InH3 hIn = _hIn;
if (is.available() < 0) {
return false;
}
//hIn.initPacket(is);
try {
return readMessage(hIn, outbox);
} finally {
//outbox.setInbox(null);
}
} | java | public boolean readMessage(InputStream is, OutboxAmp outbox)
throws IOException
{
InH3 hIn = _hIn;
if (is.available() < 0) {
return false;
}
//hIn.initPacket(is);
try {
return readMessage(hIn, outbox);
} finally {
//outbox.setInbox(null);
}
} | [
"public",
"boolean",
"readMessage",
"(",
"InputStream",
"is",
",",
"OutboxAmp",
"outbox",
")",
"throws",
"IOException",
"{",
"InH3",
"hIn",
"=",
"_hIn",
";",
"if",
"(",
"is",
".",
"available",
"(",
")",
"<",
"0",
")",
"{",
"return",
"false",
";",
"}",
... | Reads the next HMTP packet from the stream, returning false on
end of file. | [
"Reads",
"the",
"next",
"HMTP",
"packet",
"from",
"the",
"stream",
"returning",
"false",
"on",
"end",
"of",
"file",
"."
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/ramp/hamp/InHamp.java#L235-L251 |
jfinal/jfinal | src/main/java/com/jfinal/plugin/activerecord/Model.java | Model.findFirstByCache | public M findFirstByCache(String cacheName, Object key, String sql, Object... paras) {
ICache cache = _getConfig().getCache();
M result = cache.get(cacheName, key);
if (result == null) {
result = findFirst(sql, paras);
cache.put(cacheName, key, result);
}
return result;
} | java | public M findFirstByCache(String cacheName, Object key, String sql, Object... paras) {
ICache cache = _getConfig().getCache();
M result = cache.get(cacheName, key);
if (result == null) {
result = findFirst(sql, paras);
cache.put(cacheName, key, result);
}
return result;
} | [
"public",
"M",
"findFirstByCache",
"(",
"String",
"cacheName",
",",
"Object",
"key",
",",
"String",
"sql",
",",
"Object",
"...",
"paras",
")",
"{",
"ICache",
"cache",
"=",
"_getConfig",
"(",
")",
".",
"getCache",
"(",
")",
";",
"M",
"result",
"=",
"cac... | Find first model by cache. I recommend add "limit 1" in your sql.
@see #findFirst(String, Object...)
@param cacheName the cache name
@param key the key used to get data from cache
@param sql an SQL statement that may contain one or more '?' IN parameter placeholders
@param paras the parameters of sql | [
"Find",
"first",
"model",
"by",
"cache",
".",
"I",
"recommend",
"add",
"limit",
"1",
"in",
"your",
"sql",
"."
] | train | https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/plugin/activerecord/Model.java#L967-L975 |
io7m/jregions | com.io7m.jregions.generators/src/main/java/com/io7m/jregions/generators/PAreaSizeBDGenerator.java | PAreaSizeBDGenerator.create | public static <S> PAreaSizeBDGenerator<S> create()
{
final LongGenerator gen = new LongGenerator(0L, Long.MAX_VALUE);
return new PAreaSizeBDGenerator<>(() -> new BigDecimal(gen.next().toString()));
} | java | public static <S> PAreaSizeBDGenerator<S> create()
{
final LongGenerator gen = new LongGenerator(0L, Long.MAX_VALUE);
return new PAreaSizeBDGenerator<>(() -> new BigDecimal(gen.next().toString()));
} | [
"public",
"static",
"<",
"S",
">",
"PAreaSizeBDGenerator",
"<",
"S",
">",
"create",
"(",
")",
"{",
"final",
"LongGenerator",
"gen",
"=",
"new",
"LongGenerator",
"(",
"0L",
",",
"Long",
".",
"MAX_VALUE",
")",
";",
"return",
"new",
"PAreaSizeBDGenerator",
"<... | @param <S> A phantom type parameter indicating the coordinate space of the
area
@return A generator initialized with useful defaults | [
"@param",
"<S",
">",
"A",
"phantom",
"type",
"parameter",
"indicating",
"the",
"coordinate",
"space",
"of",
"the",
"area"
] | train | https://github.com/io7m/jregions/blob/ae03850b5fa2a5fcbd8788953fba7897d4a88d7c/com.io7m.jregions.generators/src/main/java/com/io7m/jregions/generators/PAreaSizeBDGenerator.java#L56-L60 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/cloud/PointCloudUtils.java | PointCloudUtils.statistics | public static void statistics( List<Point3D_F64> cloud , Point3D_F64 mean , Point3D_F64 stdev ) {
final int N = cloud.size();
for (int i = 0; i < N; i++) {
Point3D_F64 p = cloud.get(i);
mean.x += p.x / N;
mean.y += p.y / N;
mean.z += p.z / N;
}
for (int i = 0; i < N; i++) {
Point3D_F64 p = cloud.get(i);
double dx = p.x-mean.x;
double dy = p.y-mean.y;
double dz = p.z-mean.z;
stdev.x += dx*dx/N;
stdev.y += dy*dy/N;
stdev.z += dz*dz/N;
}
stdev.x = Math.sqrt(stdev.x);
stdev.y = Math.sqrt(stdev.y);
stdev.z = Math.sqrt(stdev.z);
} | java | public static void statistics( List<Point3D_F64> cloud , Point3D_F64 mean , Point3D_F64 stdev ) {
final int N = cloud.size();
for (int i = 0; i < N; i++) {
Point3D_F64 p = cloud.get(i);
mean.x += p.x / N;
mean.y += p.y / N;
mean.z += p.z / N;
}
for (int i = 0; i < N; i++) {
Point3D_F64 p = cloud.get(i);
double dx = p.x-mean.x;
double dy = p.y-mean.y;
double dz = p.z-mean.z;
stdev.x += dx*dx/N;
stdev.y += dy*dy/N;
stdev.z += dz*dz/N;
}
stdev.x = Math.sqrt(stdev.x);
stdev.y = Math.sqrt(stdev.y);
stdev.z = Math.sqrt(stdev.z);
} | [
"public",
"static",
"void",
"statistics",
"(",
"List",
"<",
"Point3D_F64",
">",
"cloud",
",",
"Point3D_F64",
"mean",
",",
"Point3D_F64",
"stdev",
")",
"{",
"final",
"int",
"N",
"=",
"cloud",
".",
"size",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0... | Computes the mean and standard deviation of each axis in the point cloud computed in dependently
@param cloud (Input) Cloud
@param mean (Output) mean of each axis
@param stdev (Output) standard deviation of each axis | [
"Computes",
"the",
"mean",
"and",
"standard",
"deviation",
"of",
"each",
"axis",
"in",
"the",
"point",
"cloud",
"computed",
"in",
"dependently"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/cloud/PointCloudUtils.java#L65-L87 |
fcrepo3/fcrepo | fcrepo-security/fcrepo-security-pdp/src/main/java/org/fcrepo/server/security/xacml/pdp/data/DbXmlPolicyIndex.java | DbXmlPolicyIndex.createQuery | private String createQuery(Map<String, Collection<AttributeBean>> attributeMap) {
StringBuilder sb = new StringBuilder(256);
sb.append("collection('");
sb.append(m_dbXmlManager.CONTAINER);
sb.append("')");
getXpath(attributeMap, sb);
return sb.toString();
} | java | private String createQuery(Map<String, Collection<AttributeBean>> attributeMap) {
StringBuilder sb = new StringBuilder(256);
sb.append("collection('");
sb.append(m_dbXmlManager.CONTAINER);
sb.append("')");
getXpath(attributeMap, sb);
return sb.toString();
} | [
"private",
"String",
"createQuery",
"(",
"Map",
"<",
"String",
",",
"Collection",
"<",
"AttributeBean",
">",
">",
"attributeMap",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"256",
")",
";",
"sb",
".",
"append",
"(",
"\"collection('\""... | Given a set of attributes this method generates a DBXML XPath query based
on those attributes to extract a subset of policies from the database.
@param attributeMap
the Map of Attributes from which to generate the query
@param r
the number of components in the resource id
@return the query as a String | [
"Given",
"a",
"set",
"of",
"attributes",
"this",
"method",
"generates",
"a",
"DBXML",
"XPath",
"query",
"based",
"on",
"those",
"attributes",
"to",
"extract",
"a",
"subset",
"of",
"policies",
"from",
"the",
"database",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-security/fcrepo-security-pdp/src/main/java/org/fcrepo/server/security/xacml/pdp/data/DbXmlPolicyIndex.java#L262-L269 |
VoltDB/voltdb | third_party/java/src/com/google_voltpatches/common/collect/Maps.java | Maps.newTreeMap | public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() {
return new TreeMap<K, V>();
} | java | public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() {
return new TreeMap<K, V>();
} | [
"public",
"static",
"<",
"K",
"extends",
"Comparable",
",",
"V",
">",
"TreeMap",
"<",
"K",
",",
"V",
">",
"newTreeMap",
"(",
")",
"{",
"return",
"new",
"TreeMap",
"<",
"K",
",",
"V",
">",
"(",
")",
";",
"}"
] | Creates a <i>mutable</i>, empty {@code TreeMap} instance using the natural
ordering of its elements.
<p><b>Note:</b> if mutability is not required, use {@link
ImmutableSortedMap#of()} instead.
<p><b>Note for Java 7 and later:</b> this method is now unnecessary and
should be treated as deprecated. Instead, use the {@code TreeMap}
constructor directly, taking advantage of the new
<a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
@return a new, empty {@code TreeMap} | [
"Creates",
"a",
"<i",
">",
"mutable<",
"/",
"i",
">",
"empty",
"{",
"@code",
"TreeMap",
"}",
"instance",
"using",
"the",
"natural",
"ordering",
"of",
"its",
"elements",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/com/google_voltpatches/common/collect/Maps.java#L320-L322 |
hyperledger/fabric-chaincode-java | fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementUtils.java | StateBasedEndorsementUtils.signedByFabricEntity | static SignaturePolicyEnvelope signedByFabricEntity(String mspId, MSPRoleType role) {
// specify the principal: it's a member of the msp we just found
MSPPrincipal principal = MSPPrincipal
.newBuilder()
.setPrincipalClassification(Classification.ROLE)
.setPrincipal(MSPRole
.newBuilder()
.setMspIdentifier(mspId)
.setRole(role)
.build().toByteString())
.build();
// create the policy: it requires exactly 1 signature from the first (and only) principal
return SignaturePolicyEnvelope
.newBuilder()
.setVersion(0)
.setRule(nOutOf(1, Arrays.asList(signedBy(0))))
.addIdentities(principal)
.build();
} | java | static SignaturePolicyEnvelope signedByFabricEntity(String mspId, MSPRoleType role) {
// specify the principal: it's a member of the msp we just found
MSPPrincipal principal = MSPPrincipal
.newBuilder()
.setPrincipalClassification(Classification.ROLE)
.setPrincipal(MSPRole
.newBuilder()
.setMspIdentifier(mspId)
.setRole(role)
.build().toByteString())
.build();
// create the policy: it requires exactly 1 signature from the first (and only) principal
return SignaturePolicyEnvelope
.newBuilder()
.setVersion(0)
.setRule(nOutOf(1, Arrays.asList(signedBy(0))))
.addIdentities(principal)
.build();
} | [
"static",
"SignaturePolicyEnvelope",
"signedByFabricEntity",
"(",
"String",
"mspId",
",",
"MSPRoleType",
"role",
")",
"{",
"// specify the principal: it's a member of the msp we just found",
"MSPPrincipal",
"principal",
"=",
"MSPPrincipal",
".",
"newBuilder",
"(",
")",
".",
... | Creates a {@link SignaturePolicyEnvelope}
requiring 1 signature from any fabric entity, having the passed role, of the specified MSP
@param mspId
@param role
@return | [
"Creates",
"a",
"{",
"@link",
"SignaturePolicyEnvelope",
"}",
"requiring",
"1",
"signature",
"from",
"any",
"fabric",
"entity",
"having",
"the",
"passed",
"role",
"of",
"the",
"specified",
"MSP"
] | train | https://github.com/hyperledger/fabric-chaincode-java/blob/1c688a3c7824758448fec31daaf0a1410a427e91/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementUtils.java#L60-L80 |
fcrepo3/fcrepo | fcrepo-server/src/main/java/org/fcrepo/server/journal/xmlhelpers/ContextXmlReader.java | ContextXmlReader.storeInMultiMap | private void storeInMultiMap(MultiValueMap<String> map, String key, String[] values)
throws JournalException {
try {
map.set(key, values);
} catch (Exception e) {
// totally bogus Exception here.
throw new JournalException(e);
}
} | java | private void storeInMultiMap(MultiValueMap<String> map, String key, String[] values)
throws JournalException {
try {
map.set(key, values);
} catch (Exception e) {
// totally bogus Exception here.
throw new JournalException(e);
}
} | [
"private",
"void",
"storeInMultiMap",
"(",
"MultiValueMap",
"<",
"String",
">",
"map",
",",
"String",
"key",
",",
"String",
"[",
"]",
"values",
")",
"throws",
"JournalException",
"{",
"try",
"{",
"map",
".",
"set",
"(",
"key",
",",
"values",
")",
";",
... | This method is just to guard against the totally bogus Exception
declaration in MultiValueMap.set() | [
"This",
"method",
"is",
"just",
"to",
"guard",
"against",
"the",
"totally",
"bogus",
"Exception",
"declaration",
"in",
"MultiValueMap",
".",
"set",
"()"
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/xmlhelpers/ContextXmlReader.java#L197-L205 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/opengl/CursorLoader.java | CursorLoader.getCursor | public Cursor getCursor(ImageData imageData,int x,int y) throws IOException, LWJGLException {
ByteBuffer buf = imageData.getImageBufferData();
for (int i=0;i<buf.limit();i+=4) {
byte red = buf.get(i);
byte green = buf.get(i+1);
byte blue = buf.get(i+2);
byte alpha = buf.get(i+3);
buf.put(i+2, red);
buf.put(i+1, green);
buf.put(i, blue);
buf.put(i+3, alpha);
}
try {
int yspot = imageData.getHeight() - y - 1;
if (yspot < 0) {
yspot = 0;
}
return new Cursor(imageData.getTexWidth(), imageData.getTexHeight(), x, yspot, 1, buf.asIntBuffer(), null);
} catch (Throwable e) {
Log.info("Chances are you cursor is too small for this platform");
throw new LWJGLException(e);
}
} | java | public Cursor getCursor(ImageData imageData,int x,int y) throws IOException, LWJGLException {
ByteBuffer buf = imageData.getImageBufferData();
for (int i=0;i<buf.limit();i+=4) {
byte red = buf.get(i);
byte green = buf.get(i+1);
byte blue = buf.get(i+2);
byte alpha = buf.get(i+3);
buf.put(i+2, red);
buf.put(i+1, green);
buf.put(i, blue);
buf.put(i+3, alpha);
}
try {
int yspot = imageData.getHeight() - y - 1;
if (yspot < 0) {
yspot = 0;
}
return new Cursor(imageData.getTexWidth(), imageData.getTexHeight(), x, yspot, 1, buf.asIntBuffer(), null);
} catch (Throwable e) {
Log.info("Chances are you cursor is too small for this platform");
throw new LWJGLException(e);
}
} | [
"public",
"Cursor",
"getCursor",
"(",
"ImageData",
"imageData",
",",
"int",
"x",
",",
"int",
"y",
")",
"throws",
"IOException",
",",
"LWJGLException",
"{",
"ByteBuffer",
"buf",
"=",
"imageData",
".",
"getImageBufferData",
"(",
")",
";",
"for",
"(",
"int",
... | Get a cursor based on a set of image data
@param imageData The data from which the cursor can read it's contents
@param x The x-coordinate of the cursor hotspot (left -> right)
@param y The y-coordinate of the cursor hotspot (bottom -> top)
@return The create cursor
@throws IOException Indicates a failure to load the image
@throws LWJGLException Indicates a failure to create the hardware cursor | [
"Get",
"a",
"cursor",
"based",
"on",
"a",
"set",
"of",
"image",
"data"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/opengl/CursorLoader.java#L129-L153 |
spring-projects/spring-data-solr | src/main/java/org/springframework/data/solr/core/query/FacetOptions.java | FacetOptions.addFacetByRange | public final FacetOptions addFacetByRange(FieldWithRangeParameters<?, ?, ?> field) {
Assert.notNull(field, "Cannot range facet on null field.");
Assert.hasText(field.getName(), "Cannot range facet on field with null/empty fieldname.");
this.facetRangeOnFields.add(field);
return this;
} | java | public final FacetOptions addFacetByRange(FieldWithRangeParameters<?, ?, ?> field) {
Assert.notNull(field, "Cannot range facet on null field.");
Assert.hasText(field.getName(), "Cannot range facet on field with null/empty fieldname.");
this.facetRangeOnFields.add(field);
return this;
} | [
"public",
"final",
"FacetOptions",
"addFacetByRange",
"(",
"FieldWithRangeParameters",
"<",
"?",
",",
"?",
",",
"?",
">",
"field",
")",
"{",
"Assert",
".",
"notNull",
"(",
"field",
",",
"\"Cannot range facet on null field.\"",
")",
";",
"Assert",
".",
"hasText",... | Append additional field for range faceting
@param field the {@link Field} to be appended to range faceting fields
@return this
@since 1.5 | [
"Append",
"additional",
"field",
"for",
"range",
"faceting"
] | train | https://github.com/spring-projects/spring-data-solr/blob/20be5cb82498b70134dfda6c1a91ad21f8e657e0/src/main/java/org/springframework/data/solr/core/query/FacetOptions.java#L132-L138 |
wdullaer/SwipeActionAdapter | library/src/main/java/com/wdullaer/swipeactionadapter/SwipeViewGroup.java | SwipeViewGroup.addBackground | public SwipeViewGroup addBackground(View background, SwipeDirection direction){
if(mBackgroundMap.get(direction) != null) removeView(mBackgroundMap.get(direction));
background.setVisibility(View.INVISIBLE);
mBackgroundMap.put(direction, background);
addView(background);
return this;
} | java | public SwipeViewGroup addBackground(View background, SwipeDirection direction){
if(mBackgroundMap.get(direction) != null) removeView(mBackgroundMap.get(direction));
background.setVisibility(View.INVISIBLE);
mBackgroundMap.put(direction, background);
addView(background);
return this;
} | [
"public",
"SwipeViewGroup",
"addBackground",
"(",
"View",
"background",
",",
"SwipeDirection",
"direction",
")",
"{",
"if",
"(",
"mBackgroundMap",
".",
"get",
"(",
"direction",
")",
"!=",
"null",
")",
"removeView",
"(",
"mBackgroundMap",
".",
"get",
"(",
"dire... | Add a View to the background of the Layout. The background should have the same height
as the contentView
@param background The View to be added to the Layout
@param direction The key to be used to find it again
@return A reference to the a layout so commands can be chained | [
"Add",
"a",
"View",
"to",
"the",
"background",
"of",
"the",
"Layout",
".",
"The",
"background",
"should",
"have",
"the",
"same",
"height",
"as",
"the",
"contentView"
] | train | https://github.com/wdullaer/SwipeActionAdapter/blob/24a7e2ed953ac11ea0d8875d375bba571ffeba55/library/src/main/java/com/wdullaer/swipeactionadapter/SwipeViewGroup.java#L76-L83 |
javagl/Common | src/main/java/de/javagl/common/beans/XmlBeanUtil.java | XmlBeanUtil.writeFullBeanXml | public static void writeFullBeanXml(
Object object, OutputStream outputStream)
{
XMLEncoder encoder = XmlEncoders.createVerbose(outputStream);
encoder.setExceptionListener(new ExceptionListener()
{
@Override
public void exceptionThrown(Exception e)
{
throw new XmlException("Could not encode object", e);
}
});
encoder.writeObject(object);
encoder.flush();
encoder.close();
} | java | public static void writeFullBeanXml(
Object object, OutputStream outputStream)
{
XMLEncoder encoder = XmlEncoders.createVerbose(outputStream);
encoder.setExceptionListener(new ExceptionListener()
{
@Override
public void exceptionThrown(Exception e)
{
throw new XmlException("Could not encode object", e);
}
});
encoder.writeObject(object);
encoder.flush();
encoder.close();
} | [
"public",
"static",
"void",
"writeFullBeanXml",
"(",
"Object",
"object",
",",
"OutputStream",
"outputStream",
")",
"{",
"XMLEncoder",
"encoder",
"=",
"XmlEncoders",
".",
"createVerbose",
"(",
"outputStream",
")",
";",
"encoder",
".",
"setExceptionListener",
"(",
"... | Write the XML describing the given bean to the given output stream,
as it is done by an <code>XMLEncoder</code>, but including all
properties, even if they still have their default values. The
caller is responsible for closing the given stream.
@param object The bean object
@param outputStream The stream to write to
@throws XmlException If there is an error while encoding the object | [
"Write",
"the",
"XML",
"describing",
"the",
"given",
"bean",
"to",
"the",
"given",
"output",
"stream",
"as",
"it",
"is",
"done",
"by",
"an",
"<code",
">",
"XMLEncoder<",
"/",
"code",
">",
"but",
"including",
"all",
"properties",
"even",
"if",
"they",
"st... | train | https://github.com/javagl/Common/blob/5a4876b48c3a2dc61d21324733cf37512d721c33/src/main/java/de/javagl/common/beans/XmlBeanUtil.java#L52-L67 |
sgroschupf/zkclient | src/main/java/org/I0Itec/zkclient/ZkClient.java | ZkClient.createPersistent | public void createPersistent(String path, Object data, List<ACL> acl) {
create(path, data, acl, CreateMode.PERSISTENT);
} | java | public void createPersistent(String path, Object data, List<ACL> acl) {
create(path, data, acl, CreateMode.PERSISTENT);
} | [
"public",
"void",
"createPersistent",
"(",
"String",
"path",
",",
"Object",
"data",
",",
"List",
"<",
"ACL",
">",
"acl",
")",
"{",
"create",
"(",
"path",
",",
"data",
",",
"acl",
",",
"CreateMode",
".",
"PERSISTENT",
")",
";",
"}"
] | Create a persistent node.
@param path
@param data
@param acl
@throws ZkInterruptedException
if operation was interrupted, or a required reconnection got interrupted
@throws IllegalArgumentException
if called from anything except the ZooKeeper event thread
@throws ZkException
if any ZooKeeper exception occurred
@throws RuntimeException
if any other exception occurs | [
"Create",
"a",
"persistent",
"node",
"."
] | train | https://github.com/sgroschupf/zkclient/blob/03ccf12c70aca2f771bfcd94d44dc7c4d4a1495e/src/main/java/org/I0Itec/zkclient/ZkClient.java#L404-L406 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/ExpressionResolverImpl.java | ExpressionResolverImpl.resolveExpressionStringRecursively | private ModelNode resolveExpressionStringRecursively(final String expressionString, final boolean ignoreDMRResolutionFailure,
final boolean initial) throws OperationFailedException {
ParseAndResolveResult resolved = parseAndResolve(expressionString, ignoreDMRResolutionFailure);
if (resolved.recursive) {
// Some part of expressionString resolved into a different expression.
// So, start over, ignoring failures. Ignore failures because we don't require
// that expressions must not resolve to something that *looks like* an expression but isn't
return resolveExpressionStringRecursively(resolved.result, true, false);
} else if (resolved.modified) {
// Typical case
return new ModelNode(resolved.result);
} else if (initial && EXPRESSION_PATTERN.matcher(expressionString).matches()) {
// We should only get an unmodified expression string back if there was a resolution
// failure that we ignored.
assert ignoreDMRResolutionFailure;
// expressionString came from a node of type expression, so since we did nothing send it back in the same type
return new ModelNode(new ValueExpression(expressionString));
} else {
// The string wasn't really an expression. Two possible cases:
// 1) if initial == true, someone created a expression node with a non-expression string, which is legal
// 2) if initial == false, we resolved from an ModelType.EXPRESSION to a string that looked like an
// expression but can't be resolved. We don't require that expressions must not resolve to something that
// *looks like* an expression but isn't, so we'll just treat this as a string
return new ModelNode(expressionString);
}
} | java | private ModelNode resolveExpressionStringRecursively(final String expressionString, final boolean ignoreDMRResolutionFailure,
final boolean initial) throws OperationFailedException {
ParseAndResolveResult resolved = parseAndResolve(expressionString, ignoreDMRResolutionFailure);
if (resolved.recursive) {
// Some part of expressionString resolved into a different expression.
// So, start over, ignoring failures. Ignore failures because we don't require
// that expressions must not resolve to something that *looks like* an expression but isn't
return resolveExpressionStringRecursively(resolved.result, true, false);
} else if (resolved.modified) {
// Typical case
return new ModelNode(resolved.result);
} else if (initial && EXPRESSION_PATTERN.matcher(expressionString).matches()) {
// We should only get an unmodified expression string back if there was a resolution
// failure that we ignored.
assert ignoreDMRResolutionFailure;
// expressionString came from a node of type expression, so since we did nothing send it back in the same type
return new ModelNode(new ValueExpression(expressionString));
} else {
// The string wasn't really an expression. Two possible cases:
// 1) if initial == true, someone created a expression node with a non-expression string, which is legal
// 2) if initial == false, we resolved from an ModelType.EXPRESSION to a string that looked like an
// expression but can't be resolved. We don't require that expressions must not resolve to something that
// *looks like* an expression but isn't, so we'll just treat this as a string
return new ModelNode(expressionString);
}
} | [
"private",
"ModelNode",
"resolveExpressionStringRecursively",
"(",
"final",
"String",
"expressionString",
",",
"final",
"boolean",
"ignoreDMRResolutionFailure",
",",
"final",
"boolean",
"initial",
")",
"throws",
"OperationFailedException",
"{",
"ParseAndResolveResult",
"resol... | Attempt to resolve the given expression string, recursing if resolution of one string produces
another expression.
@param expressionString the expression string from a node of {@link ModelType#EXPRESSION}
@param ignoreDMRResolutionFailure {@code false} if {@link org.jboss.dmr.ModelNode#resolve() basic DMR resolution}
failures should be ignored, and {@code new ModelNode(expressionType.asString())} returned
@param initial {@code true} if this call originated outside this method; {@code false} if it is a recursive call
@return a node of {@link ModelType#STRING} where the encapsulated string is the resolved expression, or a node
of {@link ModelType#EXPRESSION} if {@code ignoreDMRResolutionFailure} and {@code initial} are
{@code true} and the string could not be resolved.
@throws OperationFailedException if the expression cannot be resolved | [
"Attempt",
"to",
"resolve",
"the",
"given",
"expression",
"string",
"recursing",
"if",
"resolution",
"of",
"one",
"string",
"produces",
"another",
"expression",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/ExpressionResolverImpl.java#L141-L166 |
moleculer-java/moleculer-java | src/main/java/services/moleculer/ServiceBroker.java | ServiceBroker.waitForServices | public Promise waitForServices(long timeoutMillis, String... services) {
return waitForServices(timeoutMillis, Arrays.asList(services));
} | java | public Promise waitForServices(long timeoutMillis, String... services) {
return waitForServices(timeoutMillis, Arrays.asList(services));
} | [
"public",
"Promise",
"waitForServices",
"(",
"long",
"timeoutMillis",
",",
"String",
"...",
"services",
")",
"{",
"return",
"waitForServices",
"(",
"timeoutMillis",
",",
"Arrays",
".",
"asList",
"(",
"services",
")",
")",
";",
"}"
] | Waits for one (or an array of) service(s). Sample code:<br>
<br>
broker.waitForServices(5000, "logger").then(in -> {<br>
broker.getLogger().info("Logger started successfully");<br>
}.catchError(error -> {<br>
broker.getLogger().info("Logger did not start");<br>
}
@param timeoutMillis
timeout in milliseconds
@param services
array of service names
@return listenable Promise | [
"Waits",
"for",
"one",
"(",
"or",
"an",
"array",
"of",
")",
"service",
"(",
"s",
")",
".",
"Sample",
"code",
":",
"<br",
">",
"<br",
">",
"broker",
".",
"waitForServices",
"(",
"5000",
"logger",
")",
".",
"then",
"(",
"in",
"-",
">",
";",
"{",
... | train | https://github.com/moleculer-java/moleculer-java/blob/27575c44b9ecacc17c4456ceacf5d1851abf1cc4/src/main/java/services/moleculer/ServiceBroker.java#L805-L807 |
imsweb/naaccr-xml | src/main/java/com/imsweb/naaccrxml/sas/SasUtils.java | SasUtils.createWriter | public static BufferedWriter createWriter(File file) throws IOException {
OutputStream os = new FileOutputStream(file);
if (file.getName().toLowerCase().endsWith(".gz"))
os = new GZIPOutputStream(os);
return new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
} | java | public static BufferedWriter createWriter(File file) throws IOException {
OutputStream os = new FileOutputStream(file);
if (file.getName().toLowerCase().endsWith(".gz"))
os = new GZIPOutputStream(os);
return new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
} | [
"public",
"static",
"BufferedWriter",
"createWriter",
"(",
"File",
"file",
")",
"throws",
"IOException",
"{",
"OutputStream",
"os",
"=",
"new",
"FileOutputStream",
"(",
"file",
")",
";",
"if",
"(",
"file",
".",
"getName",
"(",
")",
".",
"toLowerCase",
"(",
... | Creates a writer from the given file. Supports GZIP compressed files.
@param file file to write
@return writer | [
"Creates",
"a",
"writer",
"from",
"the",
"given",
"file",
".",
"Supports",
"GZIP",
"compressed",
"files",
"."
] | train | https://github.com/imsweb/naaccr-xml/blob/a3a501faa2a0c3411dd5248b2c1379f279131696/src/main/java/com/imsweb/naaccrxml/sas/SasUtils.java#L50-L55 |
morimekta/utils | io-util/src/main/java/net/morimekta/util/io/IndentedPrintWriter.java | IndentedPrintWriter.printf | @Override
public IndentedPrintWriter printf(String format, Object... args) {
super.format(format, args);
return this;
} | java | @Override
public IndentedPrintWriter printf(String format, Object... args) {
super.format(format, args);
return this;
} | [
"@",
"Override",
"public",
"IndentedPrintWriter",
"printf",
"(",
"String",
"format",
",",
"Object",
"...",
"args",
")",
"{",
"super",
".",
"format",
"(",
"format",
",",
"args",
")",
";",
"return",
"this",
";",
"}"
] | --- Override PrintWriter methods to return IndentedPrintWriter. | [
"---",
"Override",
"PrintWriter",
"methods",
"to",
"return",
"IndentedPrintWriter",
"."
] | train | https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/io/IndentedPrintWriter.java#L132-L136 |
ksclarke/freelib-utils | src/main/java/info/freelibrary/util/FileUtils.java | FileUtils.toElement | public static Element toElement(final String aFilePath, final String aPattern) throws FileNotFoundException,
ParserConfigurationException {
return toElement(aFilePath, aPattern, false);
} | java | public static Element toElement(final String aFilePath, final String aPattern) throws FileNotFoundException,
ParserConfigurationException {
return toElement(aFilePath, aPattern, false);
} | [
"public",
"static",
"Element",
"toElement",
"(",
"final",
"String",
"aFilePath",
",",
"final",
"String",
"aPattern",
")",
"throws",
"FileNotFoundException",
",",
"ParserConfigurationException",
"{",
"return",
"toElement",
"(",
"aFilePath",
",",
"aPattern",
",",
"fal... | Returns an XML Element representing the file structure found at the supplied file system path. Files included
in the representation will match the supplied regular expression pattern. This method doesn't descend through
the directory structure.
@param aFilePath The directory from which the structural representation should be built
@param aPattern A regular expression pattern which files included in the Element should match
@return An XML Element representation of the directory structure
@throws FileNotFoundException If the supplied directory isn't found
@throws ParserConfigurationException If the default XML parser for the JRE isn't configured correctly | [
"Returns",
"an",
"XML",
"Element",
"representing",
"the",
"file",
"structure",
"found",
"at",
"the",
"supplied",
"file",
"system",
"path",
".",
"Files",
"included",
"in",
"the",
"representation",
"will",
"match",
"the",
"supplied",
"regular",
"expression",
"patt... | train | https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/FileUtils.java#L254-L257 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUBinary.java | ICUBinary.compareKeys | static int compareKeys(CharSequence key, ByteBuffer bytes, int offset) {
for (int i = 0;; ++i, ++offset) {
int c2 = bytes.get(offset);
if (c2 == 0) {
if (i == key.length()) {
return 0;
} else {
return 1; // key > table key because key is longer.
}
} else if (i == key.length()) {
return -1; // key < table key because key is shorter.
}
int diff = key.charAt(i) - c2;
if (diff != 0) {
return diff;
}
}
} | java | static int compareKeys(CharSequence key, ByteBuffer bytes, int offset) {
for (int i = 0;; ++i, ++offset) {
int c2 = bytes.get(offset);
if (c2 == 0) {
if (i == key.length()) {
return 0;
} else {
return 1; // key > table key because key is longer.
}
} else if (i == key.length()) {
return -1; // key < table key because key is shorter.
}
int diff = key.charAt(i) - c2;
if (diff != 0) {
return diff;
}
}
} | [
"static",
"int",
"compareKeys",
"(",
"CharSequence",
"key",
",",
"ByteBuffer",
"bytes",
",",
"int",
"offset",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
";",
"++",
"i",
",",
"++",
"offset",
")",
"{",
"int",
"c2",
"=",
"bytes",
".",
"get",
"... | Compares the length-specified input key with the
NUL-terminated table key. (ASCII) | [
"Compares",
"the",
"length",
"-",
"specified",
"input",
"key",
"with",
"the",
"NUL",
"-",
"terminated",
"table",
"key",
".",
"(",
"ASCII",
")"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUBinary.java#L362-L379 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WButtonRenderer.java | WButtonRenderer.paintAjax | private void paintAjax(final WButton button, final XmlStringBuilder xml) {
// Start tag
xml.appendTagOpen("ui:ajaxtrigger");
xml.appendAttribute("triggerId", button.getId());
xml.appendClose();
// Target
xml.appendTagOpen("ui:ajaxtargetid");
xml.appendAttribute("targetId", button.getAjaxTarget().getId());
xml.appendEnd();
// End tag
xml.appendEndTag("ui:ajaxtrigger");
} | java | private void paintAjax(final WButton button, final XmlStringBuilder xml) {
// Start tag
xml.appendTagOpen("ui:ajaxtrigger");
xml.appendAttribute("triggerId", button.getId());
xml.appendClose();
// Target
xml.appendTagOpen("ui:ajaxtargetid");
xml.appendAttribute("targetId", button.getAjaxTarget().getId());
xml.appendEnd();
// End tag
xml.appendEndTag("ui:ajaxtrigger");
} | [
"private",
"void",
"paintAjax",
"(",
"final",
"WButton",
"button",
",",
"final",
"XmlStringBuilder",
"xml",
")",
"{",
"// Start tag",
"xml",
".",
"appendTagOpen",
"(",
"\"ui:ajaxtrigger\"",
")",
";",
"xml",
".",
"appendAttribute",
"(",
"\"triggerId\"",
",",
"but... | Paints the AJAX information for the given WButton.
@param button the WButton to paint.
@param xml the XmlStringBuilder to paint to. | [
"Paints",
"the",
"AJAX",
"information",
"for",
"the",
"given",
"WButton",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WButtonRenderer.java#L134-L147 |
cloudant/java-cloudant | cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java | HttpConnection.setRequestBody | public HttpConnection setRequestBody(final InputStream input, final long inputLength) {
try {
return setRequestBody(new InputStreamWrappingGenerator(input, inputLength),
inputLength);
} catch (IOException e) {
logger.log(Level.SEVERE, "Error copying input stream for request body", e);
throw new RuntimeException(e);
}
} | java | public HttpConnection setRequestBody(final InputStream input, final long inputLength) {
try {
return setRequestBody(new InputStreamWrappingGenerator(input, inputLength),
inputLength);
} catch (IOException e) {
logger.log(Level.SEVERE, "Error copying input stream for request body", e);
throw new RuntimeException(e);
}
} | [
"public",
"HttpConnection",
"setRequestBody",
"(",
"final",
"InputStream",
"input",
",",
"final",
"long",
"inputLength",
")",
"{",
"try",
"{",
"return",
"setRequestBody",
"(",
"new",
"InputStreamWrappingGenerator",
"(",
"input",
",",
"inputLength",
")",
",",
"inpu... | Set the InputStream of request body data, of known length, to be sent to the server.
@param input InputStream of request body data to be sent to the server
@param inputLength Length of request body data to be sent to the server, in bytes
@return an {@link HttpConnection} for method chaining
@deprecated Use {@link #setRequestBody(InputStreamGenerator, long)} | [
"Set",
"the",
"InputStream",
"of",
"request",
"body",
"data",
"of",
"known",
"length",
"to",
"be",
"sent",
"to",
"the",
"server",
"."
] | train | https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java#L197-L205 |
pryzach/midao | midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/utils/InputUtils.java | InputUtils.getClassName | public static String getClassName(Map<String, Object> map) {
String className = null;
if (map.containsKey(MAP_CLASS_NAME) == true) {
className = (String) map.get(MAP_CLASS_NAME);
}
return className;
} | java | public static String getClassName(Map<String, Object> map) {
String className = null;
if (map.containsKey(MAP_CLASS_NAME) == true) {
className = (String) map.get(MAP_CLASS_NAME);
}
return className;
} | [
"public",
"static",
"String",
"getClassName",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
")",
"{",
"String",
"className",
"=",
"null",
";",
"if",
"(",
"map",
".",
"containsKey",
"(",
"MAP_CLASS_NAME",
")",
"==",
"true",
")",
"{",
"className",
... | InputHandler converts every object into Map.
This function returns Class name of object from which this Map was created.
@param map Map from which Class name would be returned
@return Class name from which Map was built | [
"InputHandler",
"converts",
"every",
"object",
"into",
"Map",
".",
"This",
"function",
"returns",
"Class",
"name",
"of",
"object",
"from",
"which",
"this",
"Map",
"was",
"created",
"."
] | train | https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/utils/InputUtils.java#L58-L66 |
tvesalainen/util | util/src/main/java/d3/env/TSAGeoMag.java | TSAGeoMag.getIntensity | public double getIntensity( double dlat, double dlong, double year, double altitude )
{
calcGeoMag( dlat, dlong, year, altitude );
return ti;
} | java | public double getIntensity( double dlat, double dlong, double year, double altitude )
{
calcGeoMag( dlat, dlong, year, altitude );
return ti;
} | [
"public",
"double",
"getIntensity",
"(",
"double",
"dlat",
",",
"double",
"dlong",
",",
"double",
"year",
",",
"double",
"altitude",
")",
"{",
"calcGeoMag",
"(",
"dlat",
",",
"dlong",
",",
"year",
",",
"altitude",
")",
";",
"return",
"ti",
";",
"}"
] | Returns the magnetic field intensity from the
Department of Defense geomagnetic model and data
in nano Tesla.
@param dlat Latitude in decimal degrees.
@param dlong Longitude in decimal degrees.
@param year Date of the calculation in decimal years.
@param altitude Altitude of the calculation in kilometers.
@return Magnetic field strength in nano Tesla. | [
"Returns",
"the",
"magnetic",
"field",
"intensity",
"from",
"the",
"Department",
"of",
"Defense",
"geomagnetic",
"model",
"and",
"data",
"in",
"nano",
"Tesla",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/d3/env/TSAGeoMag.java#L968-L972 |
Azure/azure-sdk-for-java | logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/SchemasInner.java | SchemasInner.getAsync | public Observable<IntegrationAccountSchemaInner> getAsync(String resourceGroupName, String integrationAccountName, String schemaName) {
return getWithServiceResponseAsync(resourceGroupName, integrationAccountName, schemaName).map(new Func1<ServiceResponse<IntegrationAccountSchemaInner>, IntegrationAccountSchemaInner>() {
@Override
public IntegrationAccountSchemaInner call(ServiceResponse<IntegrationAccountSchemaInner> response) {
return response.body();
}
});
} | java | public Observable<IntegrationAccountSchemaInner> getAsync(String resourceGroupName, String integrationAccountName, String schemaName) {
return getWithServiceResponseAsync(resourceGroupName, integrationAccountName, schemaName).map(new Func1<ServiceResponse<IntegrationAccountSchemaInner>, IntegrationAccountSchemaInner>() {
@Override
public IntegrationAccountSchemaInner call(ServiceResponse<IntegrationAccountSchemaInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"IntegrationAccountSchemaInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"integrationAccountName",
",",
"String",
"schemaName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"inte... | Gets an integration account schema.
@param resourceGroupName The resource group name.
@param integrationAccountName The integration account name.
@param schemaName The integration account schema name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the IntegrationAccountSchemaInner object | [
"Gets",
"an",
"integration",
"account",
"schema",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/SchemasInner.java#L381-L388 |
strator-dev/greenpepper | greenpepper/greenpepper-client/src/main/java/com/greenpepper/util/I18nUtil.java | I18nUtil.getText | public static String getText(String key, ResourceBundle bundle, Object... arguments)
{
try
{
String value = bundle.getString(key);
return MessageFormat.format(value, arguments);
}
catch (MissingResourceException ex)
{
return key;
}
} | java | public static String getText(String key, ResourceBundle bundle, Object... arguments)
{
try
{
String value = bundle.getString(key);
return MessageFormat.format(value, arguments);
}
catch (MissingResourceException ex)
{
return key;
}
} | [
"public",
"static",
"String",
"getText",
"(",
"String",
"key",
",",
"ResourceBundle",
"bundle",
",",
"Object",
"...",
"arguments",
")",
"{",
"try",
"{",
"String",
"value",
"=",
"bundle",
".",
"getString",
"(",
"key",
")",
";",
"return",
"MessageFormat",
".... | <p>getText.</p>
@param key a {@link java.lang.String} object.
@param bundle a {@link java.util.ResourceBundle} object.
@param arguments a {@link java.lang.Object} object.
@return a {@link java.lang.String} object. | [
"<p",
">",
"getText",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/greenpepper-client/src/main/java/com/greenpepper/util/I18nUtil.java#L48-L60 |
Azure/azure-sdk-for-java | authorization/resource-manager/v2015_07_01/src/main/java/com/microsoft/azure/management/authorization/v2015_07_01/implementation/ProviderOperationsMetadatasInner.java | ProviderOperationsMetadatasInner.getAsync | public Observable<ProviderOperationsMetadataInner> getAsync(String resourceProviderNamespace, String apiVersion) {
return getWithServiceResponseAsync(resourceProviderNamespace, apiVersion).map(new Func1<ServiceResponse<ProviderOperationsMetadataInner>, ProviderOperationsMetadataInner>() {
@Override
public ProviderOperationsMetadataInner call(ServiceResponse<ProviderOperationsMetadataInner> response) {
return response.body();
}
});
} | java | public Observable<ProviderOperationsMetadataInner> getAsync(String resourceProviderNamespace, String apiVersion) {
return getWithServiceResponseAsync(resourceProviderNamespace, apiVersion).map(new Func1<ServiceResponse<ProviderOperationsMetadataInner>, ProviderOperationsMetadataInner>() {
@Override
public ProviderOperationsMetadataInner call(ServiceResponse<ProviderOperationsMetadataInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ProviderOperationsMetadataInner",
">",
"getAsync",
"(",
"String",
"resourceProviderNamespace",
",",
"String",
"apiVersion",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceProviderNamespace",
",",
"apiVersion",
")",
".",
"map... | Gets provider operations metadata for the specified resource provider.
@param resourceProviderNamespace The namespace of the resource provider.
@param apiVersion The API version to use for the operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ProviderOperationsMetadataInner object | [
"Gets",
"provider",
"operations",
"metadata",
"for",
"the",
"specified",
"resource",
"provider",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/authorization/resource-manager/v2015_07_01/src/main/java/com/microsoft/azure/management/authorization/v2015_07_01/implementation/ProviderOperationsMetadatasInner.java#L109-L116 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/utils/TernaryPatcher.java | TernaryPatcher.post | public static void post(OpcodeStack stack, int opcode) {
if (!sawGOTO || (opcode == Const.GOTO) || (opcode == Const.GOTO_W)) {
return;
}
int depth = stack.getStackDepth();
for (int i = 0; i < depth && i < userValues.size(); i++) {
OpcodeStack.Item item = stack.getStackItem(i);
if (item.getUserValue() == null) {
item.setUserValue(userValues.get(i));
}
}
userValues.clear();
sawGOTO = false;
} | java | public static void post(OpcodeStack stack, int opcode) {
if (!sawGOTO || (opcode == Const.GOTO) || (opcode == Const.GOTO_W)) {
return;
}
int depth = stack.getStackDepth();
for (int i = 0; i < depth && i < userValues.size(); i++) {
OpcodeStack.Item item = stack.getStackItem(i);
if (item.getUserValue() == null) {
item.setUserValue(userValues.get(i));
}
}
userValues.clear();
sawGOTO = false;
} | [
"public",
"static",
"void",
"post",
"(",
"OpcodeStack",
"stack",
",",
"int",
"opcode",
")",
"{",
"if",
"(",
"!",
"sawGOTO",
"||",
"(",
"opcode",
"==",
"Const",
".",
"GOTO",
")",
"||",
"(",
"opcode",
"==",
"Const",
".",
"GOTO_W",
")",
")",
"{",
"ret... | called after the execution of the parent OpcodeStack.sawOpcode, to restore the user values after the GOTO or GOTO_W's mergeJumps were processed
@param stack
the OpcodeStack with the items containing user values
@param opcode
the opcode currently seen | [
"called",
"after",
"the",
"execution",
"of",
"the",
"parent",
"OpcodeStack",
".",
"sawOpcode",
"to",
"restore",
"the",
"user",
"values",
"after",
"the",
"GOTO",
"or",
"GOTO_W",
"s",
"mergeJumps",
"were",
"processed"
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/utils/TernaryPatcher.java#L76-L90 |
kkopacz/agiso-tempel | bundles/tempel-core/src/main/java/org/agiso/tempel/core/DefaultTemplateExecutor.java | DefaultTemplateExecutor.executeTemplate | @Override
public void executeTemplate(String templateName, Map<String, Object> properties, String workDir) {
// Pobieranie definicji szablonu do użycia:
Template<?> template = templateProvider.get(templateName, null, null, null);
if(template == null) {
throw new RuntimeException("Nie znaleziono szablonu " + templateName);
}
if(template.isAbstract()) {
throw new AbstractTemplateException(templateName);
}
// Weryfikowanie definicji szablonu, szablonu nadrzędnego i wszystkich
// szablonów używanych. Sprawdzanie dostępność klas silników generatorów.
templateVerifier.verifyTemplate(template, templateProvider);
MapStack<String, Object> propertiesStack = new SimpleMapStack<String,Object>();
propertiesStack.push(new HashMap<String, Object>(properties));
doExecuteTemplate(template, propertiesStack, workDir);
propertiesStack.pop();
} | java | @Override
public void executeTemplate(String templateName, Map<String, Object> properties, String workDir) {
// Pobieranie definicji szablonu do użycia:
Template<?> template = templateProvider.get(templateName, null, null, null);
if(template == null) {
throw new RuntimeException("Nie znaleziono szablonu " + templateName);
}
if(template.isAbstract()) {
throw new AbstractTemplateException(templateName);
}
// Weryfikowanie definicji szablonu, szablonu nadrzędnego i wszystkich
// szablonów używanych. Sprawdzanie dostępność klas silników generatorów.
templateVerifier.verifyTemplate(template, templateProvider);
MapStack<String, Object> propertiesStack = new SimpleMapStack<String,Object>();
propertiesStack.push(new HashMap<String, Object>(properties));
doExecuteTemplate(template, propertiesStack, workDir);
propertiesStack.pop();
} | [
"@",
"Override",
"public",
"void",
"executeTemplate",
"(",
"String",
"templateName",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
",",
"String",
"workDir",
")",
"{",
"// Pobieranie definicji szablonu do użycia:",
"Template",
"<",
"?",
">",
"templat... | Uruchamia proces generacji treści w oparciu o szablon.
@param templateName Szablon do uruchomienia.
@param properties Mapa parametrów uruchomienia szablonu.
@param workDir Ścieżka do katalogu roboczego. | [
"Uruchamia",
"proces",
"generacji",
"treści",
"w",
"oparciu",
"o",
"szablon",
"."
] | train | https://github.com/kkopacz/agiso-tempel/blob/ff7a96153153b6bc07212d776816b87d9538f6fa/bundles/tempel-core/src/main/java/org/agiso/tempel/core/DefaultTemplateExecutor.java#L125-L144 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/util/PropertyUtils.java | PropertyUtils.getPropertyDescriptor | private static PropertyDescriptor getPropertyDescriptor(Object bean, String name) {
PropertyDescriptor descriptor = null;
PropertyDescriptor descriptors[] = getPropertyDescriptors(bean.getClass());
if (descriptors != null) {
for (PropertyDescriptor descriptor1 : descriptors) {
if (name.equals(descriptor1.getName())) {
descriptor = descriptor1;
}
}
}
return descriptor;
} | java | private static PropertyDescriptor getPropertyDescriptor(Object bean, String name) {
PropertyDescriptor descriptor = null;
PropertyDescriptor descriptors[] = getPropertyDescriptors(bean.getClass());
if (descriptors != null) {
for (PropertyDescriptor descriptor1 : descriptors) {
if (name.equals(descriptor1.getName())) {
descriptor = descriptor1;
}
}
}
return descriptor;
} | [
"private",
"static",
"PropertyDescriptor",
"getPropertyDescriptor",
"(",
"Object",
"bean",
",",
"String",
"name",
")",
"{",
"PropertyDescriptor",
"descriptor",
"=",
"null",
";",
"PropertyDescriptor",
"descriptors",
"[",
"]",
"=",
"getPropertyDescriptors",
"(",
"bean",... | <p>
Retrieve the property descriptor for the specified property of the
specified bean, or return <code>null</code> if there is no such
descriptor. This method resolves indexed and nested property references
in the same manner as other methods in this class, except that if the
last (or only) name element is indexed, the descriptor for the last
resolved property itself is returned.
</p>
@param bean
Bean for which a property descriptor is requested
@param name
Possibly indexed and/or nested name of the property for which
a property descriptor is requested
@exception IllegalAccessException
if the caller does not have access to the property
accessor method
@exception IllegalArgumentException
if <code>bean</code> or <code>name</code> is null
@exception IllegalArgumentException
if a nested reference to a property returns null
@exception InvocationTargetException
if the property accessor method throws an exception
@exception NoSuchMethodException
if an accessor method for this propety cannot be found | [
"<p",
">",
"Retrieve",
"the",
"property",
"descriptor",
"for",
"the",
"specified",
"property",
"of",
"the",
"specified",
"bean",
"or",
"return",
"<code",
">",
"null<",
"/",
"code",
">",
"if",
"there",
"is",
"no",
"such",
"descriptor",
".",
"This",
"method"... | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/util/PropertyUtils.java#L116-L128 |
kite-sdk/kite | kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/filesystem/FileSystemDatasetRepository.java | FileSystemDatasetRepository.partitionKeyForPath | @SuppressWarnings({"unchecked", "deprecation"})
public static PartitionKey partitionKeyForPath(Dataset dataset, URI partitionPath) {
Preconditions.checkState(dataset.getDescriptor().isPartitioned(),
"Attempt to get a partition on a non-partitioned dataset (name:%s)",
dataset.getName());
Preconditions.checkArgument(dataset instanceof FileSystemDataset,
"Dataset is not a FileSystemDataset");
FileSystemDataset fsDataset = (FileSystemDataset) dataset;
FileSystem fs = fsDataset.getFileSystem();
URI partitionUri = fs.makeQualified(new Path(partitionPath)).toUri();
URI directoryUri = fsDataset.getDirectory().toUri();
URI relativizedUri = directoryUri.relativize(partitionUri);
if (relativizedUri.equals(partitionUri)) {
throw new IllegalArgumentException(String.format("Partition URI %s has different " +
"root directory to dataset (directory: %s).", partitionUri, directoryUri));
}
Iterable<String> parts = Splitter.on('/').split(relativizedUri.getPath());
PartitionStrategy partitionStrategy = dataset.getDescriptor().getPartitionStrategy();
List<FieldPartitioner> fieldPartitioners =
Accessor.getDefault().getFieldPartitioners(partitionStrategy);
if (Iterables.size(parts) > fieldPartitioners.size()) {
throw new IllegalArgumentException(String.format("Too many partition directories " +
"for %s (%s), expecting %s.", partitionUri, Iterables.size(parts),
fieldPartitioners.size()));
}
Schema schema = dataset.getDescriptor().getSchema();
List<Object> values = Lists.newArrayList();
int i = 0;
for (String part : parts) {
Iterator<String> split = Splitter.on('=').split(part).iterator();
String fieldName = split.next();
FieldPartitioner fp = fieldPartitioners.get(i++);
if (!fieldName.equals(fp.getName())) {
throw new IllegalArgumentException(String.format("Unrecognized partition name " +
"'%s' in partition %s, expecting '%s'.", fieldName, partitionUri,
fp.getName()));
}
if (!split.hasNext()) {
throw new IllegalArgumentException(String.format("Missing partition value for " +
"'%s' in partition %s.", fieldName, partitionUri));
}
String stringValue = split.next();
values.add(PathConversion.valueForDirname(fp, schema, stringValue));
}
return new PartitionKey(values.toArray(new Object[values.size()]));
} | java | @SuppressWarnings({"unchecked", "deprecation"})
public static PartitionKey partitionKeyForPath(Dataset dataset, URI partitionPath) {
Preconditions.checkState(dataset.getDescriptor().isPartitioned(),
"Attempt to get a partition on a non-partitioned dataset (name:%s)",
dataset.getName());
Preconditions.checkArgument(dataset instanceof FileSystemDataset,
"Dataset is not a FileSystemDataset");
FileSystemDataset fsDataset = (FileSystemDataset) dataset;
FileSystem fs = fsDataset.getFileSystem();
URI partitionUri = fs.makeQualified(new Path(partitionPath)).toUri();
URI directoryUri = fsDataset.getDirectory().toUri();
URI relativizedUri = directoryUri.relativize(partitionUri);
if (relativizedUri.equals(partitionUri)) {
throw new IllegalArgumentException(String.format("Partition URI %s has different " +
"root directory to dataset (directory: %s).", partitionUri, directoryUri));
}
Iterable<String> parts = Splitter.on('/').split(relativizedUri.getPath());
PartitionStrategy partitionStrategy = dataset.getDescriptor().getPartitionStrategy();
List<FieldPartitioner> fieldPartitioners =
Accessor.getDefault().getFieldPartitioners(partitionStrategy);
if (Iterables.size(parts) > fieldPartitioners.size()) {
throw new IllegalArgumentException(String.format("Too many partition directories " +
"for %s (%s), expecting %s.", partitionUri, Iterables.size(parts),
fieldPartitioners.size()));
}
Schema schema = dataset.getDescriptor().getSchema();
List<Object> values = Lists.newArrayList();
int i = 0;
for (String part : parts) {
Iterator<String> split = Splitter.on('=').split(part).iterator();
String fieldName = split.next();
FieldPartitioner fp = fieldPartitioners.get(i++);
if (!fieldName.equals(fp.getName())) {
throw new IllegalArgumentException(String.format("Unrecognized partition name " +
"'%s' in partition %s, expecting '%s'.", fieldName, partitionUri,
fp.getName()));
}
if (!split.hasNext()) {
throw new IllegalArgumentException(String.format("Missing partition value for " +
"'%s' in partition %s.", fieldName, partitionUri));
}
String stringValue = split.next();
values.add(PathConversion.valueForDirname(fp, schema, stringValue));
}
return new PartitionKey(values.toArray(new Object[values.size()]));
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
",",
"\"deprecation\"",
"}",
")",
"public",
"static",
"PartitionKey",
"partitionKeyForPath",
"(",
"Dataset",
"dataset",
",",
"URI",
"partitionPath",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"dataset",
"... | Get a {@link org.kitesdk.data.spi.PartitionKey} corresponding to a partition's filesystem path
represented as a {@link URI}. If the path is not a valid partition,
then {@link IllegalArgumentException} is thrown. Note that the partition does not
have to exist.
@param dataset the filesystem dataset
@param partitionPath a directory path where the partition data is stored
@return a partition key representing the partition at the given path
@since 0.4.0 | [
"Get",
"a",
"{"
] | train | https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/filesystem/FileSystemDatasetRepository.java#L332-L384 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/linear/kernelized/OSKL.java | OSKL.scoreSaveEval | private double scoreSaveEval(Vec x, List<Double> qi)
{
inputKEvals.clear();
inputKEvals.add(k.eval(0, 0, Arrays.asList(x), qi));
double sum = 0;
for(int i = 0; i < alphas.size(); i++)
{
double k_ix = k.eval(i, x, qi, vecs, accelCache);
inputKEvals.add(k_ix);
sum += alphas.getD(i)*k_ix;
}
return sum;
} | java | private double scoreSaveEval(Vec x, List<Double> qi)
{
inputKEvals.clear();
inputKEvals.add(k.eval(0, 0, Arrays.asList(x), qi));
double sum = 0;
for(int i = 0; i < alphas.size(); i++)
{
double k_ix = k.eval(i, x, qi, vecs, accelCache);
inputKEvals.add(k_ix);
sum += alphas.getD(i)*k_ix;
}
return sum;
} | [
"private",
"double",
"scoreSaveEval",
"(",
"Vec",
"x",
",",
"List",
"<",
"Double",
">",
"qi",
")",
"{",
"inputKEvals",
".",
"clear",
"(",
")",
";",
"inputKEvals",
".",
"add",
"(",
"k",
".",
"eval",
"(",
"0",
",",
"0",
",",
"Arrays",
".",
"asList",
... | Computes the score and saves the results of the kernel computations in
{@link #inputKEvals}. The first value in the list will be the self kernel
product
@param x the input vector
@param qi the query information for the vector
@return the dot product in the kernel space | [
"Computes",
"the",
"score",
"and",
"saves",
"the",
"results",
"of",
"the",
"kernel",
"computations",
"in",
"{"
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/linear/kernelized/OSKL.java#L376-L388 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.