repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
sequencelengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
sequencelengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
UrielCh/ovh-java-sdk | ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java | ApiOvhDomain.serviceName_rules_emailsObfuscation_GET | public ArrayList<OvhContactAllTypesEnum> serviceName_rules_emailsObfuscation_GET(String serviceName) throws IOException {
"""
Retrieve emails obfuscation rule
REST: GET /domain/{serviceName}/rules/emailsObfuscation
@param serviceName [required] The internal name of your domain
"""
String qPath = "/domain/{serviceName}/rules/emailsObfuscation";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t6);
} | java | public ArrayList<OvhContactAllTypesEnum> serviceName_rules_emailsObfuscation_GET(String serviceName) throws IOException {
String qPath = "/domain/{serviceName}/rules/emailsObfuscation";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t6);
} | [
"public",
"ArrayList",
"<",
"OvhContactAllTypesEnum",
">",
"serviceName_rules_emailsObfuscation_GET",
"(",
"String",
"serviceName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/domain/{serviceName}/rules/emailsObfuscation\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"t6",
")",
";",
"}"
] | Retrieve emails obfuscation rule
REST: GET /domain/{serviceName}/rules/emailsObfuscation
@param serviceName [required] The internal name of your domain | [
"Retrieve",
"emails",
"obfuscation",
"rule"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java#L1390-L1395 |
actorapp/actor-platform | actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/markdown/MarkdownParser.java | MarkdownParser.isNotSymbol | private boolean isNotSymbol(String text, int index, char c) {
"""
Checking if symbol is not eq to c
@param text
@param index
@param c
@return
"""
if (index >= 0 && index < text.length()) {
return text.charAt(index) != c;
}
return true;
} | java | private boolean isNotSymbol(String text, int index, char c) {
if (index >= 0 && index < text.length()) {
return text.charAt(index) != c;
}
return true;
} | [
"private",
"boolean",
"isNotSymbol",
"(",
"String",
"text",
",",
"int",
"index",
",",
"char",
"c",
")",
"{",
"if",
"(",
"index",
">=",
"0",
"&&",
"index",
"<",
"text",
".",
"length",
"(",
")",
")",
"{",
"return",
"text",
".",
"charAt",
"(",
"index",
")",
"!=",
"c",
";",
"}",
"return",
"true",
";",
"}"
] | Checking if symbol is not eq to c
@param text
@param index
@param c
@return | [
"Checking",
"if",
"symbol",
"is",
"not",
"eq",
"to",
"c"
] | train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/markdown/MarkdownParser.java#L396-L402 |
artikcloud/artikcloud-java | src/main/java/cloud/artik/api/RegistrationsApi.java | RegistrationsApi.confirmUserAsync | public com.squareup.okhttp.Call confirmUserAsync(DeviceRegConfirmUserRequest registrationInfo, final ApiCallback<DeviceRegConfirmUserResponseEnvelope> callback) throws ApiException {
"""
Confirm User (asynchronously)
This call updates the registration request issued earlier by associating it with an authenticated user and captures all additional information required to add a new device.
@param registrationInfo Device Registration information. (required)
@param callback The callback to be executed when the API call finishes
@return The request call
@throws ApiException If fail to process the API call, e.g. serializing the request body object
"""
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = confirmUserValidateBeforeCall(registrationInfo, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<DeviceRegConfirmUserResponseEnvelope>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} | java | public com.squareup.okhttp.Call confirmUserAsync(DeviceRegConfirmUserRequest registrationInfo, final ApiCallback<DeviceRegConfirmUserResponseEnvelope> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = confirmUserValidateBeforeCall(registrationInfo, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<DeviceRegConfirmUserResponseEnvelope>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} | [
"public",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"confirmUserAsync",
"(",
"DeviceRegConfirmUserRequest",
"registrationInfo",
",",
"final",
"ApiCallback",
"<",
"DeviceRegConfirmUserResponseEnvelope",
">",
"callback",
")",
"throws",
"ApiException",
"{",
"ProgressResponseBody",
".",
"ProgressListener",
"progressListener",
"=",
"null",
";",
"ProgressRequestBody",
".",
"ProgressRequestListener",
"progressRequestListener",
"=",
"null",
";",
"if",
"(",
"callback",
"!=",
"null",
")",
"{",
"progressListener",
"=",
"new",
"ProgressResponseBody",
".",
"ProgressListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"update",
"(",
"long",
"bytesRead",
",",
"long",
"contentLength",
",",
"boolean",
"done",
")",
"{",
"callback",
".",
"onDownloadProgress",
"(",
"bytesRead",
",",
"contentLength",
",",
"done",
")",
";",
"}",
"}",
";",
"progressRequestListener",
"=",
"new",
"ProgressRequestBody",
".",
"ProgressRequestListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onRequestProgress",
"(",
"long",
"bytesWritten",
",",
"long",
"contentLength",
",",
"boolean",
"done",
")",
"{",
"callback",
".",
"onUploadProgress",
"(",
"bytesWritten",
",",
"contentLength",
",",
"done",
")",
";",
"}",
"}",
";",
"}",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"call",
"=",
"confirmUserValidateBeforeCall",
"(",
"registrationInfo",
",",
"progressListener",
",",
"progressRequestListener",
")",
";",
"Type",
"localVarReturnType",
"=",
"new",
"TypeToken",
"<",
"DeviceRegConfirmUserResponseEnvelope",
">",
"(",
")",
"{",
"}",
".",
"getType",
"(",
")",
";",
"apiClient",
".",
"executeAsync",
"(",
"call",
",",
"localVarReturnType",
",",
"callback",
")",
";",
"return",
"call",
";",
"}"
] | Confirm User (asynchronously)
This call updates the registration request issued earlier by associating it with an authenticated user and captures all additional information required to add a new device.
@param registrationInfo Device Registration information. (required)
@param callback The callback to be executed when the API call finishes
@return The request call
@throws ApiException If fail to process the API call, e.g. serializing the request body object | [
"Confirm",
"User",
"(",
"asynchronously",
")",
"This",
"call",
"updates",
"the",
"registration",
"request",
"issued",
"earlier",
"by",
"associating",
"it",
"with",
"an",
"authenticated",
"user",
"and",
"captures",
"all",
"additional",
"information",
"required",
"to",
"add",
"a",
"new",
"device",
"."
] | train | https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/RegistrationsApi.java#L152-L177 |
FXMisc/WellBehavedFX | src/main/java/org/fxmisc/wellbehaved/event/Nodes.java | Nodes.popInputMap | public static boolean popInputMap(Node node) {
"""
If the internal stack has an {@link InputMap}, removes the current {@link InputMap} that was installed
on the give node via {@link #pushInputMap(Node, InputMap)}, reinstalls the previous {@code InputMap},
and then returns true. If the stack is empty, returns false.
"""
Stack<InputMap<?>> stackedInputMaps = getStack(node);
if (!stackedInputMaps.isEmpty()) {
// If stack is not empty, node has already been initialized, so can use unsafe methods.
// Now, completely override current input map with previous one on stack
setInputMapUnsafe(node, stackedInputMaps.pop());
return true;
} else {
return false;
}
} | java | public static boolean popInputMap(Node node) {
Stack<InputMap<?>> stackedInputMaps = getStack(node);
if (!stackedInputMaps.isEmpty()) {
// If stack is not empty, node has already been initialized, so can use unsafe methods.
// Now, completely override current input map with previous one on stack
setInputMapUnsafe(node, stackedInputMaps.pop());
return true;
} else {
return false;
}
} | [
"public",
"static",
"boolean",
"popInputMap",
"(",
"Node",
"node",
")",
"{",
"Stack",
"<",
"InputMap",
"<",
"?",
">",
">",
"stackedInputMaps",
"=",
"getStack",
"(",
"node",
")",
";",
"if",
"(",
"!",
"stackedInputMaps",
".",
"isEmpty",
"(",
")",
")",
"{",
"// If stack is not empty, node has already been initialized, so can use unsafe methods.",
"// Now, completely override current input map with previous one on stack",
"setInputMapUnsafe",
"(",
"node",
",",
"stackedInputMaps",
".",
"pop",
"(",
")",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | If the internal stack has an {@link InputMap}, removes the current {@link InputMap} that was installed
on the give node via {@link #pushInputMap(Node, InputMap)}, reinstalls the previous {@code InputMap},
and then returns true. If the stack is empty, returns false. | [
"If",
"the",
"internal",
"stack",
"has",
"an",
"{"
] | train | https://github.com/FXMisc/WellBehavedFX/blob/ca889734481f5439655ca8deb6f742964b5654b0/src/main/java/org/fxmisc/wellbehaved/event/Nodes.java#L102-L112 |
kaazing/gateway | mina.core/core/src/main/java/org/apache/mina/handler/demux/DemuxingIoHandler.java | DemuxingIoHandler.exceptionCaught | @Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
"""
Invoked when any exception is thrown by user IoHandler implementation
or by MINA. If cause is an instance of IOException, MINA will close the
connection automatically.
<b>Warning !</b> If you are to overload this method, be aware that you
_must_ call the messageHandler in your own method, otherwise it won't
be called.
"""
ExceptionHandler<Throwable> handler = findExceptionHandler(cause.getClass());
if (handler != null) {
handler.exceptionCaught(session, cause);
} else {
throw new UnknownMessageTypeException(
"No handler found for exception type: " +
cause.getClass().getSimpleName());
}
} | java | @Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
ExceptionHandler<Throwable> handler = findExceptionHandler(cause.getClass());
if (handler != null) {
handler.exceptionCaught(session, cause);
} else {
throw new UnknownMessageTypeException(
"No handler found for exception type: " +
cause.getClass().getSimpleName());
}
} | [
"@",
"Override",
"public",
"void",
"exceptionCaught",
"(",
"IoSession",
"session",
",",
"Throwable",
"cause",
")",
"throws",
"Exception",
"{",
"ExceptionHandler",
"<",
"Throwable",
">",
"handler",
"=",
"findExceptionHandler",
"(",
"cause",
".",
"getClass",
"(",
")",
")",
";",
"if",
"(",
"handler",
"!=",
"null",
")",
"{",
"handler",
".",
"exceptionCaught",
"(",
"session",
",",
"cause",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"UnknownMessageTypeException",
"(",
"\"No handler found for exception type: \"",
"+",
"cause",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
")",
";",
"}",
"}"
] | Invoked when any exception is thrown by user IoHandler implementation
or by MINA. If cause is an instance of IOException, MINA will close the
connection automatically.
<b>Warning !</b> If you are to overload this method, be aware that you
_must_ call the messageHandler in your own method, otherwise it won't
be called. | [
"Invoked",
"when",
"any",
"exception",
"is",
"thrown",
"by",
"user",
"IoHandler",
"implementation",
"or",
"by",
"MINA",
".",
"If",
"cause",
"is",
"an",
"instance",
"of",
"IOException",
"MINA",
"will",
"close",
"the",
"connection",
"automatically",
"."
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.core/core/src/main/java/org/apache/mina/handler/demux/DemuxingIoHandler.java#L264-L274 |
VoltDB/voltdb | src/frontend/org/voltdb/importer/ImporterLifeCycleManager.java | ImporterLifeCycleManager.configure | public final void configure(Properties props, FormatterBuilder formatterBuilder) {
"""
This will be called for every importer configuration section for this importer type.
@param props Properties defined in a configuration section for this importer
"""
Map<URI, ImporterConfig> configs = m_factory.createImporterConfigurations(props, formatterBuilder);
m_configs = new ImmutableMap.Builder<URI, ImporterConfig>()
.putAll(configs)
.putAll(Maps.filterKeys(m_configs, not(in(configs.keySet()))))
.build();
} | java | public final void configure(Properties props, FormatterBuilder formatterBuilder)
{
Map<URI, ImporterConfig> configs = m_factory.createImporterConfigurations(props, formatterBuilder);
m_configs = new ImmutableMap.Builder<URI, ImporterConfig>()
.putAll(configs)
.putAll(Maps.filterKeys(m_configs, not(in(configs.keySet()))))
.build();
} | [
"public",
"final",
"void",
"configure",
"(",
"Properties",
"props",
",",
"FormatterBuilder",
"formatterBuilder",
")",
"{",
"Map",
"<",
"URI",
",",
"ImporterConfig",
">",
"configs",
"=",
"m_factory",
".",
"createImporterConfigurations",
"(",
"props",
",",
"formatterBuilder",
")",
";",
"m_configs",
"=",
"new",
"ImmutableMap",
".",
"Builder",
"<",
"URI",
",",
"ImporterConfig",
">",
"(",
")",
".",
"putAll",
"(",
"configs",
")",
".",
"putAll",
"(",
"Maps",
".",
"filterKeys",
"(",
"m_configs",
",",
"not",
"(",
"in",
"(",
"configs",
".",
"keySet",
"(",
")",
")",
")",
")",
")",
".",
"build",
"(",
")",
";",
"}"
] | This will be called for every importer configuration section for this importer type.
@param props Properties defined in a configuration section for this importer | [
"This",
"will",
"be",
"called",
"for",
"every",
"importer",
"configuration",
"section",
"for",
"this",
"importer",
"type",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/importer/ImporterLifeCycleManager.java#L85-L92 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/appservice/v2016_03_01/implementation/ResourceHealthMetadatasInner.java | ResourceHealthMetadatasInner.listBySiteSlotWithServiceResponseAsync | public Observable<ServiceResponse<Page<ResourceHealthMetadataInner>>> listBySiteSlotWithServiceResponseAsync(final String resourceGroupName, final String name, final String slot) {
"""
Gets the category of ResourceHealthMetadata to use for the given site as a collection.
Gets the category of ResourceHealthMetadata to use for the given site as a collection.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of web app.
@param slot Name of web app slot. If not specified then will default to production slot.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ResourceHealthMetadataInner> object
"""
return listBySiteSlotSinglePageAsync(resourceGroupName, name, slot)
.concatMap(new Func1<ServiceResponse<Page<ResourceHealthMetadataInner>>, Observable<ServiceResponse<Page<ResourceHealthMetadataInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ResourceHealthMetadataInner>>> call(ServiceResponse<Page<ResourceHealthMetadataInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listBySiteSlotNextWithServiceResponseAsync(nextPageLink));
}
});
} | java | public Observable<ServiceResponse<Page<ResourceHealthMetadataInner>>> listBySiteSlotWithServiceResponseAsync(final String resourceGroupName, final String name, final String slot) {
return listBySiteSlotSinglePageAsync(resourceGroupName, name, slot)
.concatMap(new Func1<ServiceResponse<Page<ResourceHealthMetadataInner>>, Observable<ServiceResponse<Page<ResourceHealthMetadataInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ResourceHealthMetadataInner>>> call(ServiceResponse<Page<ResourceHealthMetadataInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listBySiteSlotNextWithServiceResponseAsync(nextPageLink));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ResourceHealthMetadataInner",
">",
">",
">",
"listBySiteSlotWithServiceResponseAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"name",
",",
"final",
"String",
"slot",
")",
"{",
"return",
"listBySiteSlotSinglePageAsync",
"(",
"resourceGroupName",
",",
"name",
",",
"slot",
")",
".",
"concatMap",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ResourceHealthMetadataInner",
">",
">",
",",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ResourceHealthMetadataInner",
">",
">",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ResourceHealthMetadataInner",
">",
">",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"ResourceHealthMetadataInner",
">",
">",
"page",
")",
"{",
"String",
"nextPageLink",
"=",
"page",
".",
"body",
"(",
")",
".",
"nextPageLink",
"(",
")",
";",
"if",
"(",
"nextPageLink",
"==",
"null",
")",
"{",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
";",
"}",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
".",
"concatWith",
"(",
"listBySiteSlotNextWithServiceResponseAsync",
"(",
"nextPageLink",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] | Gets the category of ResourceHealthMetadata to use for the given site as a collection.
Gets the category of ResourceHealthMetadata to use for the given site as a collection.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of web app.
@param slot Name of web app slot. If not specified then will default to production slot.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ResourceHealthMetadataInner> object | [
"Gets",
"the",
"category",
"of",
"ResourceHealthMetadata",
"to",
"use",
"for",
"the",
"given",
"site",
"as",
"a",
"collection",
".",
"Gets",
"the",
"category",
"of",
"ResourceHealthMetadata",
"to",
"use",
"for",
"the",
"given",
"site",
"as",
"a",
"collection",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/appservice/v2016_03_01/implementation/ResourceHealthMetadatasInner.java#L628-L640 |
salesforce/Argus | ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/ManagementResources.java | ManagementResources.getWardenDashboard | @GET
@Path("/wardendashboard/ {
"""
Returns the warden dashboard for the user.
@param req The HTTP request.
@param userName The user name. Cannot be null or empty.
@return The dashboard object.
@throws IllegalArgumentException Throws IllegalArgument exception when the input is not valid.
@throws WebApplicationException Throws this exception if the user does not exist or the user is not authorized to carry out this operation.
"""username}")
@Produces(MediaType.APPLICATION_JSON)
@Description("Returns the warden dashboard for a user.")
public DashboardDto getWardenDashboard(@Context HttpServletRequest req,
@PathParam("username") String userName) {
if (userName == null || userName.isEmpty()) {
throw new IllegalArgumentException("User name cannot be null or empty.");
}
validatePrivilegedUser(req);
PrincipalUser user = userService.findUserByUsername(userName);
if (user == null) {
throw new WebApplicationException("User does not exist.", Status.NOT_FOUND);
}
return DashboardDto.transformToDto(managementService.getWardenDashboard(user));
} | java | @GET
@Path("/wardendashboard/{username}")
@Produces(MediaType.APPLICATION_JSON)
@Description("Returns the warden dashboard for a user.")
public DashboardDto getWardenDashboard(@Context HttpServletRequest req,
@PathParam("username") String userName) {
if (userName == null || userName.isEmpty()) {
throw new IllegalArgumentException("User name cannot be null or empty.");
}
validatePrivilegedUser(req);
PrincipalUser user = userService.findUserByUsername(userName);
if (user == null) {
throw new WebApplicationException("User does not exist.", Status.NOT_FOUND);
}
return DashboardDto.transformToDto(managementService.getWardenDashboard(user));
} | [
"@",
"GET",
"@",
"Path",
"(",
"\"/wardendashboard/{username}\"",
")",
"@",
"Produces",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Description",
"(",
"\"Returns the warden dashboard for a user.\"",
")",
"public",
"DashboardDto",
"getWardenDashboard",
"(",
"@",
"Context",
"HttpServletRequest",
"req",
",",
"@",
"PathParam",
"(",
"\"username\"",
")",
"String",
"userName",
")",
"{",
"if",
"(",
"userName",
"==",
"null",
"||",
"userName",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"User name cannot be null or empty.\"",
")",
";",
"}",
"validatePrivilegedUser",
"(",
"req",
")",
";",
"PrincipalUser",
"user",
"=",
"userService",
".",
"findUserByUsername",
"(",
"userName",
")",
";",
"if",
"(",
"user",
"==",
"null",
")",
"{",
"throw",
"new",
"WebApplicationException",
"(",
"\"User does not exist.\"",
",",
"Status",
".",
"NOT_FOUND",
")",
";",
"}",
"return",
"DashboardDto",
".",
"transformToDto",
"(",
"managementService",
".",
"getWardenDashboard",
"(",
"user",
")",
")",
";",
"}"
] | Returns the warden dashboard for the user.
@param req The HTTP request.
@param userName The user name. Cannot be null or empty.
@return The dashboard object.
@throws IllegalArgumentException Throws IllegalArgument exception when the input is not valid.
@throws WebApplicationException Throws this exception if the user does not exist or the user is not authorized to carry out this operation. | [
"Returns",
"the",
"warden",
"dashboard",
"for",
"the",
"user",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/ManagementResources.java#L333-L350 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.cdn_webstorage_serviceName_storage_duration_GET | public OvhOrder cdn_webstorage_serviceName_storage_duration_GET(String serviceName, String duration, OvhOrderStorageEnum storage) throws IOException {
"""
Get prices and contracts information
REST: GET /order/cdn/webstorage/{serviceName}/storage/{duration}
@param storage [required] Storage option that will be ordered
@param serviceName [required] The internal name of your CDN Static offer
@param duration [required] Duration
"""
String qPath = "/order/cdn/webstorage/{serviceName}/storage/{duration}";
StringBuilder sb = path(qPath, serviceName, duration);
query(sb, "storage", storage);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOrder.class);
} | java | public OvhOrder cdn_webstorage_serviceName_storage_duration_GET(String serviceName, String duration, OvhOrderStorageEnum storage) throws IOException {
String qPath = "/order/cdn/webstorage/{serviceName}/storage/{duration}";
StringBuilder sb = path(qPath, serviceName, duration);
query(sb, "storage", storage);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOrder.class);
} | [
"public",
"OvhOrder",
"cdn_webstorage_serviceName_storage_duration_GET",
"(",
"String",
"serviceName",
",",
"String",
"duration",
",",
"OvhOrderStorageEnum",
"storage",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/order/cdn/webstorage/{serviceName}/storage/{duration}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"duration",
")",
";",
"query",
"(",
"sb",
",",
"\"storage\"",
",",
"storage",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhOrder",
".",
"class",
")",
";",
"}"
] | Get prices and contracts information
REST: GET /order/cdn/webstorage/{serviceName}/storage/{duration}
@param storage [required] Storage option that will be ordered
@param serviceName [required] The internal name of your CDN Static offer
@param duration [required] Duration | [
"Get",
"prices",
"and",
"contracts",
"information"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L5482-L5488 |
alkacon/opencms-core | src/org/opencms/widgets/CmsCalendarWidget.java | CmsCalendarWidget.getCalendarDate | public static long getCalendarDate(CmsMessages messages, String dateString, boolean useTime) throws ParseException {
"""
Creates the time in milliseconds from the given parameter.<p>
@param messages the messages that contain the time format definitions
@param dateString the String representation of the date
@param useTime true if the time should be parsed, too, otherwise false
@return the time in milliseconds
@throws ParseException if something goes wrong
"""
long dateLong = 0;
// substitute some chars because calendar syntax != DateFormat syntax
String dateFormat = messages.key(org.opencms.workplace.Messages.GUI_CALENDAR_DATE_FORMAT_0);
if (useTime) {
dateFormat += " " + messages.key(org.opencms.workplace.Messages.GUI_CALENDAR_TIME_FORMAT_0);
}
dateFormat = CmsCalendarWidget.getCalendarJavaDateFormat(dateFormat);
SimpleDateFormat df = new SimpleDateFormat(dateFormat);
dateLong = df.parse(dateString).getTime();
return dateLong;
} | java | public static long getCalendarDate(CmsMessages messages, String dateString, boolean useTime) throws ParseException {
long dateLong = 0;
// substitute some chars because calendar syntax != DateFormat syntax
String dateFormat = messages.key(org.opencms.workplace.Messages.GUI_CALENDAR_DATE_FORMAT_0);
if (useTime) {
dateFormat += " " + messages.key(org.opencms.workplace.Messages.GUI_CALENDAR_TIME_FORMAT_0);
}
dateFormat = CmsCalendarWidget.getCalendarJavaDateFormat(dateFormat);
SimpleDateFormat df = new SimpleDateFormat(dateFormat);
dateLong = df.parse(dateString).getTime();
return dateLong;
} | [
"public",
"static",
"long",
"getCalendarDate",
"(",
"CmsMessages",
"messages",
",",
"String",
"dateString",
",",
"boolean",
"useTime",
")",
"throws",
"ParseException",
"{",
"long",
"dateLong",
"=",
"0",
";",
"// substitute some chars because calendar syntax != DateFormat syntax",
"String",
"dateFormat",
"=",
"messages",
".",
"key",
"(",
"org",
".",
"opencms",
".",
"workplace",
".",
"Messages",
".",
"GUI_CALENDAR_DATE_FORMAT_0",
")",
";",
"if",
"(",
"useTime",
")",
"{",
"dateFormat",
"+=",
"\" \"",
"+",
"messages",
".",
"key",
"(",
"org",
".",
"opencms",
".",
"workplace",
".",
"Messages",
".",
"GUI_CALENDAR_TIME_FORMAT_0",
")",
";",
"}",
"dateFormat",
"=",
"CmsCalendarWidget",
".",
"getCalendarJavaDateFormat",
"(",
"dateFormat",
")",
";",
"SimpleDateFormat",
"df",
"=",
"new",
"SimpleDateFormat",
"(",
"dateFormat",
")",
";",
"dateLong",
"=",
"df",
".",
"parse",
"(",
"dateString",
")",
".",
"getTime",
"(",
")",
";",
"return",
"dateLong",
";",
"}"
] | Creates the time in milliseconds from the given parameter.<p>
@param messages the messages that contain the time format definitions
@param dateString the String representation of the date
@param useTime true if the time should be parsed, too, otherwise false
@return the time in milliseconds
@throws ParseException if something goes wrong | [
"Creates",
"the",
"time",
"in",
"milliseconds",
"from",
"the",
"given",
"parameter",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/widgets/CmsCalendarWidget.java#L217-L231 |
hdbeukel/james-core | src/main/java/org/jamesframework/core/search/Search.java | Search.updateBestSolution | protected boolean updateBestSolution(SolutionType newSolution,
Evaluation newSolutionEvaluation,
Validation newSolutionValidation) {
"""
<p>
Checks whether a new best solution has been found and updates it accordingly,
given that the solution has already been evaluated and validated. The best
solution is updated only if the presented solution is valid and
</p>
<ul>
<li>no best solution had been set before, or</li>
<li>the new solution has a better evaluation</li>
</ul>
<p>
If the new solution is invalid or has a worse evaluation than the current best
solution, calling this method has no effect. Note that the best solution is
<b>retained</b> across subsequent runs of the same search.
</p>
@param newSolution newly presented solution
@param newSolutionEvaluation evaluation of given solution
@param newSolutionValidation validation of given solution
@return <code>true</code> if the given solution is accepted as the new best solution
"""
// check: valid solution
if(newSolutionValidation.passed()){
// check: improvement or no best solution set
Double delta = null;
if(bestSolution == null
|| (delta = computeDelta(newSolutionEvaluation, getBestSolutionEvaluation())) > 0){
// flag improvement
improvementDuringCurrentStep = true;
// store last improvement time
lastImprovementTime = System.currentTimeMillis();
// update minimum delta if applicable (only if first delta or smaller than current minimum delta)
if(delta != null && (minDelta == JamesConstants.INVALID_DELTA || delta < minDelta)){
minDelta = delta;
}
// update best solution (create copy!)
bestSolution = Solution.checkedCopy(newSolution);
bestSolutionEvaluation = newSolutionEvaluation;
bestSolutionValidation = newSolutionValidation;
// fire callback
fireNewBestSolution(bestSolution, bestSolutionEvaluation, bestSolutionValidation);
// found improvement
return true;
} else {
// no improvement
return false;
}
} else {
// invalid solution
return false;
}
} | java | protected boolean updateBestSolution(SolutionType newSolution,
Evaluation newSolutionEvaluation,
Validation newSolutionValidation){
// check: valid solution
if(newSolutionValidation.passed()){
// check: improvement or no best solution set
Double delta = null;
if(bestSolution == null
|| (delta = computeDelta(newSolutionEvaluation, getBestSolutionEvaluation())) > 0){
// flag improvement
improvementDuringCurrentStep = true;
// store last improvement time
lastImprovementTime = System.currentTimeMillis();
// update minimum delta if applicable (only if first delta or smaller than current minimum delta)
if(delta != null && (minDelta == JamesConstants.INVALID_DELTA || delta < minDelta)){
minDelta = delta;
}
// update best solution (create copy!)
bestSolution = Solution.checkedCopy(newSolution);
bestSolutionEvaluation = newSolutionEvaluation;
bestSolutionValidation = newSolutionValidation;
// fire callback
fireNewBestSolution(bestSolution, bestSolutionEvaluation, bestSolutionValidation);
// found improvement
return true;
} else {
// no improvement
return false;
}
} else {
// invalid solution
return false;
}
} | [
"protected",
"boolean",
"updateBestSolution",
"(",
"SolutionType",
"newSolution",
",",
"Evaluation",
"newSolutionEvaluation",
",",
"Validation",
"newSolutionValidation",
")",
"{",
"// check: valid solution",
"if",
"(",
"newSolutionValidation",
".",
"passed",
"(",
")",
")",
"{",
"// check: improvement or no best solution set",
"Double",
"delta",
"=",
"null",
";",
"if",
"(",
"bestSolution",
"==",
"null",
"||",
"(",
"delta",
"=",
"computeDelta",
"(",
"newSolutionEvaluation",
",",
"getBestSolutionEvaluation",
"(",
")",
")",
")",
">",
"0",
")",
"{",
"// flag improvement",
"improvementDuringCurrentStep",
"=",
"true",
";",
"// store last improvement time",
"lastImprovementTime",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"// update minimum delta if applicable (only if first delta or smaller than current minimum delta)",
"if",
"(",
"delta",
"!=",
"null",
"&&",
"(",
"minDelta",
"==",
"JamesConstants",
".",
"INVALID_DELTA",
"||",
"delta",
"<",
"minDelta",
")",
")",
"{",
"minDelta",
"=",
"delta",
";",
"}",
"// update best solution (create copy!)",
"bestSolution",
"=",
"Solution",
".",
"checkedCopy",
"(",
"newSolution",
")",
";",
"bestSolutionEvaluation",
"=",
"newSolutionEvaluation",
";",
"bestSolutionValidation",
"=",
"newSolutionValidation",
";",
"// fire callback",
"fireNewBestSolution",
"(",
"bestSolution",
",",
"bestSolutionEvaluation",
",",
"bestSolutionValidation",
")",
";",
"// found improvement",
"return",
"true",
";",
"}",
"else",
"{",
"// no improvement",
"return",
"false",
";",
"}",
"}",
"else",
"{",
"// invalid solution",
"return",
"false",
";",
"}",
"}"
] | <p>
Checks whether a new best solution has been found and updates it accordingly,
given that the solution has already been evaluated and validated. The best
solution is updated only if the presented solution is valid and
</p>
<ul>
<li>no best solution had been set before, or</li>
<li>the new solution has a better evaluation</li>
</ul>
<p>
If the new solution is invalid or has a worse evaluation than the current best
solution, calling this method has no effect. Note that the best solution is
<b>retained</b> across subsequent runs of the same search.
</p>
@param newSolution newly presented solution
@param newSolutionEvaluation evaluation of given solution
@param newSolutionValidation validation of given solution
@return <code>true</code> if the given solution is accepted as the new best solution | [
"<p",
">",
"Checks",
"whether",
"a",
"new",
"best",
"solution",
"has",
"been",
"found",
"and",
"updates",
"it",
"accordingly",
"given",
"that",
"the",
"solution",
"has",
"already",
"been",
"evaluated",
"and",
"validated",
".",
"The",
"best",
"solution",
"is",
"updated",
"only",
"if",
"the",
"presented",
"solution",
"is",
"valid",
"and",
"<",
"/",
"p",
">",
"<ul",
">",
"<li",
">",
"no",
"best",
"solution",
"had",
"been",
"set",
"before",
"or<",
"/",
"li",
">",
"<li",
">",
"the",
"new",
"solution",
"has",
"a",
"better",
"evaluation<",
"/",
"li",
">",
"<",
"/",
"ul",
">",
"<p",
">",
"If",
"the",
"new",
"solution",
"is",
"invalid",
"or",
"has",
"a",
"worse",
"evaluation",
"than",
"the",
"current",
"best",
"solution",
"calling",
"this",
"method",
"has",
"no",
"effect",
".",
"Note",
"that",
"the",
"best",
"solution",
"is",
"<b",
">",
"retained<",
"/",
"b",
">",
"across",
"subsequent",
"runs",
"of",
"the",
"same",
"search",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/hdbeukel/james-core/blob/4e85c20c142902373e5b5e8b5d12a2558650f66d/src/main/java/org/jamesframework/core/search/Search.java#L888-L921 |
Stratio/stratio-cassandra | src/java/com/stratio/cassandra/index/query/Search.java | Search.fromJson | public static Search fromJson(String json) {
"""
Returns a new {@link Search} from the specified JSON {@code String}.
@param json A JSON {@code String} representing a {@link Search}.
@return The {@link Search} represented by the specified JSON {@code String}.
"""
try {
return JsonSerializer.fromString(json, Search.class);
} catch (Exception e) {
String message = String.format("Unparseable JSON search: %s", e.getMessage());
Log.error(e, message);
throw new IllegalArgumentException(message, e);
}
} | java | public static Search fromJson(String json) {
try {
return JsonSerializer.fromString(json, Search.class);
} catch (Exception e) {
String message = String.format("Unparseable JSON search: %s", e.getMessage());
Log.error(e, message);
throw new IllegalArgumentException(message, e);
}
} | [
"public",
"static",
"Search",
"fromJson",
"(",
"String",
"json",
")",
"{",
"try",
"{",
"return",
"JsonSerializer",
".",
"fromString",
"(",
"json",
",",
"Search",
".",
"class",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"String",
"message",
"=",
"String",
".",
"format",
"(",
"\"Unparseable JSON search: %s\"",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"Log",
".",
"error",
"(",
"e",
",",
"message",
")",
";",
"throw",
"new",
"IllegalArgumentException",
"(",
"message",
",",
"e",
")",
";",
"}",
"}"
] | Returns a new {@link Search} from the specified JSON {@code String}.
@param json A JSON {@code String} representing a {@link Search}.
@return The {@link Search} represented by the specified JSON {@code String}. | [
"Returns",
"a",
"new",
"{",
"@link",
"Search",
"}",
"from",
"the",
"specified",
"JSON",
"{",
"@code",
"String",
"}",
"."
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/query/Search.java#L73-L81 |
apache/incubator-druid | core/src/main/java/org/apache/druid/java/util/common/StringUtils.java | StringUtils.nonStrictFormat | public static String nonStrictFormat(String message, Object... formatArgs) {
"""
Formats the string as {@link #format(String, Object...)}, but instead of failing on illegal format, returns the
concatenated format string and format arguments. Should be used for unimportant formatting like logging,
exception messages, typically not directly.
"""
if (formatArgs == null || formatArgs.length == 0) {
return message;
}
try {
return String.format(Locale.ENGLISH, message, formatArgs);
}
catch (IllegalFormatException e) {
StringBuilder bob = new StringBuilder(message);
for (Object formatArg : formatArgs) {
bob.append("; ").append(formatArg);
}
return bob.toString();
}
} | java | public static String nonStrictFormat(String message, Object... formatArgs)
{
if (formatArgs == null || formatArgs.length == 0) {
return message;
}
try {
return String.format(Locale.ENGLISH, message, formatArgs);
}
catch (IllegalFormatException e) {
StringBuilder bob = new StringBuilder(message);
for (Object formatArg : formatArgs) {
bob.append("; ").append(formatArg);
}
return bob.toString();
}
} | [
"public",
"static",
"String",
"nonStrictFormat",
"(",
"String",
"message",
",",
"Object",
"...",
"formatArgs",
")",
"{",
"if",
"(",
"formatArgs",
"==",
"null",
"||",
"formatArgs",
".",
"length",
"==",
"0",
")",
"{",
"return",
"message",
";",
"}",
"try",
"{",
"return",
"String",
".",
"format",
"(",
"Locale",
".",
"ENGLISH",
",",
"message",
",",
"formatArgs",
")",
";",
"}",
"catch",
"(",
"IllegalFormatException",
"e",
")",
"{",
"StringBuilder",
"bob",
"=",
"new",
"StringBuilder",
"(",
"message",
")",
";",
"for",
"(",
"Object",
"formatArg",
":",
"formatArgs",
")",
"{",
"bob",
".",
"append",
"(",
"\"; \"",
")",
".",
"append",
"(",
"formatArg",
")",
";",
"}",
"return",
"bob",
".",
"toString",
"(",
")",
";",
"}",
"}"
] | Formats the string as {@link #format(String, Object...)}, but instead of failing on illegal format, returns the
concatenated format string and format arguments. Should be used for unimportant formatting like logging,
exception messages, typically not directly. | [
"Formats",
"the",
"string",
"as",
"{"
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/core/src/main/java/org/apache/druid/java/util/common/StringUtils.java#L132-L147 |
kuujo/vertigo | core/src/main/java/net/kuujo/vertigo/network/manager/NetworkManager.java | NetworkManager.deployModule | private void deployModule(final Node node, final InstanceContext instance, final CountingCompletionHandler<Void> counter) {
"""
Deploys a module component instance in the network's cluster.
"""
log.debug(String.format("%s - Deploying %s to %s", NetworkManager.this, instance.component().asModule().module(), node.address()));
node.deployModule(instance.component().asModule().module(), Components.buildConfig(instance, cluster), 1, new Handler<AsyncResult<String>>() {
@Override
public void handle(AsyncResult<String> result) {
if (result.failed()) {
counter.fail(result.cause());
} else {
deploymentIDs.put(instance.address(), result.result(), new Handler<AsyncResult<String>>() {
@Override
public void handle(AsyncResult<String> result) {
counter.succeed();
}
});
}
}
});
} | java | private void deployModule(final Node node, final InstanceContext instance, final CountingCompletionHandler<Void> counter) {
log.debug(String.format("%s - Deploying %s to %s", NetworkManager.this, instance.component().asModule().module(), node.address()));
node.deployModule(instance.component().asModule().module(), Components.buildConfig(instance, cluster), 1, new Handler<AsyncResult<String>>() {
@Override
public void handle(AsyncResult<String> result) {
if (result.failed()) {
counter.fail(result.cause());
} else {
deploymentIDs.put(instance.address(), result.result(), new Handler<AsyncResult<String>>() {
@Override
public void handle(AsyncResult<String> result) {
counter.succeed();
}
});
}
}
});
} | [
"private",
"void",
"deployModule",
"(",
"final",
"Node",
"node",
",",
"final",
"InstanceContext",
"instance",
",",
"final",
"CountingCompletionHandler",
"<",
"Void",
">",
"counter",
")",
"{",
"log",
".",
"debug",
"(",
"String",
".",
"format",
"(",
"\"%s - Deploying %s to %s\"",
",",
"NetworkManager",
".",
"this",
",",
"instance",
".",
"component",
"(",
")",
".",
"asModule",
"(",
")",
".",
"module",
"(",
")",
",",
"node",
".",
"address",
"(",
")",
")",
")",
";",
"node",
".",
"deployModule",
"(",
"instance",
".",
"component",
"(",
")",
".",
"asModule",
"(",
")",
".",
"module",
"(",
")",
",",
"Components",
".",
"buildConfig",
"(",
"instance",
",",
"cluster",
")",
",",
"1",
",",
"new",
"Handler",
"<",
"AsyncResult",
"<",
"String",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"handle",
"(",
"AsyncResult",
"<",
"String",
">",
"result",
")",
"{",
"if",
"(",
"result",
".",
"failed",
"(",
")",
")",
"{",
"counter",
".",
"fail",
"(",
"result",
".",
"cause",
"(",
")",
")",
";",
"}",
"else",
"{",
"deploymentIDs",
".",
"put",
"(",
"instance",
".",
"address",
"(",
")",
",",
"result",
".",
"result",
"(",
")",
",",
"new",
"Handler",
"<",
"AsyncResult",
"<",
"String",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"handle",
"(",
"AsyncResult",
"<",
"String",
">",
"result",
")",
"{",
"counter",
".",
"succeed",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | Deploys a module component instance in the network's cluster. | [
"Deploys",
"a",
"module",
"component",
"instance",
"in",
"the",
"network",
"s",
"cluster",
"."
] | train | https://github.com/kuujo/vertigo/blob/c5869dbc5fff89eb5262e83f7a81719b01a5ba6f/core/src/main/java/net/kuujo/vertigo/network/manager/NetworkManager.java#L833-L850 |
contentful/contentful.java | src/main/java/com/contentful/java/cda/rich/RichTextFactory.java | RichTextFactory.resolveRichLink | private static void resolveRichLink(ArrayResource array, CDAEntry entry, CDAField field) {
"""
Resolve all links if possible. If linked to entry is not found, null it's field.
@param array the array containing the complete response
@param entry the entry to be completed.
@param field the field pointing to a link.
"""
final Map<String, Object> rawValue = (Map<String, Object>) entry.rawFields().get(field.id());
if (rawValue == null) {
return;
}
for (final String locale : rawValue.keySet()) {
final CDARichDocument document = entry.getField(locale, field.id());
for (final CDARichNode node : document.getContent()) {
resolveOneLink(array, field, locale, node);
}
}
} | java | private static void resolveRichLink(ArrayResource array, CDAEntry entry, CDAField field) {
final Map<String, Object> rawValue = (Map<String, Object>) entry.rawFields().get(field.id());
if (rawValue == null) {
return;
}
for (final String locale : rawValue.keySet()) {
final CDARichDocument document = entry.getField(locale, field.id());
for (final CDARichNode node : document.getContent()) {
resolveOneLink(array, field, locale, node);
}
}
} | [
"private",
"static",
"void",
"resolveRichLink",
"(",
"ArrayResource",
"array",
",",
"CDAEntry",
"entry",
",",
"CDAField",
"field",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"rawValue",
"=",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
")",
"entry",
".",
"rawFields",
"(",
")",
".",
"get",
"(",
"field",
".",
"id",
"(",
")",
")",
";",
"if",
"(",
"rawValue",
"==",
"null",
")",
"{",
"return",
";",
"}",
"for",
"(",
"final",
"String",
"locale",
":",
"rawValue",
".",
"keySet",
"(",
")",
")",
"{",
"final",
"CDARichDocument",
"document",
"=",
"entry",
".",
"getField",
"(",
"locale",
",",
"field",
".",
"id",
"(",
")",
")",
";",
"for",
"(",
"final",
"CDARichNode",
"node",
":",
"document",
".",
"getContent",
"(",
")",
")",
"{",
"resolveOneLink",
"(",
"array",
",",
"field",
",",
"locale",
",",
"node",
")",
";",
"}",
"}",
"}"
] | Resolve all links if possible. If linked to entry is not found, null it's field.
@param array the array containing the complete response
@param entry the entry to be completed.
@param field the field pointing to a link. | [
"Resolve",
"all",
"links",
"if",
"possible",
".",
"If",
"linked",
"to",
"entry",
"is",
"not",
"found",
"null",
"it",
"s",
"field",
"."
] | train | https://github.com/contentful/contentful.java/blob/6ecc2ace454c674b218b99489dc50697b1dbffcb/src/main/java/com/contentful/java/cda/rich/RichTextFactory.java#L350-L362 |
samskivert/samskivert | src/main/java/com/samskivert/swing/RadialMenu.java | RadialMenu.addMenuItem | public RadialMenuItem addMenuItem (String command, String label, Image icon, Predicate predicate) {
"""
Adds a menu item to the menu. The menu should not currently be active.
@param command the command to be issued when the item is selected.
@param label the textual label to be displayed with the menu item.
@param icon the icon to display next to the menu text or null if no
icon is desired.
@param predicate a predicate that will be used to determine whether or not this menu item
should be included in the menu and enabled when it is shown.
@return the item that was added to the menu. It can be modified while the menu is not being
displayed.
"""
RadialMenuItem item = new RadialMenuItem(command, label, new ImageIcon(icon), predicate);
addMenuItem(item);
return item;
} | java | public RadialMenuItem addMenuItem (String command, String label, Image icon, Predicate predicate)
{
RadialMenuItem item = new RadialMenuItem(command, label, new ImageIcon(icon), predicate);
addMenuItem(item);
return item;
} | [
"public",
"RadialMenuItem",
"addMenuItem",
"(",
"String",
"command",
",",
"String",
"label",
",",
"Image",
"icon",
",",
"Predicate",
"predicate",
")",
"{",
"RadialMenuItem",
"item",
"=",
"new",
"RadialMenuItem",
"(",
"command",
",",
"label",
",",
"new",
"ImageIcon",
"(",
"icon",
")",
",",
"predicate",
")",
";",
"addMenuItem",
"(",
"item",
")",
";",
"return",
"item",
";",
"}"
] | Adds a menu item to the menu. The menu should not currently be active.
@param command the command to be issued when the item is selected.
@param label the textual label to be displayed with the menu item.
@param icon the icon to display next to the menu text or null if no
icon is desired.
@param predicate a predicate that will be used to determine whether or not this menu item
should be included in the menu and enabled when it is shown.
@return the item that was added to the menu. It can be modified while the menu is not being
displayed. | [
"Adds",
"a",
"menu",
"item",
"to",
"the",
"menu",
".",
"The",
"menu",
"should",
"not",
"currently",
"be",
"active",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/RadialMenu.java#L123-L128 |
stratosphere/stratosphere | stratosphere-runtime/src/main/java/eu/stratosphere/nephele/jobgraph/JobGraph.java | JobGraph.collectVertices | private void collectVertices(final AbstractJobVertex jv, final List<AbstractJobVertex> collector) {
"""
Auxiliary method to collect all vertices which are reachable from the input vertices.
@param jv
the currently considered job vertex
@param collector
a temporary list to store the vertices that have already been visisted
"""
if (jv == null) {
final Iterator<AbstractJobInputVertex> iter = getInputVertices();
while (iter.hasNext()) {
collectVertices(iter.next(), collector);
}
} else {
if (!collector.contains(jv)) {
collector.add(jv);
} else {
return;
}
for (int i = 0; i < jv.getNumberOfForwardConnections(); i++) {
collectVertices(jv.getForwardConnection(i).getConnectedVertex(), collector);
}
}
} | java | private void collectVertices(final AbstractJobVertex jv, final List<AbstractJobVertex> collector) {
if (jv == null) {
final Iterator<AbstractJobInputVertex> iter = getInputVertices();
while (iter.hasNext()) {
collectVertices(iter.next(), collector);
}
} else {
if (!collector.contains(jv)) {
collector.add(jv);
} else {
return;
}
for (int i = 0; i < jv.getNumberOfForwardConnections(); i++) {
collectVertices(jv.getForwardConnection(i).getConnectedVertex(), collector);
}
}
} | [
"private",
"void",
"collectVertices",
"(",
"final",
"AbstractJobVertex",
"jv",
",",
"final",
"List",
"<",
"AbstractJobVertex",
">",
"collector",
")",
"{",
"if",
"(",
"jv",
"==",
"null",
")",
"{",
"final",
"Iterator",
"<",
"AbstractJobInputVertex",
">",
"iter",
"=",
"getInputVertices",
"(",
")",
";",
"while",
"(",
"iter",
".",
"hasNext",
"(",
")",
")",
"{",
"collectVertices",
"(",
"iter",
".",
"next",
"(",
")",
",",
"collector",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"!",
"collector",
".",
"contains",
"(",
"jv",
")",
")",
"{",
"collector",
".",
"add",
"(",
"jv",
")",
";",
"}",
"else",
"{",
"return",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"jv",
".",
"getNumberOfForwardConnections",
"(",
")",
";",
"i",
"++",
")",
"{",
"collectVertices",
"(",
"jv",
".",
"getForwardConnection",
"(",
"i",
")",
".",
"getConnectedVertex",
"(",
")",
",",
"collector",
")",
";",
"}",
"}",
"}"
] | Auxiliary method to collect all vertices which are reachable from the input vertices.
@param jv
the currently considered job vertex
@param collector
a temporary list to store the vertices that have already been visisted | [
"Auxiliary",
"method",
"to",
"collect",
"all",
"vertices",
"which",
"are",
"reachable",
"from",
"the",
"input",
"vertices",
"."
] | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/jobgraph/JobGraph.java#L304-L323 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-component/xwiki-commons-component-api/src/main/java/org/xwiki/component/util/ReflectionUtils.java | ReflectionUtils.resolveType | public static Type resolveType(Type targetType, Type rootType) {
"""
Find and replace the generic parameters with the real types.
@param targetType the type for which to resolve the parameters
@param rootType an extending class as Type
@return the Type with resolved parameters
"""
Type resolvedType;
if (targetType instanceof ParameterizedType && rootType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) targetType;
resolvedType =
resolveType((Class<?>) parameterizedType.getRawType(), parameterizedType.getActualTypeArguments(),
getTypeClass(rootType));
} else {
resolvedType = resolveType(getTypeClass(rootType), null, getTypeClass(targetType));
}
return resolvedType;
} | java | public static Type resolveType(Type targetType, Type rootType)
{
Type resolvedType;
if (targetType instanceof ParameterizedType && rootType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) targetType;
resolvedType =
resolveType((Class<?>) parameterizedType.getRawType(), parameterizedType.getActualTypeArguments(),
getTypeClass(rootType));
} else {
resolvedType = resolveType(getTypeClass(rootType), null, getTypeClass(targetType));
}
return resolvedType;
} | [
"public",
"static",
"Type",
"resolveType",
"(",
"Type",
"targetType",
",",
"Type",
"rootType",
")",
"{",
"Type",
"resolvedType",
";",
"if",
"(",
"targetType",
"instanceof",
"ParameterizedType",
"&&",
"rootType",
"instanceof",
"ParameterizedType",
")",
"{",
"ParameterizedType",
"parameterizedType",
"=",
"(",
"ParameterizedType",
")",
"targetType",
";",
"resolvedType",
"=",
"resolveType",
"(",
"(",
"Class",
"<",
"?",
">",
")",
"parameterizedType",
".",
"getRawType",
"(",
")",
",",
"parameterizedType",
".",
"getActualTypeArguments",
"(",
")",
",",
"getTypeClass",
"(",
"rootType",
")",
")",
";",
"}",
"else",
"{",
"resolvedType",
"=",
"resolveType",
"(",
"getTypeClass",
"(",
"rootType",
")",
",",
"null",
",",
"getTypeClass",
"(",
"targetType",
")",
")",
";",
"}",
"return",
"resolvedType",
";",
"}"
] | Find and replace the generic parameters with the real types.
@param targetType the type for which to resolve the parameters
@param rootType an extending class as Type
@return the Type with resolved parameters | [
"Find",
"and",
"replace",
"the",
"generic",
"parameters",
"with",
"the",
"real",
"types",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-component/xwiki-commons-component-api/src/main/java/org/xwiki/component/util/ReflectionUtils.java#L399-L414 |
jenkinsci/jenkins | core/src/main/java/hudson/slaves/Channels.java | Channels.forProcess | public static Channel forProcess(String name, ExecutorService execService, InputStream in, OutputStream out, OutputStream header, final Proc proc) throws IOException {
"""
Creates a channel that wraps a remote process, so that when we shut down the connection
we kill the process.
"""
ChannelBuilder cb = new ChannelBuilder(name,execService) {
@Override
public Channel build(CommandTransport transport) throws IOException {
return new Channel(this,transport) {
/**
* Kill the process when the channel is severed.
*/
@Override
public synchronized void terminate(IOException e) {
super.terminate(e);
try {
proc.kill();
} catch (IOException x) {
// we are already in the error recovery mode, so just record it and move on
LOGGER.log(Level.INFO, "Failed to terminate the severed connection",x);
} catch (InterruptedException x) {
// process the interrupt later
Thread.currentThread().interrupt();
}
}
@Override
public synchronized void join() throws InterruptedException {
super.join();
// wait for the child process to complete, too
try {
proc.join();
} catch (IOException e) {
throw new IOError(e);
}
}
};
}
};
cb.withHeaderStream(header);
for (ChannelConfigurator cc : ChannelConfigurator.all()) {
cc.onChannelBuilding(cb,null); // TODO: what to pass as a context?
}
return cb.build(in,out);
} | java | public static Channel forProcess(String name, ExecutorService execService, InputStream in, OutputStream out, OutputStream header, final Proc proc) throws IOException {
ChannelBuilder cb = new ChannelBuilder(name,execService) {
@Override
public Channel build(CommandTransport transport) throws IOException {
return new Channel(this,transport) {
/**
* Kill the process when the channel is severed.
*/
@Override
public synchronized void terminate(IOException e) {
super.terminate(e);
try {
proc.kill();
} catch (IOException x) {
// we are already in the error recovery mode, so just record it and move on
LOGGER.log(Level.INFO, "Failed to terminate the severed connection",x);
} catch (InterruptedException x) {
// process the interrupt later
Thread.currentThread().interrupt();
}
}
@Override
public synchronized void join() throws InterruptedException {
super.join();
// wait for the child process to complete, too
try {
proc.join();
} catch (IOException e) {
throw new IOError(e);
}
}
};
}
};
cb.withHeaderStream(header);
for (ChannelConfigurator cc : ChannelConfigurator.all()) {
cc.onChannelBuilding(cb,null); // TODO: what to pass as a context?
}
return cb.build(in,out);
} | [
"public",
"static",
"Channel",
"forProcess",
"(",
"String",
"name",
",",
"ExecutorService",
"execService",
",",
"InputStream",
"in",
",",
"OutputStream",
"out",
",",
"OutputStream",
"header",
",",
"final",
"Proc",
"proc",
")",
"throws",
"IOException",
"{",
"ChannelBuilder",
"cb",
"=",
"new",
"ChannelBuilder",
"(",
"name",
",",
"execService",
")",
"{",
"@",
"Override",
"public",
"Channel",
"build",
"(",
"CommandTransport",
"transport",
")",
"throws",
"IOException",
"{",
"return",
"new",
"Channel",
"(",
"this",
",",
"transport",
")",
"{",
"/**\n * Kill the process when the channel is severed.\n */",
"@",
"Override",
"public",
"synchronized",
"void",
"terminate",
"(",
"IOException",
"e",
")",
"{",
"super",
".",
"terminate",
"(",
"e",
")",
";",
"try",
"{",
"proc",
".",
"kill",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"x",
")",
"{",
"// we are already in the error recovery mode, so just record it and move on",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"INFO",
",",
"\"Failed to terminate the severed connection\"",
",",
"x",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"x",
")",
"{",
"// process the interrupt later",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"synchronized",
"void",
"join",
"(",
")",
"throws",
"InterruptedException",
"{",
"super",
".",
"join",
"(",
")",
";",
"// wait for the child process to complete, too",
"try",
"{",
"proc",
".",
"join",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"IOError",
"(",
"e",
")",
";",
"}",
"}",
"}",
";",
"}",
"}",
";",
"cb",
".",
"withHeaderStream",
"(",
"header",
")",
";",
"for",
"(",
"ChannelConfigurator",
"cc",
":",
"ChannelConfigurator",
".",
"all",
"(",
")",
")",
"{",
"cc",
".",
"onChannelBuilding",
"(",
"cb",
",",
"null",
")",
";",
"// TODO: what to pass as a context?",
"}",
"return",
"cb",
".",
"build",
"(",
"in",
",",
"out",
")",
";",
"}"
] | Creates a channel that wraps a remote process, so that when we shut down the connection
we kill the process. | [
"Creates",
"a",
"channel",
"that",
"wraps",
"a",
"remote",
"process",
"so",
"that",
"when",
"we",
"shut",
"down",
"the",
"connection",
"we",
"kill",
"the",
"process",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/slaves/Channels.java#L75-L117 |
datacleaner/DataCleaner | engine/core/src/main/java/org/datacleaner/result/renderer/RendererFactory.java | RendererFactory.isRendererMatch | private RendererSelection isRendererMatch(final RendererBeanDescriptor<?> rendererDescriptor,
final Renderable renderable, final RendererSelection bestMatch) {
"""
Checks if a particular renderer (descriptor) is a good match for a
particular renderer.
@param rendererDescriptor
the renderer (descriptor) to check.
@param renderable
the renderable that needs rendering.
@param bestMatchingDescriptor
the currently "best matching" renderer (descriptor), or null
if no other renderers matches yet.
@return a {@link RendererSelection} object if the renderer is a match, or
null if not.
"""
final Class<? extends Renderable> renderableType = rendererDescriptor.getRenderableType();
final Class<? extends Renderable> renderableClass = renderable.getClass();
if (ReflectionUtils.is(renderableClass, renderableType)) {
if (bestMatch == null) {
return isRendererCapable(rendererDescriptor, renderable, bestMatch);
} else {
final int hierarchyDistance;
try {
hierarchyDistance = ReflectionUtils.getHierarchyDistance(renderableClass, renderableType);
} catch (final IllegalArgumentException e) {
logger.warn(
"Failed to determine hierarchy distance between renderable type '{}' and renderable of class '{}'",
renderableType, renderableClass, e);
return null;
}
if (hierarchyDistance == 0) {
// no hierarchy distance
return isRendererCapable(rendererDescriptor, renderable, bestMatch);
}
if (hierarchyDistance <= bestMatch.getHierarchyDistance()) {
// lower hierarchy distance than best match
return isRendererCapable(rendererDescriptor, renderable, bestMatch);
}
}
}
return null;
} | java | private RendererSelection isRendererMatch(final RendererBeanDescriptor<?> rendererDescriptor,
final Renderable renderable, final RendererSelection bestMatch) {
final Class<? extends Renderable> renderableType = rendererDescriptor.getRenderableType();
final Class<? extends Renderable> renderableClass = renderable.getClass();
if (ReflectionUtils.is(renderableClass, renderableType)) {
if (bestMatch == null) {
return isRendererCapable(rendererDescriptor, renderable, bestMatch);
} else {
final int hierarchyDistance;
try {
hierarchyDistance = ReflectionUtils.getHierarchyDistance(renderableClass, renderableType);
} catch (final IllegalArgumentException e) {
logger.warn(
"Failed to determine hierarchy distance between renderable type '{}' and renderable of class '{}'",
renderableType, renderableClass, e);
return null;
}
if (hierarchyDistance == 0) {
// no hierarchy distance
return isRendererCapable(rendererDescriptor, renderable, bestMatch);
}
if (hierarchyDistance <= bestMatch.getHierarchyDistance()) {
// lower hierarchy distance than best match
return isRendererCapable(rendererDescriptor, renderable, bestMatch);
}
}
}
return null;
} | [
"private",
"RendererSelection",
"isRendererMatch",
"(",
"final",
"RendererBeanDescriptor",
"<",
"?",
">",
"rendererDescriptor",
",",
"final",
"Renderable",
"renderable",
",",
"final",
"RendererSelection",
"bestMatch",
")",
"{",
"final",
"Class",
"<",
"?",
"extends",
"Renderable",
">",
"renderableType",
"=",
"rendererDescriptor",
".",
"getRenderableType",
"(",
")",
";",
"final",
"Class",
"<",
"?",
"extends",
"Renderable",
">",
"renderableClass",
"=",
"renderable",
".",
"getClass",
"(",
")",
";",
"if",
"(",
"ReflectionUtils",
".",
"is",
"(",
"renderableClass",
",",
"renderableType",
")",
")",
"{",
"if",
"(",
"bestMatch",
"==",
"null",
")",
"{",
"return",
"isRendererCapable",
"(",
"rendererDescriptor",
",",
"renderable",
",",
"bestMatch",
")",
";",
"}",
"else",
"{",
"final",
"int",
"hierarchyDistance",
";",
"try",
"{",
"hierarchyDistance",
"=",
"ReflectionUtils",
".",
"getHierarchyDistance",
"(",
"renderableClass",
",",
"renderableType",
")",
";",
"}",
"catch",
"(",
"final",
"IllegalArgumentException",
"e",
")",
"{",
"logger",
".",
"warn",
"(",
"\"Failed to determine hierarchy distance between renderable type '{}' and renderable of class '{}'\"",
",",
"renderableType",
",",
"renderableClass",
",",
"e",
")",
";",
"return",
"null",
";",
"}",
"if",
"(",
"hierarchyDistance",
"==",
"0",
")",
"{",
"// no hierarchy distance",
"return",
"isRendererCapable",
"(",
"rendererDescriptor",
",",
"renderable",
",",
"bestMatch",
")",
";",
"}",
"if",
"(",
"hierarchyDistance",
"<=",
"bestMatch",
".",
"getHierarchyDistance",
"(",
")",
")",
"{",
"// lower hierarchy distance than best match",
"return",
"isRendererCapable",
"(",
"rendererDescriptor",
",",
"renderable",
",",
"bestMatch",
")",
";",
"}",
"}",
"}",
"return",
"null",
";",
"}"
] | Checks if a particular renderer (descriptor) is a good match for a
particular renderer.
@param rendererDescriptor
the renderer (descriptor) to check.
@param renderable
the renderable that needs rendering.
@param bestMatchingDescriptor
the currently "best matching" renderer (descriptor), or null
if no other renderers matches yet.
@return a {@link RendererSelection} object if the renderer is a match, or
null if not. | [
"Checks",
"if",
"a",
"particular",
"renderer",
"(",
"descriptor",
")",
"is",
"a",
"good",
"match",
"for",
"a",
"particular",
"renderer",
"."
] | train | https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/core/src/main/java/org/datacleaner/result/renderer/RendererFactory.java#L182-L213 |
google/closure-compiler | src/com/google/javascript/jscomp/NodeUtil.java | NodeUtil.deleteFunctionCall | public static void deleteFunctionCall(Node n, AbstractCompiler compiler) {
"""
Permanently delete the given call from the AST while maintaining a valid node structure, as
well as report the related AST changes to the given compiler. In some cases, this is done by
deleting the parent from the AST and is come cases expression is replaced by {@code
undefined}.
"""
checkState(n.isCall());
Node parent = n.getParent();
if (parent.isExprResult()) {
Node grandParent = parent.getParent();
grandParent.removeChild(parent);
parent = grandParent;
} else {
// Seems like part of more complex expression, fallback to replacing with no-op.
parent.replaceChild(n, newUndefinedNode(n));
}
NodeUtil.markFunctionsDeleted(n, compiler);
compiler.reportChangeToEnclosingScope(parent);
} | java | public static void deleteFunctionCall(Node n, AbstractCompiler compiler) {
checkState(n.isCall());
Node parent = n.getParent();
if (parent.isExprResult()) {
Node grandParent = parent.getParent();
grandParent.removeChild(parent);
parent = grandParent;
} else {
// Seems like part of more complex expression, fallback to replacing with no-op.
parent.replaceChild(n, newUndefinedNode(n));
}
NodeUtil.markFunctionsDeleted(n, compiler);
compiler.reportChangeToEnclosingScope(parent);
} | [
"public",
"static",
"void",
"deleteFunctionCall",
"(",
"Node",
"n",
",",
"AbstractCompiler",
"compiler",
")",
"{",
"checkState",
"(",
"n",
".",
"isCall",
"(",
")",
")",
";",
"Node",
"parent",
"=",
"n",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"parent",
".",
"isExprResult",
"(",
")",
")",
"{",
"Node",
"grandParent",
"=",
"parent",
".",
"getParent",
"(",
")",
";",
"grandParent",
".",
"removeChild",
"(",
"parent",
")",
";",
"parent",
"=",
"grandParent",
";",
"}",
"else",
"{",
"// Seems like part of more complex expression, fallback to replacing with no-op.",
"parent",
".",
"replaceChild",
"(",
"n",
",",
"newUndefinedNode",
"(",
"n",
")",
")",
";",
"}",
"NodeUtil",
".",
"markFunctionsDeleted",
"(",
"n",
",",
"compiler",
")",
";",
"compiler",
".",
"reportChangeToEnclosingScope",
"(",
"parent",
")",
";",
"}"
] | Permanently delete the given call from the AST while maintaining a valid node structure, as
well as report the related AST changes to the given compiler. In some cases, this is done by
deleting the parent from the AST and is come cases expression is replaced by {@code
undefined}. | [
"Permanently",
"delete",
"the",
"given",
"call",
"from",
"the",
"AST",
"while",
"maintaining",
"a",
"valid",
"node",
"structure",
"as",
"well",
"as",
"report",
"the",
"related",
"AST",
"changes",
"to",
"the",
"given",
"compiler",
".",
"In",
"some",
"cases",
"this",
"is",
"done",
"by",
"deleting",
"the",
"parent",
"from",
"the",
"AST",
"and",
"is",
"come",
"cases",
"expression",
"is",
"replaced",
"by",
"{"
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/NodeUtil.java#L2759-L2774 |
evernote/evernote-sdk-android | library/src/main/java/com/evernote/client/android/EvernoteUtil.java | EvernoteUtil.bytesToHex | public static String bytesToHex(byte[] bytes, boolean withSpaces) {
"""
Takes the provided byte array and converts it into a hexadecimal string
with two characters per byte.
@param withSpaces if true, include a space character between each hex-rendered
byte for readability.
"""
StringBuilder sb = new StringBuilder();
for (byte hashByte : bytes) {
int intVal = 0xff & hashByte;
if (intVal < 0x10) {
sb.append('0');
}
sb.append(Integer.toHexString(intVal));
if (withSpaces) {
sb.append(' ');
}
}
return sb.toString();
} | java | public static String bytesToHex(byte[] bytes, boolean withSpaces) {
StringBuilder sb = new StringBuilder();
for (byte hashByte : bytes) {
int intVal = 0xff & hashByte;
if (intVal < 0x10) {
sb.append('0');
}
sb.append(Integer.toHexString(intVal));
if (withSpaces) {
sb.append(' ');
}
}
return sb.toString();
} | [
"public",
"static",
"String",
"bytesToHex",
"(",
"byte",
"[",
"]",
"bytes",
",",
"boolean",
"withSpaces",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"byte",
"hashByte",
":",
"bytes",
")",
"{",
"int",
"intVal",
"=",
"0xff",
"&",
"hashByte",
";",
"if",
"(",
"intVal",
"<",
"0x10",
")",
"{",
"sb",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
"sb",
".",
"append",
"(",
"Integer",
".",
"toHexString",
"(",
"intVal",
")",
")",
";",
"if",
"(",
"withSpaces",
")",
"{",
"sb",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | Takes the provided byte array and converts it into a hexadecimal string
with two characters per byte.
@param withSpaces if true, include a space character between each hex-rendered
byte for readability. | [
"Takes",
"the",
"provided",
"byte",
"array",
"and",
"converts",
"it",
"into",
"a",
"hexadecimal",
"string",
"with",
"two",
"characters",
"per",
"byte",
"."
] | train | https://github.com/evernote/evernote-sdk-android/blob/fc59be643e85c4f59d562d1bfe76563997aa73cf/library/src/main/java/com/evernote/client/android/EvernoteUtil.java#L170-L183 |
alibaba/transmittable-thread-local | src/main/java/com/alibaba/ttl/TtlRunnable.java | TtlRunnable.get | @Nullable
public static TtlRunnable get(@Nullable Runnable runnable) {
"""
Factory method, wrap input {@link Runnable} to {@link TtlRunnable}.
@param runnable input {@link Runnable}. if input is {@code null}, return {@code null}.
@return Wrapped {@link Runnable}
@throws IllegalStateException when input is {@link TtlRunnable} already.
"""
return get(runnable, false, false);
} | java | @Nullable
public static TtlRunnable get(@Nullable Runnable runnable) {
return get(runnable, false, false);
} | [
"@",
"Nullable",
"public",
"static",
"TtlRunnable",
"get",
"(",
"@",
"Nullable",
"Runnable",
"runnable",
")",
"{",
"return",
"get",
"(",
"runnable",
",",
"false",
",",
"false",
")",
";",
"}"
] | Factory method, wrap input {@link Runnable} to {@link TtlRunnable}.
@param runnable input {@link Runnable}. if input is {@code null}, return {@code null}.
@return Wrapped {@link Runnable}
@throws IllegalStateException when input is {@link TtlRunnable} already. | [
"Factory",
"method",
"wrap",
"input",
"{",
"@link",
"Runnable",
"}",
"to",
"{",
"@link",
"TtlRunnable",
"}",
"."
] | train | https://github.com/alibaba/transmittable-thread-local/blob/30b4d99cdb7064b4c1797d2e40bfa07adce8e7f9/src/main/java/com/alibaba/ttl/TtlRunnable.java#L92-L95 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java | ElementsExceptionsFactory.newSystemException | public static SystemException newSystemException(String message, Object... args) {
"""
Constructs and initializes a new {@link SystemException} with the given {@link String message}
formatted with the given {@link Object[] arguments}.
@param message {@link String} describing the {@link SystemException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link SystemException} with the given {@link String message}.
@see #newSystemException(Throwable, String, Object...)
@see org.cp.elements.util.SystemException
"""
return newSystemException(null, message, args);
} | java | public static SystemException newSystemException(String message, Object... args) {
return newSystemException(null, message, args);
} | [
"public",
"static",
"SystemException",
"newSystemException",
"(",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"newSystemException",
"(",
"null",
",",
"message",
",",
"args",
")",
";",
"}"
] | Constructs and initializes a new {@link SystemException} with the given {@link String message}
formatted with the given {@link Object[] arguments}.
@param message {@link String} describing the {@link SystemException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link SystemException} with the given {@link String message}.
@see #newSystemException(Throwable, String, Object...)
@see org.cp.elements.util.SystemException | [
"Constructs",
"and",
"initializes",
"a",
"new",
"{",
"@link",
"SystemException",
"}",
"with",
"the",
"given",
"{",
"@link",
"String",
"message",
"}",
"formatted",
"with",
"the",
"given",
"{",
"@link",
"Object",
"[]",
"arguments",
"}",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L901-L903 |
vladmihalcea/flexy-pool | flexy-pool-core/src/main/java/com/vladmihalcea/flexypool/util/ReflectionUtils.java | ReflectionUtils.getFieldValue | public static <T> T getFieldValue(Object target, String fieldName) {
"""
Get target object field value
@param target target object
@param fieldName field name
@param <T> field type
@return field value
"""
try {
Field field = target.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
@SuppressWarnings("unchecked")
T returnValue = (T) field.get(target);
return returnValue;
} catch (NoSuchFieldException e) {
throw handleException(fieldName, e);
} catch (IllegalAccessException e) {
throw handleException(fieldName, e);
}
} | java | public static <T> T getFieldValue(Object target, String fieldName) {
try {
Field field = target.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
@SuppressWarnings("unchecked")
T returnValue = (T) field.get(target);
return returnValue;
} catch (NoSuchFieldException e) {
throw handleException(fieldName, e);
} catch (IllegalAccessException e) {
throw handleException(fieldName, e);
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"getFieldValue",
"(",
"Object",
"target",
",",
"String",
"fieldName",
")",
"{",
"try",
"{",
"Field",
"field",
"=",
"target",
".",
"getClass",
"(",
")",
".",
"getDeclaredField",
"(",
"fieldName",
")",
";",
"field",
".",
"setAccessible",
"(",
"true",
")",
";",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"T",
"returnValue",
"=",
"(",
"T",
")",
"field",
".",
"get",
"(",
"target",
")",
";",
"return",
"returnValue",
";",
"}",
"catch",
"(",
"NoSuchFieldException",
"e",
")",
"{",
"throw",
"handleException",
"(",
"fieldName",
",",
"e",
")",
";",
"}",
"catch",
"(",
"IllegalAccessException",
"e",
")",
"{",
"throw",
"handleException",
"(",
"fieldName",
",",
"e",
")",
";",
"}",
"}"
] | Get target object field value
@param target target object
@param fieldName field name
@param <T> field type
@return field value | [
"Get",
"target",
"object",
"field",
"value"
] | train | https://github.com/vladmihalcea/flexy-pool/blob/d763d359e68299c2b4e28e4b67770581ae083431/flexy-pool-core/src/main/java/com/vladmihalcea/flexypool/util/ReflectionUtils.java#L35-L47 |
acromusashi/acromusashi-stream-ml | src/main/java/acromusashi/stream/ml/anomaly/lof/LofCalculator.java | LofCalculator.calculateLofNoIntermediate | public static double calculateLofNoIntermediate(int kn, LofPoint targetPoint, LofDataSet dataSet) {
"""
指定したK値、対象点、データセットを基に局所外れ係数スコアを算出する。その際、データセットが中間データを使用せずに処理を行う。<br>
本メソッド呼び出しによってデータセットの更新は行われない。<br>
@param kn K値
@param targetPoint 対象点
@param dataSet 学習データセット
@return LOFスコア
"""
// 対象点のK距離、K距離近傍を算出する。
KDistanceResult kResult = calculateKDistance(kn, targetPoint, dataSet);
LofPoint tmpTargetPoint = targetPoint.deepCopy();
tmpTargetPoint.setkDistance(kResult.getkDistance());
tmpTargetPoint.setkDistanceNeighbor(kResult.getkDistanceNeighbor());
// データセット用の学習データモデルを一時的に生成する。
LofDataSet tmpDataSet = dataSet.deepCopy();
initDataSet(kn, tmpDataSet);
updateLrd(tmpTargetPoint, tmpDataSet);
// 対象の局所外れ係数を算出する。
double lof = calculateLof(tmpTargetPoint, tmpDataSet);
return lof;
} | java | public static double calculateLofNoIntermediate(int kn, LofPoint targetPoint, LofDataSet dataSet)
{
// 対象点のK距離、K距離近傍を算出する。
KDistanceResult kResult = calculateKDistance(kn, targetPoint, dataSet);
LofPoint tmpTargetPoint = targetPoint.deepCopy();
tmpTargetPoint.setkDistance(kResult.getkDistance());
tmpTargetPoint.setkDistanceNeighbor(kResult.getkDistanceNeighbor());
// データセット用の学習データモデルを一時的に生成する。
LofDataSet tmpDataSet = dataSet.deepCopy();
initDataSet(kn, tmpDataSet);
updateLrd(tmpTargetPoint, tmpDataSet);
// 対象の局所外れ係数を算出する。
double lof = calculateLof(tmpTargetPoint, tmpDataSet);
return lof;
} | [
"public",
"static",
"double",
"calculateLofNoIntermediate",
"(",
"int",
"kn",
",",
"LofPoint",
"targetPoint",
",",
"LofDataSet",
"dataSet",
")",
"{",
"// 対象点のK距離、K距離近傍を算出する。",
"KDistanceResult",
"kResult",
"=",
"calculateKDistance",
"(",
"kn",
",",
"targetPoint",
",",
"dataSet",
")",
";",
"LofPoint",
"tmpTargetPoint",
"=",
"targetPoint",
".",
"deepCopy",
"(",
")",
";",
"tmpTargetPoint",
".",
"setkDistance",
"(",
"kResult",
".",
"getkDistance",
"(",
")",
")",
";",
"tmpTargetPoint",
".",
"setkDistanceNeighbor",
"(",
"kResult",
".",
"getkDistanceNeighbor",
"(",
")",
")",
";",
"// データセット用の学習データモデルを一時的に生成する。",
"LofDataSet",
"tmpDataSet",
"=",
"dataSet",
".",
"deepCopy",
"(",
")",
";",
"initDataSet",
"(",
"kn",
",",
"tmpDataSet",
")",
";",
"updateLrd",
"(",
"tmpTargetPoint",
",",
"tmpDataSet",
")",
";",
"// 対象の局所外れ係数を算出する。",
"double",
"lof",
"=",
"calculateLof",
"(",
"tmpTargetPoint",
",",
"tmpDataSet",
")",
";",
"return",
"lof",
";",
"}"
] | 指定したK値、対象点、データセットを基に局所外れ係数スコアを算出する。その際、データセットが中間データを使用せずに処理を行う。<br>
本メソッド呼び出しによってデータセットの更新は行われない。<br>
@param kn K値
@param targetPoint 対象点
@param dataSet 学習データセット
@return LOFスコア | [
"指定したK値、対象点、データセットを基に局所外れ係数スコアを算出する。その際、データセットが中間データを使用せずに処理を行う。<br",
">",
"本メソッド呼び出しによってデータセットの更新は行われない。<br",
">"
] | train | https://github.com/acromusashi/acromusashi-stream-ml/blob/26d6799a917cacda68e21d506c75cfeb17d832a6/src/main/java/acromusashi/stream/ml/anomaly/lof/LofCalculator.java#L56-L74 |
voldemort/voldemort | src/java/voldemort/client/rebalance/RebalancePlan.java | RebalancePlan.storageOverhead | private String storageOverhead(Map<Integer, Integer> finalNodeToOverhead) {
"""
Determines storage overhead and returns pretty printed summary.
@param finalNodeToOverhead Map of node IDs from final cluster to number
of partition-stores to be moved to the node.
@return pretty printed string summary of storage overhead.
"""
double maxOverhead = Double.MIN_VALUE;
PartitionBalance pb = new PartitionBalance(currentCluster, currentStoreDefs);
StringBuilder sb = new StringBuilder();
sb.append("Per-node store-overhead:").append(Utils.NEWLINE);
DecimalFormat doubleDf = new DecimalFormat("####.##");
for(int nodeId: finalCluster.getNodeIds()) {
Node node = finalCluster.getNodeById(nodeId);
String nodeTag = "Node " + String.format("%4d", nodeId) + " (" + node.getHost() + ")";
int initialLoad = 0;
if(currentCluster.getNodeIds().contains(nodeId)) {
initialLoad = pb.getNaryPartitionCount(nodeId);
}
int toLoad = 0;
if(finalNodeToOverhead.containsKey(nodeId)) {
toLoad = finalNodeToOverhead.get(nodeId);
}
double overhead = (initialLoad + toLoad) / (double) initialLoad;
if(initialLoad > 0 && maxOverhead < overhead) {
maxOverhead = overhead;
}
String loadTag = String.format("%6d", initialLoad) + " + "
+ String.format("%6d", toLoad) + " -> "
+ String.format("%6d", initialLoad + toLoad) + " ("
+ doubleDf.format(overhead) + " X)";
sb.append(nodeTag + " : " + loadTag).append(Utils.NEWLINE);
}
sb.append(Utils.NEWLINE)
.append("**** Max per-node storage overhead: " + doubleDf.format(maxOverhead) + " X.")
.append(Utils.NEWLINE);
return (sb.toString());
} | java | private String storageOverhead(Map<Integer, Integer> finalNodeToOverhead) {
double maxOverhead = Double.MIN_VALUE;
PartitionBalance pb = new PartitionBalance(currentCluster, currentStoreDefs);
StringBuilder sb = new StringBuilder();
sb.append("Per-node store-overhead:").append(Utils.NEWLINE);
DecimalFormat doubleDf = new DecimalFormat("####.##");
for(int nodeId: finalCluster.getNodeIds()) {
Node node = finalCluster.getNodeById(nodeId);
String nodeTag = "Node " + String.format("%4d", nodeId) + " (" + node.getHost() + ")";
int initialLoad = 0;
if(currentCluster.getNodeIds().contains(nodeId)) {
initialLoad = pb.getNaryPartitionCount(nodeId);
}
int toLoad = 0;
if(finalNodeToOverhead.containsKey(nodeId)) {
toLoad = finalNodeToOverhead.get(nodeId);
}
double overhead = (initialLoad + toLoad) / (double) initialLoad;
if(initialLoad > 0 && maxOverhead < overhead) {
maxOverhead = overhead;
}
String loadTag = String.format("%6d", initialLoad) + " + "
+ String.format("%6d", toLoad) + " -> "
+ String.format("%6d", initialLoad + toLoad) + " ("
+ doubleDf.format(overhead) + " X)";
sb.append(nodeTag + " : " + loadTag).append(Utils.NEWLINE);
}
sb.append(Utils.NEWLINE)
.append("**** Max per-node storage overhead: " + doubleDf.format(maxOverhead) + " X.")
.append(Utils.NEWLINE);
return (sb.toString());
} | [
"private",
"String",
"storageOverhead",
"(",
"Map",
"<",
"Integer",
",",
"Integer",
">",
"finalNodeToOverhead",
")",
"{",
"double",
"maxOverhead",
"=",
"Double",
".",
"MIN_VALUE",
";",
"PartitionBalance",
"pb",
"=",
"new",
"PartitionBalance",
"(",
"currentCluster",
",",
"currentStoreDefs",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"\"Per-node store-overhead:\"",
")",
".",
"append",
"(",
"Utils",
".",
"NEWLINE",
")",
";",
"DecimalFormat",
"doubleDf",
"=",
"new",
"DecimalFormat",
"(",
"\"####.##\"",
")",
";",
"for",
"(",
"int",
"nodeId",
":",
"finalCluster",
".",
"getNodeIds",
"(",
")",
")",
"{",
"Node",
"node",
"=",
"finalCluster",
".",
"getNodeById",
"(",
"nodeId",
")",
";",
"String",
"nodeTag",
"=",
"\"Node \"",
"+",
"String",
".",
"format",
"(",
"\"%4d\"",
",",
"nodeId",
")",
"+",
"\" (\"",
"+",
"node",
".",
"getHost",
"(",
")",
"+",
"\")\"",
";",
"int",
"initialLoad",
"=",
"0",
";",
"if",
"(",
"currentCluster",
".",
"getNodeIds",
"(",
")",
".",
"contains",
"(",
"nodeId",
")",
")",
"{",
"initialLoad",
"=",
"pb",
".",
"getNaryPartitionCount",
"(",
"nodeId",
")",
";",
"}",
"int",
"toLoad",
"=",
"0",
";",
"if",
"(",
"finalNodeToOverhead",
".",
"containsKey",
"(",
"nodeId",
")",
")",
"{",
"toLoad",
"=",
"finalNodeToOverhead",
".",
"get",
"(",
"nodeId",
")",
";",
"}",
"double",
"overhead",
"=",
"(",
"initialLoad",
"+",
"toLoad",
")",
"/",
"(",
"double",
")",
"initialLoad",
";",
"if",
"(",
"initialLoad",
">",
"0",
"&&",
"maxOverhead",
"<",
"overhead",
")",
"{",
"maxOverhead",
"=",
"overhead",
";",
"}",
"String",
"loadTag",
"=",
"String",
".",
"format",
"(",
"\"%6d\"",
",",
"initialLoad",
")",
"+",
"\" + \"",
"+",
"String",
".",
"format",
"(",
"\"%6d\"",
",",
"toLoad",
")",
"+",
"\" -> \"",
"+",
"String",
".",
"format",
"(",
"\"%6d\"",
",",
"initialLoad",
"+",
"toLoad",
")",
"+",
"\" (\"",
"+",
"doubleDf",
".",
"format",
"(",
"overhead",
")",
"+",
"\" X)\"",
";",
"sb",
".",
"append",
"(",
"nodeTag",
"+",
"\" : \"",
"+",
"loadTag",
")",
".",
"append",
"(",
"Utils",
".",
"NEWLINE",
")",
";",
"}",
"sb",
".",
"append",
"(",
"Utils",
".",
"NEWLINE",
")",
".",
"append",
"(",
"\"**** Max per-node storage overhead: \"",
"+",
"doubleDf",
".",
"format",
"(",
"maxOverhead",
")",
"+",
"\" X.\"",
")",
".",
"append",
"(",
"Utils",
".",
"NEWLINE",
")",
";",
"return",
"(",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Determines storage overhead and returns pretty printed summary.
@param finalNodeToOverhead Map of node IDs from final cluster to number
of partition-stores to be moved to the node.
@return pretty printed string summary of storage overhead. | [
"Determines",
"storage",
"overhead",
"and",
"returns",
"pretty",
"printed",
"summary",
"."
] | train | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalancePlan.java#L235-L267 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/jql/JQLChecker.java | JQLChecker.replaceInternal | private String replaceInternal(final JQLContext jqlContext, String jql, final List<Triple<Token, Token, String>> replace, JqlBaseListener rewriterListener) {
"""
Replace internal.
@param jqlContext
the jql context
@param jql
the jql
@param replace
the replace
@param rewriterListener
the rewriter listener
@return the string
"""
Pair<ParserRuleContext, CommonTokenStream> parser = prepareParser(jqlContext, jql);
walker.walk(rewriterListener, parser.value0);
TokenStreamRewriter rewriter = new TokenStreamRewriter(parser.value1);
for (Triple<Token, Token, String> item : replace) {
rewriter.replace(item.value0, item.value1, item.value2);
}
return rewriter.getText();
} | java | private String replaceInternal(final JQLContext jqlContext, String jql, final List<Triple<Token, Token, String>> replace, JqlBaseListener rewriterListener) {
Pair<ParserRuleContext, CommonTokenStream> parser = prepareParser(jqlContext, jql);
walker.walk(rewriterListener, parser.value0);
TokenStreamRewriter rewriter = new TokenStreamRewriter(parser.value1);
for (Triple<Token, Token, String> item : replace) {
rewriter.replace(item.value0, item.value1, item.value2);
}
return rewriter.getText();
} | [
"private",
"String",
"replaceInternal",
"(",
"final",
"JQLContext",
"jqlContext",
",",
"String",
"jql",
",",
"final",
"List",
"<",
"Triple",
"<",
"Token",
",",
"Token",
",",
"String",
">",
">",
"replace",
",",
"JqlBaseListener",
"rewriterListener",
")",
"{",
"Pair",
"<",
"ParserRuleContext",
",",
"CommonTokenStream",
">",
"parser",
"=",
"prepareParser",
"(",
"jqlContext",
",",
"jql",
")",
";",
"walker",
".",
"walk",
"(",
"rewriterListener",
",",
"parser",
".",
"value0",
")",
";",
"TokenStreamRewriter",
"rewriter",
"=",
"new",
"TokenStreamRewriter",
"(",
"parser",
".",
"value1",
")",
";",
"for",
"(",
"Triple",
"<",
"Token",
",",
"Token",
",",
"String",
">",
"item",
":",
"replace",
")",
"{",
"rewriter",
".",
"replace",
"(",
"item",
".",
"value0",
",",
"item",
".",
"value1",
",",
"item",
".",
"value2",
")",
";",
"}",
"return",
"rewriter",
".",
"getText",
"(",
")",
";",
"}"
] | Replace internal.
@param jqlContext
the jql context
@param jql
the jql
@param replace
the replace
@param rewriterListener
the rewriter listener
@return the string | [
"Replace",
"internal",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/jql/JQLChecker.java#L697-L708 |
sdl/odata | odata_renderer/src/main/java/com/sdl/odata/renderer/AbstractRenderer.java | AbstractRenderer.isEntityQuery | protected boolean isEntityQuery(ODataUri uri, EntityDataModel entityDataModel) {
"""
Check if the parsed OData URI is a query and it results in an entity or a collection of entities.
@param uri The parsed OData URI.
@param entityDataModel The Entity Data Model.
@return {@code true} if it is about an entity query.
"""
return getTargetType(uri, entityDataModel).map(t -> t.getMetaType() == MetaType.ENTITY).orElse(false);
} | java | protected boolean isEntityQuery(ODataUri uri, EntityDataModel entityDataModel) {
return getTargetType(uri, entityDataModel).map(t -> t.getMetaType() == MetaType.ENTITY).orElse(false);
} | [
"protected",
"boolean",
"isEntityQuery",
"(",
"ODataUri",
"uri",
",",
"EntityDataModel",
"entityDataModel",
")",
"{",
"return",
"getTargetType",
"(",
"uri",
",",
"entityDataModel",
")",
".",
"map",
"(",
"t",
"->",
"t",
".",
"getMetaType",
"(",
")",
"==",
"MetaType",
".",
"ENTITY",
")",
".",
"orElse",
"(",
"false",
")",
";",
"}"
] | Check if the parsed OData URI is a query and it results in an entity or a collection of entities.
@param uri The parsed OData URI.
@param entityDataModel The Entity Data Model.
@return {@code true} if it is about an entity query. | [
"Check",
"if",
"the",
"parsed",
"OData",
"URI",
"is",
"a",
"query",
"and",
"it",
"results",
"in",
"an",
"entity",
"or",
"a",
"collection",
"of",
"entities",
"."
] | train | https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/AbstractRenderer.java#L106-L108 |
Kickflip/kickflip-android-sdk | sdk/src/main/java/io/kickflip/sdk/av/Texture2dProgram.java | Texture2dProgram.setTexSize | public void setTexSize(int width, int height) {
"""
Sets the size of the texture. This is used to find adjacent texels when filtering.
"""
mTexHeight = height;
mTexWidth = width;
float rw = 1.0f / width;
float rh = 1.0f / height;
// Don't need to create a new array here, but it's syntactically convenient.
mTexOffset = new float[] {
-rw, -rh, 0f, -rh, rw, -rh,
-rw, 0f, 0f, 0f, rw, 0f,
-rw, rh, 0f, rh, rw, rh
};
//Log.d(TAG, "filt size: " + width + "x" + height + ": " + Arrays.toString(mTexOffset));
} | java | public void setTexSize(int width, int height) {
mTexHeight = height;
mTexWidth = width;
float rw = 1.0f / width;
float rh = 1.0f / height;
// Don't need to create a new array here, but it's syntactically convenient.
mTexOffset = new float[] {
-rw, -rh, 0f, -rh, rw, -rh,
-rw, 0f, 0f, 0f, rw, 0f,
-rw, rh, 0f, rh, rw, rh
};
//Log.d(TAG, "filt size: " + width + "x" + height + ": " + Arrays.toString(mTexOffset));
} | [
"public",
"void",
"setTexSize",
"(",
"int",
"width",
",",
"int",
"height",
")",
"{",
"mTexHeight",
"=",
"height",
";",
"mTexWidth",
"=",
"width",
";",
"float",
"rw",
"=",
"1.0f",
"/",
"width",
";",
"float",
"rh",
"=",
"1.0f",
"/",
"height",
";",
"// Don't need to create a new array here, but it's syntactically convenient.",
"mTexOffset",
"=",
"new",
"float",
"[",
"]",
"{",
"-",
"rw",
",",
"-",
"rh",
",",
"0f",
",",
"-",
"rh",
",",
"rw",
",",
"-",
"rh",
",",
"-",
"rw",
",",
"0f",
",",
"0f",
",",
"0f",
",",
"rw",
",",
"0f",
",",
"-",
"rw",
",",
"rh",
",",
"0f",
",",
"rh",
",",
"rw",
",",
"rh",
"}",
";",
"//Log.d(TAG, \"filt size: \" + width + \"x\" + height + \": \" + Arrays.toString(mTexOffset));",
"}"
] | Sets the size of the texture. This is used to find adjacent texels when filtering. | [
"Sets",
"the",
"size",
"of",
"the",
"texture",
".",
"This",
"is",
"used",
"to",
"find",
"adjacent",
"texels",
"when",
"filtering",
"."
] | train | https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/av/Texture2dProgram.java#L504-L517 |
iipc/webarchive-commons | src/main/java/org/archive/url/UsableURIFactory.java | UsableURIFactory.ensureMinimalEscaping | private String ensureMinimalEscaping(String u, final String charset) {
"""
Ensure that there all characters needing escaping
in the passed-in String are escaped. Stray '%' characters
are *not* escaped, as per browser behavior.
@param u String to escape
@param charset
@return string with any necessary escaping applied
"""
return ensureMinimalEscaping(u, charset, LaxURLCodec.EXPANDED_URI_SAFE);
} | java | private String ensureMinimalEscaping(String u, final String charset) {
return ensureMinimalEscaping(u, charset, LaxURLCodec.EXPANDED_URI_SAFE);
} | [
"private",
"String",
"ensureMinimalEscaping",
"(",
"String",
"u",
",",
"final",
"String",
"charset",
")",
"{",
"return",
"ensureMinimalEscaping",
"(",
"u",
",",
"charset",
",",
"LaxURLCodec",
".",
"EXPANDED_URI_SAFE",
")",
";",
"}"
] | Ensure that there all characters needing escaping
in the passed-in String are escaped. Stray '%' characters
are *not* escaped, as per browser behavior.
@param u String to escape
@param charset
@return string with any necessary escaping applied | [
"Ensure",
"that",
"there",
"all",
"characters",
"needing",
"escaping",
"in",
"the",
"passed",
"-",
"in",
"String",
"are",
"escaped",
".",
"Stray",
"%",
"characters",
"are",
"*",
"not",
"*",
"escaped",
"as",
"per",
"browser",
"behavior",
"."
] | train | https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/url/UsableURIFactory.java#L630-L632 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/cert/CertPath.java | CertPath.writeReplace | protected Object writeReplace() throws ObjectStreamException {
"""
Replaces the {@code CertPath} to be serialized with a
{@code CertPathRep} object.
@return the {@code CertPathRep} to be serialized
@throws ObjectStreamException if a {@code CertPathRep} object
representing this certification path could not be created
"""
try {
return new CertPathRep(type, getEncoded());
} catch (CertificateException ce) {
NotSerializableException nse =
new NotSerializableException
("java.security.cert.CertPath: " + type);
nse.initCause(ce);
throw nse;
}
} | java | protected Object writeReplace() throws ObjectStreamException {
try {
return new CertPathRep(type, getEncoded());
} catch (CertificateException ce) {
NotSerializableException nse =
new NotSerializableException
("java.security.cert.CertPath: " + type);
nse.initCause(ce);
throw nse;
}
} | [
"protected",
"Object",
"writeReplace",
"(",
")",
"throws",
"ObjectStreamException",
"{",
"try",
"{",
"return",
"new",
"CertPathRep",
"(",
"type",
",",
"getEncoded",
"(",
")",
")",
";",
"}",
"catch",
"(",
"CertificateException",
"ce",
")",
"{",
"NotSerializableException",
"nse",
"=",
"new",
"NotSerializableException",
"(",
"\"java.security.cert.CertPath: \"",
"+",
"type",
")",
";",
"nse",
".",
"initCause",
"(",
"ce",
")",
";",
"throw",
"nse",
";",
"}",
"}"
] | Replaces the {@code CertPath} to be serialized with a
{@code CertPathRep} object.
@return the {@code CertPathRep} to be serialized
@throws ObjectStreamException if a {@code CertPathRep} object
representing this certification path could not be created | [
"Replaces",
"the",
"{",
"@code",
"CertPath",
"}",
"to",
"be",
"serialized",
"with",
"a",
"{",
"@code",
"CertPathRep",
"}",
"object",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/cert/CertPath.java#L285-L295 |
apache/groovy | subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java | NioGroovyMethods.newWriter | public static BufferedWriter newWriter(Path self, boolean append) throws IOException {
"""
Creates a buffered writer for this file, optionally appending to the
existing file content.
@param self a Path
@param append true if data should be appended to the file
@return a BufferedWriter
@throws java.io.IOException if an IOException occurs.
@since 2.3.0
"""
if (append) {
return Files.newBufferedWriter(self, Charset.defaultCharset(), CREATE, APPEND);
}
return Files.newBufferedWriter(self, Charset.defaultCharset());
} | java | public static BufferedWriter newWriter(Path self, boolean append) throws IOException {
if (append) {
return Files.newBufferedWriter(self, Charset.defaultCharset(), CREATE, APPEND);
}
return Files.newBufferedWriter(self, Charset.defaultCharset());
} | [
"public",
"static",
"BufferedWriter",
"newWriter",
"(",
"Path",
"self",
",",
"boolean",
"append",
")",
"throws",
"IOException",
"{",
"if",
"(",
"append",
")",
"{",
"return",
"Files",
".",
"newBufferedWriter",
"(",
"self",
",",
"Charset",
".",
"defaultCharset",
"(",
")",
",",
"CREATE",
",",
"APPEND",
")",
";",
"}",
"return",
"Files",
".",
"newBufferedWriter",
"(",
"self",
",",
"Charset",
".",
"defaultCharset",
"(",
")",
")",
";",
"}"
] | Creates a buffered writer for this file, optionally appending to the
existing file content.
@param self a Path
@param append true if data should be appended to the file
@return a BufferedWriter
@throws java.io.IOException if an IOException occurs.
@since 2.3.0 | [
"Creates",
"a",
"buffered",
"writer",
"for",
"this",
"file",
"optionally",
"appending",
"to",
"the",
"existing",
"file",
"content",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java#L1556-L1561 |
netty/netty | handler/src/main/java/io/netty/handler/logging/LoggingHandler.java | LoggingHandler.formatSimple | private static String formatSimple(ChannelHandlerContext ctx, String eventName, Object msg) {
"""
Generates the default log message of the specified event whose argument is an arbitrary object.
"""
String chStr = ctx.channel().toString();
String msgStr = String.valueOf(msg);
StringBuilder buf = new StringBuilder(chStr.length() + 1 + eventName.length() + 2 + msgStr.length());
return buf.append(chStr).append(' ').append(eventName).append(": ").append(msgStr).toString();
} | java | private static String formatSimple(ChannelHandlerContext ctx, String eventName, Object msg) {
String chStr = ctx.channel().toString();
String msgStr = String.valueOf(msg);
StringBuilder buf = new StringBuilder(chStr.length() + 1 + eventName.length() + 2 + msgStr.length());
return buf.append(chStr).append(' ').append(eventName).append(": ").append(msgStr).toString();
} | [
"private",
"static",
"String",
"formatSimple",
"(",
"ChannelHandlerContext",
"ctx",
",",
"String",
"eventName",
",",
"Object",
"msg",
")",
"{",
"String",
"chStr",
"=",
"ctx",
".",
"channel",
"(",
")",
".",
"toString",
"(",
")",
";",
"String",
"msgStr",
"=",
"String",
".",
"valueOf",
"(",
"msg",
")",
";",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
"chStr",
".",
"length",
"(",
")",
"+",
"1",
"+",
"eventName",
".",
"length",
"(",
")",
"+",
"2",
"+",
"msgStr",
".",
"length",
"(",
")",
")",
";",
"return",
"buf",
".",
"append",
"(",
"chStr",
")",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"eventName",
")",
".",
"append",
"(",
"\": \"",
")",
".",
"append",
"(",
"msgStr",
")",
".",
"toString",
"(",
")",
";",
"}"
] | Generates the default log message of the specified event whose argument is an arbitrary object. | [
"Generates",
"the",
"default",
"log",
"message",
"of",
"the",
"specified",
"event",
"whose",
"argument",
"is",
"an",
"arbitrary",
"object",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/logging/LoggingHandler.java#L369-L374 |
KostyaSha/yet-another-docker-plugin | yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/client/ClientBuilderForConnector.java | ClientBuilderForConnector.forServer | public ClientBuilderForConnector forServer(String uri, @Nullable String version) {
"""
Method to setup url and docker-api version. Convenient for test-connection purposes and quick requests
@param uri docker server uri
@param version docker-api version
@return this newClientBuilderForConnector
"""
configBuilder.withDockerHost(URI.create(uri).toString())
.withApiVersion(version);
return this;
} | java | public ClientBuilderForConnector forServer(String uri, @Nullable String version) {
configBuilder.withDockerHost(URI.create(uri).toString())
.withApiVersion(version);
return this;
} | [
"public",
"ClientBuilderForConnector",
"forServer",
"(",
"String",
"uri",
",",
"@",
"Nullable",
"String",
"version",
")",
"{",
"configBuilder",
".",
"withDockerHost",
"(",
"URI",
".",
"create",
"(",
"uri",
")",
".",
"toString",
"(",
")",
")",
".",
"withApiVersion",
"(",
"version",
")",
";",
"return",
"this",
";",
"}"
] | Method to setup url and docker-api version. Convenient for test-connection purposes and quick requests
@param uri docker server uri
@param version docker-api version
@return this newClientBuilderForConnector | [
"Method",
"to",
"setup",
"url",
"and",
"docker",
"-",
"api",
"version",
".",
"Convenient",
"for",
"test",
"-",
"connection",
"purposes",
"and",
"quick",
"requests"
] | train | https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/client/ClientBuilderForConnector.java#L119-L123 |
Sciss/abc4j | abc/src/main/java/abc/ui/swing/JScoreElementAbstract.java | JScoreElementAbstract.setColor | protected void setColor(Graphics2D g2, byte scoreElement) {
"""
Set the color for renderer, get color value in the score
template, or apply the specified color for the current
element.
"""
if (m_color != null)
g2.setColor(m_color);
else {
Color c = getTemplate().getElementColor(scoreElement);
Color d = getTemplate().getElementColor(ScoreElements._DEFAULT);
if ((c != null) && !c.equals(d))
g2.setColor(c);
}
} | java | protected void setColor(Graphics2D g2, byte scoreElement) {
if (m_color != null)
g2.setColor(m_color);
else {
Color c = getTemplate().getElementColor(scoreElement);
Color d = getTemplate().getElementColor(ScoreElements._DEFAULT);
if ((c != null) && !c.equals(d))
g2.setColor(c);
}
} | [
"protected",
"void",
"setColor",
"(",
"Graphics2D",
"g2",
",",
"byte",
"scoreElement",
")",
"{",
"if",
"(",
"m_color",
"!=",
"null",
")",
"g2",
".",
"setColor",
"(",
"m_color",
")",
";",
"else",
"{",
"Color",
"c",
"=",
"getTemplate",
"(",
")",
".",
"getElementColor",
"(",
"scoreElement",
")",
";",
"Color",
"d",
"=",
"getTemplate",
"(",
")",
".",
"getElementColor",
"(",
"ScoreElements",
".",
"_DEFAULT",
")",
";",
"if",
"(",
"(",
"c",
"!=",
"null",
")",
"&&",
"!",
"c",
".",
"equals",
"(",
"d",
")",
")",
"g2",
".",
"setColor",
"(",
"c",
")",
";",
"}",
"}"
] | Set the color for renderer, get color value in the score
template, or apply the specified color for the current
element. | [
"Set",
"the",
"color",
"for",
"renderer",
"get",
"color",
"value",
"in",
"the",
"score",
"template",
"or",
"apply",
"the",
"specified",
"color",
"for",
"the",
"current",
"element",
"."
] | train | https://github.com/Sciss/abc4j/blob/117b405642c84a7bfca4e3e13668838258b90ca7/abc/src/main/java/abc/ui/swing/JScoreElementAbstract.java#L276-L285 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/MergeRequestApi.java | MergeRequestApi.acceptMergeRequest | public MergeRequest acceptMergeRequest(Object projectIdOrPath, Integer mergeRequestIid) throws GitLabApiException {
"""
Merge changes to the merge request. If the MR has any conflicts and can not be merged,
you'll get a 405 and the error message 'Branch cannot be merged'. If merge request is
already merged or closed, you'll get a 406 and the error message 'Method Not Allowed'.
If the sha parameter is passed and does not match the HEAD of the source, you'll get
a 409 and the error message 'SHA does not match HEAD of source branch'. If you don't
have permissions to accept this merge request, you'll get a 401.
<p>NOTE: GitLab API V4 uses IID (internal ID), V3 uses ID to identify the merge request.</p>
<pre><code>GitLab Endpoint: PUT /projects/:id/merge_requests/:merge_request_iid/merge</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param mergeRequestIid the internal ID of the merge request
@return the merged merge request
@throws GitLabApiException if any exception occurs
"""
return (acceptMergeRequest(projectIdOrPath, mergeRequestIid, null, null, null, null));
} | java | public MergeRequest acceptMergeRequest(Object projectIdOrPath, Integer mergeRequestIid) throws GitLabApiException {
return (acceptMergeRequest(projectIdOrPath, mergeRequestIid, null, null, null, null));
} | [
"public",
"MergeRequest",
"acceptMergeRequest",
"(",
"Object",
"projectIdOrPath",
",",
"Integer",
"mergeRequestIid",
")",
"throws",
"GitLabApiException",
"{",
"return",
"(",
"acceptMergeRequest",
"(",
"projectIdOrPath",
",",
"mergeRequestIid",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
")",
")",
";",
"}"
] | Merge changes to the merge request. If the MR has any conflicts and can not be merged,
you'll get a 405 and the error message 'Branch cannot be merged'. If merge request is
already merged or closed, you'll get a 406 and the error message 'Method Not Allowed'.
If the sha parameter is passed and does not match the HEAD of the source, you'll get
a 409 and the error message 'SHA does not match HEAD of source branch'. If you don't
have permissions to accept this merge request, you'll get a 401.
<p>NOTE: GitLab API V4 uses IID (internal ID), V3 uses ID to identify the merge request.</p>
<pre><code>GitLab Endpoint: PUT /projects/:id/merge_requests/:merge_request_iid/merge</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param mergeRequestIid the internal ID of the merge request
@return the merged merge request
@throws GitLabApiException if any exception occurs | [
"Merge",
"changes",
"to",
"the",
"merge",
"request",
".",
"If",
"the",
"MR",
"has",
"any",
"conflicts",
"and",
"can",
"not",
"be",
"merged",
"you",
"ll",
"get",
"a",
"405",
"and",
"the",
"error",
"message",
"Branch",
"cannot",
"be",
"merged",
".",
"If",
"merge",
"request",
"is",
"already",
"merged",
"or",
"closed",
"you",
"ll",
"get",
"a",
"406",
"and",
"the",
"error",
"message",
"Method",
"Not",
"Allowed",
".",
"If",
"the",
"sha",
"parameter",
"is",
"passed",
"and",
"does",
"not",
"match",
"the",
"HEAD",
"of",
"the",
"source",
"you",
"ll",
"get",
"a",
"409",
"and",
"the",
"error",
"message",
"SHA",
"does",
"not",
"match",
"HEAD",
"of",
"source",
"branch",
".",
"If",
"you",
"don",
"t",
"have",
"permissions",
"to",
"accept",
"this",
"merge",
"request",
"you",
"ll",
"get",
"a",
"401",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/MergeRequestApi.java#L585-L587 |
BranchMetrics/android-branch-deep-linking | Branch-SDK/src/io/branch/referral/util/BranchEvent.java | BranchEvent.logEvent | public boolean logEvent(Context context) {
"""
Logs this BranchEvent to Branch for tracking and analytics
@param context Current context
@return {@code true} if the event is logged to Branch
"""
boolean isReqQueued = false;
String reqPath = isStandardEvent ? Defines.RequestPath.TrackStandardEvent.getPath() : Defines.RequestPath.TrackCustomEvent.getPath();
if (Branch.getInstance() != null) {
Branch.getInstance().handleNewRequest(new ServerRequestLogEvent(context, reqPath));
isReqQueued = true;
}
return isReqQueued;
} | java | public boolean logEvent(Context context) {
boolean isReqQueued = false;
String reqPath = isStandardEvent ? Defines.RequestPath.TrackStandardEvent.getPath() : Defines.RequestPath.TrackCustomEvent.getPath();
if (Branch.getInstance() != null) {
Branch.getInstance().handleNewRequest(new ServerRequestLogEvent(context, reqPath));
isReqQueued = true;
}
return isReqQueued;
} | [
"public",
"boolean",
"logEvent",
"(",
"Context",
"context",
")",
"{",
"boolean",
"isReqQueued",
"=",
"false",
";",
"String",
"reqPath",
"=",
"isStandardEvent",
"?",
"Defines",
".",
"RequestPath",
".",
"TrackStandardEvent",
".",
"getPath",
"(",
")",
":",
"Defines",
".",
"RequestPath",
".",
"TrackCustomEvent",
".",
"getPath",
"(",
")",
";",
"if",
"(",
"Branch",
".",
"getInstance",
"(",
")",
"!=",
"null",
")",
"{",
"Branch",
".",
"getInstance",
"(",
")",
".",
"handleNewRequest",
"(",
"new",
"ServerRequestLogEvent",
"(",
"context",
",",
"reqPath",
")",
")",
";",
"isReqQueued",
"=",
"true",
";",
"}",
"return",
"isReqQueued",
";",
"}"
] | Logs this BranchEvent to Branch for tracking and analytics
@param context Current context
@return {@code true} if the event is logged to Branch | [
"Logs",
"this",
"BranchEvent",
"to",
"Branch",
"for",
"tracking",
"and",
"analytics"
] | train | https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/util/BranchEvent.java#L227-L235 |
Azure/azure-sdk-for-java | automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ModulesInner.java | ModulesInner.createOrUpdateAsync | public Observable<ModuleInner> createOrUpdateAsync(String resourceGroupName, String automationAccountName, String moduleName, ModuleCreateOrUpdateParameters parameters) {
"""
Create or Update the module identified by module name.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param moduleName The name of module.
@param parameters The create or update parameters for module.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ModuleInner object
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, automationAccountName, moduleName, parameters).map(new Func1<ServiceResponse<ModuleInner>, ModuleInner>() {
@Override
public ModuleInner call(ServiceResponse<ModuleInner> response) {
return response.body();
}
});
} | java | public Observable<ModuleInner> createOrUpdateAsync(String resourceGroupName, String automationAccountName, String moduleName, ModuleCreateOrUpdateParameters parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, automationAccountName, moduleName, parameters).map(new Func1<ServiceResponse<ModuleInner>, ModuleInner>() {
@Override
public ModuleInner call(ServiceResponse<ModuleInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ModuleInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"automationAccountName",
",",
"String",
"moduleName",
",",
"ModuleCreateOrUpdateParameters",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"automationAccountName",
",",
"moduleName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ModuleInner",
">",
",",
"ModuleInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ModuleInner",
"call",
"(",
"ServiceResponse",
"<",
"ModuleInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Create or Update the module identified by module name.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param moduleName The name of module.
@param parameters The create or update parameters for module.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ModuleInner object | [
"Create",
"or",
"Update",
"the",
"module",
"identified",
"by",
"module",
"name",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ModulesInner.java#L315-L322 |
apache/predictionio-sdk-java | client/src/main/java/org/apache/predictionio/sdk/java/EventClient.java | EventClient.unsetItem | public String unsetItem(String iid, List<String> properties)
throws ExecutionException, InterruptedException, IOException {
"""
Unsets properties of a item. Same as {@link #unsetItem(String, List, DateTime)
unsetItem(String, List<String>, DateTime)} except event time is not specified and
recorded as the time when the function is called.
"""
return unsetItem(iid, properties, new DateTime());
} | java | public String unsetItem(String iid, List<String> properties)
throws ExecutionException, InterruptedException, IOException {
return unsetItem(iid, properties, new DateTime());
} | [
"public",
"String",
"unsetItem",
"(",
"String",
"iid",
",",
"List",
"<",
"String",
">",
"properties",
")",
"throws",
"ExecutionException",
",",
"InterruptedException",
",",
"IOException",
"{",
"return",
"unsetItem",
"(",
"iid",
",",
"properties",
",",
"new",
"DateTime",
"(",
")",
")",
";",
"}"
] | Unsets properties of a item. Same as {@link #unsetItem(String, List, DateTime)
unsetItem(String, List<String>, DateTime)} except event time is not specified and
recorded as the time when the function is called. | [
"Unsets",
"properties",
"of",
"a",
"item",
".",
"Same",
"as",
"{"
] | train | https://github.com/apache/predictionio-sdk-java/blob/16052c96b136340c175c3f9c2692e720850df219/client/src/main/java/org/apache/predictionio/sdk/java/EventClient.java#L551-L554 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/ZipUtil.java | ZipUtil.unpackEntry | public static boolean unpackEntry(File zip, String name, File file) {
"""
Unpacks a single file from a ZIP archive to a file.
@param zip
ZIP file.
@param name
entry name.
@param file
target file to be created or overwritten.
@return <code>true</code> if the entry was found and unpacked,
<code>false</code> if the entry was not found.
"""
return unpackEntry(zip, name, file, null);
} | java | public static boolean unpackEntry(File zip, String name, File file) {
return unpackEntry(zip, name, file, null);
} | [
"public",
"static",
"boolean",
"unpackEntry",
"(",
"File",
"zip",
",",
"String",
"name",
",",
"File",
"file",
")",
"{",
"return",
"unpackEntry",
"(",
"zip",
",",
"name",
",",
"file",
",",
"null",
")",
";",
"}"
] | Unpacks a single file from a ZIP archive to a file.
@param zip
ZIP file.
@param name
entry name.
@param file
target file to be created or overwritten.
@return <code>true</code> if the entry was found and unpacked,
<code>false</code> if the entry was not found. | [
"Unpacks",
"a",
"single",
"file",
"from",
"a",
"ZIP",
"archive",
"to",
"a",
"file",
"."
] | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L318-L320 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/utils/KerasLayerUtils.java | KerasLayerUtils.removeDefaultWeights | public static void removeDefaultWeights(Map<String, INDArray> weights, KerasLayerConfiguration conf) {
"""
Remove weights from config after weight setting.
@param weights layer weights
@param conf Keras layer configuration
"""
if (weights.size() > 2) {
Set<String> paramNames = weights.keySet();
paramNames.remove(conf.getKERAS_PARAM_NAME_W());
paramNames.remove(conf.getKERAS_PARAM_NAME_B());
String unknownParamNames = paramNames.toString();
log.warn("Attemping to set weights for unknown parameters: "
+ unknownParamNames.substring(1, unknownParamNames.length() - 1));
}
} | java | public static void removeDefaultWeights(Map<String, INDArray> weights, KerasLayerConfiguration conf) {
if (weights.size() > 2) {
Set<String> paramNames = weights.keySet();
paramNames.remove(conf.getKERAS_PARAM_NAME_W());
paramNames.remove(conf.getKERAS_PARAM_NAME_B());
String unknownParamNames = paramNames.toString();
log.warn("Attemping to set weights for unknown parameters: "
+ unknownParamNames.substring(1, unknownParamNames.length() - 1));
}
} | [
"public",
"static",
"void",
"removeDefaultWeights",
"(",
"Map",
"<",
"String",
",",
"INDArray",
">",
"weights",
",",
"KerasLayerConfiguration",
"conf",
")",
"{",
"if",
"(",
"weights",
".",
"size",
"(",
")",
">",
"2",
")",
"{",
"Set",
"<",
"String",
">",
"paramNames",
"=",
"weights",
".",
"keySet",
"(",
")",
";",
"paramNames",
".",
"remove",
"(",
"conf",
".",
"getKERAS_PARAM_NAME_W",
"(",
")",
")",
";",
"paramNames",
".",
"remove",
"(",
"conf",
".",
"getKERAS_PARAM_NAME_B",
"(",
")",
")",
";",
"String",
"unknownParamNames",
"=",
"paramNames",
".",
"toString",
"(",
")",
";",
"log",
".",
"warn",
"(",
"\"Attemping to set weights for unknown parameters: \"",
"+",
"unknownParamNames",
".",
"substring",
"(",
"1",
",",
"unknownParamNames",
".",
"length",
"(",
")",
"-",
"1",
")",
")",
";",
"}",
"}"
] | Remove weights from config after weight setting.
@param weights layer weights
@param conf Keras layer configuration | [
"Remove",
"weights",
"from",
"config",
"after",
"weight",
"setting",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/utils/KerasLayerUtils.java#L610-L619 |
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.getByResourceGroup | public VirtualMachineScaleSetInner getByResourceGroup(String resourceGroupName, String vmScaleSetName) {
"""
Display information about a virtual machine scale set.
@param resourceGroupName The name of the resource group.
@param vmScaleSetName The name of the VM scale set.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the VirtualMachineScaleSetInner object if successful.
"""
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, vmScaleSetName).toBlocking().single().body();
} | java | public VirtualMachineScaleSetInner getByResourceGroup(String resourceGroupName, String vmScaleSetName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, vmScaleSetName).toBlocking().single().body();
} | [
"public",
"VirtualMachineScaleSetInner",
"getByResourceGroup",
"(",
"String",
"resourceGroupName",
",",
"String",
"vmScaleSetName",
")",
"{",
"return",
"getByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"vmScaleSetName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Display information about a virtual machine scale set.
@param resourceGroupName The name of the resource group.
@param vmScaleSetName The name of the VM scale set.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the VirtualMachineScaleSetInner object if successful. | [
"Display",
"information",
"about",
"a",
"virtual",
"machine",
"scale",
"set",
"."
] | 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#L704-L706 |
UrielCh/ovh-java-sdk | ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java | ApiOvhPrice.dedicated_server_ip_routedTo_GET | public OvhPrice dedicated_server_ip_routedTo_GET(net.minidev.ovh.api.price.dedicated.server.OvhIpEnum routedTo) throws IOException {
"""
Get price of IPs
REST: GET /price/dedicated/server/ip/{routedTo}
@param routedTo [required] Ip
"""
String qPath = "/price/dedicated/server/ip/{routedTo}";
StringBuilder sb = path(qPath, routedTo);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPrice.class);
} | java | public OvhPrice dedicated_server_ip_routedTo_GET(net.minidev.ovh.api.price.dedicated.server.OvhIpEnum routedTo) throws IOException {
String qPath = "/price/dedicated/server/ip/{routedTo}";
StringBuilder sb = path(qPath, routedTo);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPrice.class);
} | [
"public",
"OvhPrice",
"dedicated_server_ip_routedTo_GET",
"(",
"net",
".",
"minidev",
".",
"ovh",
".",
"api",
".",
"price",
".",
"dedicated",
".",
"server",
".",
"OvhIpEnum",
"routedTo",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/price/dedicated/server/ip/{routedTo}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"routedTo",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhPrice",
".",
"class",
")",
";",
"}"
] | Get price of IPs
REST: GET /price/dedicated/server/ip/{routedTo}
@param routedTo [required] Ip | [
"Get",
"price",
"of",
"IPs"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java#L128-L133 |
Impetus/Kundera | src/kundera-elastic-search/src/main/java/com/impetus/client/es/utils/ESResponseWrapper.java | ESResponseWrapper.isValidBucket | private boolean isValidBucket(InternalAggregations internalAgg, KunderaQuery query, Expression conditionalExpression) {
"""
Checks if is valid bucket.
@param internalAgg
the internal agg
@param query
the query
@param conditionalExpression
the conditional expression
@return true, if is valid bucket
"""
if (conditionalExpression instanceof ComparisonExpression)
{
Expression expression = ((ComparisonExpression) conditionalExpression).getLeftExpression();
Object leftValue = getAggregatedResult(internalAgg, ((AggregateFunction) expression).getIdentifier(),
expression);
String rightValue = ((ComparisonExpression) conditionalExpression).getRightExpression().toParsedText();
return validateBucket(leftValue.toString(), rightValue,
((ComparisonExpression) conditionalExpression).getIdentifier());
}
else if (LogicalExpression.class.isAssignableFrom(conditionalExpression.getClass()))
{
Expression leftExpression = null, rightExpression = null;
if (conditionalExpression instanceof AndExpression)
{
AndExpression andExpression = (AndExpression) conditionalExpression;
leftExpression = andExpression.getLeftExpression();
rightExpression = andExpression.getRightExpression();
}
else
{
OrExpression orExpression = (OrExpression) conditionalExpression;
leftExpression = orExpression.getLeftExpression();
rightExpression = orExpression.getRightExpression();
}
return validateBucket(isValidBucket(internalAgg, query, leftExpression),
isValidBucket(internalAgg, query, rightExpression),
((LogicalExpression) conditionalExpression).getIdentifier());
}
else
{
logger.error("Expression " + conditionalExpression + " in having clause is not supported in Kundera");
throw new UnsupportedOperationException(conditionalExpression
+ " in having clause is not supported in Kundera");
}
} | java | private boolean isValidBucket(InternalAggregations internalAgg, KunderaQuery query, Expression conditionalExpression)
{
if (conditionalExpression instanceof ComparisonExpression)
{
Expression expression = ((ComparisonExpression) conditionalExpression).getLeftExpression();
Object leftValue = getAggregatedResult(internalAgg, ((AggregateFunction) expression).getIdentifier(),
expression);
String rightValue = ((ComparisonExpression) conditionalExpression).getRightExpression().toParsedText();
return validateBucket(leftValue.toString(), rightValue,
((ComparisonExpression) conditionalExpression).getIdentifier());
}
else if (LogicalExpression.class.isAssignableFrom(conditionalExpression.getClass()))
{
Expression leftExpression = null, rightExpression = null;
if (conditionalExpression instanceof AndExpression)
{
AndExpression andExpression = (AndExpression) conditionalExpression;
leftExpression = andExpression.getLeftExpression();
rightExpression = andExpression.getRightExpression();
}
else
{
OrExpression orExpression = (OrExpression) conditionalExpression;
leftExpression = orExpression.getLeftExpression();
rightExpression = orExpression.getRightExpression();
}
return validateBucket(isValidBucket(internalAgg, query, leftExpression),
isValidBucket(internalAgg, query, rightExpression),
((LogicalExpression) conditionalExpression).getIdentifier());
}
else
{
logger.error("Expression " + conditionalExpression + " in having clause is not supported in Kundera");
throw new UnsupportedOperationException(conditionalExpression
+ " in having clause is not supported in Kundera");
}
} | [
"private",
"boolean",
"isValidBucket",
"(",
"InternalAggregations",
"internalAgg",
",",
"KunderaQuery",
"query",
",",
"Expression",
"conditionalExpression",
")",
"{",
"if",
"(",
"conditionalExpression",
"instanceof",
"ComparisonExpression",
")",
"{",
"Expression",
"expression",
"=",
"(",
"(",
"ComparisonExpression",
")",
"conditionalExpression",
")",
".",
"getLeftExpression",
"(",
")",
";",
"Object",
"leftValue",
"=",
"getAggregatedResult",
"(",
"internalAgg",
",",
"(",
"(",
"AggregateFunction",
")",
"expression",
")",
".",
"getIdentifier",
"(",
")",
",",
"expression",
")",
";",
"String",
"rightValue",
"=",
"(",
"(",
"ComparisonExpression",
")",
"conditionalExpression",
")",
".",
"getRightExpression",
"(",
")",
".",
"toParsedText",
"(",
")",
";",
"return",
"validateBucket",
"(",
"leftValue",
".",
"toString",
"(",
")",
",",
"rightValue",
",",
"(",
"(",
"ComparisonExpression",
")",
"conditionalExpression",
")",
".",
"getIdentifier",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"LogicalExpression",
".",
"class",
".",
"isAssignableFrom",
"(",
"conditionalExpression",
".",
"getClass",
"(",
")",
")",
")",
"{",
"Expression",
"leftExpression",
"=",
"null",
",",
"rightExpression",
"=",
"null",
";",
"if",
"(",
"conditionalExpression",
"instanceof",
"AndExpression",
")",
"{",
"AndExpression",
"andExpression",
"=",
"(",
"AndExpression",
")",
"conditionalExpression",
";",
"leftExpression",
"=",
"andExpression",
".",
"getLeftExpression",
"(",
")",
";",
"rightExpression",
"=",
"andExpression",
".",
"getRightExpression",
"(",
")",
";",
"}",
"else",
"{",
"OrExpression",
"orExpression",
"=",
"(",
"OrExpression",
")",
"conditionalExpression",
";",
"leftExpression",
"=",
"orExpression",
".",
"getLeftExpression",
"(",
")",
";",
"rightExpression",
"=",
"orExpression",
".",
"getRightExpression",
"(",
")",
";",
"}",
"return",
"validateBucket",
"(",
"isValidBucket",
"(",
"internalAgg",
",",
"query",
",",
"leftExpression",
")",
",",
"isValidBucket",
"(",
"internalAgg",
",",
"query",
",",
"rightExpression",
")",
",",
"(",
"(",
"LogicalExpression",
")",
"conditionalExpression",
")",
".",
"getIdentifier",
"(",
")",
")",
";",
"}",
"else",
"{",
"logger",
".",
"error",
"(",
"\"Expression \"",
"+",
"conditionalExpression",
"+",
"\" in having clause is not supported in Kundera\"",
")",
";",
"throw",
"new",
"UnsupportedOperationException",
"(",
"conditionalExpression",
"+",
"\" in having clause is not supported in Kundera\"",
")",
";",
"}",
"}"
] | Checks if is valid bucket.
@param internalAgg
the internal agg
@param query
the query
@param conditionalExpression
the conditional expression
@return true, if is valid bucket | [
"Checks",
"if",
"is",
"valid",
"bucket",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-elastic-search/src/main/java/com/impetus/client/es/utils/ESResponseWrapper.java#L395-L433 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CharsTrieBuilder.java | CharsTrieBuilder.writeValueAndFinal | @Deprecated
@Override
protected int writeValueAndFinal(int i, boolean isFinal) {
"""
{@inheritDoc}
@deprecated This API is ICU internal only.
@hide draft / provisional / internal are hidden on Android
"""
if(0<=i && i<=CharsTrie.kMaxOneUnitValue) {
return write(i|(isFinal ? CharsTrie.kValueIsFinal : 0));
}
int length;
if(i<0 || i>CharsTrie.kMaxTwoUnitValue) {
intUnits[0]=(char)(CharsTrie.kThreeUnitValueLead);
intUnits[1]=(char)(i>>16);
intUnits[2]=(char)i;
length=3;
// } else if(i<=CharsTrie.kMaxOneUnitValue) {
// intUnits[0]=(char)(i);
// length=1;
} else {
intUnits[0]=(char)(CharsTrie.kMinTwoUnitValueLead+(i>>16));
intUnits[1]=(char)i;
length=2;
}
intUnits[0]=(char)(intUnits[0]|(isFinal ? CharsTrie.kValueIsFinal : 0));
return write(intUnits, length);
} | java | @Deprecated
@Override
protected int writeValueAndFinal(int i, boolean isFinal) {
if(0<=i && i<=CharsTrie.kMaxOneUnitValue) {
return write(i|(isFinal ? CharsTrie.kValueIsFinal : 0));
}
int length;
if(i<0 || i>CharsTrie.kMaxTwoUnitValue) {
intUnits[0]=(char)(CharsTrie.kThreeUnitValueLead);
intUnits[1]=(char)(i>>16);
intUnits[2]=(char)i;
length=3;
// } else if(i<=CharsTrie.kMaxOneUnitValue) {
// intUnits[0]=(char)(i);
// length=1;
} else {
intUnits[0]=(char)(CharsTrie.kMinTwoUnitValueLead+(i>>16));
intUnits[1]=(char)i;
length=2;
}
intUnits[0]=(char)(intUnits[0]|(isFinal ? CharsTrie.kValueIsFinal : 0));
return write(intUnits, length);
} | [
"@",
"Deprecated",
"@",
"Override",
"protected",
"int",
"writeValueAndFinal",
"(",
"int",
"i",
",",
"boolean",
"isFinal",
")",
"{",
"if",
"(",
"0",
"<=",
"i",
"&&",
"i",
"<=",
"CharsTrie",
".",
"kMaxOneUnitValue",
")",
"{",
"return",
"write",
"(",
"i",
"|",
"(",
"isFinal",
"?",
"CharsTrie",
".",
"kValueIsFinal",
":",
"0",
")",
")",
";",
"}",
"int",
"length",
";",
"if",
"(",
"i",
"<",
"0",
"||",
"i",
">",
"CharsTrie",
".",
"kMaxTwoUnitValue",
")",
"{",
"intUnits",
"[",
"0",
"]",
"=",
"(",
"char",
")",
"(",
"CharsTrie",
".",
"kThreeUnitValueLead",
")",
";",
"intUnits",
"[",
"1",
"]",
"=",
"(",
"char",
")",
"(",
"i",
">>",
"16",
")",
";",
"intUnits",
"[",
"2",
"]",
"=",
"(",
"char",
")",
"i",
";",
"length",
"=",
"3",
";",
"// } else if(i<=CharsTrie.kMaxOneUnitValue) {",
"// intUnits[0]=(char)(i);",
"// length=1;",
"}",
"else",
"{",
"intUnits",
"[",
"0",
"]",
"=",
"(",
"char",
")",
"(",
"CharsTrie",
".",
"kMinTwoUnitValueLead",
"+",
"(",
"i",
">>",
"16",
")",
")",
";",
"intUnits",
"[",
"1",
"]",
"=",
"(",
"char",
")",
"i",
";",
"length",
"=",
"2",
";",
"}",
"intUnits",
"[",
"0",
"]",
"=",
"(",
"char",
")",
"(",
"intUnits",
"[",
"0",
"]",
"|",
"(",
"isFinal",
"?",
"CharsTrie",
".",
"kValueIsFinal",
":",
"0",
")",
")",
";",
"return",
"write",
"(",
"intUnits",
",",
"length",
")",
";",
"}"
] | {@inheritDoc}
@deprecated This API is ICU internal only.
@hide draft / provisional / internal are hidden on Android | [
"{"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CharsTrieBuilder.java#L195-L217 |
WorldwideAntimalarialResistanceNetwork/WWARN-Maps-Surveyor | MapCore/src/main/java/org/wwarn/mapcore/client/components/customwidgets/map/MapBuilder.java | MapBuilder.configureMapDimension | public MapBuilder configureMapDimension(Integer width, Integer height) {
"""
Setup map display properties
@param width value in px
@param height value in px
"""
this.mapHeight = height;
this.mapWidth = width;
return this;
} | java | public MapBuilder configureMapDimension(Integer width, Integer height) {
this.mapHeight = height;
this.mapWidth = width;
return this;
} | [
"public",
"MapBuilder",
"configureMapDimension",
"(",
"Integer",
"width",
",",
"Integer",
"height",
")",
"{",
"this",
".",
"mapHeight",
"=",
"height",
";",
"this",
".",
"mapWidth",
"=",
"width",
";",
"return",
"this",
";",
"}"
] | Setup map display properties
@param width value in px
@param height value in px | [
"Setup",
"map",
"display",
"properties"
] | train | https://github.com/WorldwideAntimalarialResistanceNetwork/WWARN-Maps-Surveyor/blob/224280bcd6e8045bda6b673584caf0aea5e4c841/MapCore/src/main/java/org/wwarn/mapcore/client/components/customwidgets/map/MapBuilder.java#L100-L104 |
KostyaSha/yet-another-docker-plugin | yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerCloud.java | DockerCloud.runContainer | public String runContainer(DockerSlaveTemplate slaveTemplate) throws DockerException, IOException {
"""
Run docker container for given template
@return container id
"""
final DockerCreateContainer dockerCreateContainer = slaveTemplate.getDockerContainerLifecycle().getCreateContainer();
final String image = slaveTemplate.getDockerContainerLifecycle().getImage();
CreateContainerCmd containerConfig = getClient().createContainerCmd(image);
// template specific options
dockerCreateContainer.fillContainerConfig(containerConfig, null);
// launcher specific options
slaveTemplate.getLauncher().appendContainerConfig(slaveTemplate, containerConfig);
// cloud specific options
appendContainerConfig(slaveTemplate, containerConfig);
// create
CreateContainerResponse response = containerConfig.exec();
String containerId = response.getId();
LOG.debug("Created container {}, for {}", containerId, getDisplayName());
slaveTemplate.getLauncher().afterContainerCreate(getClient(), containerId);
// start
StartContainerCmd startCommand = getClient().startContainerCmd(containerId);
try {
startCommand.exec();
LOG.debug("Running container {}, for {}", containerId, getDisplayName());
} catch (Exception ex) {
try {
getClient().logContainerCmd(containerId)
.withStdErr(true)
.withStdOut(true)
.exec(new MyLogContainerResultCallback())
.awaitCompletion();
} catch (Throwable t) {
LOG.warn("Can't get logs for container start", t);
}
throw ex;
}
return containerId;
} | java | public String runContainer(DockerSlaveTemplate slaveTemplate) throws DockerException, IOException {
final DockerCreateContainer dockerCreateContainer = slaveTemplate.getDockerContainerLifecycle().getCreateContainer();
final String image = slaveTemplate.getDockerContainerLifecycle().getImage();
CreateContainerCmd containerConfig = getClient().createContainerCmd(image);
// template specific options
dockerCreateContainer.fillContainerConfig(containerConfig, null);
// launcher specific options
slaveTemplate.getLauncher().appendContainerConfig(slaveTemplate, containerConfig);
// cloud specific options
appendContainerConfig(slaveTemplate, containerConfig);
// create
CreateContainerResponse response = containerConfig.exec();
String containerId = response.getId();
LOG.debug("Created container {}, for {}", containerId, getDisplayName());
slaveTemplate.getLauncher().afterContainerCreate(getClient(), containerId);
// start
StartContainerCmd startCommand = getClient().startContainerCmd(containerId);
try {
startCommand.exec();
LOG.debug("Running container {}, for {}", containerId, getDisplayName());
} catch (Exception ex) {
try {
getClient().logContainerCmd(containerId)
.withStdErr(true)
.withStdOut(true)
.exec(new MyLogContainerResultCallback())
.awaitCompletion();
} catch (Throwable t) {
LOG.warn("Can't get logs for container start", t);
}
throw ex;
}
return containerId;
} | [
"public",
"String",
"runContainer",
"(",
"DockerSlaveTemplate",
"slaveTemplate",
")",
"throws",
"DockerException",
",",
"IOException",
"{",
"final",
"DockerCreateContainer",
"dockerCreateContainer",
"=",
"slaveTemplate",
".",
"getDockerContainerLifecycle",
"(",
")",
".",
"getCreateContainer",
"(",
")",
";",
"final",
"String",
"image",
"=",
"slaveTemplate",
".",
"getDockerContainerLifecycle",
"(",
")",
".",
"getImage",
"(",
")",
";",
"CreateContainerCmd",
"containerConfig",
"=",
"getClient",
"(",
")",
".",
"createContainerCmd",
"(",
"image",
")",
";",
"// template specific options",
"dockerCreateContainer",
".",
"fillContainerConfig",
"(",
"containerConfig",
",",
"null",
")",
";",
"// launcher specific options",
"slaveTemplate",
".",
"getLauncher",
"(",
")",
".",
"appendContainerConfig",
"(",
"slaveTemplate",
",",
"containerConfig",
")",
";",
"// cloud specific options",
"appendContainerConfig",
"(",
"slaveTemplate",
",",
"containerConfig",
")",
";",
"// create",
"CreateContainerResponse",
"response",
"=",
"containerConfig",
".",
"exec",
"(",
")",
";",
"String",
"containerId",
"=",
"response",
".",
"getId",
"(",
")",
";",
"LOG",
".",
"debug",
"(",
"\"Created container {}, for {}\"",
",",
"containerId",
",",
"getDisplayName",
"(",
")",
")",
";",
"slaveTemplate",
".",
"getLauncher",
"(",
")",
".",
"afterContainerCreate",
"(",
"getClient",
"(",
")",
",",
"containerId",
")",
";",
"// start",
"StartContainerCmd",
"startCommand",
"=",
"getClient",
"(",
")",
".",
"startContainerCmd",
"(",
"containerId",
")",
";",
"try",
"{",
"startCommand",
".",
"exec",
"(",
")",
";",
"LOG",
".",
"debug",
"(",
"\"Running container {}, for {}\"",
",",
"containerId",
",",
"getDisplayName",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"try",
"{",
"getClient",
"(",
")",
".",
"logContainerCmd",
"(",
"containerId",
")",
".",
"withStdErr",
"(",
"true",
")",
".",
"withStdOut",
"(",
"true",
")",
".",
"exec",
"(",
"new",
"MyLogContainerResultCallback",
"(",
")",
")",
".",
"awaitCompletion",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"Can't get logs for container start\"",
",",
"t",
")",
";",
"}",
"throw",
"ex",
";",
"}",
"return",
"containerId",
";",
"}"
] | Run docker container for given template
@return container id | [
"Run",
"docker",
"container",
"for",
"given",
"template"
] | train | https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerCloud.java#L161-L203 |
samskivert/samskivert | src/main/java/com/samskivert/util/ValueMarshaller.java | ValueMarshaller.unmarshal | public static Object unmarshal (Class<?> type, String source)
throws Exception {
"""
Attempts to convert the specified value to an instance of the
specified object type.
@exception Exception thrown if no field parser exists for the
target type or if an error occurs while parsing the value.
"""
if (type.isEnum()) {
// we need to use a dummy enum type here as there's no way to ask Enum.valueOf to
// execute on an existentially typed enum; it all works out under the hood
@SuppressWarnings("unchecked") Class<Dummy> etype = (Class<Dummy>)type;
return Enum.valueOf(etype, source); // may throw an exception
}
// look up an argument parser for the field type
Parser parser = _parsers.get(type);
if (parser == null) {
throw new Exception(
"Don't know how to convert strings into values of type '" + type + "'.");
}
return parser.parse(source);
} | java | public static Object unmarshal (Class<?> type, String source)
throws Exception
{
if (type.isEnum()) {
// we need to use a dummy enum type here as there's no way to ask Enum.valueOf to
// execute on an existentially typed enum; it all works out under the hood
@SuppressWarnings("unchecked") Class<Dummy> etype = (Class<Dummy>)type;
return Enum.valueOf(etype, source); // may throw an exception
}
// look up an argument parser for the field type
Parser parser = _parsers.get(type);
if (parser == null) {
throw new Exception(
"Don't know how to convert strings into values of type '" + type + "'.");
}
return parser.parse(source);
} | [
"public",
"static",
"Object",
"unmarshal",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"String",
"source",
")",
"throws",
"Exception",
"{",
"if",
"(",
"type",
".",
"isEnum",
"(",
")",
")",
"{",
"// we need to use a dummy enum type here as there's no way to ask Enum.valueOf to",
"// execute on an existentially typed enum; it all works out under the hood",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Class",
"<",
"Dummy",
">",
"etype",
"=",
"(",
"Class",
"<",
"Dummy",
">",
")",
"type",
";",
"return",
"Enum",
".",
"valueOf",
"(",
"etype",
",",
"source",
")",
";",
"// may throw an exception",
"}",
"// look up an argument parser for the field type",
"Parser",
"parser",
"=",
"_parsers",
".",
"get",
"(",
"type",
")",
";",
"if",
"(",
"parser",
"==",
"null",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Don't know how to convert strings into values of type '\"",
"+",
"type",
"+",
"\"'.\"",
")",
";",
"}",
"return",
"parser",
".",
"parse",
"(",
"source",
")",
";",
"}"
] | Attempts to convert the specified value to an instance of the
specified object type.
@exception Exception thrown if no field parser exists for the
target type or if an error occurs while parsing the value. | [
"Attempts",
"to",
"convert",
"the",
"specified",
"value",
"to",
"an",
"instance",
"of",
"the",
"specified",
"object",
"type",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/ValueMarshaller.java#L27-L43 |
Azure/azure-sdk-for-java | sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/TransparentDataEncryptionsInner.java | TransparentDataEncryptionsInner.createOrUpdate | public TransparentDataEncryptionInner createOrUpdate(String resourceGroupName, String serverName, String databaseName) {
"""
Creates or updates a database's transparent data encryption configuration.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database for which setting the transparent data encryption applies.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the TransparentDataEncryptionInner object if successful.
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName).toBlocking().single().body();
} | java | public TransparentDataEncryptionInner createOrUpdate(String resourceGroupName, String serverName, String databaseName) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName).toBlocking().single().body();
} | [
"public",
"TransparentDataEncryptionInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
"databaseName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Creates or updates a database's transparent data encryption configuration.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database for which setting the transparent data encryption applies.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the TransparentDataEncryptionInner object if successful. | [
"Creates",
"or",
"updates",
"a",
"database",
"s",
"transparent",
"data",
"encryption",
"configuration",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/TransparentDataEncryptionsInner.java#L78-L80 |
jbundle/jbundle | base/screen/view/xml/src/main/java/org/jbundle/base/screen/view/xml/XBaseMenuScreen.java | XBaseMenuScreen.printControl | public boolean printControl(PrintWriter out, int iPrintOptions) {
"""
Code to display a Menu.
@exception DBException File exception.
"""
boolean bFieldsFound = true; // This will keep screen from printing (non-existent sub-fields)
MenusModel recMenus = (MenusModel)((BaseMenuScreen)this.getScreenField()).getMainRecord();
if ((recMenus.getField(MenusModel.XML_DATA).isNull()) || (recMenus.getField(MenusModel.XML_DATA).toString().startsWith("<HTML>")) || (recMenus.getField(Menus.XML_DATA).toString().startsWith("<html>")))
{
String filename = ((PropertiesField)recMenus.getField(MenusModel.PARAMS)).getProperty(DBParams.XML);
if ((filename != null) && (filename.length() > 0))
{
InputStream streamIn = this.getTask().getInputStream(filename);
if (streamIn == null)
{
Utility.getLogger().warning("XmlFile not found " + filename);
return false;
}
String str = Utility.transferURLStream(null, null, new InputStreamReader(streamIn));
recMenus.getField(MenusModel.XML_DATA).setString(str);
}
}
if (!recMenus.getField(MenusModel.XML_DATA).isNull())
{
String str = recMenus.getField(Menus.XML_DATA).toString();
str = Utility.replaceResources(str, null, null, (BaseMenuScreen)this.getScreenField());
recMenus.getField(MenusModel.XML_DATA).setString(str);
}
String strContentArea = recMenus.getSubMenuXML();
out.println(strContentArea);
return bFieldsFound;
} | java | public boolean printControl(PrintWriter out, int iPrintOptions)
{
boolean bFieldsFound = true; // This will keep screen from printing (non-existent sub-fields)
MenusModel recMenus = (MenusModel)((BaseMenuScreen)this.getScreenField()).getMainRecord();
if ((recMenus.getField(MenusModel.XML_DATA).isNull()) || (recMenus.getField(MenusModel.XML_DATA).toString().startsWith("<HTML>")) || (recMenus.getField(Menus.XML_DATA).toString().startsWith("<html>")))
{
String filename = ((PropertiesField)recMenus.getField(MenusModel.PARAMS)).getProperty(DBParams.XML);
if ((filename != null) && (filename.length() > 0))
{
InputStream streamIn = this.getTask().getInputStream(filename);
if (streamIn == null)
{
Utility.getLogger().warning("XmlFile not found " + filename);
return false;
}
String str = Utility.transferURLStream(null, null, new InputStreamReader(streamIn));
recMenus.getField(MenusModel.XML_DATA).setString(str);
}
}
if (!recMenus.getField(MenusModel.XML_DATA).isNull())
{
String str = recMenus.getField(Menus.XML_DATA).toString();
str = Utility.replaceResources(str, null, null, (BaseMenuScreen)this.getScreenField());
recMenus.getField(MenusModel.XML_DATA).setString(str);
}
String strContentArea = recMenus.getSubMenuXML();
out.println(strContentArea);
return bFieldsFound;
} | [
"public",
"boolean",
"printControl",
"(",
"PrintWriter",
"out",
",",
"int",
"iPrintOptions",
")",
"{",
"boolean",
"bFieldsFound",
"=",
"true",
";",
"// This will keep screen from printing (non-existent sub-fields)",
"MenusModel",
"recMenus",
"=",
"(",
"MenusModel",
")",
"(",
"(",
"BaseMenuScreen",
")",
"this",
".",
"getScreenField",
"(",
")",
")",
".",
"getMainRecord",
"(",
")",
";",
"if",
"(",
"(",
"recMenus",
".",
"getField",
"(",
"MenusModel",
".",
"XML_DATA",
")",
".",
"isNull",
"(",
")",
")",
"||",
"(",
"recMenus",
".",
"getField",
"(",
"MenusModel",
".",
"XML_DATA",
")",
".",
"toString",
"(",
")",
".",
"startsWith",
"(",
"\"<HTML>\"",
")",
")",
"||",
"(",
"recMenus",
".",
"getField",
"(",
"Menus",
".",
"XML_DATA",
")",
".",
"toString",
"(",
")",
".",
"startsWith",
"(",
"\"<html>\"",
")",
")",
")",
"{",
"String",
"filename",
"=",
"(",
"(",
"PropertiesField",
")",
"recMenus",
".",
"getField",
"(",
"MenusModel",
".",
"PARAMS",
")",
")",
".",
"getProperty",
"(",
"DBParams",
".",
"XML",
")",
";",
"if",
"(",
"(",
"filename",
"!=",
"null",
")",
"&&",
"(",
"filename",
".",
"length",
"(",
")",
">",
"0",
")",
")",
"{",
"InputStream",
"streamIn",
"=",
"this",
".",
"getTask",
"(",
")",
".",
"getInputStream",
"(",
"filename",
")",
";",
"if",
"(",
"streamIn",
"==",
"null",
")",
"{",
"Utility",
".",
"getLogger",
"(",
")",
".",
"warning",
"(",
"\"XmlFile not found \"",
"+",
"filename",
")",
";",
"return",
"false",
";",
"}",
"String",
"str",
"=",
"Utility",
".",
"transferURLStream",
"(",
"null",
",",
"null",
",",
"new",
"InputStreamReader",
"(",
"streamIn",
")",
")",
";",
"recMenus",
".",
"getField",
"(",
"MenusModel",
".",
"XML_DATA",
")",
".",
"setString",
"(",
"str",
")",
";",
"}",
"}",
"if",
"(",
"!",
"recMenus",
".",
"getField",
"(",
"MenusModel",
".",
"XML_DATA",
")",
".",
"isNull",
"(",
")",
")",
"{",
"String",
"str",
"=",
"recMenus",
".",
"getField",
"(",
"Menus",
".",
"XML_DATA",
")",
".",
"toString",
"(",
")",
";",
"str",
"=",
"Utility",
".",
"replaceResources",
"(",
"str",
",",
"null",
",",
"null",
",",
"(",
"BaseMenuScreen",
")",
"this",
".",
"getScreenField",
"(",
")",
")",
";",
"recMenus",
".",
"getField",
"(",
"MenusModel",
".",
"XML_DATA",
")",
".",
"setString",
"(",
"str",
")",
";",
"}",
"String",
"strContentArea",
"=",
"recMenus",
".",
"getSubMenuXML",
"(",
")",
";",
"out",
".",
"println",
"(",
"strContentArea",
")",
";",
"return",
"bFieldsFound",
";",
"}"
] | Code to display a Menu.
@exception DBException File exception. | [
"Code",
"to",
"display",
"a",
"Menu",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/xml/src/main/java/org/jbundle/base/screen/view/xml/XBaseMenuScreen.java#L82-L113 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/io/compress/CompressedSequentialWriter.java | CompressedSequentialWriter.seekToChunkStart | private void seekToChunkStart() {
"""
Seek to the offset where next compressed data chunk should be stored.
"""
if (getOnDiskFilePointer() != chunkOffset)
{
try
{
out.seek(chunkOffset);
}
catch (IOException e)
{
throw new FSReadError(e, getPath());
}
}
} | java | private void seekToChunkStart()
{
if (getOnDiskFilePointer() != chunkOffset)
{
try
{
out.seek(chunkOffset);
}
catch (IOException e)
{
throw new FSReadError(e, getPath());
}
}
} | [
"private",
"void",
"seekToChunkStart",
"(",
")",
"{",
"if",
"(",
"getOnDiskFilePointer",
"(",
")",
"!=",
"chunkOffset",
")",
"{",
"try",
"{",
"out",
".",
"seek",
"(",
"chunkOffset",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"FSReadError",
"(",
"e",
",",
"getPath",
"(",
")",
")",
";",
"}",
"}",
"}"
] | Seek to the offset where next compressed data chunk should be stored. | [
"Seek",
"to",
"the",
"offset",
"where",
"next",
"compressed",
"data",
"chunk",
"should",
"be",
"stored",
"."
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/compress/CompressedSequentialWriter.java#L243-L256 |
Whiley/WhileyCompiler | src/main/java/wyil/transform/VerificationConditionGenerator.java | VerificationConditionGenerator.translateAssign | private Context translateAssign(WyilFile.Stmt.Assign stmt, Context context) {
"""
Translate an assign statement. This updates the version number of the
underlying assigned variable.
@param stmt
@param wyalFile
@throws ResolutionError
"""
Tuple<WyilFile.LVal> lhs = stmt.getLeftHandSide();
Tuple<WyilFile.Expr> rhs = stmt.getRightHandSide();
WyilFile.LVal[][] lvals = new LVal[rhs.size()][];
Expr[][] rvals = new Expr[rhs.size()][];
// First, generate bundles
for (int i = 0, j = 0; i != rhs.size(); ++i) {
WyilFile.Expr rval = rhs.get(i);
lvals[i] = generateEmptyLValBundle(rval.getTypes(), lhs, j);
j += lvals[i].length;
Pair<Expr[], Context> p = generateRValBundle(rval, context);
rvals[i] = p.first();
context = p.second();
}
// Second, apply the bundles to implement assignments.
for (int i = 0; i != rhs.size(); ++i) {
context = translateAssign(lvals[i], rvals[i], context);
}
// Done
return context;
} | java | private Context translateAssign(WyilFile.Stmt.Assign stmt, Context context) {
Tuple<WyilFile.LVal> lhs = stmt.getLeftHandSide();
Tuple<WyilFile.Expr> rhs = stmt.getRightHandSide();
WyilFile.LVal[][] lvals = new LVal[rhs.size()][];
Expr[][] rvals = new Expr[rhs.size()][];
// First, generate bundles
for (int i = 0, j = 0; i != rhs.size(); ++i) {
WyilFile.Expr rval = rhs.get(i);
lvals[i] = generateEmptyLValBundle(rval.getTypes(), lhs, j);
j += lvals[i].length;
Pair<Expr[], Context> p = generateRValBundle(rval, context);
rvals[i] = p.first();
context = p.second();
}
// Second, apply the bundles to implement assignments.
for (int i = 0; i != rhs.size(); ++i) {
context = translateAssign(lvals[i], rvals[i], context);
}
// Done
return context;
} | [
"private",
"Context",
"translateAssign",
"(",
"WyilFile",
".",
"Stmt",
".",
"Assign",
"stmt",
",",
"Context",
"context",
")",
"{",
"Tuple",
"<",
"WyilFile",
".",
"LVal",
">",
"lhs",
"=",
"stmt",
".",
"getLeftHandSide",
"(",
")",
";",
"Tuple",
"<",
"WyilFile",
".",
"Expr",
">",
"rhs",
"=",
"stmt",
".",
"getRightHandSide",
"(",
")",
";",
"WyilFile",
".",
"LVal",
"[",
"]",
"[",
"]",
"lvals",
"=",
"new",
"LVal",
"[",
"rhs",
".",
"size",
"(",
")",
"]",
"[",
"",
"]",
";",
"Expr",
"[",
"]",
"[",
"]",
"rvals",
"=",
"new",
"Expr",
"[",
"rhs",
".",
"size",
"(",
")",
"]",
"[",
"",
"]",
";",
"// First, generate bundles",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"j",
"=",
"0",
";",
"i",
"!=",
"rhs",
".",
"size",
"(",
")",
";",
"++",
"i",
")",
"{",
"WyilFile",
".",
"Expr",
"rval",
"=",
"rhs",
".",
"get",
"(",
"i",
")",
";",
"lvals",
"[",
"i",
"]",
"=",
"generateEmptyLValBundle",
"(",
"rval",
".",
"getTypes",
"(",
")",
",",
"lhs",
",",
"j",
")",
";",
"j",
"+=",
"lvals",
"[",
"i",
"]",
".",
"length",
";",
"Pair",
"<",
"Expr",
"[",
"]",
",",
"Context",
">",
"p",
"=",
"generateRValBundle",
"(",
"rval",
",",
"context",
")",
";",
"rvals",
"[",
"i",
"]",
"=",
"p",
".",
"first",
"(",
")",
";",
"context",
"=",
"p",
".",
"second",
"(",
")",
";",
"}",
"// Second, apply the bundles to implement assignments.",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"!=",
"rhs",
".",
"size",
"(",
")",
";",
"++",
"i",
")",
"{",
"context",
"=",
"translateAssign",
"(",
"lvals",
"[",
"i",
"]",
",",
"rvals",
"[",
"i",
"]",
",",
"context",
")",
";",
"}",
"// Done",
"return",
"context",
";",
"}"
] | Translate an assign statement. This updates the version number of the
underlying assigned variable.
@param stmt
@param wyalFile
@throws ResolutionError | [
"Translate",
"an",
"assign",
"statement",
".",
"This",
"updates",
"the",
"version",
"number",
"of",
"the",
"underlying",
"assigned",
"variable",
"."
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/transform/VerificationConditionGenerator.java#L494-L514 |
amaembo/streamex | src/main/java/one/util/streamex/StreamEx.java | StreamEx.ofCombinations | public static StreamEx<int[]> ofCombinations(int n, int k) {
"""
Returns a new {@code StreamEx} of {@code int[]} arrays containing all the possible combinations of length {@code
k} consisting of numbers from 0 to {@code n-1} in lexicographic order.
<p>
Example: {@code StreamEx.ofCombinations(3, 2)} returns the stream of three elements: {@code [0, 1]}, {@code [0,
2]} and {@code [1, 2]} in this order.
@param n number of possible distinct elements
@param k number of elements in each combination
@return new sequential stream of possible combinations. Returns an empty stream if {@code k} is bigger
than {@code n}.
@throws IllegalArgumentException if n or k is negative or number of possible combinations exceeds {@code
Long.MAX_VALUE}.
@since 0.6.7
"""
checkNonNegative("k", k);
checkNonNegative("n", n);
if (k > n) {
return StreamEx.empty();
}
if (k == 0) {
return StreamEx.of(new int[0]);
}
long size = CombinationSpliterator.cnk(n, k);
int[] value = new int[k];
for (int i = 0; i < k; i++) {
value[i] = i;
}
return StreamEx.of(new CombinationSpliterator(n, size, 0, value));
} | java | public static StreamEx<int[]> ofCombinations(int n, int k) {
checkNonNegative("k", k);
checkNonNegative("n", n);
if (k > n) {
return StreamEx.empty();
}
if (k == 0) {
return StreamEx.of(new int[0]);
}
long size = CombinationSpliterator.cnk(n, k);
int[] value = new int[k];
for (int i = 0; i < k; i++) {
value[i] = i;
}
return StreamEx.of(new CombinationSpliterator(n, size, 0, value));
} | [
"public",
"static",
"StreamEx",
"<",
"int",
"[",
"]",
">",
"ofCombinations",
"(",
"int",
"n",
",",
"int",
"k",
")",
"{",
"checkNonNegative",
"(",
"\"k\"",
",",
"k",
")",
";",
"checkNonNegative",
"(",
"\"n\"",
",",
"n",
")",
";",
"if",
"(",
"k",
">",
"n",
")",
"{",
"return",
"StreamEx",
".",
"empty",
"(",
")",
";",
"}",
"if",
"(",
"k",
"==",
"0",
")",
"{",
"return",
"StreamEx",
".",
"of",
"(",
"new",
"int",
"[",
"0",
"]",
")",
";",
"}",
"long",
"size",
"=",
"CombinationSpliterator",
".",
"cnk",
"(",
"n",
",",
"k",
")",
";",
"int",
"[",
"]",
"value",
"=",
"new",
"int",
"[",
"k",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"k",
";",
"i",
"++",
")",
"{",
"value",
"[",
"i",
"]",
"=",
"i",
";",
"}",
"return",
"StreamEx",
".",
"of",
"(",
"new",
"CombinationSpliterator",
"(",
"n",
",",
"size",
",",
"0",
",",
"value",
")",
")",
";",
"}"
] | Returns a new {@code StreamEx} of {@code int[]} arrays containing all the possible combinations of length {@code
k} consisting of numbers from 0 to {@code n-1} in lexicographic order.
<p>
Example: {@code StreamEx.ofCombinations(3, 2)} returns the stream of three elements: {@code [0, 1]}, {@code [0,
2]} and {@code [1, 2]} in this order.
@param n number of possible distinct elements
@param k number of elements in each combination
@return new sequential stream of possible combinations. Returns an empty stream if {@code k} is bigger
than {@code n}.
@throws IllegalArgumentException if n or k is negative or number of possible combinations exceeds {@code
Long.MAX_VALUE}.
@since 0.6.7 | [
"Returns",
"a",
"new",
"{",
"@code",
"StreamEx",
"}",
"of",
"{",
"@code",
"int",
"[]",
"}",
"arrays",
"containing",
"all",
"the",
"possible",
"combinations",
"of",
"length",
"{",
"@code",
"k",
"}",
"consisting",
"of",
"numbers",
"from",
"0",
"to",
"{",
"@code",
"n",
"-",
"1",
"}",
"in",
"lexicographic",
"order",
".",
"<p",
">",
"Example",
":",
"{",
"@code",
"StreamEx",
".",
"ofCombinations",
"(",
"3",
"2",
")",
"}",
"returns",
"the",
"stream",
"of",
"three",
"elements",
":",
"{",
"@code",
"[",
"0",
"1",
"]",
"}",
"{",
"@code",
"[",
"0",
"2",
"]",
"}",
"and",
"{",
"@code",
"[",
"1",
"2",
"]",
"}",
"in",
"this",
"order",
"."
] | train | https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/StreamEx.java#L2511-L2527 |
google/closure-templates | java/src/com/google/template/soy/shared/internal/AbstractGenerateSoyEscapingDirectiveCode.java | AbstractGenerateSoyEscapingDirectiveCode.writeStringLiteral | protected void writeStringLiteral(String value, StringBuilder out) {
"""
Appends a string literal with the given value onto the given buffer.
"""
out.append('\'').append(escapeOutputString(value)).append('\'');
} | java | protected void writeStringLiteral(String value, StringBuilder out) {
out.append('\'').append(escapeOutputString(value)).append('\'');
} | [
"protected",
"void",
"writeStringLiteral",
"(",
"String",
"value",
",",
"StringBuilder",
"out",
")",
"{",
"out",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"escapeOutputString",
"(",
"value",
")",
")",
".",
"append",
"(",
"'",
"'",
")",
";",
"}"
] | Appends a string literal with the given value onto the given buffer. | [
"Appends",
"a",
"string",
"literal",
"with",
"the",
"given",
"value",
"onto",
"the",
"given",
"buffer",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/AbstractGenerateSoyEscapingDirectiveCode.java#L455-L457 |
overturetool/overture | ide/debug/src/main/java/org/overture/ide/debug/utils/CharOperation.java | CharOperation.startsWith | public static final boolean startsWith(char[] array, char[] toBeFound) {
"""
Return <code>true</code> if array starts with the sequence of characters contained in toBeFound, otherwise
<code>false</code>.
@param array
@param toBeFound
@return
"""
int i = toBeFound.length;
if (array.length < i)
{
return false;
}
while (--i >= 0)
{
if (toBeFound[i] != array[i])
{
return false;
}
}
return true;
} | java | public static final boolean startsWith(char[] array, char[] toBeFound)
{
int i = toBeFound.length;
if (array.length < i)
{
return false;
}
while (--i >= 0)
{
if (toBeFound[i] != array[i])
{
return false;
}
}
return true;
} | [
"public",
"static",
"final",
"boolean",
"startsWith",
"(",
"char",
"[",
"]",
"array",
",",
"char",
"[",
"]",
"toBeFound",
")",
"{",
"int",
"i",
"=",
"toBeFound",
".",
"length",
";",
"if",
"(",
"array",
".",
"length",
"<",
"i",
")",
"{",
"return",
"false",
";",
"}",
"while",
"(",
"--",
"i",
">=",
"0",
")",
"{",
"if",
"(",
"toBeFound",
"[",
"i",
"]",
"!=",
"array",
"[",
"i",
"]",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Return <code>true</code> if array starts with the sequence of characters contained in toBeFound, otherwise
<code>false</code>.
@param array
@param toBeFound
@return | [
"Return",
"<code",
">",
"true<",
"/",
"code",
">",
"if",
"array",
"starts",
"with",
"the",
"sequence",
"of",
"characters",
"contained",
"in",
"toBeFound",
"otherwise",
"<code",
">",
"false<",
"/",
"code",
">",
"."
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/debug/src/main/java/org/overture/ide/debug/utils/CharOperation.java#L1302-L1317 |
apereo/cas | core/cas-server-core-tickets-api/src/main/java/org/apereo/cas/util/CoreTicketUtils.java | CoreTicketUtils.newTicketRegistryCipherExecutor | public static CipherExecutor newTicketRegistryCipherExecutor(final EncryptionRandomizedSigningJwtCryptographyProperties registry,
final String registryName) {
"""
New ticket registry cipher executor cipher executor.
@param registry the registry
@param registryName the registry name
@return the cipher executor
"""
return newTicketRegistryCipherExecutor(registry, false, registryName);
} | java | public static CipherExecutor newTicketRegistryCipherExecutor(final EncryptionRandomizedSigningJwtCryptographyProperties registry,
final String registryName) {
return newTicketRegistryCipherExecutor(registry, false, registryName);
} | [
"public",
"static",
"CipherExecutor",
"newTicketRegistryCipherExecutor",
"(",
"final",
"EncryptionRandomizedSigningJwtCryptographyProperties",
"registry",
",",
"final",
"String",
"registryName",
")",
"{",
"return",
"newTicketRegistryCipherExecutor",
"(",
"registry",
",",
"false",
",",
"registryName",
")",
";",
"}"
] | New ticket registry cipher executor cipher executor.
@param registry the registry
@param registryName the registry name
@return the cipher executor | [
"New",
"ticket",
"registry",
"cipher",
"executor",
"cipher",
"executor",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-tickets-api/src/main/java/org/apereo/cas/util/CoreTicketUtils.java#L29-L32 |
Mthwate/DatLib | src/main/java/com/mthwate/datlib/ImageUtils.java | ImageUtils.totalImageDiff | public static long totalImageDiff(BufferedImage img1, BufferedImage img2) {
"""
The total difference between two images calculated as the sum of the difference in RGB values of each pixel
the images MUST be the same dimensions.
@since 1.2
@param img1 the first image to be compared
@param img2 the second image to be compared
@return the difference between the two images
"""
int width = img1.getWidth();
int height = img1.getHeight();
if ((width != img2.getWidth()) || (height != img2.getHeight())) {
throw new IllegalArgumentException("Image dimensions do not match");
}
long diff = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb1 = img1.getRGB(x, y);
int rgb2 = img2.getRGB(x, y);
int a1 = ColorUtils.getAlpha(rgb1);
int r1 = ColorUtils.getRed(rgb1);
int g1 = ColorUtils.getGreen(rgb1);
int b1 = ColorUtils.getBlue(rgb1);
int a2 = ColorUtils.getAlpha(rgb2);
int r2 = ColorUtils.getRed(rgb2);
int g2 = ColorUtils.getGreen(rgb2);
int b2 = ColorUtils.getBlue(rgb2);
diff += Math.abs(a1 - a2);
diff += Math.abs(r1 - r2);
diff += Math.abs(g1 - g2);
diff += Math.abs(b1 - b2);
}
}
return diff;
} | java | public static long totalImageDiff(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
if ((width != img2.getWidth()) || (height != img2.getHeight())) {
throw new IllegalArgumentException("Image dimensions do not match");
}
long diff = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb1 = img1.getRGB(x, y);
int rgb2 = img2.getRGB(x, y);
int a1 = ColorUtils.getAlpha(rgb1);
int r1 = ColorUtils.getRed(rgb1);
int g1 = ColorUtils.getGreen(rgb1);
int b1 = ColorUtils.getBlue(rgb1);
int a2 = ColorUtils.getAlpha(rgb2);
int r2 = ColorUtils.getRed(rgb2);
int g2 = ColorUtils.getGreen(rgb2);
int b2 = ColorUtils.getBlue(rgb2);
diff += Math.abs(a1 - a2);
diff += Math.abs(r1 - r2);
diff += Math.abs(g1 - g2);
diff += Math.abs(b1 - b2);
}
}
return diff;
} | [
"public",
"static",
"long",
"totalImageDiff",
"(",
"BufferedImage",
"img1",
",",
"BufferedImage",
"img2",
")",
"{",
"int",
"width",
"=",
"img1",
".",
"getWidth",
"(",
")",
";",
"int",
"height",
"=",
"img1",
".",
"getHeight",
"(",
")",
";",
"if",
"(",
"(",
"width",
"!=",
"img2",
".",
"getWidth",
"(",
")",
")",
"||",
"(",
"height",
"!=",
"img2",
".",
"getHeight",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Image dimensions do not match\"",
")",
";",
"}",
"long",
"diff",
"=",
"0",
";",
"for",
"(",
"int",
"x",
"=",
"0",
";",
"x",
"<",
"width",
";",
"x",
"++",
")",
"{",
"for",
"(",
"int",
"y",
"=",
"0",
";",
"y",
"<",
"height",
";",
"y",
"++",
")",
"{",
"int",
"rgb1",
"=",
"img1",
".",
"getRGB",
"(",
"x",
",",
"y",
")",
";",
"int",
"rgb2",
"=",
"img2",
".",
"getRGB",
"(",
"x",
",",
"y",
")",
";",
"int",
"a1",
"=",
"ColorUtils",
".",
"getAlpha",
"(",
"rgb1",
")",
";",
"int",
"r1",
"=",
"ColorUtils",
".",
"getRed",
"(",
"rgb1",
")",
";",
"int",
"g1",
"=",
"ColorUtils",
".",
"getGreen",
"(",
"rgb1",
")",
";",
"int",
"b1",
"=",
"ColorUtils",
".",
"getBlue",
"(",
"rgb1",
")",
";",
"int",
"a2",
"=",
"ColorUtils",
".",
"getAlpha",
"(",
"rgb2",
")",
";",
"int",
"r2",
"=",
"ColorUtils",
".",
"getRed",
"(",
"rgb2",
")",
";",
"int",
"g2",
"=",
"ColorUtils",
".",
"getGreen",
"(",
"rgb2",
")",
";",
"int",
"b2",
"=",
"ColorUtils",
".",
"getBlue",
"(",
"rgb2",
")",
";",
"diff",
"+=",
"Math",
".",
"abs",
"(",
"a1",
"-",
"a2",
")",
";",
"diff",
"+=",
"Math",
".",
"abs",
"(",
"r1",
"-",
"r2",
")",
";",
"diff",
"+=",
"Math",
".",
"abs",
"(",
"g1",
"-",
"g2",
")",
";",
"diff",
"+=",
"Math",
".",
"abs",
"(",
"b1",
"-",
"b2",
")",
";",
"}",
"}",
"return",
"diff",
";",
"}"
] | The total difference between two images calculated as the sum of the difference in RGB values of each pixel
the images MUST be the same dimensions.
@since 1.2
@param img1 the first image to be compared
@param img2 the second image to be compared
@return the difference between the two images | [
"The",
"total",
"difference",
"between",
"two",
"images",
"calculated",
"as",
"the",
"sum",
"of",
"the",
"difference",
"in",
"RGB",
"values",
"of",
"each",
"pixel",
"the",
"images",
"MUST",
"be",
"the",
"same",
"dimensions",
"."
] | train | https://github.com/Mthwate/DatLib/blob/f0b3a9f9cf6fdc773d4f86234ebd95986c9b6077/src/main/java/com/mthwate/datlib/ImageUtils.java#L21-L51 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.service.location/src/com/ibm/ws/kernel/service/location/internal/FileLocator.java | FileLocator.findFileInFilePath | public static File findFileInFilePath(String name, Collection<File> pathList) {
"""
Look for given file in any of the specified directories, return the first
one found.
@param name
The name of the file to find
@param pathList
The list of directories to check
@return The File object if the file is found; null if name is null,
pathList is null or empty, or file is not found.
@throws SecurityException
If a security manager exists and its <code>{@link java.lang.SecurityManager#checkRead(java.lang.String)}</code> method denies read access to the file.
"""
if (name == null || pathList == null || pathList.size() == 0)
return null;
for (File dirPath : pathList) {
File result = getFile(dirPath, name);
if (result != null)
return result;
}
return null;
} | java | public static File findFileInFilePath(String name, Collection<File> pathList) {
if (name == null || pathList == null || pathList.size() == 0)
return null;
for (File dirPath : pathList) {
File result = getFile(dirPath, name);
if (result != null)
return result;
}
return null;
} | [
"public",
"static",
"File",
"findFileInFilePath",
"(",
"String",
"name",
",",
"Collection",
"<",
"File",
">",
"pathList",
")",
"{",
"if",
"(",
"name",
"==",
"null",
"||",
"pathList",
"==",
"null",
"||",
"pathList",
".",
"size",
"(",
")",
"==",
"0",
")",
"return",
"null",
";",
"for",
"(",
"File",
"dirPath",
":",
"pathList",
")",
"{",
"File",
"result",
"=",
"getFile",
"(",
"dirPath",
",",
"name",
")",
";",
"if",
"(",
"result",
"!=",
"null",
")",
"return",
"result",
";",
"}",
"return",
"null",
";",
"}"
] | Look for given file in any of the specified directories, return the first
one found.
@param name
The name of the file to find
@param pathList
The list of directories to check
@return The File object if the file is found; null if name is null,
pathList is null or empty, or file is not found.
@throws SecurityException
If a security manager exists and its <code>{@link java.lang.SecurityManager#checkRead(java.lang.String)}</code> method denies read access to the file. | [
"Look",
"for",
"given",
"file",
"in",
"any",
"of",
"the",
"specified",
"directories",
"return",
"the",
"first",
"one",
"found",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.service.location/src/com/ibm/ws/kernel/service/location/internal/FileLocator.java#L73-L83 |
phax/ph-oton | ph-oton-security/src/main/java/com/helger/photon/security/role/RoleManager.java | RoleManager.createPredefinedRole | @Nonnull
public IRole createPredefinedRole (@Nonnull @Nonempty final String sID,
@Nonnull @Nonempty final String sName,
@Nullable final String sDescription,
@Nullable final Map <String, String> aCustomAttrs) {
"""
Create a predefined role.
@param sID
The ID of the new role
@param sName
The name of the new role
@param sDescription
Optional description text. May be <code>null</code>.
@param aCustomAttrs
A set of custom attributes. May be <code>null</code>.
@return The created role and never <code>null</code>.
"""
// Create role
final Role aRole = new Role (StubObject.createForCurrentUserAndID (sID, aCustomAttrs), sName, sDescription);
m_aRWLock.writeLocked ( () -> {
// Store
internalCreateItem (aRole);
});
AuditHelper.onAuditCreateSuccess (Role.OT, aRole.getID (), "predefind-role", sName);
// Execute callback as the very last action
m_aCallbacks.forEach (aCB -> aCB.onRoleCreated (aRole, true));
return aRole;
} | java | @Nonnull
public IRole createPredefinedRole (@Nonnull @Nonempty final String sID,
@Nonnull @Nonempty final String sName,
@Nullable final String sDescription,
@Nullable final Map <String, String> aCustomAttrs)
{
// Create role
final Role aRole = new Role (StubObject.createForCurrentUserAndID (sID, aCustomAttrs), sName, sDescription);
m_aRWLock.writeLocked ( () -> {
// Store
internalCreateItem (aRole);
});
AuditHelper.onAuditCreateSuccess (Role.OT, aRole.getID (), "predefind-role", sName);
// Execute callback as the very last action
m_aCallbacks.forEach (aCB -> aCB.onRoleCreated (aRole, true));
return aRole;
} | [
"@",
"Nonnull",
"public",
"IRole",
"createPredefinedRole",
"(",
"@",
"Nonnull",
"@",
"Nonempty",
"final",
"String",
"sID",
",",
"@",
"Nonnull",
"@",
"Nonempty",
"final",
"String",
"sName",
",",
"@",
"Nullable",
"final",
"String",
"sDescription",
",",
"@",
"Nullable",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"aCustomAttrs",
")",
"{",
"// Create role",
"final",
"Role",
"aRole",
"=",
"new",
"Role",
"(",
"StubObject",
".",
"createForCurrentUserAndID",
"(",
"sID",
",",
"aCustomAttrs",
")",
",",
"sName",
",",
"sDescription",
")",
";",
"m_aRWLock",
".",
"writeLocked",
"(",
"(",
")",
"->",
"{",
"// Store",
"internalCreateItem",
"(",
"aRole",
")",
";",
"}",
")",
";",
"AuditHelper",
".",
"onAuditCreateSuccess",
"(",
"Role",
".",
"OT",
",",
"aRole",
".",
"getID",
"(",
")",
",",
"\"predefind-role\"",
",",
"sName",
")",
";",
"// Execute callback as the very last action",
"m_aCallbacks",
".",
"forEach",
"(",
"aCB",
"->",
"aCB",
".",
"onRoleCreated",
"(",
"aRole",
",",
"true",
")",
")",
";",
"return",
"aRole",
";",
"}"
] | Create a predefined role.
@param sID
The ID of the new role
@param sName
The name of the new role
@param sDescription
Optional description text. May be <code>null</code>.
@param aCustomAttrs
A set of custom attributes. May be <code>null</code>.
@return The created role and never <code>null</code>. | [
"Create",
"a",
"predefined",
"role",
"."
] | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-security/src/main/java/com/helger/photon/security/role/RoleManager.java#L118-L137 |
wcm-io/wcm-io-handler | media/src/main/java/io/wcm/handler/mediasource/inline/InlineRendition.java | InlineRendition.getRequestedDimension | private Dimension getRequestedDimension() {
"""
Requested dimensions either from media format or fixed dimensions from media args.
@return Requested dimensions
"""
// check for fixed dimensions from media args
if (mediaArgs.getFixedWidth() > 0 || mediaArgs.getFixedHeight() > 0) {
return new Dimension(mediaArgs.getFixedWidth(), mediaArgs.getFixedHeight());
}
// check for dimensions from mediaformat (evaluate only first media format)
MediaFormat[] mediaFormats = mediaArgs.getMediaFormats();
if (mediaFormats != null && mediaFormats.length > 0) {
Dimension dimension = mediaFormats[0].getMinDimension();
if (dimension != null) {
return dimension;
}
}
// fallback to 0/0 - no specific dimension requested
return new Dimension(0, 0);
} | java | private Dimension getRequestedDimension() {
// check for fixed dimensions from media args
if (mediaArgs.getFixedWidth() > 0 || mediaArgs.getFixedHeight() > 0) {
return new Dimension(mediaArgs.getFixedWidth(), mediaArgs.getFixedHeight());
}
// check for dimensions from mediaformat (evaluate only first media format)
MediaFormat[] mediaFormats = mediaArgs.getMediaFormats();
if (mediaFormats != null && mediaFormats.length > 0) {
Dimension dimension = mediaFormats[0].getMinDimension();
if (dimension != null) {
return dimension;
}
}
// fallback to 0/0 - no specific dimension requested
return new Dimension(0, 0);
} | [
"private",
"Dimension",
"getRequestedDimension",
"(",
")",
"{",
"// check for fixed dimensions from media args",
"if",
"(",
"mediaArgs",
".",
"getFixedWidth",
"(",
")",
">",
"0",
"||",
"mediaArgs",
".",
"getFixedHeight",
"(",
")",
">",
"0",
")",
"{",
"return",
"new",
"Dimension",
"(",
"mediaArgs",
".",
"getFixedWidth",
"(",
")",
",",
"mediaArgs",
".",
"getFixedHeight",
"(",
")",
")",
";",
"}",
"// check for dimensions from mediaformat (evaluate only first media format)",
"MediaFormat",
"[",
"]",
"mediaFormats",
"=",
"mediaArgs",
".",
"getMediaFormats",
"(",
")",
";",
"if",
"(",
"mediaFormats",
"!=",
"null",
"&&",
"mediaFormats",
".",
"length",
">",
"0",
")",
"{",
"Dimension",
"dimension",
"=",
"mediaFormats",
"[",
"0",
"]",
".",
"getMinDimension",
"(",
")",
";",
"if",
"(",
"dimension",
"!=",
"null",
")",
"{",
"return",
"dimension",
";",
"}",
"}",
"// fallback to 0/0 - no specific dimension requested",
"return",
"new",
"Dimension",
"(",
"0",
",",
"0",
")",
";",
"}"
] | Requested dimensions either from media format or fixed dimensions from media args.
@return Requested dimensions | [
"Requested",
"dimensions",
"either",
"from",
"media",
"format",
"or",
"fixed",
"dimensions",
"from",
"media",
"args",
"."
] | train | https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/mediasource/inline/InlineRendition.java#L326-L344 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.updateClosedListEntityRoleAsync | public Observable<OperationStatus> updateClosedListEntityRoleAsync(UUID appId, String versionId, UUID entityId, UUID roleId, UpdateClosedListEntityRoleOptionalParameter updateClosedListEntityRoleOptionalParameter) {
"""
Update an entity role for a given entity.
@param appId The application ID.
@param versionId The version ID.
@param entityId The entity ID.
@param roleId The entity role ID.
@param updateClosedListEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the OperationStatus object
"""
return updateClosedListEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId, updateClosedListEntityRoleOptionalParameter).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
} | java | public Observable<OperationStatus> updateClosedListEntityRoleAsync(UUID appId, String versionId, UUID entityId, UUID roleId, UpdateClosedListEntityRoleOptionalParameter updateClosedListEntityRoleOptionalParameter) {
return updateClosedListEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId, updateClosedListEntityRoleOptionalParameter).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"OperationStatus",
">",
"updateClosedListEntityRoleAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"entityId",
",",
"UUID",
"roleId",
",",
"UpdateClosedListEntityRoleOptionalParameter",
"updateClosedListEntityRoleOptionalParameter",
")",
"{",
"return",
"updateClosedListEntityRoleWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"entityId",
",",
"roleId",
",",
"updateClosedListEntityRoleOptionalParameter",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"OperationStatus",
">",
",",
"OperationStatus",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"OperationStatus",
"call",
"(",
"ServiceResponse",
"<",
"OperationStatus",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Update an entity role for a given entity.
@param appId The application ID.
@param versionId The version ID.
@param entityId The entity ID.
@param roleId The entity role ID.
@param updateClosedListEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the OperationStatus object | [
"Update",
"an",
"entity",
"role",
"for",
"a",
"given",
"entity",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L11679-L11686 |
pierre/serialization | smile/src/main/java/com/ning/metrics/serialization/smile/SmileEnvelopeEventDeserializer.java | SmileEnvelopeEventDeserializer.extractEvents | public static List<SmileEnvelopeEvent> extractEvents(final InputStream in) throws IOException {
"""
Extracts all events in the stream
Note: Stream must be formatted as an array of (serialized) SmileEnvelopeEvents.
@param in InputStream containing events
@return A list of SmileEnvelopeEvents
@throws IOException generic I/O exception
"""
final PushbackInputStream pbIn = new PushbackInputStream(in);
final byte firstByte = (byte) pbIn.read();
// EOF?
if (firstByte == -1) {
return null;
}
pbIn.unread(firstByte);
SmileEnvelopeEventDeserializer deser = (firstByte == SMILE_MARKER) ?
new SmileEnvelopeEventDeserializer(pbIn, false) :
new SmileEnvelopeEventDeserializer(pbIn, true);
final List<SmileEnvelopeEvent> events = new LinkedList<SmileEnvelopeEvent>();
while (deser.hasNextEvent()) {
SmileEnvelopeEvent event = deser.getNextEvent();
if (event == null) {
// TODO: this is NOT expected, should warn
break;
}
events.add(event);
}
return events;
} | java | public static List<SmileEnvelopeEvent> extractEvents(final InputStream in) throws IOException
{
final PushbackInputStream pbIn = new PushbackInputStream(in);
final byte firstByte = (byte) pbIn.read();
// EOF?
if (firstByte == -1) {
return null;
}
pbIn.unread(firstByte);
SmileEnvelopeEventDeserializer deser = (firstByte == SMILE_MARKER) ?
new SmileEnvelopeEventDeserializer(pbIn, false) :
new SmileEnvelopeEventDeserializer(pbIn, true);
final List<SmileEnvelopeEvent> events = new LinkedList<SmileEnvelopeEvent>();
while (deser.hasNextEvent()) {
SmileEnvelopeEvent event = deser.getNextEvent();
if (event == null) {
// TODO: this is NOT expected, should warn
break;
}
events.add(event);
}
return events;
} | [
"public",
"static",
"List",
"<",
"SmileEnvelopeEvent",
">",
"extractEvents",
"(",
"final",
"InputStream",
"in",
")",
"throws",
"IOException",
"{",
"final",
"PushbackInputStream",
"pbIn",
"=",
"new",
"PushbackInputStream",
"(",
"in",
")",
";",
"final",
"byte",
"firstByte",
"=",
"(",
"byte",
")",
"pbIn",
".",
"read",
"(",
")",
";",
"// EOF?",
"if",
"(",
"firstByte",
"==",
"-",
"1",
")",
"{",
"return",
"null",
";",
"}",
"pbIn",
".",
"unread",
"(",
"firstByte",
")",
";",
"SmileEnvelopeEventDeserializer",
"deser",
"=",
"(",
"firstByte",
"==",
"SMILE_MARKER",
")",
"?",
"new",
"SmileEnvelopeEventDeserializer",
"(",
"pbIn",
",",
"false",
")",
":",
"new",
"SmileEnvelopeEventDeserializer",
"(",
"pbIn",
",",
"true",
")",
";",
"final",
"List",
"<",
"SmileEnvelopeEvent",
">",
"events",
"=",
"new",
"LinkedList",
"<",
"SmileEnvelopeEvent",
">",
"(",
")",
";",
"while",
"(",
"deser",
".",
"hasNextEvent",
"(",
")",
")",
"{",
"SmileEnvelopeEvent",
"event",
"=",
"deser",
".",
"getNextEvent",
"(",
")",
";",
"if",
"(",
"event",
"==",
"null",
")",
"{",
"// TODO: this is NOT expected, should warn",
"break",
";",
"}",
"events",
".",
"add",
"(",
"event",
")",
";",
"}",
"return",
"events",
";",
"}"
] | Extracts all events in the stream
Note: Stream must be formatted as an array of (serialized) SmileEnvelopeEvents.
@param in InputStream containing events
@return A list of SmileEnvelopeEvents
@throws IOException generic I/O exception | [
"Extracts",
"all",
"events",
"in",
"the",
"stream",
"Note",
":",
"Stream",
"must",
"be",
"formatted",
"as",
"an",
"array",
"of",
"(",
"serialized",
")",
"SmileEnvelopeEvents",
"."
] | train | https://github.com/pierre/serialization/blob/b15b7c749ba78bfe94dce8fc22f31b30b2e6830b/smile/src/main/java/com/ning/metrics/serialization/smile/SmileEnvelopeEventDeserializer.java#L164-L191 |
joelittlejohn/jsonschema2pojo | jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/TitleRule.java | TitleRule.apply | @Override
public JDocComment apply(String nodeName, JsonNode node, JsonNode parent, JDocCommentable generatableType, Schema schema) {
"""
Applies this schema rule to take the required code generation steps.
<p>
When a title node is found and applied with this rule, the value of the
title is added as a JavaDoc comment. This rule is typically applied to
the generated field, generated getter and generated setter for the
property.
<p>
Note that the title is always inserted at the top of the JavaDoc comment.
@param nodeName
the name of the property to which this title applies
@param node
the "title" schema node
@param parent
the parent node
@param generatableType
comment-able code generation construct, usually a field or
method, which should have this title applied
@return the JavaDoc comment created to contain the title
"""
JDocComment javadoc = generatableType.javadoc();
javadoc.add(0, node.asText() + "\n<p>\n");
return javadoc;
} | java | @Override
public JDocComment apply(String nodeName, JsonNode node, JsonNode parent, JDocCommentable generatableType, Schema schema) {
JDocComment javadoc = generatableType.javadoc();
javadoc.add(0, node.asText() + "\n<p>\n");
return javadoc;
} | [
"@",
"Override",
"public",
"JDocComment",
"apply",
"(",
"String",
"nodeName",
",",
"JsonNode",
"node",
",",
"JsonNode",
"parent",
",",
"JDocCommentable",
"generatableType",
",",
"Schema",
"schema",
")",
"{",
"JDocComment",
"javadoc",
"=",
"generatableType",
".",
"javadoc",
"(",
")",
";",
"javadoc",
".",
"add",
"(",
"0",
",",
"node",
".",
"asText",
"(",
")",
"+",
"\"\\n<p>\\n\"",
")",
";",
"return",
"javadoc",
";",
"}"
] | Applies this schema rule to take the required code generation steps.
<p>
When a title node is found and applied with this rule, the value of the
title is added as a JavaDoc comment. This rule is typically applied to
the generated field, generated getter and generated setter for the
property.
<p>
Note that the title is always inserted at the top of the JavaDoc comment.
@param nodeName
the name of the property to which this title applies
@param node
the "title" schema node
@param parent
the parent node
@param generatableType
comment-able code generation construct, usually a field or
method, which should have this title applied
@return the JavaDoc comment created to contain the title | [
"Applies",
"this",
"schema",
"rule",
"to",
"take",
"the",
"required",
"code",
"generation",
"steps",
".",
"<p",
">",
"When",
"a",
"title",
"node",
"is",
"found",
"and",
"applied",
"with",
"this",
"rule",
"the",
"value",
"of",
"the",
"title",
"is",
"added",
"as",
"a",
"JavaDoc",
"comment",
".",
"This",
"rule",
"is",
"typically",
"applied",
"to",
"the",
"generated",
"field",
"generated",
"getter",
"and",
"generated",
"setter",
"for",
"the",
"property",
".",
"<p",
">",
"Note",
"that",
"the",
"title",
"is",
"always",
"inserted",
"at",
"the",
"top",
"of",
"the",
"JavaDoc",
"comment",
"."
] | train | https://github.com/joelittlejohn/jsonschema2pojo/blob/0552b80db93214eb186e4ae45b40866cc1e7eb84/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/TitleRule.java#L56-L63 |
rhuss/jolokia | agent/core/src/main/java/org/jolokia/request/JmxSearchRequest.java | JmxSearchRequest.newCreator | static RequestCreator<JmxSearchRequest> newCreator() {
"""
Creator for {@link JmxSearchRequest}s
@return the creator implementation
"""
return new RequestCreator<JmxSearchRequest>() {
/** {@inheritDoc} */
public JmxSearchRequest create(Stack<String> pStack, ProcessingParameters pParams) throws MalformedObjectNameException {
return new JmxSearchRequest(pStack.pop(),pParams);
}
/** {@inheritDoc} */
public JmxSearchRequest create(Map<String, ?> requestMap, ProcessingParameters pParams)
throws MalformedObjectNameException {
return new JmxSearchRequest(requestMap,pParams);
}
};
} | java | static RequestCreator<JmxSearchRequest> newCreator() {
return new RequestCreator<JmxSearchRequest>() {
/** {@inheritDoc} */
public JmxSearchRequest create(Stack<String> pStack, ProcessingParameters pParams) throws MalformedObjectNameException {
return new JmxSearchRequest(pStack.pop(),pParams);
}
/** {@inheritDoc} */
public JmxSearchRequest create(Map<String, ?> requestMap, ProcessingParameters pParams)
throws MalformedObjectNameException {
return new JmxSearchRequest(requestMap,pParams);
}
};
} | [
"static",
"RequestCreator",
"<",
"JmxSearchRequest",
">",
"newCreator",
"(",
")",
"{",
"return",
"new",
"RequestCreator",
"<",
"JmxSearchRequest",
">",
"(",
")",
"{",
"/** {@inheritDoc} */",
"public",
"JmxSearchRequest",
"create",
"(",
"Stack",
"<",
"String",
">",
"pStack",
",",
"ProcessingParameters",
"pParams",
")",
"throws",
"MalformedObjectNameException",
"{",
"return",
"new",
"JmxSearchRequest",
"(",
"pStack",
".",
"pop",
"(",
")",
",",
"pParams",
")",
";",
"}",
"/** {@inheritDoc} */",
"public",
"JmxSearchRequest",
"create",
"(",
"Map",
"<",
"String",
",",
"?",
">",
"requestMap",
",",
"ProcessingParameters",
"pParams",
")",
"throws",
"MalformedObjectNameException",
"{",
"return",
"new",
"JmxSearchRequest",
"(",
"requestMap",
",",
"pParams",
")",
";",
"}",
"}",
";",
"}"
] | Creator for {@link JmxSearchRequest}s
@return the creator implementation | [
"Creator",
"for",
"{",
"@link",
"JmxSearchRequest",
"}",
"s"
] | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/request/JmxSearchRequest.java#L76-L89 |
sarl/sarl | contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyGenerator.java | PyGenerator._generate | protected void _generate(SarlAction action, PyAppendable it, IExtraLanguageGeneratorContext context) {
"""
Generate the given object.
@param action the action.
@param it the target for the generated content.
@param context the context.
"""
final String feature = getFeatureNameConverter(context).convertDeclarationName(action.getName(), action);
generateExecutable(feature, action, !action.isStatic(), action.isAbstract(),
action.getReturnType(),
getTypeBuilder().getDocumentation(action),
it, context);
} | java | protected void _generate(SarlAction action, PyAppendable it, IExtraLanguageGeneratorContext context) {
final String feature = getFeatureNameConverter(context).convertDeclarationName(action.getName(), action);
generateExecutable(feature, action, !action.isStatic(), action.isAbstract(),
action.getReturnType(),
getTypeBuilder().getDocumentation(action),
it, context);
} | [
"protected",
"void",
"_generate",
"(",
"SarlAction",
"action",
",",
"PyAppendable",
"it",
",",
"IExtraLanguageGeneratorContext",
"context",
")",
"{",
"final",
"String",
"feature",
"=",
"getFeatureNameConverter",
"(",
"context",
")",
".",
"convertDeclarationName",
"(",
"action",
".",
"getName",
"(",
")",
",",
"action",
")",
";",
"generateExecutable",
"(",
"feature",
",",
"action",
",",
"!",
"action",
".",
"isStatic",
"(",
")",
",",
"action",
".",
"isAbstract",
"(",
")",
",",
"action",
".",
"getReturnType",
"(",
")",
",",
"getTypeBuilder",
"(",
")",
".",
"getDocumentation",
"(",
"action",
")",
",",
"it",
",",
"context",
")",
";",
"}"
] | Generate the given object.
@param action the action.
@param it the target for the generated content.
@param context the context. | [
"Generate",
"the",
"given",
"object",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyGenerator.java#L955-L961 |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java | CacheConfigurationBuilder.withValueCopier | public CacheConfigurationBuilder<K, V> withValueCopier(Class<? extends Copier<V>> valueCopierClass) {
"""
Adds by-value semantic using the provided {@link Copier} class for the value on heap.
<p>
{@link Copier}s are what enable control of by-reference / by-value semantics for on-heap tier.
@param valueCopierClass the value copier class to use
@return a new builder with the added value copier
"""
return withCopier(new DefaultCopierConfiguration<>(requireNonNull(valueCopierClass, "Null value copier class"), DefaultCopierConfiguration.Type.VALUE));
} | java | public CacheConfigurationBuilder<K, V> withValueCopier(Class<? extends Copier<V>> valueCopierClass) {
return withCopier(new DefaultCopierConfiguration<>(requireNonNull(valueCopierClass, "Null value copier class"), DefaultCopierConfiguration.Type.VALUE));
} | [
"public",
"CacheConfigurationBuilder",
"<",
"K",
",",
"V",
">",
"withValueCopier",
"(",
"Class",
"<",
"?",
"extends",
"Copier",
"<",
"V",
">",
">",
"valueCopierClass",
")",
"{",
"return",
"withCopier",
"(",
"new",
"DefaultCopierConfiguration",
"<>",
"(",
"requireNonNull",
"(",
"valueCopierClass",
",",
"\"Null value copier class\"",
")",
",",
"DefaultCopierConfiguration",
".",
"Type",
".",
"VALUE",
")",
")",
";",
"}"
] | Adds by-value semantic using the provided {@link Copier} class for the value on heap.
<p>
{@link Copier}s are what enable control of by-reference / by-value semantics for on-heap tier.
@param valueCopierClass the value copier class to use
@return a new builder with the added value copier | [
"Adds",
"by",
"-",
"value",
"semantic",
"using",
"the",
"provided",
"{",
"@link",
"Copier",
"}",
"class",
"for",
"the",
"value",
"on",
"heap",
".",
"<p",
">",
"{",
"@link",
"Copier",
"}",
"s",
"are",
"what",
"enable",
"control",
"of",
"by",
"-",
"reference",
"/",
"by",
"-",
"value",
"semantics",
"for",
"on",
"-",
"heap",
"tier",
"."
] | train | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java#L444-L446 |
lucee/Lucee | core/src/main/java/lucee/runtime/net/ntp/NtpMessage.java | NtpMessage.referenceIdentifierToString | public static String referenceIdentifierToString(byte[] ref, short stratum, byte version) {
"""
Returns a string representation of a reference identifier according to the rules set out in RFC
2030.
@param ref
@param stratum
@param version
@return
"""
// From the RFC 2030:
// In the case of NTP Version 3 or Version 4 stratum-0 (unspecified)
// or stratum-1 (primary) servers, this is a four-character ASCII
// string, left justified and zero padded to 32 bits.
if (stratum == 0 || stratum == 1) {
return new String(ref);
}
// In NTP Version 3 secondary servers, this is the 32-bit IPv4
// address of the reference source.
else if (version == 3) {
return unsignedByteToShort(ref[0]) + "." + unsignedByteToShort(ref[1]) + "." + unsignedByteToShort(ref[2]) + "." + unsignedByteToShort(ref[3]);
}
// In NTP Version 4 secondary servers, this is the low order 32 bits
// of the latest transmit timestamp of the reference source.
else if (version == 4) {
return "" + ((unsignedByteToShort(ref[0]) / 256.0) + (unsignedByteToShort(ref[1]) / 65536.0) + (unsignedByteToShort(ref[2]) / 16777216.0)
+ (unsignedByteToShort(ref[3]) / 4294967296.0));
}
return "";
} | java | public static String referenceIdentifierToString(byte[] ref, short stratum, byte version) {
// From the RFC 2030:
// In the case of NTP Version 3 or Version 4 stratum-0 (unspecified)
// or stratum-1 (primary) servers, this is a four-character ASCII
// string, left justified and zero padded to 32 bits.
if (stratum == 0 || stratum == 1) {
return new String(ref);
}
// In NTP Version 3 secondary servers, this is the 32-bit IPv4
// address of the reference source.
else if (version == 3) {
return unsignedByteToShort(ref[0]) + "." + unsignedByteToShort(ref[1]) + "." + unsignedByteToShort(ref[2]) + "." + unsignedByteToShort(ref[3]);
}
// In NTP Version 4 secondary servers, this is the low order 32 bits
// of the latest transmit timestamp of the reference source.
else if (version == 4) {
return "" + ((unsignedByteToShort(ref[0]) / 256.0) + (unsignedByteToShort(ref[1]) / 65536.0) + (unsignedByteToShort(ref[2]) / 16777216.0)
+ (unsignedByteToShort(ref[3]) / 4294967296.0));
}
return "";
} | [
"public",
"static",
"String",
"referenceIdentifierToString",
"(",
"byte",
"[",
"]",
"ref",
",",
"short",
"stratum",
",",
"byte",
"version",
")",
"{",
"// From the RFC 2030:",
"// In the case of NTP Version 3 or Version 4 stratum-0 (unspecified)",
"// or stratum-1 (primary) servers, this is a four-character ASCII",
"// string, left justified and zero padded to 32 bits.",
"if",
"(",
"stratum",
"==",
"0",
"||",
"stratum",
"==",
"1",
")",
"{",
"return",
"new",
"String",
"(",
"ref",
")",
";",
"}",
"// In NTP Version 3 secondary servers, this is the 32-bit IPv4",
"// address of the reference source.",
"else",
"if",
"(",
"version",
"==",
"3",
")",
"{",
"return",
"unsignedByteToShort",
"(",
"ref",
"[",
"0",
"]",
")",
"+",
"\".\"",
"+",
"unsignedByteToShort",
"(",
"ref",
"[",
"1",
"]",
")",
"+",
"\".\"",
"+",
"unsignedByteToShort",
"(",
"ref",
"[",
"2",
"]",
")",
"+",
"\".\"",
"+",
"unsignedByteToShort",
"(",
"ref",
"[",
"3",
"]",
")",
";",
"}",
"// In NTP Version 4 secondary servers, this is the low order 32 bits",
"// of the latest transmit timestamp of the reference source.",
"else",
"if",
"(",
"version",
"==",
"4",
")",
"{",
"return",
"\"\"",
"+",
"(",
"(",
"unsignedByteToShort",
"(",
"ref",
"[",
"0",
"]",
")",
"/",
"256.0",
")",
"+",
"(",
"unsignedByteToShort",
"(",
"ref",
"[",
"1",
"]",
")",
"/",
"65536.0",
")",
"+",
"(",
"unsignedByteToShort",
"(",
"ref",
"[",
"2",
"]",
")",
"/",
"16777216.0",
")",
"+",
"(",
"unsignedByteToShort",
"(",
"ref",
"[",
"3",
"]",
")",
"/",
"4294967296.0",
")",
")",
";",
"}",
"return",
"\"\"",
";",
"}"
] | Returns a string representation of a reference identifier according to the rules set out in RFC
2030.
@param ref
@param stratum
@param version
@return | [
"Returns",
"a",
"string",
"representation",
"of",
"a",
"reference",
"identifier",
"according",
"to",
"the",
"rules",
"set",
"out",
"in",
"RFC",
"2030",
"."
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/net/ntp/NtpMessage.java#L361-L384 |
couchbase/java-dcp-client | src/main/java/com/couchbase/client/dcp/transport/netty/AuthHandler.java | AuthHandler.channelRead0 | @Override
protected void channelRead0(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception {
"""
Every time we recieve a message as part of the negotiation process, handle
it according to the req/res process.
"""
if (SaslListMechsResponse.is(msg)) {
handleListMechsResponse(ctx, msg);
} else if (SaslAuthResponse.is(msg)) {
handleAuthResponse(ctx, msg);
} else if (SaslStepResponse.is(msg)) {
checkIsAuthed(ctx, MessageUtil.getResponseStatus(msg));
} else {
throw new IllegalStateException("Received unexpected SASL response! " + MessageUtil.humanize(msg));
}
} | java | @Override
protected void channelRead0(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception {
if (SaslListMechsResponse.is(msg)) {
handleListMechsResponse(ctx, msg);
} else if (SaslAuthResponse.is(msg)) {
handleAuthResponse(ctx, msg);
} else if (SaslStepResponse.is(msg)) {
checkIsAuthed(ctx, MessageUtil.getResponseStatus(msg));
} else {
throw new IllegalStateException("Received unexpected SASL response! " + MessageUtil.humanize(msg));
}
} | [
"@",
"Override",
"protected",
"void",
"channelRead0",
"(",
"final",
"ChannelHandlerContext",
"ctx",
",",
"final",
"ByteBuf",
"msg",
")",
"throws",
"Exception",
"{",
"if",
"(",
"SaslListMechsResponse",
".",
"is",
"(",
"msg",
")",
")",
"{",
"handleListMechsResponse",
"(",
"ctx",
",",
"msg",
")",
";",
"}",
"else",
"if",
"(",
"SaslAuthResponse",
".",
"is",
"(",
"msg",
")",
")",
"{",
"handleAuthResponse",
"(",
"ctx",
",",
"msg",
")",
";",
"}",
"else",
"if",
"(",
"SaslStepResponse",
".",
"is",
"(",
"msg",
")",
")",
"{",
"checkIsAuthed",
"(",
"ctx",
",",
"MessageUtil",
".",
"getResponseStatus",
"(",
"msg",
")",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Received unexpected SASL response! \"",
"+",
"MessageUtil",
".",
"humanize",
"(",
"msg",
")",
")",
";",
"}",
"}"
] | Every time we recieve a message as part of the negotiation process, handle
it according to the req/res process. | [
"Every",
"time",
"we",
"recieve",
"a",
"message",
"as",
"part",
"of",
"the",
"negotiation",
"process",
"handle",
"it",
"according",
"to",
"the",
"req",
"/",
"res",
"process",
"."
] | train | https://github.com/couchbase/java-dcp-client/blob/75359d8c081d6c575f8087cf7c28d24ab24c6421/src/main/java/com/couchbase/client/dcp/transport/netty/AuthHandler.java#L107-L118 |
RKumsher/utils | src/main/java/com/github/rkumsher/date/RandomDateUtils.java | RandomDateUtils.randomInstantBefore | public static Instant randomInstantBefore(Instant before) {
"""
Returns a random {@link Instant} that is before the given {@link Instant}.
@param before the value that returned {@link Instant} must be before
@return the random {@link Instant}
@throws IllegalArgumentException if before is null or if before is equal to or before {@link
RandomDateUtils#MIN_INSTANT}
"""
checkArgument(before != null, "Before must be non-null");
checkArgument(before.isAfter(MIN_INSTANT), "Cannot produce date before %s", MIN_INSTANT);
return randomInstant(MIN_INSTANT, before);
} | java | public static Instant randomInstantBefore(Instant before) {
checkArgument(before != null, "Before must be non-null");
checkArgument(before.isAfter(MIN_INSTANT), "Cannot produce date before %s", MIN_INSTANT);
return randomInstant(MIN_INSTANT, before);
} | [
"public",
"static",
"Instant",
"randomInstantBefore",
"(",
"Instant",
"before",
")",
"{",
"checkArgument",
"(",
"before",
"!=",
"null",
",",
"\"Before must be non-null\"",
")",
";",
"checkArgument",
"(",
"before",
".",
"isAfter",
"(",
"MIN_INSTANT",
")",
",",
"\"Cannot produce date before %s\"",
",",
"MIN_INSTANT",
")",
";",
"return",
"randomInstant",
"(",
"MIN_INSTANT",
",",
"before",
")",
";",
"}"
] | Returns a random {@link Instant} that is before the given {@link Instant}.
@param before the value that returned {@link Instant} must be before
@return the random {@link Instant}
@throws IllegalArgumentException if before is null or if before is equal to or before {@link
RandomDateUtils#MIN_INSTANT} | [
"Returns",
"a",
"random",
"{",
"@link",
"Instant",
"}",
"that",
"is",
"before",
"the",
"given",
"{",
"@link",
"Instant",
"}",
"."
] | train | https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/date/RandomDateUtils.java#L510-L514 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/P2sVpnServerConfigurationsInner.java | P2sVpnServerConfigurationsInner.beginCreateOrUpdateAsync | public Observable<P2SVpnServerConfigurationInner> beginCreateOrUpdateAsync(String resourceGroupName, String virtualWanName, String p2SVpnServerConfigurationName, P2SVpnServerConfigurationInner p2SVpnServerConfigurationParameters) {
"""
Creates a P2SVpnServerConfiguration to associate with a VirtualWan if it doesn't exist else updates the existing P2SVpnServerConfiguration.
@param resourceGroupName The resource group name of the VirtualWan.
@param virtualWanName The name of the VirtualWan.
@param p2SVpnServerConfigurationName The name of the P2SVpnServerConfiguration.
@param p2SVpnServerConfigurationParameters Parameters supplied to create or Update a P2SVpnServerConfiguration.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the P2SVpnServerConfigurationInner object
"""
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, virtualWanName, p2SVpnServerConfigurationName, p2SVpnServerConfigurationParameters).map(new Func1<ServiceResponse<P2SVpnServerConfigurationInner>, P2SVpnServerConfigurationInner>() {
@Override
public P2SVpnServerConfigurationInner call(ServiceResponse<P2SVpnServerConfigurationInner> response) {
return response.body();
}
});
} | java | public Observable<P2SVpnServerConfigurationInner> beginCreateOrUpdateAsync(String resourceGroupName, String virtualWanName, String p2SVpnServerConfigurationName, P2SVpnServerConfigurationInner p2SVpnServerConfigurationParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, virtualWanName, p2SVpnServerConfigurationName, p2SVpnServerConfigurationParameters).map(new Func1<ServiceResponse<P2SVpnServerConfigurationInner>, P2SVpnServerConfigurationInner>() {
@Override
public P2SVpnServerConfigurationInner call(ServiceResponse<P2SVpnServerConfigurationInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"P2SVpnServerConfigurationInner",
">",
"beginCreateOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"virtualWanName",
",",
"String",
"p2SVpnServerConfigurationName",
",",
"P2SVpnServerConfigurationInner",
"p2SVpnServerConfigurationParameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"virtualWanName",
",",
"p2SVpnServerConfigurationName",
",",
"p2SVpnServerConfigurationParameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"P2SVpnServerConfigurationInner",
">",
",",
"P2SVpnServerConfigurationInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"P2SVpnServerConfigurationInner",
"call",
"(",
"ServiceResponse",
"<",
"P2SVpnServerConfigurationInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Creates a P2SVpnServerConfiguration to associate with a VirtualWan if it doesn't exist else updates the existing P2SVpnServerConfiguration.
@param resourceGroupName The resource group name of the VirtualWan.
@param virtualWanName The name of the VirtualWan.
@param p2SVpnServerConfigurationName The name of the P2SVpnServerConfiguration.
@param p2SVpnServerConfigurationParameters Parameters supplied to create or Update a P2SVpnServerConfiguration.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the P2SVpnServerConfigurationInner object | [
"Creates",
"a",
"P2SVpnServerConfiguration",
"to",
"associate",
"with",
"a",
"VirtualWan",
"if",
"it",
"doesn",
"t",
"exist",
"else",
"updates",
"the",
"existing",
"P2SVpnServerConfiguration",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/P2sVpnServerConfigurationsInner.java#L308-L315 |
infinispan/infinispan | commons/src/main/java/org/infinispan/commons/marshall/MarshallUtil.java | MarshallUtil.marshallCollection | public static <E> void marshallCollection(Collection<E> collection, ObjectOutput out) throws IOException {
"""
Marshall a {@link Collection}.
<p>
This method supports {@code null} {@code collection}.
@param collection {@link Collection} to marshal.
@param out {@link ObjectOutput} to write.
@param <E> Collection's element type.
@throws IOException If any of the usual Input/Output related exceptions occur.
"""
marshallCollection(collection, out, ObjectOutput::writeObject);
} | java | public static <E> void marshallCollection(Collection<E> collection, ObjectOutput out) throws IOException {
marshallCollection(collection, out, ObjectOutput::writeObject);
} | [
"public",
"static",
"<",
"E",
">",
"void",
"marshallCollection",
"(",
"Collection",
"<",
"E",
">",
"collection",
",",
"ObjectOutput",
"out",
")",
"throws",
"IOException",
"{",
"marshallCollection",
"(",
"collection",
",",
"out",
",",
"ObjectOutput",
"::",
"writeObject",
")",
";",
"}"
] | Marshall a {@link Collection}.
<p>
This method supports {@code null} {@code collection}.
@param collection {@link Collection} to marshal.
@param out {@link ObjectOutput} to write.
@param <E> Collection's element type.
@throws IOException If any of the usual Input/Output related exceptions occur. | [
"Marshall",
"a",
"{",
"@link",
"Collection",
"}",
".",
"<p",
">",
"This",
"method",
"supports",
"{",
"@code",
"null",
"}",
"{",
"@code",
"collection",
"}",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/commons/src/main/java/org/infinispan/commons/marshall/MarshallUtil.java#L229-L231 |
Azure/azure-sdk-for-java | sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabasesInner.java | DatabasesInner.importMethodAsync | public Observable<ImportExportResponseInner> importMethodAsync(String resourceGroupName, String serverName, ImportRequest parameters) {
"""
Imports a bacpac into a new database.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param parameters The required parameters for importing a Bacpac into a database.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return importMethodWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ImportExportResponseInner>, ImportExportResponseInner>() {
@Override
public ImportExportResponseInner call(ServiceResponse<ImportExportResponseInner> response) {
return response.body();
}
});
} | java | public Observable<ImportExportResponseInner> importMethodAsync(String resourceGroupName, String serverName, ImportRequest parameters) {
return importMethodWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ImportExportResponseInner>, ImportExportResponseInner>() {
@Override
public ImportExportResponseInner call(ServiceResponse<ImportExportResponseInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ImportExportResponseInner",
">",
"importMethodAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"ImportRequest",
"parameters",
")",
"{",
"return",
"importMethodWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ImportExportResponseInner",
">",
",",
"ImportExportResponseInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ImportExportResponseInner",
"call",
"(",
"ServiceResponse",
"<",
"ImportExportResponseInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Imports a bacpac into a new database.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param parameters The required parameters for importing a Bacpac into a database.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Imports",
"a",
"bacpac",
"into",
"a",
"new",
"database",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabasesInner.java#L1764-L1771 |
Jasig/uPortal | uPortal-web/src/main/java/org/apereo/portal/portlet/rendering/PortletRendererImpl.java | PortletRendererImpl.doRenderReplayCachedContent | protected PortletRenderResult doRenderReplayCachedContent(
IPortletWindow portletWindow,
HttpServletRequest httpServletRequest,
CacheState<CachedPortletData<PortletRenderResult>, PortletRenderResult> cacheState,
PortletOutputHandler portletOutputHandler,
RenderPart renderPart,
long baseExecutionTime)
throws IOException {
"""
Replay the cached content inside the {@link CachedPortletData} as the response to a doRender.
"""
enforceConfigPermission(httpServletRequest, portletWindow);
logger.debug(
"Replaying cached content for Render {} request to {}", renderPart, portletWindow);
final long renderStartTime = System.nanoTime();
final CachedPortletData<PortletRenderResult> cachedPortletData =
cacheState.getCachedPortletData();
cachedPortletData.replay(portletOutputHandler);
final long executionTime = baseExecutionTime + (System.nanoTime() - renderStartTime);
publishRenderEvent(portletWindow, httpServletRequest, renderPart, executionTime, true);
final PortletRenderResult portletResult = cachedPortletData.getPortletResult();
return new PortletRenderResult(portletResult, executionTime);
} | java | protected PortletRenderResult doRenderReplayCachedContent(
IPortletWindow portletWindow,
HttpServletRequest httpServletRequest,
CacheState<CachedPortletData<PortletRenderResult>, PortletRenderResult> cacheState,
PortletOutputHandler portletOutputHandler,
RenderPart renderPart,
long baseExecutionTime)
throws IOException {
enforceConfigPermission(httpServletRequest, portletWindow);
logger.debug(
"Replaying cached content for Render {} request to {}", renderPart, portletWindow);
final long renderStartTime = System.nanoTime();
final CachedPortletData<PortletRenderResult> cachedPortletData =
cacheState.getCachedPortletData();
cachedPortletData.replay(portletOutputHandler);
final long executionTime = baseExecutionTime + (System.nanoTime() - renderStartTime);
publishRenderEvent(portletWindow, httpServletRequest, renderPart, executionTime, true);
final PortletRenderResult portletResult = cachedPortletData.getPortletResult();
return new PortletRenderResult(portletResult, executionTime);
} | [
"protected",
"PortletRenderResult",
"doRenderReplayCachedContent",
"(",
"IPortletWindow",
"portletWindow",
",",
"HttpServletRequest",
"httpServletRequest",
",",
"CacheState",
"<",
"CachedPortletData",
"<",
"PortletRenderResult",
">",
",",
"PortletRenderResult",
">",
"cacheState",
",",
"PortletOutputHandler",
"portletOutputHandler",
",",
"RenderPart",
"renderPart",
",",
"long",
"baseExecutionTime",
")",
"throws",
"IOException",
"{",
"enforceConfigPermission",
"(",
"httpServletRequest",
",",
"portletWindow",
")",
";",
"logger",
".",
"debug",
"(",
"\"Replaying cached content for Render {} request to {}\"",
",",
"renderPart",
",",
"portletWindow",
")",
";",
"final",
"long",
"renderStartTime",
"=",
"System",
".",
"nanoTime",
"(",
")",
";",
"final",
"CachedPortletData",
"<",
"PortletRenderResult",
">",
"cachedPortletData",
"=",
"cacheState",
".",
"getCachedPortletData",
"(",
")",
";",
"cachedPortletData",
".",
"replay",
"(",
"portletOutputHandler",
")",
";",
"final",
"long",
"executionTime",
"=",
"baseExecutionTime",
"+",
"(",
"System",
".",
"nanoTime",
"(",
")",
"-",
"renderStartTime",
")",
";",
"publishRenderEvent",
"(",
"portletWindow",
",",
"httpServletRequest",
",",
"renderPart",
",",
"executionTime",
",",
"true",
")",
";",
"final",
"PortletRenderResult",
"portletResult",
"=",
"cachedPortletData",
".",
"getPortletResult",
"(",
")",
";",
"return",
"new",
"PortletRenderResult",
"(",
"portletResult",
",",
"executionTime",
")",
";",
"}"
] | Replay the cached content inside the {@link CachedPortletData} as the response to a doRender. | [
"Replay",
"the",
"cached",
"content",
"inside",
"the",
"{"
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-web/src/main/java/org/apereo/portal/portlet/rendering/PortletRendererImpl.java#L550-L576 |
intuit/QuickBooks-V3-Java-SDK | ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/PrepareRequestInterceptor.java | PrepareRequestInterceptor.isSendEmail | private boolean isSendEmail(Map<String, String> map) {
"""
Method returns true if this request should be send as email
@param map
@return
"""
return StringUtils.hasText(map.get(RequestElements.REQ_PARAM_ENTITY_SELECTOR))
&& map.get(RequestElements.REQ_PARAM_ENTITY_SELECTOR).equalsIgnoreCase(RequestElements.PARAM_SEND_SELECTOR);
} | java | private boolean isSendEmail(Map<String, String> map) {
return StringUtils.hasText(map.get(RequestElements.REQ_PARAM_ENTITY_SELECTOR))
&& map.get(RequestElements.REQ_PARAM_ENTITY_SELECTOR).equalsIgnoreCase(RequestElements.PARAM_SEND_SELECTOR);
} | [
"private",
"boolean",
"isSendEmail",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"map",
")",
"{",
"return",
"StringUtils",
".",
"hasText",
"(",
"map",
".",
"get",
"(",
"RequestElements",
".",
"REQ_PARAM_ENTITY_SELECTOR",
")",
")",
"&&",
"map",
".",
"get",
"(",
"RequestElements",
".",
"REQ_PARAM_ENTITY_SELECTOR",
")",
".",
"equalsIgnoreCase",
"(",
"RequestElements",
".",
"PARAM_SEND_SELECTOR",
")",
";",
"}"
] | Method returns true if this request should be send as email
@param map
@return | [
"Method",
"returns",
"true",
"if",
"this",
"request",
"should",
"be",
"send",
"as",
"email"
] | train | https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/PrepareRequestInterceptor.java#L586-L589 |
awin/rabbiteasy | rabbiteasy-core/src/main/java/com/zanox/rabbiteasy/MessageWriter.java | MessageWriter.writeBodyFromObject | public <T> void writeBodyFromObject(T bodyAsObject, Charset charset) {
"""
Writes the body by serializing the given object to XML.
@param bodyAsObject The body as object
@param <T> The object type
"""
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>)bodyAsObject.getClass();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Writer outputWriter = new OutputStreamWriter(outputStream, charset);
try {
Marshaller marshaller = JAXBContext.newInstance(clazz).createMarshaller();
if (clazz.isAnnotationPresent(XmlRootElement.class)) {
marshaller.marshal(bodyAsObject, outputWriter);
} else {
String tagName = unCapitalizedClassName(clazz);
JAXBElement<T> element = new JAXBElement<T>(new QName("", tagName), clazz, bodyAsObject);
marshaller.marshal(element, outputWriter);
}
} catch (JAXBException e) {
throw new RuntimeException(e);
}
byte[] bodyContent = outputStream.toByteArray();
message.contentType(Message.APPLICATION_XML)
.contentEncoding(charset.name());
message.body(bodyContent);
} | java | public <T> void writeBodyFromObject(T bodyAsObject, Charset charset) {
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>)bodyAsObject.getClass();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Writer outputWriter = new OutputStreamWriter(outputStream, charset);
try {
Marshaller marshaller = JAXBContext.newInstance(clazz).createMarshaller();
if (clazz.isAnnotationPresent(XmlRootElement.class)) {
marshaller.marshal(bodyAsObject, outputWriter);
} else {
String tagName = unCapitalizedClassName(clazz);
JAXBElement<T> element = new JAXBElement<T>(new QName("", tagName), clazz, bodyAsObject);
marshaller.marshal(element, outputWriter);
}
} catch (JAXBException e) {
throw new RuntimeException(e);
}
byte[] bodyContent = outputStream.toByteArray();
message.contentType(Message.APPLICATION_XML)
.contentEncoding(charset.name());
message.body(bodyContent);
} | [
"public",
"<",
"T",
">",
"void",
"writeBodyFromObject",
"(",
"T",
"bodyAsObject",
",",
"Charset",
"charset",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Class",
"<",
"T",
">",
"clazz",
"=",
"(",
"Class",
"<",
"T",
">",
")",
"bodyAsObject",
".",
"getClass",
"(",
")",
";",
"ByteArrayOutputStream",
"outputStream",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"Writer",
"outputWriter",
"=",
"new",
"OutputStreamWriter",
"(",
"outputStream",
",",
"charset",
")",
";",
"try",
"{",
"Marshaller",
"marshaller",
"=",
"JAXBContext",
".",
"newInstance",
"(",
"clazz",
")",
".",
"createMarshaller",
"(",
")",
";",
"if",
"(",
"clazz",
".",
"isAnnotationPresent",
"(",
"XmlRootElement",
".",
"class",
")",
")",
"{",
"marshaller",
".",
"marshal",
"(",
"bodyAsObject",
",",
"outputWriter",
")",
";",
"}",
"else",
"{",
"String",
"tagName",
"=",
"unCapitalizedClassName",
"(",
"clazz",
")",
";",
"JAXBElement",
"<",
"T",
">",
"element",
"=",
"new",
"JAXBElement",
"<",
"T",
">",
"(",
"new",
"QName",
"(",
"\"\"",
",",
"tagName",
")",
",",
"clazz",
",",
"bodyAsObject",
")",
";",
"marshaller",
".",
"marshal",
"(",
"element",
",",
"outputWriter",
")",
";",
"}",
"}",
"catch",
"(",
"JAXBException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"byte",
"[",
"]",
"bodyContent",
"=",
"outputStream",
".",
"toByteArray",
"(",
")",
";",
"message",
".",
"contentType",
"(",
"Message",
".",
"APPLICATION_XML",
")",
".",
"contentEncoding",
"(",
"charset",
".",
"name",
"(",
")",
")",
";",
"message",
".",
"body",
"(",
"bodyContent",
")",
";",
"}"
] | Writes the body by serializing the given object to XML.
@param bodyAsObject The body as object
@param <T> The object type | [
"Writes",
"the",
"body",
"by",
"serializing",
"the",
"given",
"object",
"to",
"XML",
"."
] | train | https://github.com/awin/rabbiteasy/blob/c161efda6c0f7ef319aedf09dfe40a4a90165510/rabbiteasy-core/src/main/java/com/zanox/rabbiteasy/MessageWriter.java#L80-L103 |
aws/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/event/ProgressInputStream.java | ProgressInputStream.inputStreamForResponse | public static InputStream inputStreamForResponse(InputStream is, AmazonWebServiceRequest req) {
"""
Returns an input stream for response progress tracking purposes. If
request/response progress tracking is not enabled, this method simply
return the given input stream as is.
@param is the response content input stream
"""
return req == null
? is
: new ResponseProgressInputStream(is, req.getGeneralProgressListener());
} | java | public static InputStream inputStreamForResponse(InputStream is, AmazonWebServiceRequest req) {
return req == null
? is
: new ResponseProgressInputStream(is, req.getGeneralProgressListener());
} | [
"public",
"static",
"InputStream",
"inputStreamForResponse",
"(",
"InputStream",
"is",
",",
"AmazonWebServiceRequest",
"req",
")",
"{",
"return",
"req",
"==",
"null",
"?",
"is",
":",
"new",
"ResponseProgressInputStream",
"(",
"is",
",",
"req",
".",
"getGeneralProgressListener",
"(",
")",
")",
";",
"}"
] | Returns an input stream for response progress tracking purposes. If
request/response progress tracking is not enabled, this method simply
return the given input stream as is.
@param is the response content input stream | [
"Returns",
"an",
"input",
"stream",
"for",
"response",
"progress",
"tracking",
"purposes",
".",
"If",
"request",
"/",
"response",
"progress",
"tracking",
"is",
"not",
"enabled",
"this",
"method",
"simply",
"return",
"the",
"given",
"input",
"stream",
"as",
"is",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/event/ProgressInputStream.java#L66-L70 |
ow2-chameleon/fuchsia | bases/knx/calimero/src/main/java/tuwien/auto/calimero/log/LogManager.java | LogManager.addWriter | public boolean addWriter(String logService, LogWriter writer) {
"""
Adds a log writer, either global or to a particular log service.
<p>
Note that the writer is added to the log service(s) regardless if it was already
added before.<br>
If the writer is added global, it will receive logging information from all log
services that are already registered or will be registered in the future.
@param logService name of a log service; to add the writer global, use an empty
string or <code>null</code>
@param writer log writer to add
@return true if the writer was added successfully,<br>
false a specified log service name was not found
@see LogService#addWriter(LogWriter)
"""
if (logService != null && logService.length() > 0) {
final LogService l = (LogService) loggers.get(logService);
if (l != null)
l.addWriter(writer);
return l != null;
}
synchronized (loggers) {
writers.add(writer);
for (final Iterator i = loggers.values().iterator(); i.hasNext();)
((LogService) i.next()).addWriter(writer);
return true;
}
} | java | public boolean addWriter(String logService, LogWriter writer)
{
if (logService != null && logService.length() > 0) {
final LogService l = (LogService) loggers.get(logService);
if (l != null)
l.addWriter(writer);
return l != null;
}
synchronized (loggers) {
writers.add(writer);
for (final Iterator i = loggers.values().iterator(); i.hasNext();)
((LogService) i.next()).addWriter(writer);
return true;
}
} | [
"public",
"boolean",
"addWriter",
"(",
"String",
"logService",
",",
"LogWriter",
"writer",
")",
"{",
"if",
"(",
"logService",
"!=",
"null",
"&&",
"logService",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"final",
"LogService",
"l",
"=",
"(",
"LogService",
")",
"loggers",
".",
"get",
"(",
"logService",
")",
";",
"if",
"(",
"l",
"!=",
"null",
")",
"l",
".",
"addWriter",
"(",
"writer",
")",
";",
"return",
"l",
"!=",
"null",
";",
"}",
"synchronized",
"(",
"loggers",
")",
"{",
"writers",
".",
"add",
"(",
"writer",
")",
";",
"for",
"(",
"final",
"Iterator",
"i",
"=",
"loggers",
".",
"values",
"(",
")",
".",
"iterator",
"(",
")",
";",
"i",
".",
"hasNext",
"(",
")",
";",
")",
"",
"(",
"(",
"LogService",
")",
"i",
".",
"next",
"(",
")",
")",
".",
"addWriter",
"(",
"writer",
")",
";",
"return",
"true",
";",
"}",
"}"
] | Adds a log writer, either global or to a particular log service.
<p>
Note that the writer is added to the log service(s) regardless if it was already
added before.<br>
If the writer is added global, it will receive logging information from all log
services that are already registered or will be registered in the future.
@param logService name of a log service; to add the writer global, use an empty
string or <code>null</code>
@param writer log writer to add
@return true if the writer was added successfully,<br>
false a specified log service name was not found
@see LogService#addWriter(LogWriter) | [
"Adds",
"a",
"log",
"writer",
"either",
"global",
"or",
"to",
"a",
"particular",
"log",
"service",
".",
"<p",
">",
"Note",
"that",
"the",
"writer",
"is",
"added",
"to",
"the",
"log",
"service",
"(",
"s",
")",
"regardless",
"if",
"it",
"was",
"already",
"added",
"before",
".",
"<br",
">",
"If",
"the",
"writer",
"is",
"added",
"global",
"it",
"will",
"receive",
"logging",
"information",
"from",
"all",
"log",
"services",
"that",
"are",
"already",
"registered",
"or",
"will",
"be",
"registered",
"in",
"the",
"future",
"."
] | train | https://github.com/ow2-chameleon/fuchsia/blob/4e9318eadbdeb945e529789f573b45386e619bed/bases/knx/calimero/src/main/java/tuwien/auto/calimero/log/LogManager.java#L181-L195 |
Jasig/uPortal | uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java | PropertiesManager.getPropertyAsFloat | public static float getPropertyAsFloat(String name)
throws MissingPropertyException, BadPropertyException {
"""
Returns the value of a property for a given name as a <code>float</code>
@param name the name of the requested property
@return value the property's value as a <code>float</code>
@throws MissingPropertyException - if the property is not set
@throws BadPropertyException - if the property cannot be parsed as a float
"""
if (PropertiesManager.props == null) loadProps();
try {
return Float.parseFloat(getProperty(name));
} catch (NumberFormatException nfe) {
throw new BadPropertyException(name, getProperty(name), "float");
}
} | java | public static float getPropertyAsFloat(String name)
throws MissingPropertyException, BadPropertyException {
if (PropertiesManager.props == null) loadProps();
try {
return Float.parseFloat(getProperty(name));
} catch (NumberFormatException nfe) {
throw new BadPropertyException(name, getProperty(name), "float");
}
} | [
"public",
"static",
"float",
"getPropertyAsFloat",
"(",
"String",
"name",
")",
"throws",
"MissingPropertyException",
",",
"BadPropertyException",
"{",
"if",
"(",
"PropertiesManager",
".",
"props",
"==",
"null",
")",
"loadProps",
"(",
")",
";",
"try",
"{",
"return",
"Float",
".",
"parseFloat",
"(",
"getProperty",
"(",
"name",
")",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",
"nfe",
")",
"{",
"throw",
"new",
"BadPropertyException",
"(",
"name",
",",
"getProperty",
"(",
"name",
")",
",",
"\"float\"",
")",
";",
"}",
"}"
] | Returns the value of a property for a given name as a <code>float</code>
@param name the name of the requested property
@return value the property's value as a <code>float</code>
@throws MissingPropertyException - if the property is not set
@throws BadPropertyException - if the property cannot be parsed as a float | [
"Returns",
"the",
"value",
"of",
"a",
"property",
"for",
"a",
"given",
"name",
"as",
"a",
"<code",
">",
"float<",
"/",
"code",
">"
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java#L273-L281 |
spotify/async-google-pubsub-client | src/main/java/com/spotify/google/cloud/pubsub/client/Pubsub.java | Pubsub.listTopics | public PubsubFuture<TopicList> listTopics(final String project) {
"""
List the Pub/Sub topics in a project. This will get the first page of topics. To enumerate all topics you might
have to make further calls to {@link #listTopics(String, String)} with the page token in order to get further
pages.
@param project The Google Cloud project.
@return A future that is completed when this request is completed.
"""
final String path = "projects/" + project + "/topics";
return get("list topics", path, readJson(TopicList.class));
} | java | public PubsubFuture<TopicList> listTopics(final String project) {
final String path = "projects/" + project + "/topics";
return get("list topics", path, readJson(TopicList.class));
} | [
"public",
"PubsubFuture",
"<",
"TopicList",
">",
"listTopics",
"(",
"final",
"String",
"project",
")",
"{",
"final",
"String",
"path",
"=",
"\"projects/\"",
"+",
"project",
"+",
"\"/topics\"",
";",
"return",
"get",
"(",
"\"list topics\"",
",",
"path",
",",
"readJson",
"(",
"TopicList",
".",
"class",
")",
")",
";",
"}"
] | List the Pub/Sub topics in a project. This will get the first page of topics. To enumerate all topics you might
have to make further calls to {@link #listTopics(String, String)} with the page token in order to get further
pages.
@param project The Google Cloud project.
@return A future that is completed when this request is completed. | [
"List",
"the",
"Pub",
"/",
"Sub",
"topics",
"in",
"a",
"project",
".",
"This",
"will",
"get",
"the",
"first",
"page",
"of",
"topics",
".",
"To",
"enumerate",
"all",
"topics",
"you",
"might",
"have",
"to",
"make",
"further",
"calls",
"to",
"{",
"@link",
"#listTopics",
"(",
"String",
"String",
")",
"}",
"with",
"the",
"page",
"token",
"in",
"order",
"to",
"get",
"further",
"pages",
"."
] | train | https://github.com/spotify/async-google-pubsub-client/blob/7d021528fa5bc29be458e6f210fa62f59b71d004/src/main/java/com/spotify/google/cloud/pubsub/client/Pubsub.java#L256-L259 |
JOML-CI/JOML | src/org/joml/Vector2d.java | Vector2d.fma | public Vector2d fma(Vector2dc a, Vector2dc b) {
"""
Add the component-wise multiplication of <code>a * b</code> to this vector.
@param a
the first multiplicand
@param b
the second multiplicand
@return a vector holding the result
"""
return fma(a, b, thisOrNew());
} | java | public Vector2d fma(Vector2dc a, Vector2dc b) {
return fma(a, b, thisOrNew());
} | [
"public",
"Vector2d",
"fma",
"(",
"Vector2dc",
"a",
",",
"Vector2dc",
"b",
")",
"{",
"return",
"fma",
"(",
"a",
",",
"b",
",",
"thisOrNew",
"(",
")",
")",
";",
"}"
] | Add the component-wise multiplication of <code>a * b</code> to this vector.
@param a
the first multiplicand
@param b
the second multiplicand
@return a vector holding the result | [
"Add",
"the",
"component",
"-",
"wise",
"multiplication",
"of",
"<code",
">",
"a",
"*",
"b<",
"/",
"code",
">",
"to",
"this",
"vector",
"."
] | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Vector2d.java#L1012-L1014 |
apereo/cas | core/cas-server-core-webflow-api/src/main/java/org/apereo/cas/web/flow/configurer/AbstractCasWebflowConfigurer.java | AbstractCasWebflowConfigurer.createClonedActionState | public void createClonedActionState(final Flow flow, final String actionStateId, final String actionStateIdToClone) {
"""
Clone and create action state.
@param flow the flow
@param actionStateId the action state id
@param actionStateIdToClone the action state id to clone
"""
val generateServiceTicket = getState(flow, actionStateIdToClone, ActionState.class);
val consentTicketAction = createActionState(flow, actionStateId);
cloneActionState(generateServiceTicket, consentTicketAction);
} | java | public void createClonedActionState(final Flow flow, final String actionStateId, final String actionStateIdToClone) {
val generateServiceTicket = getState(flow, actionStateIdToClone, ActionState.class);
val consentTicketAction = createActionState(flow, actionStateId);
cloneActionState(generateServiceTicket, consentTicketAction);
} | [
"public",
"void",
"createClonedActionState",
"(",
"final",
"Flow",
"flow",
",",
"final",
"String",
"actionStateId",
",",
"final",
"String",
"actionStateIdToClone",
")",
"{",
"val",
"generateServiceTicket",
"=",
"getState",
"(",
"flow",
",",
"actionStateIdToClone",
",",
"ActionState",
".",
"class",
")",
";",
"val",
"consentTicketAction",
"=",
"createActionState",
"(",
"flow",
",",
"actionStateId",
")",
";",
"cloneActionState",
"(",
"generateServiceTicket",
",",
"consentTicketAction",
")",
";",
"}"
] | Clone and create action state.
@param flow the flow
@param actionStateId the action state id
@param actionStateIdToClone the action state id to clone | [
"Clone",
"and",
"create",
"action",
"state",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-webflow-api/src/main/java/org/apereo/cas/web/flow/configurer/AbstractCasWebflowConfigurer.java#L711-L715 |
craftercms/deployer | src/main/java/org/craftercms/deployer/utils/ConfigUtils.java | ConfigUtils.getStringProperty | public static String getStringProperty(Configuration config, String key) throws DeployerConfigurationException {
"""
Returns the specified String property from the configuration
@param config the configuration
@param key the key of the property
@return the String value of the property, or null if not found
@throws DeployerConfigurationException if an error occurred
"""
return getStringProperty(config, key, null);
} | java | public static String getStringProperty(Configuration config, String key) throws DeployerConfigurationException {
return getStringProperty(config, key, null);
} | [
"public",
"static",
"String",
"getStringProperty",
"(",
"Configuration",
"config",
",",
"String",
"key",
")",
"throws",
"DeployerConfigurationException",
"{",
"return",
"getStringProperty",
"(",
"config",
",",
"key",
",",
"null",
")",
";",
"}"
] | Returns the specified String property from the configuration
@param config the configuration
@param key the key of the property
@return the String value of the property, or null if not found
@throws DeployerConfigurationException if an error occurred | [
"Returns",
"the",
"specified",
"String",
"property",
"from",
"the",
"configuration"
] | train | https://github.com/craftercms/deployer/blob/3ed446e3cc8af1055de2de6f871907f90ef27f63/src/main/java/org/craftercms/deployer/utils/ConfigUtils.java#L90-L92 |
alkacon/opencms-core | src/org/opencms/lock/CmsLockUtil.java | CmsLockUtil.tryUnlock | public static void tryUnlock(CmsObject cms, CmsResource resource) {
"""
Tries to unlock the given resource.<p>
Will ignore any failure.<p>
@param cms the cms context
@param resource the resource to unlock
"""
try {
cms.unlockResource(resource);
} catch (CmsException e) {
LOG.debug("Unable to unlock " + resource.getRootPath(), e);
}
} | java | public static void tryUnlock(CmsObject cms, CmsResource resource) {
try {
cms.unlockResource(resource);
} catch (CmsException e) {
LOG.debug("Unable to unlock " + resource.getRootPath(), e);
}
} | [
"public",
"static",
"void",
"tryUnlock",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"resource",
")",
"{",
"try",
"{",
"cms",
".",
"unlockResource",
"(",
"resource",
")",
";",
"}",
"catch",
"(",
"CmsException",
"e",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Unable to unlock \"",
"+",
"resource",
".",
"getRootPath",
"(",
")",
",",
"e",
")",
";",
"}",
"}"
] | Tries to unlock the given resource.<p>
Will ignore any failure.<p>
@param cms the cms context
@param resource the resource to unlock | [
"Tries",
"to",
"unlock",
"the",
"given",
"resource",
".",
"<p",
">",
"Will",
"ignore",
"any",
"failure",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/lock/CmsLockUtil.java#L229-L236 |
samskivert/samskivert | src/main/java/com/samskivert/servlet/user/UserManager.java | UserManager.init | public void init (Properties config, ConnectionProvider conprov)
throws PersistenceException {
"""
Prepares this user manager for operation. Presently the user manager requires the
following configuration information:
<ul>
<li><code>login_url</code>: Should be set to the URL to which to redirect a requester if
they are required to login before accessing the requested page. For example:
<pre>
login_url = /usermgmt/login.ajsp?return=%R
</pre>
The <code>%R</code> will be replaced with the URL encoded URL the user is currently
requesting (complete with query parameters) so that the login code can redirect the user
back to this request once they are authenticated.
</ul>
@param config the user manager configuration properties.
@param conprov the database connection provider that will be used to obtain a connection to
the user database.
"""
init(config, conprov, null);
} | java | public void init (Properties config, ConnectionProvider conprov)
throws PersistenceException
{
init(config, conprov, null);
} | [
"public",
"void",
"init",
"(",
"Properties",
"config",
",",
"ConnectionProvider",
"conprov",
")",
"throws",
"PersistenceException",
"{",
"init",
"(",
"config",
",",
"conprov",
",",
"null",
")",
";",
"}"
] | Prepares this user manager for operation. Presently the user manager requires the
following configuration information:
<ul>
<li><code>login_url</code>: Should be set to the URL to which to redirect a requester if
they are required to login before accessing the requested page. For example:
<pre>
login_url = /usermgmt/login.ajsp?return=%R
</pre>
The <code>%R</code> will be replaced with the URL encoded URL the user is currently
requesting (complete with query parameters) so that the login code can redirect the user
back to this request once they are authenticated.
</ul>
@param config the user manager configuration properties.
@param conprov the database connection provider that will be used to obtain a connection to
the user database. | [
"Prepares",
"this",
"user",
"manager",
"for",
"operation",
".",
"Presently",
"the",
"user",
"manager",
"requires",
"the",
"following",
"configuration",
"information",
":"
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/servlet/user/UserManager.java#L89-L93 |
pushbit/sprockets | src/main/java/net/sf/sprockets/sql/Statements.java | Statements.setStrings | public static PreparedStatement setStrings(int index, PreparedStatement stmt, String... params)
throws SQLException {
"""
Set the statement parameters, starting at the index, in the order of the params.
@since 3.0.0
"""
return set(index, stmt, null, null, params);
} | java | public static PreparedStatement setStrings(int index, PreparedStatement stmt, String... params)
throws SQLException {
return set(index, stmt, null, null, params);
} | [
"public",
"static",
"PreparedStatement",
"setStrings",
"(",
"int",
"index",
",",
"PreparedStatement",
"stmt",
",",
"String",
"...",
"params",
")",
"throws",
"SQLException",
"{",
"return",
"set",
"(",
"index",
",",
"stmt",
",",
"null",
",",
"null",
",",
"params",
")",
";",
"}"
] | Set the statement parameters, starting at the index, in the order of the params.
@since 3.0.0 | [
"Set",
"the",
"statement",
"parameters",
"starting",
"at",
"the",
"index",
"in",
"the",
"order",
"of",
"the",
"params",
"."
] | train | https://github.com/pushbit/sprockets/blob/5d967317cbb2374c69d33271d3c7b7311e1ea4ac/src/main/java/net/sf/sprockets/sql/Statements.java#L100-L103 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Trie2Writable.java | Trie2Writable.getDataBlock | private int getDataBlock(int c, boolean forLSCP) {
"""
No error checking for illegal arguments.
@hide draft / provisional / internal are hidden on Android
"""
int i2, oldBlock, newBlock;
i2=getIndex2Block(c, forLSCP);
i2+=(c>>UTRIE2_SHIFT_2)&UTRIE2_INDEX_2_MASK;
oldBlock=index2[i2];
if(isWritableBlock(oldBlock)) {
return oldBlock;
}
/* allocate a new data block */
newBlock=allocDataBlock(oldBlock);
setIndex2Entry(i2, newBlock);
return newBlock;
} | java | private int getDataBlock(int c, boolean forLSCP) {
int i2, oldBlock, newBlock;
i2=getIndex2Block(c, forLSCP);
i2+=(c>>UTRIE2_SHIFT_2)&UTRIE2_INDEX_2_MASK;
oldBlock=index2[i2];
if(isWritableBlock(oldBlock)) {
return oldBlock;
}
/* allocate a new data block */
newBlock=allocDataBlock(oldBlock);
setIndex2Entry(i2, newBlock);
return newBlock;
} | [
"private",
"int",
"getDataBlock",
"(",
"int",
"c",
",",
"boolean",
"forLSCP",
")",
"{",
"int",
"i2",
",",
"oldBlock",
",",
"newBlock",
";",
"i2",
"=",
"getIndex2Block",
"(",
"c",
",",
"forLSCP",
")",
";",
"i2",
"+=",
"(",
"c",
">>",
"UTRIE2_SHIFT_2",
")",
"&",
"UTRIE2_INDEX_2_MASK",
";",
"oldBlock",
"=",
"index2",
"[",
"i2",
"]",
";",
"if",
"(",
"isWritableBlock",
"(",
"oldBlock",
")",
")",
"{",
"return",
"oldBlock",
";",
"}",
"/* allocate a new data block */",
"newBlock",
"=",
"allocDataBlock",
"(",
"oldBlock",
")",
";",
"setIndex2Entry",
"(",
"i2",
",",
"newBlock",
")",
";",
"return",
"newBlock",
";",
"}"
] | No error checking for illegal arguments.
@hide draft / provisional / internal are hidden on Android | [
"No",
"error",
"checking",
"for",
"illegal",
"arguments",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Trie2Writable.java#L273-L288 |
BioPAX/Paxtools | paxtools-core/src/main/java/org/biopax/paxtools/io/BioPAXIOHandlerAdapter.java | BioPAXIOHandlerAdapter.resetLevel | protected final void resetLevel(BioPAXLevel level, BioPAXFactory factory) {
"""
Updates the level and factory for this I/O
(final - because used in the constructor)
@param level BioPAX Level
@param factory concrete BioPAX factory impl.
"""
this.level = (level != null) ? level : BioPAXLevel.L3;
this.factory = (factory != null) ? factory : this.level.getDefaultFactory();
// default flags
if (this.level == BioPAXLevel.L2)
{
this.fixReusedPEPs = true;
}
bp = this.level.getNameSpace();
resetEditorMap(); //implemented by concrete subclasses
} | java | protected final void resetLevel(BioPAXLevel level, BioPAXFactory factory)
{
this.level = (level != null) ? level : BioPAXLevel.L3;
this.factory = (factory != null) ? factory : this.level.getDefaultFactory();
// default flags
if (this.level == BioPAXLevel.L2)
{
this.fixReusedPEPs = true;
}
bp = this.level.getNameSpace();
resetEditorMap(); //implemented by concrete subclasses
} | [
"protected",
"final",
"void",
"resetLevel",
"(",
"BioPAXLevel",
"level",
",",
"BioPAXFactory",
"factory",
")",
"{",
"this",
".",
"level",
"=",
"(",
"level",
"!=",
"null",
")",
"?",
"level",
":",
"BioPAXLevel",
".",
"L3",
";",
"this",
".",
"factory",
"=",
"(",
"factory",
"!=",
"null",
")",
"?",
"factory",
":",
"this",
".",
"level",
".",
"getDefaultFactory",
"(",
")",
";",
"// default flags",
"if",
"(",
"this",
".",
"level",
"==",
"BioPAXLevel",
".",
"L2",
")",
"{",
"this",
".",
"fixReusedPEPs",
"=",
"true",
";",
"}",
"bp",
"=",
"this",
".",
"level",
".",
"getNameSpace",
"(",
")",
";",
"resetEditorMap",
"(",
")",
";",
"//implemented by concrete subclasses",
"}"
] | Updates the level and factory for this I/O
(final - because used in the constructor)
@param level BioPAX Level
@param factory concrete BioPAX factory impl. | [
"Updates",
"the",
"level",
"and",
"factory",
"for",
"this",
"I",
"/",
"O",
"(",
"final",
"-",
"because",
"used",
"in",
"the",
"constructor",
")"
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/paxtools-core/src/main/java/org/biopax/paxtools/io/BioPAXIOHandlerAdapter.java#L66-L80 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java | SimpleDocTreeVisitor.visitComment | @Override
public R visitComment(CommentTree node, P p) {
"""
{@inheritDoc} This implementation calls {@code defaultAction}.
@param node {@inheritDoc}
@param p {@inheritDoc}
@return the result of {@code defaultAction}
"""
return defaultAction(node, p);
} | java | @Override
public R visitComment(CommentTree node, P p) {
return defaultAction(node, p);
} | [
"@",
"Override",
"public",
"R",
"visitComment",
"(",
"CommentTree",
"node",
",",
"P",
"p",
")",
"{",
"return",
"defaultAction",
"(",
"node",
",",
"p",
")",
";",
"}"
] | {@inheritDoc} This implementation calls {@code defaultAction}.
@param node {@inheritDoc}
@param p {@inheritDoc}
@return the result of {@code defaultAction} | [
"{",
"@inheritDoc",
"}",
"This",
"implementation",
"calls",
"{",
"@code",
"defaultAction",
"}",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java#L129-L132 |
cdapio/tigon | tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/QueueEntryRow.java | QueueEntryRow.getQueueName | public static QueueName getQueueName(String appName, String flowName, KeyValue keyValue) {
"""
Extracts the queue name from the KeyValue row, which the row must be a queue entry.
"""
return getQueueName(appName, flowName, keyValue.getBuffer(), keyValue.getRowOffset(), keyValue.getRowLength());
} | java | public static QueueName getQueueName(String appName, String flowName, KeyValue keyValue) {
return getQueueName(appName, flowName, keyValue.getBuffer(), keyValue.getRowOffset(), keyValue.getRowLength());
} | [
"public",
"static",
"QueueName",
"getQueueName",
"(",
"String",
"appName",
",",
"String",
"flowName",
",",
"KeyValue",
"keyValue",
")",
"{",
"return",
"getQueueName",
"(",
"appName",
",",
"flowName",
",",
"keyValue",
".",
"getBuffer",
"(",
")",
",",
"keyValue",
".",
"getRowOffset",
"(",
")",
",",
"keyValue",
".",
"getRowLength",
"(",
")",
")",
";",
"}"
] | Extracts the queue name from the KeyValue row, which the row must be a queue entry. | [
"Extracts",
"the",
"queue",
"name",
"from",
"the",
"KeyValue",
"row",
"which",
"the",
"row",
"must",
"be",
"a",
"queue",
"entry",
"."
] | train | https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/QueueEntryRow.java#L108-L110 |
theHilikus/Event-manager | src/main/java/com/github/thehilikus/events/event_manager/GenericEventDispatcher.java | GenericEventDispatcher.addListener | public void addListener(T listener) {
"""
Adds a listener if it doesn't already exist. The event handler methods must have its first
argument as a descendant of {@link EventObject} <br>
The event handling methods must be declared directly in the listener and not in one of its
super-classes. This is a performance limitation
@param listener the object to notify
"""
Method[] declaredMethods = listener.getClass().getDeclaredMethods();
boolean found = false;
for (Method method : declaredMethods) { // loop only on declared methods to avoid
// calling
// empty Adapter methods on event fire
if (CALLBACK_NAME.equals(method.getName())) {
found = true;
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length >= 1 && EventObject.class.isAssignableFrom(parameterTypes[0])) { // since
// event
// methods
// have
// at
// least
// the
// event
// argument
register(listener, parameterTypes[0]);
}
}
}
if (!found) {
log.warn("[addListener] No callback method found in provided listener {}", listener);
}
} | java | public void addListener(T listener) {
Method[] declaredMethods = listener.getClass().getDeclaredMethods();
boolean found = false;
for (Method method : declaredMethods) { // loop only on declared methods to avoid
// calling
// empty Adapter methods on event fire
if (CALLBACK_NAME.equals(method.getName())) {
found = true;
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length >= 1 && EventObject.class.isAssignableFrom(parameterTypes[0])) { // since
// event
// methods
// have
// at
// least
// the
// event
// argument
register(listener, parameterTypes[0]);
}
}
}
if (!found) {
log.warn("[addListener] No callback method found in provided listener {}", listener);
}
} | [
"public",
"void",
"addListener",
"(",
"T",
"listener",
")",
"{",
"Method",
"[",
"]",
"declaredMethods",
"=",
"listener",
".",
"getClass",
"(",
")",
".",
"getDeclaredMethods",
"(",
")",
";",
"boolean",
"found",
"=",
"false",
";",
"for",
"(",
"Method",
"method",
":",
"declaredMethods",
")",
"{",
"// loop only on declared methods to avoid",
"// calling",
"// empty Adapter methods on event fire",
"if",
"(",
"CALLBACK_NAME",
".",
"equals",
"(",
"method",
".",
"getName",
"(",
")",
")",
")",
"{",
"found",
"=",
"true",
";",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
"=",
"method",
".",
"getParameterTypes",
"(",
")",
";",
"if",
"(",
"parameterTypes",
".",
"length",
">=",
"1",
"&&",
"EventObject",
".",
"class",
".",
"isAssignableFrom",
"(",
"parameterTypes",
"[",
"0",
"]",
")",
")",
"{",
"// since",
"// event",
"// methods",
"// have",
"// at",
"// least",
"// the",
"// event",
"// argument",
"register",
"(",
"listener",
",",
"parameterTypes",
"[",
"0",
"]",
")",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"found",
")",
"{",
"log",
".",
"warn",
"(",
"\"[addListener] No callback method found in provided listener {}\"",
",",
"listener",
")",
";",
"}",
"}"
] | Adds a listener if it doesn't already exist. The event handler methods must have its first
argument as a descendant of {@link EventObject} <br>
The event handling methods must be declared directly in the listener and not in one of its
super-classes. This is a performance limitation
@param listener the object to notify | [
"Adds",
"a",
"listener",
"if",
"it",
"doesn",
"t",
"already",
"exist",
".",
"The",
"event",
"handler",
"methods",
"must",
"have",
"its",
"first",
"argument",
"as",
"a",
"descendant",
"of",
"{",
"@link",
"EventObject",
"}",
"<br",
">",
"The",
"event",
"handling",
"methods",
"must",
"be",
"declared",
"directly",
"in",
"the",
"listener",
"and",
"not",
"in",
"one",
"of",
"its",
"super",
"-",
"classes",
".",
"This",
"is",
"a",
"performance",
"limitation"
] | train | https://github.com/theHilikus/Event-manager/blob/c3dabf5a145e57b2a6de89c1910851b8a8ae6064/src/main/java/com/github/thehilikus/events/event_manager/GenericEventDispatcher.java#L43-L71 |
diffplug/durian | src/com/diffplug/common/base/StringPrinter.java | StringPrinter.toWriter | public Writer toWriter() {
"""
Creates a Writer which passes its content to this StringPrinter.
"""
return new Writer() {
@Override
public Writer append(char c) {
consumer.accept(new String(new char[]{c}));
return this;
}
@Override
public Writer append(CharSequence csq) {
if (csq instanceof String) {
consumer.accept((String) csq);
} else {
consumer.accept(toStringSafely(csq));
}
return this;
}
@Override
public Writer append(CharSequence csq, int start, int end) {
if (csq instanceof String) {
consumer.accept(((String) csq).substring(start, end));
} else {
consumer.accept(toStringSafely(csq.subSequence(start, end)));
}
return this;
}
private String toStringSafely(CharSequence csq) {
String asString = csq.toString();
if (asString.length() == csq.length()) {
return asString;
} else {
// It's pretty easy to implement CharSequence.toString() incorrectly
// http://stackoverflow.com/a/15870428/1153071
// but for String, we know we won't have them, thus the fast-path above
Errors.log().accept(new IllegalArgumentException(csq.getClass() + " did not implement toString() correctly."));
char[] chars = new char[csq.length()];
for (int i = 0; i < chars.length; ++i) {
chars[i] = csq.charAt(i);
}
return new String(chars);
}
}
@Override
public void close() throws IOException {}
@Override
public void flush() throws IOException {}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
consumer.accept(new String(cbuf, off, len));
}
@Override
public void write(String str) {
consumer.accept(str);
}
@Override
public void write(String str, int off, int len) {
consumer.accept(str.substring(off, off + len));
}
};
} | java | public Writer toWriter() {
return new Writer() {
@Override
public Writer append(char c) {
consumer.accept(new String(new char[]{c}));
return this;
}
@Override
public Writer append(CharSequence csq) {
if (csq instanceof String) {
consumer.accept((String) csq);
} else {
consumer.accept(toStringSafely(csq));
}
return this;
}
@Override
public Writer append(CharSequence csq, int start, int end) {
if (csq instanceof String) {
consumer.accept(((String) csq).substring(start, end));
} else {
consumer.accept(toStringSafely(csq.subSequence(start, end)));
}
return this;
}
private String toStringSafely(CharSequence csq) {
String asString = csq.toString();
if (asString.length() == csq.length()) {
return asString;
} else {
// It's pretty easy to implement CharSequence.toString() incorrectly
// http://stackoverflow.com/a/15870428/1153071
// but for String, we know we won't have them, thus the fast-path above
Errors.log().accept(new IllegalArgumentException(csq.getClass() + " did not implement toString() correctly."));
char[] chars = new char[csq.length()];
for (int i = 0; i < chars.length; ++i) {
chars[i] = csq.charAt(i);
}
return new String(chars);
}
}
@Override
public void close() throws IOException {}
@Override
public void flush() throws IOException {}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
consumer.accept(new String(cbuf, off, len));
}
@Override
public void write(String str) {
consumer.accept(str);
}
@Override
public void write(String str, int off, int len) {
consumer.accept(str.substring(off, off + len));
}
};
} | [
"public",
"Writer",
"toWriter",
"(",
")",
"{",
"return",
"new",
"Writer",
"(",
")",
"{",
"@",
"Override",
"public",
"Writer",
"append",
"(",
"char",
"c",
")",
"{",
"consumer",
".",
"accept",
"(",
"new",
"String",
"(",
"new",
"char",
"[",
"]",
"{",
"c",
"}",
")",
")",
";",
"return",
"this",
";",
"}",
"@",
"Override",
"public",
"Writer",
"append",
"(",
"CharSequence",
"csq",
")",
"{",
"if",
"(",
"csq",
"instanceof",
"String",
")",
"{",
"consumer",
".",
"accept",
"(",
"(",
"String",
")",
"csq",
")",
";",
"}",
"else",
"{",
"consumer",
".",
"accept",
"(",
"toStringSafely",
"(",
"csq",
")",
")",
";",
"}",
"return",
"this",
";",
"}",
"@",
"Override",
"public",
"Writer",
"append",
"(",
"CharSequence",
"csq",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"if",
"(",
"csq",
"instanceof",
"String",
")",
"{",
"consumer",
".",
"accept",
"(",
"(",
"(",
"String",
")",
"csq",
")",
".",
"substring",
"(",
"start",
",",
"end",
")",
")",
";",
"}",
"else",
"{",
"consumer",
".",
"accept",
"(",
"toStringSafely",
"(",
"csq",
".",
"subSequence",
"(",
"start",
",",
"end",
")",
")",
")",
";",
"}",
"return",
"this",
";",
"}",
"private",
"String",
"toStringSafely",
"(",
"CharSequence",
"csq",
")",
"{",
"String",
"asString",
"=",
"csq",
".",
"toString",
"(",
")",
";",
"if",
"(",
"asString",
".",
"length",
"(",
")",
"==",
"csq",
".",
"length",
"(",
")",
")",
"{",
"return",
"asString",
";",
"}",
"else",
"{",
"// It's pretty easy to implement CharSequence.toString() incorrectly ",
"// http://stackoverflow.com/a/15870428/1153071",
"// but for String, we know we won't have them, thus the fast-path above",
"Errors",
".",
"log",
"(",
")",
".",
"accept",
"(",
"new",
"IllegalArgumentException",
"(",
"csq",
".",
"getClass",
"(",
")",
"+",
"\" did not implement toString() correctly.\"",
")",
")",
";",
"char",
"[",
"]",
"chars",
"=",
"new",
"char",
"[",
"csq",
".",
"length",
"(",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"chars",
".",
"length",
";",
"++",
"i",
")",
"{",
"chars",
"[",
"i",
"]",
"=",
"csq",
".",
"charAt",
"(",
"i",
")",
";",
"}",
"return",
"new",
"String",
"(",
"chars",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"throws",
"IOException",
"{",
"}",
"@",
"Override",
"public",
"void",
"flush",
"(",
")",
"throws",
"IOException",
"{",
"}",
"@",
"Override",
"public",
"void",
"write",
"(",
"char",
"[",
"]",
"cbuf",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"consumer",
".",
"accept",
"(",
"new",
"String",
"(",
"cbuf",
",",
"off",
",",
"len",
")",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"write",
"(",
"String",
"str",
")",
"{",
"consumer",
".",
"accept",
"(",
"str",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"write",
"(",
"String",
"str",
",",
"int",
"off",
",",
"int",
"len",
")",
"{",
"consumer",
".",
"accept",
"(",
"str",
".",
"substring",
"(",
"off",
",",
"off",
"+",
"len",
")",
")",
";",
"}",
"}",
";",
"}"
] | Creates a Writer which passes its content to this StringPrinter. | [
"Creates",
"a",
"Writer",
"which",
"passes",
"its",
"content",
"to",
"this",
"StringPrinter",
"."
] | train | https://github.com/diffplug/durian/blob/10631a3480e5491eb6eb6ee06e752d8596914232/src/com/diffplug/common/base/StringPrinter.java#L161-L227 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/persistent/filemgr/FileManagerImpl.java | FileManagerImpl.add_block_to_freelist | private void add_block_to_freelist(Block block, int ql_index) {
"""
/* Add a new block to the beginning of a free list data structure
"""
block.next = ql_heads[ql_index].first_block;
ql_heads[ql_index].first_block = block;
ql_heads[ql_index].length++;
if (ql_heads[ql_index].length == 1) {
nonempty_lists++;
}
} | java | private void add_block_to_freelist(Block block, int ql_index)
{
block.next = ql_heads[ql_index].first_block;
ql_heads[ql_index].first_block = block;
ql_heads[ql_index].length++;
if (ql_heads[ql_index].length == 1) {
nonempty_lists++;
}
} | [
"private",
"void",
"add_block_to_freelist",
"(",
"Block",
"block",
",",
"int",
"ql_index",
")",
"{",
"block",
".",
"next",
"=",
"ql_heads",
"[",
"ql_index",
"]",
".",
"first_block",
";",
"ql_heads",
"[",
"ql_index",
"]",
".",
"first_block",
"=",
"block",
";",
"ql_heads",
"[",
"ql_index",
"]",
".",
"length",
"++",
";",
"if",
"(",
"ql_heads",
"[",
"ql_index",
"]",
".",
"length",
"==",
"1",
")",
"{",
"nonempty_lists",
"++",
";",
"}",
"}"
] | /* Add a new block to the beginning of a free list data structure | [
"/",
"*",
"Add",
"a",
"new",
"block",
"to",
"the",
"beginning",
"of",
"a",
"free",
"list",
"data",
"structure"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/persistent/filemgr/FileManagerImpl.java#L1127-L1135 |
geomajas/geomajas-project-client-gwt | client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java | DomHelper.setCursor | public void setCursor(Object object, String cursor) {
"""
Set a specific cursor on an element of this <code>GraphicsContext</code>.
@param object
the element on which the controller should be set.
@param cursor
The string representation of the cursor to use.
"""
if (object == null) {
Dom.setStyleAttribute(getRootElement(), "cursor", cursor);
} else {
Element element = getGroup(object);
if (element != null) {
Dom.setStyleAttribute(element, "cursor", cursor);
}
}
} | java | public void setCursor(Object object, String cursor) {
if (object == null) {
Dom.setStyleAttribute(getRootElement(), "cursor", cursor);
} else {
Element element = getGroup(object);
if (element != null) {
Dom.setStyleAttribute(element, "cursor", cursor);
}
}
} | [
"public",
"void",
"setCursor",
"(",
"Object",
"object",
",",
"String",
"cursor",
")",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"Dom",
".",
"setStyleAttribute",
"(",
"getRootElement",
"(",
")",
",",
"\"cursor\"",
",",
"cursor",
")",
";",
"}",
"else",
"{",
"Element",
"element",
"=",
"getGroup",
"(",
"object",
")",
";",
"if",
"(",
"element",
"!=",
"null",
")",
"{",
"Dom",
".",
"setStyleAttribute",
"(",
"element",
",",
"\"cursor\"",
",",
"cursor",
")",
";",
"}",
"}",
"}"
] | Set a specific cursor on an element of this <code>GraphicsContext</code>.
@param object
the element on which the controller should be set.
@param cursor
The string representation of the cursor to use. | [
"Set",
"a",
"specific",
"cursor",
"on",
"an",
"element",
"of",
"this",
"<code",
">",
"GraphicsContext<",
"/",
"code",
">",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java#L628-L637 |
foundation-runtime/service-directory | 1.2/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/HttpUtils.java | HttpUtils.postJson | public static HttpResponse postJson(String urlStr, String body) throws IOException, ServiceException {
"""
Invoke REST Service using POST method.
@param urlStr
the REST service URL String
@param body
the Http Body String.
@return the HttpResponse.
@throws IOException
@throws ServiceException
"""
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
if (urlConnection instanceof HttpsURLConnection) {
setTLSConnection((HttpsURLConnection)urlConnection);
}
urlConnection.addRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.addRequestProperty("Content-Type", "application/json");
urlConnection.addRequestProperty("Content-Length",
Integer.toString(body.length()));
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
OutputStream out = urlConnection.getOutputStream();
out.write(body.getBytes());
ByteStreams.copy(new ByteArrayInputStream(body.getBytes()), out);
return getHttpResponse(urlConnection);
} | java | public static HttpResponse postJson(String urlStr, String body) throws IOException, ServiceException {
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
if (urlConnection instanceof HttpsURLConnection) {
setTLSConnection((HttpsURLConnection)urlConnection);
}
urlConnection.addRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.addRequestProperty("Content-Type", "application/json");
urlConnection.addRequestProperty("Content-Length",
Integer.toString(body.length()));
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
OutputStream out = urlConnection.getOutputStream();
out.write(body.getBytes());
ByteStreams.copy(new ByteArrayInputStream(body.getBytes()), out);
return getHttpResponse(urlConnection);
} | [
"public",
"static",
"HttpResponse",
"postJson",
"(",
"String",
"urlStr",
",",
"String",
"body",
")",
"throws",
"IOException",
",",
"ServiceException",
"{",
"URL",
"url",
"=",
"new",
"URL",
"(",
"urlStr",
")",
";",
"HttpURLConnection",
"urlConnection",
"=",
"(",
"HttpURLConnection",
")",
"url",
".",
"openConnection",
"(",
")",
";",
"if",
"(",
"urlConnection",
"instanceof",
"HttpsURLConnection",
")",
"{",
"setTLSConnection",
"(",
"(",
"HttpsURLConnection",
")",
"urlConnection",
")",
";",
"}",
"urlConnection",
".",
"addRequestProperty",
"(",
"\"Accept\"",
",",
"\"application/json\"",
")",
";",
"urlConnection",
".",
"setRequestMethod",
"(",
"\"POST\"",
")",
";",
"urlConnection",
".",
"addRequestProperty",
"(",
"\"Content-Type\"",
",",
"\"application/json\"",
")",
";",
"urlConnection",
".",
"addRequestProperty",
"(",
"\"Content-Length\"",
",",
"Integer",
".",
"toString",
"(",
"body",
".",
"length",
"(",
")",
")",
")",
";",
"urlConnection",
".",
"setDoOutput",
"(",
"true",
")",
";",
"urlConnection",
".",
"setDoInput",
"(",
"true",
")",
";",
"urlConnection",
".",
"setUseCaches",
"(",
"false",
")",
";",
"OutputStream",
"out",
"=",
"urlConnection",
".",
"getOutputStream",
"(",
")",
";",
"out",
".",
"write",
"(",
"body",
".",
"getBytes",
"(",
")",
")",
";",
"ByteStreams",
".",
"copy",
"(",
"new",
"ByteArrayInputStream",
"(",
"body",
".",
"getBytes",
"(",
")",
")",
",",
"out",
")",
";",
"return",
"getHttpResponse",
"(",
"urlConnection",
")",
";",
"}"
] | Invoke REST Service using POST method.
@param urlStr
the REST service URL String
@param body
the Http Body String.
@return the HttpResponse.
@throws IOException
@throws ServiceException | [
"Invoke",
"REST",
"Service",
"using",
"POST",
"method",
"."
] | train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.2/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/HttpUtils.java#L74-L97 |
alkacon/opencms-core | src-gwt/org/opencms/ade/publish/client/CmsPublishSelectPanel.java | CmsPublishSelectPanel.setGroups | protected void setGroups(List<CmsPublishGroup> groups, boolean newData, String defaultWorkflow) {
"""
Sets the publish groups.<p>
@param groups the list of publish groups
@param newData true if the data is new
@param defaultWorkflow the default workflow id
"""
m_model = new CmsPublishDataModel(groups, this);
m_model.setSelectionChangeAction(new Runnable() {
public void run() {
onChangePublishSelection();
}
});
m_currentGroupIndex = 0;
m_currentGroupPanel = null;
m_problemsPanel.clear();
if (newData) {
m_showProblemsOnly = false;
m_checkboxProblems.setChecked(false);
m_checkboxProblems.setVisible(false);
m_problemsPanel.setVisible(false);
}
m_groupPanels.clear();
m_groupPanelContainer.clear();
m_scrollPanel.onResizeDescendant();
enableActions(false);
int numGroups = groups.size();
setResourcesVisible(numGroups > 0);
if (numGroups == 0) {
return;
}
enableActions(true);
addMoreListItems();
showProblemCount(m_model.countProblems());
if (defaultWorkflow != null) {
m_workflowSelector.setFormValue(defaultWorkflow, false);
m_publishDialog.setWorkflowId(defaultWorkflow);
m_actions = m_publishDialog.getSelectedWorkflow().getActions();
m_publishDialog.setPanel(CmsPublishDialog.PANEL_SELECT);
}
} | java | protected void setGroups(List<CmsPublishGroup> groups, boolean newData, String defaultWorkflow) {
m_model = new CmsPublishDataModel(groups, this);
m_model.setSelectionChangeAction(new Runnable() {
public void run() {
onChangePublishSelection();
}
});
m_currentGroupIndex = 0;
m_currentGroupPanel = null;
m_problemsPanel.clear();
if (newData) {
m_showProblemsOnly = false;
m_checkboxProblems.setChecked(false);
m_checkboxProblems.setVisible(false);
m_problemsPanel.setVisible(false);
}
m_groupPanels.clear();
m_groupPanelContainer.clear();
m_scrollPanel.onResizeDescendant();
enableActions(false);
int numGroups = groups.size();
setResourcesVisible(numGroups > 0);
if (numGroups == 0) {
return;
}
enableActions(true);
addMoreListItems();
showProblemCount(m_model.countProblems());
if (defaultWorkflow != null) {
m_workflowSelector.setFormValue(defaultWorkflow, false);
m_publishDialog.setWorkflowId(defaultWorkflow);
m_actions = m_publishDialog.getSelectedWorkflow().getActions();
m_publishDialog.setPanel(CmsPublishDialog.PANEL_SELECT);
}
} | [
"protected",
"void",
"setGroups",
"(",
"List",
"<",
"CmsPublishGroup",
">",
"groups",
",",
"boolean",
"newData",
",",
"String",
"defaultWorkflow",
")",
"{",
"m_model",
"=",
"new",
"CmsPublishDataModel",
"(",
"groups",
",",
"this",
")",
";",
"m_model",
".",
"setSelectionChangeAction",
"(",
"new",
"Runnable",
"(",
")",
"{",
"public",
"void",
"run",
"(",
")",
"{",
"onChangePublishSelection",
"(",
")",
";",
"}",
"}",
")",
";",
"m_currentGroupIndex",
"=",
"0",
";",
"m_currentGroupPanel",
"=",
"null",
";",
"m_problemsPanel",
".",
"clear",
"(",
")",
";",
"if",
"(",
"newData",
")",
"{",
"m_showProblemsOnly",
"=",
"false",
";",
"m_checkboxProblems",
".",
"setChecked",
"(",
"false",
")",
";",
"m_checkboxProblems",
".",
"setVisible",
"(",
"false",
")",
";",
"m_problemsPanel",
".",
"setVisible",
"(",
"false",
")",
";",
"}",
"m_groupPanels",
".",
"clear",
"(",
")",
";",
"m_groupPanelContainer",
".",
"clear",
"(",
")",
";",
"m_scrollPanel",
".",
"onResizeDescendant",
"(",
")",
";",
"enableActions",
"(",
"false",
")",
";",
"int",
"numGroups",
"=",
"groups",
".",
"size",
"(",
")",
";",
"setResourcesVisible",
"(",
"numGroups",
">",
"0",
")",
";",
"if",
"(",
"numGroups",
"==",
"0",
")",
"{",
"return",
";",
"}",
"enableActions",
"(",
"true",
")",
";",
"addMoreListItems",
"(",
")",
";",
"showProblemCount",
"(",
"m_model",
".",
"countProblems",
"(",
")",
")",
";",
"if",
"(",
"defaultWorkflow",
"!=",
"null",
")",
"{",
"m_workflowSelector",
".",
"setFormValue",
"(",
"defaultWorkflow",
",",
"false",
")",
";",
"m_publishDialog",
".",
"setWorkflowId",
"(",
"defaultWorkflow",
")",
";",
"m_actions",
"=",
"m_publishDialog",
".",
"getSelectedWorkflow",
"(",
")",
".",
"getActions",
"(",
")",
";",
"m_publishDialog",
".",
"setPanel",
"(",
"CmsPublishDialog",
".",
"PANEL_SELECT",
")",
";",
"}",
"}"
] | Sets the publish groups.<p>
@param groups the list of publish groups
@param newData true if the data is new
@param defaultWorkflow the default workflow id | [
"Sets",
"the",
"publish",
"groups",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/publish/client/CmsPublishSelectPanel.java#L968-L1008 |
lessthanoptimal/ejml | main/ejml-zdense/src/org/ejml/dense/row/MatrixFeatures_ZDRM.java | MatrixFeatures_ZDRM.isLowerTriangle | public static boolean isLowerTriangle(ZMatrixRMaj A , int hessenberg , double tol ) {
"""
<p>
Checks to see if a matrix is lower triangular or Hessenberg. A Hessenberg matrix of degree N
has the following property:<br>
<br>
a<sub>ij</sub> ≤ 0 for all i < j+N<br>
<br>
A triangular matrix is a Hessenberg matrix of degree 0.
</p>
@param A Matrix being tested. Not modified.
@param hessenberg The degree of being hessenberg.
@param tol How close to zero the lower left elements need to be.
@return If it is an upper triangular/hessenberg matrix or not.
"""
tol *= tol;
for( int i = 0; i < A.numRows-hessenberg-1; i++ ) {
for( int j = i+hessenberg+1; j < A.numCols; j++ ) {
int index = (i*A.numCols+j)*2;
double real = A.data[index];
double imag = A.data[index+1];
double mag = real*real + imag*imag;
if( !(mag <= tol) ) {
return false;
}
}
}
return true;
} | java | public static boolean isLowerTriangle(ZMatrixRMaj A , int hessenberg , double tol ) {
tol *= tol;
for( int i = 0; i < A.numRows-hessenberg-1; i++ ) {
for( int j = i+hessenberg+1; j < A.numCols; j++ ) {
int index = (i*A.numCols+j)*2;
double real = A.data[index];
double imag = A.data[index+1];
double mag = real*real + imag*imag;
if( !(mag <= tol) ) {
return false;
}
}
}
return true;
} | [
"public",
"static",
"boolean",
"isLowerTriangle",
"(",
"ZMatrixRMaj",
"A",
",",
"int",
"hessenberg",
",",
"double",
"tol",
")",
"{",
"tol",
"*=",
"tol",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"A",
".",
"numRows",
"-",
"hessenberg",
"-",
"1",
";",
"i",
"++",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"i",
"+",
"hessenberg",
"+",
"1",
";",
"j",
"<",
"A",
".",
"numCols",
";",
"j",
"++",
")",
"{",
"int",
"index",
"=",
"(",
"i",
"*",
"A",
".",
"numCols",
"+",
"j",
")",
"*",
"2",
";",
"double",
"real",
"=",
"A",
".",
"data",
"[",
"index",
"]",
";",
"double",
"imag",
"=",
"A",
".",
"data",
"[",
"index",
"+",
"1",
"]",
";",
"double",
"mag",
"=",
"real",
"*",
"real",
"+",
"imag",
"*",
"imag",
";",
"if",
"(",
"!",
"(",
"mag",
"<=",
"tol",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"}",
"return",
"true",
";",
"}"
] | <p>
Checks to see if a matrix is lower triangular or Hessenberg. A Hessenberg matrix of degree N
has the following property:<br>
<br>
a<sub>ij</sub> ≤ 0 for all i < j+N<br>
<br>
A triangular matrix is a Hessenberg matrix of degree 0.
</p>
@param A Matrix being tested. Not modified.
@param hessenberg The degree of being hessenberg.
@param tol How close to zero the lower left elements need to be.
@return If it is an upper triangular/hessenberg matrix or not. | [
"<p",
">",
"Checks",
"to",
"see",
"if",
"a",
"matrix",
"is",
"lower",
"triangular",
"or",
"Hessenberg",
".",
"A",
"Hessenberg",
"matrix",
"of",
"degree",
"N",
"has",
"the",
"following",
"property",
":",
"<br",
">",
"<br",
">",
"a<sub",
">",
"ij<",
"/",
"sub",
">",
"&le",
";",
"0",
"for",
"all",
"i",
"<",
";",
"j",
"+",
"N<br",
">",
"<br",
">",
"A",
"triangular",
"matrix",
"is",
"a",
"Hessenberg",
"matrix",
"of",
"degree",
"0",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-zdense/src/org/ejml/dense/row/MatrixFeatures_ZDRM.java#L399-L415 |
apiman/apiman | gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/IgnoredResourcesPolicy.java | IgnoredResourcesPolicy.satisfiesAnyPath | private boolean satisfiesAnyPath(IgnoredResourcesConfig config, String destination, String verb) {
"""
Evaluates whether the destination provided matches any of the configured
rules
@param config
The {@link IgnoredResourcesConfig} containing the
rules
@param destination
The destination to evaluate
@param verb
HTTP verb or '*' for all verbs
@return true if any path matches the destination. false otherwise
"""
if (destination == null || destination.trim().length() == 0) {
destination = "/"; //$NON-NLS-1$
}
for (IgnoredResource resource : config.getRules()) {
String resourceVerb = resource.getVerb();
boolean verbMatches = verb == null || IgnoredResource.VERB_MATCH_ALL.equals(resourceVerb)
|| verb.equalsIgnoreCase(resourceVerb); // $NON-NLS-1$
boolean destinationMatches = destination.matches(resource.getPathPattern());
if (verbMatches && destinationMatches) {
return true;
}
}
return false;
} | java | private boolean satisfiesAnyPath(IgnoredResourcesConfig config, String destination, String verb) {
if (destination == null || destination.trim().length() == 0) {
destination = "/"; //$NON-NLS-1$
}
for (IgnoredResource resource : config.getRules()) {
String resourceVerb = resource.getVerb();
boolean verbMatches = verb == null || IgnoredResource.VERB_MATCH_ALL.equals(resourceVerb)
|| verb.equalsIgnoreCase(resourceVerb); // $NON-NLS-1$
boolean destinationMatches = destination.matches(resource.getPathPattern());
if (verbMatches && destinationMatches) {
return true;
}
}
return false;
} | [
"private",
"boolean",
"satisfiesAnyPath",
"(",
"IgnoredResourcesConfig",
"config",
",",
"String",
"destination",
",",
"String",
"verb",
")",
"{",
"if",
"(",
"destination",
"==",
"null",
"||",
"destination",
".",
"trim",
"(",
")",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"destination",
"=",
"\"/\"",
";",
"//$NON-NLS-1$",
"}",
"for",
"(",
"IgnoredResource",
"resource",
":",
"config",
".",
"getRules",
"(",
")",
")",
"{",
"String",
"resourceVerb",
"=",
"resource",
".",
"getVerb",
"(",
")",
";",
"boolean",
"verbMatches",
"=",
"verb",
"==",
"null",
"||",
"IgnoredResource",
".",
"VERB_MATCH_ALL",
".",
"equals",
"(",
"resourceVerb",
")",
"||",
"verb",
".",
"equalsIgnoreCase",
"(",
"resourceVerb",
")",
";",
"// $NON-NLS-1$",
"boolean",
"destinationMatches",
"=",
"destination",
".",
"matches",
"(",
"resource",
".",
"getPathPattern",
"(",
")",
")",
";",
"if",
"(",
"verbMatches",
"&&",
"destinationMatches",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Evaluates whether the destination provided matches any of the configured
rules
@param config
The {@link IgnoredResourcesConfig} containing the
rules
@param destination
The destination to evaluate
@param verb
HTTP verb or '*' for all verbs
@return true if any path matches the destination. false otherwise | [
"Evaluates",
"whether",
"the",
"destination",
"provided",
"matches",
"any",
"of",
"the",
"configured",
"rules"
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/IgnoredResourcesPolicy.java#L85-L99 |
knowm/XChange | xchange-gateio/src/main/java/org/knowm/xchange/gateio/service/GateioTradeServiceRaw.java | GateioTradeServiceRaw.cancelAllOrders | public boolean cancelAllOrders(String type, CurrencyPair currencyPair) throws IOException {
"""
Cancels all orders. See https://gate.io/api2.
@param type order type(0:sell,1:buy,-1:all)
@param currencyPair currency pair
@return
@throws IOException
"""
GateioBaseResponse cancelAllOrdersResult =
bter.cancelAllOrders(type, formatCurrencyPair(currencyPair), apiKey, signatureCreator);
return handleResponse(cancelAllOrdersResult).isResult();
} | java | public boolean cancelAllOrders(String type, CurrencyPair currencyPair) throws IOException {
GateioBaseResponse cancelAllOrdersResult =
bter.cancelAllOrders(type, formatCurrencyPair(currencyPair), apiKey, signatureCreator);
return handleResponse(cancelAllOrdersResult).isResult();
} | [
"public",
"boolean",
"cancelAllOrders",
"(",
"String",
"type",
",",
"CurrencyPair",
"currencyPair",
")",
"throws",
"IOException",
"{",
"GateioBaseResponse",
"cancelAllOrdersResult",
"=",
"bter",
".",
"cancelAllOrders",
"(",
"type",
",",
"formatCurrencyPair",
"(",
"currencyPair",
")",
",",
"apiKey",
",",
"signatureCreator",
")",
";",
"return",
"handleResponse",
"(",
"cancelAllOrdersResult",
")",
".",
"isResult",
"(",
")",
";",
"}"
] | Cancels all orders. See https://gate.io/api2.
@param type order type(0:sell,1:buy,-1:all)
@param currencyPair currency pair
@return
@throws IOException | [
"Cancels",
"all",
"orders",
".",
"See",
"https",
":",
"//",
"gate",
".",
"io",
"/",
"api2",
"."
] | train | https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-gateio/src/main/java/org/knowm/xchange/gateio/service/GateioTradeServiceRaw.java#L106-L112 |
VoltDB/voltdb | src/frontend/org/voltdb/iv2/LeaderAppointer.java | LeaderAppointer.updatePartitionLeader | public void updatePartitionLeader(int partitionId, long newMasterHISD, boolean isLeaderMigrated) {
"""
update the partition call back with current master and replica
@param partitionId partition id
@param newMasterHISD new master HSID
"""
PartitionCallback cb = m_callbacks.get(partitionId);
if (cb != null && cb.m_currentLeader != newMasterHISD) {
cb.m_previousLeader = cb.m_currentLeader;
cb.m_currentLeader = newMasterHISD;
cb.m_isLeaderMigrated = isLeaderMigrated;
}
} | java | public void updatePartitionLeader(int partitionId, long newMasterHISD, boolean isLeaderMigrated) {
PartitionCallback cb = m_callbacks.get(partitionId);
if (cb != null && cb.m_currentLeader != newMasterHISD) {
cb.m_previousLeader = cb.m_currentLeader;
cb.m_currentLeader = newMasterHISD;
cb.m_isLeaderMigrated = isLeaderMigrated;
}
} | [
"public",
"void",
"updatePartitionLeader",
"(",
"int",
"partitionId",
",",
"long",
"newMasterHISD",
",",
"boolean",
"isLeaderMigrated",
")",
"{",
"PartitionCallback",
"cb",
"=",
"m_callbacks",
".",
"get",
"(",
"partitionId",
")",
";",
"if",
"(",
"cb",
"!=",
"null",
"&&",
"cb",
".",
"m_currentLeader",
"!=",
"newMasterHISD",
")",
"{",
"cb",
".",
"m_previousLeader",
"=",
"cb",
".",
"m_currentLeader",
";",
"cb",
".",
"m_currentLeader",
"=",
"newMasterHISD",
";",
"cb",
".",
"m_isLeaderMigrated",
"=",
"isLeaderMigrated",
";",
"}",
"}"
] | update the partition call back with current master and replica
@param partitionId partition id
@param newMasterHISD new master HSID | [
"update",
"the",
"partition",
"call",
"back",
"with",
"current",
"master",
"and",
"replica"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/iv2/LeaderAppointer.java#L753-L760 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.