repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 194 | func_name stringlengths 6 111 | whole_func_string stringlengths 80 3.8k | language stringclasses 1
value | func_code_string stringlengths 80 3.8k | func_code_tokens listlengths 20 697 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 434 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
spring-projects/spring-android | spring-android-rest-template/src/main/java/org/springframework/http/client/HttpComponentsClientHttpRequestFactory.java | HttpComponentsClientHttpRequestFactory.setLegacySocketTimeout | @SuppressWarnings("deprecation")
private void setLegacySocketTimeout(HttpClient client, int timeout) {
if (org.apache.http.impl.client.AbstractHttpClient.class.isInstance(client)) {
client.getParams().setIntParameter(
org.apache.http.params.CoreConnectionPNames.SO_TIMEOUT, timeout);
}
} | java | @SuppressWarnings("deprecation")
private void setLegacySocketTimeout(HttpClient client, int timeout) {
if (org.apache.http.impl.client.AbstractHttpClient.class.isInstance(client)) {
client.getParams().setIntParameter(
org.apache.http.params.CoreConnectionPNames.SO_TIMEOUT, timeout);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"private",
"void",
"setLegacySocketTimeout",
"(",
"HttpClient",
"client",
",",
"int",
"timeout",
")",
"{",
"if",
"(",
"org",
".",
"apache",
".",
"http",
".",
"impl",
".",
"client",
".",
"AbstractHttpClient"... | Apply the specified socket timeout to deprecated {@link HttpClient}
implementations. See {@link #setLegacyConnectionTimeout}.
@param client the client to configure
@param timeout the custom socket timeout
@see #setLegacyConnectionTimeout | [
"Apply",
"the",
"specified",
"socket",
"timeout",
"to",
"deprecated",
"{"
] | train | https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-rest-template/src/main/java/org/springframework/http/client/HttpComponentsClientHttpRequestFactory.java#L163-L169 |
intuit/QuickBooks-V3-Java-SDK | ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/HTTPBatchClientConnectionInterceptor.java | HTTPBatchClientConnectionInterceptor.populateRequestHeaders | private void populateRequestHeaders(HttpRequestBase httpRequest, Map<String, String> requestHeaders) {
Set<String> keySet = requestHeaders.keySet();
Iterator<String> keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
String key = keySetIterator.next();
String value = requestHeaders.get(key);
httpRequest.addHeader(key, value);
}
PropertyHelper propertyHelper = PropertyHelper.getInstance();
String requestSource = propertyHelper.getRequestSource() + propertyHelper.getVersion();
if(propertyHelper.getRequestSourceHeader() != null){
httpRequest.addHeader(propertyHelper.getRequestSourceHeader(), requestSource);
}
} | java | private void populateRequestHeaders(HttpRequestBase httpRequest, Map<String, String> requestHeaders) {
Set<String> keySet = requestHeaders.keySet();
Iterator<String> keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
String key = keySetIterator.next();
String value = requestHeaders.get(key);
httpRequest.addHeader(key, value);
}
PropertyHelper propertyHelper = PropertyHelper.getInstance();
String requestSource = propertyHelper.getRequestSource() + propertyHelper.getVersion();
if(propertyHelper.getRequestSourceHeader() != null){
httpRequest.addHeader(propertyHelper.getRequestSourceHeader(), requestSource);
}
} | [
"private",
"void",
"populateRequestHeaders",
"(",
"HttpRequestBase",
"httpRequest",
",",
"Map",
"<",
"String",
",",
"String",
">",
"requestHeaders",
")",
"{",
"Set",
"<",
"String",
">",
"keySet",
"=",
"requestHeaders",
".",
"keySet",
"(",
")",
";",
"Iterator",... | Method to populate the HTTP request headers by reading it from the requestHeaders Map
@param httpRequest the http request
@param requestHeaders the request headers | [
"Method",
"to",
"populate",
"the",
"HTTP",
"request",
"headers",
"by",
"reading",
"it",
"from",
"the",
"requestHeaders",
"Map"
] | train | https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/HTTPBatchClientConnectionInterceptor.java#L344-L360 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/dns/dnsview_dnspolicy_binding.java | dnsview_dnspolicy_binding.count_filtered | public static long count_filtered(nitro_service service, String viewname, String filter) throws Exception{
dnsview_dnspolicy_binding obj = new dnsview_dnspolicy_binding();
obj.set_viewname(viewname);
options option = new options();
option.set_count(true);
option.set_filter(filter);
dnsview_dnspolicy_binding[] response = (dnsview_dnspolicy_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
} | java | public static long count_filtered(nitro_service service, String viewname, String filter) throws Exception{
dnsview_dnspolicy_binding obj = new dnsview_dnspolicy_binding();
obj.set_viewname(viewname);
options option = new options();
option.set_count(true);
option.set_filter(filter);
dnsview_dnspolicy_binding[] response = (dnsview_dnspolicy_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
} | [
"public",
"static",
"long",
"count_filtered",
"(",
"nitro_service",
"service",
",",
"String",
"viewname",
",",
"String",
"filter",
")",
"throws",
"Exception",
"{",
"dnsview_dnspolicy_binding",
"obj",
"=",
"new",
"dnsview_dnspolicy_binding",
"(",
")",
";",
"obj",
"... | Use this API to count the filtered set of dnsview_dnspolicy_binding resources.
filter string should be in JSON format.eg: "port:80,servicetype:HTTP". | [
"Use",
"this",
"API",
"to",
"count",
"the",
"filtered",
"set",
"of",
"dnsview_dnspolicy_binding",
"resources",
".",
"filter",
"string",
"should",
"be",
"in",
"JSON",
"format",
".",
"eg",
":",
"port",
":",
"80",
"servicetype",
":",
"HTTP",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/dns/dnsview_dnspolicy_binding.java#L164-L175 |
sarl/sarl | main/coreplugins/io.sarl.lang.core/src/io/sarl/lang/core/SREutils.java | SREutils.setSreSpecificData | public static <S> S setSreSpecificData(SRESpecificDataContainer container, S data, Class<S> type) {
assert container != null;
final S oldData = container.$getSreSpecificData(type);
container.$setSreSpecificData(data);
return oldData;
} | java | public static <S> S setSreSpecificData(SRESpecificDataContainer container, S data, Class<S> type) {
assert container != null;
final S oldData = container.$getSreSpecificData(type);
container.$setSreSpecificData(data);
return oldData;
} | [
"public",
"static",
"<",
"S",
">",
"S",
"setSreSpecificData",
"(",
"SRESpecificDataContainer",
"container",
",",
"S",
"data",
",",
"Class",
"<",
"S",
">",
"type",
")",
"{",
"assert",
"container",
"!=",
"null",
";",
"final",
"S",
"oldData",
"=",
"container"... | Change the data associated to the given container by the SRE.
@param <S> the type of the data.
@param type the type of the data.
@param container the container.
@param data the SRE-specific data.
@return the SRE-specific data that was associated to the container before associating data to it.
@since 0.6 | [
"Change",
"the",
"data",
"associated",
"to",
"the",
"given",
"container",
"by",
"the",
"SRE",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.core/src/io/sarl/lang/core/SREutils.java#L94-L99 |
fuinorg/utils4swing | src/main/java/org/fuin/utils4swing/dialogs/DirectorySelector.java | DirectorySelector.selectDirectory | public static Result selectDirectory(final String title,
final String directory) throws CanceledException {
return selectDirectory(title, directory, false);
} | java | public static Result selectDirectory(final String title,
final String directory) throws CanceledException {
return selectDirectory(title, directory, false);
} | [
"public",
"static",
"Result",
"selectDirectory",
"(",
"final",
"String",
"title",
",",
"final",
"String",
"directory",
")",
"throws",
"CanceledException",
"{",
"return",
"selectDirectory",
"(",
"title",
",",
"directory",
",",
"false",
")",
";",
"}"
] | Blocks the current thread and waits for the result of the selection
dialog. WARNING: Don't use this inside the Event Dispatching Thread
(EDT)! This is only for usage outside the UI thread. The checkbox
"include subdirectories" is not visible.
@param title
Title to display for the dialog.
@param directory
Initial directory.
@return Selection result.
@throws CanceledException
The user canceled the dialog. | [
"Blocks",
"the",
"current",
"thread",
"and",
"waits",
"for",
"the",
"result",
"of",
"the",
"selection",
"dialog",
".",
"WARNING",
":",
"Don",
"t",
"use",
"this",
"inside",
"the",
"Event",
"Dispatching",
"Thread",
"(",
"EDT",
")",
"!",
"This",
"is",
"only... | train | https://github.com/fuinorg/utils4swing/blob/560fb69eac182e3473de9679c3c15433e524ef6b/src/main/java/org/fuin/utils4swing/dialogs/DirectorySelector.java#L210-L213 |
greese/dasein-persist | src/main/java/org/dasein/persist/PersistentFactory.java | PersistentFactory.addCounter | public void addCounter(String field, Class<? extends Execution> cls) {
counters.put(field, cls);
} | java | public void addCounter(String field, Class<? extends Execution> cls) {
counters.put(field, cls);
} | [
"public",
"void",
"addCounter",
"(",
"String",
"field",
",",
"Class",
"<",
"?",
"extends",
"Execution",
">",
"cls",
")",
"{",
"counters",
".",
"put",
"(",
"field",
",",
"cls",
")",
";",
"}"
] | Adds a query for counts on a specified field.
@param field the field to count matches on
@param cls the class of the query that performs the count | [
"Adds",
"a",
"query",
"for",
"counts",
"on",
"a",
"specified",
"field",
"."
] | train | https://github.com/greese/dasein-persist/blob/1104621ad1670a45488b093b984ec1db4c7be781/src/main/java/org/dasein/persist/PersistentFactory.java#L298-L300 |
foundation-runtime/service-directory | 1.1/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java | DirectoryServiceClient.unregisterInstance | public void unregisterInstance(String serviceName, String instanceId, boolean isOwned){
String uri = toInstanceUri(serviceName, instanceId) + "/" + isOwned;
HttpResponse result = invoker.invoke(uri, null,
HttpMethod.DELETE);
if (result.getHttpCode() != HTTP_OK) {
throw new ServiceException(ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR,
"HTTP Code is not OK, code=%s", result.getHttpCode());
}
} | java | public void unregisterInstance(String serviceName, String instanceId, boolean isOwned){
String uri = toInstanceUri(serviceName, instanceId) + "/" + isOwned;
HttpResponse result = invoker.invoke(uri, null,
HttpMethod.DELETE);
if (result.getHttpCode() != HTTP_OK) {
throw new ServiceException(ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR,
"HTTP Code is not OK, code=%s", result.getHttpCode());
}
} | [
"public",
"void",
"unregisterInstance",
"(",
"String",
"serviceName",
",",
"String",
"instanceId",
",",
"boolean",
"isOwned",
")",
"{",
"String",
"uri",
"=",
"toInstanceUri",
"(",
"serviceName",
",",
"instanceId",
")",
"+",
"\"/\"",
"+",
"isOwned",
";",
"HttpR... | Unregister a ServiceInstance.
@param serviceName
service name.
@param instanceId
the instance id.
@param isOwned
whether the DirectoryAPI owns this ServiceProvider. | [
"Unregister",
"a",
"ServiceInstance",
"."
] | train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.1/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java#L226-L235 |
RestComm/sipunit | src/main/java/org/cafesip/sipunit/SipAssert.java | SipAssert.assertNotAnswered | public static void assertNotAnswered(String msg, SipCall call) {
assertNotNull("Null assert object passed in", call);
assertFalse(msg, call.isCallAnswered());
} | java | public static void assertNotAnswered(String msg, SipCall call) {
assertNotNull("Null assert object passed in", call);
assertFalse(msg, call.isCallAnswered());
} | [
"public",
"static",
"void",
"assertNotAnswered",
"(",
"String",
"msg",
",",
"SipCall",
"call",
")",
"{",
"assertNotNull",
"(",
"\"Null assert object passed in\"",
",",
"call",
")",
";",
"assertFalse",
"(",
"msg",
",",
"call",
".",
"isCallAnswered",
"(",
")",
"... | Asserts that the given incoming or outgoing call leg has not been answered. Assertion failure
output includes the given message text.
@param msg message text to output if the assertion fails.
@param call The incoming or outgoing call leg. | [
"Asserts",
"that",
"the",
"given",
"incoming",
"or",
"outgoing",
"call",
"leg",
"has",
"not",
"been",
"answered",
".",
"Assertion",
"failure",
"output",
"includes",
"the",
"given",
"message",
"text",
"."
] | train | https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/SipAssert.java#L627-L630 |
neo4j/neo4j-java-driver | driver/src/main/java/org/neo4j/driver/internal/DriverFactory.java | DriverFactory.createLoadBalancer | protected LoadBalancer createLoadBalancer( BoltServerAddress address, ConnectionPool connectionPool,
EventExecutorGroup eventExecutorGroup, Config config, RoutingSettings routingSettings )
{
LoadBalancingStrategy loadBalancingStrategy = createLoadBalancingStrategy( config, connectionPool );
ServerAddressResolver resolver = createResolver( config );
return new LoadBalancer( address, routingSettings, connectionPool, eventExecutorGroup, createClock(),
config.logging(), loadBalancingStrategy, resolver );
} | java | protected LoadBalancer createLoadBalancer( BoltServerAddress address, ConnectionPool connectionPool,
EventExecutorGroup eventExecutorGroup, Config config, RoutingSettings routingSettings )
{
LoadBalancingStrategy loadBalancingStrategy = createLoadBalancingStrategy( config, connectionPool );
ServerAddressResolver resolver = createResolver( config );
return new LoadBalancer( address, routingSettings, connectionPool, eventExecutorGroup, createClock(),
config.logging(), loadBalancingStrategy, resolver );
} | [
"protected",
"LoadBalancer",
"createLoadBalancer",
"(",
"BoltServerAddress",
"address",
",",
"ConnectionPool",
"connectionPool",
",",
"EventExecutorGroup",
"eventExecutorGroup",
",",
"Config",
"config",
",",
"RoutingSettings",
"routingSettings",
")",
"{",
"LoadBalancingStrate... | Creates new {@link LoadBalancer} for the routing driver.
<p>
<b>This method is protected only for testing</b> | [
"Creates",
"new",
"{"
] | train | https://github.com/neo4j/neo4j-java-driver/blob/8dad6c48251fa1ab7017e72d9998a24fa2337a22/driver/src/main/java/org/neo4j/driver/internal/DriverFactory.java#L203-L210 |
alkacon/opencms-core | src/org/opencms/file/CmsObject.java | CmsObject.chtype | public void chtype(String resourcename, I_CmsResourceType type) throws CmsException {
CmsResource resource = readResource(resourcename, CmsResourceFilter.IGNORE_EXPIRATION);
getResourceType(resource).chtype(this, m_securityManager, resource, type);
} | java | public void chtype(String resourcename, I_CmsResourceType type) throws CmsException {
CmsResource resource = readResource(resourcename, CmsResourceFilter.IGNORE_EXPIRATION);
getResourceType(resource).chtype(this, m_securityManager, resource, type);
} | [
"public",
"void",
"chtype",
"(",
"String",
"resourcename",
",",
"I_CmsResourceType",
"type",
")",
"throws",
"CmsException",
"{",
"CmsResource",
"resource",
"=",
"readResource",
"(",
"resourcename",
",",
"CmsResourceFilter",
".",
"IGNORE_EXPIRATION",
")",
";",
"getRe... | Changes the resource type of a resource.<p>
OpenCms handles resources according to the resource type,
not the file suffix. This is e.g. why a JSP in OpenCms can have the
suffix ".html" instead of ".jsp" only. Changing the resource type
makes sense e.g. if you want to make a plain text file a JSP resource,
or a binary file an image, etc.<p>
@param resourcename the name of the resource to change the type for (full current site relative path)
@param type the new resource type for this resource
@throws CmsException if something goes wrong | [
"Changes",
"the",
"resource",
"type",
"of",
"a",
"resource",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L498-L502 |
fabric8io/mockwebserver | src/main/java/io/fabric8/mockwebserver/crud/CrudDispatcher.java | CrudDispatcher.handlePatch | public MockResponse handlePatch(String path, String s) {
MockResponse response = new MockResponse();
String body = doGet(path);
if (body == null) {
response.setResponseCode(404);
} else {
try {
JsonNode patch = context.getMapper().readTree(s);
JsonNode source = context.getMapper().readTree(body);
JsonNode updated = JsonPatch.apply(patch, source);
String updatedAsString = context.getMapper().writeValueAsString(updated);
AttributeSet features = AttributeSet.merge(attributeExtractor.fromPath(path),
attributeExtractor.fromResource(updatedAsString));
map.put(features, updatedAsString);
response.setResponseCode(202);
response.setBody(updatedAsString);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return response;
} | java | public MockResponse handlePatch(String path, String s) {
MockResponse response = new MockResponse();
String body = doGet(path);
if (body == null) {
response.setResponseCode(404);
} else {
try {
JsonNode patch = context.getMapper().readTree(s);
JsonNode source = context.getMapper().readTree(body);
JsonNode updated = JsonPatch.apply(patch, source);
String updatedAsString = context.getMapper().writeValueAsString(updated);
AttributeSet features = AttributeSet.merge(attributeExtractor.fromPath(path),
attributeExtractor.fromResource(updatedAsString));
map.put(features, updatedAsString);
response.setResponseCode(202);
response.setBody(updatedAsString);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return response;
} | [
"public",
"MockResponse",
"handlePatch",
"(",
"String",
"path",
",",
"String",
"s",
")",
"{",
"MockResponse",
"response",
"=",
"new",
"MockResponse",
"(",
")",
";",
"String",
"body",
"=",
"doGet",
"(",
"path",
")",
";",
"if",
"(",
"body",
"==",
"null",
... | Patches the specified object to the in-memory db.
@param path
@param s
@return | [
"Patches",
"the",
"specified",
"object",
"to",
"the",
"in",
"-",
"memory",
"db",
"."
] | train | https://github.com/fabric8io/mockwebserver/blob/ca14c6dd2ec8e2425585a548d5c0d993332b9d2f/src/main/java/io/fabric8/mockwebserver/crud/CrudDispatcher.java#L78-L100 |
jbundle/jbundle | thin/base/screen/cal/grid/src/main/java/org/jbundle/thin/base/screen/cal/grid/CalendarThinTableModel.java | CalendarThinTableModel.selectionChanged | public boolean selectionChanged(Object source, int iStartRow, int iEndRow, int iSelectType)
{
boolean bChanged = super.selectionChanged(source, iStartRow, iEndRow, iSelectType);
if (bChanged)
{ // Notify all the listSelectionListeners
this.fireMySelectionChanged(new MyListSelectionEvent(source, this, m_iSelectedRow, iSelectType));
}
return bChanged;
} | java | public boolean selectionChanged(Object source, int iStartRow, int iEndRow, int iSelectType)
{
boolean bChanged = super.selectionChanged(source, iStartRow, iEndRow, iSelectType);
if (bChanged)
{ // Notify all the listSelectionListeners
this.fireMySelectionChanged(new MyListSelectionEvent(source, this, m_iSelectedRow, iSelectType));
}
return bChanged;
} | [
"public",
"boolean",
"selectionChanged",
"(",
"Object",
"source",
",",
"int",
"iStartRow",
",",
"int",
"iEndRow",
",",
"int",
"iSelectType",
")",
"{",
"boolean",
"bChanged",
"=",
"super",
".",
"selectionChanged",
"(",
"source",
",",
"iStartRow",
",",
"iEndRow"... | User selected a new row.
From the ListSelectionListener interface. | [
"User",
"selected",
"a",
"new",
"row",
".",
"From",
"the",
"ListSelectionListener",
"interface",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/cal/grid/src/main/java/org/jbundle/thin/base/screen/cal/grid/CalendarThinTableModel.java#L184-L192 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/OperatorStateCheckpointOutputStream.java | OperatorStateCheckpointOutputStream.closeAndGetHandle | @Override
OperatorStateHandle closeAndGetHandle() throws IOException {
StreamStateHandle streamStateHandle = delegate.closeAndGetHandle();
if (null == streamStateHandle) {
return null;
}
if (partitionOffsets.isEmpty() && delegate.getPos() > initialPosition) {
startNewPartition();
}
Map<String, OperatorStateHandle.StateMetaInfo> offsetsMap = new HashMap<>(1);
OperatorStateHandle.StateMetaInfo metaInfo =
new OperatorStateHandle.StateMetaInfo(
partitionOffsets.toArray(),
OperatorStateHandle.Mode.SPLIT_DISTRIBUTE);
offsetsMap.put(DefaultOperatorStateBackend.DEFAULT_OPERATOR_STATE_NAME, metaInfo);
return new OperatorStreamStateHandle(offsetsMap, streamStateHandle);
} | java | @Override
OperatorStateHandle closeAndGetHandle() throws IOException {
StreamStateHandle streamStateHandle = delegate.closeAndGetHandle();
if (null == streamStateHandle) {
return null;
}
if (partitionOffsets.isEmpty() && delegate.getPos() > initialPosition) {
startNewPartition();
}
Map<String, OperatorStateHandle.StateMetaInfo> offsetsMap = new HashMap<>(1);
OperatorStateHandle.StateMetaInfo metaInfo =
new OperatorStateHandle.StateMetaInfo(
partitionOffsets.toArray(),
OperatorStateHandle.Mode.SPLIT_DISTRIBUTE);
offsetsMap.put(DefaultOperatorStateBackend.DEFAULT_OPERATOR_STATE_NAME, metaInfo);
return new OperatorStreamStateHandle(offsetsMap, streamStateHandle);
} | [
"@",
"Override",
"OperatorStateHandle",
"closeAndGetHandle",
"(",
")",
"throws",
"IOException",
"{",
"StreamStateHandle",
"streamStateHandle",
"=",
"delegate",
".",
"closeAndGetHandle",
"(",
")",
";",
"if",
"(",
"null",
"==",
"streamStateHandle",
")",
"{",
"return",... | This method should not be public so as to not expose internals to user code. | [
"This",
"method",
"should",
"not",
"be",
"public",
"so",
"as",
"to",
"not",
"expose",
"internals",
"to",
"user",
"code",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/state/OperatorStateCheckpointOutputStream.java#L57-L79 |
Stratio/deep-spark | deep-commons/src/main/java/com/stratio/deep/commons/entity/Cells.java | Cells.getCharacter | public Character getCharacter(String nameSpace, String cellName) {
return getValue(nameSpace, cellName, Character.class);
} | java | public Character getCharacter(String nameSpace, String cellName) {
return getValue(nameSpace, cellName, Character.class);
} | [
"public",
"Character",
"getCharacter",
"(",
"String",
"nameSpace",
",",
"String",
"cellName",
")",
"{",
"return",
"getValue",
"(",
"nameSpace",
",",
"cellName",
",",
"Character",
".",
"class",
")",
";",
"}"
] | Returns the {@code Character} value of the {@link Cell} (associated to {@code table}) whose name iscellName, or
null if this Cells object contains no cell whose name is cellName.
@param nameSpace the name of the owning table
@param cellName the name of the Cell we want to retrieve from this Cells object.
@return the {@code Character} value of the {@link Cell} (associated to {@code table}) whose name is cellName, or
null if this Cells object contains no cell whose name is cellName | [
"Returns",
"the",
"{",
"@code",
"Character",
"}",
"value",
"of",
"the",
"{",
"@link",
"Cell",
"}",
"(",
"associated",
"to",
"{",
"@code",
"table",
"}",
")",
"whose",
"name",
"iscellName",
"or",
"null",
"if",
"this",
"Cells",
"object",
"contains",
"no",
... | train | https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-commons/src/main/java/com/stratio/deep/commons/entity/Cells.java#L787-L789 |
Stratio/stratio-cassandra | src/java/com/stratio/cassandra/index/geospatial/GeoDistance.java | GeoDistance.create | @JsonCreator
public static GeoDistance create(String json) {
try {
for (GeoDistanceUnit geoDistanceUnit : GeoDistanceUnit.values()) {
for (String name : geoDistanceUnit.getNames()) {
if (json.endsWith(name)) {
double value = Double.parseDouble(json.substring(0, json.indexOf(name)));
return new GeoDistance(value, geoDistanceUnit);
}
}
}
double value = Double.parseDouble(json);
return new GeoDistance(value, GeoDistanceUnit.METRES);
} catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException("Unparseable distance: " + json);
}
} | java | @JsonCreator
public static GeoDistance create(String json) {
try {
for (GeoDistanceUnit geoDistanceUnit : GeoDistanceUnit.values()) {
for (String name : geoDistanceUnit.getNames()) {
if (json.endsWith(name)) {
double value = Double.parseDouble(json.substring(0, json.indexOf(name)));
return new GeoDistance(value, geoDistanceUnit);
}
}
}
double value = Double.parseDouble(json);
return new GeoDistance(value, GeoDistanceUnit.METRES);
} catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException("Unparseable distance: " + json);
}
} | [
"@",
"JsonCreator",
"public",
"static",
"GeoDistance",
"create",
"(",
"String",
"json",
")",
"{",
"try",
"{",
"for",
"(",
"GeoDistanceUnit",
"geoDistanceUnit",
":",
"GeoDistanceUnit",
".",
"values",
"(",
")",
")",
"{",
"for",
"(",
"String",
"name",
":",
"g... | Returns the {@link GeoDistance} represented by the specified JSON {@code String}.
@param json A {@code String} containing a JSON encoded {@link GeoDistance}.
@return The {@link GeoDistance} represented by the specified JSON {@code String}. | [
"Returns",
"the",
"{",
"@link",
"GeoDistance",
"}",
"represented",
"by",
"the",
"specified",
"JSON",
"{",
"@code",
"String",
"}",
"."
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/geospatial/GeoDistance.java#L59-L76 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/trifocal/TrifocalLinearPoint7.java | TrifocalLinearPoint7.process | public boolean process( List<AssociatedTriple> observations , TrifocalTensor solution ) {
if( observations.size() < 7 )
throw new IllegalArgumentException(
"At least 7 correspondences must be provided. Found "+observations.size());
// compute normalization to reduce numerical errors
LowLevelMultiViewOps.computeNormalization(observations, N1, N2, N3);
// compute solution in normalized pixel coordinates
createLinearSystem(observations);
// solve for the trifocal tensor
solveLinearSystem();
// enforce geometric constraints to improve solution
extractEpipoles.setTensor(solutionN);
extractEpipoles.extractEpipoles(e2,e3);
enforce.process(e2,e3,A);
enforce.extractSolution(solutionN);
// undo normalization
removeNormalization(solution);
return true;
} | java | public boolean process( List<AssociatedTriple> observations , TrifocalTensor solution ) {
if( observations.size() < 7 )
throw new IllegalArgumentException(
"At least 7 correspondences must be provided. Found "+observations.size());
// compute normalization to reduce numerical errors
LowLevelMultiViewOps.computeNormalization(observations, N1, N2, N3);
// compute solution in normalized pixel coordinates
createLinearSystem(observations);
// solve for the trifocal tensor
solveLinearSystem();
// enforce geometric constraints to improve solution
extractEpipoles.setTensor(solutionN);
extractEpipoles.extractEpipoles(e2,e3);
enforce.process(e2,e3,A);
enforce.extractSolution(solutionN);
// undo normalization
removeNormalization(solution);
return true;
} | [
"public",
"boolean",
"process",
"(",
"List",
"<",
"AssociatedTriple",
">",
"observations",
",",
"TrifocalTensor",
"solution",
")",
"{",
"if",
"(",
"observations",
".",
"size",
"(",
")",
"<",
"7",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"At leas... | Estimates the trifocal tensor given the set of observations
@param observations Set of observations
@param solution Output: Where the solution is written to
@return true if successful and false if it fails | [
"Estimates",
"the",
"trifocal",
"tensor",
"given",
"the",
"set",
"of",
"observations"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/trifocal/TrifocalLinearPoint7.java#L97-L122 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java | TrainingsImpl.getImagePerformances | public List<ImagePerformance> getImagePerformances(UUID projectId, UUID iterationId, GetImagePerformancesOptionalParameter getImagePerformancesOptionalParameter) {
return getImagePerformancesWithServiceResponseAsync(projectId, iterationId, getImagePerformancesOptionalParameter).toBlocking().single().body();
} | java | public List<ImagePerformance> getImagePerformances(UUID projectId, UUID iterationId, GetImagePerformancesOptionalParameter getImagePerformancesOptionalParameter) {
return getImagePerformancesWithServiceResponseAsync(projectId, iterationId, getImagePerformancesOptionalParameter).toBlocking().single().body();
} | [
"public",
"List",
"<",
"ImagePerformance",
">",
"getImagePerformances",
"(",
"UUID",
"projectId",
",",
"UUID",
"iterationId",
",",
"GetImagePerformancesOptionalParameter",
"getImagePerformancesOptionalParameter",
")",
"{",
"return",
"getImagePerformancesWithServiceResponseAsync",... | Get image with its prediction for a given project iteration.
This API supports batching and range selection. By default it will only return first 50 images matching images.
Use the {take} and {skip} parameters to control how many images to return in a given batch.
The filtering is on an and/or relationship. For example, if the provided tag ids are for the "Dog" and
"Cat" tags, then only images tagged with Dog and/or Cat will be returned.
@param projectId The project id
@param iterationId The iteration id. Defaults to workspace
@param getImagePerformancesOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the List<ImagePerformance> object if successful. | [
"Get",
"image",
"with",
"its",
"prediction",
"for",
"a",
"given",
"project",
"iteration",
".",
"This",
"API",
"supports",
"batching",
"and",
"range",
"selection",
".",
"By",
"default",
"it",
"will",
"only",
"return",
"first",
"50",
"images",
"matching",
"ima... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L1403-L1405 |
GoogleCloudPlatform/bigdata-interop | bigquery/src/main/java/com/google/cloud/hadoop/io/bigquery/output/IndirectBigQueryOutputCommitter.java | IndirectBigQueryOutputCommitter.abortJob | @Override
public void abortJob(JobContext context, State state) throws IOException {
super.abortJob(context, state);
cleanup(context);
} | java | @Override
public void abortJob(JobContext context, State state) throws IOException {
super.abortJob(context, state);
cleanup(context);
} | [
"@",
"Override",
"public",
"void",
"abortJob",
"(",
"JobContext",
"context",
",",
"State",
"state",
")",
"throws",
"IOException",
"{",
"super",
".",
"abortJob",
"(",
"context",
",",
"state",
")",
";",
"cleanup",
"(",
"context",
")",
";",
"}"
] | Performs a cleanup of the output path in addition to delegating the call to the wrapped
OutputCommitter. | [
"Performs",
"a",
"cleanup",
"of",
"the",
"output",
"path",
"in",
"addition",
"to",
"delegating",
"the",
"call",
"to",
"the",
"wrapped",
"OutputCommitter",
"."
] | train | https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/bigquery/src/main/java/com/google/cloud/hadoop/io/bigquery/output/IndirectBigQueryOutputCommitter.java#L91-L95 |
aws/aws-sdk-java | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/Put.java | Put.withItem | public Put withItem(java.util.Map<String, AttributeValue> item) {
setItem(item);
return this;
} | java | public Put withItem(java.util.Map<String, AttributeValue> item) {
setItem(item);
return this;
} | [
"public",
"Put",
"withItem",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"AttributeValue",
">",
"item",
")",
"{",
"setItem",
"(",
"item",
")",
";",
"return",
"this",
";",
"}"
] | <p>
A map of attribute name to attribute values, representing the primary key of the item to be written by
<code>PutItem</code>. All of the table's primary key attributes must be specified, and their data types must
match those of the table's key schema. If any attributes are present in the item that are part of an index key
schema for the table, their types must match the index key schema.
</p>
@param item
A map of attribute name to attribute values, representing the primary key of the item to be written by
<code>PutItem</code>. All of the table's primary key attributes must be specified, and their data types
must match those of the table's key schema. If any attributes are present in the item that are part of an
index key schema for the table, their types must match the index key schema.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"A",
"map",
"of",
"attribute",
"name",
"to",
"attribute",
"values",
"representing",
"the",
"primary",
"key",
"of",
"the",
"item",
"to",
"be",
"written",
"by",
"<code",
">",
"PutItem<",
"/",
"code",
">",
".",
"All",
"of",
"the",
"table",
"s",... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/Put.java#L124-L127 |
Netflix/eureka | eureka-core/src/main/java/com/netflix/eureka/aws/AwsAsgUtil.java | AwsAsgUtil.setStatus | public void setStatus(String asgName, boolean enabled) {
String asgAccountId = getASGAccount(asgName);
asgCache.put(new CacheKey(asgAccountId, asgName), enabled);
} | java | public void setStatus(String asgName, boolean enabled) {
String asgAccountId = getASGAccount(asgName);
asgCache.put(new CacheKey(asgAccountId, asgName), enabled);
} | [
"public",
"void",
"setStatus",
"(",
"String",
"asgName",
",",
"boolean",
"enabled",
")",
"{",
"String",
"asgAccountId",
"=",
"getASGAccount",
"(",
"asgName",
")",
";",
"asgCache",
".",
"put",
"(",
"new",
"CacheKey",
"(",
"asgAccountId",
",",
"asgName",
")",
... | Sets the status of the ASG.
@param asgName The name of the ASG
@param enabled true to enable, false to disable | [
"Sets",
"the",
"status",
"of",
"the",
"ASG",
"."
] | train | https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-core/src/main/java/com/netflix/eureka/aws/AwsAsgUtil.java#L193-L196 |
opendatatrentino/s-match | src/main/java/it/unitn/disi/common/components/Configurable.java | Configurable.getComponentProperties | protected static Properties getComponentProperties(String componentPrefix, Properties properties) {
Properties result = new Properties();
if (null != componentPrefix) {
int componentPrefixLength = componentPrefix.length();
for (String propertyName : properties.stringPropertyNames()) {
if (propertyName.startsWith(componentPrefix)) {
result.put(propertyName.substring(componentPrefixLength), properties.getProperty(propertyName));
}
}
}
return result;
} | java | protected static Properties getComponentProperties(String componentPrefix, Properties properties) {
Properties result = new Properties();
if (null != componentPrefix) {
int componentPrefixLength = componentPrefix.length();
for (String propertyName : properties.stringPropertyNames()) {
if (propertyName.startsWith(componentPrefix)) {
result.put(propertyName.substring(componentPrefixLength), properties.getProperty(propertyName));
}
}
}
return result;
} | [
"protected",
"static",
"Properties",
"getComponentProperties",
"(",
"String",
"componentPrefix",
",",
"Properties",
"properties",
")",
"{",
"Properties",
"result",
"=",
"new",
"Properties",
"(",
")",
";",
"if",
"(",
"null",
"!=",
"componentPrefix",
")",
"{",
"in... | Returns only properties that start with componentPrefix, removing this prefix.
@param componentPrefix a prefix to search
@param properties properties
@return properties that start with componentPrefix | [
"Returns",
"only",
"properties",
"that",
"start",
"with",
"componentPrefix",
"removing",
"this",
"prefix",
"."
] | train | https://github.com/opendatatrentino/s-match/blob/ba5982ef406b7010c2f92592e43887a485935aa1/src/main/java/it/unitn/disi/common/components/Configurable.java#L61-L72 |
windup/windup | rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/provider/DiscoverMavenProjectsRuleProvider.java | DiscoverMavenProjectsRuleProvider.getMavenProject | private MavenProjectModel getMavenProject(MavenProjectService mavenProjectService, String groupId, String artifactId, String version)
{
Iterable<MavenProjectModel> possibleProjects = mavenProjectService.findByGroupArtifactVersion(groupId, artifactId, version);
MavenProjectModel project = null;
for (MavenProjectModel possibleProject : possibleProjects)
{
if (possibleProject.getRootFileModel() != null)
{
return possibleProject;
}
else if (project == null)
{
project = possibleProject;
}
}
return project;
} | java | private MavenProjectModel getMavenProject(MavenProjectService mavenProjectService, String groupId, String artifactId, String version)
{
Iterable<MavenProjectModel> possibleProjects = mavenProjectService.findByGroupArtifactVersion(groupId, artifactId, version);
MavenProjectModel project = null;
for (MavenProjectModel possibleProject : possibleProjects)
{
if (possibleProject.getRootFileModel() != null)
{
return possibleProject;
}
else if (project == null)
{
project = possibleProject;
}
}
return project;
} | [
"private",
"MavenProjectModel",
"getMavenProject",
"(",
"MavenProjectService",
"mavenProjectService",
",",
"String",
"groupId",
",",
"String",
"artifactId",
",",
"String",
"version",
")",
"{",
"Iterable",
"<",
"MavenProjectModel",
">",
"possibleProjects",
"=",
"mavenPro... | This will return a {@link MavenProjectModel} with the give gav, preferring one that has been found in the input
application as opposed to a stub. | [
"This",
"will",
"return",
"a",
"{"
] | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/provider/DiscoverMavenProjectsRuleProvider.java#L378-L394 |
OpenLiberty/open-liberty | dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/jmx/PmiCollaborator.java | PmiCollaborator.setCustomSetString | @Override
public void setCustomSetString(String setting, Boolean recursive) {
if (tc.isEntryEnabled())
Tr.entry(tc, "setCustomSetString (String, Boolean): " + setting);
setInstrumentationLevel(_createSLSFromString(setting), recursive);
if (tc.isEntryEnabled())
Tr.exit(tc, "setCustomSetString");
} | java | @Override
public void setCustomSetString(String setting, Boolean recursive) {
if (tc.isEntryEnabled())
Tr.entry(tc, "setCustomSetString (String, Boolean): " + setting);
setInstrumentationLevel(_createSLSFromString(setting), recursive);
if (tc.isEntryEnabled())
Tr.exit(tc, "setCustomSetString");
} | [
"@",
"Override",
"public",
"void",
"setCustomSetString",
"(",
"String",
"setting",
",",
"Boolean",
"recursive",
")",
"{",
"if",
"(",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"entry",
"(",
"tc",
",",
"\"setCustomSetString (String, Boolean): \"",
"... | New in 6.0: Set custom statistic set using fine-grained control | [
"New",
"in",
"6",
".",
"0",
":",
"Set",
"custom",
"statistic",
"set",
"using",
"fine",
"-",
"grained",
"control"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/jmx/PmiCollaborator.java#L89-L98 |
modelmapper/modelmapper | core/src/main/java/org/modelmapper/internal/PropertyInfoRegistry.java | PropertyInfoRegistry.mutatorFor | static synchronized Mutator mutatorFor(Class<?> type, Method method, Configuration configuration,
String name) {
PropertyInfoKey key = new PropertyInfoKey(type, name, configuration);
Mutator mutator = MUTATOR_CACHE.get(key);
if (mutator == null) {
mutator = new MethodMutator(type, method, name);
MUTATOR_CACHE.put(key, mutator);
}
return mutator;
} | java | static synchronized Mutator mutatorFor(Class<?> type, Method method, Configuration configuration,
String name) {
PropertyInfoKey key = new PropertyInfoKey(type, name, configuration);
Mutator mutator = MUTATOR_CACHE.get(key);
if (mutator == null) {
mutator = new MethodMutator(type, method, name);
MUTATOR_CACHE.put(key, mutator);
}
return mutator;
} | [
"static",
"synchronized",
"Mutator",
"mutatorFor",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"Method",
"method",
",",
"Configuration",
"configuration",
",",
"String",
"name",
")",
"{",
"PropertyInfoKey",
"key",
"=",
"new",
"PropertyInfoKey",
"(",
"type",
",",
... | Returns a Mutator instance for the given mutator method. The method must be externally
validated to ensure that it accepts one argument and returns void.class. | [
"Returns",
"a",
"Mutator",
"instance",
"for",
"the",
"given",
"mutator",
"method",
".",
"The",
"method",
"must",
"be",
"externally",
"validated",
"to",
"ensure",
"that",
"it",
"accepts",
"one",
"argument",
"and",
"returns",
"void",
".",
"class",
"."
] | train | https://github.com/modelmapper/modelmapper/blob/491d165ded9dc9aba7ce8b56984249e1a1363204/core/src/main/java/org/modelmapper/internal/PropertyInfoRegistry.java#L152-L162 |
Whiley/WhileyCompiler | src/main/java/wyc/io/WhileyFileParser.java | WhileyFileParser.parseStaticVariableDeclaration | private Decl.StaticVariable parseStaticVariableDeclaration(Tuple<Modifier> modifiers) {
//
int start = index;
EnclosingScope scope = new EnclosingScope();
//
Type type = parseType(scope);
//
Identifier name = parseIdentifier();
match(Equals);
Expr e = parseExpression(scope, false);
int end = index;
matchEndLine();
return annotateSourceLocation(new Decl.StaticVariable(modifiers, name, type, e), start);
} | java | private Decl.StaticVariable parseStaticVariableDeclaration(Tuple<Modifier> modifiers) {
//
int start = index;
EnclosingScope scope = new EnclosingScope();
//
Type type = parseType(scope);
//
Identifier name = parseIdentifier();
match(Equals);
Expr e = parseExpression(scope, false);
int end = index;
matchEndLine();
return annotateSourceLocation(new Decl.StaticVariable(modifiers, name, type, e), start);
} | [
"private",
"Decl",
".",
"StaticVariable",
"parseStaticVariableDeclaration",
"(",
"Tuple",
"<",
"Modifier",
">",
"modifiers",
")",
"{",
"//",
"int",
"start",
"=",
"index",
";",
"EnclosingScope",
"scope",
"=",
"new",
"EnclosingScope",
"(",
")",
";",
"//",
"Type"... | Parse a constant declaration in a Whiley source file, which has the form:
<pre>
ConstantDeclaration ::= "constant" Identifier "is"Expr
</pre>
A simple example to illustrate is:
<pre>
constant PI is 3.141592654
</pre>
Here, we are defining a constant called <code>PI</code> which represents
the decimal value "3.141592654". Constant declarations may also have
modifiers, such as <code>public</code> and <code>private</code>.
@see wyc.lang.WhielyFile.StaticVariable
@param modifiers
--- The list of modifiers for this declaration (which were
already parsed before this method was called). | [
"Parse",
"a",
"constant",
"declaration",
"in",
"a",
"Whiley",
"source",
"file",
"which",
"has",
"the",
"form",
":"
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L545-L558 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/SourceToHTMLConverter.java | SourceToHTMLConverter.addLineNo | private static void addLineNo(Content pre, int lineno) {
HtmlTree span = new HtmlTree(HtmlTag.SPAN);
span.addStyle(HtmlStyle.sourceLineNo);
if (lineno < 10) {
span.addContent("00" + Integer.toString(lineno));
} else if (lineno < 100) {
span.addContent("0" + Integer.toString(lineno));
} else {
span.addContent(Integer.toString(lineno));
}
pre.addContent(span);
} | java | private static void addLineNo(Content pre, int lineno) {
HtmlTree span = new HtmlTree(HtmlTag.SPAN);
span.addStyle(HtmlStyle.sourceLineNo);
if (lineno < 10) {
span.addContent("00" + Integer.toString(lineno));
} else if (lineno < 100) {
span.addContent("0" + Integer.toString(lineno));
} else {
span.addContent(Integer.toString(lineno));
}
pre.addContent(span);
} | [
"private",
"static",
"void",
"addLineNo",
"(",
"Content",
"pre",
",",
"int",
"lineno",
")",
"{",
"HtmlTree",
"span",
"=",
"new",
"HtmlTree",
"(",
"HtmlTag",
".",
"SPAN",
")",
";",
"span",
".",
"addStyle",
"(",
"HtmlStyle",
".",
"sourceLineNo",
")",
";",
... | Add the line numbers for the source code.
@param pre the content tree to which the line number will be added
@param lineno The line number | [
"Add",
"the",
"line",
"numbers",
"for",
"the",
"source",
"code",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/SourceToHTMLConverter.java#L247-L258 |
pip-services3-java/pip-services3-components-java | src/org/pipservices3/components/count/CompositeCounters.java | CompositeCounters.endTiming | public void endTiming(String name, float elapsed) {
for (ICounters counter : _counters) {
if (counter instanceof ITimingCallback)
((ITimingCallback) counter).endTiming(name, elapsed);
}
} | java | public void endTiming(String name, float elapsed) {
for (ICounters counter : _counters) {
if (counter instanceof ITimingCallback)
((ITimingCallback) counter).endTiming(name, elapsed);
}
} | [
"public",
"void",
"endTiming",
"(",
"String",
"name",
",",
"float",
"elapsed",
")",
"{",
"for",
"(",
"ICounters",
"counter",
":",
"_counters",
")",
"{",
"if",
"(",
"counter",
"instanceof",
"ITimingCallback",
")",
"(",
"(",
"ITimingCallback",
")",
"counter",
... | Ends measurement of execution elapsed time and updates specified counter.
@param name a counter name
@param elapsed execution elapsed time in milliseconds to update the counter.
@see Timing#endTiming() | [
"Ends",
"measurement",
"of",
"execution",
"elapsed",
"time",
"and",
"updates",
"specified",
"counter",
"."
] | train | https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/count/CompositeCounters.java#L86-L91 |
atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java | RaftServiceContext.executeCommand | public OperationResult executeCommand(long index, long sequence, long timestamp, RaftSession session, PrimitiveOperation operation) {
// If the service has been deleted then throw an unknown service exception.
if (deleted) {
log.warn("Service {} has been deleted by another process", serviceName);
throw new RaftException.UnknownService("Service " + serviceName + " has been deleted");
}
// If the session is not open, fail the request.
if (!session.getState().active()) {
log.warn("Session not open: {}", session);
throw new RaftException.UnknownSession("Unknown session: " + session.sessionId());
}
// Update the session's timestamp to prevent it from being expired.
session.setLastUpdated(timestamp);
// Update the state machine index/timestamp.
tick(index, timestamp);
// If the command's sequence number is less than the next session sequence number then that indicates that
// we've received a command that was previously applied to the state machine. Ensure linearizability by
// returning the cached response instead of applying it to the user defined state machine.
if (sequence > 0 && sequence < session.nextCommandSequence()) {
log.trace("Returning cached result for command with sequence number {} < {}", sequence, session.nextCommandSequence());
return sequenceCommand(index, sequence, session);
}
// If we've made it this far, the command must have been applied in the proper order as sequenced by the
// session. This should be the case for most commands applied to the state machine.
else {
// Execute the command in the state machine thread. Once complete, the CompletableFuture callback will be completed
// in the state machine thread. Register the result in that thread and then complete the future in the caller's thread.
return applyCommand(index, sequence, timestamp, operation, session);
}
} | java | public OperationResult executeCommand(long index, long sequence, long timestamp, RaftSession session, PrimitiveOperation operation) {
// If the service has been deleted then throw an unknown service exception.
if (deleted) {
log.warn("Service {} has been deleted by another process", serviceName);
throw new RaftException.UnknownService("Service " + serviceName + " has been deleted");
}
// If the session is not open, fail the request.
if (!session.getState().active()) {
log.warn("Session not open: {}", session);
throw new RaftException.UnknownSession("Unknown session: " + session.sessionId());
}
// Update the session's timestamp to prevent it from being expired.
session.setLastUpdated(timestamp);
// Update the state machine index/timestamp.
tick(index, timestamp);
// If the command's sequence number is less than the next session sequence number then that indicates that
// we've received a command that was previously applied to the state machine. Ensure linearizability by
// returning the cached response instead of applying it to the user defined state machine.
if (sequence > 0 && sequence < session.nextCommandSequence()) {
log.trace("Returning cached result for command with sequence number {} < {}", sequence, session.nextCommandSequence());
return sequenceCommand(index, sequence, session);
}
// If we've made it this far, the command must have been applied in the proper order as sequenced by the
// session. This should be the case for most commands applied to the state machine.
else {
// Execute the command in the state machine thread. Once complete, the CompletableFuture callback will be completed
// in the state machine thread. Register the result in that thread and then complete the future in the caller's thread.
return applyCommand(index, sequence, timestamp, operation, session);
}
} | [
"public",
"OperationResult",
"executeCommand",
"(",
"long",
"index",
",",
"long",
"sequence",
",",
"long",
"timestamp",
",",
"RaftSession",
"session",
",",
"PrimitiveOperation",
"operation",
")",
"{",
"// If the service has been deleted then throw an unknown service exception... | Executes the given command on the state machine.
@param index The index of the command.
@param timestamp The timestamp of the command.
@param sequence The command sequence number.
@param session The session that submitted the command.
@param operation The command to execute.
@return A future to be completed with the command result. | [
"Executes",
"the",
"given",
"command",
"on",
"the",
"state",
"machine",
"."
] | train | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java#L483-L516 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/db/GridTable.java | GridTable.bookmarkToIndex | public int bookmarkToIndex(Object bookmark, int iHandleType)
{
if (bookmark == null)
return -1;
int iTargetPosition = m_gridBuffer.bookmarkToIndex(bookmark, iHandleType);
if (iTargetPosition == -1)
iTargetPosition = m_gridList.bookmarkToIndex(bookmark, iHandleType);
return iTargetPosition; // Target position
} | java | public int bookmarkToIndex(Object bookmark, int iHandleType)
{
if (bookmark == null)
return -1;
int iTargetPosition = m_gridBuffer.bookmarkToIndex(bookmark, iHandleType);
if (iTargetPosition == -1)
iTargetPosition = m_gridList.bookmarkToIndex(bookmark, iHandleType);
return iTargetPosition; // Target position
} | [
"public",
"int",
"bookmarkToIndex",
"(",
"Object",
"bookmark",
",",
"int",
"iHandleType",
")",
"{",
"if",
"(",
"bookmark",
"==",
"null",
")",
"return",
"-",
"1",
";",
"int",
"iTargetPosition",
"=",
"m_gridBuffer",
".",
"bookmarkToIndex",
"(",
"bookmark",
","... | Search through the buffers for this bookmark.
@return int index in table; or -1 if not found.
@param bookmark java.lang.Object The bookmark to search for.
@param iHandleType The bookmark type. | [
"Search",
"through",
"the",
"buffers",
"for",
"this",
"bookmark",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/GridTable.java#L222-L230 |
BBN-E/bue-common-open | common-core-open/src/main/java/com/bbn/bue/common/collections/CollectionUtils.java | CollectionUtils.minOr | public static <T extends Comparable<T>> T minOr(Collection<T> values, T defaultVal) {
if (values.isEmpty()) {
return defaultVal;
} else {
return Collections.min(values);
}
} | java | public static <T extends Comparable<T>> T minOr(Collection<T> values, T defaultVal) {
if (values.isEmpty()) {
return defaultVal;
} else {
return Collections.min(values);
}
} | [
"public",
"static",
"<",
"T",
"extends",
"Comparable",
"<",
"T",
">",
">",
"T",
"minOr",
"(",
"Collection",
"<",
"T",
">",
"values",
",",
"T",
"defaultVal",
")",
"{",
"if",
"(",
"values",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"defaultVal",
... | Like {@link Collections#min(java.util.Collection)} except with a default value returned in the
case of an empty collection. | [
"Like",
"{"
] | train | https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/collections/CollectionUtils.java#L197-L203 |
igniterealtime/Smack | smack-openpgp/src/main/java/org/jivesoftware/smackx/ox_im/OXInstantMessagingManager.java | OXInstantMessagingManager.addOxMessage | public OpenPgpMetadata addOxMessage(Message message, OpenPgpContact contact, List<ExtensionElement> payload)
throws SmackException.NotLoggedInException, PGPException, IOException {
return addOxMessage(message, Collections.singleton(contact), payload);
} | java | public OpenPgpMetadata addOxMessage(Message message, OpenPgpContact contact, List<ExtensionElement> payload)
throws SmackException.NotLoggedInException, PGPException, IOException {
return addOxMessage(message, Collections.singleton(contact), payload);
} | [
"public",
"OpenPgpMetadata",
"addOxMessage",
"(",
"Message",
"message",
",",
"OpenPgpContact",
"contact",
",",
"List",
"<",
"ExtensionElement",
">",
"payload",
")",
"throws",
"SmackException",
".",
"NotLoggedInException",
",",
"PGPException",
",",
"IOException",
"{",
... | Add an OX-IM message element to a message.
@param message message
@param contact recipient of the message
@param payload payload which will be encrypted and signed
@return {@link OpenPgpMetadata} about the messages encryption + metadata.
@throws SmackException.NotLoggedInException in case we are not logged in
@throws PGPException in case something goes wrong during encryption
@throws IOException IO is dangerous (we need to read keys) | [
"Add",
"an",
"OX",
"-",
"IM",
"message",
"element",
"to",
"a",
"message",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-openpgp/src/main/java/org/jivesoftware/smackx/ox_im/OXInstantMessagingManager.java#L253-L256 |
alkacon/opencms-core | src/org/opencms/db/CmsDriverManager.java | CmsDriverManager.readAliasesBySite | public List<CmsAlias> readAliasesBySite(CmsDbContext dbc, CmsProject currentProject, String siteRoot)
throws CmsException {
return getVfsDriver(dbc).readAliases(dbc, currentProject, new CmsAliasFilter(siteRoot, null, null));
} | java | public List<CmsAlias> readAliasesBySite(CmsDbContext dbc, CmsProject currentProject, String siteRoot)
throws CmsException {
return getVfsDriver(dbc).readAliases(dbc, currentProject, new CmsAliasFilter(siteRoot, null, null));
} | [
"public",
"List",
"<",
"CmsAlias",
">",
"readAliasesBySite",
"(",
"CmsDbContext",
"dbc",
",",
"CmsProject",
"currentProject",
",",
"String",
"siteRoot",
")",
"throws",
"CmsException",
"{",
"return",
"getVfsDriver",
"(",
"dbc",
")",
".",
"readAliases",
"(",
"dbc"... | Reads the aliases for a given site root.<p>
@param dbc the current database context
@param currentProject the current project
@param siteRoot the site root
@return the list of aliases for the given site root
@throws CmsException if something goes wrong | [
"Reads",
"the",
"aliases",
"for",
"a",
"given",
"site",
"root",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L6365-L6369 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jaxrs.2.0.common/src/org/apache/cxf/jaxrs/utils/ThreadLocalProxyCopyOnWriteArrayList.java | ThreadLocalProxyCopyOnWriteArrayList.set | @Override
public E set(int index, E element) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
E oldValue = get(elements, index);
if (oldValue != element) {
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len);
newElements[index] = element;
setArray(newElements);
} else {
// Not quite a no-op; ensures volatile write semantics
setArray(elements);
}
return oldValue;
} finally {
lock.unlock();
}
} | java | @Override
public E set(int index, E element) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
E oldValue = get(elements, index);
if (oldValue != element) {
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len);
newElements[index] = element;
setArray(newElements);
} else {
// Not quite a no-op; ensures volatile write semantics
setArray(elements);
}
return oldValue;
} finally {
lock.unlock();
}
} | [
"@",
"Override",
"public",
"E",
"set",
"(",
"int",
"index",
",",
"E",
"element",
")",
"{",
"final",
"ReentrantLock",
"lock",
"=",
"this",
".",
"lock",
";",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"Object",
"[",
"]",
"elements",
"=",
"getArr... | Replaces the element at the specified position in this list with the
specified element.
@throws IndexOutOfBoundsException {@inheritDoc} | [
"Replaces",
"the",
"element",
"at",
"the",
"specified",
"position",
"in",
"this",
"list",
"with",
"the",
"specified",
"element",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxrs.2.0.common/src/org/apache/cxf/jaxrs/utils/ThreadLocalProxyCopyOnWriteArrayList.java#L325-L346 |
QSFT/Doradus | doradus-common/src/main/java/com/dell/doradus/management/CronUtils.java | CronUtils.replaceChars | private static String replaceChars(String e, String chars1, String chars2) {
assert chars1.length() == chars2.length();
String[] parts = e.split(",");
for (int i = 0; i < parts.length; ++i) {
String[] elems = parts[i].split("/");
for (int j = 0; j < chars1.length(); ++j) {
elems[0] = elems[0].replace(chars1.charAt(j), chars2.charAt(j));
}
parts[i] = concat('/', elems);
}
return concat(',', parts);
} | java | private static String replaceChars(String e, String chars1, String chars2) {
assert chars1.length() == chars2.length();
String[] parts = e.split(",");
for (int i = 0; i < parts.length; ++i) {
String[] elems = parts[i].split("/");
for (int j = 0; j < chars1.length(); ++j) {
elems[0] = elems[0].replace(chars1.charAt(j), chars2.charAt(j));
}
parts[i] = concat('/', elems);
}
return concat(',', parts);
} | [
"private",
"static",
"String",
"replaceChars",
"(",
"String",
"e",
",",
"String",
"chars1",
",",
"String",
"chars2",
")",
"{",
"assert",
"chars1",
".",
"length",
"(",
")",
"==",
"chars2",
".",
"length",
"(",
")",
";",
"String",
"[",
"]",
"parts",
"=",
... | Replaces in first argument string all the characters of the second argument string
to the characters of the third argument string. Actually the source string
is divided into "parts", and replacing takes place in every part before a slash
symbol (if exists), but not after it.
@param e Source string
@param chars1 Characters to replace
@param chars2 Characters to insert
@return String with replacements made. | [
"Replaces",
"in",
"first",
"argument",
"string",
"all",
"the",
"characters",
"of",
"the",
"second",
"argument",
"string",
"to",
"the",
"characters",
"of",
"the",
"third",
"argument",
"string",
".",
"Actually",
"the",
"source",
"string",
"is",
"divided",
"into"... | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/management/CronUtils.java#L153-L165 |
JOML-CI/JOML | src/org/joml/Matrix4d.java | Matrix4d.rotateZYX | public Matrix4d rotateZYX(Vector3d angles) {
return rotateZYX(angles.z, angles.y, angles.x);
} | java | public Matrix4d rotateZYX(Vector3d angles) {
return rotateZYX(angles.z, angles.y, angles.x);
} | [
"public",
"Matrix4d",
"rotateZYX",
"(",
"Vector3d",
"angles",
")",
"{",
"return",
"rotateZYX",
"(",
"angles",
".",
"z",
",",
"angles",
".",
"y",
",",
"angles",
".",
"x",
")",
";",
"}"
] | Apply rotation of <code>angles.z</code> radians about the Z axis, followed by a rotation of <code>angles.y</code> radians about the Y axis and
followed by a rotation of <code>angles.x</code> radians about the X axis.
<p>
When used with a right-handed coordinate system, the produced rotation will rotate a vector
counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin.
When used with a left-handed coordinate system, the rotation is clockwise.
<p>
If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix,
then the new matrix will be <code>M * R</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the
rotation will be applied first!
<p>
This method is equivalent to calling: <code>rotateZ(angles.z).rotateY(angles.y).rotateX(angles.x)</code>
@param angles
the Euler angles
@return this | [
"Apply",
"rotation",
"of",
"<code",
">",
"angles",
".",
"z<",
"/",
"code",
">",
"radians",
"about",
"the",
"Z",
"axis",
"followed",
"by",
"a",
"rotation",
"of",
"<code",
">",
"angles",
".",
"y<",
"/",
"code",
">",
"radians",
"about",
"the",
"Y",
"axi... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L6437-L6439 |
cloudant/java-cloudant | cloudant-client/src/main/java/com/cloudant/client/internal/DatabaseURIHelper.java | DatabaseURIHelper.documentUri | public URI documentUri(String documentId, String key, Object value) {
return this.documentId(documentId).query(key, value).build();
} | java | public URI documentUri(String documentId, String key, Object value) {
return this.documentId(documentId).query(key, value).build();
} | [
"public",
"URI",
"documentUri",
"(",
"String",
"documentId",
",",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"return",
"this",
".",
"documentId",
"(",
"documentId",
")",
".",
"query",
"(",
"key",
",",
"value",
")",
".",
"build",
"(",
")",
";",
... | Returns URI for {@code documentId} with {@code query} key and value. | [
"Returns",
"URI",
"for",
"{"
] | train | https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/DatabaseURIHelper.java#L134-L136 |
roboconf/roboconf-platform | core/roboconf-core/src/main/java/net/roboconf/core/model/helpers/VariableHelpers.java | VariableHelpers.updateNetworkVariables | static void updateNetworkVariables( Map<String,String> instanceExports, String ipAddress ) {
// Find the keys to update ( xxx.ip )
Set<String> keysToUpdate = new HashSet<> ();
for( Map.Entry<String,String> entry : instanceExports.entrySet()) {
String suffix = parseVariableName( entry.getKey()).getValue();
if( Constants.SPECIFIC_VARIABLE_IP.equalsIgnoreCase( suffix ))
keysToUpdate.add( entry.getKey());
}
// Update them
for( String key : keysToUpdate )
instanceExports.put( key, ipAddress );
} | java | static void updateNetworkVariables( Map<String,String> instanceExports, String ipAddress ) {
// Find the keys to update ( xxx.ip )
Set<String> keysToUpdate = new HashSet<> ();
for( Map.Entry<String,String> entry : instanceExports.entrySet()) {
String suffix = parseVariableName( entry.getKey()).getValue();
if( Constants.SPECIFIC_VARIABLE_IP.equalsIgnoreCase( suffix ))
keysToUpdate.add( entry.getKey());
}
// Update them
for( String key : keysToUpdate )
instanceExports.put( key, ipAddress );
} | [
"static",
"void",
"updateNetworkVariables",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"instanceExports",
",",
"String",
"ipAddress",
")",
"{",
"// Find the keys to update ( xxx.ip )",
"Set",
"<",
"String",
">",
"keysToUpdate",
"=",
"new",
"HashSet",
"<>",
"("... | Updates the exports of an instance with network values.
<p>
For the moment, only IP is supported.
</p>
@param instanceExports a non-null map of instance exports
@param ipAddress the IP address to set | [
"Updates",
"the",
"exports",
"of",
"an",
"instance",
"with",
"network",
"values",
".",
"<p",
">",
"For",
"the",
"moment",
"only",
"IP",
"is",
"supported",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/helpers/VariableHelpers.java#L244-L257 |
spring-projects/spring-boot | spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ColorConverter.java | ColorConverter.newInstance | public static ColorConverter newInstance(Configuration config, String[] options) {
if (options.length < 1) {
LOGGER.error("Incorrect number of options on style. "
+ "Expected at least 1, received {}", options.length);
return null;
}
if (options[0] == null) {
LOGGER.error("No pattern supplied on style");
return null;
}
PatternParser parser = PatternLayout.createPatternParser(config);
List<PatternFormatter> formatters = parser.parse(options[0]);
AnsiElement element = (options.length != 1) ? ELEMENTS.get(options[1]) : null;
return new ColorConverter(formatters, element);
} | java | public static ColorConverter newInstance(Configuration config, String[] options) {
if (options.length < 1) {
LOGGER.error("Incorrect number of options on style. "
+ "Expected at least 1, received {}", options.length);
return null;
}
if (options[0] == null) {
LOGGER.error("No pattern supplied on style");
return null;
}
PatternParser parser = PatternLayout.createPatternParser(config);
List<PatternFormatter> formatters = parser.parse(options[0]);
AnsiElement element = (options.length != 1) ? ELEMENTS.get(options[1]) : null;
return new ColorConverter(formatters, element);
} | [
"public",
"static",
"ColorConverter",
"newInstance",
"(",
"Configuration",
"config",
",",
"String",
"[",
"]",
"options",
")",
"{",
"if",
"(",
"options",
".",
"length",
"<",
"1",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"Incorrect number of options on style. \"",... | Creates a new instance of the class. Required by Log4J2.
@param config the configuration
@param options the options
@return a new instance, or {@code null} if the options are invalid | [
"Creates",
"a",
"new",
"instance",
"of",
"the",
"class",
".",
"Required",
"by",
"Log4J2",
"."
] | train | https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ColorConverter.java#L92-L106 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeBuilder.java | AnnotationTypeBuilder.buildAnnotationTypeSignature | public void buildAnnotationTypeSignature(XMLNode node, Content annotationInfoTree) {
writer.addAnnotationTypeSignature(utils.modifiersToString(annotationType, true),
annotationInfoTree);
} | java | public void buildAnnotationTypeSignature(XMLNode node, Content annotationInfoTree) {
writer.addAnnotationTypeSignature(utils.modifiersToString(annotationType, true),
annotationInfoTree);
} | [
"public",
"void",
"buildAnnotationTypeSignature",
"(",
"XMLNode",
"node",
",",
"Content",
"annotationInfoTree",
")",
"{",
"writer",
".",
"addAnnotationTypeSignature",
"(",
"utils",
".",
"modifiersToString",
"(",
"annotationType",
",",
"true",
")",
",",
"annotationInfo... | Build the signature of the current annotation type.
@param node the XML element that specifies which components to document
@param annotationInfoTree the content tree to which the documentation will be added | [
"Build",
"the",
"signature",
"of",
"the",
"current",
"annotation",
"type",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeBuilder.java#L180-L183 |
the-fascinator/plugin-authentication-internal | src/main/java/com/googlecode/fascinator/authentication/internal/InternalAuthentication.java | InternalAuthentication.changePassword | @Override
public void changePassword(String username, String password)
throws AuthenticationException {
String user = file_store.getProperty(username);
if (user == null) {
throw new AuthenticationException("User '" + username
+ "' not found.");
}
// Encrypt the new password
String ePwd = encryptPassword(password);
file_store.put(username, ePwd);
try {
saveUsers();
} catch (IOException e) {
throw new AuthenticationException("Error changing password: ", e);
}
} | java | @Override
public void changePassword(String username, String password)
throws AuthenticationException {
String user = file_store.getProperty(username);
if (user == null) {
throw new AuthenticationException("User '" + username
+ "' not found.");
}
// Encrypt the new password
String ePwd = encryptPassword(password);
file_store.put(username, ePwd);
try {
saveUsers();
} catch (IOException e) {
throw new AuthenticationException("Error changing password: ", e);
}
} | [
"@",
"Override",
"public",
"void",
"changePassword",
"(",
"String",
"username",
",",
"String",
"password",
")",
"throws",
"AuthenticationException",
"{",
"String",
"user",
"=",
"file_store",
".",
"getProperty",
"(",
"username",
")",
";",
"if",
"(",
"user",
"==... | Change a user's password.
@param username The user changing their password.
@param password The new password for the user.
@throws AuthenticationException if there was an error changing the
password. | [
"Change",
"a",
"user",
"s",
"password",
"."
] | train | https://github.com/the-fascinator/plugin-authentication-internal/blob/a2b9a0eda9b43bf20583036a406c83c938be3042/src/main/java/com/googlecode/fascinator/authentication/internal/InternalAuthentication.java#L368-L384 |
sagiegurari/fax4j | src/main/java/org/fax4j/common/ServiceFactory.java | ServiceFactory.createService | public static Service createService(String classNameKey,String defaultClassName,ConfigurationHolder configurationHolder,String propertyPart)
{
//validate input
if(configurationHolder==null)
{
throw new FaxException("Service configuration not provided.");
}
if(classNameKey==null)
{
throw new FaxException("Service class name key not provided.");
}
//get class name
String className=configurationHolder.getConfigurationValue(classNameKey);
if(className==null)
{
className=defaultClassName;
if(className==null)
{
throw new FaxException("Service class name not found in configuration and no default value provided.");
}
}
//get configuration
Map<String,String> configuration=configurationHolder.getConfiguration();
//create service
Service service=(Service)ReflectionHelper.createInstance(className);
//set property part
service.setPropertyPart(propertyPart);
//initialize service
service.initialize(configuration);
return service;
} | java | public static Service createService(String classNameKey,String defaultClassName,ConfigurationHolder configurationHolder,String propertyPart)
{
//validate input
if(configurationHolder==null)
{
throw new FaxException("Service configuration not provided.");
}
if(classNameKey==null)
{
throw new FaxException("Service class name key not provided.");
}
//get class name
String className=configurationHolder.getConfigurationValue(classNameKey);
if(className==null)
{
className=defaultClassName;
if(className==null)
{
throw new FaxException("Service class name not found in configuration and no default value provided.");
}
}
//get configuration
Map<String,String> configuration=configurationHolder.getConfiguration();
//create service
Service service=(Service)ReflectionHelper.createInstance(className);
//set property part
service.setPropertyPart(propertyPart);
//initialize service
service.initialize(configuration);
return service;
} | [
"public",
"static",
"Service",
"createService",
"(",
"String",
"classNameKey",
",",
"String",
"defaultClassName",
",",
"ConfigurationHolder",
"configurationHolder",
",",
"String",
"propertyPart",
")",
"{",
"//validate input",
"if",
"(",
"configurationHolder",
"==",
"nul... | This function creates, initializes and returns new service objects.
@param classNameKey
The configuration key holding the service object class name
@param defaultClassName
The default service object class name if the value was not found in the configuration
@param configurationHolder
The configuration holder used to provide the configuration to the service
@param propertyPart
The service property part
@return The initialized service object | [
"This",
"function",
"creates",
"initializes",
"and",
"returns",
"new",
"service",
"objects",
"."
] | train | https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/common/ServiceFactory.java#L67-L103 |
threerings/nenya | core/src/main/java/com/threerings/util/BrowserUtil.java | BrowserUtil.browseURL | public static void browseURL (URL url, ResultListener<Void> listener, String genagent)
{
String[] cmd;
if (RunAnywhere.isWindows()) {
// TODO: test this on Vinders 98
// cmd = new String[] { "rundll32", "url.dll,FileProtocolHandler",
// url.toString() };
String osName = System.getProperty("os.name");
if (osName.indexOf("9") != -1 || osName.indexOf("Me") != -1) {
cmd = new String[] { "command.com", "/c", "start",
"\"" + url.toString() + "\"" };
} else {
cmd = new String[] { "cmd.exe", "/c", "start", "\"\"",
"\"" + url.toString() + "\"" };
}
} else if (RunAnywhere.isMacOS()) {
cmd = new String[] { "open", url.toString() };
} else { // Linux, Solaris, etc
cmd = new String[] { genagent, url.toString() };
}
// obscure any password information
String logcmd = StringUtil.join(cmd, " ");
logcmd = logcmd.replaceAll("password=[^&]*", "password=XXX");
log.info("Browsing URL [cmd=" + logcmd + "].");
try {
Process process = Runtime.getRuntime().exec(cmd);
BrowserTracker tracker = new BrowserTracker(process, url, listener);
tracker.start();
} catch (Exception e) {
log.warning("Failed to launch browser [url=" + url +
", error=" + e + "].");
listener.requestFailed(e);
}
} | java | public static void browseURL (URL url, ResultListener<Void> listener, String genagent)
{
String[] cmd;
if (RunAnywhere.isWindows()) {
// TODO: test this on Vinders 98
// cmd = new String[] { "rundll32", "url.dll,FileProtocolHandler",
// url.toString() };
String osName = System.getProperty("os.name");
if (osName.indexOf("9") != -1 || osName.indexOf("Me") != -1) {
cmd = new String[] { "command.com", "/c", "start",
"\"" + url.toString() + "\"" };
} else {
cmd = new String[] { "cmd.exe", "/c", "start", "\"\"",
"\"" + url.toString() + "\"" };
}
} else if (RunAnywhere.isMacOS()) {
cmd = new String[] { "open", url.toString() };
} else { // Linux, Solaris, etc
cmd = new String[] { genagent, url.toString() };
}
// obscure any password information
String logcmd = StringUtil.join(cmd, " ");
logcmd = logcmd.replaceAll("password=[^&]*", "password=XXX");
log.info("Browsing URL [cmd=" + logcmd + "].");
try {
Process process = Runtime.getRuntime().exec(cmd);
BrowserTracker tracker = new BrowserTracker(process, url, listener);
tracker.start();
} catch (Exception e) {
log.warning("Failed to launch browser [url=" + url +
", error=" + e + "].");
listener.requestFailed(e);
}
} | [
"public",
"static",
"void",
"browseURL",
"(",
"URL",
"url",
",",
"ResultListener",
"<",
"Void",
">",
"listener",
",",
"String",
"genagent",
")",
"{",
"String",
"[",
"]",
"cmd",
";",
"if",
"(",
"RunAnywhere",
".",
"isWindows",
"(",
")",
")",
"{",
"// TO... | Opens the user's web browser with the specified URL.
@param url the URL to display in an external browser.
@param listener a listener to be notified if we failed to launch the
browser. <em>Note:</em> it will not be notified of success.
@param genagent the path to the browser to execute on non-Windows,
non-MacOS. | [
"Opens",
"the",
"user",
"s",
"web",
"browser",
"with",
"the",
"specified",
"URL",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/util/BrowserUtil.java#L57-L94 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/NeedlessMemberCollectionSynchronization.java | NeedlessMemberCollectionSynchronization.visitClassContext | @Override
public void visitClassContext(ClassContext classContext) {
try {
if ((collectionClass != null) && (mapClass != null)) {
collectionFields = new HashMap<>();
aliases = new HashMap<>();
stack = new OpcodeStack();
JavaClass cls = classContext.getJavaClass();
className = cls.getClassName();
super.visitClassContext(classContext);
for (FieldInfo fi : collectionFields.values()) {
if (fi.isSynchronized()) {
bugReporter.reportBug(new BugInstance(this, BugType.NMCS_NEEDLESS_MEMBER_COLLECTION_SYNCHRONIZATION.name(), NORMAL_PRIORITY)
.addClass(this).addField(fi.getFieldAnnotation()));
}
}
}
} finally {
collectionFields = null;
aliases = null;
stack = null;
}
} | java | @Override
public void visitClassContext(ClassContext classContext) {
try {
if ((collectionClass != null) && (mapClass != null)) {
collectionFields = new HashMap<>();
aliases = new HashMap<>();
stack = new OpcodeStack();
JavaClass cls = classContext.getJavaClass();
className = cls.getClassName();
super.visitClassContext(classContext);
for (FieldInfo fi : collectionFields.values()) {
if (fi.isSynchronized()) {
bugReporter.reportBug(new BugInstance(this, BugType.NMCS_NEEDLESS_MEMBER_COLLECTION_SYNCHRONIZATION.name(), NORMAL_PRIORITY)
.addClass(this).addField(fi.getFieldAnnotation()));
}
}
}
} finally {
collectionFields = null;
aliases = null;
stack = null;
}
} | [
"@",
"Override",
"public",
"void",
"visitClassContext",
"(",
"ClassContext",
"classContext",
")",
"{",
"try",
"{",
"if",
"(",
"(",
"collectionClass",
"!=",
"null",
")",
"&&",
"(",
"mapClass",
"!=",
"null",
")",
")",
"{",
"collectionFields",
"=",
"new",
"Ha... | implements the visitor to clear the collectionFields and stack and to report collections that remain unmodified out of clinit or init
@param classContext
the context object of the currently parsed class | [
"implements",
"the",
"visitor",
"to",
"clear",
"the",
"collectionFields",
"and",
"stack",
"and",
"to",
"report",
"collections",
"that",
"remain",
"unmodified",
"out",
"of",
"clinit",
"or",
"init"
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/NeedlessMemberCollectionSynchronization.java#L106-L128 |
nextreports/nextreports-engine | src/ro/nextreports/engine/util/ReportUtil.java | ReportUtil.saveReport | public static void saveReport(String xml, String path) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path);
fos.write(xml.getBytes("UTF-8"));
fos.flush();
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
ex.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | java | public static void saveReport(String xml, String path) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path);
fos.write(xml.getBytes("UTF-8"));
fos.flush();
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
ex.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | [
"public",
"static",
"void",
"saveReport",
"(",
"String",
"xml",
",",
"String",
"path",
")",
"{",
"FileOutputStream",
"fos",
"=",
"null",
";",
"try",
"{",
"fos",
"=",
"new",
"FileOutputStream",
"(",
"path",
")",
";",
"fos",
".",
"write",
"(",
"xml",
"."... | Write a xml text to a file at specified path
@param xml
xml text
@param path
file path | [
"Write",
"a",
"xml",
"text",
"to",
"a",
"file",
"at",
"specified",
"path"
] | train | https://github.com/nextreports/nextreports-engine/blob/a847575a9298b5fce63b88961190c5b83ddccc44/src/ro/nextreports/engine/util/ReportUtil.java#L238-L256 |
alkacon/opencms-core | src/org/opencms/main/CmsStaticResourceHandler.java | CmsStaticResourceHandler.getStaticResourceContext | public static String getStaticResourceContext(String opencmsContext, String opencmsVersion) {
return opencmsContext + STATIC_RESOURCE_PREFIX + "/v" + opencmsVersion.hashCode() + "v";
} | java | public static String getStaticResourceContext(String opencmsContext, String opencmsVersion) {
return opencmsContext + STATIC_RESOURCE_PREFIX + "/v" + opencmsVersion.hashCode() + "v";
} | [
"public",
"static",
"String",
"getStaticResourceContext",
"(",
"String",
"opencmsContext",
",",
"String",
"opencmsVersion",
")",
"{",
"return",
"opencmsContext",
"+",
"STATIC_RESOURCE_PREFIX",
"+",
"\"/v\"",
"+",
"opencmsVersion",
".",
"hashCode",
"(",
")",
"+",
"\"... | Returns the context for static resources served from the class path, e.g. "/opencms/handleStatic/v5976v".<p>
@param opencmsContext the OpenCms context
@param opencmsVersion the OpenCms version
@return the static resource context | [
"Returns",
"the",
"context",
"for",
"static",
"resources",
"served",
"from",
"the",
"class",
"path",
"e",
".",
"g",
".",
"/",
"opencms",
"/",
"handleStatic",
"/",
"v5976v",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsStaticResourceHandler.java#L85-L88 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/FeaturesImpl.java | FeaturesImpl.updatePhraseListWithServiceResponseAsync | public Observable<ServiceResponse<OperationStatus>> updatePhraseListWithServiceResponseAsync(UUID appId, String versionId, int phraselistId, UpdatePhraseListOptionalParameter updatePhraseListOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
final PhraselistUpdateObject phraselistUpdateObject = updatePhraseListOptionalParameter != null ? updatePhraseListOptionalParameter.phraselistUpdateObject() : null;
return updatePhraseListWithServiceResponseAsync(appId, versionId, phraselistId, phraselistUpdateObject);
} | java | public Observable<ServiceResponse<OperationStatus>> updatePhraseListWithServiceResponseAsync(UUID appId, String versionId, int phraselistId, UpdatePhraseListOptionalParameter updatePhraseListOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
final PhraselistUpdateObject phraselistUpdateObject = updatePhraseListOptionalParameter != null ? updatePhraseListOptionalParameter.phraselistUpdateObject() : null;
return updatePhraseListWithServiceResponseAsync(appId, versionId, phraselistId, phraselistUpdateObject);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"OperationStatus",
">",
">",
"updatePhraseListWithServiceResponseAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"int",
"phraselistId",
",",
"UpdatePhraseListOptionalParameter",
"updatePhraseListOptionalParam... | Updates the phrases, the state and the name of the phraselist feature.
@param appId The application ID.
@param versionId The version ID.
@param phraselistId The ID of the feature to be updated.
@param updatePhraseListOptionalParameter 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 | [
"Updates",
"the",
"phrases",
"the",
"state",
"and",
"the",
"name",
"of",
"the",
"phraselist",
"feature",
"."
] | 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/FeaturesImpl.java#L694-L707 |
fcrepo4/fcrepo4 | fcrepo-kernel-api/src/main/java/org/fcrepo/kernel/api/utils/SubjectMappingUtil.java | SubjectMappingUtil.mapSubject | public static Triple mapSubject(final Triple t, final String resourceUri, final String destinationUri) {
final Node destinationNode = createURI(destinationUri);
return mapSubject(t, resourceUri, destinationNode);
} | java | public static Triple mapSubject(final Triple t, final String resourceUri, final String destinationUri) {
final Node destinationNode = createURI(destinationUri);
return mapSubject(t, resourceUri, destinationNode);
} | [
"public",
"static",
"Triple",
"mapSubject",
"(",
"final",
"Triple",
"t",
",",
"final",
"String",
"resourceUri",
",",
"final",
"String",
"destinationUri",
")",
"{",
"final",
"Node",
"destinationNode",
"=",
"createURI",
"(",
"destinationUri",
")",
";",
"return",
... | Maps the subject of t from resourceUri to destinationUri to produce a new Triple.
If the triple does not have the subject resourceUri, then the triple is unchanged.
@param t triple to be remapped.
@param resourceUri resource subject uri to be remapped.
@param destinationUri subject uri for the resultant triple.
@return triple with subject remapped to destinationUri or the original subject. | [
"Maps",
"the",
"subject",
"of",
"t",
"from",
"resourceUri",
"to",
"destinationUri",
"to",
"produce",
"a",
"new",
"Triple",
".",
"If",
"the",
"triple",
"does",
"not",
"have",
"the",
"subject",
"resourceUri",
"then",
"the",
"triple",
"is",
"unchanged",
"."
] | train | https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-kernel-api/src/main/java/org/fcrepo/kernel/api/utils/SubjectMappingUtil.java#L45-L48 |
landawn/AbacusUtil | src/com/landawn/abacus/util/CharList.java | CharList.reduce | public <E extends Exception> char reduce(final char identity, final Try.CharBinaryOperator<E> accumulator) throws E {
if (isEmpty()) {
return identity;
}
char result = identity;
for (int i = 0; i < size; i++) {
result = accumulator.applyAsChar(result, elementData[i]);
}
return result;
} | java | public <E extends Exception> char reduce(final char identity, final Try.CharBinaryOperator<E> accumulator) throws E {
if (isEmpty()) {
return identity;
}
char result = identity;
for (int i = 0; i < size; i++) {
result = accumulator.applyAsChar(result, elementData[i]);
}
return result;
} | [
"public",
"<",
"E",
"extends",
"Exception",
">",
"char",
"reduce",
"(",
"final",
"char",
"identity",
",",
"final",
"Try",
".",
"CharBinaryOperator",
"<",
"E",
">",
"accumulator",
")",
"throws",
"E",
"{",
"if",
"(",
"isEmpty",
"(",
")",
")",
"{",
"retur... | This is equivalent to:
<pre>
<code>
if (isEmpty()) {
return identity;
}
char result = identity;
for (int i = 0; i < size; i++) {
result = accumulator.applyAsChar(result, elementData[i]);
}
return result;
</code>
</pre>
@param identity
@param accumulator
@return | [
"This",
"is",
"equivalent",
"to",
":",
"<pre",
">",
"<code",
">",
"if",
"(",
"isEmpty",
"()",
")",
"{",
"return",
"identity",
";",
"}"
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/CharList.java#L1152-L1164 |
Azure/azure-sdk-for-java | network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java | NetworkWatchersInner.beginSetFlowLogConfigurationAsync | public Observable<FlowLogInformationInner> beginSetFlowLogConfigurationAsync(String resourceGroupName, String networkWatcherName, FlowLogInformationInner parameters) {
return beginSetFlowLogConfigurationWithServiceResponseAsync(resourceGroupName, networkWatcherName, parameters).map(new Func1<ServiceResponse<FlowLogInformationInner>, FlowLogInformationInner>() {
@Override
public FlowLogInformationInner call(ServiceResponse<FlowLogInformationInner> response) {
return response.body();
}
});
} | java | public Observable<FlowLogInformationInner> beginSetFlowLogConfigurationAsync(String resourceGroupName, String networkWatcherName, FlowLogInformationInner parameters) {
return beginSetFlowLogConfigurationWithServiceResponseAsync(resourceGroupName, networkWatcherName, parameters).map(new Func1<ServiceResponse<FlowLogInformationInner>, FlowLogInformationInner>() {
@Override
public FlowLogInformationInner call(ServiceResponse<FlowLogInformationInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"FlowLogInformationInner",
">",
"beginSetFlowLogConfigurationAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"networkWatcherName",
",",
"FlowLogInformationInner",
"parameters",
")",
"{",
"return",
"beginSetFlowLogConfigurationWithServiceRes... | Configures flow log on a specified resource.
@param resourceGroupName The name of the network watcher resource group.
@param networkWatcherName The name of the network watcher resource.
@param parameters Parameters that define the configuration of flow log.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the FlowLogInformationInner object | [
"Configures",
"flow",
"log",
"on",
"a",
"specified",
"resource",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java#L1904-L1911 |
gallandarakhneorg/afc | core/maths/mathtree/src/main/java/org/arakhne/afc/math/tree/node/NaryTreeNode.java | NaryTreeNode.moveTo | public boolean moveTo(N newParent) {
if (newParent == null) {
return false;
}
return moveTo(newParent, newParent.getChildCount());
} | java | public boolean moveTo(N newParent) {
if (newParent == null) {
return false;
}
return moveTo(newParent, newParent.getChildCount());
} | [
"public",
"boolean",
"moveTo",
"(",
"N",
"newParent",
")",
"{",
"if",
"(",
"newParent",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"return",
"moveTo",
"(",
"newParent",
",",
"newParent",
".",
"getChildCount",
"(",
")",
")",
";",
"}"
] | Move this node in the given new parent node.
<p>This function adds this node at the end of the list
of the children of the new parent node.
<p>This function is preferred to a sequence of calls
to {@link #removeFromParent()} and {@link #setChildAt(int, NaryTreeNode)}
because it fires a limited set of events dedicated to the move
the node.
@param newParent is the new parent for this node.
@return <code>true</code> on success, otherwise <code>false</code>. | [
"Move",
"this",
"node",
"in",
"the",
"given",
"new",
"parent",
"node",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathtree/src/main/java/org/arakhne/afc/math/tree/node/NaryTreeNode.java#L221-L226 |
xiaosunzhu/resource-utils | src/main/java/net/sunyijun/resource/config/Configs.java | Configs.modifyHavePathSelfConfig | public static void modifyHavePathSelfConfig(Map<IConfigKeyWithPath, String> modifyConfig) throws IOException {
Map<String, Map<IConfigKeyWithPath, String>> configPaths =
new HashMap<String, Map<IConfigKeyWithPath, String>>();
for (IConfigKeyWithPath configKeyWithPath : modifyConfig.keySet()) {
String configAbsoluteClassPath = configKeyWithPath.getConfigPath();
Map<IConfigKeyWithPath, String> configKeys = configPaths.get(configAbsoluteClassPath);
if (configKeys == null) {
configKeys = new HashMap<IConfigKeyWithPath, String>();
configPaths.put(configAbsoluteClassPath, configKeys);
}
configKeys.put(configKeyWithPath, modifyConfig.get(configKeyWithPath));
}
for (String configAbsoluteClassPath : configPaths.keySet()) {
OneProperties configs = otherConfigs.get(configAbsoluteClassPath);
if (configs == null) {
return;
}
configs.modifyConfig(configPaths.get(configAbsoluteClassPath));
}
} | java | public static void modifyHavePathSelfConfig(Map<IConfigKeyWithPath, String> modifyConfig) throws IOException {
Map<String, Map<IConfigKeyWithPath, String>> configPaths =
new HashMap<String, Map<IConfigKeyWithPath, String>>();
for (IConfigKeyWithPath configKeyWithPath : modifyConfig.keySet()) {
String configAbsoluteClassPath = configKeyWithPath.getConfigPath();
Map<IConfigKeyWithPath, String> configKeys = configPaths.get(configAbsoluteClassPath);
if (configKeys == null) {
configKeys = new HashMap<IConfigKeyWithPath, String>();
configPaths.put(configAbsoluteClassPath, configKeys);
}
configKeys.put(configKeyWithPath, modifyConfig.get(configKeyWithPath));
}
for (String configAbsoluteClassPath : configPaths.keySet()) {
OneProperties configs = otherConfigs.get(configAbsoluteClassPath);
if (configs == null) {
return;
}
configs.modifyConfig(configPaths.get(configAbsoluteClassPath));
}
} | [
"public",
"static",
"void",
"modifyHavePathSelfConfig",
"(",
"Map",
"<",
"IConfigKeyWithPath",
",",
"String",
">",
"modifyConfig",
")",
"throws",
"IOException",
"{",
"Map",
"<",
"String",
",",
"Map",
"<",
"IConfigKeyWithPath",
",",
"String",
">",
">",
"configPat... | Modify self configs.
@param modifyConfig need update configs. If one value is null, will not update that one.
@throws IOException | [
"Modify",
"self",
"configs",
"."
] | train | https://github.com/xiaosunzhu/resource-utils/blob/4f2bf3f36df10195a978f122ed682ba1eb0462b5/src/main/java/net/sunyijun/resource/config/Configs.java#L549-L568 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/appservice/v2016_03_01/implementation/DiagnosticsInner.java | DiagnosticsInner.getSiteDetectorResponseSlotAsync | public Observable<DetectorResponseInner> getSiteDetectorResponseSlotAsync(String resourceGroupName, String siteName, String detectorName, String slot, DateTime startTime, DateTime endTime, String timeGrain) {
return getSiteDetectorResponseSlotWithServiceResponseAsync(resourceGroupName, siteName, detectorName, slot, startTime, endTime, timeGrain).map(new Func1<ServiceResponse<DetectorResponseInner>, DetectorResponseInner>() {
@Override
public DetectorResponseInner call(ServiceResponse<DetectorResponseInner> response) {
return response.body();
}
});
} | java | public Observable<DetectorResponseInner> getSiteDetectorResponseSlotAsync(String resourceGroupName, String siteName, String detectorName, String slot, DateTime startTime, DateTime endTime, String timeGrain) {
return getSiteDetectorResponseSlotWithServiceResponseAsync(resourceGroupName, siteName, detectorName, slot, startTime, endTime, timeGrain).map(new Func1<ServiceResponse<DetectorResponseInner>, DetectorResponseInner>() {
@Override
public DetectorResponseInner call(ServiceResponse<DetectorResponseInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DetectorResponseInner",
">",
"getSiteDetectorResponseSlotAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"siteName",
",",
"String",
"detectorName",
",",
"String",
"slot",
",",
"DateTime",
"startTime",
",",
"DateTime",
"endTime",
... | Get site detector response.
Get site detector response.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param siteName Site Name
@param detectorName Detector Resource Name
@param slot Slot Name
@param startTime Start Time
@param endTime End Time
@param timeGrain Time Grain
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DetectorResponseInner object | [
"Get",
"site",
"detector",
"response",
".",
"Get",
"site",
"detector",
"response",
"."
] | 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/DiagnosticsInner.java#L2322-L2329 |
aalmiray/Json-lib | src/main/java/net/sf/json/JSONArray.java | JSONArray.toArray | public static Object toArray( JSONArray jsonArray, Class objectClass, Map classMap ) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setRootClass( objectClass );
jsonConfig.setClassMap( classMap );
return toArray( jsonArray, jsonConfig );
} | java | public static Object toArray( JSONArray jsonArray, Class objectClass, Map classMap ) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setRootClass( objectClass );
jsonConfig.setClassMap( classMap );
return toArray( jsonArray, jsonConfig );
} | [
"public",
"static",
"Object",
"toArray",
"(",
"JSONArray",
"jsonArray",
",",
"Class",
"objectClass",
",",
"Map",
"classMap",
")",
"{",
"JsonConfig",
"jsonConfig",
"=",
"new",
"JsonConfig",
"(",
")",
";",
"jsonConfig",
".",
"setRootClass",
"(",
"objectClass",
"... | Creates a java array from a JSONArray.<br>
Any attribute is a JSONObject and matches a key in the classMap, it will
be converted to that target class.<br>
The classMap has the following conventions:
<ul>
<li>Every key must be an String.</li>
<li>Every value must be a Class.</li>
<li>A key may be a regular expression.</li>
</ul> | [
"Creates",
"a",
"java",
"array",
"from",
"a",
"JSONArray",
".",
"<br",
">",
"Any",
"attribute",
"is",
"a",
"JSONObject",
"and",
"matches",
"a",
"key",
"in",
"the",
"classMap",
"it",
"will",
"be",
"converted",
"to",
"that",
"target",
"class",
".",
"<br",
... | train | https://github.com/aalmiray/Json-lib/blob/9e2b3376ee8f511a48aa7ac05f75a7414e02280f/src/main/java/net/sf/json/JSONArray.java#L215-L220 |
radkovo/CSSBox | src/main/java/org/fit/cssbox/layout/HTMLBoxFactory.java | HTMLBoxFactory.createBox | public ElementBox createBox(ElementBox parent, Element e, Viewport viewport, NodeData style)
{
String name = e.getNodeName().toLowerCase();
if (name.equals("object"))
return createSubtreeObject(parent, e, viewport, style);
else if (name.equals("img"))
return createSubtreeImg(parent, e, viewport, style);
else if (name.equals("a") && e.hasAttribute("name")
&& (e.getTextContent() == null || e.getTextContent().trim().length() == 0))
{
//make the named anchors sticky
ElementBox eb = factory.createElementInstance(parent, e, style);
eb.setSticky(true);
return eb;
}
else
return null;
} | java | public ElementBox createBox(ElementBox parent, Element e, Viewport viewport, NodeData style)
{
String name = e.getNodeName().toLowerCase();
if (name.equals("object"))
return createSubtreeObject(parent, e, viewport, style);
else if (name.equals("img"))
return createSubtreeImg(parent, e, viewport, style);
else if (name.equals("a") && e.hasAttribute("name")
&& (e.getTextContent() == null || e.getTextContent().trim().length() == 0))
{
//make the named anchors sticky
ElementBox eb = factory.createElementInstance(parent, e, style);
eb.setSticky(true);
return eb;
}
else
return null;
} | [
"public",
"ElementBox",
"createBox",
"(",
"ElementBox",
"parent",
",",
"Element",
"e",
",",
"Viewport",
"viewport",
",",
"NodeData",
"style",
")",
"{",
"String",
"name",
"=",
"e",
".",
"getNodeName",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"("... | Creates the box according to the HTML element.
@param parent The box in the main box tree to be used as a parent box for the new box.
@param e The element to be processed.
@param viewport The viewport to be used for the new box.
@param style The style of the element.
@return The newly created box or <code>null</code> when the element is not supported
or cannot be created. | [
"Creates",
"the",
"box",
"according",
"to",
"the",
"HTML",
"element",
"."
] | train | https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/layout/HTMLBoxFactory.java#L96-L113 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Math.java | Math.max | public static float max(float a, float b) {
if (a != a)
return a; // a is NaN
if ((a == 0.0f) &&
(b == 0.0f) &&
(Float.floatToRawIntBits(a) == negativeZeroFloatBits)) {
// Raw conversion ok since NaN can't map to -0.0.
return b;
}
return (a >= b) ? a : b;
} | java | public static float max(float a, float b) {
if (a != a)
return a; // a is NaN
if ((a == 0.0f) &&
(b == 0.0f) &&
(Float.floatToRawIntBits(a) == negativeZeroFloatBits)) {
// Raw conversion ok since NaN can't map to -0.0.
return b;
}
return (a >= b) ? a : b;
} | [
"public",
"static",
"float",
"max",
"(",
"float",
"a",
",",
"float",
"b",
")",
"{",
"if",
"(",
"a",
"!=",
"a",
")",
"return",
"a",
";",
"// a is NaN",
"if",
"(",
"(",
"a",
"==",
"0.0f",
")",
"&&",
"(",
"b",
"==",
"0.0f",
")",
"&&",
"(",
"Floa... | Returns the greater of two {@code float} values. That is,
the result is the argument closer to positive infinity. If the
arguments have the same value, the result is that same
value. If either value is NaN, then the result is NaN. Unlike
the numerical comparison operators, this method considers
negative zero to be strictly smaller than positive zero. If one
argument is positive zero and the other negative zero, the
result is positive zero.
@param a an argument.
@param b another argument.
@return the larger of {@code a} and {@code b}. | [
"Returns",
"the",
"greater",
"of",
"two",
"{",
"@code",
"float",
"}",
"values",
".",
"That",
"is",
"the",
"result",
"is",
"the",
"argument",
"closer",
"to",
"positive",
"infinity",
".",
"If",
"the",
"arguments",
"have",
"the",
"same",
"value",
"the",
"re... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Math.java#L1298-L1308 |
lucee/Lucee | core/src/main/java/lucee/commons/management/MemoryInfo.java | MemoryInfo.deepMemoryUsageOf | public static long deepMemoryUsageOf(Instrumentation inst, final Object obj, final int referenceFilter) {
return deepMemoryUsageOf0(inst, new HashSet<Integer>(), obj, referenceFilter);
} | java | public static long deepMemoryUsageOf(Instrumentation inst, final Object obj, final int referenceFilter) {
return deepMemoryUsageOf0(inst, new HashSet<Integer>(), obj, referenceFilter);
} | [
"public",
"static",
"long",
"deepMemoryUsageOf",
"(",
"Instrumentation",
"inst",
",",
"final",
"Object",
"obj",
",",
"final",
"int",
"referenceFilter",
")",
"{",
"return",
"deepMemoryUsageOf0",
"(",
"inst",
",",
"new",
"HashSet",
"<",
"Integer",
">",
"(",
")",... | Returns an estimation, in bytes, of the memory usage of the given object plus (recursively)
objects it references via non-static references. Which references are traversed depends on the
Visibility Filter passed in. The estimate for each individual object is provided by the running
JVM and is likely to be as accurate a measure as can be reasonably made by the running Java
program. It will generally include memory taken up for "housekeeping" of that object.
@param obj The object whose memory usage (and that of objects it references) is to be estimated.
@param referenceFilter specifies which references are to be recursively included in the resulting
count (ALL,PRIVATE_ONLY,NON_PUBLIC,NONE).
@return An estimate, in bytes, of the heap memory taken up by obj and objects it references. | [
"Returns",
"an",
"estimation",
"in",
"bytes",
"of",
"the",
"memory",
"usage",
"of",
"the",
"given",
"object",
"plus",
"(",
"recursively",
")",
"objects",
"it",
"references",
"via",
"non",
"-",
"static",
"references",
".",
"Which",
"references",
"are",
"trave... | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/management/MemoryInfo.java#L86-L88 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/Environment.java | Environment.getHtml | public String getHtml(Formatter formatter, String value) {
String result = null;
if (value != null) {
if ("".equals(value)) {
result = "";
} else {
String formattedResponse = formatter.format(value);
result = "<pre>" + StringEscapeUtils.escapeHtml4(formattedResponse) + "</pre>";
}
}
return result;
} | java | public String getHtml(Formatter formatter, String value) {
String result = null;
if (value != null) {
if ("".equals(value)) {
result = "";
} else {
String formattedResponse = formatter.format(value);
result = "<pre>" + StringEscapeUtils.escapeHtml4(formattedResponse) + "</pre>";
}
}
return result;
} | [
"public",
"String",
"getHtml",
"(",
"Formatter",
"formatter",
",",
"String",
"value",
")",
"{",
"String",
"result",
"=",
"null",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"if",
"(",
"\"\"",
".",
"equals",
"(",
"value",
")",
")",
"{",
"result",... | Formats supplied value for display as pre-formatted text in FitNesse page.
@param formatter formatter to use to generate pre-formatted text.
@param value value to format.
@return HTML formatted version of value. | [
"Formats",
"supplied",
"value",
"for",
"display",
"as",
"pre",
"-",
"formatted",
"text",
"in",
"FitNesse",
"page",
"."
] | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/Environment.java#L526-L537 |
voldemort/voldemort | src/java/voldemort/tools/Repartitioner.java | Repartitioner.greedyShufflePartitions | public static Cluster greedyShufflePartitions(final Cluster nextCandidateCluster,
final int greedyAttempts,
final int greedySwapMaxPartitionsPerNode,
final int greedySwapMaxPartitionsPerZone,
List<Integer> greedySwapZoneIds,
List<StoreDefinition> storeDefs) {
List<Integer> zoneIds = null;
if(greedySwapZoneIds.isEmpty()) {
zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds());
} else {
zoneIds = new ArrayList<Integer>(greedySwapZoneIds);
}
List<Integer> nodeIds = new ArrayList<Integer>();
Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);
double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();
for(int i = 0; i < greedyAttempts; i++) {
// Iterate over zone ids to decide which node ids to include for
// intra-zone swapping.
// In future, if there is a need to support inter-zone swapping,
// then just remove the
// zone specific logic that populates nodeIdSet and add all nodes
// from across all zones.
int zoneIdOffset = i % zoneIds.size();
Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset));
nodeIds = new ArrayList<Integer>(nodeIdSet);
Collections.shuffle(zoneIds, new Random(System.currentTimeMillis()));
Cluster shuffleResults = swapGreedyRandomPartitions(returnCluster,
nodeIds,
greedySwapMaxPartitionsPerNode,
greedySwapMaxPartitionsPerZone,
storeDefs);
double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility();
System.out.println("Swap improved max-min ratio: " + currentUtility + " -> "
+ nextUtility + " (swap attempt " + i + " in zone "
+ zoneIds.get(zoneIdOffset) + ")");
returnCluster = shuffleResults;
currentUtility = nextUtility;
}
return returnCluster;
} | java | public static Cluster greedyShufflePartitions(final Cluster nextCandidateCluster,
final int greedyAttempts,
final int greedySwapMaxPartitionsPerNode,
final int greedySwapMaxPartitionsPerZone,
List<Integer> greedySwapZoneIds,
List<StoreDefinition> storeDefs) {
List<Integer> zoneIds = null;
if(greedySwapZoneIds.isEmpty()) {
zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds());
} else {
zoneIds = new ArrayList<Integer>(greedySwapZoneIds);
}
List<Integer> nodeIds = new ArrayList<Integer>();
Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);
double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();
for(int i = 0; i < greedyAttempts; i++) {
// Iterate over zone ids to decide which node ids to include for
// intra-zone swapping.
// In future, if there is a need to support inter-zone swapping,
// then just remove the
// zone specific logic that populates nodeIdSet and add all nodes
// from across all zones.
int zoneIdOffset = i % zoneIds.size();
Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset));
nodeIds = new ArrayList<Integer>(nodeIdSet);
Collections.shuffle(zoneIds, new Random(System.currentTimeMillis()));
Cluster shuffleResults = swapGreedyRandomPartitions(returnCluster,
nodeIds,
greedySwapMaxPartitionsPerNode,
greedySwapMaxPartitionsPerZone,
storeDefs);
double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility();
System.out.println("Swap improved max-min ratio: " + currentUtility + " -> "
+ nextUtility + " (swap attempt " + i + " in zone "
+ zoneIds.get(zoneIdOffset) + ")");
returnCluster = shuffleResults;
currentUtility = nextUtility;
}
return returnCluster;
} | [
"public",
"static",
"Cluster",
"greedyShufflePartitions",
"(",
"final",
"Cluster",
"nextCandidateCluster",
",",
"final",
"int",
"greedyAttempts",
",",
"final",
"int",
"greedySwapMaxPartitionsPerNode",
",",
"final",
"int",
"greedySwapMaxPartitionsPerZone",
",",
"List",
"<"... | Within a single zone, tries swapping some minimum number of random
partitions per node with some minimum number of random partitions from
other nodes within the zone. Chooses the best swap in each iteration.
Large values of the greedSwapMaxPartitions... arguments make this method
equivalent to comparing every possible swap. This is very expensive.
Normal case should be :
#zones X #nodes/zone X max partitions/node X max partitions/zone
@param nextCandidateCluster cluster object.
@param greedyAttempts See RebalanceCLI.
@param greedySwapMaxPartitionsPerNode See RebalanceCLI.
@param greedySwapMaxPartitionsPerZone See RebalanceCLI.
@param greedySwapZoneIds The set of zoneIds to consider. Each zone is done
independently.
@param storeDefs
@return updated cluster | [
"Within",
"a",
"single",
"zone",
"tries",
"swapping",
"some",
"minimum",
"number",
"of",
"random",
"partitions",
"per",
"node",
"with",
"some",
"minimum",
"number",
"of",
"random",
"partitions",
"from",
"other",
"nodes",
"within",
"the",
"zone",
".",
"Chooses"... | train | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L862-L907 |
OpenLiberty/open-liberty | dev/com.ibm.ws.concurrent.mp.1.0/src/com/ibm/ws/concurrent/mp/ManagedCompletableFuture.java | ManagedCompletableFuture.supplyAsync | @Trivial
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> action) {
throw new UnsupportedOperationException(Tr.formatMessage(tc, "CWWKC1156.not.supported", "ManagedExecutor.supplyAsync"));
} | java | @Trivial
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> action) {
throw new UnsupportedOperationException(Tr.formatMessage(tc, "CWWKC1156.not.supported", "ManagedExecutor.supplyAsync"));
} | [
"@",
"Trivial",
"public",
"static",
"<",
"U",
">",
"CompletableFuture",
"<",
"U",
">",
"supplyAsync",
"(",
"Supplier",
"<",
"U",
">",
"action",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"Tr",
".",
"formatMessage",
"(",
"tc",
",",
"\"C... | Because CompletableFuture.supplyAsync is static, this is not a true override.
It will be difficult for the user to invoke this method because they would need to get the class
of the CompletableFuture implementation and locate the static supplyAsync method on that.
@throws UnsupportedOperationException directing the user to use the ManagedExecutor spec interface instead. | [
"Because",
"CompletableFuture",
".",
"supplyAsync",
"is",
"static",
"this",
"is",
"not",
"a",
"true",
"override",
".",
"It",
"will",
"be",
"difficult",
"for",
"the",
"user",
"to",
"invoke",
"this",
"method",
"because",
"they",
"would",
"need",
"to",
"get",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.concurrent.mp.1.0/src/com/ibm/ws/concurrent/mp/ManagedCompletableFuture.java#L490-L493 |
banq/jdonframework | JdonAccessory/jdon-hibernate3x/src/main/java/com/jdon/model/query/block/BlockStrategy.java | BlockStrategy.getBlock | private Block getBlock(QueryConditonDatakey qcdk) {
Block clientBlock = new Block(qcdk.getStart(), qcdk.getCount());
if (clientBlock.getCount() > this.blockLength)
clientBlock.setCount(this.blockLength);
// create dataBlock get DataBase or cache;
List list = getBlockKeys(qcdk);
Block dataBlock = new Block(qcdk.getBlockStart(), list.size());
int currentStart = clientBlock.getStart() - dataBlock.getStart();
Block currentBlock = new Block(currentStart, clientBlock.getCount());
currentBlock.setList(list);
try {
// because clientBlock's length maybe not be equals to the
// dataBlock's length
// we need the last length:
// 1.the last block length is great than the clientBlock's
// length,the current block's length is the clientBlock's length
// 2.the last block length is less than the clientBlock's
// length,under this condition, there are two choice.
int lastCount = dataBlock.getCount() + dataBlock.getStart() - clientBlock.getStart();
Debug.logVerbose("[JdonFramework] lastCount=" + lastCount, module);
// 2 happened
if (lastCount < clientBlock.getCount()) {
// if 2 , two case:
// 1. if the dataBlock's length is this.blockLength(200),should
// have more dataBlocks.
if (dataBlock.getCount() == this.blockLength) {
// new datablock, we must support new start and new count
// the new start = old datablock's length + old datablock's
// start.
int newStartIndex = dataBlock.getStart() + dataBlock.getCount();
int newCount = clientBlock.getCount() - lastCount;
qcdk.setStart(newStartIndex);
qcdk.setCount(newCount);
Debug.logVerbose("[JdonFramework] newStartIndex=" + newStartIndex + " newCount=" + newCount, module);
Block nextBlock = getBlock(qcdk);
Debug.logVerbose("[JdonFramework] nextBlock.getCount()=" + nextBlock.getCount(), module);
currentBlock.setCount(currentBlock.getCount() + nextBlock.getCount());
} else {
// 2. if not, all datas just be here, clientBlock's count
// value maybe not correct.
currentBlock.setCount(lastCount);
}
}
} catch (Exception e) {
Debug.logError(" getBlock error" + e, module);
}
return currentBlock;
} | java | private Block getBlock(QueryConditonDatakey qcdk) {
Block clientBlock = new Block(qcdk.getStart(), qcdk.getCount());
if (clientBlock.getCount() > this.blockLength)
clientBlock.setCount(this.blockLength);
// create dataBlock get DataBase or cache;
List list = getBlockKeys(qcdk);
Block dataBlock = new Block(qcdk.getBlockStart(), list.size());
int currentStart = clientBlock.getStart() - dataBlock.getStart();
Block currentBlock = new Block(currentStart, clientBlock.getCount());
currentBlock.setList(list);
try {
// because clientBlock's length maybe not be equals to the
// dataBlock's length
// we need the last length:
// 1.the last block length is great than the clientBlock's
// length,the current block's length is the clientBlock's length
// 2.the last block length is less than the clientBlock's
// length,under this condition, there are two choice.
int lastCount = dataBlock.getCount() + dataBlock.getStart() - clientBlock.getStart();
Debug.logVerbose("[JdonFramework] lastCount=" + lastCount, module);
// 2 happened
if (lastCount < clientBlock.getCount()) {
// if 2 , two case:
// 1. if the dataBlock's length is this.blockLength(200),should
// have more dataBlocks.
if (dataBlock.getCount() == this.blockLength) {
// new datablock, we must support new start and new count
// the new start = old datablock's length + old datablock's
// start.
int newStartIndex = dataBlock.getStart() + dataBlock.getCount();
int newCount = clientBlock.getCount() - lastCount;
qcdk.setStart(newStartIndex);
qcdk.setCount(newCount);
Debug.logVerbose("[JdonFramework] newStartIndex=" + newStartIndex + " newCount=" + newCount, module);
Block nextBlock = getBlock(qcdk);
Debug.logVerbose("[JdonFramework] nextBlock.getCount()=" + nextBlock.getCount(), module);
currentBlock.setCount(currentBlock.getCount() + nextBlock.getCount());
} else {
// 2. if not, all datas just be here, clientBlock's count
// value maybe not correct.
currentBlock.setCount(lastCount);
}
}
} catch (Exception e) {
Debug.logError(" getBlock error" + e, module);
}
return currentBlock;
} | [
"private",
"Block",
"getBlock",
"(",
"QueryConditonDatakey",
"qcdk",
")",
"{",
"Block",
"clientBlock",
"=",
"new",
"Block",
"(",
"qcdk",
".",
"getStart",
"(",
")",
",",
"qcdk",
".",
"getCount",
"(",
")",
")",
";",
"if",
"(",
"clientBlock",
".",
"getCount... | get the current block being avaliable to the query condition
@param qcdk
@return | [
"get",
"the",
"current",
"block",
"being",
"avaliable",
"to",
"the",
"query",
"condition"
] | train | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/JdonAccessory/jdon-hibernate3x/src/main/java/com/jdon/model/query/block/BlockStrategy.java#L167-L217 |
openskynetwork/java-adsb | src/main/java/org/opensky/libadsb/PositionDecoder.java | PositionDecoder.decodePosition | public Position decodePosition(double time, SurfacePositionV0Msg msg) {
if (last_pos == null)
return null;
return decodePosition(time, msg, last_pos);
} | java | public Position decodePosition(double time, SurfacePositionV0Msg msg) {
if (last_pos == null)
return null;
return decodePosition(time, msg, last_pos);
} | [
"public",
"Position",
"decodePosition",
"(",
"double",
"time",
",",
"SurfacePositionV0Msg",
"msg",
")",
"{",
"if",
"(",
"last_pos",
"==",
"null",
")",
"return",
"null",
";",
"return",
"decodePosition",
"(",
"time",
",",
"msg",
",",
"last_pos",
")",
";",
"}... | Shortcut for using the last known position for reference; no reasonableness check on distance to receiver
@param time time of applicability/reception of position report (seconds)
@param msg surface position message
@return WGS84 coordinates with latitude and longitude in dec degrees, and altitude in meters. altitude might be null if unavailable
On error, the returned position is null. Check the .isReasonable() flag before using the position. | [
"Shortcut",
"for",
"using",
"the",
"last",
"known",
"position",
"for",
"reference",
";",
"no",
"reasonableness",
"check",
"on",
"distance",
"to",
"receiver"
] | train | https://github.com/openskynetwork/java-adsb/blob/01d497d3e74ad10063ab443ab583e9c8653a8b8d/src/main/java/org/opensky/libadsb/PositionDecoder.java#L447-L452 |
elki-project/elki | elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/hierarchical/SLINKHDBSCANLinearMemory.java | SLINKHDBSCANLinearMemory.step1 | private void step1(DBIDRef id, WritableDBIDDataStore pi, WritableDoubleDataStore lambda) {
// P(n+1) = n+1:
pi.put(id, id);
// L(n+1) = infinity
// Initialized already.
// lambda.putDouble(id, Double.POSITIVE_INFINITY);
} | java | private void step1(DBIDRef id, WritableDBIDDataStore pi, WritableDoubleDataStore lambda) {
// P(n+1) = n+1:
pi.put(id, id);
// L(n+1) = infinity
// Initialized already.
// lambda.putDouble(id, Double.POSITIVE_INFINITY);
} | [
"private",
"void",
"step1",
"(",
"DBIDRef",
"id",
",",
"WritableDBIDDataStore",
"pi",
",",
"WritableDoubleDataStore",
"lambda",
")",
"{",
"// P(n+1) = n+1:",
"pi",
".",
"put",
"(",
"id",
",",
"id",
")",
";",
"// L(n+1) = infinity",
"// Initialized already.",
"// l... | First step: Initialize P(id) = id, L(id) = infinity.
@param id the id of the object to be inserted into the pointer
representation
@param pi Pi data store
@param lambda Lambda data store | [
"First",
"step",
":",
"Initialize",
"P",
"(",
"id",
")",
"=",
"id",
"L",
"(",
"id",
")",
"=",
"infinity",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/hierarchical/SLINKHDBSCANLinearMemory.java#L138-L144 |
salesforce/Argus | ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AuthResourcesV2.java | AuthResourcesV2.login | @POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Description("Authenticates a user and returns access and refresh tokens.")
@Path("/login")
public Response login(@Context HttpServletRequest req, final CredentialsDto creds) {
try {
PrincipalUser user = authService.getUser(creds.getUsername(), creds.getPassword());
if (user != null) {
JWTUtils.Tokens tokens = JWTUtils.generateTokens(user.getUserName());
req.setAttribute(AuthFilter.USER_ATTRIBUTE_NAME, user.getUserName());
return Response.ok(tokens).build();
} else {
throw new WebApplicationException("User does not exist. Please provide valid credentials.", Response.Status.UNAUTHORIZED);
}
} catch (Exception ex) {
throw new WebApplicationException("Exception: " + ex.getMessage(), Response.Status.UNAUTHORIZED);
}
} | java | @POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Description("Authenticates a user and returns access and refresh tokens.")
@Path("/login")
public Response login(@Context HttpServletRequest req, final CredentialsDto creds) {
try {
PrincipalUser user = authService.getUser(creds.getUsername(), creds.getPassword());
if (user != null) {
JWTUtils.Tokens tokens = JWTUtils.generateTokens(user.getUserName());
req.setAttribute(AuthFilter.USER_ATTRIBUTE_NAME, user.getUserName());
return Response.ok(tokens).build();
} else {
throw new WebApplicationException("User does not exist. Please provide valid credentials.", Response.Status.UNAUTHORIZED);
}
} catch (Exception ex) {
throw new WebApplicationException("Exception: " + ex.getMessage(), Response.Status.UNAUTHORIZED);
}
} | [
"@",
"POST",
"@",
"Produces",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Consumes",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Description",
"(",
"\"Authenticates a user and returns access and refresh tokens.\"",
")",
"@",
"Path",
"(",
"\"/login\... | Authenticates a user and return JsonWebTokens (AccessToken and RefreshToken).
@param req The HTTP request.
@param creds The credentials with which to authenticate.
@return The tokens (access and refresh) or Exception if authentication fails.
@throws WebApplicationException If the user is not authenticated. | [
"Authenticates",
"a",
"user",
"and",
"return",
"JsonWebTokens",
"(",
"AccessToken",
"and",
"RefreshToken",
")",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AuthResourcesV2.java#L80-L99 |
datasift/datasift-java | src/main/java/com/datasift/client/managedsource/sources/FacebookPage.java | FacebookPage.addPage | public FacebookPage addPage(String id, String url, String title) {
ResourceParams parameterSet = newResourceParams();
parameterSet.set("id", id);
parameterSet.set("url", url);
parameterSet.set("title", title);
return this;
} | java | public FacebookPage addPage(String id, String url, String title) {
ResourceParams parameterSet = newResourceParams();
parameterSet.set("id", id);
parameterSet.set("url", url);
parameterSet.set("title", title);
return this;
} | [
"public",
"FacebookPage",
"addPage",
"(",
"String",
"id",
",",
"String",
"url",
",",
"String",
"title",
")",
"{",
"ResourceParams",
"parameterSet",
"=",
"newResourceParams",
"(",
")",
";",
"parameterSet",
".",
"set",
"(",
"\"id\"",
",",
"id",
")",
";",
"pa... | /*
Adds information about a single facebook page
@param id the id of the facebook page
@param url the facebook page's URL
@param title the page's title
@return this | [
"/",
"*",
"Adds",
"information",
"about",
"a",
"single",
"facebook",
"page"
] | train | https://github.com/datasift/datasift-java/blob/09de124f2a1a507ff6181e59875c6f325290850e/src/main/java/com/datasift/client/managedsource/sources/FacebookPage.java#L71-L77 |
ontop/ontop | mapping/sql/core/src/main/java/it/unibz/inf/ontop/spec/mapping/parser/impl/RAExpression.java | RAExpression.joinUsing | public static RAExpression joinUsing(RAExpression re1, RAExpression re2,
ImmutableSet<QuotedID> using, TermFactory termFactory) throws IllegalJoinException {
RAExpressionAttributes attributes =
RAExpressionAttributes.joinUsing(re1.attributes, re2.attributes, using);
return new RAExpression(union(re1.dataAtoms, re2.dataAtoms),
union(re1.filterAtoms, re2.filterAtoms,
getJoinOnFilter(re1.attributes, re2.attributes, using, termFactory)),
attributes, termFactory);
} | java | public static RAExpression joinUsing(RAExpression re1, RAExpression re2,
ImmutableSet<QuotedID> using, TermFactory termFactory) throws IllegalJoinException {
RAExpressionAttributes attributes =
RAExpressionAttributes.joinUsing(re1.attributes, re2.attributes, using);
return new RAExpression(union(re1.dataAtoms, re2.dataAtoms),
union(re1.filterAtoms, re2.filterAtoms,
getJoinOnFilter(re1.attributes, re2.attributes, using, termFactory)),
attributes, termFactory);
} | [
"public",
"static",
"RAExpression",
"joinUsing",
"(",
"RAExpression",
"re1",
",",
"RAExpression",
"re2",
",",
"ImmutableSet",
"<",
"QuotedID",
">",
"using",
",",
"TermFactory",
"termFactory",
")",
"throws",
"IllegalJoinException",
"{",
"RAExpressionAttributes",
"attri... | JOIN USING
@param re1 a {@link RAExpression}
@param re2 a {@link RAExpression}
@param using a {@link ImmutableSet}<{@link QuotedID}>
@return a {@link RAExpression}
@throws IllegalJoinException if the same alias occurs in both arguments
or one of the `using' attributes is ambiguous or absent | [
"JOIN",
"USING"
] | train | https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/mapping/sql/core/src/main/java/it/unibz/inf/ontop/spec/mapping/parser/impl/RAExpression.java#L130-L140 |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/JsonRpcBasicServer.java | JsonRpcBasicServer.findBestMethodUsingParamNames | private AMethodWithItsArgs findBestMethodUsingParamNames(Set<Method> methods, Set<String> paramNames, ObjectNode paramNodes) {
ParameterCount max = new ParameterCount();
for (Method method : methods) {
List<Class<?>> parameterTypes = getParameterTypes(method);
int typeNameCountDiff = parameterTypes.size() - paramNames.size();
if (!acceptParamCount(typeNameCountDiff)) {
continue;
}
ParameterCount parStat = new ParameterCount(paramNames, paramNodes, parameterTypes, method);
if (!acceptParamCount(parStat.nameCount - paramNames.size())) {
continue;
}
if (hasMoreMatches(max.nameCount, parStat.nameCount) || parStat.nameCount == max.nameCount && hasMoreMatches(max.typeCount, parStat.typeCount)) {
max = parStat;
}
}
if (max.method == null) {
return null;
}
return new AMethodWithItsArgs(max.method, paramNames, max.allNames, paramNodes);
} | java | private AMethodWithItsArgs findBestMethodUsingParamNames(Set<Method> methods, Set<String> paramNames, ObjectNode paramNodes) {
ParameterCount max = new ParameterCount();
for (Method method : methods) {
List<Class<?>> parameterTypes = getParameterTypes(method);
int typeNameCountDiff = parameterTypes.size() - paramNames.size();
if (!acceptParamCount(typeNameCountDiff)) {
continue;
}
ParameterCount parStat = new ParameterCount(paramNames, paramNodes, parameterTypes, method);
if (!acceptParamCount(parStat.nameCount - paramNames.size())) {
continue;
}
if (hasMoreMatches(max.nameCount, parStat.nameCount) || parStat.nameCount == max.nameCount && hasMoreMatches(max.typeCount, parStat.typeCount)) {
max = parStat;
}
}
if (max.method == null) {
return null;
}
return new AMethodWithItsArgs(max.method, paramNames, max.allNames, paramNodes);
} | [
"private",
"AMethodWithItsArgs",
"findBestMethodUsingParamNames",
"(",
"Set",
"<",
"Method",
">",
"methods",
",",
"Set",
"<",
"String",
">",
"paramNames",
",",
"ObjectNode",
"paramNodes",
")",
"{",
"ParameterCount",
"max",
"=",
"new",
"ParameterCount",
"(",
")",
... | Finds the {@link Method} from the supplied {@link Set} that best matches the rest of the arguments supplied and
returns it as a {@link AMethodWithItsArgs} class.
@param methods the {@link Method}s
@param paramNames the parameter allNames
@param paramNodes the parameters for matching types
@return the {@link AMethodWithItsArgs} | [
"Finds",
"the",
"{",
"@link",
"Method",
"}",
"from",
"the",
"supplied",
"{",
"@link",
"Set",
"}",
"that",
"best",
"matches",
"the",
"rest",
"of",
"the",
"arguments",
"supplied",
"and",
"returns",
"it",
"as",
"a",
"{",
"@link",
"AMethodWithItsArgs",
"}",
... | train | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/JsonRpcBasicServer.java#L768-L792 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/File.java | File.createTempFile | public static File createTempFile(String prefix, String suffix) throws IOException {
return createTempFile(prefix, suffix, null);
} | java | public static File createTempFile(String prefix, String suffix) throws IOException {
return createTempFile(prefix, suffix, null);
} | [
"public",
"static",
"File",
"createTempFile",
"(",
"String",
"prefix",
",",
"String",
"suffix",
")",
"throws",
"IOException",
"{",
"return",
"createTempFile",
"(",
"prefix",
",",
"suffix",
",",
"null",
")",
";",
"}"
] | Creates an empty temporary file using the given prefix and suffix as part
of the file name. If {@code suffix} is null, {@code .tmp} is used. This
method is a convenience method that calls
{@link #createTempFile(String, String, File)} with the third argument
being {@code null}.
@param prefix
the prefix to the temp file name.
@param suffix
the suffix to the temp file name.
@return the temporary file.
@throws IOException
if an error occurs when writing the file. | [
"Creates",
"an",
"empty",
"temporary",
"file",
"using",
"the",
"given",
"prefix",
"and",
"suffix",
"as",
"part",
"of",
"the",
"file",
"name",
".",
"If",
"{",
"@code",
"suffix",
"}",
"is",
"null",
"{",
"@code",
".",
"tmp",
"}",
"is",
"used",
".",
"Thi... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/File.java#L1061-L1063 |
Samsung/GearVRf | GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/Widget.java | Widget.rotate | public void rotate(float w, float x, float y, float z) {
getTransform().rotate(w, x, y, z);
if (mTransformCache.rotate(w, x, y, z)) {
onTransformChanged();
}
} | java | public void rotate(float w, float x, float y, float z) {
getTransform().rotate(w, x, y, z);
if (mTransformCache.rotate(w, x, y, z)) {
onTransformChanged();
}
} | [
"public",
"void",
"rotate",
"(",
"float",
"w",
",",
"float",
"x",
",",
"float",
"y",
",",
"float",
"z",
")",
"{",
"getTransform",
"(",
")",
".",
"rotate",
"(",
"w",
",",
"x",
",",
"y",
",",
"z",
")",
";",
"if",
"(",
"mTransformCache",
".",
"rot... | Modify the tranform's current rotation in quaternion terms.
@param w
'W' component of the quaternion.
@param x
'X' component of the quaternion.
@param y
'Y' component of the quaternion.
@param z
'Z' component of the quaternion. | [
"Modify",
"the",
"tranform",
"s",
"current",
"rotation",
"in",
"quaternion",
"terms",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/Widget.java#L1592-L1597 |
OpenFeign/feign | core/src/main/java/feign/template/Template.java | Template.parseFragment | private void parseFragment(String fragment, boolean query) {
ChunkTokenizer tokenizer = new ChunkTokenizer(fragment);
while (tokenizer.hasNext()) {
/* check to see if we have an expression or a literal */
String chunk = tokenizer.next();
if (chunk.startsWith("{")) {
/* it's an expression, defer encoding until resolution */
FragmentType type = (query) ? FragmentType.QUERY : FragmentType.PATH_SEGMENT;
Expression expression = Expressions.create(chunk, type);
if (expression == null) {
this.templateChunks.add(Literal.create(encode(chunk, query)));
} else {
this.templateChunks.add(expression);
}
} else {
/* it's a literal, pct-encode it */
this.templateChunks.add(Literal.create(encode(chunk, query)));
}
}
} | java | private void parseFragment(String fragment, boolean query) {
ChunkTokenizer tokenizer = new ChunkTokenizer(fragment);
while (tokenizer.hasNext()) {
/* check to see if we have an expression or a literal */
String chunk = tokenizer.next();
if (chunk.startsWith("{")) {
/* it's an expression, defer encoding until resolution */
FragmentType type = (query) ? FragmentType.QUERY : FragmentType.PATH_SEGMENT;
Expression expression = Expressions.create(chunk, type);
if (expression == null) {
this.templateChunks.add(Literal.create(encode(chunk, query)));
} else {
this.templateChunks.add(expression);
}
} else {
/* it's a literal, pct-encode it */
this.templateChunks.add(Literal.create(encode(chunk, query)));
}
}
} | [
"private",
"void",
"parseFragment",
"(",
"String",
"fragment",
",",
"boolean",
"query",
")",
"{",
"ChunkTokenizer",
"tokenizer",
"=",
"new",
"ChunkTokenizer",
"(",
"fragment",
")",
";",
"while",
"(",
"tokenizer",
".",
"hasNext",
"(",
")",
")",
"{",
"/* check... | Parse a template fragment.
@param fragment to parse
@param query if the fragment is part of a query string. | [
"Parse",
"a",
"template",
"fragment",
"."
] | train | https://github.com/OpenFeign/feign/blob/318fb0e955b8cfcf64f70d6aeea0ba5795f8a7eb/core/src/main/java/feign/template/Template.java#L213-L235 |
datacleaner/DataCleaner | engine/core/src/main/java/org/datacleaner/job/AnalysisJobImmutabilizer.java | AnalysisJobImmutabilizer.getOrCreateTransformerJob | public TransformerJob getOrCreateTransformerJob(final boolean validate, final TransformerComponentBuilder<?> tjb) {
TransformerJob componentJob = (TransformerJob) _componentJobs.get(tjb);
if (componentJob == null) {
try {
componentJob = tjb.toTransformerJob(validate, this);
_componentJobs.put(tjb, componentJob);
} catch (final IllegalStateException e) {
throw new IllegalStateException(
"Could not create transformer job from builder: " + tjb + ", (" + e.getMessage() + ")", e);
}
}
return componentJob;
} | java | public TransformerJob getOrCreateTransformerJob(final boolean validate, final TransformerComponentBuilder<?> tjb) {
TransformerJob componentJob = (TransformerJob) _componentJobs.get(tjb);
if (componentJob == null) {
try {
componentJob = tjb.toTransformerJob(validate, this);
_componentJobs.put(tjb, componentJob);
} catch (final IllegalStateException e) {
throw new IllegalStateException(
"Could not create transformer job from builder: " + tjb + ", (" + e.getMessage() + ")", e);
}
}
return componentJob;
} | [
"public",
"TransformerJob",
"getOrCreateTransformerJob",
"(",
"final",
"boolean",
"validate",
",",
"final",
"TransformerComponentBuilder",
"<",
"?",
">",
"tjb",
")",
"{",
"TransformerJob",
"componentJob",
"=",
"(",
"TransformerJob",
")",
"_componentJobs",
".",
"get",
... | Gets or creates a {@link TransformerJob} for a particular
{@link TransformerComponentBuilder}. Since {@link MultiStreamComponent}s
are subtypes of {@link Transformer} it is necesary to have this caching
mechanism in place in order to allow diamond-shaped component graphs
where multiple streams include the same component.
@param validate
@param tjb
@return | [
"Gets",
"or",
"creates",
"a",
"{",
"@link",
"TransformerJob",
"}",
"for",
"a",
"particular",
"{",
"@link",
"TransformerComponentBuilder",
"}",
".",
"Since",
"{",
"@link",
"MultiStreamComponent",
"}",
"s",
"are",
"subtypes",
"of",
"{",
"@link",
"Transformer",
"... | train | https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/core/src/main/java/org/datacleaner/job/AnalysisJobImmutabilizer.java#L123-L135 |
web3j/web3j | crypto/src/main/java/org/web3j/crypto/Sign.java | Sign.recoverFromSignature | public static BigInteger recoverFromSignature(int recId, ECDSASignature sig, byte[] message) {
verifyPrecondition(recId >= 0, "recId must be positive");
verifyPrecondition(sig.r.signum() >= 0, "r must be positive");
verifyPrecondition(sig.s.signum() >= 0, "s must be positive");
verifyPrecondition(message != null, "message cannot be null");
// 1.0 For j from 0 to h (h == recId here and the loop is outside this function)
// 1.1 Let x = r + jn
BigInteger n = CURVE.getN(); // Curve order.
BigInteger i = BigInteger.valueOf((long) recId / 2);
BigInteger x = sig.r.add(i.multiply(n));
// 1.2. Convert the integer x to an octet string X of length mlen using the conversion
// routine specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen = ⌈m/8⌉.
// 1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve point R
// using the conversion routine specified in Section 2.3.4. If this conversion
// routine outputs "invalid", then do another iteration of Step 1.
//
// More concisely, what these points mean is to use X as a compressed public key.
BigInteger prime = SecP256K1Curve.q;
if (x.compareTo(prime) >= 0) {
// Cannot have point co-ordinates larger than this as everything takes place modulo Q.
return null;
}
// Compressed keys require you to know an extra bit of data about the y-coord as there are
// two possibilities. So it's encoded in the recId.
ECPoint R = decompressKey(x, (recId & 1) == 1);
// 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers
// responsibility).
if (!R.multiply(n).isInfinity()) {
return null;
}
// 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification.
BigInteger e = new BigInteger(1, message);
// 1.6. For k from 1 to 2 do the following. (loop is outside this function via
// iterating recId)
// 1.6.1. Compute a candidate public key as:
// Q = mi(r) * (sR - eG)
//
// Where mi(x) is the modular multiplicative inverse. We transform this into the following:
// Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
// Where -e is the modular additive inverse of e, that is z such that z + e = 0 (mod n).
// In the above equation ** is point multiplication and + is point addition (the EC group
// operator).
//
// We can find the additive inverse by subtracting e from zero then taking the mod. For
// example the additive inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and
// -3 mod 11 = 8.
BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n);
BigInteger rInv = sig.r.modInverse(n);
BigInteger srInv = rInv.multiply(sig.s).mod(n);
BigInteger eInvrInv = rInv.multiply(eInv).mod(n);
ECPoint q = ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv);
byte[] qBytes = q.getEncoded(false);
// We remove the prefix
return new BigInteger(1, Arrays.copyOfRange(qBytes, 1, qBytes.length));
} | java | public static BigInteger recoverFromSignature(int recId, ECDSASignature sig, byte[] message) {
verifyPrecondition(recId >= 0, "recId must be positive");
verifyPrecondition(sig.r.signum() >= 0, "r must be positive");
verifyPrecondition(sig.s.signum() >= 0, "s must be positive");
verifyPrecondition(message != null, "message cannot be null");
// 1.0 For j from 0 to h (h == recId here and the loop is outside this function)
// 1.1 Let x = r + jn
BigInteger n = CURVE.getN(); // Curve order.
BigInteger i = BigInteger.valueOf((long) recId / 2);
BigInteger x = sig.r.add(i.multiply(n));
// 1.2. Convert the integer x to an octet string X of length mlen using the conversion
// routine specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen = ⌈m/8⌉.
// 1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve point R
// using the conversion routine specified in Section 2.3.4. If this conversion
// routine outputs "invalid", then do another iteration of Step 1.
//
// More concisely, what these points mean is to use X as a compressed public key.
BigInteger prime = SecP256K1Curve.q;
if (x.compareTo(prime) >= 0) {
// Cannot have point co-ordinates larger than this as everything takes place modulo Q.
return null;
}
// Compressed keys require you to know an extra bit of data about the y-coord as there are
// two possibilities. So it's encoded in the recId.
ECPoint R = decompressKey(x, (recId & 1) == 1);
// 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers
// responsibility).
if (!R.multiply(n).isInfinity()) {
return null;
}
// 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification.
BigInteger e = new BigInteger(1, message);
// 1.6. For k from 1 to 2 do the following. (loop is outside this function via
// iterating recId)
// 1.6.1. Compute a candidate public key as:
// Q = mi(r) * (sR - eG)
//
// Where mi(x) is the modular multiplicative inverse. We transform this into the following:
// Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
// Where -e is the modular additive inverse of e, that is z such that z + e = 0 (mod n).
// In the above equation ** is point multiplication and + is point addition (the EC group
// operator).
//
// We can find the additive inverse by subtracting e from zero then taking the mod. For
// example the additive inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and
// -3 mod 11 = 8.
BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n);
BigInteger rInv = sig.r.modInverse(n);
BigInteger srInv = rInv.multiply(sig.s).mod(n);
BigInteger eInvrInv = rInv.multiply(eInv).mod(n);
ECPoint q = ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv);
byte[] qBytes = q.getEncoded(false);
// We remove the prefix
return new BigInteger(1, Arrays.copyOfRange(qBytes, 1, qBytes.length));
} | [
"public",
"static",
"BigInteger",
"recoverFromSignature",
"(",
"int",
"recId",
",",
"ECDSASignature",
"sig",
",",
"byte",
"[",
"]",
"message",
")",
"{",
"verifyPrecondition",
"(",
"recId",
">=",
"0",
",",
"\"recId must be positive\"",
")",
";",
"verifyPrecondition... | <p>Given the components of a signature and a selector value, recover and return the public
key that generated the signature according to the algorithm in SEC1v2 section 4.1.6.</p>
<p>The recId is an index from 0 to 3 which indicates which of the 4 possible keys is the
correct one. Because the key recovery operation yields multiple potential keys, the correct
key must either be stored alongside the
signature, or you must be willing to try each recId in turn until you find one that outputs
the key you are expecting.</p>
<p>If this method returns null it means recovery was not possible and recId should be
iterated.</p>
<p>Given the above two points, a correct usage of this method is inside a for loop from
0 to 3, and if the output is null OR a key that is not the one you expect, you try again
with the next recId.</p>
@param recId Which possible key to recover.
@param sig the R and S components of the signature, wrapped.
@param message Hash of the data that was signed.
@return An ECKey containing only the public part, or null if recovery wasn't possible. | [
"<p",
">",
"Given",
"the",
"components",
"of",
"a",
"signature",
"and",
"a",
"selector",
"value",
"recover",
"and",
"return",
"the",
"public",
"key",
"that",
"generated",
"the",
"signature",
"according",
"to",
"the",
"algorithm",
"in",
"SEC1v2",
"section",
"... | train | https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/crypto/src/main/java/org/web3j/crypto/Sign.java#L114-L170 |
javabeanz/owasp-security-logging | owasp-security-logging-common/src/main/java/org/owasp/security/logging/util/SecurityUtil.java | SecurityUtil.bindSystemStreamsToSLF4J | public static void bindSystemStreamsToSLF4J(Logger sysOutLogger, Logger sysErrLogger) {
SecurityUtil.sysOutLogger = sysOutLogger;
SecurityUtil.sysErrLogger = sysErrLogger;
bindSystemStreamsToSLF4J();
} | java | public static void bindSystemStreamsToSLF4J(Logger sysOutLogger, Logger sysErrLogger) {
SecurityUtil.sysOutLogger = sysOutLogger;
SecurityUtil.sysErrLogger = sysErrLogger;
bindSystemStreamsToSLF4J();
} | [
"public",
"static",
"void",
"bindSystemStreamsToSLF4J",
"(",
"Logger",
"sysOutLogger",
",",
"Logger",
"sysErrLogger",
")",
"{",
"SecurityUtil",
".",
"sysOutLogger",
"=",
"sysOutLogger",
";",
"SecurityUtil",
".",
"sysErrLogger",
"=",
"sysErrLogger",
";",
"bindSystemStr... | Redirect <code>System.out</code> and <code>System.err</code> streams to the given SLF4J loggers.
This is a benefit if you have a legacy console logger application. Does not provide
benefit of a full implementation. For example, no hierarchical or logger inheritence
support but there are some ancilarity benefits like, 1) capturing messages that would
otherwise be lost, 2) redirecting console messages to centralized log services, 3)
formatting console messages in other types of output (e.g., HTML).
@param sysOutLogger
@param sysErrLogger | [
"Redirect",
"<code",
">",
"System",
".",
"out<",
"/",
"code",
">",
"and",
"<code",
">",
"System",
".",
"err<",
"/",
"code",
">",
"streams",
"to",
"the",
"given",
"SLF4J",
"loggers",
".",
"This",
"is",
"a",
"benefit",
"if",
"you",
"have",
"a",
"legacy... | train | https://github.com/javabeanz/owasp-security-logging/blob/060dcb1ab5f62aaea274597418ce41c8433a6c10/owasp-security-logging-common/src/main/java/org/owasp/security/logging/util/SecurityUtil.java#L53-L57 |
apptik/jus | jus-java/src/main/java/io/apptik/comm/jus/http/DateUtils.java | DateUtils.formatDate | public static String formatDate(Date date, String pattern) {
if (date == null) throw new IllegalArgumentException("date is null");
if (pattern == null) throw new IllegalArgumentException("pattern is null");
SimpleDateFormat formatter = DateFormatHolder.formatFor(pattern);
return formatter.format(date);
} | java | public static String formatDate(Date date, String pattern) {
if (date == null) throw new IllegalArgumentException("date is null");
if (pattern == null) throw new IllegalArgumentException("pattern is null");
SimpleDateFormat formatter = DateFormatHolder.formatFor(pattern);
return formatter.format(date);
} | [
"public",
"static",
"String",
"formatDate",
"(",
"Date",
"date",
",",
"String",
"pattern",
")",
"{",
"if",
"(",
"date",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"date is null\"",
")",
";",
"if",
"(",
"pattern",
"==",
"null",
")... | Formats the given date according to the specified pattern. The pattern
must conform to that used by the {@link SimpleDateFormat simple date
format} class.
@param date The date to format.
@param pattern The pattern to use for formatting the date.
@return A formatted date string.
@throws IllegalArgumentException If the given date pattern is invalid.
@see SimpleDateFormat | [
"Formats",
"the",
"given",
"date",
"according",
"to",
"the",
"specified",
"pattern",
".",
"The",
"pattern",
"must",
"conform",
"to",
"that",
"used",
"by",
"the",
"{",
"@link",
"SimpleDateFormat",
"simple",
"date",
"format",
"}",
"class",
"."
] | train | https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/jus-java/src/main/java/io/apptik/comm/jus/http/DateUtils.java#L214-L220 |
jaxio/celerio | celerio-engine/src/main/java/com/jaxio/celerio/factory/RelationCollisionUtil.java | RelationCollisionUtil.getOneToManyNamer | public Namer getOneToManyNamer(ColumnConfig fromAttributeColumnConfig, Namer fromEntityNamer) {
// configuration
Namer result = getOneToManyNamerFromConf(fromAttributeColumnConfig.getOneToManyConfig(), fromEntityNamer);
// convention
if (result == null) {
result = fromEntityNamer;
}
return result;
} | java | public Namer getOneToManyNamer(ColumnConfig fromAttributeColumnConfig, Namer fromEntityNamer) {
// configuration
Namer result = getOneToManyNamerFromConf(fromAttributeColumnConfig.getOneToManyConfig(), fromEntityNamer);
// convention
if (result == null) {
result = fromEntityNamer;
}
return result;
} | [
"public",
"Namer",
"getOneToManyNamer",
"(",
"ColumnConfig",
"fromAttributeColumnConfig",
",",
"Namer",
"fromEntityNamer",
")",
"{",
"// configuration",
"Namer",
"result",
"=",
"getOneToManyNamerFromConf",
"(",
"fromAttributeColumnConfig",
".",
"getOneToManyConfig",
"(",
")... | Compute the appropriate namer for the Java field marked by @OneToMany
@param fromAttributeColumnConfig the column that is the foreign key
@param fromEntityNamer the default namer for the entity contained in the collection. | [
"Compute",
"the",
"appropriate",
"namer",
"for",
"the",
"Java",
"field",
"marked",
"by",
"@OneToMany"
] | train | https://github.com/jaxio/celerio/blob/fbfacb639e286f9f3f3a18986f74ea275bebd887/celerio-engine/src/main/java/com/jaxio/celerio/factory/RelationCollisionUtil.java#L74-L84 |
joniles/mpxj | src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java | MSPDIReader.readResourceBaselines | private void readResourceBaselines(Project.Resources.Resource xmlResource, Resource mpxjResource)
{
for (Project.Resources.Resource.Baseline baseline : xmlResource.getBaseline())
{
int number = NumberHelper.getInt(baseline.getNumber());
Double cost = DatatypeConverter.parseCurrency(baseline.getCost());
Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());
if (number == 0)
{
mpxjResource.setBaselineCost(cost);
mpxjResource.setBaselineWork(work);
}
else
{
mpxjResource.setBaselineCost(number, cost);
mpxjResource.setBaselineWork(number, work);
}
}
} | java | private void readResourceBaselines(Project.Resources.Resource xmlResource, Resource mpxjResource)
{
for (Project.Resources.Resource.Baseline baseline : xmlResource.getBaseline())
{
int number = NumberHelper.getInt(baseline.getNumber());
Double cost = DatatypeConverter.parseCurrency(baseline.getCost());
Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());
if (number == 0)
{
mpxjResource.setBaselineCost(cost);
mpxjResource.setBaselineWork(work);
}
else
{
mpxjResource.setBaselineCost(number, cost);
mpxjResource.setBaselineWork(number, work);
}
}
} | [
"private",
"void",
"readResourceBaselines",
"(",
"Project",
".",
"Resources",
".",
"Resource",
"xmlResource",
",",
"Resource",
"mpxjResource",
")",
"{",
"for",
"(",
"Project",
".",
"Resources",
".",
"Resource",
".",
"Baseline",
"baseline",
":",
"xmlResource",
".... | Reads baseline values for the current resource.
@param xmlResource MSPDI resource instance
@param mpxjResource MPXJ resource instance | [
"Reads",
"baseline",
"values",
"for",
"the",
"current",
"resource",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java#L978-L998 |
cloudinary/cloudinary_java | cloudinary-http43/src/main/java/com/cloudinary/http43/ApiStrategy.java | ApiStrategy.prepareRequest | private HttpUriRequest prepareRequest(HttpMethod method, String apiUrl, Map<String, ?> params, Map options) throws URISyntaxException, UnsupportedEncodingException {
URI apiUri;
HttpRequestBase request;
String contentType = ObjectUtils.asString(options.get("content_type"), "urlencoded");
URIBuilder apiUrlBuilder = new URIBuilder(apiUrl);
HashMap<String,Object> unboxedParams = new HashMap<String,Object>(params);
if (method == HttpMethod.GET) {
apiUrlBuilder.setParameters(prepareParams(params));
apiUri = apiUrlBuilder.build();
request = new HttpGet(apiUri);
} else {
apiUri = apiUrlBuilder.build();
switch (method) {
case PUT:
request = new HttpPut(apiUri);
break;
case DELETE: //uses HttpPost instead of HttpDelete
unboxedParams.put("_method","delete");
//continue with POST
case POST:
request = new HttpPost(apiUri);
break;
default:
throw new IllegalArgumentException("Unknown HTTP method");
}
if (contentType.equals("json")) {
JSONObject asJSON = ObjectUtils.toJSON(unboxedParams);
StringEntity requestEntity = new StringEntity(asJSON.toString(), ContentType.APPLICATION_JSON);
((HttpEntityEnclosingRequestBase) request).setEntity(requestEntity);
} else {
((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(prepareParams(unboxedParams), Consts.UTF_8));
}
}
setTimeouts(request, options);
return request;
} | java | private HttpUriRequest prepareRequest(HttpMethod method, String apiUrl, Map<String, ?> params, Map options) throws URISyntaxException, UnsupportedEncodingException {
URI apiUri;
HttpRequestBase request;
String contentType = ObjectUtils.asString(options.get("content_type"), "urlencoded");
URIBuilder apiUrlBuilder = new URIBuilder(apiUrl);
HashMap<String,Object> unboxedParams = new HashMap<String,Object>(params);
if (method == HttpMethod.GET) {
apiUrlBuilder.setParameters(prepareParams(params));
apiUri = apiUrlBuilder.build();
request = new HttpGet(apiUri);
} else {
apiUri = apiUrlBuilder.build();
switch (method) {
case PUT:
request = new HttpPut(apiUri);
break;
case DELETE: //uses HttpPost instead of HttpDelete
unboxedParams.put("_method","delete");
//continue with POST
case POST:
request = new HttpPost(apiUri);
break;
default:
throw new IllegalArgumentException("Unknown HTTP method");
}
if (contentType.equals("json")) {
JSONObject asJSON = ObjectUtils.toJSON(unboxedParams);
StringEntity requestEntity = new StringEntity(asJSON.toString(), ContentType.APPLICATION_JSON);
((HttpEntityEnclosingRequestBase) request).setEntity(requestEntity);
} else {
((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(prepareParams(unboxedParams), Consts.UTF_8));
}
}
setTimeouts(request, options);
return request;
} | [
"private",
"HttpUriRequest",
"prepareRequest",
"(",
"HttpMethod",
"method",
",",
"String",
"apiUrl",
",",
"Map",
"<",
"String",
",",
"?",
">",
"params",
",",
"Map",
"options",
")",
"throws",
"URISyntaxException",
",",
"UnsupportedEncodingException",
"{",
"URI",
... | Prepare a request with the URL and parameters based on the HTTP method used
@param method the HTTP method: GET, PUT, POST, DELETE
@param apiUrl the cloudinary API URI
@param params the parameters to pass to the server
@return an HTTP request
@throws URISyntaxException
@throws UnsupportedEncodingException | [
"Prepare",
"a",
"request",
"with",
"the",
"URL",
"and",
"parameters",
"based",
"on",
"the",
"HTTP",
"method",
"used"
] | train | https://github.com/cloudinary/cloudinary_java/blob/58ee1823180da2dea6a2eb7e5cf00d5a760f8aef/cloudinary-http43/src/main/java/com/cloudinary/http43/ApiStrategy.java#L141-L179 |
classgraph/classgraph | src/main/java/nonapi/io/github/classgraph/json/JSONDeserializer.java | JSONDeserializer.deserializeObject | private static <T> T deserializeObject(final Class<T> expectedType, final String json,
final ClassFieldCache classFieldCache) throws IllegalArgumentException {
// Parse the JSON
Object parsedJSON;
try {
parsedJSON = JSONParser.parseJSON(json);
} catch (final ParseException e) {
throw new IllegalArgumentException("Could not parse JSON", e);
}
T objectInstance;
try {
// Construct an object of the expected type
final Constructor<?> constructor = classFieldCache.getDefaultConstructorForConcreteTypeOf(expectedType);
@SuppressWarnings("unchecked")
final T newInstance = (T) constructor.newInstance();
objectInstance = newInstance;
} catch (final ReflectiveOperationException | SecurityException e) {
throw new IllegalArgumentException("Could not construct object of type " + expectedType.getName(), e);
}
// Populate the object from the parsed JSON
final List<Runnable> collectionElementAdders = new ArrayList<>();
populateObjectFromJsonObject(objectInstance, expectedType, parsedJSON, classFieldCache,
getInitialIdToObjectMap(objectInstance, parsedJSON), collectionElementAdders);
for (final Runnable runnable : collectionElementAdders) {
runnable.run();
}
return objectInstance;
} | java | private static <T> T deserializeObject(final Class<T> expectedType, final String json,
final ClassFieldCache classFieldCache) throws IllegalArgumentException {
// Parse the JSON
Object parsedJSON;
try {
parsedJSON = JSONParser.parseJSON(json);
} catch (final ParseException e) {
throw new IllegalArgumentException("Could not parse JSON", e);
}
T objectInstance;
try {
// Construct an object of the expected type
final Constructor<?> constructor = classFieldCache.getDefaultConstructorForConcreteTypeOf(expectedType);
@SuppressWarnings("unchecked")
final T newInstance = (T) constructor.newInstance();
objectInstance = newInstance;
} catch (final ReflectiveOperationException | SecurityException e) {
throw new IllegalArgumentException("Could not construct object of type " + expectedType.getName(), e);
}
// Populate the object from the parsed JSON
final List<Runnable> collectionElementAdders = new ArrayList<>();
populateObjectFromJsonObject(objectInstance, expectedType, parsedJSON, classFieldCache,
getInitialIdToObjectMap(objectInstance, parsedJSON), collectionElementAdders);
for (final Runnable runnable : collectionElementAdders) {
runnable.run();
}
return objectInstance;
} | [
"private",
"static",
"<",
"T",
">",
"T",
"deserializeObject",
"(",
"final",
"Class",
"<",
"T",
">",
"expectedType",
",",
"final",
"String",
"json",
",",
"final",
"ClassFieldCache",
"classFieldCache",
")",
"throws",
"IllegalArgumentException",
"{",
"// Parse the JS... | Deserialize JSON to a new object graph, with the root object of the specified expected type, using or reusing
the given type cache. Does not work for generic types, since it is not possible to obtain the generic type of
a Class reference.
@param <T>
the expected type
@param expectedType
The type that the JSON should conform to.
@param json
the JSON string to deserialize.
@param classFieldCache
The class field cache. Reusing this cache will increase the speed if many JSON documents of the
same type need to be parsed.
@return The object graph after deserialization.
@throws IllegalArgumentException
If anything goes wrong during deserialization. | [
"Deserialize",
"JSON",
"to",
"a",
"new",
"object",
"graph",
"with",
"the",
"root",
"object",
"of",
"the",
"specified",
"expected",
"type",
"using",
"or",
"reusing",
"the",
"given",
"type",
"cache",
".",
"Does",
"not",
"work",
"for",
"generic",
"types",
"si... | train | https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/nonapi/io/github/classgraph/json/JSONDeserializer.java#L642-L672 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/utils/KerasModelUtils.java | KerasModelUtils.copyWeightsToModel | public static Model copyWeightsToModel(Model model, Map<String, KerasLayer> kerasLayers)
throws InvalidKerasConfigurationException {
/* Get list if layers from model. */
Layer[] layersFromModel;
if (model instanceof MultiLayerNetwork)
layersFromModel = ((MultiLayerNetwork) model).getLayers();
else
layersFromModel = ((ComputationGraph) model).getLayers();
/* Iterate over layers in model, setting weights when relevant. */
Set<String> layerNames = new HashSet<>(kerasLayers.keySet());
for (org.deeplearning4j.nn.api.Layer layer : layersFromModel) {
String layerName = layer.conf().getLayer().getLayerName();
if (!kerasLayers.containsKey(layerName))
throw new InvalidKerasConfigurationException(
"No weights found for layer in model (named " + layerName + ")");
kerasLayers.get(layerName).copyWeightsToLayer(layer);
layerNames.remove(layerName);
}
for (String layerName : layerNames) {
if (kerasLayers.get(layerName).getNumParams() > 0)
throw new InvalidKerasConfigurationException(
"Attemping to copy weights for layer not in model (named " + layerName + ")");
}
return model;
} | java | public static Model copyWeightsToModel(Model model, Map<String, KerasLayer> kerasLayers)
throws InvalidKerasConfigurationException {
/* Get list if layers from model. */
Layer[] layersFromModel;
if (model instanceof MultiLayerNetwork)
layersFromModel = ((MultiLayerNetwork) model).getLayers();
else
layersFromModel = ((ComputationGraph) model).getLayers();
/* Iterate over layers in model, setting weights when relevant. */
Set<String> layerNames = new HashSet<>(kerasLayers.keySet());
for (org.deeplearning4j.nn.api.Layer layer : layersFromModel) {
String layerName = layer.conf().getLayer().getLayerName();
if (!kerasLayers.containsKey(layerName))
throw new InvalidKerasConfigurationException(
"No weights found for layer in model (named " + layerName + ")");
kerasLayers.get(layerName).copyWeightsToLayer(layer);
layerNames.remove(layerName);
}
for (String layerName : layerNames) {
if (kerasLayers.get(layerName).getNumParams() > 0)
throw new InvalidKerasConfigurationException(
"Attemping to copy weights for layer not in model (named " + layerName + ")");
}
return model;
} | [
"public",
"static",
"Model",
"copyWeightsToModel",
"(",
"Model",
"model",
",",
"Map",
"<",
"String",
",",
"KerasLayer",
">",
"kerasLayers",
")",
"throws",
"InvalidKerasConfigurationException",
"{",
"/* Get list if layers from model. */",
"Layer",
"[",
"]",
"layersFromMo... | Helper function to import weights from nested Map into existing model. Depends critically
on matched layer and parameter names. In general this seems to be straightforward for most
Keras models and layersOrdered, but there may be edge cases.
@param model DL4J Model interface
@return DL4J Model interface
@throws InvalidKerasConfigurationException Invalid Keras config | [
"Helper",
"function",
"to",
"import",
"weights",
"from",
"nested",
"Map",
"into",
"existing",
"model",
".",
"Depends",
"critically",
"on",
"matched",
"layer",
"and",
"parameter",
"names",
".",
"In",
"general",
"this",
"seems",
"to",
"be",
"straightforward",
"f... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/utils/KerasModelUtils.java#L60-L86 |
fullcontact/hadoop-sstable | sstable-core/src/main/java/com/fullcontact/sstable/index/SSTableIndexIndex.java | SSTableIndexIndex.writeIndex | public static void writeIndex(final FileSystem fileSystem, final Path sstablePath) throws IOException {
final Configuration configuration = fileSystem.getConf();
final long splitSize = configuration.getLong(HadoopSSTableConstants.HADOOP_SSTABLE_SPLIT_MB,
HadoopSSTableConstants.DEFAULT_SPLIT_MB) * 1024 * 1024;
final Closer closer = Closer.create();
final Path outputPath = sstablePath.suffix(SSTABLE_INDEX_SUFFIX);
final Path inProgressOutputPath = sstablePath.suffix(SSTABLE_INDEX_IN_PROGRESS_SUFFIX);
boolean success = false;
try {
final FSDataOutputStream os = closer.register(fileSystem.create(inProgressOutputPath));
final TLongArrayList splitOffsets = new TLongArrayList();
long currentStart = 0;
long currentEnd = 0;
final IndexOffsetScanner index = closer.register(new IndexOffsetScanner(sstablePath, fileSystem));
while (index.hasNext()) {
// NOTE: This does not give an exact size of this split in bytes but a rough estimate.
// This should be good enough since it's only used for sorting splits by size in hadoop land.
while (currentEnd - currentStart < splitSize && index.hasNext()) {
currentEnd = index.next();
splitOffsets.add(currentEnd);
}
// Record the split
final long[] offsets = splitOffsets.toArray();
os.writeLong(offsets[0]); // Start
os.writeLong(offsets[offsets.length - 1]); // End
// Clear the offsets
splitOffsets.clear();
if (index.hasNext()) {
currentStart = index.next();
currentEnd = currentStart;
splitOffsets.add(currentStart);
}
}
success = true;
} finally {
closer.close();
if (!success) {
fileSystem.delete(inProgressOutputPath, false);
} else {
fileSystem.rename(inProgressOutputPath, outputPath);
}
}
} | java | public static void writeIndex(final FileSystem fileSystem, final Path sstablePath) throws IOException {
final Configuration configuration = fileSystem.getConf();
final long splitSize = configuration.getLong(HadoopSSTableConstants.HADOOP_SSTABLE_SPLIT_MB,
HadoopSSTableConstants.DEFAULT_SPLIT_MB) * 1024 * 1024;
final Closer closer = Closer.create();
final Path outputPath = sstablePath.suffix(SSTABLE_INDEX_SUFFIX);
final Path inProgressOutputPath = sstablePath.suffix(SSTABLE_INDEX_IN_PROGRESS_SUFFIX);
boolean success = false;
try {
final FSDataOutputStream os = closer.register(fileSystem.create(inProgressOutputPath));
final TLongArrayList splitOffsets = new TLongArrayList();
long currentStart = 0;
long currentEnd = 0;
final IndexOffsetScanner index = closer.register(new IndexOffsetScanner(sstablePath, fileSystem));
while (index.hasNext()) {
// NOTE: This does not give an exact size of this split in bytes but a rough estimate.
// This should be good enough since it's only used for sorting splits by size in hadoop land.
while (currentEnd - currentStart < splitSize && index.hasNext()) {
currentEnd = index.next();
splitOffsets.add(currentEnd);
}
// Record the split
final long[] offsets = splitOffsets.toArray();
os.writeLong(offsets[0]); // Start
os.writeLong(offsets[offsets.length - 1]); // End
// Clear the offsets
splitOffsets.clear();
if (index.hasNext()) {
currentStart = index.next();
currentEnd = currentStart;
splitOffsets.add(currentStart);
}
}
success = true;
} finally {
closer.close();
if (!success) {
fileSystem.delete(inProgressOutputPath, false);
} else {
fileSystem.rename(inProgressOutputPath, outputPath);
}
}
} | [
"public",
"static",
"void",
"writeIndex",
"(",
"final",
"FileSystem",
"fileSystem",
",",
"final",
"Path",
"sstablePath",
")",
"throws",
"IOException",
"{",
"final",
"Configuration",
"configuration",
"=",
"fileSystem",
".",
"getConf",
"(",
")",
";",
"final",
"lon... | Create and write an index index based on the input Cassandra Index.db file. Read the Index.db and generate chunks
(splits) based on the configured chunk size.
@param fileSystem Hadoop file system.
@param sstablePath SSTable Index.db.
@throws IOException | [
"Create",
"and",
"write",
"an",
"index",
"index",
"based",
"on",
"the",
"input",
"Cassandra",
"Index",
".",
"db",
"file",
".",
"Read",
"the",
"Index",
".",
"db",
"and",
"generate",
"chunks",
"(",
"splits",
")",
"based",
"on",
"the",
"configured",
"chunk"... | train | https://github.com/fullcontact/hadoop-sstable/blob/1189c2cb3a2cbbe03b75fda1cf02698e6283dfb2/sstable-core/src/main/java/com/fullcontact/sstable/index/SSTableIndexIndex.java#L89-L143 |
elki-project/elki | elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/em/EM.java | EM.assignProbabilitiesToInstances | public static double assignProbabilitiesToInstances(Relation<? extends NumberVector> relation, List<? extends EMClusterModel<?>> models, WritableDataStore<double[]> probClusterIGivenX) {
final int k = models.size();
double emSum = 0.;
for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
NumberVector vec = relation.get(iditer);
double[] probs = new double[k];
for(int i = 0; i < k; i++) {
double v = models.get(i).estimateLogDensity(vec);
probs[i] = v > MIN_LOGLIKELIHOOD ? v : MIN_LOGLIKELIHOOD;
}
final double logP = logSumExp(probs);
for(int i = 0; i < k; i++) {
probs[i] = FastMath.exp(probs[i] - logP);
}
probClusterIGivenX.put(iditer, probs);
emSum += logP;
}
return emSum / relation.size();
} | java | public static double assignProbabilitiesToInstances(Relation<? extends NumberVector> relation, List<? extends EMClusterModel<?>> models, WritableDataStore<double[]> probClusterIGivenX) {
final int k = models.size();
double emSum = 0.;
for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
NumberVector vec = relation.get(iditer);
double[] probs = new double[k];
for(int i = 0; i < k; i++) {
double v = models.get(i).estimateLogDensity(vec);
probs[i] = v > MIN_LOGLIKELIHOOD ? v : MIN_LOGLIKELIHOOD;
}
final double logP = logSumExp(probs);
for(int i = 0; i < k; i++) {
probs[i] = FastMath.exp(probs[i] - logP);
}
probClusterIGivenX.put(iditer, probs);
emSum += logP;
}
return emSum / relation.size();
} | [
"public",
"static",
"double",
"assignProbabilitiesToInstances",
"(",
"Relation",
"<",
"?",
"extends",
"NumberVector",
">",
"relation",
",",
"List",
"<",
"?",
"extends",
"EMClusterModel",
"<",
"?",
">",
">",
"models",
",",
"WritableDataStore",
"<",
"double",
"[",... | Assigns the current probability values to the instances in the database and
compute the expectation value of the current mixture of distributions.
Computed as the sum of the logarithms of the prior probability of each
instance.
@param relation the database used for assignment to instances
@param models Cluster models
@param probClusterIGivenX Output storage for cluster probabilities
@return the expectation value of the current mixture of distributions | [
"Assigns",
"the",
"current",
"probability",
"values",
"to",
"the",
"instances",
"in",
"the",
"database",
"and",
"compute",
"the",
"expectation",
"value",
"of",
"the",
"current",
"mixture",
"of",
"distributions",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/em/EM.java#L336-L355 |
caelum/vraptor4 | vraptor-core/src/main/java/br/com/caelum/vraptor/converter/EnumConverter.java | EnumConverter.convert | @Override
public Object convert(String value, Class type) {
if (isNullOrEmpty(value)) {
return null;
}
if (Character.isDigit(value.charAt(0))) {
return resolveByOrdinal(value, type);
} else {
return resolveByName(value, type);
}
} | java | @Override
public Object convert(String value, Class type) {
if (isNullOrEmpty(value)) {
return null;
}
if (Character.isDigit(value.charAt(0))) {
return resolveByOrdinal(value, type);
} else {
return resolveByName(value, type);
}
} | [
"@",
"Override",
"public",
"Object",
"convert",
"(",
"String",
"value",
",",
"Class",
"type",
")",
"{",
"if",
"(",
"isNullOrEmpty",
"(",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"Character",
".",
"isDigit",
"(",
"value",
".",
"c... | Enums are always final, so I can suppress this warning safely | [
"Enums",
"are",
"always",
"final",
"so",
"I",
"can",
"suppress",
"this",
"warning",
"safely"
] | train | https://github.com/caelum/vraptor4/blob/593ce9ad60f9d38c360881b2132417c56b8cc093/vraptor-core/src/main/java/br/com/caelum/vraptor/converter/EnumConverter.java#L46-L57 |
osmdroid/osmdroid | OpenStreetMapViewer/src/main/java/org/osmdroid/ExtraSamplesActivity.java | ExtraSamplesActivity.onKeyUp | @Override
public boolean onKeyUp (int keyCode, KeyEvent event){
Fragment frag = getSupportFragmentManager().findFragmentByTag(SAMPLES_FRAGMENT_TAG);
if (frag==null) {
return super.onKeyUp(keyCode, event);
}
if (!(frag instanceof BaseSampleFragment)) {
return super.onKeyUp(keyCode,event);
}
MapView mMapView = ((BaseSampleFragment)frag).getmMapView();
if (mMapView==null)
return super.onKeyUp(keyCode,event);
switch (keyCode) {
case KeyEvent.KEYCODE_PAGE_DOWN:
mMapView.getController().zoomIn();
return true;
case KeyEvent.KEYCODE_PAGE_UP:
mMapView.getController().zoomOut();
return true;
}
return super.onKeyUp(keyCode,event);
} | java | @Override
public boolean onKeyUp (int keyCode, KeyEvent event){
Fragment frag = getSupportFragmentManager().findFragmentByTag(SAMPLES_FRAGMENT_TAG);
if (frag==null) {
return super.onKeyUp(keyCode, event);
}
if (!(frag instanceof BaseSampleFragment)) {
return super.onKeyUp(keyCode,event);
}
MapView mMapView = ((BaseSampleFragment)frag).getmMapView();
if (mMapView==null)
return super.onKeyUp(keyCode,event);
switch (keyCode) {
case KeyEvent.KEYCODE_PAGE_DOWN:
mMapView.getController().zoomIn();
return true;
case KeyEvent.KEYCODE_PAGE_UP:
mMapView.getController().zoomOut();
return true;
}
return super.onKeyUp(keyCode,event);
} | [
"@",
"Override",
"public",
"boolean",
"onKeyUp",
"(",
"int",
"keyCode",
",",
"KeyEvent",
"event",
")",
"{",
"Fragment",
"frag",
"=",
"getSupportFragmentManager",
"(",
")",
".",
"findFragmentByTag",
"(",
"SAMPLES_FRAGMENT_TAG",
")",
";",
"if",
"(",
"frag",
"=="... | small example of keyboard events on the mapview
page up = zoom out
page down = zoom in
@param keyCode
@param event
@return | [
"small",
"example",
"of",
"keyboard",
"events",
"on",
"the",
"mapview",
"page",
"up",
"=",
"zoom",
"out",
"page",
"down",
"=",
"zoom",
"in"
] | train | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/OpenStreetMapViewer/src/main/java/org/osmdroid/ExtraSamplesActivity.java#L53-L74 |
apache/reef | lang/java/reef-examples/src/main/java/org/apache/reef/examples/group/bgd/BGDClient.java | BGDClient.submit | public void submit(final Configuration runtimeConfiguration, final String jobName) throws Exception {
final Configuration driverConfiguration = getDriverConfiguration(jobName);
Tang.Factory.getTang().newInjector(runtimeConfiguration).getInstance(REEF.class).submit(driverConfiguration);
} | java | public void submit(final Configuration runtimeConfiguration, final String jobName) throws Exception {
final Configuration driverConfiguration = getDriverConfiguration(jobName);
Tang.Factory.getTang().newInjector(runtimeConfiguration).getInstance(REEF.class).submit(driverConfiguration);
} | [
"public",
"void",
"submit",
"(",
"final",
"Configuration",
"runtimeConfiguration",
",",
"final",
"String",
"jobName",
")",
"throws",
"Exception",
"{",
"final",
"Configuration",
"driverConfiguration",
"=",
"getDriverConfiguration",
"(",
"jobName",
")",
";",
"Tang",
"... | Runs BGD on the given runtime.
@param runtimeConfiguration the runtime to run on.
@param jobName the name of the job on the runtime. | [
"Runs",
"BGD",
"on",
"the",
"given",
"runtime",
"."
] | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-examples/src/main/java/org/apache/reef/examples/group/bgd/BGDClient.java#L71-L74 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/parser/lexparser/AbstractTreebankParserParams.java | AbstractTreebankParserParams.typedDependencyObjectify | public static Collection<List<String>> typedDependencyObjectify(Tree t, HeadFinder hf, TreeTransformer collinizer) {
return dependencyObjectify(t, hf, collinizer, new TypedDependencyTyper(hf));
} | java | public static Collection<List<String>> typedDependencyObjectify(Tree t, HeadFinder hf, TreeTransformer collinizer) {
return dependencyObjectify(t, hf, collinizer, new TypedDependencyTyper(hf));
} | [
"public",
"static",
"Collection",
"<",
"List",
"<",
"String",
">",
">",
"typedDependencyObjectify",
"(",
"Tree",
"t",
",",
"HeadFinder",
"hf",
",",
"TreeTransformer",
"collinizer",
")",
"{",
"return",
"dependencyObjectify",
"(",
"t",
",",
"hf",
",",
"collinize... | Returns a collection of word-word dependencies typed by mother, head, daughter node syntactic categories. | [
"Returns",
"a",
"collection",
"of",
"word",
"-",
"word",
"dependencies",
"typed",
"by",
"mother",
"head",
"daughter",
"node",
"syntactic",
"categories",
"."
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/parser/lexparser/AbstractTreebankParserParams.java#L358-L360 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/PushbackInputStream.java | PushbackInputStream.unread | public void unread(byte[] b, int off, int len) throws IOException {
ensureOpen();
if (len > pos) {
throw new IOException("Push back buffer is full");
}
pos -= len;
System.arraycopy(b, off, buf, pos, len);
} | java | public void unread(byte[] b, int off, int len) throws IOException {
ensureOpen();
if (len > pos) {
throw new IOException("Push back buffer is full");
}
pos -= len;
System.arraycopy(b, off, buf, pos, len);
} | [
"public",
"void",
"unread",
"(",
"byte",
"[",
"]",
"b",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"ensureOpen",
"(",
")",
";",
"if",
"(",
"len",
">",
"pos",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Push back buf... | Pushes back a portion of an array of bytes by copying it to the front
of the pushback buffer. After this method returns, the next byte to be
read will have the value <code>b[off]</code>, the byte after that will
have the value <code>b[off+1]</code>, and so forth.
@param b the byte array to push back.
@param off the start offset of the data.
@param len the number of bytes to push back.
@exception IOException If there is not enough room in the pushback
buffer for the specified number of bytes,
or this input stream has been closed by
invoking its {@link #close()} method.
@since JDK1.1 | [
"Pushes",
"back",
"a",
"portion",
"of",
"an",
"array",
"of",
"bytes",
"by",
"copying",
"it",
"to",
"the",
"front",
"of",
"the",
"pushback",
"buffer",
".",
"After",
"this",
"method",
"returns",
"the",
"next",
"byte",
"to",
"be",
"read",
"will",
"have",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/PushbackInputStream.java#L229-L236 |
box/box-java-sdk | src/main/java/com/box/sdk/BoxAPIConnection.java | BoxAPIConnection.getLowerScopedToken | public ScopedToken getLowerScopedToken(List<String> scopes, String resource) {
assert (scopes != null);
assert (scopes.size() > 0);
URL url = null;
try {
url = new URL(this.getTokenURL());
} catch (MalformedURLException e) {
assert false : "An invalid refresh URL indicates a bug in the SDK.";
throw new RuntimeException("An invalid refresh URL indicates a bug in the SDK.", e);
}
StringBuilder spaceSeparatedScopes = new StringBuilder();
for (int i = 0; i < scopes.size(); i++) {
spaceSeparatedScopes.append(scopes.get(i));
if (i < scopes.size() - 1) {
spaceSeparatedScopes.append(" ");
}
}
String urlParameters = null;
if (resource != null) {
//this.getAccessToken() ensures we have a valid access token
urlParameters = String.format("grant_type=urn:ietf:params:oauth:grant-type:token-exchange"
+ "&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s"
+ "&scope=%s&resource=%s",
this.getAccessToken(), spaceSeparatedScopes, resource);
} else {
//this.getAccessToken() ensures we have a valid access token
urlParameters = String.format("grant_type=urn:ietf:params:oauth:grant-type:token-exchange"
+ "&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s"
+ "&scope=%s",
this.getAccessToken(), spaceSeparatedScopes);
}
BoxAPIRequest request = new BoxAPIRequest(this, url, "POST");
request.shouldAuthenticate(false);
request.setBody(urlParameters);
String json;
try {
BoxJSONResponse response = (BoxJSONResponse) request.send();
json = response.getJSON();
} catch (BoxAPIException e) {
this.notifyError(e);
throw e;
}
JsonObject jsonObject = JsonObject.readFrom(json);
ScopedToken token = new ScopedToken(jsonObject);
token.setObtainedAt(System.currentTimeMillis());
token.setExpiresIn(jsonObject.get("expires_in").asLong() * 1000);
return token;
} | java | public ScopedToken getLowerScopedToken(List<String> scopes, String resource) {
assert (scopes != null);
assert (scopes.size() > 0);
URL url = null;
try {
url = new URL(this.getTokenURL());
} catch (MalformedURLException e) {
assert false : "An invalid refresh URL indicates a bug in the SDK.";
throw new RuntimeException("An invalid refresh URL indicates a bug in the SDK.", e);
}
StringBuilder spaceSeparatedScopes = new StringBuilder();
for (int i = 0; i < scopes.size(); i++) {
spaceSeparatedScopes.append(scopes.get(i));
if (i < scopes.size() - 1) {
spaceSeparatedScopes.append(" ");
}
}
String urlParameters = null;
if (resource != null) {
//this.getAccessToken() ensures we have a valid access token
urlParameters = String.format("grant_type=urn:ietf:params:oauth:grant-type:token-exchange"
+ "&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s"
+ "&scope=%s&resource=%s",
this.getAccessToken(), spaceSeparatedScopes, resource);
} else {
//this.getAccessToken() ensures we have a valid access token
urlParameters = String.format("grant_type=urn:ietf:params:oauth:grant-type:token-exchange"
+ "&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s"
+ "&scope=%s",
this.getAccessToken(), spaceSeparatedScopes);
}
BoxAPIRequest request = new BoxAPIRequest(this, url, "POST");
request.shouldAuthenticate(false);
request.setBody(urlParameters);
String json;
try {
BoxJSONResponse response = (BoxJSONResponse) request.send();
json = response.getJSON();
} catch (BoxAPIException e) {
this.notifyError(e);
throw e;
}
JsonObject jsonObject = JsonObject.readFrom(json);
ScopedToken token = new ScopedToken(jsonObject);
token.setObtainedAt(System.currentTimeMillis());
token.setExpiresIn(jsonObject.get("expires_in").asLong() * 1000);
return token;
} | [
"public",
"ScopedToken",
"getLowerScopedToken",
"(",
"List",
"<",
"String",
">",
"scopes",
",",
"String",
"resource",
")",
"{",
"assert",
"(",
"scopes",
"!=",
"null",
")",
";",
"assert",
"(",
"scopes",
".",
"size",
"(",
")",
">",
"0",
")",
";",
"URL",
... | Get a lower-scoped token restricted to a resource for the list of scopes that are passed.
@param scopes the list of scopes to which the new token should be restricted for
@param resource the resource for which the new token has to be obtained
@return scopedToken which has access token and other details | [
"Get",
"a",
"lower",
"-",
"scoped",
"token",
"restricted",
"to",
"a",
"resource",
"for",
"the",
"list",
"of",
"scopes",
"that",
"are",
"passed",
"."
] | train | https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxAPIConnection.java#L680-L733 |
primefaces/primefaces | src/main/java/org/primefaces/component/organigram/OrganigramRenderer.java | OrganigramRenderer.decodeSelection | protected void decodeSelection(FacesContext context, Organigram organigram) {
if (ComponentUtils.isRequestSource(organigram, context)) {
boolean selectionEnabled = organigram.getValueExpression("selection") != null;
if (selectionEnabled) {
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
String rowKey = params.get(organigram.getClientId(context) + "_selectNode");
if (!isValueBlank(rowKey)) {
OrganigramNode node = organigram.findTreeNode(organigram.getValue(), rowKey);
assignSelection(context, organigram, node);
}
}
}
} | java | protected void decodeSelection(FacesContext context, Organigram organigram) {
if (ComponentUtils.isRequestSource(organigram, context)) {
boolean selectionEnabled = organigram.getValueExpression("selection") != null;
if (selectionEnabled) {
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
String rowKey = params.get(organigram.getClientId(context) + "_selectNode");
if (!isValueBlank(rowKey)) {
OrganigramNode node = organigram.findTreeNode(organigram.getValue(), rowKey);
assignSelection(context, organigram, node);
}
}
}
} | [
"protected",
"void",
"decodeSelection",
"(",
"FacesContext",
"context",
",",
"Organigram",
"organigram",
")",
"{",
"if",
"(",
"ComponentUtils",
".",
"isRequestSource",
"(",
"organigram",
",",
"context",
")",
")",
"{",
"boolean",
"selectionEnabled",
"=",
"organigra... | Checks if the current request is a selection request and
assigns the found {@link OrganigramNode} to the <code>selection</code> value expression.
@param context The current {@link FacesContext}.
@param organigram The {@link Organigram} component. | [
"Checks",
"if",
"the",
"current",
"request",
"is",
"a",
"selection",
"request",
"and",
"assigns",
"the",
"found",
"{",
"@link",
"OrganigramNode",
"}",
"to",
"the",
"<code",
">",
"selection<",
"/",
"code",
">",
"value",
"expression",
"."
] | train | https://github.com/primefaces/primefaces/blob/b8cdd5ed395d09826e40e3302d6b14901d3ef4e7/src/main/java/org/primefaces/component/organigram/OrganigramRenderer.java#L62-L78 |
Azure/autorest-clientruntime-for-java | azure-arm-client-runtime/src/main/java/com/microsoft/azure/arm/resources/models/implementation/ResourceImpl.java | ResourceImpl.withTags | @SuppressWarnings("unchecked")
public final FluentModelImplT withTags(Map<String, String> tags) {
this.inner().withTags(new HashMap<>(tags));
return (FluentModelImplT) this;
} | java | @SuppressWarnings("unchecked")
public final FluentModelImplT withTags(Map<String, String> tags) {
this.inner().withTags(new HashMap<>(tags));
return (FluentModelImplT) this;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"final",
"FluentModelImplT",
"withTags",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"this",
".",
"inner",
"(",
")",
".",
"withTags",
"(",
"new",
"HashMap",
"<>",
"(",
"ta... | Specifies tags for the resource as a {@link Map}.
@param tags a {@link Map} of tags
@return the next stage of the definition/update | [
"Specifies",
"tags",
"for",
"the",
"resource",
"as",
"a",
"{"
] | train | https://github.com/Azure/autorest-clientruntime-for-java/blob/04621e07dbb0456dd5459dd641f06a9fd4f3abad/azure-arm-client-runtime/src/main/java/com/microsoft/azure/arm/resources/models/implementation/ResourceImpl.java#L97-L101 |
cdk/cdk | base/core/src/main/java/org/openscience/cdk/graph/Cycles.java | Cycles.toRing | private static IRing toRing(IAtomContainer container, int[] cycle, EdgeToBondMap bondMap) {
IAtom[] atoms = new IAtom[cycle.length - 1];
IBond[] bonds = new IBond[cycle.length - 1];
for (int i = 1; i < cycle.length; i++) {
int v = cycle[i];
int u = cycle[i - 1];
atoms[i - 1] = container.getAtom(u);
bonds[i - 1] = getBond(container, bondMap, u, v);
}
IChemObjectBuilder builder = container.getBuilder();
IAtomContainer ring = builder.newInstance(IAtomContainer.class, 0, 0, 0, 0);
ring.setAtoms(atoms);
ring.setBonds(bonds);
return builder.newInstance(IRing.class, ring);
} | java | private static IRing toRing(IAtomContainer container, int[] cycle, EdgeToBondMap bondMap) {
IAtom[] atoms = new IAtom[cycle.length - 1];
IBond[] bonds = new IBond[cycle.length - 1];
for (int i = 1; i < cycle.length; i++) {
int v = cycle[i];
int u = cycle[i - 1];
atoms[i - 1] = container.getAtom(u);
bonds[i - 1] = getBond(container, bondMap, u, v);
}
IChemObjectBuilder builder = container.getBuilder();
IAtomContainer ring = builder.newInstance(IAtomContainer.class, 0, 0, 0, 0);
ring.setAtoms(atoms);
ring.setBonds(bonds);
return builder.newInstance(IRing.class, ring);
} | [
"private",
"static",
"IRing",
"toRing",
"(",
"IAtomContainer",
"container",
",",
"int",
"[",
"]",
"cycle",
",",
"EdgeToBondMap",
"bondMap",
")",
"{",
"IAtom",
"[",
"]",
"atoms",
"=",
"new",
"IAtom",
"[",
"cycle",
".",
"length",
"-",
"1",
"]",
";",
"IBo... | Internal - convert a set of cycles to a ring.
@param container molecule
@param cycle a cycle of the chemical graph
@param bondMap mapping of the edges (int,int) to the bonds of the
container
@return the ring for the specified cycle | [
"Internal",
"-",
"convert",
"a",
"set",
"of",
"cycles",
"to",
"a",
"ring",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/core/src/main/java/org/openscience/cdk/graph/Cycles.java#L938-L956 |
jmapper-framework/jmapper-core | JMapper Framework/src/main/java/com/googlecode/jmapper/xml/XML.java | XML.addClass | public XML addClass(Class<?> aClass, Global global){
checksClassAbsence(aClass);
XmlClass xmlClass = new XmlClass();
xmlClass.name = aClass.getName();
xmlJmapper.classes.add(xmlClass);
addGlobal(aClass, global);
return this;
} | java | public XML addClass(Class<?> aClass, Global global){
checksClassAbsence(aClass);
XmlClass xmlClass = new XmlClass();
xmlClass.name = aClass.getName();
xmlJmapper.classes.add(xmlClass);
addGlobal(aClass, global);
return this;
} | [
"public",
"XML",
"addClass",
"(",
"Class",
"<",
"?",
">",
"aClass",
",",
"Global",
"global",
")",
"{",
"checksClassAbsence",
"(",
"aClass",
")",
";",
"XmlClass",
"xmlClass",
"=",
"new",
"XmlClass",
"(",
")",
";",
"xmlClass",
".",
"name",
"=",
"aClass",
... | This method adds aClass with this global mapping and attributes to XML configuration file.<br>
It's mandatory define at least one attribute, global is optional instead.
@param aClass Class to adds
@param global global mapping
@return this instance | [
"This",
"method",
"adds",
"aClass",
"with",
"this",
"global",
"mapping",
"and",
"attributes",
"to",
"XML",
"configuration",
"file",
".",
"<br",
">",
"It",
"s",
"mandatory",
"define",
"at",
"least",
"one",
"attribute",
"global",
"is",
"optional",
"instead",
"... | train | https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/xml/XML.java#L258-L266 |
ops4j/org.ops4j.base | ops4j-base-io/src/main/java/org/ops4j/io/ZipExploder.java | ZipExploder.processJars | @Deprecated
public void processJars(String[] jarNames, String destDir) throws IOException {
//Delegation to preferred method
processJars(FileUtils.pathNamesToFiles(jarNames), new File(destDir));
} | java | @Deprecated
public void processJars(String[] jarNames, String destDir) throws IOException {
//Delegation to preferred method
processJars(FileUtils.pathNamesToFiles(jarNames), new File(destDir));
} | [
"@",
"Deprecated",
"public",
"void",
"processJars",
"(",
"String",
"[",
"]",
"jarNames",
",",
"String",
"destDir",
")",
"throws",
"IOException",
"{",
"//Delegation to preferred method",
"processJars",
"(",
"FileUtils",
".",
"pathNamesToFiles",
"(",
"jarNames",
")",
... | Explode source JAR files into a target directory
@param jarNames
names of source files
@param destDir
target directory name (should already exist)
@exception IOException
error creating a target file
@deprecated use {@link #processJars(File[], File)} for a type save
variant | [
"Explode",
"source",
"JAR",
"files",
"into",
"a",
"target",
"directory"
] | train | https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-io/src/main/java/org/ops4j/io/ZipExploder.java#L152-L156 |
Berico-Technologies/CLAVIN | src/main/java/com/bericotech/clavin/resolver/ClavinLocationResolver.java | ClavinLocationResolver.resolveLocations | public List<ResolvedLocation> resolveLocations(final List<LocationOccurrence> locations, final boolean fuzzy)
throws ClavinException {
return resolveLocations(locations, DEFAULT_MAX_HIT_DEPTH, DEFAULT_MAX_CONTEXT_WINDOW, fuzzy, DEFAULT_ANCESTRY_MODE);
} | java | public List<ResolvedLocation> resolveLocations(final List<LocationOccurrence> locations, final boolean fuzzy)
throws ClavinException {
return resolveLocations(locations, DEFAULT_MAX_HIT_DEPTH, DEFAULT_MAX_CONTEXT_WINDOW, fuzzy, DEFAULT_ANCESTRY_MODE);
} | [
"public",
"List",
"<",
"ResolvedLocation",
">",
"resolveLocations",
"(",
"final",
"List",
"<",
"LocationOccurrence",
">",
"locations",
",",
"final",
"boolean",
"fuzzy",
")",
"throws",
"ClavinException",
"{",
"return",
"resolveLocations",
"(",
"locations",
",",
"DE... | Resolves the supplied list of location names into
{@link ResolvedLocation}s containing {@link com.bericotech.clavin.gazetteer.GeoName} objects
using the defaults for maxHitDepth and maxContentWindow.
Calls {@link Gazetteer#getClosestLocations} on
each location name to find all possible matches, then uses
heuristics to select the best match for each by calling
{@link ClavinLocationResolver#pickBestCandidates}.
@param locations list of location names to be resolved
@param fuzzy switch for turning on/off fuzzy matching
@return list of {@link ResolvedLocation} objects
@throws ClavinException if an error occurs parsing the search terms | [
"Resolves",
"the",
"supplied",
"list",
"of",
"location",
"names",
"into",
"{",
"@link",
"ResolvedLocation",
"}",
"s",
"containing",
"{",
"@link",
"com",
".",
"bericotech",
".",
"clavin",
".",
"gazetteer",
".",
"GeoName",
"}",
"objects",
"using",
"the",
"defa... | train | https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/resolver/ClavinLocationResolver.java#L115-L118 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/axis/HelixAxisAligner.java | HelixAxisAligner.getMidPoint | private Point3d getMidPoint(Point3d p1, Point3d p2, Point3d p3) {
Vector3d v1 = new Vector3d();
v1.sub(p1, p2);
Vector3d v2 = new Vector3d();
v2.sub(p3, p2);
Vector3d v3 = new Vector3d();
v3.add(v1);
v3.add(v2);
v3.normalize();
// calculat the total distance between to subunits
double dTotal = v1.length();
// calculate the rise along the y-axis. The helix axis is aligned with y-axis,
// therfore, the rise between subunits is the y-distance
double rise = p2.y - p1.y;
// use phythagorean theoremm to calculate chord length between two subunit centers
double chord = Math.sqrt(dTotal*dTotal - rise*rise);
// System.out.println("Chord d: " + dTotal + " rise: " + rise + "chord: " + chord);
double angle = helixLayers.getByLargestContacts().getAxisAngle().angle;
// using the axis angle and the chord length, we can calculate the radius of the helix
// http://en.wikipedia.org/wiki/Chord_%28geometry%29
double radius = chord/Math.sin(angle/2)/2; // can this go to zero?
// System.out.println("Radius: " + radius);
// project the radius onto the vector that points toward the helix axis
v3.scale(radius);
v3.add(p2);
// System.out.println("Angle: " + Math.toDegrees(helixLayers.getByLowestAngle().getAxisAngle().angle));
Point3d cor = new Point3d(v3);
return cor;
} | java | private Point3d getMidPoint(Point3d p1, Point3d p2, Point3d p3) {
Vector3d v1 = new Vector3d();
v1.sub(p1, p2);
Vector3d v2 = new Vector3d();
v2.sub(p3, p2);
Vector3d v3 = new Vector3d();
v3.add(v1);
v3.add(v2);
v3.normalize();
// calculat the total distance between to subunits
double dTotal = v1.length();
// calculate the rise along the y-axis. The helix axis is aligned with y-axis,
// therfore, the rise between subunits is the y-distance
double rise = p2.y - p1.y;
// use phythagorean theoremm to calculate chord length between two subunit centers
double chord = Math.sqrt(dTotal*dTotal - rise*rise);
// System.out.println("Chord d: " + dTotal + " rise: " + rise + "chord: " + chord);
double angle = helixLayers.getByLargestContacts().getAxisAngle().angle;
// using the axis angle and the chord length, we can calculate the radius of the helix
// http://en.wikipedia.org/wiki/Chord_%28geometry%29
double radius = chord/Math.sin(angle/2)/2; // can this go to zero?
// System.out.println("Radius: " + radius);
// project the radius onto the vector that points toward the helix axis
v3.scale(radius);
v3.add(p2);
// System.out.println("Angle: " + Math.toDegrees(helixLayers.getByLowestAngle().getAxisAngle().angle));
Point3d cor = new Point3d(v3);
return cor;
} | [
"private",
"Point3d",
"getMidPoint",
"(",
"Point3d",
"p1",
",",
"Point3d",
"p2",
",",
"Point3d",
"p3",
")",
"{",
"Vector3d",
"v1",
"=",
"new",
"Vector3d",
"(",
")",
";",
"v1",
".",
"sub",
"(",
"p1",
",",
"p2",
")",
";",
"Vector3d",
"v2",
"=",
"new"... | Return a midpoint of a helix, calculated from three positions
of three adjacent subunit centers.
@param p1 center of first subunit
@param p2 center of second subunit
@param p3 center of third subunit
@return midpoint of helix | [
"Return",
"a",
"midpoint",
"of",
"a",
"helix",
"calculated",
"from",
"three",
"positions",
"of",
"three",
"adjacent",
"subunit",
"centers",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/axis/HelixAxisAligner.java#L311-L342 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PatternsImpl.java | PatternsImpl.deletePatterns | public OperationStatus deletePatterns(UUID appId, String versionId, List<UUID> patternIds) {
return deletePatternsWithServiceResponseAsync(appId, versionId, patternIds).toBlocking().single().body();
} | java | public OperationStatus deletePatterns(UUID appId, String versionId, List<UUID> patternIds) {
return deletePatternsWithServiceResponseAsync(appId, versionId, patternIds).toBlocking().single().body();
} | [
"public",
"OperationStatus",
"deletePatterns",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"List",
"<",
"UUID",
">",
"patternIds",
")",
"{",
"return",
"deletePatternsWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"patternIds",
")",
".",... | Deletes the patterns with the specified IDs.
@param appId The application ID.
@param versionId The version ID.
@param patternIds The patterns IDs.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the OperationStatus object if successful. | [
"Deletes",
"the",
"patterns",
"with",
"the",
"specified",
"IDs",
"."
] | 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/PatternsImpl.java#L568-L570 |
DV8FromTheWorld/JDA | src/main/java/net/dv8tion/jda/core/utils/PermissionUtil.java | PermissionUtil.canInteract | public static boolean canInteract(Role issuer, Role target)
{
Checks.notNull(issuer, "Issuer Role");
Checks.notNull(target, "Target Role");
if(!issuer.getGuild().equals(target.getGuild()))
throw new IllegalArgumentException("The 2 Roles are not from same Guild!");
return target.getPosition() < issuer.getPosition();
} | java | public static boolean canInteract(Role issuer, Role target)
{
Checks.notNull(issuer, "Issuer Role");
Checks.notNull(target, "Target Role");
if(!issuer.getGuild().equals(target.getGuild()))
throw new IllegalArgumentException("The 2 Roles are not from same Guild!");
return target.getPosition() < issuer.getPosition();
} | [
"public",
"static",
"boolean",
"canInteract",
"(",
"Role",
"issuer",
",",
"Role",
"target",
")",
"{",
"Checks",
".",
"notNull",
"(",
"issuer",
",",
"\"Issuer Role\"",
")",
";",
"Checks",
".",
"notNull",
"(",
"target",
",",
"\"Target Role\"",
")",
";",
"if"... | Checks if one given Role can interact with a 2nd given Role - in a permission sense (kick/ban/modify perms).
This only checks the Role-Position and does not check the actual permission (kick/ban/manage_role/...)
@param issuer
The role that tries to interact with 2nd role
@param target
The role that is the target of the interaction
@throws IllegalArgumentException
if any of the provided parameters is {@code null}
or the provided entities are not from the same guild
@return True, if issuer can interact with target | [
"Checks",
"if",
"one",
"given",
"Role",
"can",
"interact",
"with",
"a",
"2nd",
"given",
"Role",
"-",
"in",
"a",
"permission",
"sense",
"(",
"kick",
"/",
"ban",
"/",
"modify",
"perms",
")",
".",
"This",
"only",
"checks",
"the",
"Role",
"-",
"Position",
... | train | https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/utils/PermissionUtil.java#L104-L112 |
jbundle/jbundle | base/model/src/main/java/org/jbundle/base/model/Utility.java | Utility.replaceResources | public static String replaceResources(String string, ResourceBundle reg, Map<String, Object> map, PropertyOwner propertyOwner)
{
return Utility.replaceResources(string, reg, map, propertyOwner, false);
} | java | public static String replaceResources(String string, ResourceBundle reg, Map<String, Object> map, PropertyOwner propertyOwner)
{
return Utility.replaceResources(string, reg, map, propertyOwner, false);
} | [
"public",
"static",
"String",
"replaceResources",
"(",
"String",
"string",
",",
"ResourceBundle",
"reg",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
",",
"PropertyOwner",
"propertyOwner",
")",
"{",
"return",
"Utility",
".",
"replaceResources",
"(",
"... | Replace the {} resources in this string.
@param reg
@param map A map of key/values
@param strResource
@return | [
"Replace",
"the",
"{}",
"resources",
"in",
"this",
"string",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/model/src/main/java/org/jbundle/base/model/Utility.java#L291-L294 |
jbundle/jbundle | base/db/xml/src/main/java/org/jbundle/base/db/xml/XTable.java | XTable.writeData | public void writeData(FieldTable table) throws Exception
{
if (this.getLookupKey() instanceof String)
{
FieldList record = table.getRecord();
/** Write a tree object, and all the subtrees */
String strFilePath = (String)this.getLookupKey();
String strFilename = this.getPDatabase().getFilename(strFilePath, true);
if (record != null) if (((Record)record).isInFree())
{
// Read the XML records
XmlInOut inOut = new XmlInOut(null, null, null);
inOut.exportXML(((Record)record).getTable(), strFilename);
inOut.free();
}
}
} | java | public void writeData(FieldTable table) throws Exception
{
if (this.getLookupKey() instanceof String)
{
FieldList record = table.getRecord();
/** Write a tree object, and all the subtrees */
String strFilePath = (String)this.getLookupKey();
String strFilename = this.getPDatabase().getFilename(strFilePath, true);
if (record != null) if (((Record)record).isInFree())
{
// Read the XML records
XmlInOut inOut = new XmlInOut(null, null, null);
inOut.exportXML(((Record)record).getTable(), strFilename);
inOut.free();
}
}
} | [
"public",
"void",
"writeData",
"(",
"FieldTable",
"table",
")",
"throws",
"Exception",
"{",
"if",
"(",
"this",
".",
"getLookupKey",
"(",
")",
"instanceof",
"String",
")",
"{",
"FieldList",
"record",
"=",
"table",
".",
"getRecord",
"(",
")",
";",
"/** Write... | Write the data.
If this is the last copy being closed, write the XML data to the file.
<p />Notice I flush on close, rather than free, so the record object is
still usable - This will create a performance problem for tasks that are
processing the file, but it should be rare to be using an XML file for
processing.
@param table The table. | [
"Write",
"the",
"data",
".",
"If",
"this",
"is",
"the",
"last",
"copy",
"being",
"closed",
"write",
"the",
"XML",
"data",
"to",
"the",
"file",
".",
"<p",
"/",
">",
"Notice",
"I",
"flush",
"on",
"close",
"rather",
"than",
"free",
"so",
"the",
"record"... | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/db/xml/src/main/java/org/jbundle/base/db/xml/XTable.java#L112-L128 |
OpenLiberty/open-liberty | dev/com.ibm.ws.org.apache.cxf.cxf.rt.frontend.jaxrs.3.2/src/org/apache/cxf/jaxrs/utils/JAXRSUtils.java | JAXRSUtils.intersectMimeTypes | public static List<MediaType> intersectMimeTypes(List<MediaType> requiredMediaTypes,
List<MediaType> userMediaTypes,
boolean addRequiredParamsIfPossible) {
return intersectMimeTypes(requiredMediaTypes, userMediaTypes, addRequiredParamsIfPossible, false);
} | java | public static List<MediaType> intersectMimeTypes(List<MediaType> requiredMediaTypes,
List<MediaType> userMediaTypes,
boolean addRequiredParamsIfPossible) {
return intersectMimeTypes(requiredMediaTypes, userMediaTypes, addRequiredParamsIfPossible, false);
} | [
"public",
"static",
"List",
"<",
"MediaType",
">",
"intersectMimeTypes",
"(",
"List",
"<",
"MediaType",
">",
"requiredMediaTypes",
",",
"List",
"<",
"MediaType",
">",
"userMediaTypes",
",",
"boolean",
"addRequiredParamsIfPossible",
")",
"{",
"return",
"intersectMime... | intersect two mime types
@param mimeTypesA
@param mimeTypesB
@return return a list of intersected mime types | [
"intersect",
"two",
"mime",
"types"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.org.apache.cxf.cxf.rt.frontend.jaxrs.3.2/src/org/apache/cxf/jaxrs/utils/JAXRSUtils.java#L1543-L1547 |
cdk/cdk | misc/extra/src/main/java/org/openscience/cdk/tools/AtomTypeTools.java | AtomTypeTools.assignAtomTypePropertiesToAtom | public IRingSet assignAtomTypePropertiesToAtom(IAtomContainer molecule, boolean aromaticity) throws Exception {
SmilesGenerator sg = new SmilesGenerator();
//logger.debug("assignAtomTypePropertiesToAtom Start ...");
logger.debug("assignAtomTypePropertiesToAtom Start ...");
String hoseCode = "";
IRingSet ringSetA = null;
IRingSet ringSetMolecule = Cycles.sssr(molecule).toRingSet();
logger.debug(ringSetMolecule);
if (aromaticity) {
try {
Aromaticity.cdkLegacy().apply(molecule);
} catch (Exception cdk1) {
//logger.debug("AROMATICITYError: Cannot determine aromaticity due to: " + cdk1.toString());
logger.error("AROMATICITYError: Cannot determine aromaticity due to: " + cdk1.toString());
}
}
for (int i = 0; i < molecule.getAtomCount(); i++) {
// FIXME: remove casting
IAtom atom2 = molecule.getAtom(i);
//Atom aromatic is set by HueckelAromaticityDetector
//Atom in ring?
if (ringSetMolecule.contains(atom2)) {
ringSetA = ringSetMolecule.getRings(atom2);
RingSetManipulator.sort(ringSetA);
IRing sring = (IRing) ringSetA.getAtomContainer(ringSetA.getAtomContainerCount() - 1);
atom2.setProperty(CDKConstants.PART_OF_RING_OF_SIZE, Integer.valueOf(sring.getRingSize()));
atom2.setProperty(
CDKConstants.CHEMICAL_GROUP_CONSTANT,
Integer.valueOf(ringSystemClassifier(sring, getSubgraphSmiles(sring, molecule))));
atom2.setFlag(CDKConstants.ISINRING, true);
atom2.setFlag(CDKConstants.ISALIPHATIC, false);
} else {
atom2.setProperty(CDKConstants.CHEMICAL_GROUP_CONSTANT, Integer.valueOf(CDKConstants.ISNOTINRING));
atom2.setFlag(CDKConstants.ISINRING, false);
atom2.setFlag(CDKConstants.ISALIPHATIC, true);
}
try {
hoseCode = hcg.getHOSECode(molecule, atom2, 3);
hoseCode = removeAromaticityFlagsFromHoseCode(hoseCode);
atom2.setProperty(CDKConstants.SPHERICAL_MATCHER, hoseCode);
} catch (CDKException ex1) {
throw new CDKException("Could not build HOSECode from atom " + i + " due to " + ex1.toString(), ex1);
}
}
return ringSetMolecule;
} | java | public IRingSet assignAtomTypePropertiesToAtom(IAtomContainer molecule, boolean aromaticity) throws Exception {
SmilesGenerator sg = new SmilesGenerator();
//logger.debug("assignAtomTypePropertiesToAtom Start ...");
logger.debug("assignAtomTypePropertiesToAtom Start ...");
String hoseCode = "";
IRingSet ringSetA = null;
IRingSet ringSetMolecule = Cycles.sssr(molecule).toRingSet();
logger.debug(ringSetMolecule);
if (aromaticity) {
try {
Aromaticity.cdkLegacy().apply(molecule);
} catch (Exception cdk1) {
//logger.debug("AROMATICITYError: Cannot determine aromaticity due to: " + cdk1.toString());
logger.error("AROMATICITYError: Cannot determine aromaticity due to: " + cdk1.toString());
}
}
for (int i = 0; i < molecule.getAtomCount(); i++) {
// FIXME: remove casting
IAtom atom2 = molecule.getAtom(i);
//Atom aromatic is set by HueckelAromaticityDetector
//Atom in ring?
if (ringSetMolecule.contains(atom2)) {
ringSetA = ringSetMolecule.getRings(atom2);
RingSetManipulator.sort(ringSetA);
IRing sring = (IRing) ringSetA.getAtomContainer(ringSetA.getAtomContainerCount() - 1);
atom2.setProperty(CDKConstants.PART_OF_RING_OF_SIZE, Integer.valueOf(sring.getRingSize()));
atom2.setProperty(
CDKConstants.CHEMICAL_GROUP_CONSTANT,
Integer.valueOf(ringSystemClassifier(sring, getSubgraphSmiles(sring, molecule))));
atom2.setFlag(CDKConstants.ISINRING, true);
atom2.setFlag(CDKConstants.ISALIPHATIC, false);
} else {
atom2.setProperty(CDKConstants.CHEMICAL_GROUP_CONSTANT, Integer.valueOf(CDKConstants.ISNOTINRING));
atom2.setFlag(CDKConstants.ISINRING, false);
atom2.setFlag(CDKConstants.ISALIPHATIC, true);
}
try {
hoseCode = hcg.getHOSECode(molecule, atom2, 3);
hoseCode = removeAromaticityFlagsFromHoseCode(hoseCode);
atom2.setProperty(CDKConstants.SPHERICAL_MATCHER, hoseCode);
} catch (CDKException ex1) {
throw new CDKException("Could not build HOSECode from atom " + i + " due to " + ex1.toString(), ex1);
}
}
return ringSetMolecule;
} | [
"public",
"IRingSet",
"assignAtomTypePropertiesToAtom",
"(",
"IAtomContainer",
"molecule",
",",
"boolean",
"aromaticity",
")",
"throws",
"Exception",
"{",
"SmilesGenerator",
"sg",
"=",
"new",
"SmilesGenerator",
"(",
")",
";",
"//logger.debug(\"assignAtomTypePropertiesToAtom... | Method assigns certain properties to an atom. Necessary for the atom type matching
Properties:
<ul>
<li>aromaticity)
<li>ChemicalGroup (CDKChemicalRingGroupConstant)
<li>SSSR
<li>Ring/Group, ringSize, aromaticity
<li>SphericalMatcher (HoSe Code)
</ul>
@param aromaticity boolean true/false true if aromaticity should be calculated
@return sssrf ringSetofTheMolecule
@exception Exception Description of the Exception | [
"Method",
"assigns",
"certain",
"properties",
"to",
"an",
"atom",
".",
"Necessary",
"for",
"the",
"atom",
"type",
"matching",
"Properties",
":",
"<ul",
">",
"<li",
">",
"aromaticity",
")",
"<li",
">",
"ChemicalGroup",
"(",
"CDKChemicalRingGroupConstant",
")",
... | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/misc/extra/src/main/java/org/openscience/cdk/tools/AtomTypeTools.java#L85-L133 |
auth0/Auth0.Android | auth0/src/main/java/com/auth0/android/authentication/AuthenticationAPIClient.java | AuthenticationAPIClient.signUp | @SuppressWarnings("WeakerAccess")
public SignUpRequest signUp(@NonNull String email, @NonNull String password, @NonNull String username, @NonNull String connection) {
final DatabaseConnectionRequest<DatabaseUser, AuthenticationException> createUserRequest = createUser(email, password, username, connection);
final AuthenticationRequest authenticationRequest = login(email, password, connection);
return new SignUpRequest(createUserRequest, authenticationRequest);
} | java | @SuppressWarnings("WeakerAccess")
public SignUpRequest signUp(@NonNull String email, @NonNull String password, @NonNull String username, @NonNull String connection) {
final DatabaseConnectionRequest<DatabaseUser, AuthenticationException> createUserRequest = createUser(email, password, username, connection);
final AuthenticationRequest authenticationRequest = login(email, password, connection);
return new SignUpRequest(createUserRequest, authenticationRequest);
} | [
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"public",
"SignUpRequest",
"signUp",
"(",
"@",
"NonNull",
"String",
"email",
",",
"@",
"NonNull",
"String",
"password",
",",
"@",
"NonNull",
"String",
"username",
",",
"@",
"NonNull",
"String",
"connection",... | Creates a user in a DB connection using <a href="https://auth0.com/docs/api/authentication#signup">'/dbconnections/signup' endpoint</a>
and then logs in the user. How the user is logged in depends on the {@link Auth0#isOIDCConformant()} flag.
Example usage:
<pre>
{@code
client.signUp("{email}", "{password}", "{username}", "{database connection name}")
.start(new BaseCallback<Credentials>() {
{@literal}Override
public void onSuccess(Credentials payload) {}
{@literal}Override
public void onFailure(AuthenticationException error) {}
});
}
</pre>
@param email of the user and must be non null
@param password of the user and must be non null
@param username of the user and must be non null
@param connection of the database to sign up with
@return a request to configure and start that will yield {@link Credentials} | [
"Creates",
"a",
"user",
"in",
"a",
"DB",
"connection",
"using",
"<a",
"href",
"=",
"https",
":",
"//",
"auth0",
".",
"com",
"/",
"docs",
"/",
"api",
"/",
"authentication#signup",
">",
"/",
"dbconnections",
"/",
"signup",
"endpoint<",
"/",
"a",
">",
"an... | train | https://github.com/auth0/Auth0.Android/blob/ee37b7f94d989c1fbab2cb1378c87fdcaf7a8156/auth0/src/main/java/com/auth0/android/authentication/AuthenticationAPIClient.java#L587-L593 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.