repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 188 | func_name stringlengths 7 127 | whole_func_string stringlengths 77 3.91k | language stringclasses 1
value | func_code_string stringlengths 77 3.91k | func_code_tokens listlengths 20 745 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 477 | split_name stringclasses 1
value | func_code_url stringlengths 111 288 |
|---|---|---|---|---|---|---|---|---|---|---|
LMAX-Exchange/disruptor | src/main/java/com/lmax/disruptor/dsl/Disruptor.java | Disruptor.handleEventsWith | @SuppressWarnings("varargs")
@SafeVarargs
public final EventHandlerGroup<T> handleEventsWith(final EventHandler<? super T>... handlers)
{
return createEventProcessors(new Sequence[0], handlers);
} | java | @SuppressWarnings("varargs")
@SafeVarargs
public final EventHandlerGroup<T> handleEventsWith(final EventHandler<? super T>... handlers)
{
return createEventProcessors(new Sequence[0], handlers);
} | [
"@",
"SuppressWarnings",
"(",
"\"varargs\"",
")",
"@",
"SafeVarargs",
"public",
"final",
"EventHandlerGroup",
"<",
"T",
">",
"handleEventsWith",
"(",
"final",
"EventHandler",
"<",
"?",
"super",
"T",
">",
"...",
"handlers",
")",
"{",
"return",
"createEventProcess... | <p>Set up event handlers to handle events from the ring buffer. These handlers will process events
as soon as they become available, in parallel.</p>
<p>This method can be used as the start of a chain. For example if the handler <code>A</code> must
process events before handler <code>B</code>:</p>
<pre><code>dw.handleEventsWith(A).then(B);</code></pre>
<p>This call is additive, but generally should only be called once when setting up the Disruptor instance</p>
@param handlers the event handlers that will process events.
@return a {@link EventHandlerGroup} that can be used to chain dependencies. | [
"<p",
">",
"Set",
"up",
"event",
"handlers",
"to",
"handle",
"events",
"from",
"the",
"ring",
"buffer",
".",
"These",
"handlers",
"will",
"process",
"events",
"as",
"soon",
"as",
"they",
"become",
"available",
"in",
"parallel",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/LMAX-Exchange/disruptor/blob/4266d00c5250190313446fdd7c8aa7a4edb5c818/src/main/java/com/lmax/disruptor/dsl/Disruptor.java#L163-L168 |
vkostyukov/la4j | src/main/java/org/la4j/Matrix.java | Matrix.setRow | public void setRow(int i, double value) {
VectorIterator it = iteratorOfRow(i);
while (it.hasNext()) {
it.next();
it.set(value);
}
} | java | public void setRow(int i, double value) {
VectorIterator it = iteratorOfRow(i);
while (it.hasNext()) {
it.next();
it.set(value);
}
} | [
"public",
"void",
"setRow",
"(",
"int",
"i",
",",
"double",
"value",
")",
"{",
"VectorIterator",
"it",
"=",
"iteratorOfRow",
"(",
"i",
")",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{",
"it",
".",
"next",
"(",
")",
";",
"it",
".",
... | <p>
Sets all elements of the specified row of this matrix to given {@code value}.
</p>
@param i the row index
@param value the element's new value | [
"<p",
">",
"Sets",
"all",
"elements",
"of",
"the",
"specified",
"row",
"of",
"this",
"matrix",
"to",
"given",
"{",
"@code",
"value",
"}",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/Matrix.java#L441-L448 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetsInner.java | VirtualMachineScaleSetsInner.beginUpdateInstancesAsync | public Observable<OperationStatusResponseInner> beginUpdateInstancesAsync(String resourceGroupName, String vmScaleSetName, List<String> instanceIds) {
return beginUpdateInstancesWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceIds).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() {
@Override
public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) {
return response.body();
}
});
} | java | public Observable<OperationStatusResponseInner> beginUpdateInstancesAsync(String resourceGroupName, String vmScaleSetName, List<String> instanceIds) {
return beginUpdateInstancesWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceIds).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() {
@Override
public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"OperationStatusResponseInner",
">",
"beginUpdateInstancesAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"vmScaleSetName",
",",
"List",
"<",
"String",
">",
"instanceIds",
")",
"{",
"return",
"beginUpdateInstancesWithServiceResponseAs... | Upgrades one or more virtual machines to the latest SKU set in the VM scale set model.
@param resourceGroupName The name of the resource group.
@param vmScaleSetName The name of the VM scale set.
@param instanceIds The virtual machine scale set instance ids.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the OperationStatusResponseInner object | [
"Upgrades",
"one",
"or",
"more",
"virtual",
"machines",
"to",
"the",
"latest",
"SKU",
"set",
"in",
"the",
"VM",
"scale",
"set",
"model",
"."
] | 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/VirtualMachineScaleSetsInner.java#L2820-L2827 |
kaazing/gateway | mina.core/core/src/main/java/org/apache/mina/proxy/handlers/http/ntlm/NTLMUtilities.java | NTLMUtilities.extractTargetInfoFromType2Message | public static byte[] extractTargetInfoFromType2Message(byte[] msg,
Integer msgFlags) {
int flags = msgFlags == null ? extractFlagsFromType2Message(msg)
: msgFlags;
if (!ByteUtilities.isFlagSet(flags, FLAG_NEGOTIATE_TARGET_INFO))
return null;
int pos = 40; //isFlagSet(flags, FLAG_NEGOTIATE_LOCAL_CALL) ? 40 : 32;
return readSecurityBufferTarget(msg, pos);
} | java | public static byte[] extractTargetInfoFromType2Message(byte[] msg,
Integer msgFlags) {
int flags = msgFlags == null ? extractFlagsFromType2Message(msg)
: msgFlags;
if (!ByteUtilities.isFlagSet(flags, FLAG_NEGOTIATE_TARGET_INFO))
return null;
int pos = 40; //isFlagSet(flags, FLAG_NEGOTIATE_LOCAL_CALL) ? 40 : 32;
return readSecurityBufferTarget(msg, pos);
} | [
"public",
"static",
"byte",
"[",
"]",
"extractTargetInfoFromType2Message",
"(",
"byte",
"[",
"]",
"msg",
",",
"Integer",
"msgFlags",
")",
"{",
"int",
"flags",
"=",
"msgFlags",
"==",
"null",
"?",
"extractFlagsFromType2Message",
"(",
"msg",
")",
":",
"msgFlags",... | Extracts the target information block from the type 2 message.
@param msg the type 2 message byte array
@param msgFlags the flags if null then flags are extracted from the
type 2 message
@return the target info | [
"Extracts",
"the",
"target",
"information",
"block",
"from",
"the",
"type",
"2",
"message",
"."
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.core/core/src/main/java/org/apache/mina/proxy/handlers/http/ntlm/NTLMUtilities.java#L330-L341 |
MythTV-Clients/MythTV-Service-API | src/main/java/org/mythtv/services/api/ServerVersionQuery.java | ServerVersionQuery.getMythVersion | public static ApiVersion getMythVersion(String baseUri, long connectTimeout, TimeUnit timeUnit) throws IOException {
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(connectTimeout, timeUnit);
return getMythVersion(baseUri, client);
} | java | public static ApiVersion getMythVersion(String baseUri, long connectTimeout, TimeUnit timeUnit) throws IOException {
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(connectTimeout, timeUnit);
return getMythVersion(baseUri, client);
} | [
"public",
"static",
"ApiVersion",
"getMythVersion",
"(",
"String",
"baseUri",
",",
"long",
"connectTimeout",
",",
"TimeUnit",
"timeUnit",
")",
"throws",
"IOException",
"{",
"OkHttpClient",
"client",
"=",
"new",
"OkHttpClient",
"(",
")",
";",
"client",
".",
"setC... | Gets the api version of the given backend
@param baseUri the backend services api url
@param connectTimeout connection timeout
@param timeUnit connection timeout unit
@return the Api version
@throws IOException if an error occurs | [
"Gets",
"the",
"api",
"version",
"of",
"the",
"given",
"backend"
] | train | https://github.com/MythTV-Clients/MythTV-Service-API/blob/7951954f767515550738f1b064d6c97099e6df15/src/main/java/org/mythtv/services/api/ServerVersionQuery.java#L43-L47 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RuleBasedBreakIterator.java | RuleBasedBreakIterator.compileRules | public static void compileRules(String rules, OutputStream ruleBinary) throws IOException {
RBBIRuleBuilder.compileRules(rules, ruleBinary);
} | java | public static void compileRules(String rules, OutputStream ruleBinary) throws IOException {
RBBIRuleBuilder.compileRules(rules, ruleBinary);
} | [
"public",
"static",
"void",
"compileRules",
"(",
"String",
"rules",
",",
"OutputStream",
"ruleBinary",
")",
"throws",
"IOException",
"{",
"RBBIRuleBuilder",
".",
"compileRules",
"(",
"rules",
",",
"ruleBinary",
")",
";",
"}"
] | Compile a set of source break rules into the binary state tables used
by the break iterator engine. Creating a break iterator from precompiled
rules is much faster than creating one from source rules.
Binary break rules are not guaranteed to be compatible between different
versions of ICU.
@param rules The source form of the break rules
@param ruleBinary An output stream to receive the compiled rules.
@throws IOException If there is an error writing the output.
@see #getInstanceFromCompiledRules(InputStream) | [
"Compile",
"a",
"set",
"of",
"source",
"break",
"rules",
"into",
"the",
"binary",
"state",
"tables",
"used",
"by",
"the",
"break",
"iterator",
"engine",
".",
"Creating",
"a",
"break",
"iterator",
"from",
"precompiled",
"rules",
"is",
"much",
"faster",
"than"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RuleBasedBreakIterator.java#L317-L319 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/IOGroovyMethods.java | IOGroovyMethods.withReader | public static <T> T withReader(Reader reader, @ClosureParams(FirstParam.class) Closure<T> closure) throws IOException {
try {
T result = closure.call(reader);
Reader temp = reader;
reader = null;
temp.close();
return result;
} finally {
closeWithWarning(reader);
}
} | java | public static <T> T withReader(Reader reader, @ClosureParams(FirstParam.class) Closure<T> closure) throws IOException {
try {
T result = closure.call(reader);
Reader temp = reader;
reader = null;
temp.close();
return result;
} finally {
closeWithWarning(reader);
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"withReader",
"(",
"Reader",
"reader",
",",
"@",
"ClosureParams",
"(",
"FirstParam",
".",
"class",
")",
"Closure",
"<",
"T",
">",
"closure",
")",
"throws",
"IOException",
"{",
"try",
"{",
"T",
"result",
"=",
"clo... | Allows this reader to be used within the closure, ensuring that it
is closed before this method returns.
@param reader the reader which is used and then closed
@param closure the closure that the writer is passed into
@return the value returned by the closure
@throws IOException if an IOException occurs.
@since 1.5.2 | [
"Allows",
"this",
"reader",
"to",
"be",
"used",
"within",
"the",
"closure",
"ensuring",
"that",
"it",
"is",
"closed",
"before",
"this",
"method",
"returns",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/IOGroovyMethods.java#L1159-L1171 |
apache/groovy | src/main/java/org/codehaus/groovy/ast/ClassNode.java | ClassNode.getMethod | public MethodNode getMethod(String name, Parameter[] parameters) {
for (MethodNode method : getMethods(name)) {
if (parametersEqual(method.getParameters(), parameters)) {
return method;
}
}
return null;
} | java | public MethodNode getMethod(String name, Parameter[] parameters) {
for (MethodNode method : getMethods(name)) {
if (parametersEqual(method.getParameters(), parameters)) {
return method;
}
}
return null;
} | [
"public",
"MethodNode",
"getMethod",
"(",
"String",
"name",
",",
"Parameter",
"[",
"]",
"parameters",
")",
"{",
"for",
"(",
"MethodNode",
"method",
":",
"getMethods",
"(",
"name",
")",
")",
"{",
"if",
"(",
"parametersEqual",
"(",
"method",
".",
"getParamet... | Finds a method matching the given name and parameters in this class
or any parent class.
@return the method matching the given name and parameters or null | [
"Finds",
"a",
"method",
"matching",
"the",
"given",
"name",
"and",
"parameters",
"in",
"this",
"class",
"or",
"any",
"parent",
"class",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/ast/ClassNode.java#L944-L951 |
pippo-java/pippo | pippo-core/src/main/java/ro/pippo/core/route/Route.java | Route.GET | public static Route GET(String uriPattern, RouteHandler routeHandler) {
return new Route(HttpConstants.Method.GET, uriPattern, routeHandler);
} | java | public static Route GET(String uriPattern, RouteHandler routeHandler) {
return new Route(HttpConstants.Method.GET, uriPattern, routeHandler);
} | [
"public",
"static",
"Route",
"GET",
"(",
"String",
"uriPattern",
",",
"RouteHandler",
"routeHandler",
")",
"{",
"return",
"new",
"Route",
"(",
"HttpConstants",
".",
"Method",
".",
"GET",
",",
"uriPattern",
",",
"routeHandler",
")",
";",
"}"
] | Create a {@code GET} route.
@param uriPattern
@param routeHandler
@return | [
"Create",
"a",
"{",
"@code",
"GET",
"}",
"route",
"."
] | train | https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-core/src/main/java/ro/pippo/core/route/Route.java#L70-L72 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java | TrainingsImpl.deletePrediction | public void deletePrediction(UUID projectId, List<String> ids) {
deletePredictionWithServiceResponseAsync(projectId, ids).toBlocking().single().body();
} | java | public void deletePrediction(UUID projectId, List<String> ids) {
deletePredictionWithServiceResponseAsync(projectId, ids).toBlocking().single().body();
} | [
"public",
"void",
"deletePrediction",
"(",
"UUID",
"projectId",
",",
"List",
"<",
"String",
">",
"ids",
")",
"{",
"deletePredictionWithServiceResponseAsync",
"(",
"projectId",
",",
"ids",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body"... | Delete a set of predicted images and their associated prediction results.
@param projectId The project id
@param ids The prediction ids. Limited to 64
@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 | [
"Delete",
"a",
"set",
"of",
"predicted",
"images",
"and",
"their",
"associated",
"prediction",
"results",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L3086-L3088 |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/Element.java | Element.getElementRef | public ElementRef getElementRef() throws IllegalStateException {
Page p = page;
if(p == null) throw new IllegalStateException("page not set");
PageRef pageRef = p.getPageRef();
String i = getId();
if(i == null) throw new IllegalStateException("page not set so no id generated");
ElementRef er = elementRef;
if(
er == null
// Make sure object still valid
|| !er.getPageRef().equals(pageRef)
|| !er.getId().equals(i)
) {
er = new ElementRef(pageRef, i);
elementRef = er;
}
return er;
} | java | public ElementRef getElementRef() throws IllegalStateException {
Page p = page;
if(p == null) throw new IllegalStateException("page not set");
PageRef pageRef = p.getPageRef();
String i = getId();
if(i == null) throw new IllegalStateException("page not set so no id generated");
ElementRef er = elementRef;
if(
er == null
// Make sure object still valid
|| !er.getPageRef().equals(pageRef)
|| !er.getId().equals(i)
) {
er = new ElementRef(pageRef, i);
elementRef = er;
}
return er;
} | [
"public",
"ElementRef",
"getElementRef",
"(",
")",
"throws",
"IllegalStateException",
"{",
"Page",
"p",
"=",
"page",
";",
"if",
"(",
"p",
"==",
"null",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"page not set\"",
")",
";",
"PageRef",
"pageRef",
"=",
... | Gets an ElementRef for this element.
Must have a page set.
If id has not yet been set, one will be generated.
@throws IllegalStateException if page not set | [
"Gets",
"an",
"ElementRef",
"for",
"this",
"element",
".",
"Must",
"have",
"a",
"page",
"set",
".",
"If",
"id",
"has",
"not",
"yet",
"been",
"set",
"one",
"will",
"be",
"generated",
"."
] | train | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/Element.java#L274-L291 |
Shusshu/Android-RecurrencePicker | library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java | Utils.getNextMidnight | public static long getNextMidnight(Time recycle, long theTime, String tz) {
if (recycle == null) {
recycle = new Time();
}
recycle.timezone = tz;
recycle.set(theTime);
recycle.monthDay++;
recycle.hour = 0;
recycle.minute = 0;
recycle.second = 0;
return recycle.normalize(true);
} | java | public static long getNextMidnight(Time recycle, long theTime, String tz) {
if (recycle == null) {
recycle = new Time();
}
recycle.timezone = tz;
recycle.set(theTime);
recycle.monthDay++;
recycle.hour = 0;
recycle.minute = 0;
recycle.second = 0;
return recycle.normalize(true);
} | [
"public",
"static",
"long",
"getNextMidnight",
"(",
"Time",
"recycle",
",",
"long",
"theTime",
",",
"String",
"tz",
")",
"{",
"if",
"(",
"recycle",
"==",
"null",
")",
"{",
"recycle",
"=",
"new",
"Time",
"(",
")",
";",
"}",
"recycle",
".",
"timezone",
... | Finds and returns the next midnight after "theTime" in milliseconds UTC
@param recycle - Time object to recycle, otherwise null.
@param theTime - Time used for calculations (in UTC)
@param tz The time zone to convert this time to. | [
"Finds",
"and",
"returns",
"the",
"next",
"midnight",
"after",
"theTime",
"in",
"milliseconds",
"UTC"
] | train | https://github.com/Shusshu/Android-RecurrencePicker/blob/4f0ae74482e4d46d57a8fb13b4b7980a8613f4af/library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java#L488-L499 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/TrmMessageFactoryImpl.java | TrmMessageFactoryImpl.createInboundTrmMessage | final TrmMessage createInboundTrmMessage(JsMsgObject jmo, int messageType) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())SibTr.entry(tc, "createInboundTrmMessage " + messageType );
TrmMessage trmMessage = null;
/* Create an instance of the appropriate message subclass */
switch (messageType) {
case TrmMessageType.ROUTE_DATA_INT:
trmMessage = new TrmRouteDataImpl(jmo);
break;
default:
trmMessage = new TrmMessageImpl(jmo);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())SibTr.exit(tc, "createInboundTrmMessage");
return trmMessage;
} | java | final TrmMessage createInboundTrmMessage(JsMsgObject jmo, int messageType) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())SibTr.entry(tc, "createInboundTrmMessage " + messageType );
TrmMessage trmMessage = null;
/* Create an instance of the appropriate message subclass */
switch (messageType) {
case TrmMessageType.ROUTE_DATA_INT:
trmMessage = new TrmRouteDataImpl(jmo);
break;
default:
trmMessage = new TrmMessageImpl(jmo);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())SibTr.exit(tc, "createInboundTrmMessage");
return trmMessage;
} | [
"final",
"TrmMessage",
"createInboundTrmMessage",
"(",
"JsMsgObject",
"jmo",
",",
"int",
"messageType",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
... | Create an instance of the appropriate sub-class, e.g. TrmRouteData if
the inbound message is actually a TRM RouteData Message, for the
given JMO. A TRM Message of unknown type will be returned as a TrmMessage.
@return TrmMessage A TrmMessage of the appropriate subtype | [
"Create",
"an",
"instance",
"of",
"the",
"appropriate",
"sub",
"-",
"class",
"e",
".",
"g",
".",
"TrmRouteData",
"if",
"the",
"inbound",
"message",
"is",
"actually",
"a",
"TRM",
"RouteData",
"Message",
"for",
"the",
"given",
"JMO",
".",
"A",
"TRM",
"Mess... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/TrmMessageFactoryImpl.java#L386-L405 |
vdmeer/skb-java-base | src/main/java/de/vandermeer/skb/base/managers/MessageMgr.java | MessageMgr.createInfoMessage | public static Message5WH createInfoMessage(String what, Object ... obj){
return new Message5WH_Builder().addWhat(FormattingTupleWrapper.create(what, obj)).setType(E_MessageType.INFO).build();
} | java | public static Message5WH createInfoMessage(String what, Object ... obj){
return new Message5WH_Builder().addWhat(FormattingTupleWrapper.create(what, obj)).setType(E_MessageType.INFO).build();
} | [
"public",
"static",
"Message5WH",
"createInfoMessage",
"(",
"String",
"what",
",",
"Object",
"...",
"obj",
")",
"{",
"return",
"new",
"Message5WH_Builder",
"(",
")",
".",
"addWhat",
"(",
"FormattingTupleWrapper",
".",
"create",
"(",
"what",
",",
"obj",
")",
... | Creates a new information message.
@param what the what part of the message (what has happened)
@param obj objects to add to the message
@return new information message | [
"Creates",
"a",
"new",
"information",
"message",
"."
] | train | https://github.com/vdmeer/skb-java-base/blob/6d845bcc482aa9344d016e80c0c3455aeae13a13/src/main/java/de/vandermeer/skb/base/managers/MessageMgr.java#L102-L104 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/base/base_resource.java | base_resource.update_bulk_request | protected static base_responses update_bulk_request(nitro_service service,base_resource resources[]) throws Exception
{
if (!service.isLogin())
service.login();
String id = service.get_sessionid();
Boolean warning = service.get_warning();
String onerror = service.get_onerror();
String request = service.get_payload_formatter().resource_to_string(resources, id, null, warning, onerror);
base_responses result = put_bulk_data(service, request);
return result;
} | java | protected static base_responses update_bulk_request(nitro_service service,base_resource resources[]) throws Exception
{
if (!service.isLogin())
service.login();
String id = service.get_sessionid();
Boolean warning = service.get_warning();
String onerror = service.get_onerror();
String request = service.get_payload_formatter().resource_to_string(resources, id, null, warning, onerror);
base_responses result = put_bulk_data(service, request);
return result;
} | [
"protected",
"static",
"base_responses",
"update_bulk_request",
"(",
"nitro_service",
"service",
",",
"base_resource",
"resources",
"[",
"]",
")",
"throws",
"Exception",
"{",
"if",
"(",
"!",
"service",
".",
"isLogin",
"(",
")",
")",
"service",
".",
"login",
"(... | Use this method to perform an update operation on netscaler resources.
@param service nitro_service object.
@param resources Array of nitro resources to be updated.
@param option options class object
@return status of the operation performed.
@throws Exception Nitro exception is thrown. | [
"Use",
"this",
"method",
"to",
"perform",
"an",
"update",
"operation",
"on",
"netscaler",
"resources",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/base/base_resource.java#L496-L507 |
RestComm/media-core | stun/src/main/java/org/restcomm/media/core/stun/messages/StunMessage.java | StunMessage.performAttributeSpecificActions | private static void performAttributeSpecificActions(StunAttribute attribute, byte[] binMessage, int offset, int msgLen)
throws StunException {
// check finger print CRC
if (attribute instanceof FingerprintAttribute) {
if (!validateFingerprint((FingerprintAttribute) attribute, binMessage, offset, msgLen)) {
// RFC 5389 says that we should ignore bad CRCs rather than
// reply with an error response.
throw new StunException("Wrong value in FINGERPRINT");
}
}
} | java | private static void performAttributeSpecificActions(StunAttribute attribute, byte[] binMessage, int offset, int msgLen)
throws StunException {
// check finger print CRC
if (attribute instanceof FingerprintAttribute) {
if (!validateFingerprint((FingerprintAttribute) attribute, binMessage, offset, msgLen)) {
// RFC 5389 says that we should ignore bad CRCs rather than
// reply with an error response.
throw new StunException("Wrong value in FINGERPRINT");
}
}
} | [
"private",
"static",
"void",
"performAttributeSpecificActions",
"(",
"StunAttribute",
"attribute",
",",
"byte",
"[",
"]",
"binMessage",
",",
"int",
"offset",
",",
"int",
"msgLen",
")",
"throws",
"StunException",
"{",
"// check finger print CRC",
"if",
"(",
"attribut... | Executes actions related specific attributes like asserting proper
fingerprint checksum.
@param attribute
the <tt>StunAttribute</tt> we'd like to process.
@param binMessage
the byte array that the message arrived with.
@param offset
the index where data starts in <tt>binMessage</tt>.
@param msgLen
the number of message bytes in <tt>binMessage</tt>.
@throws StunException
if there's something in the <tt>attribute</tt> that caused us
to discard the whole message (e.g. an invalid checksum or
username) | [
"Executes",
"actions",
"related",
"specific",
"attributes",
"like",
"asserting",
"proper",
"fingerprint",
"checksum",
"."
] | train | https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/stun/src/main/java/org/restcomm/media/core/stun/messages/StunMessage.java#L926-L936 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/ConfigUtils.java | ConfigUtils.getBoolean | public static boolean getBoolean(Config config, String path, boolean def) {
if (config.hasPath(path)) {
return config.getBoolean(path);
}
return def;
} | java | public static boolean getBoolean(Config config, String path, boolean def) {
if (config.hasPath(path)) {
return config.getBoolean(path);
}
return def;
} | [
"public",
"static",
"boolean",
"getBoolean",
"(",
"Config",
"config",
",",
"String",
"path",
",",
"boolean",
"def",
")",
"{",
"if",
"(",
"config",
".",
"hasPath",
"(",
"path",
")",
")",
"{",
"return",
"config",
".",
"getBoolean",
"(",
"path",
")",
";",... | Return boolean value at <code>path</code> if <code>config</code> has path. If not return <code>def</code>
@param config in which the path may be present
@param path key to look for in the config object
@return boolean value at <code>path</code> if <code>config</code> has path. If not return <code>def</code> | [
"Return",
"boolean",
"value",
"at",
"<code",
">",
"path<",
"/",
"code",
">",
"if",
"<code",
">",
"config<",
"/",
"code",
">",
"has",
"path",
".",
"If",
"not",
"return",
"<code",
">",
"def<",
"/",
"code",
">"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ConfigUtils.java#L364-L369 |
RestComm/media-core | rtp/src/main/java/org/restcomm/media/core/rtp/sdp/SdpComparator.java | SdpComparator.negotiateAudio | public RTPFormats negotiateAudio(SessionDescription sdp, RTPFormats formats) {
this.audio.clean();
MediaDescriptorField descriptor = sdp.getAudioDescriptor();
descriptor.getFormats().intersection(formats, this.audio);
return this.audio;
} | java | public RTPFormats negotiateAudio(SessionDescription sdp, RTPFormats formats) {
this.audio.clean();
MediaDescriptorField descriptor = sdp.getAudioDescriptor();
descriptor.getFormats().intersection(formats, this.audio);
return this.audio;
} | [
"public",
"RTPFormats",
"negotiateAudio",
"(",
"SessionDescription",
"sdp",
",",
"RTPFormats",
"formats",
")",
"{",
"this",
".",
"audio",
".",
"clean",
"(",
")",
";",
"MediaDescriptorField",
"descriptor",
"=",
"sdp",
".",
"getAudioDescriptor",
"(",
")",
";",
"... | Negotiates the audio formats to be used in the call.
@param sdp The session description
@param formats The available formats
@return The supported formats. If no formats are supported the returned list will be empty. | [
"Negotiates",
"the",
"audio",
"formats",
"to",
"be",
"used",
"in",
"the",
"call",
"."
] | train | https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/rtp/src/main/java/org/restcomm/media/core/rtp/sdp/SdpComparator.java#L70-L75 |
seancfoley/IPAddress | IPAddress/src/inet.ipaddr/inet/ipaddr/ipv4/IPv4Address.java | IPv4Address.toNormalizedString | public static String toNormalizedString(IPv4AddressNetwork network, SegmentValueProvider lowerValueProvider, SegmentValueProvider upperValueProvider, Integer prefixLength) {
return toNormalizedString(network.getPrefixConfiguration(), lowerValueProvider, upperValueProvider, prefixLength, SEGMENT_COUNT, BYTES_PER_SEGMENT, BITS_PER_SEGMENT, MAX_VALUE_PER_SEGMENT, SEGMENT_SEPARATOR, DEFAULT_TEXTUAL_RADIX, null);
} | java | public static String toNormalizedString(IPv4AddressNetwork network, SegmentValueProvider lowerValueProvider, SegmentValueProvider upperValueProvider, Integer prefixLength) {
return toNormalizedString(network.getPrefixConfiguration(), lowerValueProvider, upperValueProvider, prefixLength, SEGMENT_COUNT, BYTES_PER_SEGMENT, BITS_PER_SEGMENT, MAX_VALUE_PER_SEGMENT, SEGMENT_SEPARATOR, DEFAULT_TEXTUAL_RADIX, null);
} | [
"public",
"static",
"String",
"toNormalizedString",
"(",
"IPv4AddressNetwork",
"network",
",",
"SegmentValueProvider",
"lowerValueProvider",
",",
"SegmentValueProvider",
"upperValueProvider",
",",
"Integer",
"prefixLength",
")",
"{",
"return",
"toNormalizedString",
"(",
"ne... | Creates the normalized string for an address without having to create the address objects first.
@param lowerValueProvider
@param upperValueProvider
@param prefixLength
@param network use {@link #defaultIpv4Network()} if there is no custom network in use
@return | [
"Creates",
"the",
"normalized",
"string",
"for",
"an",
"address",
"without",
"having",
"to",
"create",
"the",
"address",
"objects",
"first",
"."
] | train | https://github.com/seancfoley/IPAddress/blob/90493d0673511d673100c36d020dd93dd870111a/IPAddress/src/inet.ipaddr/inet/ipaddr/ipv4/IPv4Address.java#L976-L978 |
enioka/jqm | jqm-all/jqm-model/src/main/java/com/enioka/jqm/jdbc/Db.java | Db.loadProperties | public static Properties loadProperties(String[] filesToLoad)
{
Properties p = new Properties();
InputStream fis = null;
for (String path : filesToLoad)
{
try
{
fis = Db.class.getClassLoader().getResourceAsStream(path);
if (fis != null)
{
p.load(fis);
jqmlogger.info("A jqm.properties file was found at {}", path);
}
}
catch (IOException e)
{
// We allow no configuration files, but not an unreadable configuration file.
throw new DatabaseException("META-INF/jqm.properties file is invalid", e);
}
finally
{
closeQuietly(fis);
}
}
// Overload the datasource name from environment variable if any (tests only).
String dbName = System.getenv("DB");
if (dbName != null)
{
p.put("com.enioka.jqm.jdbc.datasource", "jdbc/" + dbName);
}
// Done
return p;
} | java | public static Properties loadProperties(String[] filesToLoad)
{
Properties p = new Properties();
InputStream fis = null;
for (String path : filesToLoad)
{
try
{
fis = Db.class.getClassLoader().getResourceAsStream(path);
if (fis != null)
{
p.load(fis);
jqmlogger.info("A jqm.properties file was found at {}", path);
}
}
catch (IOException e)
{
// We allow no configuration files, but not an unreadable configuration file.
throw new DatabaseException("META-INF/jqm.properties file is invalid", e);
}
finally
{
closeQuietly(fis);
}
}
// Overload the datasource name from environment variable if any (tests only).
String dbName = System.getenv("DB");
if (dbName != null)
{
p.put("com.enioka.jqm.jdbc.datasource", "jdbc/" + dbName);
}
// Done
return p;
} | [
"public",
"static",
"Properties",
"loadProperties",
"(",
"String",
"[",
"]",
"filesToLoad",
")",
"{",
"Properties",
"p",
"=",
"new",
"Properties",
"(",
")",
";",
"InputStream",
"fis",
"=",
"null",
";",
"for",
"(",
"String",
"path",
":",
"filesToLoad",
")",... | Helper method to load a property file from class path.
@param filesToLoad
an array of paths (class path paths) designating where the files may be. All files are loaded, in the order
given. Missing files are silently ignored.
@return a Properties object, which may be empty but not null. | [
"Helper",
"method",
"to",
"load",
"a",
"property",
"file",
"from",
"class",
"path",
"."
] | train | https://github.com/enioka/jqm/blob/391733b8e291404b97c714c3727a241c4a861f98/jqm-all/jqm-model/src/main/java/com/enioka/jqm/jdbc/Db.java#L225-L260 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/xen/xen_health_ssl_core.java | xen_health_ssl_core.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
xen_health_ssl_core_responses result = (xen_health_ssl_core_responses) service.get_payload_formatter().string_to_resource(xen_health_ssl_core_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.xen_health_ssl_core_response_array);
}
xen_health_ssl_core[] result_xen_health_ssl_core = new xen_health_ssl_core[result.xen_health_ssl_core_response_array.length];
for(int i = 0; i < result.xen_health_ssl_core_response_array.length; i++)
{
result_xen_health_ssl_core[i] = result.xen_health_ssl_core_response_array[i].xen_health_ssl_core[0];
}
return result_xen_health_ssl_core;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
xen_health_ssl_core_responses result = (xen_health_ssl_core_responses) service.get_payload_formatter().string_to_resource(xen_health_ssl_core_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.xen_health_ssl_core_response_array);
}
xen_health_ssl_core[] result_xen_health_ssl_core = new xen_health_ssl_core[result.xen_health_ssl_core_response_array.length];
for(int i = 0; i < result.xen_health_ssl_core_response_array.length; i++)
{
result_xen_health_ssl_core[i] = result.xen_health_ssl_core_response_array[i].xen_health_ssl_core[0];
}
return result_xen_health_ssl_core;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"xen_health_ssl_core_responses",
"result",
"=",
"(",
"xen_health_ssl_core_responses",
")",
"service",
".",
"ge... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/xen/xen_health_ssl_core.java#L256-L273 |
klarna/HiveRunner | src/main/java/com/klarna/hiverunner/HiveServerContainer.java | HiveServerContainer.init | public void init(Map<String, String> testConfig, Map<String, String> hiveVars) {
context.init();
HiveConf hiveConf = context.getHiveConf();
// merge test case properties with hive conf before HiveServer is started.
for (Map.Entry<String, String> property : testConfig.entrySet()) {
hiveConf.set(property.getKey(), property.getValue());
}
try {
hiveServer2 = new HiveServer2();
hiveServer2.init(hiveConf);
// Locate the ClIService in the HiveServer2
for (Service service : hiveServer2.getServices()) {
if (service instanceof CLIService) {
client = (CLIService) service;
}
}
Preconditions.checkNotNull(client, "ClIService was not initialized by HiveServer2");
sessionHandle = client.openSession("noUser", "noPassword", null);
SessionState sessionState = client.getSessionManager().getSession(sessionHandle).getSessionState();
currentSessionState = sessionState;
currentSessionState.setHiveVariables(hiveVars);
} catch (Exception e) {
throw new IllegalStateException("Failed to create HiveServer :" + e.getMessage(), e);
}
// Ping hive server before we do anything more with it! If validation
// is switched on, this will fail if metastorage is not set up properly
pingHiveServer();
} | java | public void init(Map<String, String> testConfig, Map<String, String> hiveVars) {
context.init();
HiveConf hiveConf = context.getHiveConf();
// merge test case properties with hive conf before HiveServer is started.
for (Map.Entry<String, String> property : testConfig.entrySet()) {
hiveConf.set(property.getKey(), property.getValue());
}
try {
hiveServer2 = new HiveServer2();
hiveServer2.init(hiveConf);
// Locate the ClIService in the HiveServer2
for (Service service : hiveServer2.getServices()) {
if (service instanceof CLIService) {
client = (CLIService) service;
}
}
Preconditions.checkNotNull(client, "ClIService was not initialized by HiveServer2");
sessionHandle = client.openSession("noUser", "noPassword", null);
SessionState sessionState = client.getSessionManager().getSession(sessionHandle).getSessionState();
currentSessionState = sessionState;
currentSessionState.setHiveVariables(hiveVars);
} catch (Exception e) {
throw new IllegalStateException("Failed to create HiveServer :" + e.getMessage(), e);
}
// Ping hive server before we do anything more with it! If validation
// is switched on, this will fail if metastorage is not set up properly
pingHiveServer();
} | [
"public",
"void",
"init",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"testConfig",
",",
"Map",
"<",
"String",
",",
"String",
">",
"hiveVars",
")",
"{",
"context",
".",
"init",
"(",
")",
";",
"HiveConf",
"hiveConf",
"=",
"context",
".",
"getHiveConf... | Will start the HiveServer.
@param testConfig Specific test case properties. Will be merged with the HiveConf of the context
@param hiveVars HiveVars to pass on to the HiveServer for this session | [
"Will",
"start",
"the",
"HiveServer",
"."
] | train | https://github.com/klarna/HiveRunner/blob/c8899237db6122127f16e3d8a740c1f8657c2ae3/src/main/java/com/klarna/hiverunner/HiveServerContainer.java#L72-L108 |
elki-project/elki | elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/AbstractMTree.java | AbstractMTree.getSortedEntries | protected final List<DoubleIntPair> getSortedEntries(N node, DBID q) {
List<DoubleIntPair> result = new ArrayList<>();
for(int i = 0; i < node.getNumEntries(); i++) {
E entry = node.getEntry(i);
double distance = distance(entry.getRoutingObjectID(), q);
double radius = entry.getCoveringRadius();
double minDist = (radius > distance) ? 0.0 : distance - radius;
result.add(new DoubleIntPair(minDist, i));
}
Collections.sort(result);
return result;
} | java | protected final List<DoubleIntPair> getSortedEntries(N node, DBID q) {
List<DoubleIntPair> result = new ArrayList<>();
for(int i = 0; i < node.getNumEntries(); i++) {
E entry = node.getEntry(i);
double distance = distance(entry.getRoutingObjectID(), q);
double radius = entry.getCoveringRadius();
double minDist = (radius > distance) ? 0.0 : distance - radius;
result.add(new DoubleIntPair(minDist, i));
}
Collections.sort(result);
return result;
} | [
"protected",
"final",
"List",
"<",
"DoubleIntPair",
">",
"getSortedEntries",
"(",
"N",
"node",
",",
"DBID",
"q",
")",
"{",
"List",
"<",
"DoubleIntPair",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";... | Sorts the entries of the specified node according to their minimum distance
to the specified object.
@param node the node
@param q the id of the object
@return a list of the sorted entries | [
"Sorts",
"the",
"entries",
"of",
"the",
"specified",
"node",
"according",
"to",
"their",
"minimum",
"distance",
"to",
"the",
"specified",
"object",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/AbstractMTree.java#L221-L235 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/namenode/CorruptReplicasMap.java | CorruptReplicasMap.removeFromCorruptReplicasMap | boolean removeFromCorruptReplicasMap(Block blk, DatanodeDescriptor datanode) {
Collection<DatanodeDescriptor> datanodes = corruptReplicasMap.get(blk);
if (datanodes==null)
return false;
if (datanodes.remove(datanode)) { // remove the replicas
if (datanodes.isEmpty()) {
// remove the block if there is no more corrupted replicas
corruptReplicasMap.remove(blk);
}
return true;
}
return false;
} | java | boolean removeFromCorruptReplicasMap(Block blk, DatanodeDescriptor datanode) {
Collection<DatanodeDescriptor> datanodes = corruptReplicasMap.get(blk);
if (datanodes==null)
return false;
if (datanodes.remove(datanode)) { // remove the replicas
if (datanodes.isEmpty()) {
// remove the block if there is no more corrupted replicas
corruptReplicasMap.remove(blk);
}
return true;
}
return false;
} | [
"boolean",
"removeFromCorruptReplicasMap",
"(",
"Block",
"blk",
",",
"DatanodeDescriptor",
"datanode",
")",
"{",
"Collection",
"<",
"DatanodeDescriptor",
">",
"datanodes",
"=",
"corruptReplicasMap",
".",
"get",
"(",
"blk",
")",
";",
"if",
"(",
"datanodes",
"==",
... | Remove the block at the given datanode from CorruptBlockMap
@param blk block to be removed
@param datanode datanode where the block is located
@return true if the removal is successful;
false if the replica is not in the map | [
"Remove",
"the",
"block",
"at",
"the",
"given",
"datanode",
"from",
"CorruptBlockMap"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/CorruptReplicasMap.java#L87-L99 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/AbstractUserArgumentProcessor.java | AbstractUserArgumentProcessor.fixStructureName | private Structure fixStructureName(Structure s, String file) {
if ( s.getName() != null && (! s.getName().equals("")))
return s;
s.setName(s.getPDBCode());
if ( s.getName() == null || s.getName().equals("")){
File f = new File(file);
s.setName(f.getName());
}
return s;
} | java | private Structure fixStructureName(Structure s, String file) {
if ( s.getName() != null && (! s.getName().equals("")))
return s;
s.setName(s.getPDBCode());
if ( s.getName() == null || s.getName().equals("")){
File f = new File(file);
s.setName(f.getName());
}
return s;
} | [
"private",
"Structure",
"fixStructureName",
"(",
"Structure",
"s",
",",
"String",
"file",
")",
"{",
"if",
"(",
"s",
".",
"getName",
"(",
")",
"!=",
"null",
"&&",
"(",
"!",
"s",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"\"\"",
")",
")",
")",
... | apply a number of rules to fix the name of the structure if it did not get set during loading.
@param s
@param file
@return | [
"apply",
"a",
"number",
"of",
"rules",
"to",
"fix",
"the",
"name",
"of",
"the",
"structure",
"if",
"it",
"did",
"not",
"get",
"set",
"during",
"loading",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/AbstractUserArgumentProcessor.java#L717-L729 |
apache/incubator-gobblin | gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java | MRCompactor.checkAlreadyCompactedBasedOnCompletionFile | private static boolean checkAlreadyCompactedBasedOnCompletionFile(FileSystem fs, Dataset dataset) {
Path filePath = new Path(dataset.outputPath(), MRCompactor.COMPACTION_COMPLETE_FILE_NAME);
try {
return fs.exists(filePath);
} catch (IOException e) {
LOG.error("Failed to verify the existence of file " + filePath, e);
return false;
}
} | java | private static boolean checkAlreadyCompactedBasedOnCompletionFile(FileSystem fs, Dataset dataset) {
Path filePath = new Path(dataset.outputPath(), MRCompactor.COMPACTION_COMPLETE_FILE_NAME);
try {
return fs.exists(filePath);
} catch (IOException e) {
LOG.error("Failed to verify the existence of file " + filePath, e);
return false;
}
} | [
"private",
"static",
"boolean",
"checkAlreadyCompactedBasedOnCompletionFile",
"(",
"FileSystem",
"fs",
",",
"Dataset",
"dataset",
")",
"{",
"Path",
"filePath",
"=",
"new",
"Path",
"(",
"dataset",
".",
"outputPath",
"(",
")",
",",
"MRCompactor",
".",
"COMPACTION_CO... | When completion file strategy is used, a compaction completion means there is a file named
{@link MRCompactor#COMPACTION_COMPLETE_FILE_NAME} in its {@link Dataset#outputPath()}. | [
"When",
"completion",
"file",
"strategy",
"is",
"used",
"a",
"compaction",
"completion",
"means",
"there",
"is",
"a",
"file",
"named",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java#L634-L642 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/javax/el/CompositeELResolver.java | CompositeELResolver.isReadOnly | @Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
context.setPropertyResolved(false);
for (ELResolver resolver : resolvers) {
boolean readOnly = resolver.isReadOnly(context, base, property);
if (context.isPropertyResolved()) {
return readOnly;
}
}
return false;
} | java | @Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
context.setPropertyResolved(false);
for (ELResolver resolver : resolvers) {
boolean readOnly = resolver.isReadOnly(context, base, property);
if (context.isPropertyResolved()) {
return readOnly;
}
}
return false;
} | [
"@",
"Override",
"public",
"boolean",
"isReadOnly",
"(",
"ELContext",
"context",
",",
"Object",
"base",
",",
"Object",
"property",
")",
"{",
"context",
".",
"setPropertyResolved",
"(",
"false",
")",
";",
"for",
"(",
"ELResolver",
"resolver",
":",
"resolvers",
... | For a given base and property, attempts to determine whether a call to
{@link #setValue(ELContext, Object, Object, Object)} will always fail. The result is obtained
by querying all component resolvers. If this resolver handles the given (base, property)
pair, the propertyResolved property of the ELContext object must be set to true by the
resolver, before returning. If this property is not true after this method is called, the
caller should ignore the return value. First, propertyResolved is set to false on the
provided ELContext. Next, for each component resolver in this composite:
<ol>
<li>The isReadOnly() method is called, passing in the provided context, base and property.</li>
<li>If the ELContext's propertyResolved flag is false then iteration continues.</li>
<li>Otherwise, iteration stops and no more component resolvers are considered. The value
returned by isReadOnly() is returned by this method.</li>
</ol>
If none of the component resolvers were able to perform this operation, the value false is
returned and the propertyResolved flag remains set to false. Any exception thrown by
component resolvers during the iteration is propagated to the caller of this method.
@param context
The context of this evaluation.
@param base
The base object to return the most general property type for, or null to enumerate
the set of top-level variables that this resolver can evaluate.
@param property
The property or variable to return the acceptable type for.
@return If the propertyResolved property of ELContext was set to true, then true if the
property is read-only or false if not; otherwise undefined.
@throws NullPointerException
if context is null
@throws PropertyNotFoundException
if base is not null and the specified property does not exist or is not readable.
@throws ELException
if an exception was thrown while performing the property or variable resolution.
The thrown exception must be included as the cause property of this exception, if
available. | [
"For",
"a",
"given",
"base",
"and",
"property",
"attempts",
"to",
"determine",
"whether",
"a",
"call",
"to",
"{",
"@link",
"#setValue",
"(",
"ELContext",
"Object",
"Object",
"Object",
")",
"}",
"will",
"always",
"fail",
".",
"The",
"result",
"is",
"obtaine... | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/javax/el/CompositeELResolver.java#L275-L285 |
dkpro/dkpro-jwpl | de.tudarmstadt.ukp.wikipedia.tutorial/src/main/java/de/tudarmstadt/ukp/wikipedia/tutorial/parser/T6_NestedLists.java | T6_NestedLists.outputNestedList | public static String outputNestedList(NestedList nl, int depth){
String result = "";
if(nl == null)
{
return result; // If null return empty string
}
for(int i = 0; i<depth; i++)
{
result += " "; // insert indentation according to depth
}
if(nl.getClass() == NestedListElement.class){ // If it is a NestedListElement,
// we reached a leaf, return its contents
result += nl.getText();
}else{
result += "---"; // If it is not a NestedListElement, it is a NestedListContainer
// print out all its childs, increment depth
for(NestedList nl2 : ((NestedListContainer)nl).getNestedLists()) {
result += "\n"+outputNestedList(nl2, depth+1);
}
}
return result;
} | java | public static String outputNestedList(NestedList nl, int depth){
String result = "";
if(nl == null)
{
return result; // If null return empty string
}
for(int i = 0; i<depth; i++)
{
result += " "; // insert indentation according to depth
}
if(nl.getClass() == NestedListElement.class){ // If it is a NestedListElement,
// we reached a leaf, return its contents
result += nl.getText();
}else{
result += "---"; // If it is not a NestedListElement, it is a NestedListContainer
// print out all its childs, increment depth
for(NestedList nl2 : ((NestedListContainer)nl).getNestedLists()) {
result += "\n"+outputNestedList(nl2, depth+1);
}
}
return result;
} | [
"public",
"static",
"String",
"outputNestedList",
"(",
"NestedList",
"nl",
",",
"int",
"depth",
")",
"{",
"String",
"result",
"=",
"\"\"",
";",
"if",
"(",
"nl",
"==",
"null",
")",
"{",
"return",
"result",
";",
"// If null return empty string",
"}",
"for",
... | Returns String with all elements of a NestedList
@param nl NestedList
@param depth Current depth of the Nestedlist
@return | [
"Returns",
"String",
"with",
"all",
"elements",
"of",
"a",
"NestedList"
] | train | https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.tutorial/src/main/java/de/tudarmstadt/ukp/wikipedia/tutorial/parser/T6_NestedLists.java#L71-L95 |
telly/groundy | library/src/main/java/com/telly/groundy/GroundyManager.java | GroundyManager.cancelTasks | public static void cancelTasks(final Context context,
Class<? extends GroundyService> groundyServiceClass, final int groupId, final int reason,
final CancelListener cancelListener) {
if (groupId <= 0) {
throw new IllegalStateException("Group id must be greater than zero");
}
new GroundyServiceConnection(context, groundyServiceClass) {
@Override
protected void onGroundyServiceBound(GroundyService.GroundyServiceBinder binder) {
GroundyService.CancelGroupResponse cancelGroupResponse =
binder.cancelTasks(groupId, reason);
if (cancelListener != null) {
cancelListener.onCancelResult(groupId, cancelGroupResponse);
}
}
}.start();
} | java | public static void cancelTasks(final Context context,
Class<? extends GroundyService> groundyServiceClass, final int groupId, final int reason,
final CancelListener cancelListener) {
if (groupId <= 0) {
throw new IllegalStateException("Group id must be greater than zero");
}
new GroundyServiceConnection(context, groundyServiceClass) {
@Override
protected void onGroundyServiceBound(GroundyService.GroundyServiceBinder binder) {
GroundyService.CancelGroupResponse cancelGroupResponse =
binder.cancelTasks(groupId, reason);
if (cancelListener != null) {
cancelListener.onCancelResult(groupId, cancelGroupResponse);
}
}
}.start();
} | [
"public",
"static",
"void",
"cancelTasks",
"(",
"final",
"Context",
"context",
",",
"Class",
"<",
"?",
"extends",
"GroundyService",
">",
"groundyServiceClass",
",",
"final",
"int",
"groupId",
",",
"final",
"int",
"reason",
",",
"final",
"CancelListener",
"cancel... | Cancels all tasks of the specified group w/ the specified reason.
@param context used to interact with the service
@param groupId the group id to cancel
@param cancelListener callback for cancel result | [
"Cancels",
"all",
"tasks",
"of",
"the",
"specified",
"group",
"w",
"/",
"the",
"specified",
"reason",
"."
] | train | https://github.com/telly/groundy/blob/e90baf9901a8be20b348bd1575d5ad782560cec8/library/src/main/java/com/telly/groundy/GroundyManager.java#L123-L139 |
azkaban/azkaban | azkaban-web-server/src/main/java/azkaban/webapp/servlet/ExecutorServlet.java | ExecutorServlet.ajaxFetchExecFlowLogs | private void ajaxFetchExecFlowLogs(final HttpServletRequest req,
final HttpServletResponse resp, final HashMap<String, Object> ret, final User user,
final ExecutableFlow exFlow) throws ServletException {
final long startMs = System.currentTimeMillis();
final Project project = getProjectAjaxByPermission(ret, exFlow.getProjectId(), user, Type.READ);
if (project == null) {
return;
}
final int offset = this.getIntParam(req, "offset");
final int length = this.getIntParam(req, "length");
resp.setCharacterEncoding("utf-8");
try {
final LogData data = this.executorManagerAdapter.getExecutableFlowLog(exFlow, offset, length);
ret.putAll(appendLogData(data, offset));
} catch (final ExecutorManagerException e) {
throw new ServletException(e);
}
/*
* We originally consider leverage Drop Wizard's Timer API {@link com.codahale.metrics.Timer}
* to measure the duration time.
* However, Timer will result in too many accompanying metrics (e.g., min, max, 99th quantile)
* regarding one metrics. We decided to use gauge to do that and monitor how it behaves.
*/
this.webMetrics.setFetchLogLatency(System.currentTimeMillis() - startMs);
} | java | private void ajaxFetchExecFlowLogs(final HttpServletRequest req,
final HttpServletResponse resp, final HashMap<String, Object> ret, final User user,
final ExecutableFlow exFlow) throws ServletException {
final long startMs = System.currentTimeMillis();
final Project project = getProjectAjaxByPermission(ret, exFlow.getProjectId(), user, Type.READ);
if (project == null) {
return;
}
final int offset = this.getIntParam(req, "offset");
final int length = this.getIntParam(req, "length");
resp.setCharacterEncoding("utf-8");
try {
final LogData data = this.executorManagerAdapter.getExecutableFlowLog(exFlow, offset, length);
ret.putAll(appendLogData(data, offset));
} catch (final ExecutorManagerException e) {
throw new ServletException(e);
}
/*
* We originally consider leverage Drop Wizard's Timer API {@link com.codahale.metrics.Timer}
* to measure the duration time.
* However, Timer will result in too many accompanying metrics (e.g., min, max, 99th quantile)
* regarding one metrics. We decided to use gauge to do that and monitor how it behaves.
*/
this.webMetrics.setFetchLogLatency(System.currentTimeMillis() - startMs);
} | [
"private",
"void",
"ajaxFetchExecFlowLogs",
"(",
"final",
"HttpServletRequest",
"req",
",",
"final",
"HttpServletResponse",
"resp",
",",
"final",
"HashMap",
"<",
"String",
",",
"Object",
">",
"ret",
",",
"final",
"User",
"user",
",",
"final",
"ExecutableFlow",
"... | Gets the logs through plain text stream to reduce memory overhead. | [
"Gets",
"the",
"logs",
"through",
"plain",
"text",
"stream",
"to",
"reduce",
"memory",
"overhead",
"."
] | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ExecutorServlet.java#L528-L557 |
OpenTSDB/opentsdb | src/meta/TSMeta.java | TSMeta.getFromStorage | private static Deferred<TSMeta> getFromStorage(final TSDB tsdb,
final byte[] tsuid) {
/**
* Called after executing the GetRequest to parse the meta data.
*/
final class GetCB implements Callback<Deferred<TSMeta>, ArrayList<KeyValue>> {
/**
* @return Null if the meta did not exist or a valid TSMeta object if it
* did.
*/
@Override
public Deferred<TSMeta> call(final ArrayList<KeyValue> row) throws Exception {
if (row == null || row.isEmpty()) {
return Deferred.fromResult(null);
}
long dps = 0;
long last_received = 0;
TSMeta meta = null;
for (KeyValue column : row) {
if (Arrays.equals(COUNTER_QUALIFIER, column.qualifier())) {
dps = Bytes.getLong(column.value());
last_received = column.timestamp() / 1000;
} else if (Arrays.equals(META_QUALIFIER, column.qualifier())) {
meta = JSON.parseToObject(column.value(), TSMeta.class);
}
}
if (meta == null) {
LOG.warn("Found a counter TSMeta column without a meta for TSUID: " +
UniqueId.uidToString(row.get(0).key()));
return Deferred.fromResult(null);
}
meta.total_dps = dps;
meta.last_received = last_received;
return Deferred.fromResult(meta);
}
}
final GetRequest get = new GetRequest(tsdb.metaTable(), tsuid);
get.family(FAMILY);
get.qualifiers(new byte[][] { COUNTER_QUALIFIER, META_QUALIFIER });
return tsdb.getClient().get(get).addCallbackDeferring(new GetCB());
} | java | private static Deferred<TSMeta> getFromStorage(final TSDB tsdb,
final byte[] tsuid) {
/**
* Called after executing the GetRequest to parse the meta data.
*/
final class GetCB implements Callback<Deferred<TSMeta>, ArrayList<KeyValue>> {
/**
* @return Null if the meta did not exist or a valid TSMeta object if it
* did.
*/
@Override
public Deferred<TSMeta> call(final ArrayList<KeyValue> row) throws Exception {
if (row == null || row.isEmpty()) {
return Deferred.fromResult(null);
}
long dps = 0;
long last_received = 0;
TSMeta meta = null;
for (KeyValue column : row) {
if (Arrays.equals(COUNTER_QUALIFIER, column.qualifier())) {
dps = Bytes.getLong(column.value());
last_received = column.timestamp() / 1000;
} else if (Arrays.equals(META_QUALIFIER, column.qualifier())) {
meta = JSON.parseToObject(column.value(), TSMeta.class);
}
}
if (meta == null) {
LOG.warn("Found a counter TSMeta column without a meta for TSUID: " +
UniqueId.uidToString(row.get(0).key()));
return Deferred.fromResult(null);
}
meta.total_dps = dps;
meta.last_received = last_received;
return Deferred.fromResult(meta);
}
}
final GetRequest get = new GetRequest(tsdb.metaTable(), tsuid);
get.family(FAMILY);
get.qualifiers(new byte[][] { COUNTER_QUALIFIER, META_QUALIFIER });
return tsdb.getClient().get(get).addCallbackDeferring(new GetCB());
} | [
"private",
"static",
"Deferred",
"<",
"TSMeta",
">",
"getFromStorage",
"(",
"final",
"TSDB",
"tsdb",
",",
"final",
"byte",
"[",
"]",
"tsuid",
")",
"{",
"/**\n * Called after executing the GetRequest to parse the meta data.\n */",
"final",
"class",
"GetCB",
"impl... | Attempts to fetch the timeseries meta data from storage.
This method will fetch the {@code counter} and {@code meta} columns.
<b>Note:</b> This method will not load the UIDMeta objects.
@param tsdb The TSDB to use for storage access
@param tsuid The UID of the meta to fetch
@return A TSMeta object if found, null if not
@throws HBaseException if there was an issue fetching
@throws IllegalArgumentException if parsing failed
@throws JSONException if the data was corrupted | [
"Attempts",
"to",
"fetch",
"the",
"timeseries",
"meta",
"data",
"from",
"storage",
".",
"This",
"method",
"will",
"fetch",
"the",
"{"
] | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/meta/TSMeta.java#L695-L743 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/rules/closure/support/Minimum.java | Minimum.call | public Object call(Object comparable1, Object comparable2) {
int result = COMPARATOR.compare(comparable1,
comparable2);
if (result < 0) {
return comparable1;
}
else if (result > 0) {
return comparable2;
}
return comparable1;
} | java | public Object call(Object comparable1, Object comparable2) {
int result = COMPARATOR.compare(comparable1,
comparable2);
if (result < 0) {
return comparable1;
}
else if (result > 0) {
return comparable2;
}
return comparable1;
} | [
"public",
"Object",
"call",
"(",
"Object",
"comparable1",
",",
"Object",
"comparable2",
")",
"{",
"int",
"result",
"=",
"COMPARATOR",
".",
"compare",
"(",
"comparable1",
",",
"comparable2",
")",
";",
"if",
"(",
"result",
"<",
"0",
")",
"{",
"return",
"co... | Return the minimum of two Comparable objects.
@param comparable1
the first comparable
@param comparable2
the second comparable
@return the minimum | [
"Return",
"the",
"minimum",
"of",
"two",
"Comparable",
"objects",
"."
] | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/rules/closure/support/Minimum.java#L53-L63 |
FINRAOS/JTAF-ExtWebDriver | src/main/java/org/finra/jtaf/ewd/session/SessionManager.java | SessionManager.getNewSession | public ExtWebDriver getNewSession(Map<String, String> override) throws Exception {
return getNewSession(override, true);
} | java | public ExtWebDriver getNewSession(Map<String, String> override) throws Exception {
return getNewSession(override, true);
} | [
"public",
"ExtWebDriver",
"getNewSession",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"override",
")",
"throws",
"Exception",
"{",
"return",
"getNewSession",
"(",
"override",
",",
"true",
")",
";",
"}"
] | Create and return a new ExtWebDriver instance. The instance is
constructed with default options, with the provided Map of key/value
pairs overriding the corresponding pairs in the options. This new
ExtWebDriver instance will then become the current session.
@param override
A Map of options to be overridden
@return A new ExtWebDriver instance which is now the current session
@throws Exception | [
"Create",
"and",
"return",
"a",
"new",
"ExtWebDriver",
"instance",
".",
"The",
"instance",
"is",
"constructed",
"with",
"default",
"options",
"with",
"the",
"provided",
"Map",
"of",
"key",
"/",
"value",
"pairs",
"overriding",
"the",
"corresponding",
"pairs",
"... | train | https://github.com/FINRAOS/JTAF-ExtWebDriver/blob/78d646def1bf0904f79b19a81df0241e07f2c73a/src/main/java/org/finra/jtaf/ewd/session/SessionManager.java#L318-L320 |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceInitiator.java | DfuServiceInitiator.setZip | public DfuServiceInitiator setZip(@NonNull final Uri uri) {
return init(uri, null, 0, DfuBaseService.TYPE_AUTO, DfuBaseService.MIME_TYPE_ZIP);
} | java | public DfuServiceInitiator setZip(@NonNull final Uri uri) {
return init(uri, null, 0, DfuBaseService.TYPE_AUTO, DfuBaseService.MIME_TYPE_ZIP);
} | [
"public",
"DfuServiceInitiator",
"setZip",
"(",
"@",
"NonNull",
"final",
"Uri",
"uri",
")",
"{",
"return",
"init",
"(",
"uri",
",",
"null",
",",
"0",
",",
"DfuBaseService",
".",
"TYPE_AUTO",
",",
"DfuBaseService",
".",
"MIME_TYPE_ZIP",
")",
";",
"}"
] | Sets the URI to the Distribution packet (ZIP) or to a ZIP file matching the deprecated naming
convention.
@param uri the URI of the file
@return the builder
@see #setZip(String)
@see #setZip(int) | [
"Sets",
"the",
"URI",
"to",
"the",
"Distribution",
"packet",
"(",
"ZIP",
")",
"or",
"to",
"a",
"ZIP",
"file",
"matching",
"the",
"deprecated",
"naming",
"convention",
"."
] | train | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceInitiator.java#L565-L567 |
derari/cthul | xml/src/main/java/org/cthul/resolve/ResolvingException.java | ResolvingException.againAs | public <T1 extends Throwable, T2 extends Throwable, T3 extends Throwable>
RuntimeException againAs(Class<T1> t1, Class<T2> t2, Class<T3> t3)
throws T1, T2, T3 {
return againAs(t1, t2, t3, NULL_EX);
} | java | public <T1 extends Throwable, T2 extends Throwable, T3 extends Throwable>
RuntimeException againAs(Class<T1> t1, Class<T2> t2, Class<T3> t3)
throws T1, T2, T3 {
return againAs(t1, t2, t3, NULL_EX);
} | [
"public",
"<",
"T1",
"extends",
"Throwable",
",",
"T2",
"extends",
"Throwable",
",",
"T3",
"extends",
"Throwable",
">",
"RuntimeException",
"againAs",
"(",
"Class",
"<",
"T1",
">",
"t1",
",",
"Class",
"<",
"T2",
">",
"t2",
",",
"Class",
"<",
"T3",
">",... | Throws the {@linkplain #getResolvingCause() cause} if it is one of the
specified types, otherwise returns a
{@linkplain #asRuntimeException() runtime exception}.
<p>
Intended to be written as {@code throw e.againAs(IOException.class)}.
@param <T1>
@param <T2>
@param <T3>
@param t1
@param t2
@param t3
@return runtime exception
@throws T1
@throws T2
@throws T3 | [
"Throws",
"the",
"{"
] | train | https://github.com/derari/cthul/blob/74a31e3cb6a94f5f25cc5253d1dbd42e19a17ebc/xml/src/main/java/org/cthul/resolve/ResolvingException.java#L186-L190 |
line/armeria | core/src/main/java/com/linecorp/armeria/internal/annotation/AnnotatedHttpService.java | AnnotatedHttpService.serve0 | private CompletionStage<HttpResponse> serve0(ServiceRequestContext ctx, HttpRequest req) {
final CompletableFuture<AggregatedHttpMessage> f =
aggregationRequired(aggregationStrategy, req) ? req.aggregate()
: CompletableFuture.completedFuture(null);
ctx.setAdditionalResponseHeaders(defaultHttpHeaders);
ctx.setAdditionalResponseTrailers(defaultHttpTrailers);
switch (responseType) {
case HTTP_RESPONSE:
return f.thenApply(
msg -> new ExceptionFilteredHttpResponse(ctx, req, (HttpResponse) invoke(ctx, req, msg),
exceptionHandler));
case COMPLETION_STAGE:
return f.thenCompose(msg -> toCompletionStage(invoke(ctx, req, msg)))
.handle((result, cause) -> cause == null ? convertResponse(ctx, req, null, result,
HttpHeaders.EMPTY_HEADERS)
: exceptionHandler.handleException(ctx, req,
cause));
default:
return f.thenApplyAsync(msg -> convertResponse(ctx, req, null, invoke(ctx, req, msg),
HttpHeaders.EMPTY_HEADERS),
ctx.blockingTaskExecutor());
}
} | java | private CompletionStage<HttpResponse> serve0(ServiceRequestContext ctx, HttpRequest req) {
final CompletableFuture<AggregatedHttpMessage> f =
aggregationRequired(aggregationStrategy, req) ? req.aggregate()
: CompletableFuture.completedFuture(null);
ctx.setAdditionalResponseHeaders(defaultHttpHeaders);
ctx.setAdditionalResponseTrailers(defaultHttpTrailers);
switch (responseType) {
case HTTP_RESPONSE:
return f.thenApply(
msg -> new ExceptionFilteredHttpResponse(ctx, req, (HttpResponse) invoke(ctx, req, msg),
exceptionHandler));
case COMPLETION_STAGE:
return f.thenCompose(msg -> toCompletionStage(invoke(ctx, req, msg)))
.handle((result, cause) -> cause == null ? convertResponse(ctx, req, null, result,
HttpHeaders.EMPTY_HEADERS)
: exceptionHandler.handleException(ctx, req,
cause));
default:
return f.thenApplyAsync(msg -> convertResponse(ctx, req, null, invoke(ctx, req, msg),
HttpHeaders.EMPTY_HEADERS),
ctx.blockingTaskExecutor());
}
} | [
"private",
"CompletionStage",
"<",
"HttpResponse",
">",
"serve0",
"(",
"ServiceRequestContext",
"ctx",
",",
"HttpRequest",
"req",
")",
"{",
"final",
"CompletableFuture",
"<",
"AggregatedHttpMessage",
">",
"f",
"=",
"aggregationRequired",
"(",
"aggregationStrategy",
",... | Executes the service method in different ways regarding its return type and whether the request is
required to be aggregated. If the return type of the method is not a {@link CompletionStage} or
{@link HttpResponse}, it will be executed in the blocking task executor. | [
"Executes",
"the",
"service",
"method",
"in",
"different",
"ways",
"regarding",
"its",
"return",
"type",
"and",
"whether",
"the",
"request",
"is",
"required",
"to",
"be",
"aggregated",
".",
"If",
"the",
"return",
"type",
"of",
"the",
"method",
"is",
"not",
... | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/internal/annotation/AnnotatedHttpService.java#L221-L245 |
apache/incubator-druid | core/src/main/java/org/apache/druid/timeline/SegmentId.java | SegmentId.tryParse | @Nullable
public static SegmentId tryParse(String dataSource, String segmentId)
{
List<SegmentId> possibleParsings = iteratePossibleParsingsWithDataSource(dataSource, segmentId);
return possibleParsings.isEmpty() ? null : possibleParsings.get(0);
} | java | @Nullable
public static SegmentId tryParse(String dataSource, String segmentId)
{
List<SegmentId> possibleParsings = iteratePossibleParsingsWithDataSource(dataSource, segmentId);
return possibleParsings.isEmpty() ? null : possibleParsings.get(0);
} | [
"@",
"Nullable",
"public",
"static",
"SegmentId",
"tryParse",
"(",
"String",
"dataSource",
",",
"String",
"segmentId",
")",
"{",
"List",
"<",
"SegmentId",
">",
"possibleParsings",
"=",
"iteratePossibleParsingsWithDataSource",
"(",
"dataSource",
",",
"segmentId",
")"... | Tries to parse a segment id from the given String representation, or returns null on failure. If returns a non-null
{@code SegmentId} object, calling {@link #toString()} on the latter is guaranteed to return a string equal to the
argument string of the {@code tryParse()} call.
It is possible that this method may incorrectly parse a segment id, for example if the dataSource name in the
segment id contains a DateTime parseable string such as 'datasource_2000-01-01T00:00:00.000Z' and dataSource was
provided as 'datasource'. The desired behavior in this case would be to return null since the identifier does not
actually belong to the provided dataSource but a non-null result would be returned. This is an edge case that would
currently only affect paged select queries with a union dataSource of two similarly-named dataSources as in the
given example.
Another source of ambiguity is the end of a segment id like '_123' - it could always be interpreted either as the
partitionNum of the segment id, or as the end of the version, with the implicit partitionNum of 0. This method
prefers the first iterpretation. To iterate all possible parsings of a segment id, use {@link
#iteratePossibleParsingsWithDataSource}.
@param dataSource the dataSource corresponding to this segment id
@param segmentId segment id
@return a {@link SegmentId} object if the segment id could be parsed, null otherwise | [
"Tries",
"to",
"parse",
"a",
"segment",
"id",
"from",
"the",
"given",
"String",
"representation",
"or",
"returns",
"null",
"on",
"failure",
".",
"If",
"returns",
"a",
"non",
"-",
"null",
"{",
"@code",
"SegmentId",
"}",
"object",
"calling",
"{",
"@link",
... | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/core/src/main/java/org/apache/druid/timeline/SegmentId.java#L119-L124 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/ObjectUtils.java | ObjectUtils.identityToString | @Deprecated
public static void identityToString(final StrBuilder builder, final Object object) {
Validate.notNull(object, "Cannot get the toString of a null identity");
builder.append(object.getClass().getName())
.append('@')
.append(Integer.toHexString(System.identityHashCode(object)));
} | java | @Deprecated
public static void identityToString(final StrBuilder builder, final Object object) {
Validate.notNull(object, "Cannot get the toString of a null identity");
builder.append(object.getClass().getName())
.append('@')
.append(Integer.toHexString(System.identityHashCode(object)));
} | [
"@",
"Deprecated",
"public",
"static",
"void",
"identityToString",
"(",
"final",
"StrBuilder",
"builder",
",",
"final",
"Object",
"object",
")",
"{",
"Validate",
".",
"notNull",
"(",
"object",
",",
"\"Cannot get the toString of a null identity\"",
")",
";",
"builder... | <p>Appends the toString that would be produced by {@code Object}
if a class did not override toString itself. {@code null}
will throw a NullPointerException for either of the two parameters. </p>
<pre>
ObjectUtils.identityToString(builder, "") = builder.append("java.lang.String@1e23"
ObjectUtils.identityToString(builder, Boolean.TRUE) = builder.append("java.lang.Boolean@7fa"
ObjectUtils.identityToString(builder, Boolean.TRUE) = builder.append("java.lang.Boolean@7fa")
</pre>
@param builder the builder to append to
@param object the object to create a toString for
@since 3.2
@deprecated as of 3.6, because StrBuilder was moved to commons-text,
use one of the other {@code identityToString} methods instead | [
"<p",
">",
"Appends",
"the",
"toString",
"that",
"would",
"be",
"produced",
"by",
"{",
"@code",
"Object",
"}",
"if",
"a",
"class",
"did",
"not",
"override",
"toString",
"itself",
".",
"{",
"@code",
"null",
"}",
"will",
"throw",
"a",
"NullPointerException",... | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/ObjectUtils.java#L381-L387 |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/xml/xpath/XPathUtils.java | XPathUtils.evaluateAsNode | public static Node evaluateAsNode(Node node, String xPathExpression, NamespaceContext nsContext) {
Node result = (Node) evaluateExpression(node, xPathExpression, nsContext, XPathConstants.NODE);
if (result == null) {
throw new CitrusRuntimeException("No result for XPath expression: '" + xPathExpression + "'");
}
return result;
} | java | public static Node evaluateAsNode(Node node, String xPathExpression, NamespaceContext nsContext) {
Node result = (Node) evaluateExpression(node, xPathExpression, nsContext, XPathConstants.NODE);
if (result == null) {
throw new CitrusRuntimeException("No result for XPath expression: '" + xPathExpression + "'");
}
return result;
} | [
"public",
"static",
"Node",
"evaluateAsNode",
"(",
"Node",
"node",
",",
"String",
"xPathExpression",
",",
"NamespaceContext",
"nsContext",
")",
"{",
"Node",
"result",
"=",
"(",
"Node",
")",
"evaluateExpression",
"(",
"node",
",",
"xPathExpression",
",",
"nsConte... | Evaluate XPath expression with result type Node.
@param node
@param xPathExpression
@param nsContext
@return | [
"Evaluate",
"XPath",
"expression",
"with",
"result",
"type",
"Node",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/xml/xpath/XPathUtils.java#L181-L189 |
networknt/light-4j | mask/src/main/java/com/networknt/mask/Mask.java | Mask.maskJson | public static String maskJson(String input, String key) {
DocumentContext ctx = JsonPath.parse(input);
return maskJson(ctx, key);
} | java | public static String maskJson(String input, String key) {
DocumentContext ctx = JsonPath.parse(input);
return maskJson(ctx, key);
} | [
"public",
"static",
"String",
"maskJson",
"(",
"String",
"input",
",",
"String",
"key",
")",
"{",
"DocumentContext",
"ctx",
"=",
"JsonPath",
".",
"parse",
"(",
"input",
")",
";",
"return",
"maskJson",
"(",
"ctx",
",",
"key",
")",
";",
"}"
] | Replace values in JSON using json path
@param input String The source of the string that needs to be masked
@param key String The key maps to a list of json path for masking
@return String Masked result | [
"Replace",
"values",
"in",
"JSON",
"using",
"json",
"path"
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/mask/src/main/java/com/networknt/mask/Mask.java#L142-L145 |
evant/binding-collection-adapter | bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/collections/MergeObservableList.java | MergeObservableList.mergeToBackingIndex | public int mergeToBackingIndex(@NonNull ObservableList<? extends T> backingList, int index) {
if (index < 0) {
throw new IndexOutOfBoundsException();
}
int size = 0;
for (int i = 0, listsSize = lists.size(); i < listsSize; i++) {
List<? extends T> list = lists.get(i);
if (backingList == list) {
if (index < list.size()) {
return size + index;
} else {
throw new IndexOutOfBoundsException();
}
}
size += list.size();
}
throw new IllegalArgumentException();
} | java | public int mergeToBackingIndex(@NonNull ObservableList<? extends T> backingList, int index) {
if (index < 0) {
throw new IndexOutOfBoundsException();
}
int size = 0;
for (int i = 0, listsSize = lists.size(); i < listsSize; i++) {
List<? extends T> list = lists.get(i);
if (backingList == list) {
if (index < list.size()) {
return size + index;
} else {
throw new IndexOutOfBoundsException();
}
}
size += list.size();
}
throw new IllegalArgumentException();
} | [
"public",
"int",
"mergeToBackingIndex",
"(",
"@",
"NonNull",
"ObservableList",
"<",
"?",
"extends",
"T",
">",
"backingList",
",",
"int",
"index",
")",
"{",
"if",
"(",
"index",
"<",
"0",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
")",
";",
... | Converts an index into this merge list into an into an index of the given backing list.
@throws IndexOutOfBoundsException for an invalid index.
@throws IllegalArgumentException if the given list is not backing this merge list. | [
"Converts",
"an",
"index",
"into",
"this",
"merge",
"list",
"into",
"an",
"into",
"an",
"index",
"of",
"the",
"given",
"backing",
"list",
"."
] | train | https://github.com/evant/binding-collection-adapter/blob/f669eda0a7002128bb504dcba012c51531f1bedd/bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/collections/MergeObservableList.java#L126-L143 |
primefaces-extensions/core | src/main/java/org/primefaces/extensions/component/sheet/Sheet.java | Sheet.setSubmittedValue | public void setSubmittedValue(final FacesContext context, final String rowKey, final int col, final String value) {
submittedValues.put(new SheetRowColIndex(rowKey, col), value);
} | java | public void setSubmittedValue(final FacesContext context, final String rowKey, final int col, final String value) {
submittedValues.put(new SheetRowColIndex(rowKey, col), value);
} | [
"public",
"void",
"setSubmittedValue",
"(",
"final",
"FacesContext",
"context",
",",
"final",
"String",
"rowKey",
",",
"final",
"int",
"col",
",",
"final",
"String",
"value",
")",
"{",
"submittedValues",
".",
"put",
"(",
"new",
"SheetRowColIndex",
"(",
"rowKey... | Updates a submitted value.
@param row
@param col
@param value | [
"Updates",
"a",
"submitted",
"value",
"."
] | train | https://github.com/primefaces-extensions/core/blob/afdbca591f60f47898e3517e1e939bc2f63d5355/src/main/java/org/primefaces/extensions/component/sheet/Sheet.java#L269-L271 |
grpc/grpc-java | core/src/main/java/io/grpc/internal/Http2Ping.java | Http2Ping.addCallback | public void addCallback(final ClientTransport.PingCallback callback, Executor executor) {
Runnable runnable;
synchronized (this) {
if (!completed) {
callbacks.put(callback, executor);
return;
}
// otherwise, invoke callback immediately (but not while holding lock)
runnable = this.failureCause != null ? asRunnable(callback, failureCause)
: asRunnable(callback, roundTripTimeNanos);
}
doExecute(executor, runnable);
} | java | public void addCallback(final ClientTransport.PingCallback callback, Executor executor) {
Runnable runnable;
synchronized (this) {
if (!completed) {
callbacks.put(callback, executor);
return;
}
// otherwise, invoke callback immediately (but not while holding lock)
runnable = this.failureCause != null ? asRunnable(callback, failureCause)
: asRunnable(callback, roundTripTimeNanos);
}
doExecute(executor, runnable);
} | [
"public",
"void",
"addCallback",
"(",
"final",
"ClientTransport",
".",
"PingCallback",
"callback",
",",
"Executor",
"executor",
")",
"{",
"Runnable",
"runnable",
";",
"synchronized",
"(",
"this",
")",
"{",
"if",
"(",
"!",
"completed",
")",
"{",
"callbacks",
... | Registers a callback that is invoked when the ping operation completes. If this ping operation
is already completed, the callback is invoked immediately.
@param callback the callback to invoke
@param executor the executor to use | [
"Registers",
"a",
"callback",
"that",
"is",
"invoked",
"when",
"the",
"ping",
"operation",
"completes",
".",
"If",
"this",
"ping",
"operation",
"is",
"already",
"completed",
"the",
"callback",
"is",
"invoked",
"immediately",
"."
] | train | https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/core/src/main/java/io/grpc/internal/Http2Ping.java#L93-L105 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/input/colorpicker/CmsSliderBar.java | CmsSliderBar.setLayerColor | public void setLayerColor(String color, int layer) {
switch (layer) {
case COLORBAR_A:
m_colorA.getElement().getStyle().setBackgroundColor(color);
break;
case COLORBAR_B:
m_colorB.getElement().getStyle().setBackgroundColor(color);
break;
case COLORBAR_C:
m_colorC.getElement().getStyle().setBackgroundColor(color);
break;
case COLORBAR_D:
m_colorD.getElement().getStyle().setBackgroundColor(color);
break;
default:
return;
}
} | java | public void setLayerColor(String color, int layer) {
switch (layer) {
case COLORBAR_A:
m_colorA.getElement().getStyle().setBackgroundColor(color);
break;
case COLORBAR_B:
m_colorB.getElement().getStyle().setBackgroundColor(color);
break;
case COLORBAR_C:
m_colorC.getElement().getStyle().setBackgroundColor(color);
break;
case COLORBAR_D:
m_colorD.getElement().getStyle().setBackgroundColor(color);
break;
default:
return;
}
} | [
"public",
"void",
"setLayerColor",
"(",
"String",
"color",
",",
"int",
"layer",
")",
"{",
"switch",
"(",
"layer",
")",
"{",
"case",
"COLORBAR_A",
":",
"m_colorA",
".",
"getElement",
"(",
")",
".",
"getStyle",
"(",
")",
".",
"setBackgroundColor",
"(",
"co... | Sets the color of a particular layer.<p>
@param color Hexadecimal notation of RGB to change the layer's color
@param layer Which layer to affect | [
"Sets",
"the",
"color",
"of",
"a",
"particular",
"layer",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/input/colorpicker/CmsSliderBar.java#L260-L278 |
apereo/cas | support/cas-server-support-ldap-core/src/main/java/org/apereo/cas/util/LdapUtils.java | LdapUtils.newLdaptiveSearchExecutor | public static SearchExecutor newLdaptiveSearchExecutor(final String baseDn, final String filterQuery) {
return newLdaptiveSearchExecutor(baseDn, filterQuery, new ArrayList<>(0));
} | java | public static SearchExecutor newLdaptiveSearchExecutor(final String baseDn, final String filterQuery) {
return newLdaptiveSearchExecutor(baseDn, filterQuery, new ArrayList<>(0));
} | [
"public",
"static",
"SearchExecutor",
"newLdaptiveSearchExecutor",
"(",
"final",
"String",
"baseDn",
",",
"final",
"String",
"filterQuery",
")",
"{",
"return",
"newLdaptiveSearchExecutor",
"(",
"baseDn",
",",
"filterQuery",
",",
"new",
"ArrayList",
"<>",
"(",
"0",
... | New search executor search executor.
@param baseDn the base dn
@param filterQuery the filter query
@return the search executor | [
"New",
"search",
"executor",
"search",
"executor",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-ldap-core/src/main/java/org/apereo/cas/util/LdapUtils.java#L622-L624 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/FieldBuilder.java | FieldBuilder.buildSignature | public void buildSignature(XMLNode node, Content fieldDocTree) {
fieldDocTree.addContent(
writer.getSignature((FieldDoc) fields.get(currentFieldIndex)));
} | java | public void buildSignature(XMLNode node, Content fieldDocTree) {
fieldDocTree.addContent(
writer.getSignature((FieldDoc) fields.get(currentFieldIndex)));
} | [
"public",
"void",
"buildSignature",
"(",
"XMLNode",
"node",
",",
"Content",
"fieldDocTree",
")",
"{",
"fieldDocTree",
".",
"addContent",
"(",
"writer",
".",
"getSignature",
"(",
"(",
"FieldDoc",
")",
"fields",
".",
"get",
"(",
"currentFieldIndex",
")",
")",
... | Build the signature.
@param node the XML element that specifies which components to document
@param fieldDocTree the content tree to which the documentation will be added | [
"Build",
"the",
"signature",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/FieldBuilder.java#L181-L184 |
google/j2objc | jre_emul/Classes/com/google/j2objc/util/ReflectionUtil.java | ReflectionUtil.matchClassNamePrefix | public static boolean matchClassNamePrefix(String actual, String expected) {
return actual.equals(expected) || actual.equals(getCamelCase(expected));
} | java | public static boolean matchClassNamePrefix(String actual, String expected) {
return actual.equals(expected) || actual.equals(getCamelCase(expected));
} | [
"public",
"static",
"boolean",
"matchClassNamePrefix",
"(",
"String",
"actual",
",",
"String",
"expected",
")",
"{",
"return",
"actual",
".",
"equals",
"(",
"expected",
")",
"||",
"actual",
".",
"equals",
"(",
"getCamelCase",
"(",
"expected",
")",
")",
";",
... | When reflection is stripped, the transpiled code uses NSStringFromClass to return the name of a
class. For example, instead of getting something like java.lang.Throwable, we get
JavaLangThrowable.
<p>This method assumes that {@code actual} and {@code expected} contain a class name as prefix.
Firts, it compares directly {@code actual} to {@code expected}; if it fails, then it compares
{@actual} to the cammel case version of {@code expected}. | [
"When",
"reflection",
"is",
"stripped",
"the",
"transpiled",
"code",
"uses",
"NSStringFromClass",
"to",
"return",
"the",
"name",
"of",
"a",
"class",
".",
"For",
"example",
"instead",
"of",
"getting",
"something",
"like",
"java",
".",
"lang",
".",
"Throwable",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/Classes/com/google/j2objc/util/ReflectionUtil.java#L36-L38 |
yanzhenjie/AndServer | api/src/main/java/com/yanzhenjie/andserver/util/DigestUtils.java | DigestUtils.getDigest | private static MessageDigest getDigest(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("Could not find MessageDigest with algorithm \"" + algorithm + "\"", ex);
}
} | java | private static MessageDigest getDigest(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("Could not find MessageDigest with algorithm \"" + algorithm + "\"", ex);
}
} | [
"private",
"static",
"MessageDigest",
"getDigest",
"(",
"String",
"algorithm",
")",
"{",
"try",
"{",
"return",
"MessageDigest",
".",
"getInstance",
"(",
"algorithm",
")",
";",
"}",
"catch",
"(",
"NoSuchAlgorithmException",
"ex",
")",
"{",
"throw",
"new",
"Ille... | Create a new {@link MessageDigest} with the given algorithm. Necessary because {@code MessageDigest} is not
thread-safe. | [
"Create",
"a",
"new",
"{"
] | train | https://github.com/yanzhenjie/AndServer/blob/f95f316cdfa5755d6a3fec3c6a1b5df783b81517/api/src/main/java/com/yanzhenjie/andserver/util/DigestUtils.java#L131-L137 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/text/StrSubstitutor.java | StrSubstitutor.replaceIn | public boolean replaceIn(final StrBuilder source) {
if (source == null) {
return false;
}
return substitute(source, 0, source.length());
} | java | public boolean replaceIn(final StrBuilder source) {
if (source == null) {
return false;
}
return substitute(source, 0, source.length());
} | [
"public",
"boolean",
"replaceIn",
"(",
"final",
"StrBuilder",
"source",
")",
"{",
"if",
"(",
"source",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"return",
"substitute",
"(",
"source",
",",
"0",
",",
"source",
".",
"length",
"(",
")",
")",
... | Replaces all the occurrences of variables within the given source
builder with their matching values from the resolver.
@param source the builder to replace in, updated, null returns zero
@return true if altered | [
"Replaces",
"all",
"the",
"occurrences",
"of",
"variables",
"within",
"the",
"given",
"source",
"builder",
"with",
"their",
"matching",
"values",
"from",
"the",
"resolver",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrSubstitutor.java#L704-L709 |
landawn/AbacusUtil | src/com/landawn/abacus/util/N.java | N.callUninterruptibly | public static <T> T callUninterruptibly(final long timeout, final TimeUnit unit, final Try.BiFunction<Long, TimeUnit, T, InterruptedException> cmd) {
N.checkArgNotNull(unit, "unit");
N.checkArgNotNull(cmd);
boolean interrupted = false;
try {
long remainingNanos = unit.toNanos(timeout);
final long sysNanos = System.nanoTime();
final long end = remainingNanos >= Long.MAX_VALUE - sysNanos ? Long.MAX_VALUE : sysNanos + remainingNanos;
while (true) {
try {
return cmd.apply(remainingNanos, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
interrupted = true;
remainingNanos = end - System.nanoTime();
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
} | java | public static <T> T callUninterruptibly(final long timeout, final TimeUnit unit, final Try.BiFunction<Long, TimeUnit, T, InterruptedException> cmd) {
N.checkArgNotNull(unit, "unit");
N.checkArgNotNull(cmd);
boolean interrupted = false;
try {
long remainingNanos = unit.toNanos(timeout);
final long sysNanos = System.nanoTime();
final long end = remainingNanos >= Long.MAX_VALUE - sysNanos ? Long.MAX_VALUE : sysNanos + remainingNanos;
while (true) {
try {
return cmd.apply(remainingNanos, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
interrupted = true;
remainingNanos = end - System.nanoTime();
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"callUninterruptibly",
"(",
"final",
"long",
"timeout",
",",
"final",
"TimeUnit",
"unit",
",",
"final",
"Try",
".",
"BiFunction",
"<",
"Long",
",",
"TimeUnit",
",",
"T",
",",
"InterruptedException",
">",
"cmd",
")",
... | Note: Copied from Google Guava under Apache License v2.0
<br />
<br />
If a thread is interrupted during such a call, the call continues to block until the result is available or the
timeout elapses, and only then re-interrupts the thread.
@param timeout
@param unit
@param cmd
@return | [
"Note",
":",
"Copied",
"from",
"Google",
"Guava",
"under",
"Apache",
"License",
"v2",
".",
"0",
"<br",
"/",
">",
"<br",
"/",
">"
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/N.java#L28107-L28131 |
aws/aws-sdk-java | aws-java-sdk-iot1clickprojects/src/main/java/com/amazonaws/services/iot1clickprojects/model/UpdatePlacementRequest.java | UpdatePlacementRequest.withAttributes | public UpdatePlacementRequest withAttributes(java.util.Map<String, String> attributes) {
setAttributes(attributes);
return this;
} | java | public UpdatePlacementRequest withAttributes(java.util.Map<String, String> attributes) {
setAttributes(attributes);
return this;
} | [
"public",
"UpdatePlacementRequest",
"withAttributes",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"attributes",
")",
"{",
"setAttributes",
"(",
"attributes",
")",
";",
"return",
"this",
";",
"}"
] | <p>
The user-defined object of attributes used to update the placement. The maximum number of key/value pairs is 50.
</p>
@param attributes
The user-defined object of attributes used to update the placement. The maximum number of key/value pairs
is 50.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"user",
"-",
"defined",
"object",
"of",
"attributes",
"used",
"to",
"update",
"the",
"placement",
".",
"The",
"maximum",
"number",
"of",
"key",
"/",
"value",
"pairs",
"is",
"50",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-iot1clickprojects/src/main/java/com/amazonaws/services/iot1clickprojects/model/UpdatePlacementRequest.java#L165-L168 |
OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.faulttolerance.2.0/src/com/ibm/ws/microprofile/faulttolerance20/state/FaultToleranceStateFactory.java | FaultToleranceStateFactory.createTimeoutState | public TimeoutState createTimeoutState(ScheduledExecutorService executorService, TimeoutPolicy policy, MetricRecorder metricRecorder) {
if (policy == null) {
return new TimeoutStateNullImpl();
} else {
return new TimeoutStateImpl(executorService, policy, metricRecorder);
}
} | java | public TimeoutState createTimeoutState(ScheduledExecutorService executorService, TimeoutPolicy policy, MetricRecorder metricRecorder) {
if (policy == null) {
return new TimeoutStateNullImpl();
} else {
return new TimeoutStateImpl(executorService, policy, metricRecorder);
}
} | [
"public",
"TimeoutState",
"createTimeoutState",
"(",
"ScheduledExecutorService",
"executorService",
",",
"TimeoutPolicy",
"policy",
",",
"MetricRecorder",
"metricRecorder",
")",
"{",
"if",
"(",
"policy",
"==",
"null",
")",
"{",
"return",
"new",
"TimeoutStateNullImpl",
... | Create an object implementing Timeout
@param executorService the executor to use to schedule the timeout callback
@param policy the TimeoutPolicy, may be {@code null}
@return a new TimeoutState | [
"Create",
"an",
"object",
"implementing",
"Timeout"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.faulttolerance.2.0/src/com/ibm/ws/microprofile/faulttolerance20/state/FaultToleranceStateFactory.java#L82-L88 |
OpenLiberty/open-liberty | dev/com.ibm.ws.repository.resolver/src/com/ibm/ws/repository/resolver/internal/kernel/KernelResolverRepository.java | KernelResolverRepository.setPreferredVersion | public void setPreferredVersion(String featureName, String version) {
if (!symbolicNameToFeature.containsKey(featureName)) {
featureName = publicNameToSymbolicName.get(featureName);
}
if (featureName != null) {
try {
Version v = Version.parseVersion(version);
symbolicNameToPreferredVersion.put(featureName, v);
} catch (IllegalArgumentException ex) {
}
}
} | java | public void setPreferredVersion(String featureName, String version) {
if (!symbolicNameToFeature.containsKey(featureName)) {
featureName = publicNameToSymbolicName.get(featureName);
}
if (featureName != null) {
try {
Version v = Version.parseVersion(version);
symbolicNameToPreferredVersion.put(featureName, v);
} catch (IllegalArgumentException ex) {
}
}
} | [
"public",
"void",
"setPreferredVersion",
"(",
"String",
"featureName",
",",
"String",
"version",
")",
"{",
"if",
"(",
"!",
"symbolicNameToFeature",
".",
"containsKey",
"(",
"featureName",
")",
")",
"{",
"featureName",
"=",
"publicNameToSymbolicName",
".",
"get",
... | Set the preferred version of the given feature
<p>
This is for when a user requests that a specific version should be installed.
<p>
If the feature is not in the repository or the version does not parse, this method does nothing.
<p>
When a preferred version is set, {@link #getFeature(String)} will return the preferred version if available, unless another version is already installed.
@param featureName the short or symbolic feature name
@param version the version | [
"Set",
"the",
"preferred",
"version",
"of",
"the",
"given",
"feature",
"<p",
">",
"This",
"is",
"for",
"when",
"a",
"user",
"requests",
"that",
"a",
"specific",
"version",
"should",
"be",
"installed",
".",
"<p",
">",
"If",
"the",
"feature",
"is",
"not",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository.resolver/src/com/ibm/ws/repository/resolver/internal/kernel/KernelResolverRepository.java#L319-L331 |
UrielCh/ovh-java-sdk | ovh-java-sdk-support/src/main/java/net/minidev/ovh/api/ApiOvhSupport.java | ApiOvhSupport.tickets_ticketId_canBeScored_GET | public Boolean tickets_ticketId_canBeScored_GET(Long ticketId) throws IOException {
String qPath = "/support/tickets/{ticketId}/canBeScored";
StringBuilder sb = path(qPath, ticketId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, Boolean.class);
} | java | public Boolean tickets_ticketId_canBeScored_GET(Long ticketId) throws IOException {
String qPath = "/support/tickets/{ticketId}/canBeScored";
StringBuilder sb = path(qPath, ticketId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, Boolean.class);
} | [
"public",
"Boolean",
"tickets_ticketId_canBeScored_GET",
"(",
"Long",
"ticketId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/support/tickets/{ticketId}/canBeScored\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"ticketId",
")",
";"... | Checks whether ticket can be scored
REST: GET /support/tickets/{ticketId}/canBeScored
@param ticketId [required] internal ticket identifier | [
"Checks",
"whether",
"ticket",
"can",
"be",
"scored"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-support/src/main/java/net/minidev/ovh/api/ApiOvhSupport.java#L50-L55 |
alkacon/opencms-core | src/org/opencms/db/CmsDriverManager.java | CmsDriverManager.deleteAllStaticExportPublishedResources | public void deleteAllStaticExportPublishedResources(CmsDbContext dbc, int linkType) throws CmsException {
getProjectDriver(dbc).deleteAllStaticExportPublishedResources(dbc, linkType);
} | java | public void deleteAllStaticExportPublishedResources(CmsDbContext dbc, int linkType) throws CmsException {
getProjectDriver(dbc).deleteAllStaticExportPublishedResources(dbc, linkType);
} | [
"public",
"void",
"deleteAllStaticExportPublishedResources",
"(",
"CmsDbContext",
"dbc",
",",
"int",
"linkType",
")",
"throws",
"CmsException",
"{",
"getProjectDriver",
"(",
"dbc",
")",
".",
"deleteAllStaticExportPublishedResources",
"(",
"dbc",
",",
"linkType",
")",
... | Deletes all entries in the published resource table.<p>
@param dbc the current database context
@param linkType the type of resource deleted (0= non-paramter, 1=parameter)
@throws CmsException if something goes wrong | [
"Deletes",
"all",
"entries",
"in",
"the",
"published",
"resource",
"table",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L2308-L2311 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/query/Criteria.java | Criteria.addNotBetween | public void addNotBetween(Object attribute, Object value1, Object value2)
{
// PAW
// addSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getAlias()));
addSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getUserAlias(attribute)));
} | java | public void addNotBetween(Object attribute, Object value1, Object value2)
{
// PAW
// addSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getAlias()));
addSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getUserAlias(attribute)));
} | [
"public",
"void",
"addNotBetween",
"(",
"Object",
"attribute",
",",
"Object",
"value1",
",",
"Object",
"value2",
")",
"{",
"// PAW\r",
"// addSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getAlias()));\r",
"addSelectionCriteria",
"(",
"ValueCri... | Adds NOT BETWEEN criteria,
customer_id not between 1 and 10
@param attribute The field name to be used
@param value1 The lower boundary
@param value2 The upper boundary | [
"Adds",
"NOT",
"BETWEEN",
"criteria",
"customer_id",
"not",
"between",
"1",
"and",
"10"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/Criteria.java#L750-L755 |
JOML-CI/JOML | src/org/joml/Matrix4x3f.java | Matrix4x3f.rotateTowards | public Matrix4x3f rotateTowards(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) {
return rotateTowards(dirX, dirY, dirZ, upX, upY, upZ, this);
} | java | public Matrix4x3f rotateTowards(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) {
return rotateTowards(dirX, dirY, dirZ, upX, upY, upZ, this);
} | [
"public",
"Matrix4x3f",
"rotateTowards",
"(",
"float",
"dirX",
",",
"float",
"dirY",
",",
"float",
"dirZ",
",",
"float",
"upX",
",",
"float",
"upY",
",",
"float",
"upZ",
")",
"{",
"return",
"rotateTowards",
"(",
"dirX",
",",
"dirY",
",",
"dirZ",
",",
"... | Apply a model transformation to this matrix for a right-handed coordinate system,
that aligns the local <code>+Z</code> axis with <code>(dirX, dirY, dirZ)</code>.
<p>
If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix,
then the new matrix will be <code>M * L</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>M * L * v</code>,
the lookat transformation will be applied first!
<p>
In order to set the matrix to a rotation transformation without post-multiplying it,
use {@link #rotationTowards(float, float, float, float, float, float) rotationTowards()}.
<p>
This method is equivalent to calling: <code>mul(new Matrix4x3f().lookAt(0, 0, 0, -dirX, -dirY, -dirZ, upX, upY, upZ).invert())</code>
@see #rotateTowards(Vector3fc, Vector3fc)
@see #rotationTowards(float, float, float, float, float, float)
@param dirX
the x-coordinate of the direction to rotate towards
@param dirY
the y-coordinate of the direction to rotate towards
@param dirZ
the z-coordinate of the direction to rotate towards
@param upX
the x-coordinate of the up vector
@param upY
the y-coordinate of the up vector
@param upZ
the z-coordinate of the up vector
@return this | [
"Apply",
"a",
"model",
"transformation",
"to",
"this",
"matrix",
"for",
"a",
"right",
"-",
"handed",
"coordinate",
"system",
"that",
"aligns",
"the",
"local",
"<code",
">",
"+",
"Z<",
"/",
"code",
">",
"axis",
"with",
"<code",
">",
"(",
"dirX",
"dirY",
... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4x3f.java#L8679-L8681 |
jhalterman/failsafe | src/main/java/net/jodah/failsafe/internal/util/CircularBitSet.java | CircularBitSet.copyBits | static void copyBits(CircularBitSet left, CircularBitSet right) {
int bitsToCopy = Math.min(left.occupiedBits, right.size);
int index = left.nextIndex - bitsToCopy;
if (index < 0)
index += left.occupiedBits;
for (int i = 0; i < bitsToCopy; i++, index = left.indexAfter(index))
right.setNext(left.bitSet.get(index));
} | java | static void copyBits(CircularBitSet left, CircularBitSet right) {
int bitsToCopy = Math.min(left.occupiedBits, right.size);
int index = left.nextIndex - bitsToCopy;
if (index < 0)
index += left.occupiedBits;
for (int i = 0; i < bitsToCopy; i++, index = left.indexAfter(index))
right.setNext(left.bitSet.get(index));
} | [
"static",
"void",
"copyBits",
"(",
"CircularBitSet",
"left",
",",
"CircularBitSet",
"right",
")",
"{",
"int",
"bitsToCopy",
"=",
"Math",
".",
"min",
"(",
"left",
".",
"occupiedBits",
",",
"right",
".",
"size",
")",
";",
"int",
"index",
"=",
"left",
".",
... | Copies the most recent bits from the {@code left} BitSet to the {@code right} BitSet in order from oldest to
newest. | [
"Copies",
"the",
"most",
"recent",
"bits",
"from",
"the",
"{"
] | train | https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/internal/util/CircularBitSet.java#L52-L59 |
fernandospr/javapns-jdk16 | src/main/java/javapns/communication/KeystoreManager.java | KeystoreManager.loadKeystore | static KeyStore loadKeystore(AppleServer server, Object keystore) throws KeystoreException {
return loadKeystore(server, keystore, false);
} | java | static KeyStore loadKeystore(AppleServer server, Object keystore) throws KeystoreException {
return loadKeystore(server, keystore, false);
} | [
"static",
"KeyStore",
"loadKeystore",
"(",
"AppleServer",
"server",
",",
"Object",
"keystore",
")",
"throws",
"KeystoreException",
"{",
"return",
"loadKeystore",
"(",
"server",
",",
"keystore",
",",
"false",
")",
";",
"}"
] | Loads a keystore.
@param server the server the keystore is intended for
@param keystore a keystore containing your private key and the certificate signed by Apple (File, InputStream, byte[], KeyStore or String for a file path)
@return a loaded keystore
@throws KeystoreException | [
"Loads",
"a",
"keystore",
"."
] | train | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/communication/KeystoreManager.java#L41-L43 |
javalite/activeweb | javalite-async/src/main/java/org/javalite/async/Async.java | Async.sendTextMessage | public void sendTextMessage(String queueName, String text){
sendTextMessage(queueName, text, DeliveryMode.NON_PERSISTENT, 4, 0);
} | java | public void sendTextMessage(String queueName, String text){
sendTextMessage(queueName, text, DeliveryMode.NON_PERSISTENT, 4, 0);
} | [
"public",
"void",
"sendTextMessage",
"(",
"String",
"queueName",
",",
"String",
"text",
")",
"{",
"sendTextMessage",
"(",
"queueName",
",",
"text",
",",
"DeliveryMode",
".",
"NON_PERSISTENT",
",",
"4",
",",
"0",
")",
";",
"}"
] | Sends a non-expiring {@link TextMessage} with average priority.
@param queueName name of queue
@param text body of message | [
"Sends",
"a",
"non",
"-",
"expiring",
"{",
"@link",
"TextMessage",
"}",
"with",
"average",
"priority",
"."
] | train | https://github.com/javalite/activeweb/blob/f25f589da94852b6f5625182360732e0861794a6/javalite-async/src/main/java/org/javalite/async/Async.java#L483-L485 |
OpenLiberty/open-liberty | dev/com.ibm.ws.recoverylog/src/com/ibm/ws/recoverylog/spi/RLSUtils.java | RLSUtils.toHexString | public static String toHexString(byte [] byteSource,int bytes)
{
StringBuffer result = null;
boolean truncated = false;
if (byteSource != null)
{
if (bytes > byteSource.length)
{
// If the number of bytes to display is larger than the available number of
// bytes, then reset the number of bytes to display to be the available
// number of bytes.
bytes = byteSource.length;
}
else if (bytes < byteSource.length)
{
// If we are displaying less bytes than are available then detect this
// 'truncation' condition.
truncated = true;
}
result = new StringBuffer(bytes*2);
for (int i = 0; i < bytes; i++)
{
result.append(_digits.charAt((byteSource[i] >> 4) & 0xf));
result.append(_digits.charAt(byteSource[i] & 0xf));
}
if (truncated)
{
result.append("... (" + bytes + "/" + byteSource.length + ")");
}
else
{
result.append("(" + bytes + ")");
}
}
else
{
result = new StringBuffer("null");
}
return(result.toString());
} | java | public static String toHexString(byte [] byteSource,int bytes)
{
StringBuffer result = null;
boolean truncated = false;
if (byteSource != null)
{
if (bytes > byteSource.length)
{
// If the number of bytes to display is larger than the available number of
// bytes, then reset the number of bytes to display to be the available
// number of bytes.
bytes = byteSource.length;
}
else if (bytes < byteSource.length)
{
// If we are displaying less bytes than are available then detect this
// 'truncation' condition.
truncated = true;
}
result = new StringBuffer(bytes*2);
for (int i = 0; i < bytes; i++)
{
result.append(_digits.charAt((byteSource[i] >> 4) & 0xf));
result.append(_digits.charAt(byteSource[i] & 0xf));
}
if (truncated)
{
result.append("... (" + bytes + "/" + byteSource.length + ")");
}
else
{
result.append("(" + bytes + ")");
}
}
else
{
result = new StringBuffer("null");
}
return(result.toString());
} | [
"public",
"static",
"String",
"toHexString",
"(",
"byte",
"[",
"]",
"byteSource",
",",
"int",
"bytes",
")",
"{",
"StringBuffer",
"result",
"=",
"null",
";",
"boolean",
"truncated",
"=",
"false",
";",
"if",
"(",
"byteSource",
"!=",
"null",
")",
"{",
"if",... | Converts a byte array into a printable hex string.
@param byteSource The byte array source.
@param bytes The number of bytes to display.
@return String printable hex string or "null" | [
"Converts",
"a",
"byte",
"array",
"into",
"a",
"printable",
"hex",
"string",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.recoverylog/src/com/ibm/ws/recoverylog/spi/RLSUtils.java#L105-L148 |
linkhub-sdk/popbill.sdk.java | src/main/java/com/popbill/api/statement/StatementServiceImp.java | StatementServiceImp.sendSMS | @Override
public Response sendSMS(String CorpNum, int ItemCode, String MgtKey,
String Sender, String Receiver, String Contents, String UserID)
throws PopbillException {
if (MgtKey == null || MgtKey.isEmpty())
throw new PopbillException(-99999999, "관리번호가 입력되지 않았습니다.");
ResendRequest request = new ResendRequest();
request.sender = Sender;
request.receiver = Receiver;
request.contents = Contents;
String PostData = toJsonString(request);
return httppost("/Statement/" + ItemCode + "/" + MgtKey, CorpNum, PostData,
UserID, "SMS", Response.class);
} | java | @Override
public Response sendSMS(String CorpNum, int ItemCode, String MgtKey,
String Sender, String Receiver, String Contents, String UserID)
throws PopbillException {
if (MgtKey == null || MgtKey.isEmpty())
throw new PopbillException(-99999999, "관리번호가 입력되지 않았습니다.");
ResendRequest request = new ResendRequest();
request.sender = Sender;
request.receiver = Receiver;
request.contents = Contents;
String PostData = toJsonString(request);
return httppost("/Statement/" + ItemCode + "/" + MgtKey, CorpNum, PostData,
UserID, "SMS", Response.class);
} | [
"@",
"Override",
"public",
"Response",
"sendSMS",
"(",
"String",
"CorpNum",
",",
"int",
"ItemCode",
",",
"String",
"MgtKey",
",",
"String",
"Sender",
",",
"String",
"Receiver",
",",
"String",
"Contents",
",",
"String",
"UserID",
")",
"throws",
"PopbillExceptio... | /* (non-Javadoc)
@see com.popbill.api.StatementService#sendSMS(java.lang.String, java.number.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")"
] | train | https://github.com/linkhub-sdk/popbill.sdk.java/blob/63a341fefe96d60a368776638f3d4c81888238b7/src/main/java/com/popbill/api/statement/StatementServiceImp.java#L283-L300 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/db/xmlutil/XmlInOut.java | XmlInOut.exportXML | public boolean exportXML(BaseTable table, String strFileName)
{
Record record = table.getRecord();
boolean bSuccess = true;
File file = new File(strFileName);
if (file.exists())
file.delete(); // Delete if it exists
else
{
String strPath = file.getParent();
File fileDir = new File(strPath);
fileDir.mkdirs();
}
XmlInOut.enableAllBehaviors(record, false, true); // Disable file behaviors
Document doc = XmlUtilities.exportFileToDoc(table);
try {
OutputStream fileout = new FileOutputStream(strFileName);
Writer out = new OutputStreamWriter(fileout, XmlUtilities.XML_ENCODING); //, MIME2Java.convert("UTF-8"));
Utility.convertDOMToXML(doc, out);
out.close();
fileout.close();
} catch (Exception ex) {
ex.printStackTrace();
bSuccess = false;
}
XmlInOut.enableAllBehaviors(record, true, true);
return bSuccess;
} | java | public boolean exportXML(BaseTable table, String strFileName)
{
Record record = table.getRecord();
boolean bSuccess = true;
File file = new File(strFileName);
if (file.exists())
file.delete(); // Delete if it exists
else
{
String strPath = file.getParent();
File fileDir = new File(strPath);
fileDir.mkdirs();
}
XmlInOut.enableAllBehaviors(record, false, true); // Disable file behaviors
Document doc = XmlUtilities.exportFileToDoc(table);
try {
OutputStream fileout = new FileOutputStream(strFileName);
Writer out = new OutputStreamWriter(fileout, XmlUtilities.XML_ENCODING); //, MIME2Java.convert("UTF-8"));
Utility.convertDOMToXML(doc, out);
out.close();
fileout.close();
} catch (Exception ex) {
ex.printStackTrace();
bSuccess = false;
}
XmlInOut.enableAllBehaviors(record, true, true);
return bSuccess;
} | [
"public",
"boolean",
"exportXML",
"(",
"BaseTable",
"table",
",",
"String",
"strFileName",
")",
"{",
"Record",
"record",
"=",
"table",
".",
"getRecord",
"(",
")",
";",
"boolean",
"bSuccess",
"=",
"true",
";",
"File",
"file",
"=",
"new",
"File",
"(",
"str... | Export this table.
@record The record to export.
@strFileName The destination filename (deleted the old copy if this file exists). | [
"Export",
"this",
"table",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/xmlutil/XmlInOut.java#L213-L245 |
finmath/finmath-lib | src/main/java/net/finmath/marketdata/model/bond/Bond.java | Bond.getAccruedInterest | public double getAccruedInterest(LocalDate date, AnalyticModel model) {
int periodIndex=schedule.getPeriodIndex(date);
Period period=schedule.getPeriod(periodIndex);
DayCountConvention dcc= schedule.getDaycountconvention();
double accruedInterest=getCouponPayment(periodIndex,model)*(dcc.getDaycountFraction(period.getPeriodStart(), date))/schedule.getPeriodLength(periodIndex);
return accruedInterest;
} | java | public double getAccruedInterest(LocalDate date, AnalyticModel model) {
int periodIndex=schedule.getPeriodIndex(date);
Period period=schedule.getPeriod(periodIndex);
DayCountConvention dcc= schedule.getDaycountconvention();
double accruedInterest=getCouponPayment(periodIndex,model)*(dcc.getDaycountFraction(period.getPeriodStart(), date))/schedule.getPeriodLength(periodIndex);
return accruedInterest;
} | [
"public",
"double",
"getAccruedInterest",
"(",
"LocalDate",
"date",
",",
"AnalyticModel",
"model",
")",
"{",
"int",
"periodIndex",
"=",
"schedule",
".",
"getPeriodIndex",
"(",
"date",
")",
";",
"Period",
"period",
"=",
"schedule",
".",
"getPeriod",
"(",
"perio... | Returns the accrued interest of the bond for a given date.
@param date The date of interest.
@param model The model under which the product is valued.
@return The accrued interest. | [
"Returns",
"the",
"accrued",
"interest",
"of",
"the",
"bond",
"for",
"a",
"given",
"date",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/bond/Bond.java#L309-L315 |
openbaton/openbaton-client | sdk/src/main/java/org/openbaton/sdk/api/rest/NetworkServiceRecordAgent.java | NetworkServiceRecordAgent.deletePhysicalNetworkFunctionRecord | @Help(
help = "Delete the PhysicalNetworkFunctionRecord of a NetworkServiceRecord with specific id"
)
public void deletePhysicalNetworkFunctionRecord(final String idNsr, final String idPnfr)
throws SDKException {
String url = idNsr + "/pnfrecords" + "/" + idPnfr;
requestDelete(url);
} | java | @Help(
help = "Delete the PhysicalNetworkFunctionRecord of a NetworkServiceRecord with specific id"
)
public void deletePhysicalNetworkFunctionRecord(final String idNsr, final String idPnfr)
throws SDKException {
String url = idNsr + "/pnfrecords" + "/" + idPnfr;
requestDelete(url);
} | [
"@",
"Help",
"(",
"help",
"=",
"\"Delete the PhysicalNetworkFunctionRecord of a NetworkServiceRecord with specific id\"",
")",
"public",
"void",
"deletePhysicalNetworkFunctionRecord",
"(",
"final",
"String",
"idNsr",
",",
"final",
"String",
"idPnfr",
")",
"throws",
"SDKExcept... | Deletes a specific PhysicalNetworkFunctionRecord.
@param idNsr the ID of the NetworkFunctionRecord containing the PhysicalNetworkFunctionRecord
@param idPnfr the ID of the PhysicalNetworkFunctionRecord to delete
@throws SDKException if the request fails | [
"Deletes",
"a",
"specific",
"PhysicalNetworkFunctionRecord",
"."
] | train | https://github.com/openbaton/openbaton-client/blob/6ca6dd6b62a23940d312213d6fa489d5b636061a/sdk/src/main/java/org/openbaton/sdk/api/rest/NetworkServiceRecordAgent.java#L588-L595 |
cdk/cdk | legacy/src/main/java/org/openscience/cdk/smiles/DeduceBondSystemTool.java | DeduceBondSystemTool.storeRingSystem | private void storeRingSystem(IAtomContainer mol, IRingSet ringSet) {
listOfRings = new ArrayList<Integer[]>(); // this is a list of int arrays
for (int r = 0; r < ringSet.getAtomContainerCount(); ++r) {
IRing ring = (IRing) ringSet.getAtomContainer(r);
Integer[] bondNumbers = new Integer[ring.getBondCount()];
for (int i = 0; i < ring.getBondCount(); ++i)
bondNumbers[i] = mol.indexOf(ring.getBond(i));
listOfRings.add(bondNumbers);
}
} | java | private void storeRingSystem(IAtomContainer mol, IRingSet ringSet) {
listOfRings = new ArrayList<Integer[]>(); // this is a list of int arrays
for (int r = 0; r < ringSet.getAtomContainerCount(); ++r) {
IRing ring = (IRing) ringSet.getAtomContainer(r);
Integer[] bondNumbers = new Integer[ring.getBondCount()];
for (int i = 0; i < ring.getBondCount(); ++i)
bondNumbers[i] = mol.indexOf(ring.getBond(i));
listOfRings.add(bondNumbers);
}
} | [
"private",
"void",
"storeRingSystem",
"(",
"IAtomContainer",
"mol",
",",
"IRingSet",
"ringSet",
")",
"{",
"listOfRings",
"=",
"new",
"ArrayList",
"<",
"Integer",
"[",
"]",
">",
"(",
")",
";",
"// this is a list of int arrays",
"for",
"(",
"int",
"r",
"=",
"0... | Stores an IRingSet corresponding to a AtomContainer using the bond numbers.
@param mol The IAtomContainer for which to store the IRingSet.
@param ringSet The IRingSet to store | [
"Stores",
"an",
"IRingSet",
"corresponding",
"to",
"a",
"AtomContainer",
"using",
"the",
"bond",
"numbers",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/smiles/DeduceBondSystemTool.java#L810-L819 |
pressgang-ccms/PressGangCCMSContentSpecProcessor | src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecProcessor.java | ContentSpecProcessor.doesFileMatch | protected boolean doesFileMatch(final File file, final CSNodeWrapper node) {
if (!node.getNodeType().equals(CommonConstants.CS_NODE_FILE)) return false;
// If the unique id is not from the parser, in which case it will start with a number than use the unique id to compare
if (file.getUniqueId() != null && file.getUniqueId().matches("^\\d.*")) {
return file.getUniqueId().equals(Integer.toString(node.getId()));
} else {
// Since a content spec doesn't contain the database ids for the nodes use what is available to see if the files match
return file.getId().equals(node.getEntityId());
}
} | java | protected boolean doesFileMatch(final File file, final CSNodeWrapper node) {
if (!node.getNodeType().equals(CommonConstants.CS_NODE_FILE)) return false;
// If the unique id is not from the parser, in which case it will start with a number than use the unique id to compare
if (file.getUniqueId() != null && file.getUniqueId().matches("^\\d.*")) {
return file.getUniqueId().equals(Integer.toString(node.getId()));
} else {
// Since a content spec doesn't contain the database ids for the nodes use what is available to see if the files match
return file.getId().equals(node.getEntityId());
}
} | [
"protected",
"boolean",
"doesFileMatch",
"(",
"final",
"File",
"file",
",",
"final",
"CSNodeWrapper",
"node",
")",
"{",
"if",
"(",
"!",
"node",
".",
"getNodeType",
"(",
")",
".",
"equals",
"(",
"CommonConstants",
".",
"CS_NODE_FILE",
")",
")",
"return",
"f... | Checks to see if a ContentSpec topic matches a Content Spec Entity file.
@param file The ContentSpec file object.
@param node The Content Spec Entity file.
@return True if the file is determined to match otherwise false. | [
"Checks",
"to",
"see",
"if",
"a",
"ContentSpec",
"topic",
"matches",
"a",
"Content",
"Spec",
"Entity",
"file",
"."
] | train | https://github.com/pressgang-ccms/PressGangCCMSContentSpecProcessor/blob/85ffac047c4ede0f972364ab1f03f7d61a4de5f1/src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecProcessor.java#L2174-L2184 |
WASdev/ci.maven | liberty-maven-plugin/src/main/java/net/wasdev/wlp/maven/plugins/applications/InstallAppMojoSupport.java | InstallAppMojoSupport.installLooseConfigWar | protected void installLooseConfigWar(MavenProject proj, LooseConfigData config) throws Exception {
// return error if webapp contains java source but it is not compiled yet.
File dir = new File(proj.getBuild().getOutputDirectory());
if (!dir.exists() && containsJavaSource(proj)) {
throw new MojoExecutionException(
MessageFormat.format(messages.getString("error.project.not.compile"), proj.getId()));
}
LooseWarApplication looseWar = new LooseWarApplication(proj, config);
looseWar.addSourceDir(proj);
looseWar.addOutputDir(looseWar.getDocumentRoot(), new File(proj.getBuild().getOutputDirectory()),
"/WEB-INF/classes");
// retrieves dependent library jar files
addEmbeddedLib(looseWar.getDocumentRoot(), proj, looseWar, "/WEB-INF/lib/");
// add Manifest file
File manifestFile = MavenProjectUtil.getManifestFile(proj, "maven-war-plugin");
looseWar.addManifestFile(manifestFile);
} | java | protected void installLooseConfigWar(MavenProject proj, LooseConfigData config) throws Exception {
// return error if webapp contains java source but it is not compiled yet.
File dir = new File(proj.getBuild().getOutputDirectory());
if (!dir.exists() && containsJavaSource(proj)) {
throw new MojoExecutionException(
MessageFormat.format(messages.getString("error.project.not.compile"), proj.getId()));
}
LooseWarApplication looseWar = new LooseWarApplication(proj, config);
looseWar.addSourceDir(proj);
looseWar.addOutputDir(looseWar.getDocumentRoot(), new File(proj.getBuild().getOutputDirectory()),
"/WEB-INF/classes");
// retrieves dependent library jar files
addEmbeddedLib(looseWar.getDocumentRoot(), proj, looseWar, "/WEB-INF/lib/");
// add Manifest file
File manifestFile = MavenProjectUtil.getManifestFile(proj, "maven-war-plugin");
looseWar.addManifestFile(manifestFile);
} | [
"protected",
"void",
"installLooseConfigWar",
"(",
"MavenProject",
"proj",
",",
"LooseConfigData",
"config",
")",
"throws",
"Exception",
"{",
"// return error if webapp contains java source but it is not compiled yet.",
"File",
"dir",
"=",
"new",
"File",
"(",
"proj",
".",
... | install war project artifact using loose application configuration file | [
"install",
"war",
"project",
"artifact",
"using",
"loose",
"application",
"configuration",
"file"
] | train | https://github.com/WASdev/ci.maven/blob/4fcf2d314299a4c02e2c740e4fc99a4f6aba6918/liberty-maven-plugin/src/main/java/net/wasdev/wlp/maven/plugins/applications/InstallAppMojoSupport.java#L83-L102 |
jMetal/jMetal | jmetal-core/src/main/java/org/uma/jmetal/qualityindicator/impl/GenerationalDistance.java | GenerationalDistance.generationalDistance | public double generationalDistance(Front front, Front referenceFront) {
double sum = 0.0;
for (int i = 0; i < front.getNumberOfPoints(); i++) {
sum += Math.pow(FrontUtils.distanceToClosestPoint(front.getPoint(i),
referenceFront), pow);
}
sum = Math.pow(sum, 1.0 / pow);
return sum / front.getNumberOfPoints();
} | java | public double generationalDistance(Front front, Front referenceFront) {
double sum = 0.0;
for (int i = 0; i < front.getNumberOfPoints(); i++) {
sum += Math.pow(FrontUtils.distanceToClosestPoint(front.getPoint(i),
referenceFront), pow);
}
sum = Math.pow(sum, 1.0 / pow);
return sum / front.getNumberOfPoints();
} | [
"public",
"double",
"generationalDistance",
"(",
"Front",
"front",
",",
"Front",
"referenceFront",
")",
"{",
"double",
"sum",
"=",
"0.0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"front",
".",
"getNumberOfPoints",
"(",
")",
";",
"i",
"++",... | Returns the generational distance value for a given front
@param front The front
@param referenceFront The reference pareto front | [
"Returns",
"the",
"generational",
"distance",
"value",
"for",
"a",
"given",
"front"
] | train | https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-core/src/main/java/org/uma/jmetal/qualityindicator/impl/GenerationalDistance.java#L82-L92 |
mangstadt/biweekly | src/main/java/biweekly/component/ICalComponent.java | ICalComponent.addExperimentalProperty | public RawProperty addExperimentalProperty(String name, String value) {
return addExperimentalProperty(name, null, value);
} | java | public RawProperty addExperimentalProperty(String name, String value) {
return addExperimentalProperty(name, null, value);
} | [
"public",
"RawProperty",
"addExperimentalProperty",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"return",
"addExperimentalProperty",
"(",
"name",
",",
"null",
",",
"value",
")",
";",
"}"
] | Adds an experimental property to this component.
@param name the property name (e.g. "X-ALT-DESC")
@param value the property value
@return the property object that was created | [
"Adds",
"an",
"experimental",
"property",
"to",
"this",
"component",
"."
] | train | https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/component/ICalComponent.java#L230-L232 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.resourceOriginalPath | public String resourceOriginalPath(CmsRequestContext context, CmsResource resource) throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
String result = null;
try {
checkOfflineProject(dbc);
result = m_driverManager.getVfsDriver(
dbc).readResource(dbc, CmsProject.ONLINE_PROJECT_ID, resource.getStructureId(), true).getRootPath();
} catch (Exception e) {
dbc.report(
null,
Messages.get().container(
Messages.ERR_TEST_MOVED_RESOURCE_1,
dbc.removeSiteRoot(resource.getRootPath())),
e);
} finally {
dbc.clear();
}
return result;
} | java | public String resourceOriginalPath(CmsRequestContext context, CmsResource resource) throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
String result = null;
try {
checkOfflineProject(dbc);
result = m_driverManager.getVfsDriver(
dbc).readResource(dbc, CmsProject.ONLINE_PROJECT_ID, resource.getStructureId(), true).getRootPath();
} catch (Exception e) {
dbc.report(
null,
Messages.get().container(
Messages.ERR_TEST_MOVED_RESOURCE_1,
dbc.removeSiteRoot(resource.getRootPath())),
e);
} finally {
dbc.clear();
}
return result;
} | [
"public",
"String",
"resourceOriginalPath",
"(",
"CmsRequestContext",
"context",
",",
"CmsResource",
"resource",
")",
"throws",
"CmsException",
"{",
"CmsDbContext",
"dbc",
"=",
"m_dbContextFactory",
".",
"getDbContext",
"(",
"context",
")",
";",
"String",
"result",
... | Returns the original path of given resource, that is the online path for the resource.<p>
If it differs from the offline path, the resource has been moved.<p>
@param context the current request context
@param resource the resource to get the path for
@return the online path
@throws CmsException if something goes wrong
@see org.opencms.workplace.commons.CmsUndoChanges#resourceOriginalPath(CmsObject, String) | [
"Returns",
"the",
"original",
"path",
"of",
"given",
"resource",
"that",
"is",
"the",
"online",
"path",
"for",
"the",
"resource",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L5782-L5801 |
iig-uni-freiburg/SEWOL | ext/org/deckfour/xes/nikefs2/NikeFS2SwapFileManager.java | NikeFS2SwapFileManager.getSwapDir | private static synchronized File getSwapDir() throws IOException {
if(SWAP_DIR == null) {
// create swap directory for this instance
File swapDir = File.createTempFile(SWAP_DIR_PREFIX, SWAP_DIR_SUFFIX, TMP_DIR);
// delete if created
swapDir.delete();
// create lock file
File lockFile = new File(TMP_DIR, swapDir.getName() + LOCK_FILE_SUFFIX);
lockFile.createNewFile();
// delete lock file on exit, to make swap directory
// eligible for cleanup.
lockFile.deleteOnExit();
// make swap directory
swapDir.mkdirs();
// works reliably only on Unix platforms!
swapDir.deleteOnExit();
SWAP_DIR = swapDir;
}
return SWAP_DIR;
} | java | private static synchronized File getSwapDir() throws IOException {
if(SWAP_DIR == null) {
// create swap directory for this instance
File swapDir = File.createTempFile(SWAP_DIR_PREFIX, SWAP_DIR_SUFFIX, TMP_DIR);
// delete if created
swapDir.delete();
// create lock file
File lockFile = new File(TMP_DIR, swapDir.getName() + LOCK_FILE_SUFFIX);
lockFile.createNewFile();
// delete lock file on exit, to make swap directory
// eligible for cleanup.
lockFile.deleteOnExit();
// make swap directory
swapDir.mkdirs();
// works reliably only on Unix platforms!
swapDir.deleteOnExit();
SWAP_DIR = swapDir;
}
return SWAP_DIR;
} | [
"private",
"static",
"synchronized",
"File",
"getSwapDir",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"SWAP_DIR",
"==",
"null",
")",
"{",
"// create swap directory for this instance",
"File",
"swapDir",
"=",
"File",
".",
"createTempFile",
"(",
"SWAP_DIR_PREF... | Retrieves a file handle on the swap directory of this session.
@return The swap directory of this session.
@throws IOException | [
"Retrieves",
"a",
"file",
"handle",
"on",
"the",
"swap",
"directory",
"of",
"this",
"session",
"."
] | train | https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/ext/org/deckfour/xes/nikefs2/NikeFS2SwapFileManager.java#L128-L147 |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/factory/feature/detect/extract/FactoryFeatureExtractor.java | FactoryFeatureExtractor.nonmaxLimiter | public static NonMaxLimiter nonmaxLimiter( @Nullable ConfigExtract config , int maxFeatures ) {
NonMaxSuppression nonmax = nonmax(config);
return new NonMaxLimiter(nonmax,maxFeatures);
} | java | public static NonMaxLimiter nonmaxLimiter( @Nullable ConfigExtract config , int maxFeatures ) {
NonMaxSuppression nonmax = nonmax(config);
return new NonMaxLimiter(nonmax,maxFeatures);
} | [
"public",
"static",
"NonMaxLimiter",
"nonmaxLimiter",
"(",
"@",
"Nullable",
"ConfigExtract",
"config",
",",
"int",
"maxFeatures",
")",
"{",
"NonMaxSuppression",
"nonmax",
"=",
"nonmax",
"(",
"config",
")",
";",
"return",
"new",
"NonMaxLimiter",
"(",
"nonmax",
",... | Creates a non-maximum limiter using the specified configuration
@param config non-maxumum settings
@param maxFeatures maximum allowed features
@return The NonMaxLimiter | [
"Creates",
"a",
"non",
"-",
"maximum",
"limiter",
"using",
"the",
"specified",
"configuration"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/factory/feature/detect/extract/FactoryFeatureExtractor.java#L148-L151 |
paypal/SeLion | server/src/main/java/com/paypal/selion/grid/matchers/MinimalIOSCapabilityMatcher.java | MinimalIOSCapabilityMatcher.isValid | private boolean isValid(Map<String, Object> capability) {
return capability != null && capability.containsKey(BUNDLE_NAME);
} | java | private boolean isValid(Map<String, Object> capability) {
return capability != null && capability.containsKey(BUNDLE_NAME);
} | [
"private",
"boolean",
"isValid",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"capability",
")",
"{",
"return",
"capability",
"!=",
"null",
"&&",
"capability",
".",
"containsKey",
"(",
"BUNDLE_NAME",
")",
";",
"}"
] | /*
Checks the validity of a capability by checking for not-null reference and the availability of CFBundleIdentifier
and CFBundleName keys. | [
"/",
"*",
"Checks",
"the",
"validity",
"of",
"a",
"capability",
"by",
"checking",
"for",
"not",
"-",
"null",
"reference",
"and",
"the",
"availability",
"of",
"CFBundleIdentifier",
"and",
"CFBundleName",
"keys",
"."
] | train | https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/server/src/main/java/com/paypal/selion/grid/matchers/MinimalIOSCapabilityMatcher.java#L37-L39 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/SeaGlassLookAndFeel.java | SeaGlassLookAndFeel.defineTables | private void defineTables(UIDefaults d) {
d.put("tableHeaderBorderEnabled", new Color(0xcad3e0));
d.put("tableHeaderSortIndicator", new Color(0xc02a5481, true));
// Rossi: table headers now blue and glassy.
// I know you discussed this already but I like all interactive components to have the glassy look.
d.put("tableHeaderInteriorBaseEnabled", new Color(0x80a6d2));
String p = "TableHeader";
String c = PAINTER_PREFIX + "TableHeaderPainter";
// d.put(p + ".font", new DerivedFont("defaultFont", 0.846f, null, null));
d.put(p + "[Enabled].ascendingSortIconPainter", new LazyPainter(c, TableHeaderPainter.Which.ASCENDINGSORTICON_ENABLED));
d.put(p + "[Enabled].descendingSortIconPainter", new LazyPainter(c, TableHeaderPainter.Which.DESCENDINGSORTICON_ENABLED));
p = "Table";
d.put(p + ".background", new ColorUIResource(Color.WHITE));
d.put(p + ".alternateRowColor", new ColorUIResource(0xebf5fc));
d.put(p + ".showGrid", Boolean.FALSE);
d.put(p + ".contentMargins", new InsetsUIResource(0, 0, 0, 0));
d.put(p + ".opaque", Boolean.TRUE);
d.put(p + ".intercellSpacing", new DimensionUIResource(0, 0));
d.put(p + ".rendererUseTableColors", Boolean.TRUE);
d.put(p + ".rendererUseUIBorder", Boolean.TRUE);
d.put(p + ".cellNoFocusBorder", new BorderUIResource(BorderFactory.createEmptyBorder(2, 5, 2, 5)));
// TODO Why doesn't ColorUIResource work on these next two?
d.put(p + "[Enabled+Selected].textForeground", Color.WHITE);
d.put(p + "[Enabled+Selected].textBackground", new Color(0x6181a5));
d.put(p + "[Disabled+Selected].textBackground", new Color(0x6181a5));
d.put(p + ".ascendingSortIcon", new SeaGlassIcon("TableHeader", "ascendingSortIconPainter", 8, 7));
d.put(p + ".descendingSortIcon", new SeaGlassIcon("TableHeader", "descendingSortIconPainter", 8, 7));
d.put(p + ".scrollPaneCornerComponent", TableScrollPaneCorner.class);
c = PAINTER_PREFIX + "TableHeaderRendererPainter";
p = "TableHeader:\"TableHeader.renderer\"";
d.put(p + ".contentMargins", new InsetsUIResource(2, 4, 2, 4));
d.put(p + ".States", "Enabled,Pressed,Disabled,Focused,Sorted");
d.put(p + ".Sorted", new TableHeaderRendererSortedState());
d.put(p + "[Disabled].backgroundPainter", new LazyPainter(c, TableHeaderRendererPainter.Which.BACKGROUND_DISABLED));
d.put(p + "[Enabled].backgroundPainter", new LazyPainter(c, TableHeaderRendererPainter.Which.BACKGROUND_ENABLED));
d.put(p + "[Enabled+Focused].backgroundPainter", new LazyPainter(c, TableHeaderRendererPainter.Which.BACKGROUND_ENABLED_FOCUSED));
d.put(p + "[Pressed].backgroundPainter", new LazyPainter(c, TableHeaderRendererPainter.Which.BACKGROUND_PRESSED));
d.put(p + "[Enabled+Sorted].backgroundPainter", new LazyPainter(c, TableHeaderRendererPainter.Which.BACKGROUND_ENABLED_SORTED));
d.put(p + "[Enabled+Focused+Sorted].backgroundPainter",
new LazyPainter(c, TableHeaderRendererPainter.Which.BACKGROUND_ENABLED_FOCUSED_SORTED));
d.put(p + "[Disabled+Sorted].backgroundPainter", new LazyPainter(c, TableHeaderRendererPainter.Which.BACKGROUND_DISABLED_SORTED));
} | java | private void defineTables(UIDefaults d) {
d.put("tableHeaderBorderEnabled", new Color(0xcad3e0));
d.put("tableHeaderSortIndicator", new Color(0xc02a5481, true));
// Rossi: table headers now blue and glassy.
// I know you discussed this already but I like all interactive components to have the glassy look.
d.put("tableHeaderInteriorBaseEnabled", new Color(0x80a6d2));
String p = "TableHeader";
String c = PAINTER_PREFIX + "TableHeaderPainter";
// d.put(p + ".font", new DerivedFont("defaultFont", 0.846f, null, null));
d.put(p + "[Enabled].ascendingSortIconPainter", new LazyPainter(c, TableHeaderPainter.Which.ASCENDINGSORTICON_ENABLED));
d.put(p + "[Enabled].descendingSortIconPainter", new LazyPainter(c, TableHeaderPainter.Which.DESCENDINGSORTICON_ENABLED));
p = "Table";
d.put(p + ".background", new ColorUIResource(Color.WHITE));
d.put(p + ".alternateRowColor", new ColorUIResource(0xebf5fc));
d.put(p + ".showGrid", Boolean.FALSE);
d.put(p + ".contentMargins", new InsetsUIResource(0, 0, 0, 0));
d.put(p + ".opaque", Boolean.TRUE);
d.put(p + ".intercellSpacing", new DimensionUIResource(0, 0));
d.put(p + ".rendererUseTableColors", Boolean.TRUE);
d.put(p + ".rendererUseUIBorder", Boolean.TRUE);
d.put(p + ".cellNoFocusBorder", new BorderUIResource(BorderFactory.createEmptyBorder(2, 5, 2, 5)));
// TODO Why doesn't ColorUIResource work on these next two?
d.put(p + "[Enabled+Selected].textForeground", Color.WHITE);
d.put(p + "[Enabled+Selected].textBackground", new Color(0x6181a5));
d.put(p + "[Disabled+Selected].textBackground", new Color(0x6181a5));
d.put(p + ".ascendingSortIcon", new SeaGlassIcon("TableHeader", "ascendingSortIconPainter", 8, 7));
d.put(p + ".descendingSortIcon", new SeaGlassIcon("TableHeader", "descendingSortIconPainter", 8, 7));
d.put(p + ".scrollPaneCornerComponent", TableScrollPaneCorner.class);
c = PAINTER_PREFIX + "TableHeaderRendererPainter";
p = "TableHeader:\"TableHeader.renderer\"";
d.put(p + ".contentMargins", new InsetsUIResource(2, 4, 2, 4));
d.put(p + ".States", "Enabled,Pressed,Disabled,Focused,Sorted");
d.put(p + ".Sorted", new TableHeaderRendererSortedState());
d.put(p + "[Disabled].backgroundPainter", new LazyPainter(c, TableHeaderRendererPainter.Which.BACKGROUND_DISABLED));
d.put(p + "[Enabled].backgroundPainter", new LazyPainter(c, TableHeaderRendererPainter.Which.BACKGROUND_ENABLED));
d.put(p + "[Enabled+Focused].backgroundPainter", new LazyPainter(c, TableHeaderRendererPainter.Which.BACKGROUND_ENABLED_FOCUSED));
d.put(p + "[Pressed].backgroundPainter", new LazyPainter(c, TableHeaderRendererPainter.Which.BACKGROUND_PRESSED));
d.put(p + "[Enabled+Sorted].backgroundPainter", new LazyPainter(c, TableHeaderRendererPainter.Which.BACKGROUND_ENABLED_SORTED));
d.put(p + "[Enabled+Focused+Sorted].backgroundPainter",
new LazyPainter(c, TableHeaderRendererPainter.Which.BACKGROUND_ENABLED_FOCUSED_SORTED));
d.put(p + "[Disabled+Sorted].backgroundPainter", new LazyPainter(c, TableHeaderRendererPainter.Which.BACKGROUND_DISABLED_SORTED));
} | [
"private",
"void",
"defineTables",
"(",
"UIDefaults",
"d",
")",
"{",
"d",
".",
"put",
"(",
"\"tableHeaderBorderEnabled\"",
",",
"new",
"Color",
"(",
"0xcad3e0",
")",
")",
";",
"d",
".",
"put",
"(",
"\"tableHeaderSortIndicator\"",
",",
"new",
"Color",
"(",
... | Initialize the table UI settings.
@param d the UI defaults map. | [
"Initialize",
"the",
"table",
"UI",
"settings",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/SeaGlassLookAndFeel.java#L2048-L2094 |
Chorus-bdd/Chorus | interpreter/chorus-util/src/main/java/org/chorusbdd/chorus/util/assertion/ChorusAssert.java | ChorusAssert.assertEquals | static public void assertEquals(String message, float expected, float actual, float delta) {
if (Float.compare(expected, actual) == 0)
return;
if (!(Math.abs(expected - actual) <= delta))
failNotEquals(message, new Float(expected), new Float(actual));
} | java | static public void assertEquals(String message, float expected, float actual, float delta) {
if (Float.compare(expected, actual) == 0)
return;
if (!(Math.abs(expected - actual) <= delta))
failNotEquals(message, new Float(expected), new Float(actual));
} | [
"static",
"public",
"void",
"assertEquals",
"(",
"String",
"message",
",",
"float",
"expected",
",",
"float",
"actual",
",",
"float",
"delta",
")",
"{",
"if",
"(",
"Float",
".",
"compare",
"(",
"expected",
",",
"actual",
")",
"==",
"0",
")",
"return",
... | Asserts that two floats are equal concerning a positive delta. If they
are not an AssertionFailedError is thrown with the given message. If the
expected value is infinity then the delta value is ignored. | [
"Asserts",
"that",
"two",
"floats",
"are",
"equal",
"concerning",
"a",
"positive",
"delta",
".",
"If",
"they",
"are",
"not",
"an",
"AssertionFailedError",
"is",
"thrown",
"with",
"the",
"given",
"message",
".",
"If",
"the",
"expected",
"value",
"is",
"infini... | train | https://github.com/Chorus-bdd/Chorus/blob/1eea7ca858876bce821bb49b43fd5b6ba1737997/interpreter/chorus-util/src/main/java/org/chorusbdd/chorus/util/assertion/ChorusAssert.java#L146-L151 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/WebSiteManagementClientImpl.java | WebSiteManagementClientImpl.updateSourceControl | public SourceControlInner updateSourceControl(String sourceControlType, SourceControlInner requestMessage) {
return updateSourceControlWithServiceResponseAsync(sourceControlType, requestMessage).toBlocking().single().body();
} | java | public SourceControlInner updateSourceControl(String sourceControlType, SourceControlInner requestMessage) {
return updateSourceControlWithServiceResponseAsync(sourceControlType, requestMessage).toBlocking().single().body();
} | [
"public",
"SourceControlInner",
"updateSourceControl",
"(",
"String",
"sourceControlType",
",",
"SourceControlInner",
"requestMessage",
")",
"{",
"return",
"updateSourceControlWithServiceResponseAsync",
"(",
"sourceControlType",
",",
"requestMessage",
")",
".",
"toBlocking",
... | Updates source control token.
Updates source control token.
@param sourceControlType Type of source control
@param requestMessage Source control token information
@throws IllegalArgumentException thrown if parameters fail the validation
@throws DefaultErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the SourceControlInner object if successful. | [
"Updates",
"source",
"control",
"token",
".",
"Updates",
"source",
"control",
"token",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/WebSiteManagementClientImpl.java#L849-L851 |
cdk/cdk | descriptor/fingerprint/src/main/java/org/openscience/cdk/similarity/Tanimoto.java | Tanimoto.method1 | public static double method1(ICountFingerprint fp1, ICountFingerprint fp2) {
long xy = 0, x = 0, y = 0;
for (int i = 0; i < fp1.numOfPopulatedbins(); i++) {
int hash = fp1.getHash(i);
for (int j = 0; j < fp2.numOfPopulatedbins(); j++) {
if (hash == fp2.getHash(j)) {
xy += fp1.getCount(i) * fp2.getCount(j);
}
}
x += fp1.getCount(i) * fp1.getCount(i);
}
for (int j = 0; j < fp2.numOfPopulatedbins(); j++) {
y += fp2.getCount(j) * fp2.getCount(j);
}
return ((double) xy / (x + y - xy));
} | java | public static double method1(ICountFingerprint fp1, ICountFingerprint fp2) {
long xy = 0, x = 0, y = 0;
for (int i = 0; i < fp1.numOfPopulatedbins(); i++) {
int hash = fp1.getHash(i);
for (int j = 0; j < fp2.numOfPopulatedbins(); j++) {
if (hash == fp2.getHash(j)) {
xy += fp1.getCount(i) * fp2.getCount(j);
}
}
x += fp1.getCount(i) * fp1.getCount(i);
}
for (int j = 0; j < fp2.numOfPopulatedbins(); j++) {
y += fp2.getCount(j) * fp2.getCount(j);
}
return ((double) xy / (x + y - xy));
} | [
"public",
"static",
"double",
"method1",
"(",
"ICountFingerprint",
"fp1",
",",
"ICountFingerprint",
"fp2",
")",
"{",
"long",
"xy",
"=",
"0",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"fp1",
".",... | Calculates Tanimoto distance for two count fingerprints using method 1.
The feature/count type fingerprints may be of different length.
Uses Tanimoto method from {@cdk.cite Steffen09}.
@param fp1 count fingerprint 1
@param fp2 count fingerprint 2
@return a Tanimoto distance | [
"Calculates",
"Tanimoto",
"distance",
"for",
"two",
"count",
"fingerprints",
"using",
"method",
"1",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/descriptor/fingerprint/src/main/java/org/openscience/cdk/similarity/Tanimoto.java#L195-L210 |
alkacon/opencms-core | src-modules/org/opencms/workplace/list/CmsListDirectAction.java | CmsListDirectAction.resolveOnClic | protected String resolveOnClic(Locale locale) {
String confirmationMessage = getConfirmationMessage().key(locale);
if ((getColumnForTexts() != null) && (getItem().get(getColumnForTexts()) != null)) {
confirmationMessage = new MessageFormat(confirmationMessage, locale).format(
new Object[] {getItem().get(getColumnForTexts())});
}
StringBuffer onClic = new StringBuffer(128);
onClic.append("listAction('");
onClic.append(getListId());
onClic.append("', '");
onClic.append(getId());
onClic.append("', '");
if ((getColumnForTexts() == null)
|| (getItem().get(getColumnForTexts()) == null)
|| confirmationMessage.equals(new MessageFormat(confirmationMessage, locale).format(new Object[] {""}))) {
onClic.append("conf" + getId());
} else {
onClic.append(CmsStringUtil.escapeJavaScript(confirmationMessage));
}
onClic.append("', '");
onClic.append(CmsStringUtil.escapeJavaScript(getItem().getId()));
onClic.append("');");
return onClic.toString();
} | java | protected String resolveOnClic(Locale locale) {
String confirmationMessage = getConfirmationMessage().key(locale);
if ((getColumnForTexts() != null) && (getItem().get(getColumnForTexts()) != null)) {
confirmationMessage = new MessageFormat(confirmationMessage, locale).format(
new Object[] {getItem().get(getColumnForTexts())});
}
StringBuffer onClic = new StringBuffer(128);
onClic.append("listAction('");
onClic.append(getListId());
onClic.append("', '");
onClic.append(getId());
onClic.append("', '");
if ((getColumnForTexts() == null)
|| (getItem().get(getColumnForTexts()) == null)
|| confirmationMessage.equals(new MessageFormat(confirmationMessage, locale).format(new Object[] {""}))) {
onClic.append("conf" + getId());
} else {
onClic.append(CmsStringUtil.escapeJavaScript(confirmationMessage));
}
onClic.append("', '");
onClic.append(CmsStringUtil.escapeJavaScript(getItem().getId()));
onClic.append("');");
return onClic.toString();
} | [
"protected",
"String",
"resolveOnClic",
"(",
"Locale",
"locale",
")",
"{",
"String",
"confirmationMessage",
"=",
"getConfirmationMessage",
"(",
")",
".",
"key",
"(",
"locale",
")",
";",
"if",
"(",
"(",
"getColumnForTexts",
"(",
")",
"!=",
"null",
")",
"&&",
... | Help method to resolve the on clic text to use.<p>
@param locale the used locale
@return the on clic text | [
"Help",
"method",
"to",
"resolve",
"the",
"on",
"clic",
"text",
"to",
"use",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/list/CmsListDirectAction.java#L84-L108 |
rimerosolutions/ant-git-tasks | src/main/java/com/rimerosolutions/ant/git/GitSettings.java | GitSettings.setCredentials | public void setCredentials(String username, String password) {
if (GitTaskUtils.isNullOrBlankString(username) || GitTaskUtils.isNullOrBlankString(password)) {
throw new IllegalArgumentException("Credentials must not be empty.");
}
credentials = new UsernamePasswordCredentialsProvider(username, password);
} | java | public void setCredentials(String username, String password) {
if (GitTaskUtils.isNullOrBlankString(username) || GitTaskUtils.isNullOrBlankString(password)) {
throw new IllegalArgumentException("Credentials must not be empty.");
}
credentials = new UsernamePasswordCredentialsProvider(username, password);
} | [
"public",
"void",
"setCredentials",
"(",
"String",
"username",
",",
"String",
"password",
")",
"{",
"if",
"(",
"GitTaskUtils",
".",
"isNullOrBlankString",
"(",
"username",
")",
"||",
"GitTaskUtils",
".",
"isNullOrBlankString",
"(",
"password",
")",
")",
"{",
"... | Sets the Git credentials
@param username The username
@param password The password | [
"Sets",
"the",
"Git",
"credentials"
] | train | https://github.com/rimerosolutions/ant-git-tasks/blob/bfb32fe68afe6b9dcfd0a5194497d748ef3e8a6f/src/main/java/com/rimerosolutions/ant/git/GitSettings.java#L38-L44 |
jenkinsci/jenkins | core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java | AbstractNodeMonitorDescriptor.markOffline | protected boolean markOffline(Computer c, OfflineCause oc) {
if(isIgnored() || c.isTemporarilyOffline()) return false; // noop
c.setTemporarilyOffline(true, oc);
// notify the admin
MonitorMarkedNodeOffline no = AdministrativeMonitor.all().get(MonitorMarkedNodeOffline.class);
if(no!=null)
no.active = true;
return true;
} | java | protected boolean markOffline(Computer c, OfflineCause oc) {
if(isIgnored() || c.isTemporarilyOffline()) return false; // noop
c.setTemporarilyOffline(true, oc);
// notify the admin
MonitorMarkedNodeOffline no = AdministrativeMonitor.all().get(MonitorMarkedNodeOffline.class);
if(no!=null)
no.active = true;
return true;
} | [
"protected",
"boolean",
"markOffline",
"(",
"Computer",
"c",
",",
"OfflineCause",
"oc",
")",
"{",
"if",
"(",
"isIgnored",
"(",
")",
"||",
"c",
".",
"isTemporarilyOffline",
"(",
")",
")",
"return",
"false",
";",
"// noop",
"c",
".",
"setTemporarilyOffline",
... | Utility method to mark the computer offline for derived classes.
@return true
if the node was actually taken offline by this act (as opposed to us deciding not to do it,
or the computer already marked offline.) | [
"Utility",
"method",
"to",
"mark",
"the",
"computer",
"offline",
"for",
"derived",
"classes",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java#L226-L236 |
VoltDB/voltdb | src/frontend/org/voltdb/planner/ParsedSelectStmt.java | ParsedSelectStmt.rewriteAsMV | ParsedSelectStmt rewriteAsMV(Table view) {
m_groupByColumns.clear();
m_distinctGroupByColumns = null;
m_groupByExpressions.clear();
m_distinctProjectSchema = null;
m_distinct = m_hasAggregateExpression = m_hasComplexGroupby = m_hasComplexAgg = false;
// Resets paramsBy* filters, assuming that it's equivalent to "SELECT * from MV".
// In future, this needs update to accommodate for revised filters (e.g. removes
// one or more filters).
setParamsByIndex(new TreeMap<>());
m_paramsById.clear();
m_paramValues = null;
// m_sql does not need updating
m_tableList.clear();
m_tableList.add(view);
// reset m_tableAliasMap that keeps tracks of sub-queries
m_tableAliasMap.clear();
m_tableAliasListAsJoinOrder.clear();
m_tableAliasListAsJoinOrder.add(view.getTypeName());
m_joinTree = new TableLeafNode(0, null, null, generateStmtTableScan(view));
prepareMVBasedQueryFix(); // update MaterializedViewFixInfo when partition key comes from multiple tables.
return this;
} | java | ParsedSelectStmt rewriteAsMV(Table view) {
m_groupByColumns.clear();
m_distinctGroupByColumns = null;
m_groupByExpressions.clear();
m_distinctProjectSchema = null;
m_distinct = m_hasAggregateExpression = m_hasComplexGroupby = m_hasComplexAgg = false;
// Resets paramsBy* filters, assuming that it's equivalent to "SELECT * from MV".
// In future, this needs update to accommodate for revised filters (e.g. removes
// one or more filters).
setParamsByIndex(new TreeMap<>());
m_paramsById.clear();
m_paramValues = null;
// m_sql does not need updating
m_tableList.clear();
m_tableList.add(view);
// reset m_tableAliasMap that keeps tracks of sub-queries
m_tableAliasMap.clear();
m_tableAliasListAsJoinOrder.clear();
m_tableAliasListAsJoinOrder.add(view.getTypeName());
m_joinTree = new TableLeafNode(0, null, null, generateStmtTableScan(view));
prepareMVBasedQueryFix(); // update MaterializedViewFixInfo when partition key comes from multiple tables.
return this;
} | [
"ParsedSelectStmt",
"rewriteAsMV",
"(",
"Table",
"view",
")",
"{",
"m_groupByColumns",
".",
"clear",
"(",
")",
";",
"m_distinctGroupByColumns",
"=",
"null",
";",
"m_groupByExpressions",
".",
"clear",
"(",
")",
";",
"m_distinctProjectSchema",
"=",
"null",
";",
"m... | Updates miscellaneous fields as part of rewriting as materialized view. | [
"Updates",
"miscellaneous",
"fields",
"as",
"part",
"of",
"rewriting",
"as",
"materialized",
"view",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/planner/ParsedSelectStmt.java#L186-L208 |
Pi4J/pi4j | pi4j-core/src/main/java/com/pi4j/util/NativeLibraryLoader.java | NativeLibraryLoader.loadLibraryFromClasspath | public static void loadLibraryFromClasspath(String path) throws IOException {
Path inputPath = Paths.get(path);
if (!inputPath.isAbsolute()) {
throw new IllegalArgumentException("The path has to be absolute, but found: " + inputPath);
}
String fileNameFull = inputPath.getFileName().toString();
int dotIndex = fileNameFull.indexOf('.');
if (dotIndex < 0 || dotIndex >= fileNameFull.length() - 1) {
throw new IllegalArgumentException("The path has to end with a file name and extension, but found: " + fileNameFull);
}
String fileName = fileNameFull.substring(0, dotIndex);
String extension = fileNameFull.substring(dotIndex);
Path target = Files.createTempFile(fileName, extension);
File targetFile = target.toFile();
targetFile.deleteOnExit();
try (InputStream source = NativeLibraryLoader.class.getResourceAsStream(inputPath.toString())) {
if (source == null) {
throw new FileNotFoundException("File " + inputPath + " was not found in classpath.");
}
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
}
// Finally, load the library
System.load(target.toAbsolutePath().toString());
} | java | public static void loadLibraryFromClasspath(String path) throws IOException {
Path inputPath = Paths.get(path);
if (!inputPath.isAbsolute()) {
throw new IllegalArgumentException("The path has to be absolute, but found: " + inputPath);
}
String fileNameFull = inputPath.getFileName().toString();
int dotIndex = fileNameFull.indexOf('.');
if (dotIndex < 0 || dotIndex >= fileNameFull.length() - 1) {
throw new IllegalArgumentException("The path has to end with a file name and extension, but found: " + fileNameFull);
}
String fileName = fileNameFull.substring(0, dotIndex);
String extension = fileNameFull.substring(dotIndex);
Path target = Files.createTempFile(fileName, extension);
File targetFile = target.toFile();
targetFile.deleteOnExit();
try (InputStream source = NativeLibraryLoader.class.getResourceAsStream(inputPath.toString())) {
if (source == null) {
throw new FileNotFoundException("File " + inputPath + " was not found in classpath.");
}
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
}
// Finally, load the library
System.load(target.toAbsolutePath().toString());
} | [
"public",
"static",
"void",
"loadLibraryFromClasspath",
"(",
"String",
"path",
")",
"throws",
"IOException",
"{",
"Path",
"inputPath",
"=",
"Paths",
".",
"get",
"(",
"path",
")",
";",
"if",
"(",
"!",
"inputPath",
".",
"isAbsolute",
"(",
")",
")",
"{",
"t... | Loads library from classpath
The file from classpath is copied into system temporary directory and then loaded. The temporary file is
deleted after exiting. Method uses String as filename because the pathname is
"abstract", not system-dependent.
@param path
The file path in classpath as an absolute path, e.g. /package/File.ext (could be inside jar)
@throws IOException
If temporary file creation or read/write operation fails
@throws IllegalArgumentException
If source file (param path) does not exist
@throws IllegalArgumentException
If the path is not absolute or if the filename is shorter than three characters (restriction
of {@see File#createTempFile(java.lang.String, java.lang.String)}). | [
"Loads",
"library",
"from",
"classpath"
] | train | https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/util/NativeLibraryLoader.java#L132-L160 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.nested/src/com/ibm/ws/kernel/launch/internal/FrameworkConfigurator.java | FrameworkConfigurator.getFrameworkFactory | public static FrameworkFactory getFrameworkFactory(ClassLoader loader) {
FrameworkFactory factory = null;
Class<?> factoryClass = null;
final String factoryResource = "META-INF/services/org.osgi.framework.launch.FrameworkFactory";
java.io.InputStream inputstream = loader.getResourceAsStream(factoryResource);
if (inputstream == null)
throw new IllegalStateException("Could not find " + factoryResource + " on classpath.");
String factoryClassName = null;
BufferedReader bufferedreader;
try {
bufferedreader = new BufferedReader(new InputStreamReader(inputstream, "UTF-8"));
factoryClassName = KernelUtils.getServiceClass(bufferedreader);
bufferedreader.close();
} catch (Exception e) {
throw new IllegalStateException("Could not read FrameworkFactory service: " + factoryClassName + "; exception=" + e);
}
if (factoryClassName == null)
throw new IllegalStateException("Could not find FrameworkFactory service: " + factoryResource);
try {
factoryClass = loader.loadClass(factoryClassName);
Constructor<?> ctor = factoryClass.getConstructor();
factory = (FrameworkFactory) ctor.newInstance();
} catch (Exception e) {
throw new IllegalStateException("Could not load/instantiate framework factory (" + factoryClassName + ")", e);
} catch (Error e) {
throw new IllegalStateException("Could not load/instantiate framework factory (" + factoryClassName + ")", e);
}
return factory;
} | java | public static FrameworkFactory getFrameworkFactory(ClassLoader loader) {
FrameworkFactory factory = null;
Class<?> factoryClass = null;
final String factoryResource = "META-INF/services/org.osgi.framework.launch.FrameworkFactory";
java.io.InputStream inputstream = loader.getResourceAsStream(factoryResource);
if (inputstream == null)
throw new IllegalStateException("Could not find " + factoryResource + " on classpath.");
String factoryClassName = null;
BufferedReader bufferedreader;
try {
bufferedreader = new BufferedReader(new InputStreamReader(inputstream, "UTF-8"));
factoryClassName = KernelUtils.getServiceClass(bufferedreader);
bufferedreader.close();
} catch (Exception e) {
throw new IllegalStateException("Could not read FrameworkFactory service: " + factoryClassName + "; exception=" + e);
}
if (factoryClassName == null)
throw new IllegalStateException("Could not find FrameworkFactory service: " + factoryResource);
try {
factoryClass = loader.loadClass(factoryClassName);
Constructor<?> ctor = factoryClass.getConstructor();
factory = (FrameworkFactory) ctor.newInstance();
} catch (Exception e) {
throw new IllegalStateException("Could not load/instantiate framework factory (" + factoryClassName + ")", e);
} catch (Error e) {
throw new IllegalStateException("Could not load/instantiate framework factory (" + factoryClassName + ")", e);
}
return factory;
} | [
"public",
"static",
"FrameworkFactory",
"getFrameworkFactory",
"(",
"ClassLoader",
"loader",
")",
"{",
"FrameworkFactory",
"factory",
"=",
"null",
";",
"Class",
"<",
"?",
">",
"factoryClass",
"=",
"null",
";",
"final",
"String",
"factoryResource",
"=",
"\"META-INF... | Use the provided classloader to find the target FrameworkFactory via the
ServiceLoader pattern. If the
"META-INF/services/org.osgi.framework.launch.FrameworkFactory" resource
is found on the classpath, it is read for the first non-comment line
containing a classname. That factory is then used as the service class
for creating a FrameworkFactory instance.
@return non-null instance of the framework factory.
@throws LaunchException
if Factory can not be found or instantiated.
@see {@link KernelUtils#getServiceClass(BufferedReader)} | [
"Use",
"the",
"provided",
"classloader",
"to",
"find",
"the",
"target",
"FrameworkFactory",
"via",
"the",
"ServiceLoader",
"pattern",
".",
"If",
"the",
"META",
"-",
"INF",
"/",
"services",
"/",
"org",
".",
"osgi",
".",
"framework",
".",
"launch",
".",
"Fra... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.nested/src/com/ibm/ws/kernel/launch/internal/FrameworkConfigurator.java#L208-L245 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/RepositoryServiceImpl.java | RepositoryServiceImpl.createRepository | public void createRepository(RepositoryEntry rEntry) throws RepositoryConfigurationException, RepositoryException
{
// Need privileges to manage repository.
SecurityManager security = System.getSecurityManager();
if (security != null)
{
security.checkPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);
}
if (repositoryContainers.containsKey(rEntry.getName()))
{
throw new RepositoryConfigurationException("Repository container " + rEntry.getName() + " already started");
}
final RepositoryContainer repositoryContainer =
new RepositoryContainer(parentContainer, rEntry, addNamespacesPlugins);
// Storing and starting the repository container under
// key=repository_name
try
{
if (repositoryContainers.putIfAbsent(rEntry.getName(), repositoryContainer) == null)
{
SecurityHelper.doPrivilegedAction(new PrivilegedAction<Void>()
{
public Void run()
{
repositoryContainer.start();
return null;
}
});
}
else
{
throw new RepositoryConfigurationException("Repository container " + rEntry.getName() + " already started");
}
}
catch (Throwable t) //NOSONAR
{
repositoryContainers.remove(rEntry.getName());
throw new RepositoryConfigurationException("Repository container " + rEntry.getName() + " was not started.", t);
}
if (!config.getRepositoryConfigurations().contains(rEntry))
{
config.getRepositoryConfigurations().add(rEntry);
}
registerNodeTypes(rEntry.getName());
// turn on Repository ONLINE
ManageableRepository mr =
(ManageableRepository)repositoryContainer.getComponentInstanceOfType(ManageableRepository.class);
mr.setState(ManageableRepository.ONLINE);
} | java | public void createRepository(RepositoryEntry rEntry) throws RepositoryConfigurationException, RepositoryException
{
// Need privileges to manage repository.
SecurityManager security = System.getSecurityManager();
if (security != null)
{
security.checkPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);
}
if (repositoryContainers.containsKey(rEntry.getName()))
{
throw new RepositoryConfigurationException("Repository container " + rEntry.getName() + " already started");
}
final RepositoryContainer repositoryContainer =
new RepositoryContainer(parentContainer, rEntry, addNamespacesPlugins);
// Storing and starting the repository container under
// key=repository_name
try
{
if (repositoryContainers.putIfAbsent(rEntry.getName(), repositoryContainer) == null)
{
SecurityHelper.doPrivilegedAction(new PrivilegedAction<Void>()
{
public Void run()
{
repositoryContainer.start();
return null;
}
});
}
else
{
throw new RepositoryConfigurationException("Repository container " + rEntry.getName() + " already started");
}
}
catch (Throwable t) //NOSONAR
{
repositoryContainers.remove(rEntry.getName());
throw new RepositoryConfigurationException("Repository container " + rEntry.getName() + " was not started.", t);
}
if (!config.getRepositoryConfigurations().contains(rEntry))
{
config.getRepositoryConfigurations().add(rEntry);
}
registerNodeTypes(rEntry.getName());
// turn on Repository ONLINE
ManageableRepository mr =
(ManageableRepository)repositoryContainer.getComponentInstanceOfType(ManageableRepository.class);
mr.setState(ManageableRepository.ONLINE);
} | [
"public",
"void",
"createRepository",
"(",
"RepositoryEntry",
"rEntry",
")",
"throws",
"RepositoryConfigurationException",
",",
"RepositoryException",
"{",
"// Need privileges to manage repository.",
"SecurityManager",
"security",
"=",
"System",
".",
"getSecurityManager",
"(",
... | Create repository. <br>
Init worksapces for initial start or them load from persistence. <br>
Add namespaces and nodetypes from service plugins. | [
"Create",
"repository",
".",
"<br",
">",
"Init",
"worksapces",
"for",
"initial",
"start",
"or",
"them",
"load",
"from",
"persistence",
".",
"<br",
">",
"Add",
"namespaces",
"and",
"nodetypes",
"from",
"service",
"plugins",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/RepositoryServiceImpl.java#L126-L181 |
webmetrics/browsermob-proxy | src/main/java/org/xbill/DNS/ResolverConfig.java | ResolverConfig.findAndroid | private void
findAndroid() {
String re1 = "^\\d+(\\.\\d+){3}$";
String re2 = "^[0-9a-f]+(:[0-9a-f]*)+:[0-9a-f]+$";
try {
ArrayList maybe = new ArrayList();
String line;
Process p = Runtime.getRuntime().exec("getprop");
InputStream in = p.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null ) {
StringTokenizer t = new StringTokenizer( line, ":" );
String name = t.nextToken();
if (name.indexOf( ".dns" ) > -1) {
String v = t.nextToken();
v = v.replaceAll( "[ \\[\\]]", "" );
if ((v.matches(re1) || v.matches(re2)) &&
!maybe.contains(v))
maybe.add(v);
}
}
configureFromLists(maybe, null);
} catch ( Exception e ) {
// ignore resolutely
}
} | java | private void
findAndroid() {
String re1 = "^\\d+(\\.\\d+){3}$";
String re2 = "^[0-9a-f]+(:[0-9a-f]*)+:[0-9a-f]+$";
try {
ArrayList maybe = new ArrayList();
String line;
Process p = Runtime.getRuntime().exec("getprop");
InputStream in = p.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null ) {
StringTokenizer t = new StringTokenizer( line, ":" );
String name = t.nextToken();
if (name.indexOf( ".dns" ) > -1) {
String v = t.nextToken();
v = v.replaceAll( "[ \\[\\]]", "" );
if ((v.matches(re1) || v.matches(re2)) &&
!maybe.contains(v))
maybe.add(v);
}
}
configureFromLists(maybe, null);
} catch ( Exception e ) {
// ignore resolutely
}
} | [
"private",
"void",
"findAndroid",
"(",
")",
"{",
"String",
"re1",
"=",
"\"^\\\\d+(\\\\.\\\\d+){3}$\"",
";",
"String",
"re2",
"=",
"\"^[0-9a-f]+(:[0-9a-f]*)+:[0-9a-f]+$\"",
";",
"try",
"{",
"ArrayList",
"maybe",
"=",
"new",
"ArrayList",
"(",
")",
";",
"String",
"... | Parses the output of getprop, which is the only way to get DNS
info on Android. getprop might disappear in future releases, so
this code comes with a use-by date. | [
"Parses",
"the",
"output",
"of",
"getprop",
"which",
"is",
"the",
"only",
"way",
"to",
"get",
"DNS",
"info",
"on",
"Android",
".",
"getprop",
"might",
"disappear",
"in",
"future",
"releases",
"so",
"this",
"code",
"comes",
"with",
"a",
"use",
"-",
"by",
... | train | https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/xbill/DNS/ResolverConfig.java#L377-L403 |
ontop/ontop | client/protege/src/main/java/it/unibz/inf/ontop/protege/core/OBDAModelManager.java | OBDAModelManager.triggerOntologyChanged | private void triggerOntologyChanged() {
if (loadingData) {
return;
}
OWLModelManager owlmm = owlEditorKit.getOWLModelManager();
OWLOntology ontology = owlmm.getActiveOntology();
if (ontology == null) {
return;
}
OWLClass newClass = owlmm.getOWLDataFactory().getOWLClass(IRI.create("http://www.unibz.it/inf/obdaplugin#RandomClass6677841155"));
OWLAxiom axiom = owlmm.getOWLDataFactory().getOWLDeclarationAxiom(newClass);
try {
AddAxiom addChange = new AddAxiom(ontology, axiom);
owlmm.applyChange(addChange);
RemoveAxiom removeChange = new RemoveAxiom(ontology, axiom);
owlmm.applyChange(removeChange);
// owlmm.fireEvent(EventType.ACTIVE_ONTOLOGY_CHANGED);
} catch (Exception e) {
log.warn("Exception forcing an ontology change. Your OWL model might contain a new class that you need to remove manually: {}",
newClass.getIRI());
log.warn(e.getMessage());
log.debug(e.getMessage(), e);
}
} | java | private void triggerOntologyChanged() {
if (loadingData) {
return;
}
OWLModelManager owlmm = owlEditorKit.getOWLModelManager();
OWLOntology ontology = owlmm.getActiveOntology();
if (ontology == null) {
return;
}
OWLClass newClass = owlmm.getOWLDataFactory().getOWLClass(IRI.create("http://www.unibz.it/inf/obdaplugin#RandomClass6677841155"));
OWLAxiom axiom = owlmm.getOWLDataFactory().getOWLDeclarationAxiom(newClass);
try {
AddAxiom addChange = new AddAxiom(ontology, axiom);
owlmm.applyChange(addChange);
RemoveAxiom removeChange = new RemoveAxiom(ontology, axiom);
owlmm.applyChange(removeChange);
// owlmm.fireEvent(EventType.ACTIVE_ONTOLOGY_CHANGED);
} catch (Exception e) {
log.warn("Exception forcing an ontology change. Your OWL model might contain a new class that you need to remove manually: {}",
newClass.getIRI());
log.warn(e.getMessage());
log.debug(e.getMessage(), e);
}
} | [
"private",
"void",
"triggerOntologyChanged",
"(",
")",
"{",
"if",
"(",
"loadingData",
")",
"{",
"return",
";",
"}",
"OWLModelManager",
"owlmm",
"=",
"owlEditorKit",
".",
"getOWLModelManager",
"(",
")",
";",
"OWLOntology",
"ontology",
"=",
"owlmm",
".",
"getAct... | *
Protege wont trigger a save action unless it detects that the OWLOntology
currently opened has suffered a change. The OBDA plugin requires that
protege triggers a save action also in the case when only the OBDA model
has suffered changes. To accomplish this, this method will "fake" an
ontology change by inserting and removing a class into the OWLModel. | [
"*",
"Protege",
"wont",
"trigger",
"a",
"save",
"action",
"unless",
"it",
"detects",
"that",
"the",
"OWLOntology",
"currently",
"opened",
"has",
"suffered",
"a",
"change",
".",
"The",
"OBDA",
"plugin",
"requires",
"that",
"protege",
"triggers",
"a",
"save",
... | train | https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/client/protege/src/main/java/it/unibz/inf/ontop/protege/core/OBDAModelManager.java#L726-L752 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslpolicy_binding.java | sslpolicy_binding.get | public static sslpolicy_binding get(nitro_service service, String name) throws Exception{
sslpolicy_binding obj = new sslpolicy_binding();
obj.set_name(name);
sslpolicy_binding response = (sslpolicy_binding) obj.get_resource(service);
return response;
} | java | public static sslpolicy_binding get(nitro_service service, String name) throws Exception{
sslpolicy_binding obj = new sslpolicy_binding();
obj.set_name(name);
sslpolicy_binding response = (sslpolicy_binding) obj.get_resource(service);
return response;
} | [
"public",
"static",
"sslpolicy_binding",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"name",
")",
"throws",
"Exception",
"{",
"sslpolicy_binding",
"obj",
"=",
"new",
"sslpolicy_binding",
"(",
")",
";",
"obj",
".",
"set_name",
"(",
"name",
")",
";",
... | Use this API to fetch sslpolicy_binding resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"sslpolicy_binding",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslpolicy_binding.java#L158-L163 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/serde/binary/BinarySerde.java | BinarySerde.doByteBufferPutUnCompressed | public static void doByteBufferPutUnCompressed(INDArray arr, ByteBuffer allocated, boolean rewind) {
// ensure we send data to host memory
Nd4j.getExecutioner().commit();
Nd4j.getAffinityManager().ensureLocation(arr, AffinityManager.Location.HOST);
ByteBuffer buffer = arr.data().pointer().asByteBuffer().order(ByteOrder.nativeOrder());
ByteBuffer shapeBuffer = arr.shapeInfoDataBuffer().pointer().asByteBuffer().order(ByteOrder.nativeOrder());
//2 four byte ints at the beginning
allocated.putInt(arr.rank());
//put data opType next so its self describing
allocated.putInt(arr.data().dataType().ordinal());
allocated.put(shapeBuffer);
allocated.put(buffer);
if (rewind)
allocated.rewind();
} | java | public static void doByteBufferPutUnCompressed(INDArray arr, ByteBuffer allocated, boolean rewind) {
// ensure we send data to host memory
Nd4j.getExecutioner().commit();
Nd4j.getAffinityManager().ensureLocation(arr, AffinityManager.Location.HOST);
ByteBuffer buffer = arr.data().pointer().asByteBuffer().order(ByteOrder.nativeOrder());
ByteBuffer shapeBuffer = arr.shapeInfoDataBuffer().pointer().asByteBuffer().order(ByteOrder.nativeOrder());
//2 four byte ints at the beginning
allocated.putInt(arr.rank());
//put data opType next so its self describing
allocated.putInt(arr.data().dataType().ordinal());
allocated.put(shapeBuffer);
allocated.put(buffer);
if (rewind)
allocated.rewind();
} | [
"public",
"static",
"void",
"doByteBufferPutUnCompressed",
"(",
"INDArray",
"arr",
",",
"ByteBuffer",
"allocated",
",",
"boolean",
"rewind",
")",
"{",
"// ensure we send data to host memory",
"Nd4j",
".",
"getExecutioner",
"(",
")",
".",
"commit",
"(",
")",
";",
"... | Setup the given byte buffer
for serialization (note that this is for uncompressed INDArrays)
4 bytes int for rank
4 bytes for data opType
shape buffer
data buffer
@param arr the array to setup
@param allocated the byte buffer to setup
@param rewind whether to rewind the byte buffer or nt | [
"Setup",
"the",
"given",
"byte",
"buffer",
"for",
"serialization",
"(",
"note",
"that",
"this",
"is",
"for",
"uncompressed",
"INDArrays",
")",
"4",
"bytes",
"int",
"for",
"rank",
"4",
"bytes",
"for",
"data",
"opType",
"shape",
"buffer",
"data",
"buffer"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/serde/binary/BinarySerde.java#L205-L220 |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/crypto/digest/DigestHelper.java | DigestHelper.sha1hmac | public static String sha1hmac(String key, String plaintext)
{
return sha1hmac(key, plaintext, ENCODE_HEX);
} | java | public static String sha1hmac(String key, String plaintext)
{
return sha1hmac(key, plaintext, ENCODE_HEX);
} | [
"public",
"static",
"String",
"sha1hmac",
"(",
"String",
"key",
",",
"String",
"plaintext",
")",
"{",
"return",
"sha1hmac",
"(",
"key",
",",
"plaintext",
",",
"ENCODE_HEX",
")",
";",
"}"
] | Performs HMAC-SHA1 on the UTF-8 byte representation of strings
@param key
@param plaintext
@return | [
"Performs",
"HMAC",
"-",
"SHA1",
"on",
"the",
"UTF",
"-",
"8",
"byte",
"representation",
"of",
"strings"
] | train | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/crypto/digest/DigestHelper.java#L42-L45 |
fcrepo3/fcrepo | fcrepo-server/src/main/java/org/fcrepo/server/resourceIndex/ResourceIndexImpl.java | ResourceIndexImpl.updateTripleDiffs | private void updateTripleDiffs(Set<Triple> existing, Set<Triple> desired)
throws ResourceIndexException {
// Delete any existing triples that are no longer desired,
// leaving the ones we want in place
HashSet<Triple> obsoleteTriples = new HashSet<Triple>(existing);
obsoleteTriples.removeAll(desired);
updateTriples(obsoleteTriples, true);
// Add only new desired triples
HashSet<Triple> newTriples = new HashSet<Triple>(desired);
newTriples.removeAll(existing);
updateTriples(newTriples, false);
} | java | private void updateTripleDiffs(Set<Triple> existing, Set<Triple> desired)
throws ResourceIndexException {
// Delete any existing triples that are no longer desired,
// leaving the ones we want in place
HashSet<Triple> obsoleteTriples = new HashSet<Triple>(existing);
obsoleteTriples.removeAll(desired);
updateTriples(obsoleteTriples, true);
// Add only new desired triples
HashSet<Triple> newTriples = new HashSet<Triple>(desired);
newTriples.removeAll(existing);
updateTriples(newTriples, false);
} | [
"private",
"void",
"updateTripleDiffs",
"(",
"Set",
"<",
"Triple",
">",
"existing",
",",
"Set",
"<",
"Triple",
">",
"desired",
")",
"throws",
"ResourceIndexException",
"{",
"// Delete any existing triples that are no longer desired,",
"// leaving the ones we want in place",
... | Computes the difference between the given sets and applies the
appropriate deletes and adds to the triplestore. If _syncUpdates is true,
changes will be flushed before returning. | [
"Computes",
"the",
"difference",
"between",
"the",
"given",
"sets",
"and",
"applies",
"the",
"appropriate",
"deletes",
"and",
"adds",
"to",
"the",
"triplestore",
".",
"If",
"_syncUpdates",
"is",
"true",
"changes",
"will",
"be",
"flushed",
"before",
"returning",
... | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/resourceIndex/ResourceIndexImpl.java#L177-L191 |
alibaba/canal | client-adapter/common/src/main/java/com/alibaba/otter/canal/client/adapter/config/bind/RelaxedDataBinder.java | RelaxedDataBinder.modifyProperties | private MutablePropertyValues modifyProperties(MutablePropertyValues propertyValues, Object target) {
propertyValues = getPropertyValuesForNamePrefix(propertyValues);
if (target instanceof RelaxedDataBinder.MapHolder) {
propertyValues = addMapPrefix(propertyValues);
}
BeanWrapper wrapper = new BeanWrapperImpl(target);
wrapper.setConversionService(new RelaxedConversionService(getConversionService()));
wrapper.setAutoGrowNestedPaths(true);
List<PropertyValue> sortedValues = new ArrayList<PropertyValue>();
Set<String> modifiedNames = new HashSet<String>();
List<String> sortedNames = getSortedPropertyNames(propertyValues);
for (String name : sortedNames) {
PropertyValue propertyValue = propertyValues.getPropertyValue(name);
PropertyValue modifiedProperty = modifyProperty(wrapper, propertyValue);
if (modifiedNames.add(modifiedProperty.getName())) {
sortedValues.add(modifiedProperty);
}
}
return new MutablePropertyValues(sortedValues);
} | java | private MutablePropertyValues modifyProperties(MutablePropertyValues propertyValues, Object target) {
propertyValues = getPropertyValuesForNamePrefix(propertyValues);
if (target instanceof RelaxedDataBinder.MapHolder) {
propertyValues = addMapPrefix(propertyValues);
}
BeanWrapper wrapper = new BeanWrapperImpl(target);
wrapper.setConversionService(new RelaxedConversionService(getConversionService()));
wrapper.setAutoGrowNestedPaths(true);
List<PropertyValue> sortedValues = new ArrayList<PropertyValue>();
Set<String> modifiedNames = new HashSet<String>();
List<String> sortedNames = getSortedPropertyNames(propertyValues);
for (String name : sortedNames) {
PropertyValue propertyValue = propertyValues.getPropertyValue(name);
PropertyValue modifiedProperty = modifyProperty(wrapper, propertyValue);
if (modifiedNames.add(modifiedProperty.getName())) {
sortedValues.add(modifiedProperty);
}
}
return new MutablePropertyValues(sortedValues);
} | [
"private",
"MutablePropertyValues",
"modifyProperties",
"(",
"MutablePropertyValues",
"propertyValues",
",",
"Object",
"target",
")",
"{",
"propertyValues",
"=",
"getPropertyValuesForNamePrefix",
"(",
"propertyValues",
")",
";",
"if",
"(",
"target",
"instanceof",
"Relaxed... | Modify the property values so that period separated property paths are valid
for map keys. Also creates new maps for properties of map type that are null
(assuming all maps are potentially nested). The standard bracket {@code[...]}
dereferencing is also accepted.
@param propertyValues the property values
@param target the target object
@return modified property values | [
"Modify",
"the",
"property",
"values",
"so",
"that",
"period",
"separated",
"property",
"paths",
"are",
"valid",
"for",
"map",
"keys",
".",
"Also",
"creates",
"new",
"maps",
"for",
"properties",
"of",
"map",
"type",
"that",
"are",
"null",
"(",
"assuming",
... | train | https://github.com/alibaba/canal/blob/8f088cddc0755f4350c5aaae95c6e4002d90a40f/client-adapter/common/src/main/java/com/alibaba/otter/canal/client/adapter/config/bind/RelaxedDataBinder.java#L124-L143 |
seancfoley/IPAddress | IPAddress/src/inet.ipaddr/inet/ipaddr/ipv6/IPv6AddressSection.java | IPv6AddressSection.intersect | public IPv6AddressSection intersect(IPv6AddressSection other) throws SizeMismatchException {
return intersect(this, other, getAddressCreator(), this::getSegment, other::getSegment);
} | java | public IPv6AddressSection intersect(IPv6AddressSection other) throws SizeMismatchException {
return intersect(this, other, getAddressCreator(), this::getSegment, other::getSegment);
} | [
"public",
"IPv6AddressSection",
"intersect",
"(",
"IPv6AddressSection",
"other",
")",
"throws",
"SizeMismatchException",
"{",
"return",
"intersect",
"(",
"this",
",",
"other",
",",
"getAddressCreator",
"(",
")",
",",
"this",
"::",
"getSegment",
",",
"other",
"::",... | Produces the subnet sections whose addresses are found in both this and the given argument.
<p>
This is also known as the conjunction of the two sets of address sections.
<p>
@param other
@return the section containing the sections found in both this and the given subnet sections | [
"Produces",
"the",
"subnet",
"sections",
"whose",
"addresses",
"are",
"found",
"in",
"both",
"this",
"and",
"the",
"given",
"argument",
".",
"<p",
">",
"This",
"is",
"also",
"known",
"as",
"the",
"conjunction",
"of",
"the",
"two",
"sets",
"of",
"address",
... | train | https://github.com/seancfoley/IPAddress/blob/90493d0673511d673100c36d020dd93dd870111a/IPAddress/src/inet.ipaddr/inet/ipaddr/ipv6/IPv6AddressSection.java#L1617-L1619 |
jingwei/krati | krati-main/src/main/java/krati/io/IOFactory.java | IOFactory.createDataReader | public final static DataReader createDataReader(File file, IOType type) {
if(type == IOType.MAPPED) {
if(file.length() <= Integer.MAX_VALUE) {
return new MappedReader(file);
} else {
return new MultiMappedReader(file);
}
} else {
return new ChannelReader(file);
}
} | java | public final static DataReader createDataReader(File file, IOType type) {
if(type == IOType.MAPPED) {
if(file.length() <= Integer.MAX_VALUE) {
return new MappedReader(file);
} else {
return new MultiMappedReader(file);
}
} else {
return new ChannelReader(file);
}
} | [
"public",
"final",
"static",
"DataReader",
"createDataReader",
"(",
"File",
"file",
",",
"IOType",
"type",
")",
"{",
"if",
"(",
"type",
"==",
"IOType",
".",
"MAPPED",
")",
"{",
"if",
"(",
"file",
".",
"length",
"(",
")",
"<=",
"Integer",
".",
"MAX_VALU... | Creates a new DataReader to read from a file.
@param file - file to read.
@param type - I/O type.
@return a new DataReader instance. | [
"Creates",
"a",
"new",
"DataReader",
"to",
"read",
"from",
"a",
"file",
"."
] | train | https://github.com/jingwei/krati/blob/1ca0f994a7b0c8215b827eac9aaf95789ec08d21/krati-main/src/main/java/krati/io/IOFactory.java#L37-L47 |
Jasig/uPortal | uPortal-tools/src/main/java/org/apereo/portal/version/VersionUtils.java | VersionUtils.canUpdate | public static boolean canUpdate(Version from, Version to) {
final Field mostSpecificMatchingField = getMostSpecificMatchingField(from, to);
switch (mostSpecificMatchingField) {
case LOCAL:
{
return true;
}
case PATCH:
case MINOR:
{
return from.isBefore(to);
}
default:
{
return false;
}
}
} | java | public static boolean canUpdate(Version from, Version to) {
final Field mostSpecificMatchingField = getMostSpecificMatchingField(from, to);
switch (mostSpecificMatchingField) {
case LOCAL:
{
return true;
}
case PATCH:
case MINOR:
{
return from.isBefore(to);
}
default:
{
return false;
}
}
} | [
"public",
"static",
"boolean",
"canUpdate",
"(",
"Version",
"from",
",",
"Version",
"to",
")",
"{",
"final",
"Field",
"mostSpecificMatchingField",
"=",
"getMostSpecificMatchingField",
"(",
"from",
",",
"to",
")",
";",
"switch",
"(",
"mostSpecificMatchingField",
")... | Determine if an "update" can be done between the from and to versions. The ability to update
is defined as from == to OR (from.isBefore(to) AND mostSpecificMatchingField in (PATCH,
MINOR))
@param from Version updating from
@param to Version updating to
@return true if the major and minor versions match and the from.patch value is less than or
equal to the to.patch value | [
"Determine",
"if",
"an",
"update",
"can",
"be",
"done",
"between",
"the",
"from",
"and",
"to",
"versions",
".",
"The",
"ability",
"to",
"update",
"is",
"defined",
"as",
"from",
"==",
"to",
"OR",
"(",
"from",
".",
"isBefore",
"(",
"to",
")",
"AND",
"m... | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-tools/src/main/java/org/apereo/portal/version/VersionUtils.java#L100-L117 |
JOML-CI/JOML | src/org/joml/Vector3d.java | Vector3d.lengthSquared | public static double lengthSquared(double x, double y, double z) {
return x * x + y * y + z * z;
} | java | public static double lengthSquared(double x, double y, double z) {
return x * x + y * y + z * z;
} | [
"public",
"static",
"double",
"lengthSquared",
"(",
"double",
"x",
",",
"double",
"y",
",",
"double",
"z",
")",
"{",
"return",
"x",
"*",
"x",
"+",
"y",
"*",
"y",
"+",
"z",
"*",
"z",
";",
"}"
] | Get the length squared of a 3-dimensional double-precision vector.
@param x The vector's x component
@param y The vector's y component
@param z The vector's z component
@return the length squared of the given vector
@author F. Neurath | [
"Get",
"the",
"length",
"squared",
"of",
"a",
"3",
"-",
"dimensional",
"double",
"-",
"precision",
"vector",
"."
] | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Vector3d.java#L1677-L1679 |
mboudreau/Alternator | src/main/java/com/amazonaws/services/dynamodb/datamodeling/DynamoDBReflector.java | DynamoDBReflector.getCustomMarshalledValue | @SuppressWarnings({ "rawtypes", "unchecked" })
private <T> T getCustomMarshalledValue(T toReturn, Method getter, AttributeValue value) {
DynamoDBMarshalling annotation = getter.getAnnotation(DynamoDBMarshalling.class);
Class<? extends DynamoDBMarshaller<? extends Object>> marshallerClass = annotation.marshallerClass();
DynamoDBMarshaller marshaller;
try {
marshaller = marshallerClass.newInstance();
} catch ( InstantiationException e ) {
throw new DynamoDBMappingException("Couldn't instantiate marshaller of class " + marshallerClass, e);
} catch ( IllegalAccessException e ) {
throw new DynamoDBMappingException("Couldn't instantiate marshaller of class " + marshallerClass, e);
}
return (T) marshaller.unmarshall(getter.getReturnType(), value.getS());
} | java | @SuppressWarnings({ "rawtypes", "unchecked" })
private <T> T getCustomMarshalledValue(T toReturn, Method getter, AttributeValue value) {
DynamoDBMarshalling annotation = getter.getAnnotation(DynamoDBMarshalling.class);
Class<? extends DynamoDBMarshaller<? extends Object>> marshallerClass = annotation.marshallerClass();
DynamoDBMarshaller marshaller;
try {
marshaller = marshallerClass.newInstance();
} catch ( InstantiationException e ) {
throw new DynamoDBMappingException("Couldn't instantiate marshaller of class " + marshallerClass, e);
} catch ( IllegalAccessException e ) {
throw new DynamoDBMappingException("Couldn't instantiate marshaller of class " + marshallerClass, e);
}
return (T) marshaller.unmarshall(getter.getReturnType(), value.getS());
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"rawtypes\"",
",",
"\"unchecked\"",
"}",
")",
"private",
"<",
"T",
">",
"T",
"getCustomMarshalledValue",
"(",
"T",
"toReturn",
",",
"Method",
"getter",
",",
"AttributeValue",
"value",
")",
"{",
"DynamoDBMarshalling",
"annotat... | Marshalls the custom value given into the proper return type. | [
"Marshalls",
"the",
"custom",
"value",
"given",
"into",
"the",
"proper",
"return",
"type",
"."
] | train | https://github.com/mboudreau/Alternator/blob/4b230ac843494cb10e46ddc2848f5b5d377d7b72/src/main/java/com/amazonaws/services/dynamodb/datamodeling/DynamoDBReflector.java#L566-L581 |
alibaba/ARouter | arouter-api/src/main/java/com/alibaba/android/arouter/facade/Postcard.java | Postcard.withParcelableArrayList | public Postcard withParcelableArrayList(@Nullable String key, @Nullable ArrayList<? extends Parcelable> value) {
mBundle.putParcelableArrayList(key, value);
return this;
} | java | public Postcard withParcelableArrayList(@Nullable String key, @Nullable ArrayList<? extends Parcelable> value) {
mBundle.putParcelableArrayList(key, value);
return this;
} | [
"public",
"Postcard",
"withParcelableArrayList",
"(",
"@",
"Nullable",
"String",
"key",
",",
"@",
"Nullable",
"ArrayList",
"<",
"?",
"extends",
"Parcelable",
">",
"value",
")",
"{",
"mBundle",
".",
"putParcelableArrayList",
"(",
"key",
",",
"value",
")",
";",
... | Inserts a List of Parcelable values into the mapping of this Bundle,
replacing any existing value for the given key. Either key or value may
be null.
@param key a String, or null
@param value an ArrayList of Parcelable objects, or null
@return current | [
"Inserts",
"a",
"List",
"of",
"Parcelable",
"values",
"into",
"the",
"mapping",
"of",
"this",
"Bundle",
"replacing",
"any",
"existing",
"value",
"for",
"the",
"given",
"key",
".",
"Either",
"key",
"or",
"value",
"may",
"be",
"null",
"."
] | train | https://github.com/alibaba/ARouter/blob/1a06912a6e14a57112db1204b43f81c43d721732/arouter-api/src/main/java/com/alibaba/android/arouter/facade/Postcard.java#L402-L405 |
snowflakedb/snowflake-jdbc | src/main/java/net/snowflake/client/core/SessionUtil.java | SessionUtil.renewSession | static public LoginOutput renewSession(LoginInput loginInput)
throws SFException, SnowflakeSQLException
{
try
{
return tokenRequest(loginInput, TokenRequestType.RENEW);
}
catch (SnowflakeReauthenticationRequest ex)
{
if (Strings.isNullOrEmpty(loginInput.getIdToken()))
{
throw ex;
}
return tokenRequest(loginInput, TokenRequestType.ISSUE);
}
} | java | static public LoginOutput renewSession(LoginInput loginInput)
throws SFException, SnowflakeSQLException
{
try
{
return tokenRequest(loginInput, TokenRequestType.RENEW);
}
catch (SnowflakeReauthenticationRequest ex)
{
if (Strings.isNullOrEmpty(loginInput.getIdToken()))
{
throw ex;
}
return tokenRequest(loginInput, TokenRequestType.ISSUE);
}
} | [
"static",
"public",
"LoginOutput",
"renewSession",
"(",
"LoginInput",
"loginInput",
")",
"throws",
"SFException",
",",
"SnowflakeSQLException",
"{",
"try",
"{",
"return",
"tokenRequest",
"(",
"loginInput",
",",
"TokenRequestType",
".",
"RENEW",
")",
";",
"}",
"cat... | Renew a session.
<p>
Use cases:
- Session and Master tokens are provided. No Id token:
- succeed in getting a new Session token.
- fail and raise SnowflakeReauthenticationRequest because Master
token expires. Since no id token exists, the exception is thrown
to the upstream.
- Session and Id tokens are provided. No Master token:
- fail and raise SnowflakeReauthenticationRequest and
issue a new Session token
- fail and raise SnowflakeReauthenticationRequest and fail
to issue a new Session token as the
@param loginInput login information
@return login output
@throws SFException if unexpected uri information
@throws SnowflakeSQLException if failed to renew the session | [
"Renew",
"a",
"session",
".",
"<p",
">",
"Use",
"cases",
":",
"-",
"Session",
"and",
"Master",
"tokens",
"are",
"provided",
".",
"No",
"Id",
"token",
":",
"-",
"succeed",
"in",
"getting",
"a",
"new",
"Session",
"token",
".",
"-",
"fail",
"and",
"rais... | train | https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtil.java#L888-L903 |
lessthanoptimal/BoofCV | integration/boofcv-android/src/main/java/boofcv/android/ConvertBitmap.java | ConvertBitmap.boofToBitmap | public static void boofToBitmap( ImageBase input , Bitmap output , byte[] storage) {
if( BOverrideConvertAndroid.invokeBoofToBitmap(ColorFormat.RGB,input,output,storage))
return;
if( input instanceof Planar ) {
planarToBitmap((Planar)input,output,storage);
} else if( input instanceof ImageGray ) {
grayToBitmap((ImageGray)input,output,storage);
} else if( input instanceof ImageInterleaved ) {
interleavedToBitmap((ImageInterleaved) input, output, storage);
} else {
throw new IllegalArgumentException("Unsupported input image type");
}
} | java | public static void boofToBitmap( ImageBase input , Bitmap output , byte[] storage) {
if( BOverrideConvertAndroid.invokeBoofToBitmap(ColorFormat.RGB,input,output,storage))
return;
if( input instanceof Planar ) {
planarToBitmap((Planar)input,output,storage);
} else if( input instanceof ImageGray ) {
grayToBitmap((ImageGray)input,output,storage);
} else if( input instanceof ImageInterleaved ) {
interleavedToBitmap((ImageInterleaved) input, output, storage);
} else {
throw new IllegalArgumentException("Unsupported input image type");
}
} | [
"public",
"static",
"void",
"boofToBitmap",
"(",
"ImageBase",
"input",
",",
"Bitmap",
"output",
",",
"byte",
"[",
"]",
"storage",
")",
"{",
"if",
"(",
"BOverrideConvertAndroid",
".",
"invokeBoofToBitmap",
"(",
"ColorFormat",
".",
"RGB",
",",
"input",
",",
"o... | Converts many BoofCV image types into a Bitmap.
@see #declareStorage(android.graphics.Bitmap, byte[])
@param input Input BoofCV image.
@param output Output Bitmap image.
@param storage Byte array used for internal storage. If null it will be declared internally. | [
"Converts",
"many",
"BoofCV",
"image",
"types",
"into",
"a",
"Bitmap",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-android/src/main/java/boofcv/android/ConvertBitmap.java#L203-L216 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.