repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/DatasourceJBossASClient.java
DatasourceJBossASClient.createNewDatasourceRequest
public ModelNode createNewDatasourceRequest(String name, int blockingTimeoutWaitMillis, String connectionUrlExpression, String driverName, String exceptionSorterClassName, int idleTimeoutMinutes, boolean jta, int minPoolSize, int maxPoolSize, int preparedStatementCacheSize, String securityDomain, String staleConnectionCheckerClassName, String transactionIsolation, String validConnectionCheckerClassName, boolean validateOnMatch, Map<String, String> connectionProperties) { String jndiName = "java:jboss/datasources/" + name; String dmrTemplate = "" // + "{" // + "\"blocking-timeout-wait-millis\" => %dL " // + ", \"connection-url\" => expression \"%s\" " // + ", \"driver-name\" => \"%s\" " // + ", \"exception-sorter-class-name\" => \"%s\" " // + ", \"idle-timeout-minutes\" => %dL " // + ", \"jndi-name\" => \"%s\" " // + ", \"jta\" => %s " // + ", \"min-pool-size\" => %d " // + ", \"max-pool-size\" => %d " // + ", \"prepared-statements-cache-size\" => %dL " // + ", \"security-domain\" => \"%s\" " // + ", \"stale-connection-checker-class-name\" => \"%s\" " // + ", \"transaction-isolation\" => \"%s\" " // + ", \"use-java-context\" => true " // + ", \"valid-connection-checker-class-name\" => \"%s\" " // + ", \"validate-on-match\" => %s " // + "}"; String dmr = String.format(dmrTemplate, blockingTimeoutWaitMillis, connectionUrlExpression, driverName, exceptionSorterClassName, idleTimeoutMinutes, jndiName, jta, minPoolSize, maxPoolSize, preparedStatementCacheSize, securityDomain, staleConnectionCheckerClassName, transactionIsolation, validConnectionCheckerClassName, validateOnMatch); Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_DATASOURCES, DATA_SOURCE, name); final ModelNode request1 = ModelNode.fromString(dmr); request1.get(OPERATION).set(ADD); request1.get(ADDRESS).set(addr.getAddressNode()); // if there are no conn properties, no need to create a batch request, there is only one ADD request to make if (connectionProperties == null || connectionProperties.size() == 0) { return request1; } // create a batch of requests - the first is the main one, the rest create each conn property ModelNode[] batch = new ModelNode[1 + connectionProperties.size()]; batch[0] = request1; int n = 1; for (Map.Entry<String, String> entry : connectionProperties.entrySet()) { addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_DATASOURCES, DATA_SOURCE, name, CONNECTION_PROPERTIES, entry.getKey()); final ModelNode requestN = new ModelNode(); requestN.get(OPERATION).set(ADD); requestN.get(ADDRESS).set(addr.getAddressNode()); setPossibleExpression(requestN, VALUE, entry.getValue()); batch[n++] = requestN; } return createBatchRequest(batch); }
java
public ModelNode createNewDatasourceRequest(String name, int blockingTimeoutWaitMillis, String connectionUrlExpression, String driverName, String exceptionSorterClassName, int idleTimeoutMinutes, boolean jta, int minPoolSize, int maxPoolSize, int preparedStatementCacheSize, String securityDomain, String staleConnectionCheckerClassName, String transactionIsolation, String validConnectionCheckerClassName, boolean validateOnMatch, Map<String, String> connectionProperties) { String jndiName = "java:jboss/datasources/" + name; String dmrTemplate = "" // + "{" // + "\"blocking-timeout-wait-millis\" => %dL " // + ", \"connection-url\" => expression \"%s\" " // + ", \"driver-name\" => \"%s\" " // + ", \"exception-sorter-class-name\" => \"%s\" " // + ", \"idle-timeout-minutes\" => %dL " // + ", \"jndi-name\" => \"%s\" " // + ", \"jta\" => %s " // + ", \"min-pool-size\" => %d " // + ", \"max-pool-size\" => %d " // + ", \"prepared-statements-cache-size\" => %dL " // + ", \"security-domain\" => \"%s\" " // + ", \"stale-connection-checker-class-name\" => \"%s\" " // + ", \"transaction-isolation\" => \"%s\" " // + ", \"use-java-context\" => true " // + ", \"valid-connection-checker-class-name\" => \"%s\" " // + ", \"validate-on-match\" => %s " // + "}"; String dmr = String.format(dmrTemplate, blockingTimeoutWaitMillis, connectionUrlExpression, driverName, exceptionSorterClassName, idleTimeoutMinutes, jndiName, jta, minPoolSize, maxPoolSize, preparedStatementCacheSize, securityDomain, staleConnectionCheckerClassName, transactionIsolation, validConnectionCheckerClassName, validateOnMatch); Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_DATASOURCES, DATA_SOURCE, name); final ModelNode request1 = ModelNode.fromString(dmr); request1.get(OPERATION).set(ADD); request1.get(ADDRESS).set(addr.getAddressNode()); // if there are no conn properties, no need to create a batch request, there is only one ADD request to make if (connectionProperties == null || connectionProperties.size() == 0) { return request1; } // create a batch of requests - the first is the main one, the rest create each conn property ModelNode[] batch = new ModelNode[1 + connectionProperties.size()]; batch[0] = request1; int n = 1; for (Map.Entry<String, String> entry : connectionProperties.entrySet()) { addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_DATASOURCES, DATA_SOURCE, name, CONNECTION_PROPERTIES, entry.getKey()); final ModelNode requestN = new ModelNode(); requestN.get(OPERATION).set(ADD); requestN.get(ADDRESS).set(addr.getAddressNode()); setPossibleExpression(requestN, VALUE, entry.getValue()); batch[n++] = requestN; } return createBatchRequest(batch); }
[ "public", "ModelNode", "createNewDatasourceRequest", "(", "String", "name", ",", "int", "blockingTimeoutWaitMillis", ",", "String", "connectionUrlExpression", ",", "String", "driverName", ",", "String", "exceptionSorterClassName", ",", "int", "idleTimeoutMinutes", ",", "b...
Returns a ModelNode that can be used to create a datasource. Callers are free to tweak the datasource request that is returned, if they so choose, before asking the client to execute the request. @param name the name of the datasource @param blockingTimeoutWaitMillis see datasource documentation for meaning of this setting @param connectionUrlExpression see datasource documentation for meaning of this setting @param driverName see datasource documentation for meaning of this setting @param exceptionSorterClassName see datasource documentation for meaning of this setting @param idleTimeoutMinutes see datasource documentation for meaning of this setting @param jta true if this DS should support transactions; false if not @param minPoolSize see datasource documentation for meaning of this setting @param maxPoolSize see datasource documentation for meaning of this setting @param preparedStatementCacheSize see datasource documentation for meaning of this setting @param securityDomain see datasource documentation for meaning of this setting @param staleConnectionCheckerClassName see datasource documentation for meaning of this setting @param transactionIsolation see datasource documentation for meaning of this setting @param validConnectionCheckerClassName see datasource documentation for meaning of this setting @param validateOnMatch see datasource documentation for meaning of this setting @param connectionProperties see datasource documentation for meaning of this setting @return the request that can be used to create the datasource
[ "Returns", "a", "ModelNode", "that", "can", "be", "used", "to", "create", "a", "datasource", ".", "Callers", "are", "free", "to", "tweak", "the", "datasource", "request", "that", "is", "returned", "if", "they", "so", "choose", "before", "asking", "the", "c...
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/DatasourceJBossASClient.java#L333-L391
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/ProtocolService.java
ProtocolService.add
public void add(EndpointService<L, S> newEndpointService) { if (newEndpointService == null) { throw new IllegalArgumentException("New endpoint service must not be null"); } synchronized (this.inventoryListeners) { for (InventoryListener listener : this.inventoryListeners) { newEndpointService.addInventoryListener(listener); } } endpointServices.put(newEndpointService.getMonitoredEndpoint().getName(), newEndpointService); newEndpointService.start(); log.infoAddedEndpointService(newEndpointService.toString()); newEndpointService.discoverAll(); }
java
public void add(EndpointService<L, S> newEndpointService) { if (newEndpointService == null) { throw new IllegalArgumentException("New endpoint service must not be null"); } synchronized (this.inventoryListeners) { for (InventoryListener listener : this.inventoryListeners) { newEndpointService.addInventoryListener(listener); } } endpointServices.put(newEndpointService.getMonitoredEndpoint().getName(), newEndpointService); newEndpointService.start(); log.infoAddedEndpointService(newEndpointService.toString()); newEndpointService.discoverAll(); }
[ "public", "void", "add", "(", "EndpointService", "<", "L", ",", "S", ">", "newEndpointService", ")", "{", "if", "(", "newEndpointService", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"New endpoint service must not be null\"", ")", ";...
This will add a new endpoint service to the list. Once added, the new service will immediately be started. @param newEndpointService the new service to add and start
[ "This", "will", "add", "a", "new", "endpoint", "service", "to", "the", "list", ".", "Once", "added", "the", "new", "service", "will", "immediately", "be", "started", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/ProtocolService.java#L134-L150
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/ProtocolService.java
ProtocolService.remove
public void remove(String name) { EndpointService<L, S> service = endpointServices.remove(name); if (service != null) { service.stop(); log.infoRemovedEndpointService(service.toString()); } }
java
public void remove(String name) { EndpointService<L, S> service = endpointServices.remove(name); if (service != null) { service.stop(); log.infoRemovedEndpointService(service.toString()); } }
[ "public", "void", "remove", "(", "String", "name", ")", "{", "EndpointService", "<", "L", ",", "S", ">", "service", "=", "endpointServices", ".", "remove", "(", "name", ")", ";", "if", "(", "service", "!=", "null", ")", "{", "service", ".", "stop", "...
This will stop the given endpoint service and remove it from the list of endpoint services. @param name identifies the endpoint service to remove
[ "This", "will", "stop", "the", "given", "endpoint", "service", "and", "remove", "it", "from", "the", "list", "of", "endpoint", "services", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/ProtocolService.java#L157-L163
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/util/BaseHttpClientGenerator.java
BaseHttpClientGenerator.createWebSocketCall
public WebSocketCall createWebSocketCall(String url, Map<String, String> headers) { String base64Credentials = buildBase64Credentials(); Request.Builder requestBuilder = new Request.Builder() .url(url) .addHeader("Authorization", "Basic " + base64Credentials) .addHeader("Accept", "application/json"); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { requestBuilder.addHeader(header.getKey(), header.getValue()); } } Request request = requestBuilder.build(); WebSocketCall wsc = WebSocketCall.create(getHttpClient(), request); return wsc; }
java
public WebSocketCall createWebSocketCall(String url, Map<String, String> headers) { String base64Credentials = buildBase64Credentials(); Request.Builder requestBuilder = new Request.Builder() .url(url) .addHeader("Authorization", "Basic " + base64Credentials) .addHeader("Accept", "application/json"); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { requestBuilder.addHeader(header.getKey(), header.getValue()); } } Request request = requestBuilder.build(); WebSocketCall wsc = WebSocketCall.create(getHttpClient(), request); return wsc; }
[ "public", "WebSocketCall", "createWebSocketCall", "(", "String", "url", ",", "Map", "<", "String", ",", "String", ">", "headers", ")", "{", "String", "base64Credentials", "=", "buildBase64Credentials", "(", ")", ";", "Request", ".", "Builder", "requestBuilder", ...
Creates a websocket that connects to the given URL. @param url where the websocket server is @param headers headers to pass in the connect request @return the websocket
[ "Creates", "a", "websocket", "that", "connects", "to", "the", "given", "URL", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/util/BaseHttpClientGenerator.java#L264-L281
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/service/AgentCoreEngine.java
AgentCoreEngine.stopHawkularAgent
public void stopHawkularAgent() { synchronized (agentServiceStatus) { if (agentServiceStatus.get() == ServiceStatus.STOPPED) { log.infoStoppedAlready(); return; // we are already stopped } else if (agentServiceStatus.get() == ServiceStatus.STOPPING) { // some other thread is already stopping the agent - wait for that to finish and just return while (agentServiceStatus.get() == ServiceStatus.STOPPING) { try { agentServiceStatus.wait(30000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } return; } } setStatus(ServiceStatus.STOPPING); } log.infoStopping(); AtomicReference<Throwable> error = new AtomicReference<>(null); // will hold the first error we encountered try { // stop the metrics exporter endpoint try { stopMetricsExporter(); } catch (Throwable t) { error.compareAndSet(null, t); log.debug("Cannot shutdown metrics exporter but will continue shutdown", t); } // disconnect from the feed comm channel try { if (feedComm != null) { feedComm.destroy(); feedComm = null; } } catch (Throwable t) { error.compareAndSet(null, t); log.debug("Cannot shutdown feed comm but will continue shutdown", t); } // stop our normal protocol services try { if (protocolServices != null) { protocolServices.stop(); if (inventoryStorageProxy != null) { protocolServices.removeInventoryListener(inventoryStorageProxy); } if (platformMBeanGenerator != null) { platformMBeanGenerator.unregisterAllMBeans(); } if (notificationDispatcher != null) { protocolServices.removeInventoryListener(notificationDispatcher); } protocolServices = null; } } catch (Throwable t) { error.compareAndSet(null, t); log.debug("Cannot shutdown protocol services but will continue shutdown", t); } // now stop the storage adapter try { if (storageAdapter != null) { storageAdapter.shutdown(); storageAdapter = null; } } catch (Throwable t) { error.compareAndSet(null, t); log.debug("Cannot shutdown storage adapter but will continue shutdown", t); } // stop diagnostic reporting and spit out a final diagnostics report if (diagnosticsReporter != null) { diagnosticsReporter.stop(); if (configuration.getDiagnostics().isEnabled()) { diagnosticsReporter.report(); } diagnosticsReporter = null; } // allow subclasses to cleanup try { cleanupDuringStop(); } catch (Exception e) { error.compareAndSet(null, e); log.debug("Cannot shutdown - subclass exception", e); } // We attempted to clean everything we could. If we hit an error, throw it to log our shutdown wasn't clean if (error.get() != null) { throw error.get(); } } catch (Throwable t) { log.warnFailedToStopAgent(t); } finally { setStatus(ServiceStatus.STOPPED); } }
java
public void stopHawkularAgent() { synchronized (agentServiceStatus) { if (agentServiceStatus.get() == ServiceStatus.STOPPED) { log.infoStoppedAlready(); return; // we are already stopped } else if (agentServiceStatus.get() == ServiceStatus.STOPPING) { // some other thread is already stopping the agent - wait for that to finish and just return while (agentServiceStatus.get() == ServiceStatus.STOPPING) { try { agentServiceStatus.wait(30000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } return; } } setStatus(ServiceStatus.STOPPING); } log.infoStopping(); AtomicReference<Throwable> error = new AtomicReference<>(null); // will hold the first error we encountered try { // stop the metrics exporter endpoint try { stopMetricsExporter(); } catch (Throwable t) { error.compareAndSet(null, t); log.debug("Cannot shutdown metrics exporter but will continue shutdown", t); } // disconnect from the feed comm channel try { if (feedComm != null) { feedComm.destroy(); feedComm = null; } } catch (Throwable t) { error.compareAndSet(null, t); log.debug("Cannot shutdown feed comm but will continue shutdown", t); } // stop our normal protocol services try { if (protocolServices != null) { protocolServices.stop(); if (inventoryStorageProxy != null) { protocolServices.removeInventoryListener(inventoryStorageProxy); } if (platformMBeanGenerator != null) { platformMBeanGenerator.unregisterAllMBeans(); } if (notificationDispatcher != null) { protocolServices.removeInventoryListener(notificationDispatcher); } protocolServices = null; } } catch (Throwable t) { error.compareAndSet(null, t); log.debug("Cannot shutdown protocol services but will continue shutdown", t); } // now stop the storage adapter try { if (storageAdapter != null) { storageAdapter.shutdown(); storageAdapter = null; } } catch (Throwable t) { error.compareAndSet(null, t); log.debug("Cannot shutdown storage adapter but will continue shutdown", t); } // stop diagnostic reporting and spit out a final diagnostics report if (diagnosticsReporter != null) { diagnosticsReporter.stop(); if (configuration.getDiagnostics().isEnabled()) { diagnosticsReporter.report(); } diagnosticsReporter = null; } // allow subclasses to cleanup try { cleanupDuringStop(); } catch (Exception e) { error.compareAndSet(null, e); log.debug("Cannot shutdown - subclass exception", e); } // We attempted to clean everything we could. If we hit an error, throw it to log our shutdown wasn't clean if (error.get() != null) { throw error.get(); } } catch (Throwable t) { log.warnFailedToStopAgent(t); } finally { setStatus(ServiceStatus.STOPPED); } }
[ "public", "void", "stopHawkularAgent", "(", ")", "{", "synchronized", "(", "agentServiceStatus", ")", "{", "if", "(", "agentServiceStatus", ".", "get", "(", ")", "==", "ServiceStatus", ".", "STOPPED", ")", "{", "log", ".", "infoStoppedAlready", "(", ")", ";"...
Stops this service. If the service is already stopped, this method is a no-op.
[ "Stops", "this", "service", ".", "If", "the", "service", "is", "already", "stopped", "this", "method", "is", "a", "no", "-", "op", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/service/AgentCoreEngine.java#L375-L477
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/service/AgentCoreEngine.java
AgentCoreEngine.startStorageAdapter
private void startStorageAdapter() throws Exception { // create the storage adapter that will write our metrics/inventory data to backend storage on server this.storageAdapter = new HawkularStorageAdapter(); this.storageAdapter.initialize( feedId, configuration.getStorageAdapter(), diagnostics, httpClientBuilder); // provide our storage adapter to the proxies - allows external apps to use them to store its own data inventoryStorageProxy.setStorageAdapter(storageAdapter); // log our own diagnostic reports this.diagnosticsReporter = JBossLoggingReporter.forRegistry(this.diagnostics.getMetricRegistry()) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .outputTo(Logger.getLogger(getClass())) .withLoggingLevel(LoggingLevel.DEBUG) .build(); if (this.configuration.getDiagnostics().isEnabled()) { diagnosticsReporter.start(this.configuration.getDiagnostics().getInterval(), this.configuration.getDiagnostics().getTimeUnits()); } }
java
private void startStorageAdapter() throws Exception { // create the storage adapter that will write our metrics/inventory data to backend storage on server this.storageAdapter = new HawkularStorageAdapter(); this.storageAdapter.initialize( feedId, configuration.getStorageAdapter(), diagnostics, httpClientBuilder); // provide our storage adapter to the proxies - allows external apps to use them to store its own data inventoryStorageProxy.setStorageAdapter(storageAdapter); // log our own diagnostic reports this.diagnosticsReporter = JBossLoggingReporter.forRegistry(this.diagnostics.getMetricRegistry()) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .outputTo(Logger.getLogger(getClass())) .withLoggingLevel(LoggingLevel.DEBUG) .build(); if (this.configuration.getDiagnostics().isEnabled()) { diagnosticsReporter.start(this.configuration.getDiagnostics().getInterval(), this.configuration.getDiagnostics().getTimeUnits()); } }
[ "private", "void", "startStorageAdapter", "(", ")", "throws", "Exception", "{", "// create the storage adapter that will write our metrics/inventory data to backend storage on server", "this", ".", "storageAdapter", "=", "new", "HawkularStorageAdapter", "(", ")", ";", "this", "...
Creates and starts the storage adapter that will be used to store our inventory data and monitoring data. @throws Exception if failed to start the storage adapter
[ "Creates", "and", "starts", "the", "storage", "adapter", "that", "will", "be", "used", "to", "store", "our", "inventory", "data", "and", "monitoring", "data", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/service/AgentCoreEngine.java#L484-L508
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/Resource.java
Resource.builder
public static <L> Builder<L> builder(Resource<L> template) { return new Builder<L>(template); }
java
public static <L> Builder<L> builder(Resource<L> template) { return new Builder<L>(template); }
[ "public", "static", "<", "L", ">", "Builder", "<", "L", ">", "builder", "(", "Resource", "<", "L", ">", "template", ")", "{", "return", "new", "Builder", "<", "L", ">", "(", "template", ")", ";", "}" ]
Creates a builder with the given resource as a starting template. You can use this to clone a resource as well as build a resource that looks similar to the given template resource. @param template start with the data found in the given template resource
[ "Creates", "a", "builder", "with", "the", "given", "resource", "as", "a", "starting", "template", ".", "You", "can", "use", "this", "to", "clone", "a", "resource", "as", "well", "as", "build", "a", "resource", "that", "looks", "similar", "to", "the", "gi...
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/Resource.java#L95-L97
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/ResourceManager.java
ResourceManager.addResource
public AddResult<L> addResource(Resource<L> newResource) throws IllegalArgumentException { AddResult<L> result; graphLockWrite.lock(); try { // Need to make sure we keep our resources consistent. If the newResource has a parent, // and that parent is not the same instance we have in our graph, we need to recreate the // newResource such that it refers to our instance of the parent. // Do this BEFORE we attempt to add the new resource to the graph. if (newResource.getParent() != null) { Resource<L> parentInGraph = getResource(newResource.getParent().getID()); if (parentInGraph == null) { throw new IllegalArgumentException( String.format("The new resource [%s] has a parent [%s] that has not been added yet", newResource, newResource.getParent())); } // if parents are not the same instance, create a new resource with the parent we have in the graph if (parentInGraph != newResource.getParent()) { newResource = Resource.<L> builder(newResource).parent(parentInGraph).build(); } } boolean added = this.resourcesGraph.addVertex(newResource); if (!added) { // Looks like this resource already exists. // If the resource changed, we want to replace it but keep all edges intact. // If the resource did not change, we don't do anything. Resource<L> oldResource = getResource(newResource.getID()); if (new ResourceComparator().compare(oldResource, newResource) != 0) { Set<Resource<L>> children = getChildren(oldResource); this.resourcesGraph.removeVertex(oldResource); // removes all edges! remember to put parent back this.resourcesGraph.addVertex(newResource); for (Resource<L> child : children) { ResourceManager.this.resourcesGraph.addEdge(newResource, child); } result = new AddResult<>(AddResult.Effect.MODIFIED, newResource); } else { result = new AddResult<>(AddResult.Effect.UNCHANGED, oldResource); } } else { result = new AddResult<>(AddResult.Effect.ADDED, newResource); } if ((result.getEffect() != AddResult.Effect.UNCHANGED) && (newResource.getParent() != null)) { this.resourcesGraph.addEdge(newResource.getParent(), newResource); } return result; } finally { graphLockWrite.unlock(); } }
java
public AddResult<L> addResource(Resource<L> newResource) throws IllegalArgumentException { AddResult<L> result; graphLockWrite.lock(); try { // Need to make sure we keep our resources consistent. If the newResource has a parent, // and that parent is not the same instance we have in our graph, we need to recreate the // newResource such that it refers to our instance of the parent. // Do this BEFORE we attempt to add the new resource to the graph. if (newResource.getParent() != null) { Resource<L> parentInGraph = getResource(newResource.getParent().getID()); if (parentInGraph == null) { throw new IllegalArgumentException( String.format("The new resource [%s] has a parent [%s] that has not been added yet", newResource, newResource.getParent())); } // if parents are not the same instance, create a new resource with the parent we have in the graph if (parentInGraph != newResource.getParent()) { newResource = Resource.<L> builder(newResource).parent(parentInGraph).build(); } } boolean added = this.resourcesGraph.addVertex(newResource); if (!added) { // Looks like this resource already exists. // If the resource changed, we want to replace it but keep all edges intact. // If the resource did not change, we don't do anything. Resource<L> oldResource = getResource(newResource.getID()); if (new ResourceComparator().compare(oldResource, newResource) != 0) { Set<Resource<L>> children = getChildren(oldResource); this.resourcesGraph.removeVertex(oldResource); // removes all edges! remember to put parent back this.resourcesGraph.addVertex(newResource); for (Resource<L> child : children) { ResourceManager.this.resourcesGraph.addEdge(newResource, child); } result = new AddResult<>(AddResult.Effect.MODIFIED, newResource); } else { result = new AddResult<>(AddResult.Effect.UNCHANGED, oldResource); } } else { result = new AddResult<>(AddResult.Effect.ADDED, newResource); } if ((result.getEffect() != AddResult.Effect.UNCHANGED) && (newResource.getParent() != null)) { this.resourcesGraph.addEdge(newResource.getParent(), newResource); } return result; } finally { graphLockWrite.unlock(); } }
[ "public", "AddResult", "<", "L", ">", "addResource", "(", "Resource", "<", "L", ">", "newResource", ")", "throws", "IllegalArgumentException", "{", "AddResult", "<", "L", ">", "result", ";", "graphLockWrite", ".", "lock", "(", ")", ";", "try", "{", "// Nee...
Adds the given resource to the resource hierarchy, replacing the resource if it already exist but has changed. If the resource is a child of a parent, that parent must already be known or an exception is thrown. The return value's {@link AddResult#getEffect() effect} has the following semantics: <ul> <li>ADDED means the resource was new and was added to the inventory.</li> <li>MODIFIED means the resource was already in inventory but is different from before and so inventory was updated.</li> <li>UNCHANGED means the resource was already in inventory and is the same.</li> </ul> The return value's {@link AddResult#getResource() resource} is the resource object stored in the internal hierarchical graph, which may or may not be the same as the <code>newResource</code> that was passed into this method. @param newResource the new resource to be added @return the results - see above for a detailed description of these results @throws IllegalArgumentException if the new resource's parent does not yet exist in the hierarchy
[ "Adds", "the", "given", "resource", "to", "the", "resource", "hierarchy", "replacing", "the", "resource", "if", "it", "already", "exist", "but", "has", "changed", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/ResourceManager.java#L223-L278
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/ResourceManager.java
ResourceManager.getParent
public Resource<L> getParent(Resource<L> resource) { // do NOT call resource.getParent(), we want the one in our graph, not the one in the resource object graphLockRead.lock(); try { Set<Resource<L>> directParents = neighborIndex.predecessorsOf(resource); if (directParents.isEmpty()) { return null; } return directParents.iterator().next(); } finally { graphLockRead.unlock(); } }
java
public Resource<L> getParent(Resource<L> resource) { // do NOT call resource.getParent(), we want the one in our graph, not the one in the resource object graphLockRead.lock(); try { Set<Resource<L>> directParents = neighborIndex.predecessorsOf(resource); if (directParents.isEmpty()) { return null; } return directParents.iterator().next(); } finally { graphLockRead.unlock(); } }
[ "public", "Resource", "<", "L", ">", "getParent", "(", "Resource", "<", "L", ">", "resource", ")", "{", "// do NOT call resource.getParent(), we want the one in our graph, not the one in the resource object", "graphLockRead", ".", "lock", "(", ")", ";", "try", "{", "Set...
Returns the direct parent of the given resource. This examines the internal hierarchical graph to determine parentage. @param resource the resource whose parent is to be returned @return the direct parent of the given resource, or null if this is a root resource without a parent @throws IllegalArgumentException if the resource itself is not found in the graph
[ "Returns", "the", "direct", "parent", "of", "the", "given", "resource", ".", "This", "examines", "the", "internal", "hierarchical", "graph", "to", "determine", "parentage", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/ResourceManager.java#L355-L367
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/ResourceManager.java
ResourceManager.getAllDescendants
private void getAllDescendants(Resource<L> parent, List<Resource<L>> descendants) { for (Resource<L> child : getChildren(parent)) { if (!descendants.contains(child)) { getAllDescendants(child, descendants); descendants.add(child); } } return; }
java
private void getAllDescendants(Resource<L> parent, List<Resource<L>> descendants) { for (Resource<L> child : getChildren(parent)) { if (!descendants.contains(child)) { getAllDescendants(child, descendants); descendants.add(child); } } return; }
[ "private", "void", "getAllDescendants", "(", "Resource", "<", "L", ">", "parent", ",", "List", "<", "Resource", "<", "L", ">", ">", "descendants", ")", "{", "for", "(", "Resource", "<", "L", ">", "child", ":", "getChildren", "(", "parent", ")", ")", ...
make sure you call this with a graph lock - either read or write
[ "make", "sure", "you", "call", "this", "with", "a", "graph", "lock", "-", "either", "read", "or", "write" ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/ResourceManager.java#L537-L545
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/dmr/StatisticsControl.java
StatisticsControl.getDomainHostServers
private List<String> getDomainHostServers(ModelControllerClient mcc, String hostName) { return getChildrenNames(PathAddress.EMPTY_ADDRESS.append("host", hostName), "server", mcc); }
java
private List<String> getDomainHostServers(ModelControllerClient mcc, String hostName) { return getChildrenNames(PathAddress.EMPTY_ADDRESS.append("host", hostName), "server", mcc); }
[ "private", "List", "<", "String", ">", "getDomainHostServers", "(", "ModelControllerClient", "mcc", ",", "String", "hostName", ")", "{", "return", "getChildrenNames", "(", "PathAddress", ".", "EMPTY_ADDRESS", ".", "append", "(", "\"host\"", ",", "hostName", ")", ...
returns empty list if not in domain mode
[ "returns", "empty", "list", "if", "not", "in", "domain", "mode" ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/dmr/StatisticsControl.java#L194-L196
train
hawkular/hawkular-agent
hawkular-javaagent/src/main/java/org/hawkular/agent/javaagent/JavaAgent.java
JavaAgent.main
public static void main(String[] args) { try { start(args); } catch (Exception e) { System.err.println("Hawkular Java Agent failed at startup"); e.printStackTrace(System.err); return; } // so main doesn't exit synchronized (JavaAgent.class) { try { JavaAgent.class.wait(); } catch (InterruptedException e) { } } }
java
public static void main(String[] args) { try { start(args); } catch (Exception e) { System.err.println("Hawkular Java Agent failed at startup"); e.printStackTrace(System.err); return; } // so main doesn't exit synchronized (JavaAgent.class) { try { JavaAgent.class.wait(); } catch (InterruptedException e) { } } }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "try", "{", "start", "(", "args", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "System", ".", "err", ".", "println", "(", "\"Hawkular Java Agent failed at startup\...
an agent can be started in its own VM as the main class
[ "an", "agent", "can", "be", "started", "in", "its", "own", "VM", "as", "the", "main", "class" ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-javaagent/src/main/java/org/hawkular/agent/javaagent/JavaAgent.java#L26-L42
train
hawkular/hawkular-agent
hawkular-javaagent/src/main/java/org/hawkular/agent/javaagent/JavaAgent.java
JavaAgent.premain
public static void premain(String args) { if (args == null) { args = "config=config.yaml"; } try { start(args.split(",")); } catch (Exception e) { System.err.println("Hawkular Java Agent failed at startup"); e.printStackTrace(System.err); } }
java
public static void premain(String args) { if (args == null) { args = "config=config.yaml"; } try { start(args.split(",")); } catch (Exception e) { System.err.println("Hawkular Java Agent failed at startup"); e.printStackTrace(System.err); } }
[ "public", "static", "void", "premain", "(", "String", "args", ")", "{", "if", "(", "args", "==", "null", ")", "{", "args", "=", "\"config=config.yaml\"", ";", "}", "try", "{", "start", "(", "args", ".", "split", "(", "\",\"", ")", ")", ";", "}", "c...
an agent can be started in a VM as a javaagent allowing it to be embedded with some other main app
[ "an", "agent", "can", "be", "started", "in", "a", "VM", "as", "a", "javaagent", "allowing", "it", "to", "be", "embedded", "with", "some", "other", "main", "app" ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-javaagent/src/main/java/org/hawkular/agent/javaagent/JavaAgent.java#L45-L56
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/util/Util.java
Util.ensureEndsWithSlash
public static void ensureEndsWithSlash(StringBuilder str) { if (str.length() == 0 || str.charAt(str.length() - 1) != '/') { str.append('/'); } }
java
public static void ensureEndsWithSlash(StringBuilder str) { if (str.length() == 0 || str.charAt(str.length() - 1) != '/') { str.append('/'); } }
[ "public", "static", "void", "ensureEndsWithSlash", "(", "StringBuilder", "str", ")", "{", "if", "(", "str", ".", "length", "(", ")", "==", "0", "||", "str", ".", "charAt", "(", "str", ".", "length", "(", ")", "-", "1", ")", "!=", "'", "'", ")", "...
Given a string builder, this ensures its last character is a forward-slash. @param str string builder to have a forward-slash character as its last when this method returns
[ "Given", "a", "string", "builder", "this", "ensures", "its", "last", "character", "is", "a", "forward", "-", "slash", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/util/Util.java#L174-L178
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/util/Util.java
Util.copyStream
public static long copyStream(InputStream input, OutputStream output, boolean closeStreams) throws RuntimeException { long numBytesCopied = 0; int bufferSize = BUFFER_SIZE; try { // make sure we buffer the input input = new BufferedInputStream(input, bufferSize); byte[] buffer = new byte[bufferSize]; for (int bytesRead = input.read(buffer); bytesRead != -1; bytesRead = input.read(buffer)) { output.write(buffer, 0, bytesRead); numBytesCopied += bytesRead; } output.flush(); } catch (IOException ioe) { throw new RuntimeException("Stream data cannot be copied", ioe); } finally { if (closeStreams) { try { output.close(); } catch (IOException ioe2) { // what to do? } try { input.close(); } catch (IOException ioe2) { // what to do? } } } return numBytesCopied; }
java
public static long copyStream(InputStream input, OutputStream output, boolean closeStreams) throws RuntimeException { long numBytesCopied = 0; int bufferSize = BUFFER_SIZE; try { // make sure we buffer the input input = new BufferedInputStream(input, bufferSize); byte[] buffer = new byte[bufferSize]; for (int bytesRead = input.read(buffer); bytesRead != -1; bytesRead = input.read(buffer)) { output.write(buffer, 0, bytesRead); numBytesCopied += bytesRead; } output.flush(); } catch (IOException ioe) { throw new RuntimeException("Stream data cannot be copied", ioe); } finally { if (closeStreams) { try { output.close(); } catch (IOException ioe2) { // what to do? } try { input.close(); } catch (IOException ioe2) { // what to do? } } } return numBytesCopied; }
[ "public", "static", "long", "copyStream", "(", "InputStream", "input", ",", "OutputStream", "output", ",", "boolean", "closeStreams", ")", "throws", "RuntimeException", "{", "long", "numBytesCopied", "=", "0", ";", "int", "bufferSize", "=", "BUFFER_SIZE", ";", "...
Copies one stream to another, optionally closing the streams. @param input the data to copy @param output where to copy the data @param closeStreams if true input and output will be closed when the method returns @return the number of bytes copied @throws RuntimeException if the copy failed
[ "Copies", "one", "stream", "to", "another", "optionally", "closing", "the", "streams", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/util/Util.java#L189-L219
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/util/Util.java
Util.base64Encode
public static String base64Encode(String plainTextString) { String encoded = new String(Base64.getEncoder().encode(plainTextString.getBytes())); return encoded; }
java
public static String base64Encode(String plainTextString) { String encoded = new String(Base64.getEncoder().encode(plainTextString.getBytes())); return encoded; }
[ "public", "static", "String", "base64Encode", "(", "String", "plainTextString", ")", "{", "String", "encoded", "=", "new", "String", "(", "Base64", ".", "getEncoder", "(", ")", ".", "encode", "(", "plainTextString", ".", "getBytes", "(", ")", ")", ")", ";"...
Encodes a string using Base64 encoding. @param plainTextString the string to encode @return the given string as a Base64 encoded string.
[ "Encodes", "a", "string", "using", "Base64", "encoding", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/util/Util.java#L271-L274
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/util/Util.java
Util.getContainerId
public static String getContainerId() { if (containerId == null) { containerId = System.getProperty(HAWKULAR_AGENT_CONTAINER_ID); if (containerId != null) { log.infof("Container ID was explicitly set to [%s]", containerId); } } if (containerId == null) { final String containerIdFilename = "/proc/self/cgroup"; File containerIdFile = new File(containerIdFilename); if (containerIdFile.exists() && containerIdFile.canRead()) { try (Reader reader = new InputStreamReader(new FileInputStream(containerIdFile))) { new BufferedReader(reader).lines().forEach(new Consumer<String>() { @Override public void accept(String s) { // /proc/self/cgroup has lines that look like this: // 11:memory:/docker/99cb4a5d8c7a8a29d01dfcbb7c2ba210bad5470cc7a86474945441361a37513a // or this // 11:freezer:/system.slice/docker-c4a970c28c9d277373b5d1458679ac17c10db8538dd081072a.scope // The container ID is the same in all the /docker entries - we just want one of them. if (containerId == null) { containerId = extractDockerContainerIdFromString(s); } } }); } catch (IOException e) { log.warnf(e, "%s exists and is readable, but a read error occurred", containerIdFilename); containerId = ""; } finally { if (containerId == null) { log.infof("%s exists but could not find a container ID in it", containerIdFilename); containerId = ""; } } } else { log.debugf("%s does not exist or is unreadable. Assuming not inside a container", containerIdFilename); // for the future, we might want to check additional places and try different things containerId = ""; } } // The hostname has a portion of the container ID but only the first 12 chars. This might not be good enough, // so don't even rely on it. Leaving this code here in case in the future we do want to do this, but for now, // we do not. If we uncomment this, we need to change the code above so it leaves containerId null when // container ID is not found. // // if (containerId == null) { // try { // containerId = InetAddress.getLocalHost().getCanonicalHostName(); // } catch (Exception e) { // log.warnf(e, "Cannot determine container ID - hostname cannot be determined"); // containerId = ""; // } // } return (containerId.isEmpty()) ? null : containerId; }
java
public static String getContainerId() { if (containerId == null) { containerId = System.getProperty(HAWKULAR_AGENT_CONTAINER_ID); if (containerId != null) { log.infof("Container ID was explicitly set to [%s]", containerId); } } if (containerId == null) { final String containerIdFilename = "/proc/self/cgroup"; File containerIdFile = new File(containerIdFilename); if (containerIdFile.exists() && containerIdFile.canRead()) { try (Reader reader = new InputStreamReader(new FileInputStream(containerIdFile))) { new BufferedReader(reader).lines().forEach(new Consumer<String>() { @Override public void accept(String s) { // /proc/self/cgroup has lines that look like this: // 11:memory:/docker/99cb4a5d8c7a8a29d01dfcbb7c2ba210bad5470cc7a86474945441361a37513a // or this // 11:freezer:/system.slice/docker-c4a970c28c9d277373b5d1458679ac17c10db8538dd081072a.scope // The container ID is the same in all the /docker entries - we just want one of them. if (containerId == null) { containerId = extractDockerContainerIdFromString(s); } } }); } catch (IOException e) { log.warnf(e, "%s exists and is readable, but a read error occurred", containerIdFilename); containerId = ""; } finally { if (containerId == null) { log.infof("%s exists but could not find a container ID in it", containerIdFilename); containerId = ""; } } } else { log.debugf("%s does not exist or is unreadable. Assuming not inside a container", containerIdFilename); // for the future, we might want to check additional places and try different things containerId = ""; } } // The hostname has a portion of the container ID but only the first 12 chars. This might not be good enough, // so don't even rely on it. Leaving this code here in case in the future we do want to do this, but for now, // we do not. If we uncomment this, we need to change the code above so it leaves containerId null when // container ID is not found. // // if (containerId == null) { // try { // containerId = InetAddress.getLocalHost().getCanonicalHostName(); // } catch (Exception e) { // log.warnf(e, "Cannot determine container ID - hostname cannot be determined"); // containerId = ""; // } // } return (containerId.isEmpty()) ? null : containerId; }
[ "public", "static", "String", "getContainerId", "(", ")", "{", "if", "(", "containerId", "==", "null", ")", "{", "containerId", "=", "System", ".", "getProperty", "(", "HAWKULAR_AGENT_CONTAINER_ID", ")", ";", "if", "(", "containerId", "!=", "null", ")", "{",...
Tries to determine the container ID for the machine where this JVM is located. First check if the user explicitly set it. If not try determine it. @return container ID or null if cannot determine
[ "Tries", "to", "determine", "the", "container", "ID", "for", "the", "machine", "where", "this", "JVM", "is", "located", ".", "First", "check", "if", "the", "user", "explicitly", "set", "it", ".", "If", "not", "try", "determine", "it", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/util/Util.java#L317-L375
train
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/TransactionsJBossASClient.java
TransactionsJBossASClient.setDefaultTransactionTimeout
public void setDefaultTransactionTimeout(int timeoutSecs) throws Exception { final Address address = Address.root().add(SUBSYSTEM, TRANSACTIONS); final ModelNode req = createWriteAttributeRequest("default-timeout", String.valueOf(timeoutSecs), address); final ModelNode response = execute(req); if (!isSuccess(response)) { throw new FailureException(response); } return; }
java
public void setDefaultTransactionTimeout(int timeoutSecs) throws Exception { final Address address = Address.root().add(SUBSYSTEM, TRANSACTIONS); final ModelNode req = createWriteAttributeRequest("default-timeout", String.valueOf(timeoutSecs), address); final ModelNode response = execute(req); if (!isSuccess(response)) { throw new FailureException(response); } return; }
[ "public", "void", "setDefaultTransactionTimeout", "(", "int", "timeoutSecs", ")", "throws", "Exception", "{", "final", "Address", "address", "=", "Address", ".", "root", "(", ")", ".", "add", "(", "SUBSYSTEM", ",", "TRANSACTIONS", ")", ";", "final", "ModelNode...
Sets the default transaction timeout. @param timeoutSecs the new default transaction timeout, in seconds. @throws Exception any error
[ "Sets", "the", "default", "transaction", "timeout", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/TransactionsJBossASClient.java#L40-L49
train
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/Address.java
Address.fromModelNode
public static Address fromModelNode(ModelNode node) { // Rather than just store node as this.addressNode, we want to make sure it can be used as a valid address. // This also builds our own instance of ModelNode rather than use the one the caller gave us. Address address = Address.root(); // if the node is not defined, this simply represents the root address if (!node.isDefined()) { return address; } try { List<Property> addressList = node.asPropertyList(); for (Property addressProperty : addressList) { String resourceType = addressProperty.getName(); String resourceName = addressProperty.getValue().asString(); address.add(resourceType, resourceName); } return address; } catch (Exception e) { throw new IllegalArgumentException("Node cannot be used as an address: " + node.toJSONString(true)); } }
java
public static Address fromModelNode(ModelNode node) { // Rather than just store node as this.addressNode, we want to make sure it can be used as a valid address. // This also builds our own instance of ModelNode rather than use the one the caller gave us. Address address = Address.root(); // if the node is not defined, this simply represents the root address if (!node.isDefined()) { return address; } try { List<Property> addressList = node.asPropertyList(); for (Property addressProperty : addressList) { String resourceType = addressProperty.getName(); String resourceName = addressProperty.getValue().asString(); address.add(resourceType, resourceName); } return address; } catch (Exception e) { throw new IllegalArgumentException("Node cannot be used as an address: " + node.toJSONString(true)); } }
[ "public", "static", "Address", "fromModelNode", "(", "ModelNode", "node", ")", "{", "// Rather than just store node as this.addressNode, we want to make sure it can be used as a valid address.", "// This also builds our own instance of ModelNode rather than use the one the caller gave us.", "A...
Obtains the address from the given ModelNode which is assumed to be a property list that contains all the address parts and only the address parts. @param node address node @return the address
[ "Obtains", "the", "address", "from", "the", "given", "ModelNode", "which", "is", "assumed", "to", "be", "a", "property", "list", "that", "contains", "all", "the", "address", "parts", "and", "only", "the", "address", "parts", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/Address.java#L82-L103
train
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/Address.java
Address.add
public Address add(String... addressParts) { if (addressParts != null) { if ((addressParts.length % 2) != 0) { throw new IllegalArgumentException("address is incomplete: " + Arrays.toString(addressParts)); } if (addressParts.length > 0) { for (int i = 0; i < addressParts.length; i += 2) { addressNode.add(addressParts[i], addressParts[i + 1]); } } } return this; }
java
public Address add(String... addressParts) { if (addressParts != null) { if ((addressParts.length % 2) != 0) { throw new IllegalArgumentException("address is incomplete: " + Arrays.toString(addressParts)); } if (addressParts.length > 0) { for (int i = 0; i < addressParts.length; i += 2) { addressNode.add(addressParts[i], addressParts[i + 1]); } } } return this; }
[ "public", "Address", "add", "(", "String", "...", "addressParts", ")", "{", "if", "(", "addressParts", "!=", "null", ")", "{", "if", "(", "(", "addressParts", ".", "length", "%", "2", ")", "!=", "0", ")", "{", "throw", "new", "IllegalArgumentException", ...
Appends the given address parts to this address. This lets you build up addresses in a step-wise fashion. @param addressParts new address parts to add to the address. @return this address (which now has the new address parts appended).
[ "Appends", "the", "given", "address", "parts", "to", "this", "address", ".", "This", "lets", "you", "build", "up", "addresses", "in", "a", "step", "-", "wise", "fashion", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/Address.java#L162-L176
train
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/Address.java
Address.add
public Address add(Address address) { // if address is null or is the root address then there is nothing to append if (address == null || address.isRoot()) { return this; } // if we are the root address then the given address just is our new address, // otherwise, append all parts from "address" to us. if (isRoot()) { this.addressNode = address.addressNode.clone(); } else { List<Property> parts = address.addressNode.asPropertyList(); for (Property part : parts) { this.addressNode.add(part); } } return this; }
java
public Address add(Address address) { // if address is null or is the root address then there is nothing to append if (address == null || address.isRoot()) { return this; } // if we are the root address then the given address just is our new address, // otherwise, append all parts from "address" to us. if (isRoot()) { this.addressNode = address.addressNode.clone(); } else { List<Property> parts = address.addressNode.asPropertyList(); for (Property part : parts) { this.addressNode.add(part); } } return this; }
[ "public", "Address", "add", "(", "Address", "address", ")", "{", "// if address is null or is the root address then there is nothing to append", "if", "(", "address", "==", "null", "||", "address", ".", "isRoot", "(", ")", ")", "{", "return", "this", ";", "}", "//...
Appends the given address to this address. This lets you build up addresses in a step-wise fashion. @param address new address to appen to this address. @return this address (which now has the new address appended).
[ "Appends", "the", "given", "address", "to", "this", "address", ".", "This", "lets", "you", "build", "up", "addresses", "in", "a", "step", "-", "wise", "fashion", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/Address.java#L200-L218
train
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/Address.java
Address.toAddressPathString
public String toAddressPathString() { if (isRoot()) { return "/"; } StringBuilder str = new StringBuilder(); List<Property> parts = addressNode.asPropertyList(); for (Property part : parts) { String name = part.getName(); String value = part.getValue().asString(); str.append("/").append(name).append("=").append(value); } return str.toString(); }
java
public String toAddressPathString() { if (isRoot()) { return "/"; } StringBuilder str = new StringBuilder(); List<Property> parts = addressNode.asPropertyList(); for (Property part : parts) { String name = part.getName(); String value = part.getValue().asString(); str.append("/").append(name).append("=").append(value); } return str.toString(); }
[ "public", "String", "toAddressPathString", "(", ")", "{", "if", "(", "isRoot", "(", ")", ")", "{", "return", "\"/\"", ";", "}", "StringBuilder", "str", "=", "new", "StringBuilder", "(", ")", ";", "List", "<", "Property", ">", "parts", "=", "addressNode",...
Returns the address as a flattened string that is compatible with the DMR CLI address paths. For example, an Address whose ModelNode representation is: [ ("one" =&gt; "two"), ("three" =&gt; "four") ] will have a flat string of /one=two/three=four @return flattened address path string
[ "Returns", "the", "address", "as", "a", "flattened", "string", "that", "is", "compatible", "with", "the", "DMR", "CLI", "address", "paths", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/Address.java#L265-L278
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/platform/OshiPlatformCache.java
OshiPlatformCache.getPowerSourceMetric
public Double getPowerSourceMetric(String powerSourceName, ID metricToCollect) { Map<String, PowerSource> cache = getPowerSources(); PowerSource powerSource = cache.get(powerSourceName); if (powerSource == null) { return null; } if (PlatformMetricType.POWER_SOURCE_REMAINING_CAPACITY.getMetricTypeId().equals(metricToCollect)) { return powerSource.getRemainingCapacity(); } else if (PlatformMetricType.POWER_SOURCE_TIME_REMAINING.getMetricTypeId().equals(metricToCollect)) { return powerSource.getTimeRemaining(); } else { throw new UnsupportedOperationException("Invalid power source metric to collect: " + metricToCollect); } }
java
public Double getPowerSourceMetric(String powerSourceName, ID metricToCollect) { Map<String, PowerSource> cache = getPowerSources(); PowerSource powerSource = cache.get(powerSourceName); if (powerSource == null) { return null; } if (PlatformMetricType.POWER_SOURCE_REMAINING_CAPACITY.getMetricTypeId().equals(metricToCollect)) { return powerSource.getRemainingCapacity(); } else if (PlatformMetricType.POWER_SOURCE_TIME_REMAINING.getMetricTypeId().equals(metricToCollect)) { return powerSource.getTimeRemaining(); } else { throw new UnsupportedOperationException("Invalid power source metric to collect: " + metricToCollect); } }
[ "public", "Double", "getPowerSourceMetric", "(", "String", "powerSourceName", ",", "ID", "metricToCollect", ")", "{", "Map", "<", "String", ",", "PowerSource", ">", "cache", "=", "getPowerSources", "(", ")", ";", "PowerSource", "powerSource", "=", "cache", ".", ...
Returns the given metric's value, or null if there is no power source with the given name. @param powerSourceName name of power source @param metricToCollect the metric to collect @return the value of the metric, or null if there is no power source with the given name
[ "Returns", "the", "given", "metric", "s", "value", "or", "null", "if", "there", "is", "no", "power", "source", "with", "the", "given", "name", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/platform/OshiPlatformCache.java#L254-L269
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/platform/OshiPlatformCache.java
OshiPlatformCache.getProcessorMetric
public Double getProcessorMetric(String processorNumber, ID metricToCollect) { CentralProcessor processor = getProcessor(); if (processor == null) { return null; } int processorIndex; try { processorIndex = Integer.parseInt(processorNumber); if (processorIndex < 0 || processorIndex >= processor.getLogicalProcessorCount()) { return null; } } catch (Exception e) { return null; } if (PlatformMetricType.PROCESSOR_CPU_USAGE.getMetricTypeId().equals(metricToCollect)) { return processor.getProcessorCpuLoadBetweenTicks()[processorIndex]; } else { throw new UnsupportedOperationException("Invalid processor metric to collect: " + metricToCollect); } }
java
public Double getProcessorMetric(String processorNumber, ID metricToCollect) { CentralProcessor processor = getProcessor(); if (processor == null) { return null; } int processorIndex; try { processorIndex = Integer.parseInt(processorNumber); if (processorIndex < 0 || processorIndex >= processor.getLogicalProcessorCount()) { return null; } } catch (Exception e) { return null; } if (PlatformMetricType.PROCESSOR_CPU_USAGE.getMetricTypeId().equals(metricToCollect)) { return processor.getProcessorCpuLoadBetweenTicks()[processorIndex]; } else { throw new UnsupportedOperationException("Invalid processor metric to collect: " + metricToCollect); } }
[ "public", "Double", "getProcessorMetric", "(", "String", "processorNumber", ",", "ID", "metricToCollect", ")", "{", "CentralProcessor", "processor", "=", "getProcessor", "(", ")", ";", "if", "(", "processor", "==", "null", ")", "{", "return", "null", ";", "}",...
Returns the given metric's value, or null if there is no processor with the given number. @param processorNumber number of the processor, as a String @param metricToCollect the metric to collect @return the value of the metric, or null if there is no processor with the given number
[ "Returns", "the", "given", "metric", "s", "value", "or", "null", "if", "there", "is", "no", "processor", "with", "the", "given", "number", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/platform/OshiPlatformCache.java#L278-L300
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/platform/OshiPlatformCache.java
OshiPlatformCache.getFileStoreMetric
public Double getFileStoreMetric(String fileStoreNameName, ID metricToCollect) { Map<String, OSFileStore> cache = getFileStores(); OSFileStore fileStore = cache.get(fileStoreNameName); if (fileStore == null) { return null; } if (PlatformMetricType.FILE_STORE_TOTAL_SPACE.getMetricTypeId().equals(metricToCollect)) { return Double.valueOf(fileStore.getTotalSpace()); } else if (PlatformMetricType.FILE_STORE_USABLE_SPACE.getMetricTypeId().equals(metricToCollect)) { return Double.valueOf(fileStore.getUsableSpace()); } else { throw new UnsupportedOperationException("Invalid file store metric to collect: " + metricToCollect); } }
java
public Double getFileStoreMetric(String fileStoreNameName, ID metricToCollect) { Map<String, OSFileStore> cache = getFileStores(); OSFileStore fileStore = cache.get(fileStoreNameName); if (fileStore == null) { return null; } if (PlatformMetricType.FILE_STORE_TOTAL_SPACE.getMetricTypeId().equals(metricToCollect)) { return Double.valueOf(fileStore.getTotalSpace()); } else if (PlatformMetricType.FILE_STORE_USABLE_SPACE.getMetricTypeId().equals(metricToCollect)) { return Double.valueOf(fileStore.getUsableSpace()); } else { throw new UnsupportedOperationException("Invalid file store metric to collect: " + metricToCollect); } }
[ "public", "Double", "getFileStoreMetric", "(", "String", "fileStoreNameName", ",", "ID", "metricToCollect", ")", "{", "Map", "<", "String", ",", "OSFileStore", ">", "cache", "=", "getFileStores", "(", ")", ";", "OSFileStore", "fileStore", "=", "cache", ".", "g...
Returns the given metric's value, or null if there is no file store with the given name. @param fileStoreNameName name of file store @param metricToCollect the metric to collect @return the value of the metric, or null if there is no file store with the given name
[ "Returns", "the", "given", "metric", "s", "value", "or", "null", "if", "there", "is", "no", "file", "store", "with", "the", "given", "name", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/platform/OshiPlatformCache.java#L309-L324
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/platform/OshiPlatformCache.java
OshiPlatformCache.getMemoryMetric
public Double getMemoryMetric(ID metricToCollect) { GlobalMemory mem = getMemory(); if (PlatformMetricType.MEMORY_AVAILABLE.getMetricTypeId().equals(metricToCollect)) { return Double.valueOf(mem.getAvailable()); } else if (PlatformMetricType.MEMORY_TOTAL.getMetricTypeId().equals(metricToCollect)) { return Double.valueOf(mem.getTotal()); } else { throw new UnsupportedOperationException("Invalid memory metric to collect: " + metricToCollect); } }
java
public Double getMemoryMetric(ID metricToCollect) { GlobalMemory mem = getMemory(); if (PlatformMetricType.MEMORY_AVAILABLE.getMetricTypeId().equals(metricToCollect)) { return Double.valueOf(mem.getAvailable()); } else if (PlatformMetricType.MEMORY_TOTAL.getMetricTypeId().equals(metricToCollect)) { return Double.valueOf(mem.getTotal()); } else { throw new UnsupportedOperationException("Invalid memory metric to collect: " + metricToCollect); } }
[ "public", "Double", "getMemoryMetric", "(", "ID", "metricToCollect", ")", "{", "GlobalMemory", "mem", "=", "getMemory", "(", ")", ";", "if", "(", "PlatformMetricType", ".", "MEMORY_AVAILABLE", ".", "getMetricTypeId", "(", ")", ".", "equals", "(", "metricToCollec...
Returns the given memory metric's value. @param metricToCollect the metric to collect @return the value of the metric
[ "Returns", "the", "given", "memory", "metric", "s", "value", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/platform/OshiPlatformCache.java#L332-L343
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/platform/OshiPlatformCache.java
OshiPlatformCache.getOperatingSystemMetric
public Double getOperatingSystemMetric(ID metricId) { if (PlatformMetricType.OS_SYS_CPU_LOAD.getMetricTypeId().equals(metricId)) { return Double.valueOf(getProcessor().getSystemCpuLoad()); } else if (PlatformMetricType.OS_SYS_LOAD_AVG.getMetricTypeId().equals(metricId)) { return Double.valueOf(getProcessor().getSystemLoadAverage()); } else if (PlatformMetricType.OS_PROCESS_COUNT.getMetricTypeId().equals(metricId)) { return Double.valueOf(getOperatingSystem().getProcessCount()); } else { throw new UnsupportedOperationException("Invalid OS metric to collect: " + metricId); } }
java
public Double getOperatingSystemMetric(ID metricId) { if (PlatformMetricType.OS_SYS_CPU_LOAD.getMetricTypeId().equals(metricId)) { return Double.valueOf(getProcessor().getSystemCpuLoad()); } else if (PlatformMetricType.OS_SYS_LOAD_AVG.getMetricTypeId().equals(metricId)) { return Double.valueOf(getProcessor().getSystemLoadAverage()); } else if (PlatformMetricType.OS_PROCESS_COUNT.getMetricTypeId().equals(metricId)) { return Double.valueOf(getOperatingSystem().getProcessCount()); } else { throw new UnsupportedOperationException("Invalid OS metric to collect: " + metricId); } }
[ "public", "Double", "getOperatingSystemMetric", "(", "ID", "metricId", ")", "{", "if", "(", "PlatformMetricType", ".", "OS_SYS_CPU_LOAD", ".", "getMetricTypeId", "(", ")", ".", "equals", "(", "metricId", ")", ")", "{", "return", "Double", ".", "valueOf", "(", ...
Returns the given OS metric's value. @param metricId the metric to collect @return the value of the metric
[ "Returns", "the", "given", "OS", "metric", "s", "value", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/platform/OshiPlatformCache.java#L351-L361
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/platform/OshiPlatformCache.java
OshiPlatformCache.getMetric
public Double getMetric(PlatformResourceType type, String name, ID metricToCollect) { switch (type) { case OPERATING_SYSTEM: { return getOperatingSystemMetric(metricToCollect); } case MEMORY: { return getMemoryMetric(metricToCollect); } case FILE_STORE: { return getFileStoreMetric(name, metricToCollect); } case PROCESSOR: { return getProcessorMetric(name, metricToCollect); } case POWER_SOURCE: { return getPowerSourceMetric(name, metricToCollect); } default: { throw new IllegalArgumentException( "Platform resource [" + type + "][" + name + "] does not have metrics"); } } }
java
public Double getMetric(PlatformResourceType type, String name, ID metricToCollect) { switch (type) { case OPERATING_SYSTEM: { return getOperatingSystemMetric(metricToCollect); } case MEMORY: { return getMemoryMetric(metricToCollect); } case FILE_STORE: { return getFileStoreMetric(name, metricToCollect); } case PROCESSOR: { return getProcessorMetric(name, metricToCollect); } case POWER_SOURCE: { return getPowerSourceMetric(name, metricToCollect); } default: { throw new IllegalArgumentException( "Platform resource [" + type + "][" + name + "] does not have metrics"); } } }
[ "public", "Double", "getMetric", "(", "PlatformResourceType", "type", ",", "String", "name", ",", "ID", "metricToCollect", ")", "{", "switch", "(", "type", ")", "{", "case", "OPERATING_SYSTEM", ":", "{", "return", "getOperatingSystemMetric", "(", "metricToCollect"...
Given a platform resource type, a name, and a metric name, this will return that metric's value, or null if there is no resource that can be identified by the name and type. @param type identifies the platform resource whose metric is to be collected @param name name of the resource whose metric is to be collected @param metricToCollect the metric to collect @return the value of the metric, or null if there is no resource identified by the name
[ "Given", "a", "platform", "resource", "type", "a", "name", "and", "a", "metric", "name", "this", "will", "return", "that", "metric", "s", "value", "or", "null", "if", "there", "is", "no", "resource", "that", "can", "be", "identified", "by", "the", "name"...
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/platform/OshiPlatformCache.java#L372-L394
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/ResourceTypeManager.java
ResourceTypeManager.buildTypeMapForConstructor
private static <L> Map<Name, TypeSet<ResourceType<L>>> buildTypeMapForConstructor( Collection<ResourceType<L>> allTypes) { TypeSetBuilder<ResourceType<L>> bldr = TypeSet.<ResourceType<L>> builder(); bldr.enabled(true); bldr.name(new Name("all")); for (ResourceType<L> type : allTypes) { bldr.type(type); } TypeSet<ResourceType<L>> typeSet = bldr.build(); return Collections.singletonMap(typeSet.getName(), typeSet); }
java
private static <L> Map<Name, TypeSet<ResourceType<L>>> buildTypeMapForConstructor( Collection<ResourceType<L>> allTypes) { TypeSetBuilder<ResourceType<L>> bldr = TypeSet.<ResourceType<L>> builder(); bldr.enabled(true); bldr.name(new Name("all")); for (ResourceType<L> type : allTypes) { bldr.type(type); } TypeSet<ResourceType<L>> typeSet = bldr.build(); return Collections.singletonMap(typeSet.getName(), typeSet); }
[ "private", "static", "<", "L", ">", "Map", "<", "Name", ",", "TypeSet", "<", "ResourceType", "<", "L", ">", ">", ">", "buildTypeMapForConstructor", "(", "Collection", "<", "ResourceType", "<", "L", ">", ">", "allTypes", ")", "{", "TypeSetBuilder", "<", "...
for use by the above constructor
[ "for", "use", "by", "the", "above", "constructor" ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/ResourceTypeManager.java#L64-L75
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/ResourceTypeManager.java
ResourceTypeManager.getChildren
public Set<ResourceType<L>> getChildren(ResourceType<L> resourceType) { Set<ResourceType<L>> directChildren = index.successorsOf(resourceType); return Collections.unmodifiableSet(directChildren); }
java
public Set<ResourceType<L>> getChildren(ResourceType<L> resourceType) { Set<ResourceType<L>> directChildren = index.successorsOf(resourceType); return Collections.unmodifiableSet(directChildren); }
[ "public", "Set", "<", "ResourceType", "<", "L", ">", ">", "getChildren", "(", "ResourceType", "<", "L", ">", "resourceType", ")", "{", "Set", "<", "ResourceType", "<", "L", ">>", "directChildren", "=", "index", ".", "successorsOf", "(", "resourceType", ")"...
Returns the direct child types of the given resource type. @param resourceType the type whose children are to be returned @return the direct children of the given resource type
[ "Returns", "the", "direct", "child", "types", "of", "the", "given", "resource", "type", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/ResourceTypeManager.java#L151-L154
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/ResourceTypeManager.java
ResourceTypeManager.getParents
public Set<ResourceType<L>> getParents(ResourceType<L> resourceType) { Set<ResourceType<L>> directParents = index.predecessorsOf(resourceType); return Collections.unmodifiableSet(directParents); }
java
public Set<ResourceType<L>> getParents(ResourceType<L> resourceType) { Set<ResourceType<L>> directParents = index.predecessorsOf(resourceType); return Collections.unmodifiableSet(directParents); }
[ "public", "Set", "<", "ResourceType", "<", "L", ">", ">", "getParents", "(", "ResourceType", "<", "L", ">", "resourceType", ")", "{", "Set", "<", "ResourceType", "<", "L", ">>", "directParents", "=", "index", ".", "predecessorsOf", "(", "resourceType", ")"...
Returns the direct parent types of the given resource type. @param resourceType the type whose parents are to be returned @return the direct parents of the given resource type
[ "Returns", "the", "direct", "parent", "types", "of", "the", "given", "resource", "type", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/ResourceTypeManager.java#L163-L166
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/ResourceTypeManager.java
ResourceTypeManager.prepareGraph
private void prepareGraph() throws IllegalStateException { List<ResourceType<L>> disabledTypes = new ArrayList<>(); // flattened list of types, all sets are collapsed into one Map<Name, ResourceType<L>> allResourceTypes = new HashMap<>(); // add all resource types as vertices in the graph for (TypeSet<ResourceType<L>> rTypeSet : typeSetMap.values()) { for (ResourceType<L> rType : rTypeSet.getTypeMap().values()) { if (null != allResourceTypes.put(rType.getName(), rType)) { throw new IllegalStateException("Multiple resource types have the same name: " + rType.getName()); } resourceTypesGraph.addVertex(rType); if (!rTypeSet.isEnabled()) { disabledTypes.add(rType); } } } // now add the parent hierarchy to the graph for (TypeSet<ResourceType<L>> rTypeSet : typeSetMap.values()) { for (ResourceType<L> rType : rTypeSet.getTypeMap().values()) { for (Name parent : rType.getParents()) { ResourceType<L> parentResourceType = allResourceTypes.get(parent); if (parentResourceType == null) { log.debugf("Resource type [%s] will ignore unknown parent [%s]", rType.getName(), parent); } else { resourceTypesGraph.addEdge(parentResourceType, rType); } } } } // now strip all disabled types - if a type has an ancestor that is disabled, it too will be disabled List<ResourceType<L>> toBeDisabled = new ArrayList<>(); for (ResourceType<L> disabledType : disabledTypes) { toBeDisabled.add(disabledType); getDeepChildrenList(disabledType, toBeDisabled); log.infoDisablingResourceTypes(disabledType, toBeDisabled); } resourceTypesGraph.removeAllVertices(toBeDisabled); }
java
private void prepareGraph() throws IllegalStateException { List<ResourceType<L>> disabledTypes = new ArrayList<>(); // flattened list of types, all sets are collapsed into one Map<Name, ResourceType<L>> allResourceTypes = new HashMap<>(); // add all resource types as vertices in the graph for (TypeSet<ResourceType<L>> rTypeSet : typeSetMap.values()) { for (ResourceType<L> rType : rTypeSet.getTypeMap().values()) { if (null != allResourceTypes.put(rType.getName(), rType)) { throw new IllegalStateException("Multiple resource types have the same name: " + rType.getName()); } resourceTypesGraph.addVertex(rType); if (!rTypeSet.isEnabled()) { disabledTypes.add(rType); } } } // now add the parent hierarchy to the graph for (TypeSet<ResourceType<L>> rTypeSet : typeSetMap.values()) { for (ResourceType<L> rType : rTypeSet.getTypeMap().values()) { for (Name parent : rType.getParents()) { ResourceType<L> parentResourceType = allResourceTypes.get(parent); if (parentResourceType == null) { log.debugf("Resource type [%s] will ignore unknown parent [%s]", rType.getName(), parent); } else { resourceTypesGraph.addEdge(parentResourceType, rType); } } } } // now strip all disabled types - if a type has an ancestor that is disabled, it too will be disabled List<ResourceType<L>> toBeDisabled = new ArrayList<>(); for (ResourceType<L> disabledType : disabledTypes) { toBeDisabled.add(disabledType); getDeepChildrenList(disabledType, toBeDisabled); log.infoDisablingResourceTypes(disabledType, toBeDisabled); } resourceTypesGraph.removeAllVertices(toBeDisabled); }
[ "private", "void", "prepareGraph", "(", ")", "throws", "IllegalStateException", "{", "List", "<", "ResourceType", "<", "L", ">>", "disabledTypes", "=", "new", "ArrayList", "<>", "(", ")", ";", "// flattened list of types, all sets are collapsed into one", "Map", "<", ...
Prepares the graph. @throws IllegalStateException if there are missing types
[ "Prepares", "the", "graph", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/ResourceTypeManager.java#L173-L215
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/cmd/FeedCommProcessor.java
FeedCommProcessor.sendAsync
public void sendAsync(BasicMessageWithExtraData<? extends BasicMessage> messageWithData) { if (!isConnected()) { throw new IllegalStateException("WebSocket connection was closed. Cannot send any messages"); } BasicMessage message = messageWithData.getBasicMessage(); configurationAuthentication(message); sendExecutor.execute(new Runnable() { @Override public void run() { try { if (messageWithData.getBinaryData() == null) { String messageString = ApiDeserializer.toHawkularFormat(message); @SuppressWarnings("resource") Buffer buffer = new Buffer().writeUtf8(messageString); RequestBody requestBody = RequestBody.create(WebSocket.TEXT, buffer.readByteArray()); FeedCommProcessor.this.webSocket.sendMessage(requestBody); } else { BinaryData messageData = ApiDeserializer.toHawkularFormat(message, messageWithData.getBinaryData()); RequestBody requestBody = new RequestBody() { @Override public MediaType contentType() { return WebSocket.BINARY; } @Override public void writeTo(BufferedSink bufferedSink) throws IOException { emitToSink(messageData, bufferedSink); } }; FeedCommProcessor.this.webSocket.sendMessage(requestBody); } } catch (Throwable t) { log.errorFailedToSendOverFeedComm(message.getClass().getName(), t); } } }); }
java
public void sendAsync(BasicMessageWithExtraData<? extends BasicMessage> messageWithData) { if (!isConnected()) { throw new IllegalStateException("WebSocket connection was closed. Cannot send any messages"); } BasicMessage message = messageWithData.getBasicMessage(); configurationAuthentication(message); sendExecutor.execute(new Runnable() { @Override public void run() { try { if (messageWithData.getBinaryData() == null) { String messageString = ApiDeserializer.toHawkularFormat(message); @SuppressWarnings("resource") Buffer buffer = new Buffer().writeUtf8(messageString); RequestBody requestBody = RequestBody.create(WebSocket.TEXT, buffer.readByteArray()); FeedCommProcessor.this.webSocket.sendMessage(requestBody); } else { BinaryData messageData = ApiDeserializer.toHawkularFormat(message, messageWithData.getBinaryData()); RequestBody requestBody = new RequestBody() { @Override public MediaType contentType() { return WebSocket.BINARY; } @Override public void writeTo(BufferedSink bufferedSink) throws IOException { emitToSink(messageData, bufferedSink); } }; FeedCommProcessor.this.webSocket.sendMessage(requestBody); } } catch (Throwable t) { log.errorFailedToSendOverFeedComm(message.getClass().getName(), t); } } }); }
[ "public", "void", "sendAsync", "(", "BasicMessageWithExtraData", "<", "?", "extends", "BasicMessage", ">", "messageWithData", ")", "{", "if", "(", "!", "isConnected", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"WebSocket connection was close...
Sends a message to the server asynchronously. This method returns immediately; the message may not go out until some time in the future. @param messageWithData the message to send
[ "Sends", "a", "message", "to", "the", "server", "asynchronously", ".", "This", "method", "returns", "immediately", ";", "the", "message", "may", "not", "go", "out", "until", "some", "time", "in", "the", "future", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/cmd/FeedCommProcessor.java#L220-L261
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/cmd/FeedCommProcessor.java
FeedCommProcessor.sendSync
public void sendSync(BasicMessageWithExtraData<? extends BasicMessage> messageWithData) throws Exception { if (!isConnected()) { throw new IllegalStateException("WebSocket connection was closed. Cannot send any messages"); } BasicMessage message = messageWithData.getBasicMessage(); configurationAuthentication(message); if (messageWithData.getBinaryData() == null) { String messageString = ApiDeserializer.toHawkularFormat(message); @SuppressWarnings("resource") Buffer buffer = new Buffer().writeUtf8(messageString); RequestBody requestBody = RequestBody.create(WebSocket.TEXT, buffer.readByteArray()); FeedCommProcessor.this.webSocket.sendMessage(requestBody); } else { BinaryData messageData = ApiDeserializer.toHawkularFormat(message, messageWithData.getBinaryData()); RequestBody requestBody = new RequestBody() { @Override public MediaType contentType() { return WebSocket.BINARY; } @Override public void writeTo(BufferedSink bufferedSink) throws IOException { emitToSink(messageData, bufferedSink); } }; FeedCommProcessor.this.webSocket.sendMessage(requestBody); } }
java
public void sendSync(BasicMessageWithExtraData<? extends BasicMessage> messageWithData) throws Exception { if (!isConnected()) { throw new IllegalStateException("WebSocket connection was closed. Cannot send any messages"); } BasicMessage message = messageWithData.getBasicMessage(); configurationAuthentication(message); if (messageWithData.getBinaryData() == null) { String messageString = ApiDeserializer.toHawkularFormat(message); @SuppressWarnings("resource") Buffer buffer = new Buffer().writeUtf8(messageString); RequestBody requestBody = RequestBody.create(WebSocket.TEXT, buffer.readByteArray()); FeedCommProcessor.this.webSocket.sendMessage(requestBody); } else { BinaryData messageData = ApiDeserializer.toHawkularFormat(message, messageWithData.getBinaryData()); RequestBody requestBody = new RequestBody() { @Override public MediaType contentType() { return WebSocket.BINARY; } @Override public void writeTo(BufferedSink bufferedSink) throws IOException { emitToSink(messageData, bufferedSink); } }; FeedCommProcessor.this.webSocket.sendMessage(requestBody); } }
[ "public", "void", "sendSync", "(", "BasicMessageWithExtraData", "<", "?", "extends", "BasicMessage", ">", "messageWithData", ")", "throws", "Exception", "{", "if", "(", "!", "isConnected", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"WebS...
Sends a message to the server synchronously. This will return only when the message has been sent. @param messageWithData the message to send @throws IOException if the message failed to be sent
[ "Sends", "a", "message", "to", "the", "server", "synchronously", ".", "This", "will", "return", "only", "when", "the", "message", "has", "been", "sent", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/cmd/FeedCommProcessor.java#L269-L301
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/cmd/FeedCommProcessor.java
FeedCommProcessor.destroyPingExecutor
private void destroyPingExecutor() { synchronized (pingExecutor) { if (!pingExecutor.isShutdown()) { try { log.debugf("Shutting down WebSocket ping executor"); pingExecutor.shutdown(); if (!pingExecutor.awaitTermination(1, TimeUnit.SECONDS)) { pingExecutor.shutdownNow(); } } catch (Throwable t) { log.warnf("Cannot shut down WebSocket ping executor. Cause=%s", t.toString()); } } } }
java
private void destroyPingExecutor() { synchronized (pingExecutor) { if (!pingExecutor.isShutdown()) { try { log.debugf("Shutting down WebSocket ping executor"); pingExecutor.shutdown(); if (!pingExecutor.awaitTermination(1, TimeUnit.SECONDS)) { pingExecutor.shutdownNow(); } } catch (Throwable t) { log.warnf("Cannot shut down WebSocket ping executor. Cause=%s", t.toString()); } } } }
[ "private", "void", "destroyPingExecutor", "(", ")", "{", "synchronized", "(", "pingExecutor", ")", "{", "if", "(", "!", "pingExecutor", ".", "isShutdown", "(", ")", ")", "{", "try", "{", "log", ".", "debugf", "(", "\"Shutting down WebSocket ping executor\"", "...
Call this when you know the feed comm processor object will never be used again and thus the ping executor will also never be used again.
[ "Call", "this", "when", "you", "know", "the", "feed", "comm", "processor", "object", "will", "never", "be", "used", "again", "and", "thus", "the", "ping", "executor", "will", "also", "never", "be", "used", "again", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/cmd/FeedCommProcessor.java#L583-L597
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/InventoryIdUtil.java
InventoryIdUtil.generateResourceId
public static ID generateResourceId( String feedId, MonitoredEndpoint<? extends AbstractEndpointConfiguration> endpoint, String idPart) { ID id = new ID(String.format("%s~%s~%s", feedId, endpoint.getName(), idPart)); return id; }
java
public static ID generateResourceId( String feedId, MonitoredEndpoint<? extends AbstractEndpointConfiguration> endpoint, String idPart) { ID id = new ID(String.format("%s~%s~%s", feedId, endpoint.getName(), idPart)); return id; }
[ "public", "static", "ID", "generateResourceId", "(", "String", "feedId", ",", "MonitoredEndpoint", "<", "?", "extends", "AbstractEndpointConfiguration", ">", "endpoint", ",", "String", "idPart", ")", "{", "ID", "id", "=", "new", "ID", "(", "String", ".", "form...
Generates an ID for a resource. @param feedId the ID of the feed that owns the resource whose ID is to be generated @param endpoint the endpoint where the resource is found @param idPart a unique string that identifies the resource within the managed server @return the resource ID
[ "Generates", "an", "ID", "for", "a", "resource", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/InventoryIdUtil.java#L80-L86
train
hawkular/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/IDObject.java
IDObject.addProperty
public void addProperty(String name, Object value) { if (value != null) { properties.put(name, value); } else { removeProperty(name); } }
java
public void addProperty(String name, Object value) { if (value != null) { properties.put(name, value); } else { removeProperty(name); } }
[ "public", "void", "addProperty", "(", "String", "name", ",", "Object", "value", ")", "{", "if", "(", "value", "!=", "null", ")", "{", "properties", ".", "put", "(", "name", ",", "value", ")", ";", "}", "else", "{", "removeProperty", "(", "name", ")",...
Adds an optional property to this object. If null, any property with the given name will be removed. If the property already exists, this new value will replace the old value. @param name the name of the property @param value the value of the property; must be JSON-serializable if not-null
[ "Adds", "an", "optional", "property", "to", "this", "object", ".", "If", "null", "any", "property", "with", "the", "given", "name", "will", "be", "removed", ".", "If", "the", "property", "already", "exists", "this", "new", "value", "will", "replace", "the"...
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/IDObject.java#L69-L75
train
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SocketBindingJBossASClient.java
SocketBindingJBossASClient.isSocketBinding
public boolean isSocketBinding(String socketBindingGroupName, String socketBindingName) throws Exception { Address addr = Address.root().add(SOCKET_BINDING_GROUP, socketBindingGroupName); String haystack = SOCKET_BINDING; return null != findNodeInList(addr, haystack, socketBindingName); }
java
public boolean isSocketBinding(String socketBindingGroupName, String socketBindingName) throws Exception { Address addr = Address.root().add(SOCKET_BINDING_GROUP, socketBindingGroupName); String haystack = SOCKET_BINDING; return null != findNodeInList(addr, haystack, socketBindingName); }
[ "public", "boolean", "isSocketBinding", "(", "String", "socketBindingGroupName", ",", "String", "socketBindingName", ")", "throws", "Exception", "{", "Address", "addr", "=", "Address", ".", "root", "(", ")", ".", "add", "(", "SOCKET_BINDING_GROUP", ",", "socketBin...
Checks to see if there is already a socket binding in the given group. @param socketBindingGroupName the name of the socket binding group in which to look for the named socket binding @param socketBindingName the name of the socket binding to look for @return true if there is an existing socket binding in the given group @throws Exception any error
[ "Checks", "to", "see", "if", "there", "is", "already", "a", "socket", "binding", "in", "the", "given", "group", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SocketBindingJBossASClient.java#L74-L78
train
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SocketBindingJBossASClient.java
SocketBindingJBossASClient.addSocketBinding
public void addSocketBinding(String socketBindingGroupName, String socketBindingName, int port) throws Exception { addSocketBinding(socketBindingGroupName, socketBindingName, null, port); }
java
public void addSocketBinding(String socketBindingGroupName, String socketBindingName, int port) throws Exception { addSocketBinding(socketBindingGroupName, socketBindingName, null, port); }
[ "public", "void", "addSocketBinding", "(", "String", "socketBindingGroupName", ",", "String", "socketBindingName", ",", "int", "port", ")", "throws", "Exception", "{", "addSocketBinding", "(", "socketBindingGroupName", ",", "socketBindingName", ",", "null", ",", "port...
Adds a socket binding with the given name in the named socket binding group. If a socket binding with the given name already exists, this method does nothing. @param socketBindingGroupName the name of the socket binding group in which to create the named socket binding @param socketBindingName the name of the socket binding to be created with the given port @param port the port number @throws Exception any error
[ "Adds", "a", "socket", "binding", "with", "the", "given", "name", "in", "the", "named", "socket", "binding", "group", ".", "If", "a", "socket", "binding", "with", "the", "given", "name", "already", "exists", "this", "method", "does", "nothing", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SocketBindingJBossASClient.java#L116-L118
train
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SocketBindingJBossASClient.java
SocketBindingJBossASClient.setSocketBindingPort
public void setSocketBindingPort(String socketBindingGroupName, String socketBindingName, int port) throws Exception { setSocketBindingPortExpression(socketBindingGroupName, socketBindingName, null, port); }
java
public void setSocketBindingPort(String socketBindingGroupName, String socketBindingName, int port) throws Exception { setSocketBindingPortExpression(socketBindingGroupName, socketBindingName, null, port); }
[ "public", "void", "setSocketBindingPort", "(", "String", "socketBindingGroupName", ",", "String", "socketBindingName", ",", "int", "port", ")", "throws", "Exception", "{", "setSocketBindingPortExpression", "(", "socketBindingGroupName", ",", "socketBindingName", ",", "nul...
Sets the port number for the named socket binding found in the named socket binding group. @param socketBindingGroupName the name of the socket binding group that has the named socket binding @param socketBindingName the name of the socket binding whose port is to be set @param port the new port number @throws Exception any error
[ "Sets", "the", "port", "number", "for", "the", "named", "socket", "binding", "found", "in", "the", "named", "socket", "binding", "group", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SocketBindingJBossASClient.java#L236-L239
train
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SocketBindingJBossASClient.java
SocketBindingJBossASClient.setStandardSocketBindingInterface
public void setStandardSocketBindingInterface(String socketBindingName, String interfaceName) throws Exception { setStandardSocketBindingInterfaceExpression(socketBindingName, null, interfaceName); }
java
public void setStandardSocketBindingInterface(String socketBindingName, String interfaceName) throws Exception { setStandardSocketBindingInterfaceExpression(socketBindingName, null, interfaceName); }
[ "public", "void", "setStandardSocketBindingInterface", "(", "String", "socketBindingName", ",", "String", "interfaceName", ")", "throws", "Exception", "{", "setStandardSocketBindingInterfaceExpression", "(", "socketBindingName", ",", "null", ",", "interfaceName", ")", ";", ...
Sets the interface name for the named standard socket binding. @param socketBindingName the name of the standard socket binding whose interface is to be set @param interfaceName the new interface name @throws Exception any error
[ "Sets", "the", "interface", "name", "for", "the", "named", "standard", "socket", "binding", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SocketBindingJBossASClient.java#L279-L281
train
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SocketBindingJBossASClient.java
SocketBindingJBossASClient.setSocketBindingPort
public void setSocketBindingPort(String socketBindingGroupName, String socketBindingName, String interfaceName) throws Exception { setSocketBindingInterfaceExpression(socketBindingGroupName, socketBindingName, null, interfaceName); }
java
public void setSocketBindingPort(String socketBindingGroupName, String socketBindingName, String interfaceName) throws Exception { setSocketBindingInterfaceExpression(socketBindingGroupName, socketBindingName, null, interfaceName); }
[ "public", "void", "setSocketBindingPort", "(", "String", "socketBindingGroupName", ",", "String", "socketBindingName", ",", "String", "interfaceName", ")", "throws", "Exception", "{", "setSocketBindingInterfaceExpression", "(", "socketBindingGroupName", ",", "socketBindingNam...
Sets the interface name for the named socket binding found in the named socket binding group. @param socketBindingGroupName the name of the socket binding group that has the named socket binding @param socketBindingName the name of the socket binding whose interface is to be set @param interfaceName the new interface name @throws Exception any error
[ "Sets", "the", "interface", "name", "for", "the", "named", "socket", "binding", "found", "in", "the", "named", "socket", "binding", "group", "." ]
a7a88fc7e4f12302e4c4306d1c91e11f81c8b811
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SocketBindingJBossASClient.java#L306-L309
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/ClassUtils.java
ClassUtils.toCanonicalName
private static String toCanonicalName(String className) { className = StringUtils.deleteWhitespace(className); Validate.notNull(className, "className must not be null."); if (className.endsWith("[]")) { final StringBuilder classNameBuffer = new StringBuilder(); while (className.endsWith("[]")) { className = className.substring(0, className.length() - 2); classNameBuffer.append("["); } final String abbreviation = abbreviationMap.get(className); if (abbreviation != null) { classNameBuffer.append(abbreviation); } else { classNameBuffer.append("L").append(className).append(";"); } className = classNameBuffer.toString(); } return className; }
java
private static String toCanonicalName(String className) { className = StringUtils.deleteWhitespace(className); Validate.notNull(className, "className must not be null."); if (className.endsWith("[]")) { final StringBuilder classNameBuffer = new StringBuilder(); while (className.endsWith("[]")) { className = className.substring(0, className.length() - 2); classNameBuffer.append("["); } final String abbreviation = abbreviationMap.get(className); if (abbreviation != null) { classNameBuffer.append(abbreviation); } else { classNameBuffer.append("L").append(className).append(";"); } className = classNameBuffer.toString(); } return className; }
[ "private", "static", "String", "toCanonicalName", "(", "String", "className", ")", "{", "className", "=", "StringUtils", ".", "deleteWhitespace", "(", "className", ")", ";", "Validate", ".", "notNull", "(", "className", ",", "\"className must not be null.\"", ")", ...
Converts a class name to a JLS style class name. @param className the class name @return the converted name
[ "Converts", "a", "class", "name", "to", "a", "JLS", "style", "class", "name", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/ClassUtils.java#L1139-L1157
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/text/translate/EntityArrays.java
EntityArrays.invert
public static String[][] invert(final String[][] array) { final String[][] newarray = new String[array.length][2]; for(int i = 0; i<array.length; i++) { newarray[i][0] = array[i][1]; newarray[i][1] = array[i][0]; } return newarray; }
java
public static String[][] invert(final String[][] array) { final String[][] newarray = new String[array.length][2]; for(int i = 0; i<array.length; i++) { newarray[i][0] = array[i][1]; newarray[i][1] = array[i][0]; } return newarray; }
[ "public", "static", "String", "[", "]", "[", "]", "invert", "(", "final", "String", "[", "]", "[", "]", "array", ")", "{", "final", "String", "[", "]", "[", "]", "newarray", "=", "new", "String", "[", "array", ".", "length", "]", "[", "2", "]", ...
Used to invert an escape array into an unescape array @param array String[][] to be inverted @return String[][] inverted array
[ "Used", "to", "invert", "an", "escape", "array", "into", "an", "unescape", "array" ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/translate/EntityArrays.java#L449-L456
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/math/Fraction.java
Fraction.addSub
private Fraction addSub(final Fraction fraction, final boolean isAdd) { Validate.isTrue(fraction != null, "The fraction must not be null"); // zero is identity for addition. if (numerator == 0) { return isAdd ? fraction : fraction.negate(); } if (fraction.numerator == 0) { return this; } // if denominators are randomly distributed, d1 will be 1 about 61% // of the time. final int d1 = greatestCommonDivisor(denominator, fraction.denominator); if (d1 == 1) { // result is ( (u*v' +/- u'v) / u'v') final int uvp = mulAndCheck(numerator, fraction.denominator); final int upv = mulAndCheck(fraction.numerator, denominator); return new Fraction(isAdd ? addAndCheck(uvp, upv) : subAndCheck(uvp, upv), mulPosAndCheck(denominator, fraction.denominator)); } // the quantity 't' requires 65 bits of precision; see knuth 4.5.1 // exercise 7. we're going to use a BigInteger. // t = u(v'/d1) +/- v(u'/d1) final BigInteger uvp = BigInteger.valueOf(numerator).multiply(BigInteger.valueOf(fraction.denominator / d1)); final BigInteger upv = BigInteger.valueOf(fraction.numerator).multiply(BigInteger.valueOf(denominator / d1)); final BigInteger t = isAdd ? uvp.add(upv) : uvp.subtract(upv); // but d2 doesn't need extra precision because // d2 = gcd(t,d1) = gcd(t mod d1, d1) final int tmodd1 = t.mod(BigInteger.valueOf(d1)).intValue(); final int d2 = tmodd1 == 0 ? d1 : greatestCommonDivisor(tmodd1, d1); // result is (t/d2) / (u'/d1)(v'/d2) final BigInteger w = t.divide(BigInteger.valueOf(d2)); if (w.bitLength() > 31) { throw new ArithmeticException("overflow: numerator too large after multiply"); } return new Fraction(w.intValue(), mulPosAndCheck(denominator / d1, fraction.denominator / d2)); }
java
private Fraction addSub(final Fraction fraction, final boolean isAdd) { Validate.isTrue(fraction != null, "The fraction must not be null"); // zero is identity for addition. if (numerator == 0) { return isAdd ? fraction : fraction.negate(); } if (fraction.numerator == 0) { return this; } // if denominators are randomly distributed, d1 will be 1 about 61% // of the time. final int d1 = greatestCommonDivisor(denominator, fraction.denominator); if (d1 == 1) { // result is ( (u*v' +/- u'v) / u'v') final int uvp = mulAndCheck(numerator, fraction.denominator); final int upv = mulAndCheck(fraction.numerator, denominator); return new Fraction(isAdd ? addAndCheck(uvp, upv) : subAndCheck(uvp, upv), mulPosAndCheck(denominator, fraction.denominator)); } // the quantity 't' requires 65 bits of precision; see knuth 4.5.1 // exercise 7. we're going to use a BigInteger. // t = u(v'/d1) +/- v(u'/d1) final BigInteger uvp = BigInteger.valueOf(numerator).multiply(BigInteger.valueOf(fraction.denominator / d1)); final BigInteger upv = BigInteger.valueOf(fraction.numerator).multiply(BigInteger.valueOf(denominator / d1)); final BigInteger t = isAdd ? uvp.add(upv) : uvp.subtract(upv); // but d2 doesn't need extra precision because // d2 = gcd(t,d1) = gcd(t mod d1, d1) final int tmodd1 = t.mod(BigInteger.valueOf(d1)).intValue(); final int d2 = tmodd1 == 0 ? d1 : greatestCommonDivisor(tmodd1, d1); // result is (t/d2) / (u'/d1)(v'/d2) final BigInteger w = t.divide(BigInteger.valueOf(d2)); if (w.bitLength() > 31) { throw new ArithmeticException("overflow: numerator too large after multiply"); } return new Fraction(w.intValue(), mulPosAndCheck(denominator / d1, fraction.denominator / d2)); }
[ "private", "Fraction", "addSub", "(", "final", "Fraction", "fraction", ",", "final", "boolean", "isAdd", ")", "{", "Validate", ".", "isTrue", "(", "fraction", "!=", "null", ",", "\"The fraction must not be null\"", ")", ";", "// zero is identity for addition.", "if"...
Implement add and subtract using algorithm described in Knuth 4.5.1. @param fraction the fraction to subtract, must not be <code>null</code> @param isAdd true to add, false to subtract @return a <code>Fraction</code> instance with the resulting values @throws IllegalArgumentException if the fraction is <code>null</code> @throws ArithmeticException if the resulting numerator or denominator cannot be represented in an <code>int</code>.
[ "Implement", "add", "and", "subtract", "using", "algorithm", "described", "in", "Knuth", "4", ".", "5", ".", "1", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/math/Fraction.java#L735-L771
train
alexheretic/dynamics
src/main/java/alexh/weak/Converter.java
Converter.intoZonedDateTimeOrUse
public ZonedDateTime intoZonedDateTimeOrUse(ZoneId fallback){ try { return intoZonedDateTime(); } catch (RuntimeException ex) { return intoLocalDateTime().atZone(fallback); } }
java
public ZonedDateTime intoZonedDateTimeOrUse(ZoneId fallback){ try { return intoZonedDateTime(); } catch (RuntimeException ex) { return intoLocalDateTime().atZone(fallback); } }
[ "public", "ZonedDateTime", "intoZonedDateTimeOrUse", "(", "ZoneId", "fallback", ")", "{", "try", "{", "return", "intoZonedDateTime", "(", ")", ";", "}", "catch", "(", "RuntimeException", "ex", ")", "{", "return", "intoLocalDateTime", "(", ")", ".", "atZone", "...
Converts to string & permissively parses as a date, uses parsed time zone or falls back on input defaults day->1, month->1, hour->0, minute->0, second->0, nanoseconds->0, time-zone->input @param fallback time zone to use if value has none @throws java.time.format.DateTimeParseException converted string is in an invalid format
[ "Converts", "to", "string", "&", "permissively", "parses", "as", "a", "date", "uses", "parsed", "time", "zone", "or", "falls", "back", "on", "input", "defaults", "day", "-", ">", "1", "month", "-", ">", "1", "hour", "-", ">", "0", "minute", "-", ">",...
aa46ca76247d43f399eb9c2037c9b4c2549b3722
https://github.com/alexheretic/dynamics/blob/aa46ca76247d43f399eb9c2037c9b4c2549b3722/src/main/java/alexh/weak/Converter.java#L234-L237
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/MorphoFactory.java
MorphoFactory.createMorpheme
public final Morpheme createMorpheme(final String word, final String tag) { final Morpheme morpheme = new Morpheme(); morpheme.setValue(word); morpheme.setTag(tag); return morpheme; }
java
public final Morpheme createMorpheme(final String word, final String tag) { final Morpheme morpheme = new Morpheme(); morpheme.setValue(word); morpheme.setTag(tag); return morpheme; }
[ "public", "final", "Morpheme", "createMorpheme", "(", "final", "String", "word", ",", "final", "String", "tag", ")", "{", "final", "Morpheme", "morpheme", "=", "new", "Morpheme", "(", ")", ";", "morpheme", ".", "setValue", "(", "word", ")", ";", "morpheme"...
Construct morpheme object with word and morphological tag. @param word the word @param tag the morphological tag @return the morpheme object
[ "Construct", "morpheme", "object", "with", "word", "and", "morphological", "tag", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/MorphoFactory.java#L36-L41
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/CLI.java
CLI.annotate
public final void annotate(final InputStream inputStream, final OutputStream outputStream) throws IOException, JDOMException { final String model = this.parsedArguments.getString("model"); final String lemmatizerModel = this.parsedArguments .getString("lemmatizerModel"); final boolean allMorphology = this.parsedArguments .getBoolean("allMorphology"); final String multiwords = Boolean.toString(this.parsedArguments .getBoolean("multiwords")); final String dictag = Boolean.toString(this.parsedArguments .getBoolean("dictag")); String outputFormat = parsedArguments.getString("outputFormat"); BufferedReader breader = null; BufferedWriter bwriter = null; breader = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); bwriter = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8")); final KAFDocument kaf = KAFDocument.createFromStream(breader); // language String lang; if (this.parsedArguments.getString("language") != null) { lang = this.parsedArguments.getString("language"); if (!kaf.getLang().equalsIgnoreCase(lang)) { System.err.println("Language parameter in NAF and CLI do not match!!"); // System.exit(1); } } else { lang = kaf.getLang(); } final Properties properties = setAnnotateProperties(model, lemmatizerModel, lang, multiwords, dictag); final Annotate annotator = new Annotate(properties); final KAFDocument.LinguisticProcessor newLp = kaf.addLinguisticProcessor( "terms", "ixa-pipe-pos-" + Files.getNameWithoutExtension(model), this.version + "-" + this.commit); newLp.setBeginTimestamp(); if (allMorphology) { if (outputFormat.equalsIgnoreCase("conll")) { bwriter.write(annotator.getAllTagsLemmasToCoNLL(kaf)); } else { annotator.getAllTagsLemmasToNAF(kaf); newLp.setEndTimestamp(); bwriter.write(kaf.toString()); } } else { if (outputFormat.equalsIgnoreCase("conll")) { bwriter.write(annotator.annotatePOSToCoNLL(kaf)); } else { annotator.annotatePOSToKAF(kaf); newLp.setEndTimestamp(); bwriter.write(kaf.toString()); } } bwriter.close(); breader.close(); }
java
public final void annotate(final InputStream inputStream, final OutputStream outputStream) throws IOException, JDOMException { final String model = this.parsedArguments.getString("model"); final String lemmatizerModel = this.parsedArguments .getString("lemmatizerModel"); final boolean allMorphology = this.parsedArguments .getBoolean("allMorphology"); final String multiwords = Boolean.toString(this.parsedArguments .getBoolean("multiwords")); final String dictag = Boolean.toString(this.parsedArguments .getBoolean("dictag")); String outputFormat = parsedArguments.getString("outputFormat"); BufferedReader breader = null; BufferedWriter bwriter = null; breader = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); bwriter = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8")); final KAFDocument kaf = KAFDocument.createFromStream(breader); // language String lang; if (this.parsedArguments.getString("language") != null) { lang = this.parsedArguments.getString("language"); if (!kaf.getLang().equalsIgnoreCase(lang)) { System.err.println("Language parameter in NAF and CLI do not match!!"); // System.exit(1); } } else { lang = kaf.getLang(); } final Properties properties = setAnnotateProperties(model, lemmatizerModel, lang, multiwords, dictag); final Annotate annotator = new Annotate(properties); final KAFDocument.LinguisticProcessor newLp = kaf.addLinguisticProcessor( "terms", "ixa-pipe-pos-" + Files.getNameWithoutExtension(model), this.version + "-" + this.commit); newLp.setBeginTimestamp(); if (allMorphology) { if (outputFormat.equalsIgnoreCase("conll")) { bwriter.write(annotator.getAllTagsLemmasToCoNLL(kaf)); } else { annotator.getAllTagsLemmasToNAF(kaf); newLp.setEndTimestamp(); bwriter.write(kaf.toString()); } } else { if (outputFormat.equalsIgnoreCase("conll")) { bwriter.write(annotator.annotatePOSToCoNLL(kaf)); } else { annotator.annotatePOSToKAF(kaf); newLp.setEndTimestamp(); bwriter.write(kaf.toString()); } } bwriter.close(); breader.close(); }
[ "public", "final", "void", "annotate", "(", "final", "InputStream", "inputStream", ",", "final", "OutputStream", "outputStream", ")", "throws", "IOException", ",", "JDOMException", "{", "final", "String", "model", "=", "this", ".", "parsedArguments", ".", "getStri...
Main entry point for annotation. Takes system.in as input and outputs annotated text via system.out. @param inputStream the input stream @param outputStream the output stream @throws IOException the exception if not input is provided @throws JDOMException if malformed XML
[ "Main", "entry", "point", "for", "annotation", ".", "Takes", "system", ".", "in", "as", "input", "and", "outputs", "annotated", "text", "via", "system", ".", "out", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/CLI.java#L208-L265
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/CLI.java
CLI.loadAnnotateParameters
private void loadAnnotateParameters() { this.annotateParser.addArgument("-m", "--model") .required(true) .help("It is required to provide a POS tagging model."); this.annotateParser.addArgument("-lm", "--lemmatizerModel") .required(true) .help("It is required to provide a lemmatizer model."); this.annotateParser.addArgument("-l", "--language") .choices("de", "en", "es", "eu", "fr", "gl", "it", "nl") .required(false) .help("Choose a language."); this.annotateParser.addArgument("--beamSize") .required(false) .setDefault(DEFAULT_BEAM_SIZE) .help("Choose beam size for decoding, it defaults to 3."); annotateParser.addArgument("-o", "--outputFormat") .required(false) .choices("naf", "conll") .setDefault(Flags.DEFAULT_OUTPUT_FORMAT) .help("Choose output format; it defaults to NAF.\n"); this.annotateParser.addArgument("-mw", "--multiwords") .action(Arguments.storeTrue()) .help("Use to detect and process multiwords.\n"); this.annotateParser.addArgument("-d", "--dictag") .action(Arguments.storeTrue()) .help("Post process POS tagger output with a monosemic dictionary.\n"); this.annotateParser.addArgument("-a","--allMorphology") .action(Arguments.storeTrue()) .help("Print all the POS tags and lemmas before disambiguation.\n"); }
java
private void loadAnnotateParameters() { this.annotateParser.addArgument("-m", "--model") .required(true) .help("It is required to provide a POS tagging model."); this.annotateParser.addArgument("-lm", "--lemmatizerModel") .required(true) .help("It is required to provide a lemmatizer model."); this.annotateParser.addArgument("-l", "--language") .choices("de", "en", "es", "eu", "fr", "gl", "it", "nl") .required(false) .help("Choose a language."); this.annotateParser.addArgument("--beamSize") .required(false) .setDefault(DEFAULT_BEAM_SIZE) .help("Choose beam size for decoding, it defaults to 3."); annotateParser.addArgument("-o", "--outputFormat") .required(false) .choices("naf", "conll") .setDefault(Flags.DEFAULT_OUTPUT_FORMAT) .help("Choose output format; it defaults to NAF.\n"); this.annotateParser.addArgument("-mw", "--multiwords") .action(Arguments.storeTrue()) .help("Use to detect and process multiwords.\n"); this.annotateParser.addArgument("-d", "--dictag") .action(Arguments.storeTrue()) .help("Post process POS tagger output with a monosemic dictionary.\n"); this.annotateParser.addArgument("-a","--allMorphology") .action(Arguments.storeTrue()) .help("Print all the POS tags and lemmas before disambiguation.\n"); }
[ "private", "void", "loadAnnotateParameters", "(", ")", "{", "this", ".", "annotateParser", ".", "addArgument", "(", "\"-m\"", ",", "\"--model\"", ")", ".", "required", "(", "true", ")", ".", "help", "(", "\"It is required to provide a POS tagging model.\"", ")", "...
Generate the annotation parameter of the CLI.
[ "Generate", "the", "annotation", "parameter", "of", "the", "CLI", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/CLI.java#L270-L300
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/CLI.java
CLI.train
public final void train() throws IOException { // load training parameters file final String paramFile = this.parsedArguments.getString("params"); final TrainingParameters params = InputOutputUtils .loadTrainingParameters(paramFile); String outModel = null; if (params.getSettings().get("OutputModel") == null || params.getSettings().get("OutputModel").length() == 0) { outModel = Files.getNameWithoutExtension(paramFile) + ".bin"; params.put("OutputModel", outModel); } else { outModel = Flags.getModel(params); } String component = Flags.getComponent(params); if (component.equalsIgnoreCase("POS")) { final TaggerTrainer posTaggerTrainer = new FixedTrainer(params); final POSModel trainedModel = posTaggerTrainer.train(params); CmdLineUtil.writeModel("ixa-pipe-pos", new File(outModel), trainedModel); } else if (component.equalsIgnoreCase("Lemma")) { final LemmatizerTrainer lemmatizerTrainer = new LemmatizerFixedTrainer(params); final LemmatizerModel trainedModel = lemmatizerTrainer.train(params); CmdLineUtil.writeModel("ixa-pipe-lemma", new File(outModel), trainedModel); } }
java
public final void train() throws IOException { // load training parameters file final String paramFile = this.parsedArguments.getString("params"); final TrainingParameters params = InputOutputUtils .loadTrainingParameters(paramFile); String outModel = null; if (params.getSettings().get("OutputModel") == null || params.getSettings().get("OutputModel").length() == 0) { outModel = Files.getNameWithoutExtension(paramFile) + ".bin"; params.put("OutputModel", outModel); } else { outModel = Flags.getModel(params); } String component = Flags.getComponent(params); if (component.equalsIgnoreCase("POS")) { final TaggerTrainer posTaggerTrainer = new FixedTrainer(params); final POSModel trainedModel = posTaggerTrainer.train(params); CmdLineUtil.writeModel("ixa-pipe-pos", new File(outModel), trainedModel); } else if (component.equalsIgnoreCase("Lemma")) { final LemmatizerTrainer lemmatizerTrainer = new LemmatizerFixedTrainer(params); final LemmatizerModel trainedModel = lemmatizerTrainer.train(params); CmdLineUtil.writeModel("ixa-pipe-lemma", new File(outModel), trainedModel); } }
[ "public", "final", "void", "train", "(", ")", "throws", "IOException", "{", "// load training parameters file", "final", "String", "paramFile", "=", "this", ".", "parsedArguments", ".", "getString", "(", "\"params\"", ")", ";", "final", "TrainingParameters", "params...
Main entry point for training. @throws IOException throws an exception if errors in the various file inputs.
[ "Main", "entry", "point", "for", "training", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/CLI.java#L307-L330
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/CLI.java
CLI.eval
public final void eval() throws IOException { final String component = this.parsedArguments.getString("component"); final String testFile = this.parsedArguments.getString("testSet"); final String model = this.parsedArguments.getString("model"); Evaluate evaluator = null; if (component.equalsIgnoreCase("pos")) { evaluator = new POSEvaluate(testFile, model); } else { evaluator = new LemmaEvaluate(testFile, model); } if (this.parsedArguments.getString("evalReport") != null) { if (this.parsedArguments.getString("evalReport").equalsIgnoreCase( "detailed")) { evaluator.detailEvaluate(); } else if (this.parsedArguments.getString("evalReport").equalsIgnoreCase( "error")) { evaluator.evalError(); } else if (this.parsedArguments.getString("evalReport").equalsIgnoreCase( "brief")) { evaluator.evaluate(); } } else { evaluator.evaluate(); } }
java
public final void eval() throws IOException { final String component = this.parsedArguments.getString("component"); final String testFile = this.parsedArguments.getString("testSet"); final String model = this.parsedArguments.getString("model"); Evaluate evaluator = null; if (component.equalsIgnoreCase("pos")) { evaluator = new POSEvaluate(testFile, model); } else { evaluator = new LemmaEvaluate(testFile, model); } if (this.parsedArguments.getString("evalReport") != null) { if (this.parsedArguments.getString("evalReport").equalsIgnoreCase( "detailed")) { evaluator.detailEvaluate(); } else if (this.parsedArguments.getString("evalReport").equalsIgnoreCase( "error")) { evaluator.evalError(); } else if (this.parsedArguments.getString("evalReport").equalsIgnoreCase( "brief")) { evaluator.evaluate(); } } else { evaluator.evaluate(); } }
[ "public", "final", "void", "eval", "(", ")", "throws", "IOException", "{", "final", "String", "component", "=", "this", ".", "parsedArguments", ".", "getString", "(", "\"component\"", ")", ";", "final", "String", "testFile", "=", "this", ".", "parsedArguments"...
Main entry point for evaluation. @throws IOException the io exception thrown if errors with paths are present
[ "Main", "entry", "point", "for", "evaluation", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/CLI.java#L345-L371
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/CLI.java
CLI.loadEvalParameters
private void loadEvalParameters() { this.evalParser.addArgument("-c","--component") .required(true) .choices("pos","lemma") .help("Choose component for evaluation"); this.evalParser.addArgument("-m", "--model") .required(true) .help("Choose model"); this.evalParser.addArgument("-t", "--testSet") .required(true) .help("Input testset for evaluation"); this.evalParser.addArgument("--evalReport") .required(false) .choices("brief", "detailed", "error") .help("Choose type of evaluation report; defaults to brief"); }
java
private void loadEvalParameters() { this.evalParser.addArgument("-c","--component") .required(true) .choices("pos","lemma") .help("Choose component for evaluation"); this.evalParser.addArgument("-m", "--model") .required(true) .help("Choose model"); this.evalParser.addArgument("-t", "--testSet") .required(true) .help("Input testset for evaluation"); this.evalParser.addArgument("--evalReport") .required(false) .choices("brief", "detailed", "error") .help("Choose type of evaluation report; defaults to brief"); }
[ "private", "void", "loadEvalParameters", "(", ")", "{", "this", ".", "evalParser", ".", "addArgument", "(", "\"-c\"", ",", "\"--component\"", ")", ".", "required", "(", "true", ")", ".", "choices", "(", "\"pos\"", ",", "\"lemma\"", ")", ".", "help", "(", ...
Load the evaluation parameters of the CLI.
[ "Load", "the", "evaluation", "parameters", "of", "the", "CLI", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/CLI.java#L451-L466
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/CLI.java
CLI.crossValidate
public final void crossValidate() throws IOException { final String paramFile = this.parsedArguments.getString("params"); final TrainingParameters params = InputOutputUtils .loadTrainingParameters(paramFile); final POSCrossValidator crossValidator = new POSCrossValidator(params); crossValidator.crossValidate(params); }
java
public final void crossValidate() throws IOException { final String paramFile = this.parsedArguments.getString("params"); final TrainingParameters params = InputOutputUtils .loadTrainingParameters(paramFile); final POSCrossValidator crossValidator = new POSCrossValidator(params); crossValidator.crossValidate(params); }
[ "public", "final", "void", "crossValidate", "(", ")", "throws", "IOException", "{", "final", "String", "paramFile", "=", "this", ".", "parsedArguments", ".", "getString", "(", "\"params\"", ")", ";", "final", "TrainingParameters", "params", "=", "InputOutputUtils"...
Main access to the cross validation. @throws IOException input output exception if problems with corpora
[ "Main", "access", "to", "the", "cross", "validation", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/CLI.java#L473-L480
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/CLI.java
CLI.loadServerParameters
private void loadServerParameters() { serverParser.addArgument("-p", "--port").required(true) .help("Port to be assigned to the server.\n"); serverParser.addArgument("-m", "--model").required(true) .help("It is required to provide a model to perform POS tagging."); this.serverParser.addArgument("-lm", "--lemmatizerModel") .required(true) .help("It is required to provide a lemmatizer model."); serverParser.addArgument("-l", "--language") .choices("de", "en", "es", "eu", "fr", "gl", "it", "nl") .required(true) .help("Choose a language to perform annotation with ixa-pipe-pos."); serverParser.addArgument("--beamSize").required(false) .setDefault(DEFAULT_BEAM_SIZE) .help("Choose beam size for decoding, it defaults to 3."); serverParser.addArgument("-o", "--outputFormat").required(false) .choices("naf", "conll") .setDefault(Flags.DEFAULT_OUTPUT_FORMAT) .help("Choose output format; it defaults to NAF.\n"); serverParser.addArgument("-mw", "--multiwords") .action(Arguments.storeTrue()) .help("Use to detect and process multiwords.\n"); serverParser.addArgument("-d", "--dictag") .action(Arguments.storeTrue()) .help("Post process POS tagger output with a monosemic dictionary.\n"); serverParser.addArgument("-a","--allMorphology") .action(Arguments.storeTrue()) .help("Print all the POS tags and lemmas before disambiguation.\n"); }
java
private void loadServerParameters() { serverParser.addArgument("-p", "--port").required(true) .help("Port to be assigned to the server.\n"); serverParser.addArgument("-m", "--model").required(true) .help("It is required to provide a model to perform POS tagging."); this.serverParser.addArgument("-lm", "--lemmatizerModel") .required(true) .help("It is required to provide a lemmatizer model."); serverParser.addArgument("-l", "--language") .choices("de", "en", "es", "eu", "fr", "gl", "it", "nl") .required(true) .help("Choose a language to perform annotation with ixa-pipe-pos."); serverParser.addArgument("--beamSize").required(false) .setDefault(DEFAULT_BEAM_SIZE) .help("Choose beam size for decoding, it defaults to 3."); serverParser.addArgument("-o", "--outputFormat").required(false) .choices("naf", "conll") .setDefault(Flags.DEFAULT_OUTPUT_FORMAT) .help("Choose output format; it defaults to NAF.\n"); serverParser.addArgument("-mw", "--multiwords") .action(Arguments.storeTrue()) .help("Use to detect and process multiwords.\n"); serverParser.addArgument("-d", "--dictag") .action(Arguments.storeTrue()) .help("Post process POS tagger output with a monosemic dictionary.\n"); serverParser.addArgument("-a","--allMorphology") .action(Arguments.storeTrue()) .help("Print all the POS tags and lemmas before disambiguation.\n"); }
[ "private", "void", "loadServerParameters", "(", ")", "{", "serverParser", ".", "addArgument", "(", "\"-p\"", ",", "\"--port\"", ")", ".", "required", "(", "true", ")", ".", "help", "(", "\"Port to be assigned to the server.\\n\"", ")", ";", "serverParser", ".", ...
Create the available parameters for POS tagging.
[ "Create", "the", "available", "parameters", "for", "POS", "tagging", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/CLI.java#L493-L522
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/CLI.java
CLI.setAnnotateProperties
private Properties setAnnotateProperties(final String model, final String lemmatizerModel, final String language, final String multiwords, final String dictag) { final Properties annotateProperties = new Properties(); annotateProperties.setProperty("model", model); annotateProperties.setProperty("lemmatizerModel", lemmatizerModel); annotateProperties.setProperty("language", language); annotateProperties.setProperty("multiwords", multiwords); annotateProperties.setProperty("dictag", dictag); return annotateProperties; }
java
private Properties setAnnotateProperties(final String model, final String lemmatizerModel, final String language, final String multiwords, final String dictag) { final Properties annotateProperties = new Properties(); annotateProperties.setProperty("model", model); annotateProperties.setProperty("lemmatizerModel", lemmatizerModel); annotateProperties.setProperty("language", language); annotateProperties.setProperty("multiwords", multiwords); annotateProperties.setProperty("dictag", dictag); return annotateProperties; }
[ "private", "Properties", "setAnnotateProperties", "(", "final", "String", "model", ",", "final", "String", "lemmatizerModel", ",", "final", "String", "language", ",", "final", "String", "multiwords", ",", "final", "String", "dictag", ")", "{", "final", "Properties...
Generate Properties objects for CLI usage. @param model the model to perform the annotation @param language the language @param multiwords whether multiwords are to be detected @param dictag whether tagging from a dictionary is activated @return a properties object
[ "Generate", "Properties", "objects", "for", "CLI", "usage", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/CLI.java#L543-L553
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
StrTokenizer.getTokenArray
public String[] getTokenArray() { checkTokenized(); if (this.tokens == null) { return null; } final String[] clone = new String[this.tokens.length]; for (int i = 0; i < this.tokens.length; i++) { clone[i] = this.tokens[i]; } return clone; }
java
public String[] getTokenArray() { checkTokenized(); if (this.tokens == null) { return null; } final String[] clone = new String[this.tokens.length]; for (int i = 0; i < this.tokens.length; i++) { clone[i] = this.tokens[i]; } return clone; }
[ "public", "String", "[", "]", "getTokenArray", "(", ")", "{", "checkTokenized", "(", ")", ";", "if", "(", "this", ".", "tokens", "==", "null", ")", "{", "return", "null", ";", "}", "final", "String", "[", "]", "clone", "=", "new", "String", "[", "t...
Gets a copy of the full token list as an independent modifiable array. @return the tokens as a String array
[ "Gets", "a", "copy", "of", "the", "full", "token", "list", "as", "an", "independent", "modifiable", "array", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java#L436-L446
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
StrTokenizer.getTokenList
public List<String> getTokenList() { checkTokenized(); final List<String> list = new ArrayList<>(tokens.length); list.addAll(Arrays.asList(tokens)); return list; }
java
public List<String> getTokenList() { checkTokenized(); final List<String> list = new ArrayList<>(tokens.length); list.addAll(Arrays.asList(tokens)); return list; }
[ "public", "List", "<", "String", ">", "getTokenList", "(", ")", "{", "checkTokenized", "(", ")", ";", "final", "List", "<", "String", ">", "list", "=", "new", "ArrayList", "<>", "(", "tokens", ".", "length", ")", ";", "list", ".", "addAll", "(", "Arr...
Gets a copy of the full token list as an independent modifiable list. @return the tokens as a String array
[ "Gets", "a", "copy", "of", "the", "full", "token", "list", "as", "an", "independent", "modifiable", "list", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java#L453-L458
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
StrTokenizer.reset
public StrTokenizer reset(final String input) { reset(); if (input != null) { this.chars = input.toCharArray(); } else { this.chars = null; } return this; }
java
public StrTokenizer reset(final String input) { reset(); if (input != null) { this.chars = input.toCharArray(); } else { this.chars = null; } return this; }
[ "public", "StrTokenizer", "reset", "(", "final", "String", "input", ")", "{", "reset", "(", ")", ";", "if", "(", "input", "!=", "null", ")", "{", "this", ".", "chars", "=", "input", ".", "toCharArray", "(", ")", ";", "}", "else", "{", "this", ".", ...
Reset this tokenizer, giving it a new input string to parse. In this manner you can re-use a tokenizer with the same settings on multiple input lines. @param input the new string to tokenize, null sets no text to parse @return this, to enable chaining
[ "Reset", "this", "tokenizer", "giving", "it", "a", "new", "input", "string", "to", "parse", ".", "In", "this", "manner", "you", "can", "re", "-", "use", "a", "tokenizer", "with", "the", "same", "settings", "on", "multiple", "input", "lines", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java#L481-L489
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
StrTokenizer.checkTokenized
private void checkTokenized() { if (tokens == null) { if (chars == null) { // still call tokenize as subclass may do some work final List<String> split = tokenize(null, 0, 0); tokens = split.toArray(new String[split.size()]); } else { final List<String> split = tokenize(chars, 0, chars.length); tokens = split.toArray(new String[split.size()]); } } }
java
private void checkTokenized() { if (tokens == null) { if (chars == null) { // still call tokenize as subclass may do some work final List<String> split = tokenize(null, 0, 0); tokens = split.toArray(new String[split.size()]); } else { final List<String> split = tokenize(chars, 0, chars.length); tokens = split.toArray(new String[split.size()]); } } }
[ "private", "void", "checkTokenized", "(", ")", "{", "if", "(", "tokens", "==", "null", ")", "{", "if", "(", "chars", "==", "null", ")", "{", "// still call tokenize as subclass may do some work", "final", "List", "<", "String", ">", "split", "=", "tokenize", ...
Checks if tokenization has been done, and if not then do it.
[ "Checks", "if", "tokenization", "has", "been", "done", "and", "if", "not", "then", "do", "it", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java#L611-L622
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
StrTokenizer.addToken
private void addToken(final List<String> list, String tok) { if (StringUtils.isEmpty(tok)) { if (isIgnoreEmptyTokens()) { return; } if (isEmptyTokenAsNull()) { tok = null; } } list.add(tok); }
java
private void addToken(final List<String> list, String tok) { if (StringUtils.isEmpty(tok)) { if (isIgnoreEmptyTokens()) { return; } if (isEmptyTokenAsNull()) { tok = null; } } list.add(tok); }
[ "private", "void", "addToken", "(", "final", "List", "<", "String", ">", "list", ",", "String", "tok", ")", "{", "if", "(", "StringUtils", ".", "isEmpty", "(", "tok", ")", ")", "{", "if", "(", "isIgnoreEmptyTokens", "(", ")", ")", "{", "return", ";",...
Adds a token to a list, paying attention to the parameters we've set. @param list the list to add to @param tok the token to add
[ "Adds", "a", "token", "to", "a", "list", "paying", "attention", "to", "the", "parameters", "we", "ve", "set", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java#L671-L681
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
StrTokenizer.readNextToken
private int readNextToken(final char[] srcChars, int start, final int len, final StrBuilder workArea, final List<String> tokenList) { // skip all leading whitespace, unless it is the // field delimiter or the quote character while (start < len) { final int removeLen = Math.max( getIgnoredMatcher().isMatch(srcChars, start, start, len), getTrimmerMatcher().isMatch(srcChars, start, start, len)); if (removeLen == 0 || getDelimiterMatcher().isMatch(srcChars, start, start, len) > 0 || getQuoteMatcher().isMatch(srcChars, start, start, len) > 0) { break; } start += removeLen; } // handle reaching end if (start >= len) { addToken(tokenList, StringUtils.EMPTY); return -1; } // handle empty token final int delimLen = getDelimiterMatcher().isMatch(srcChars, start, start, len); if (delimLen > 0) { addToken(tokenList, StringUtils.EMPTY); return start + delimLen; } // handle found token final int quoteLen = getQuoteMatcher().isMatch(srcChars, start, start, len); if (quoteLen > 0) { return readWithQuotes(srcChars, start + quoteLen, len, workArea, tokenList, start, quoteLen); } return readWithQuotes(srcChars, start, len, workArea, tokenList, 0, 0); }
java
private int readNextToken(final char[] srcChars, int start, final int len, final StrBuilder workArea, final List<String> tokenList) { // skip all leading whitespace, unless it is the // field delimiter or the quote character while (start < len) { final int removeLen = Math.max( getIgnoredMatcher().isMatch(srcChars, start, start, len), getTrimmerMatcher().isMatch(srcChars, start, start, len)); if (removeLen == 0 || getDelimiterMatcher().isMatch(srcChars, start, start, len) > 0 || getQuoteMatcher().isMatch(srcChars, start, start, len) > 0) { break; } start += removeLen; } // handle reaching end if (start >= len) { addToken(tokenList, StringUtils.EMPTY); return -1; } // handle empty token final int delimLen = getDelimiterMatcher().isMatch(srcChars, start, start, len); if (delimLen > 0) { addToken(tokenList, StringUtils.EMPTY); return start + delimLen; } // handle found token final int quoteLen = getQuoteMatcher().isMatch(srcChars, start, start, len); if (quoteLen > 0) { return readWithQuotes(srcChars, start + quoteLen, len, workArea, tokenList, start, quoteLen); } return readWithQuotes(srcChars, start, len, workArea, tokenList, 0, 0); }
[ "private", "int", "readNextToken", "(", "final", "char", "[", "]", "srcChars", ",", "int", "start", ",", "final", "int", "len", ",", "final", "StrBuilder", "workArea", ",", "final", "List", "<", "String", ">", "tokenList", ")", "{", "// skip all leading whit...
Reads character by character through the String to get the next token. @param srcChars the character array being tokenized @param start the first character of field @param len the length of the character array being tokenized @param workArea a temporary work area @param tokenList the list of parsed tokens @return the starting position of the next field (the character immediately after the delimiter), or -1 if end of string found
[ "Reads", "character", "by", "character", "through", "the", "String", "to", "get", "the", "next", "token", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java#L694-L728
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
StrTokenizer.readWithQuotes
private int readWithQuotes(final char[] srcChars, final int start, final int len, final StrBuilder workArea, final List<String> tokenList, final int quoteStart, final int quoteLen) { // Loop until we've found the end of the quoted // string or the end of the input workArea.clear(); int pos = start; boolean quoting = quoteLen > 0; int trimStart = 0; while (pos < len) { // quoting mode can occur several times throughout a string // we must switch between quoting and non-quoting until we // encounter a non-quoted delimiter, or end of string if (quoting) { // In quoting mode // If we've found a quote character, see if it's // followed by a second quote. If so, then we need // to actually put the quote character into the token // rather than end the token. if (isQuote(srcChars, pos, len, quoteStart, quoteLen)) { if (isQuote(srcChars, pos + quoteLen, len, quoteStart, quoteLen)) { // matched pair of quotes, thus an escaped quote workArea.append(srcChars, pos, quoteLen); pos += quoteLen * 2; trimStart = workArea.size(); continue; } // end of quoting quoting = false; pos += quoteLen; continue; } // copy regular character from inside quotes workArea.append(srcChars[pos++]); trimStart = workArea.size(); } else { // Not in quoting mode // check for delimiter, and thus end of token final int delimLen = getDelimiterMatcher().isMatch(srcChars, pos, start, len); if (delimLen > 0) { // return condition when end of token found addToken(tokenList, workArea.substring(0, trimStart)); return pos + delimLen; } // check for quote, and thus back into quoting mode if (quoteLen > 0 && isQuote(srcChars, pos, len, quoteStart, quoteLen)) { quoting = true; pos += quoteLen; continue; } // check for ignored (outside quotes), and ignore final int ignoredLen = getIgnoredMatcher().isMatch(srcChars, pos, start, len); if (ignoredLen > 0) { pos += ignoredLen; continue; } // check for trimmed character // don't yet know if its at the end, so copy to workArea // use trimStart to keep track of trim at the end final int trimmedLen = getTrimmerMatcher().isMatch(srcChars, pos, start, len); if (trimmedLen > 0) { workArea.append(srcChars, pos, trimmedLen); pos += trimmedLen; continue; } // copy regular character from outside quotes workArea.append(srcChars[pos++]); trimStart = workArea.size(); } } // return condition when end of string found addToken(tokenList, workArea.substring(0, trimStart)); return -1; }
java
private int readWithQuotes(final char[] srcChars, final int start, final int len, final StrBuilder workArea, final List<String> tokenList, final int quoteStart, final int quoteLen) { // Loop until we've found the end of the quoted // string or the end of the input workArea.clear(); int pos = start; boolean quoting = quoteLen > 0; int trimStart = 0; while (pos < len) { // quoting mode can occur several times throughout a string // we must switch between quoting and non-quoting until we // encounter a non-quoted delimiter, or end of string if (quoting) { // In quoting mode // If we've found a quote character, see if it's // followed by a second quote. If so, then we need // to actually put the quote character into the token // rather than end the token. if (isQuote(srcChars, pos, len, quoteStart, quoteLen)) { if (isQuote(srcChars, pos + quoteLen, len, quoteStart, quoteLen)) { // matched pair of quotes, thus an escaped quote workArea.append(srcChars, pos, quoteLen); pos += quoteLen * 2; trimStart = workArea.size(); continue; } // end of quoting quoting = false; pos += quoteLen; continue; } // copy regular character from inside quotes workArea.append(srcChars[pos++]); trimStart = workArea.size(); } else { // Not in quoting mode // check for delimiter, and thus end of token final int delimLen = getDelimiterMatcher().isMatch(srcChars, pos, start, len); if (delimLen > 0) { // return condition when end of token found addToken(tokenList, workArea.substring(0, trimStart)); return pos + delimLen; } // check for quote, and thus back into quoting mode if (quoteLen > 0 && isQuote(srcChars, pos, len, quoteStart, quoteLen)) { quoting = true; pos += quoteLen; continue; } // check for ignored (outside quotes), and ignore final int ignoredLen = getIgnoredMatcher().isMatch(srcChars, pos, start, len); if (ignoredLen > 0) { pos += ignoredLen; continue; } // check for trimmed character // don't yet know if its at the end, so copy to workArea // use trimStart to keep track of trim at the end final int trimmedLen = getTrimmerMatcher().isMatch(srcChars, pos, start, len); if (trimmedLen > 0) { workArea.append(srcChars, pos, trimmedLen); pos += trimmedLen; continue; } // copy regular character from outside quotes workArea.append(srcChars[pos++]); trimStart = workArea.size(); } } // return condition when end of string found addToken(tokenList, workArea.substring(0, trimStart)); return -1; }
[ "private", "int", "readWithQuotes", "(", "final", "char", "[", "]", "srcChars", ",", "final", "int", "start", ",", "final", "int", "len", ",", "final", "StrBuilder", "workArea", ",", "final", "List", "<", "String", ">", "tokenList", ",", "final", "int", ...
Reads a possibly quoted string token. @param srcChars the character array being tokenized @param start the first character of field @param len the length of the character array being tokenized @param workArea a temporary work area @param tokenList the list of parsed tokens @param quoteStart the start position of the matched quote, 0 if no quoting @param quoteLen the length of the matched quote, 0 if no quoting @return the starting position of the next field (the character immediately after the delimiter, or if end of string found, then the length of string
[ "Reads", "a", "possibly", "quoted", "string", "token", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java#L744-L827
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
StrTokenizer.cloneReset
Object cloneReset() throws CloneNotSupportedException { // this method exists to enable 100% test coverage final StrTokenizer cloned = new StrTokenizer(); if (this.chars != null) { cloned.chars = new char[this.chars.length]; for (int i = 0; i < this.chars.length; i++) { cloned.chars[i] = this.chars[i]; } } if (this.tokens == null) { cloned.tokens = null; } else { cloned.tokens = this.getTokenArray(); } cloned.tokenPos = this.tokenPos; cloned.emptyAsNull = this.emptyAsNull; cloned.ignoreEmptyTokens = this.ignoreEmptyTokens; cloned.delimMatcher = this.delimMatcher; cloned.quoteMatcher = this.quoteMatcher; cloned.ignoredMatcher = this.ignoredMatcher; cloned.trimmerMatcher = this.trimmerMatcher; cloned.reset(); return cloned; }
java
Object cloneReset() throws CloneNotSupportedException { // this method exists to enable 100% test coverage final StrTokenizer cloned = new StrTokenizer(); if (this.chars != null) { cloned.chars = new char[this.chars.length]; for (int i = 0; i < this.chars.length; i++) { cloned.chars[i] = this.chars[i]; } } if (this.tokens == null) { cloned.tokens = null; } else { cloned.tokens = this.getTokenArray(); } cloned.tokenPos = this.tokenPos; cloned.emptyAsNull = this.emptyAsNull; cloned.ignoreEmptyTokens = this.ignoreEmptyTokens; cloned.delimMatcher = this.delimMatcher; cloned.quoteMatcher = this.quoteMatcher; cloned.ignoredMatcher = this.ignoredMatcher; cloned.trimmerMatcher = this.trimmerMatcher; cloned.reset(); return cloned; }
[ "Object", "cloneReset", "(", ")", "throws", "CloneNotSupportedException", "{", "// this method exists to enable 100% test coverage", "final", "StrTokenizer", "cloned", "=", "new", "StrTokenizer", "(", ")", ";", "if", "(", "this", ".", "chars", "!=", "null", ")", "{"...
Creates a new instance of this Tokenizer. The new instance is reset so that it will be at the start of the token list. @return a new instance of this Tokenizer which has been reset. @throws CloneNotSupportedException if there is a problem cloning
[ "Creates", "a", "new", "instance", "of", "this", "Tokenizer", ".", "The", "new", "instance", "is", "reset", "so", "that", "it", "will", "be", "at", "the", "start", "of", "the", "token", "list", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java#L1098-L1124
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/lemma/dict/MorfologikLemmatizer.java
MorfologikLemmatizer.getLemmaTagsDict
private HashMap<List<String>, String> getLemmaTagsDict(final String word) { final List<WordData> wdList = this.dictLookup.lookup(word); final HashMap<List<String>, String> dictMap = new HashMap<List<String>, String>(); for (final WordData wd : wdList) { final List<String> wordLemmaTags = new ArrayList<String>(); wordLemmaTags.add(word); wordLemmaTags.add(wd.getTag().toString()); dictMap.put(wordLemmaTags, wd.getStem().toString()); } return dictMap; }
java
private HashMap<List<String>, String> getLemmaTagsDict(final String word) { final List<WordData> wdList = this.dictLookup.lookup(word); final HashMap<List<String>, String> dictMap = new HashMap<List<String>, String>(); for (final WordData wd : wdList) { final List<String> wordLemmaTags = new ArrayList<String>(); wordLemmaTags.add(word); wordLemmaTags.add(wd.getTag().toString()); dictMap.put(wordLemmaTags, wd.getStem().toString()); } return dictMap; }
[ "private", "HashMap", "<", "List", "<", "String", ">", ",", "String", ">", "getLemmaTagsDict", "(", "final", "String", "word", ")", "{", "final", "List", "<", "WordData", ">", "wdList", "=", "this", ".", "dictLookup", ".", "lookup", "(", "word", ")", "...
Get the lemma for a surface form word and a postag from a FSA morfologik generated dictionary. @param word the surface form @return the hashmap with the word and tag as keys and the lemma as value
[ "Get", "the", "lemma", "for", "a", "surface", "form", "word", "and", "a", "postag", "from", "a", "FSA", "morfologik", "generated", "dictionary", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/lemma/dict/MorfologikLemmatizer.java#L71-L81
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/lemma/dict/MorfologikLemmatizer.java
MorfologikLemmatizer.getDictMap
private HashMap<List<String>, String> getDictMap(final String word, final String postag) { HashMap<List<String>, String> dictMap = new HashMap<List<String>, String>(); dictMap = this.getLemmaTagsDict(word.toLowerCase()); return dictMap; }
java
private HashMap<List<String>, String> getDictMap(final String word, final String postag) { HashMap<List<String>, String> dictMap = new HashMap<List<String>, String>(); dictMap = this.getLemmaTagsDict(word.toLowerCase()); return dictMap; }
[ "private", "HashMap", "<", "List", "<", "String", ">", ",", "String", ">", "getDictMap", "(", "final", "String", "word", ",", "final", "String", "postag", ")", "{", "HashMap", "<", "List", "<", "String", ">", ",", "String", ">", "dictMap", "=", "new", ...
Generates the dictionary map. @param word the surface form word @param postag the postag assigned by the pos tagger @return the hash map dictionary
[ "Generates", "the", "dictionary", "map", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/lemma/dict/MorfologikLemmatizer.java#L114-L119
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/StringUtils.java
StringUtils.getStringFromTokens
public static String getStringFromTokens(final String[] tokens) { final StringBuilder sb = new StringBuilder(); for (final String tok : tokens) { sb.append(tok).append(" "); } return sb.toString().trim(); }
java
public static String getStringFromTokens(final String[] tokens) { final StringBuilder sb = new StringBuilder(); for (final String tok : tokens) { sb.append(tok).append(" "); } return sb.toString().trim(); }
[ "public", "static", "String", "getStringFromTokens", "(", "final", "String", "[", "]", "tokens", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "final", "String", "tok", ":", "tokens", ")", "{", "sb", "....
Gets the String joined by a space of an array of tokens. @param tokens an array of tokens representing a tokenized sentence @return sentence the sentence corresponding to the tokens
[ "Gets", "the", "String", "joined", "by", "a", "space", "of", "an", "array", "of", "tokens", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/StringUtils.java#L163-L169
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/StringUtils.java
StringUtils.getFilesInDir
public static List<File> getFilesInDir(final File inputPath) { final List<File> fileList = new ArrayList<File>(); for (final File aFile : Files.fileTreeTraverser().preOrderTraversal( inputPath)) { if (aFile.isFile()) { fileList.add(aFile); } } return fileList; }
java
public static List<File> getFilesInDir(final File inputPath) { final List<File> fileList = new ArrayList<File>(); for (final File aFile : Files.fileTreeTraverser().preOrderTraversal( inputPath)) { if (aFile.isFile()) { fileList.add(aFile); } } return fileList; }
[ "public", "static", "List", "<", "File", ">", "getFilesInDir", "(", "final", "File", "inputPath", ")", "{", "final", "List", "<", "File", ">", "fileList", "=", "new", "ArrayList", "<", "File", ">", "(", ")", ";", "for", "(", "final", "File", "aFile", ...
Recursively get every file in a directory and add them to a list. @param inputPath the input directory @return the list containing all the files
[ "Recursively", "get", "every", "file", "in", "a", "directory", "and", "add", "them", "to", "a", "list", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/StringUtils.java#L187-L196
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/StringUtils.java
StringUtils.minimum
private static int minimum(int a, int b, int c) { int minValue; minValue = a; if (b < minValue) { minValue = b; } if (c < minValue) { minValue = c; } return minValue; }
java
private static int minimum(int a, int b, int c) { int minValue; minValue = a; if (b < minValue) { minValue = b; } if (c < minValue) { minValue = c; } return minValue; }
[ "private", "static", "int", "minimum", "(", "int", "a", ",", "int", "b", ",", "int", "c", ")", "{", "int", "minValue", ";", "minValue", "=", "a", ";", "if", "(", "b", "<", "minValue", ")", "{", "minValue", "=", "b", ";", "}", "if", "(", "c", ...
Get mininum of three values. @param a number a @param b number b @param c number c @return the minimum
[ "Get", "mininum", "of", "three", "values", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/StringUtils.java#L206-L216
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/Resources.java
Resources.mapGermanTagSetToKaf
private static String mapGermanTagSetToKaf(final String postag) { if (postag.startsWith("ADV")) { return "A"; // adverb } else if (postag.startsWith("KO")) { return "C"; // conjunction } else if (postag.equalsIgnoreCase("ART")) { return "D"; // determiner and predeterminer } else if (postag.startsWith("ADJ")) { return "G"; // adjective } else if (postag.equalsIgnoreCase("NN")) { return "N"; // common noun } else if (postag.startsWith("NE")) { return "R"; // proper noun } else if (postag.startsWith("AP")) { return "P"; // preposition } else if (postag.startsWith("PD") || postag.startsWith("PI") || postag.startsWith("PP") || postag.startsWith("PR") || postag.startsWith("PW") || postag.startsWith("PA")) { return "Q"; // pronoun } else if (postag.startsWith("V")) { return "V"; // verb } else { return "O"; // other } }
java
private static String mapGermanTagSetToKaf(final String postag) { if (postag.startsWith("ADV")) { return "A"; // adverb } else if (postag.startsWith("KO")) { return "C"; // conjunction } else if (postag.equalsIgnoreCase("ART")) { return "D"; // determiner and predeterminer } else if (postag.startsWith("ADJ")) { return "G"; // adjective } else if (postag.equalsIgnoreCase("NN")) { return "N"; // common noun } else if (postag.startsWith("NE")) { return "R"; // proper noun } else if (postag.startsWith("AP")) { return "P"; // preposition } else if (postag.startsWith("PD") || postag.startsWith("PI") || postag.startsWith("PP") || postag.startsWith("PR") || postag.startsWith("PW") || postag.startsWith("PA")) { return "Q"; // pronoun } else if (postag.startsWith("V")) { return "V"; // verb } else { return "O"; // other } }
[ "private", "static", "String", "mapGermanTagSetToKaf", "(", "final", "String", "postag", ")", "{", "if", "(", "postag", ".", "startsWith", "(", "\"ADV\"", ")", ")", "{", "return", "\"A\"", ";", "// adverb", "}", "else", "if", "(", "postag", ".", "startsWit...
Mapping between CoNLL 2009 German tagset and KAF tagset. Based on the Stuttgart-Tuebingen tagset. @param postag the postag @return kaf POS tag
[ "Mapping", "between", "CoNLL", "2009", "German", "tagset", "and", "KAF", "tagset", ".", "Based", "on", "the", "Stuttgart", "-", "Tuebingen", "tagset", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/Resources.java#L158-L181
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/Resources.java
Resources.mapEnglishTagSetToKaf
private static String mapEnglishTagSetToKaf(final String postag) { if (postag.startsWith("RB")) { return "A"; // adverb } else if (postag.equalsIgnoreCase("CC")) { return "C"; // conjunction } else if (postag.startsWith("D") || postag.equalsIgnoreCase("PDT")) { return "D"; // determiner and predeterminer } else if (postag.startsWith("J")) { return "G"; // adjective } else if (postag.equalsIgnoreCase("NN") || postag.equalsIgnoreCase("NNS")) { return "N"; // common noun } else if (postag.startsWith("NNP")) { return "R"; // proper noun } else if (postag.equalsIgnoreCase("TO") || postag.equalsIgnoreCase("IN")) { return "P"; // preposition } else if (postag.startsWith("PRP") || postag.startsWith("WP")) { return "Q"; // pronoun } else if (postag.startsWith("V")) { return "V"; // verb } else { return "O"; // other } }
java
private static String mapEnglishTagSetToKaf(final String postag) { if (postag.startsWith("RB")) { return "A"; // adverb } else if (postag.equalsIgnoreCase("CC")) { return "C"; // conjunction } else if (postag.startsWith("D") || postag.equalsIgnoreCase("PDT")) { return "D"; // determiner and predeterminer } else if (postag.startsWith("J")) { return "G"; // adjective } else if (postag.equalsIgnoreCase("NN") || postag.equalsIgnoreCase("NNS")) { return "N"; // common noun } else if (postag.startsWith("NNP")) { return "R"; // proper noun } else if (postag.equalsIgnoreCase("TO") || postag.equalsIgnoreCase("IN")) { return "P"; // preposition } else if (postag.startsWith("PRP") || postag.startsWith("WP")) { return "Q"; // pronoun } else if (postag.startsWith("V")) { return "V"; // verb } else { return "O"; // other } }
[ "private", "static", "String", "mapEnglishTagSetToKaf", "(", "final", "String", "postag", ")", "{", "if", "(", "postag", ".", "startsWith", "(", "\"RB\"", ")", ")", "{", "return", "\"A\"", ";", "// adverb", "}", "else", "if", "(", "postag", ".", "equalsIgn...
Mapping between Penn Treebank tagset and KAF tagset. @param postag treebank postag @return kaf POS tag
[ "Mapping", "between", "Penn", "Treebank", "tagset", "and", "KAF", "tagset", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/Resources.java#L189-L211
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/Resources.java
Resources.mapSpanishTagSetToKaf
private static String mapSpanishTagSetToKaf(final String postag) { if (postag.equalsIgnoreCase("RG") || postag.equalsIgnoreCase("RN")) { return "A"; // adverb } else if (postag.equalsIgnoreCase("CC") || postag.equalsIgnoreCase("CS")) { return "C"; // conjunction } else if (postag.startsWith("D")) { return "D"; // det predeterminer } else if (postag.startsWith("A")) { return "G"; // adjective } else if (postag.startsWith("NC")) { return "N"; // common noun } else if (postag.startsWith("NP")) { return "R"; // proper noun } else if (postag.startsWith("SP")) { return "P"; // preposition } else if (postag.startsWith("P")) { return "Q"; // pronoun } else if (postag.startsWith("V")) { return "V"; // verb } else { return "O"; // other } }
java
private static String mapSpanishTagSetToKaf(final String postag) { if (postag.equalsIgnoreCase("RG") || postag.equalsIgnoreCase("RN")) { return "A"; // adverb } else if (postag.equalsIgnoreCase("CC") || postag.equalsIgnoreCase("CS")) { return "C"; // conjunction } else if (postag.startsWith("D")) { return "D"; // det predeterminer } else if (postag.startsWith("A")) { return "G"; // adjective } else if (postag.startsWith("NC")) { return "N"; // common noun } else if (postag.startsWith("NP")) { return "R"; // proper noun } else if (postag.startsWith("SP")) { return "P"; // preposition } else if (postag.startsWith("P")) { return "Q"; // pronoun } else if (postag.startsWith("V")) { return "V"; // verb } else { return "O"; // other } }
[ "private", "static", "String", "mapSpanishTagSetToKaf", "(", "final", "String", "postag", ")", "{", "if", "(", "postag", ".", "equalsIgnoreCase", "(", "\"RG\"", ")", "||", "postag", ".", "equalsIgnoreCase", "(", "\"RN\"", ")", ")", "{", "return", "\"A\"", ";...
Mapping between EAGLES PAROLE tagset and NAF. @param postag the postag @return the mapping to NAF pos tagset
[ "Mapping", "between", "EAGLES", "PAROLE", "tagset", "and", "NAF", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/Resources.java#L220-L242
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java
TimedSemaphore.shutdown
public synchronized void shutdown() { if (!shutdown) { if (ownExecutor) { // if the executor was created by this instance, it has // to be shutdown getExecutorService().shutdownNow(); } if (task != null) { task.cancel(false); } shutdown = true; } }
java
public synchronized void shutdown() { if (!shutdown) { if (ownExecutor) { // if the executor was created by this instance, it has // to be shutdown getExecutorService().shutdownNow(); } if (task != null) { task.cancel(false); } shutdown = true; } }
[ "public", "synchronized", "void", "shutdown", "(", ")", "{", "if", "(", "!", "shutdown", ")", "{", "if", "(", "ownExecutor", ")", "{", "// if the executor was created by this instance, it has", "// to be shutdown", "getExecutorService", "(", ")", ".", "shutdownNow", ...
Initializes a shutdown. After that the object cannot be used any more. This method can be invoked an arbitrary number of times. All invocations after the first one do not have any effect.
[ "Initializes", "a", "shutdown", ".", "After", "that", "the", "object", "cannot", "be", "used", "any", "more", ".", "This", "method", "can", "be", "invoked", "an", "arbitrary", "number", "of", "times", ".", "All", "invocations", "after", "the", "first", "on...
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java#L267-L281
train
alexheretic/dynamics
src/main/java/alexh/weak/ConverterTimeFormats.java
ConverterTimeFormats.orderedParseAttempter
@SafeVarargs public static Function<CharSequence, TemporalAccessor> orderedParseAttempter(Function<CharSequence, TemporalAccessor>... parsers) { return date -> { RuntimeException first = null; for (Function<CharSequence, TemporalAccessor> parser : parsers) { try { return parser.apply(date); } catch (RuntimeException ex) { if (first == null) first = ex; } } if (first == null) throw new IllegalStateException("Empty parse attempter"); throw first; }; }
java
@SafeVarargs public static Function<CharSequence, TemporalAccessor> orderedParseAttempter(Function<CharSequence, TemporalAccessor>... parsers) { return date -> { RuntimeException first = null; for (Function<CharSequence, TemporalAccessor> parser : parsers) { try { return parser.apply(date); } catch (RuntimeException ex) { if (first == null) first = ex; } } if (first == null) throw new IllegalStateException("Empty parse attempter"); throw first; }; }
[ "@", "SafeVarargs", "public", "static", "Function", "<", "CharSequence", ",", "TemporalAccessor", ">", "orderedParseAttempter", "(", "Function", "<", "CharSequence", ",", "TemporalAccessor", ">", "...", "parsers", ")", "{", "return", "date", "->", "{", "RuntimeExc...
Returns an ordered functional blend of all input parsers. The attempter will try all functions until it succeeds. If none succeed will re-throw the first exception @param parsers ordered sequence of parsers to try to convert a CharSequence into a TemporalAccessor @return ordered functional blend of all input parsers
[ "Returns", "an", "ordered", "functional", "blend", "of", "all", "input", "parsers", ".", "The", "attempter", "will", "try", "all", "functions", "until", "it", "succeeds", ".", "If", "none", "succeed", "will", "re", "-", "throw", "the", "first", "exception" ]
aa46ca76247d43f399eb9c2037c9b4c2549b3722
https://github.com/alexheretic/dynamics/blob/aa46ca76247d43f399eb9c2037c9b4c2549b3722/src/main/java/alexh/weak/ConverterTimeFormats.java#L217-L230
train
ManfredTremmel/gwt-commons-lang3
src/main/resources/org/apache/commons/jre/java/nio/charset/Charset.java
Charset.forName
public static Charset forName(String charsetName) { // NOPMD if (charsetName == null) { throw new IllegalArgumentException("Null charset name"); } charsetName = charsetName.toUpperCase(); if (EmulatedCharset.ISO_8859_1.name().equals(charsetName)) { return EmulatedCharset.ISO_8859_1; } else if (EmulatedCharset.ISO_LATIN_1.name().equals(charsetName)) { return EmulatedCharset.ISO_LATIN_1; } else if (EmulatedCharset.UTF_8.name().equals(charsetName)) { return EmulatedCharset.UTF_8; } if (!charsetName.matches("^[A-Za-z0-9][\\w-:\\.\\+]*$")) { // NOPMD throw new IllegalCharsetNameException(charsetName); } else { throw new UnsupportedCharsetException(charsetName); } }
java
public static Charset forName(String charsetName) { // NOPMD if (charsetName == null) { throw new IllegalArgumentException("Null charset name"); } charsetName = charsetName.toUpperCase(); if (EmulatedCharset.ISO_8859_1.name().equals(charsetName)) { return EmulatedCharset.ISO_8859_1; } else if (EmulatedCharset.ISO_LATIN_1.name().equals(charsetName)) { return EmulatedCharset.ISO_LATIN_1; } else if (EmulatedCharset.UTF_8.name().equals(charsetName)) { return EmulatedCharset.UTF_8; } if (!charsetName.matches("^[A-Za-z0-9][\\w-:\\.\\+]*$")) { // NOPMD throw new IllegalCharsetNameException(charsetName); } else { throw new UnsupportedCharsetException(charsetName); } }
[ "public", "static", "Charset", "forName", "(", "String", "charsetName", ")", "{", "// NOPMD", "if", "(", "charsetName", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Null charset name\"", ")", ";", "}", "charsetName", "=", "charsetN...
get charset for name. @param charsetName name of the charset @return coresponding charset
[ "get", "charset", "for", "name", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/resources/org/apache/commons/jre/java/nio/charset/Charset.java#L50-L69
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java
ReflectionToStringBuilder.setExcludeFieldNames
public ReflectionToStringBuilder setExcludeFieldNames(final String... excludeFieldNamesParam) { if (excludeFieldNamesParam == null) { this.excludeFieldNames = null; } else { //clone and remove nulls this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam); Arrays.sort(this.excludeFieldNames); } return this; }
java
public ReflectionToStringBuilder setExcludeFieldNames(final String... excludeFieldNamesParam) { if (excludeFieldNamesParam == null) { this.excludeFieldNames = null; } else { //clone and remove nulls this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam); Arrays.sort(this.excludeFieldNames); } return this; }
[ "public", "ReflectionToStringBuilder", "setExcludeFieldNames", "(", "final", "String", "...", "excludeFieldNamesParam", ")", "{", "if", "(", "excludeFieldNamesParam", "==", "null", ")", "{", "this", ".", "excludeFieldNames", "=", "null", ";", "}", "else", "{", "//...
Sets the field names to exclude. @param excludeFieldNamesParam The excludeFieldNames to excluding from toString or <code>null</code>. @return <code>this</code>
[ "Sets", "the", "field", "names", "to", "exclude", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java#L790-L799
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/time/DateUtils.java
DateUtils.getFragment
@GwtIncompatible("incompatible method") private static long getFragment(final Date date, final int fragment, final TimeUnit unit) { validateDateNotNull(date); final Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return getFragment(calendar, fragment, unit); }
java
@GwtIncompatible("incompatible method") private static long getFragment(final Date date, final int fragment, final TimeUnit unit) { validateDateNotNull(date); final Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return getFragment(calendar, fragment, unit); }
[ "@", "GwtIncompatible", "(", "\"incompatible method\"", ")", "private", "static", "long", "getFragment", "(", "final", "Date", "date", ",", "final", "int", "fragment", ",", "final", "TimeUnit", "unit", ")", "{", "validateDateNotNull", "(", "date", ")", ";", "f...
Gets a Date fragment for any unit. @param date the date to work with, not null @param fragment the Calendar field part of date to calculate @param unit the time unit @return number of units within the fragment of the date @throws IllegalArgumentException if the date is <code>null</code> or fragment is not supported @since 2.4
[ "Gets", "a", "Date", "fragment", "for", "any", "unit", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L1664-L1670
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/time/DateUtils.java
DateUtils.getFragment
@GwtIncompatible("incompatible method") private static long getFragment(final Calendar calendar, final int fragment, final TimeUnit unit) { if(calendar == null) { throw new IllegalArgumentException("The date must not be null"); } long result = 0; final int offset = (unit == TimeUnit.DAYS) ? 0 : 1; // Fragments bigger than a day require a breakdown to days switch (fragment) { case Calendar.YEAR: result += unit.convert(calendar.get(Calendar.DAY_OF_YEAR) - offset, TimeUnit.DAYS); break; case Calendar.MONTH: result += unit.convert(calendar.get(Calendar.DAY_OF_MONTH) - offset, TimeUnit.DAYS); break; default: break; } switch (fragment) { // Number of days already calculated for these cases case Calendar.YEAR: case Calendar.MONTH: // The rest of the valid cases case Calendar.DAY_OF_YEAR: case Calendar.DATE: result += unit.convert(calendar.get(Calendar.HOUR_OF_DAY), TimeUnit.HOURS); //$FALL-THROUGH$ case Calendar.HOUR_OF_DAY: result += unit.convert(calendar.get(Calendar.MINUTE), TimeUnit.MINUTES); //$FALL-THROUGH$ case Calendar.MINUTE: result += unit.convert(calendar.get(Calendar.SECOND), TimeUnit.SECONDS); //$FALL-THROUGH$ case Calendar.SECOND: result += unit.convert(calendar.get(Calendar.MILLISECOND), TimeUnit.MILLISECONDS); break; case Calendar.MILLISECOND: break;//never useful default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported"); } return result; }
java
@GwtIncompatible("incompatible method") private static long getFragment(final Calendar calendar, final int fragment, final TimeUnit unit) { if(calendar == null) { throw new IllegalArgumentException("The date must not be null"); } long result = 0; final int offset = (unit == TimeUnit.DAYS) ? 0 : 1; // Fragments bigger than a day require a breakdown to days switch (fragment) { case Calendar.YEAR: result += unit.convert(calendar.get(Calendar.DAY_OF_YEAR) - offset, TimeUnit.DAYS); break; case Calendar.MONTH: result += unit.convert(calendar.get(Calendar.DAY_OF_MONTH) - offset, TimeUnit.DAYS); break; default: break; } switch (fragment) { // Number of days already calculated for these cases case Calendar.YEAR: case Calendar.MONTH: // The rest of the valid cases case Calendar.DAY_OF_YEAR: case Calendar.DATE: result += unit.convert(calendar.get(Calendar.HOUR_OF_DAY), TimeUnit.HOURS); //$FALL-THROUGH$ case Calendar.HOUR_OF_DAY: result += unit.convert(calendar.get(Calendar.MINUTE), TimeUnit.MINUTES); //$FALL-THROUGH$ case Calendar.MINUTE: result += unit.convert(calendar.get(Calendar.SECOND), TimeUnit.SECONDS); //$FALL-THROUGH$ case Calendar.SECOND: result += unit.convert(calendar.get(Calendar.MILLISECOND), TimeUnit.MILLISECONDS); break; case Calendar.MILLISECOND: break;//never useful default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported"); } return result; }
[ "@", "GwtIncompatible", "(", "\"incompatible method\"", ")", "private", "static", "long", "getFragment", "(", "final", "Calendar", "calendar", ",", "final", "int", "fragment", ",", "final", "TimeUnit", "unit", ")", "{", "if", "(", "calendar", "==", "null", ")"...
Gets a Calendar fragment for any unit. @param calendar the calendar to work with, not null @param fragment the Calendar field part of calendar to calculate @param unit the time unit @return number of units within the fragment of the calendar @throws IllegalArgumentException if the date is <code>null</code> or fragment is not supported @since 2.4
[ "Gets", "a", "Calendar", "fragment", "for", "any", "unit", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L1683-L1728
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/time/DateUtils.java
DateUtils.truncatedEquals
public static boolean truncatedEquals(final Date date1, final Date date2, final int field) { return truncatedCompareTo(date1, date2, field) == 0; }
java
public static boolean truncatedEquals(final Date date1, final Date date2, final int field) { return truncatedCompareTo(date1, date2, field) == 0; }
[ "public", "static", "boolean", "truncatedEquals", "(", "final", "Date", "date1", ",", "final", "Date", "date2", ",", "final", "int", "field", ")", "{", "return", "truncatedCompareTo", "(", "date1", ",", "date2", ",", "field", ")", "==", "0", ";", "}" ]
Determines if two dates are equal up to no more than the specified most significant field. @param date1 the first date, not <code>null</code> @param date2 the second date, not <code>null</code> @param field the field from {@code Calendar} @return <code>true</code> if equal; otherwise <code>false</code> @throws IllegalArgumentException if any argument is <code>null</code> @see #truncate(Date, int) @see #truncatedEquals(Calendar, Calendar, int) @since 3.0
[ "Determines", "if", "two", "dates", "are", "equal", "up", "to", "no", "more", "than", "the", "specified", "most", "significant", "field", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L1760-L1762
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/time/DateUtils.java
DateUtils.truncatedCompareTo
public static int truncatedCompareTo(final Calendar cal1, final Calendar cal2, final int field) { final Calendar truncatedCal1 = truncate(cal1, field); final Calendar truncatedCal2 = truncate(cal2, field); return truncatedCal1.compareTo(truncatedCal2); }
java
public static int truncatedCompareTo(final Calendar cal1, final Calendar cal2, final int field) { final Calendar truncatedCal1 = truncate(cal1, field); final Calendar truncatedCal2 = truncate(cal2, field); return truncatedCal1.compareTo(truncatedCal2); }
[ "public", "static", "int", "truncatedCompareTo", "(", "final", "Calendar", "cal1", ",", "final", "Calendar", "cal2", ",", "final", "int", "field", ")", "{", "final", "Calendar", "truncatedCal1", "=", "truncate", "(", "cal1", ",", "field", ")", ";", "final", ...
Determines how two calendars compare up to no more than the specified most significant field. @param cal1 the first calendar, not <code>null</code> @param cal2 the second calendar, not <code>null</code> @param field the field from {@code Calendar} @return a negative integer, zero, or a positive integer as the first calendar is less than, equal to, or greater than the second. @throws IllegalArgumentException if any argument is <code>null</code> @see #truncate(Calendar, int) @see #truncatedCompareTo(Date, Date, int) @since 3.0
[ "Determines", "how", "two", "calendars", "compare", "up", "to", "no", "more", "than", "the", "specified", "most", "significant", "field", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L1778-L1782
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/time/DateUtils.java
DateUtils.truncatedCompareTo
public static int truncatedCompareTo(final Date date1, final Date date2, final int field) { final Date truncatedDate1 = truncate(date1, field); final Date truncatedDate2 = truncate(date2, field); return truncatedDate1.compareTo(truncatedDate2); }
java
public static int truncatedCompareTo(final Date date1, final Date date2, final int field) { final Date truncatedDate1 = truncate(date1, field); final Date truncatedDate2 = truncate(date2, field); return truncatedDate1.compareTo(truncatedDate2); }
[ "public", "static", "int", "truncatedCompareTo", "(", "final", "Date", "date1", ",", "final", "Date", "date2", ",", "final", "int", "field", ")", "{", "final", "Date", "truncatedDate1", "=", "truncate", "(", "date1", ",", "field", ")", ";", "final", "Date"...
Determines how two dates compare up to no more than the specified most significant field. @param date1 the first date, not <code>null</code> @param date2 the second date, not <code>null</code> @param field the field from <code>Calendar</code> @return a negative integer, zero, or a positive integer as the first date is less than, equal to, or greater than the second. @throws IllegalArgumentException if any argument is <code>null</code> @see #truncate(Calendar, int) @see #truncatedCompareTo(Date, Date, int) @since 3.0
[ "Determines", "how", "two", "dates", "compare", "up", "to", "no", "more", "than", "the", "specified", "most", "significant", "field", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L1798-L1802
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/event/EventUtils.java
EventUtils.bindEventsToMethod
public static <L> void bindEventsToMethod(final Object target, final String methodName, final Object eventSource, final Class<L> listenerType, final String... eventTypes) { final L listener = listenerType.cast(Proxy.newProxyInstance(target.getClass().getClassLoader(), new Class[] { listenerType }, new EventBindingInvocationHandler(target, methodName, eventTypes))); addEventListener(eventSource, listenerType, listener); }
java
public static <L> void bindEventsToMethod(final Object target, final String methodName, final Object eventSource, final Class<L> listenerType, final String... eventTypes) { final L listener = listenerType.cast(Proxy.newProxyInstance(target.getClass().getClassLoader(), new Class[] { listenerType }, new EventBindingInvocationHandler(target, methodName, eventTypes))); addEventListener(eventSource, listenerType, listener); }
[ "public", "static", "<", "L", ">", "void", "bindEventsToMethod", "(", "final", "Object", "target", ",", "final", "String", "methodName", ",", "final", "Object", "eventSource", ",", "final", "Class", "<", "L", ">", "listenerType", ",", "final", "String", "......
Binds an event listener to a specific method on a specific object. @param <L> the event listener type @param target the target object @param methodName the name of the method to be called @param eventSource the object which is generating events (JButton, JList, etc.) @param listenerType the listener interface (ActionListener.class, SelectionListener.class, etc.) @param eventTypes the event types (method names) from the listener interface (if none specified, all will be supported)
[ "Binds", "an", "event", "listener", "to", "a", "specific", "method", "on", "a", "specific", "object", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/event/EventUtils.java#L77-L82
train
grove/exmeso
exmeso-core/src/main/java/org/geirove/exmeso/ExternalMergeSort.java
ExternalMergeSort.newSorter
public static <T> Builder<T> newSorter(Serializer<T> serializer, Comparator<T> comparator) { return new Builder<T>(serializer, comparator); }
java
public static <T> Builder<T> newSorter(Serializer<T> serializer, Comparator<T> comparator) { return new Builder<T>(serializer, comparator); }
[ "public", "static", "<", "T", ">", "Builder", "<", "T", ">", "newSorter", "(", "Serializer", "<", "T", ">", "serializer", ",", "Comparator", "<", "T", ">", "comparator", ")", "{", "return", "new", "Builder", "<", "T", ">", "(", "serializer", ",", "co...
Fluent API building a new instance of ExternalMergeSort<T. @param serializer Serializer<T> to use when sorting. @return Config instance that can be used to set options and in the end create a new instance.
[ "Fluent", "API", "building", "a", "new", "instance", "of", "ExternalMergeSort<T", "." ]
e9ff70161658acd6bf9b71844d95a8922159f333
https://github.com/grove/exmeso/blob/e9ff70161658acd6bf9b71844d95a8922159f333/exmeso-core/src/main/java/org/geirove/exmeso/ExternalMergeSort.java#L46-L48
train
grove/exmeso
exmeso-core/src/main/java/org/geirove/exmeso/ExternalMergeSort.java
ExternalMergeSort.mergeSort
public CloseableIterator<T> mergeSort(Iterator<T> values) throws IOException { ChunkSizeIterator<T> csi = new ChunkSizeIterator<T>(values, config.chunkSize); if (csi.isMultipleChunks()) { List<File> sortedChunks = writeSortedChunks(csi); return mergeSortedChunks(sortedChunks); } else { if (config.distinct) { SortedSet<T> list = new TreeSet<T>(comparator); while (csi.hasNext()) { list.add(csi.next()); } return new DelegatingMergeIterator<T>(list.iterator()); } else { List<T> list = new ArrayList<T>(csi.getHeadSize()); while (csi.hasNext()) { list.add(csi.next()); } Collections.sort(list, comparator); return new DelegatingMergeIterator<T>(list.iterator()); } } }
java
public CloseableIterator<T> mergeSort(Iterator<T> values) throws IOException { ChunkSizeIterator<T> csi = new ChunkSizeIterator<T>(values, config.chunkSize); if (csi.isMultipleChunks()) { List<File> sortedChunks = writeSortedChunks(csi); return mergeSortedChunks(sortedChunks); } else { if (config.distinct) { SortedSet<T> list = new TreeSet<T>(comparator); while (csi.hasNext()) { list.add(csi.next()); } return new DelegatingMergeIterator<T>(list.iterator()); } else { List<T> list = new ArrayList<T>(csi.getHeadSize()); while (csi.hasNext()) { list.add(csi.next()); } Collections.sort(list, comparator); return new DelegatingMergeIterator<T>(list.iterator()); } } }
[ "public", "CloseableIterator", "<", "T", ">", "mergeSort", "(", "Iterator", "<", "T", ">", "values", ")", "throws", "IOException", "{", "ChunkSizeIterator", "<", "T", ">", "csi", "=", "new", "ChunkSizeIterator", "<", "T", ">", "(", "values", ",", "config",...
Performs an external merge on the values in the iterator. @param values Iterator containing the data to sort. @return an iterator the iterates over the sorted result. @throws IOException if something fails when doing I/O.
[ "Performs", "an", "external", "merge", "on", "the", "values", "in", "the", "iterator", "." ]
e9ff70161658acd6bf9b71844d95a8922159f333
https://github.com/grove/exmeso/blob/e9ff70161658acd6bf9b71844d95a8922159f333/exmeso-core/src/main/java/org/geirove/exmeso/ExternalMergeSort.java#L157-L178
train
grove/exmeso
exmeso-core/src/main/java/org/geirove/exmeso/ExternalMergeSort.java
ExternalMergeSort.mergeSortedChunks
public CloseableIterator<T> mergeSortedChunks(List<File> sortedChunks) throws IOException { return mergeSortedChunksNoPartialMerge(partialMerge(sortedChunks)); }
java
public CloseableIterator<T> mergeSortedChunks(List<File> sortedChunks) throws IOException { return mergeSortedChunksNoPartialMerge(partialMerge(sortedChunks)); }
[ "public", "CloseableIterator", "<", "T", ">", "mergeSortedChunks", "(", "List", "<", "File", ">", "sortedChunks", ")", "throws", "IOException", "{", "return", "mergeSortedChunksNoPartialMerge", "(", "partialMerge", "(", "sortedChunks", ")", ")", ";", "}" ]
Returns an iterator over the sorted result. Takes a list of already sorted chunk files as input. Note that this method is normally used with one of the writeSortedChunks methods. @param sortedChunks a list of sorted chunk files @return an iterator the iterates over the sorted result. @throws IOException if something fails when doing I/O.
[ "Returns", "an", "iterator", "over", "the", "sorted", "result", ".", "Takes", "a", "list", "of", "already", "sorted", "chunk", "files", "as", "input", ".", "Note", "that", "this", "method", "is", "normally", "used", "with", "one", "of", "the", "writeSorted...
e9ff70161658acd6bf9b71844d95a8922159f333
https://github.com/grove/exmeso/blob/e9ff70161658acd6bf9b71844d95a8922159f333/exmeso-core/src/main/java/org/geirove/exmeso/ExternalMergeSort.java#L217-L219
train
grove/exmeso
exmeso-core/src/main/java/org/geirove/exmeso/ExternalMergeSort.java
ExternalMergeSort.writeSortedChunks
public List<File> writeSortedChunks(Iterator<T> input) throws IOException { List<File> result = new ArrayList<File>(); while (input.hasNext()) { File chunkFile = writeSortedChunk(input); result.add(chunkFile); } if (debugMerge) { System.out.printf("Chunks %d (chunkSize=%d, maxOpenFiles=%d)\n", result.size(), config.chunkSize, config.maxOpenFiles); } return result; }
java
public List<File> writeSortedChunks(Iterator<T> input) throws IOException { List<File> result = new ArrayList<File>(); while (input.hasNext()) { File chunkFile = writeSortedChunk(input); result.add(chunkFile); } if (debugMerge) { System.out.printf("Chunks %d (chunkSize=%d, maxOpenFiles=%d)\n", result.size(), config.chunkSize, config.maxOpenFiles); } return result; }
[ "public", "List", "<", "File", ">", "writeSortedChunks", "(", "Iterator", "<", "T", ">", "input", ")", "throws", "IOException", "{", "List", "<", "File", ">", "result", "=", "new", "ArrayList", "<", "File", ">", "(", ")", ";", "while", "(", "input", ...
Read the data from the iterator, then perform a sort, and write individually sorted chunk files to disk. @param input Iterator containing the data to sort. @return list of sorted chunk files. @throws IOException if something fails when doing I/O.
[ "Read", "the", "data", "from", "the", "iterator", "then", "perform", "a", "sort", "and", "write", "individually", "sorted", "chunk", "files", "to", "disk", "." ]
e9ff70161658acd6bf9b71844d95a8922159f333
https://github.com/grove/exmeso/blob/e9ff70161658acd6bf9b71844d95a8922159f333/exmeso-core/src/main/java/org/geirove/exmeso/ExternalMergeSort.java#L362-L372
train
grove/exmeso
exmeso-core/src/main/java/org/geirove/exmeso/ExternalMergeSort.java
ExternalMergeSort.writeSortedChunk
public File writeSortedChunk(Iterator<T> input) throws IOException { List<T> chunk = readChunk(input); return writeInternalSortedChunk(chunk); }
java
public File writeSortedChunk(Iterator<T> input) throws IOException { List<T> chunk = readChunk(input); return writeInternalSortedChunk(chunk); }
[ "public", "File", "writeSortedChunk", "(", "Iterator", "<", "T", ">", "input", ")", "throws", "IOException", "{", "List", "<", "T", ">", "chunk", "=", "readChunk", "(", "input", ")", ";", "return", "writeInternalSortedChunk", "(", "chunk", ")", ";", "}" ]
Read the data from the iterator, then perform a sort, and write a single sorted chunk file to disk. Note that a maximum of elements equal to the chunk size will be read from the iterator, so make sure that the iterator contains no more than that. If that is the case then you may want to use the writeSortedChunks method instead. @param input Iterator containing the data to sort. @return chunk file @throws IOException if something fails when doing I/O.
[ "Read", "the", "data", "from", "the", "iterator", "then", "perform", "a", "sort", "and", "write", "a", "single", "sorted", "chunk", "file", "to", "disk", ".", "Note", "that", "a", "maximum", "of", "elements", "equal", "to", "the", "chunk", "size", "will"...
e9ff70161658acd6bf9b71844d95a8922159f333
https://github.com/grove/exmeso/blob/e9ff70161658acd6bf9b71844d95a8922159f333/exmeso-core/src/main/java/org/geirove/exmeso/ExternalMergeSort.java#L384-L387
train
sockeqwe/sqlbrite-dao
objectmapper-processor/src/main/java/com/hannesdorfmann/sqlbrite/objectmapper/processor/HungarianNotation.java
HungarianNotation.removeNotation
public static String removeNotation(String name) { if (name.matches("^m[A-Z]{1}")) { return name.substring(1, 2).toLowerCase(); } else if (name.matches("m[A-Z]{1}.*")) { return name.substring(1, 2).toLowerCase() + name.substring(2); } return name; }
java
public static String removeNotation(String name) { if (name.matches("^m[A-Z]{1}")) { return name.substring(1, 2).toLowerCase(); } else if (name.matches("m[A-Z]{1}.*")) { return name.substring(1, 2).toLowerCase() + name.substring(2); } return name; }
[ "public", "static", "String", "removeNotation", "(", "String", "name", ")", "{", "if", "(", "name", ".", "matches", "(", "\"^m[A-Z]{1}\"", ")", ")", "{", "return", "name", ".", "substring", "(", "1", ",", "2", ")", ".", "toLowerCase", "(", ")", ";", ...
Get the name of the field removing hungarian notation @param name The field name @return the field name without hungarian notation
[ "Get", "the", "name", "of", "the", "field", "removing", "hungarian", "notation" ]
8d02b76f00bd2f8997a58d33146b98b2eec35452
https://github.com/sockeqwe/sqlbrite-dao/blob/8d02b76f00bd2f8997a58d33146b98b2eec35452/objectmapper-processor/src/main/java/com/hannesdorfmann/sqlbrite/objectmapper/processor/HungarianNotation.java#L20-L27
train
sockeqwe/sqlbrite-dao
objectmapper-processor/src/main/java/com/hannesdorfmann/sqlbrite/objectmapper/processor/HungarianNotation.java
HungarianNotation.removeNotationFromSetterAndSetPrefix
public static String removeNotationFromSetterAndSetPrefix(String methodName) { if (methodName.matches("^set\\w+")) { String withoutSetPrefix = methodName.substring(3); if (Character.isLowerCase(withoutSetPrefix.charAt(0))) { return HungarianNotation.removeNotation(withoutSetPrefix); } else if (withoutSetPrefix.length() >= 2 && withoutSetPrefix.charAt(0) == 'M' && Character.isUpperCase(withoutSetPrefix.charAt(1))) { return Character.toLowerCase(withoutSetPrefix.charAt(1)) + withoutSetPrefix.substring(2); } return removeNotation(withoutSetPrefix); } return removeNotation(methodName); }
java
public static String removeNotationFromSetterAndSetPrefix(String methodName) { if (methodName.matches("^set\\w+")) { String withoutSetPrefix = methodName.substring(3); if (Character.isLowerCase(withoutSetPrefix.charAt(0))) { return HungarianNotation.removeNotation(withoutSetPrefix); } else if (withoutSetPrefix.length() >= 2 && withoutSetPrefix.charAt(0) == 'M' && Character.isUpperCase(withoutSetPrefix.charAt(1))) { return Character.toLowerCase(withoutSetPrefix.charAt(1)) + withoutSetPrefix.substring(2); } return removeNotation(withoutSetPrefix); } return removeNotation(methodName); }
[ "public", "static", "String", "removeNotationFromSetterAndSetPrefix", "(", "String", "methodName", ")", "{", "if", "(", "methodName", ".", "matches", "(", "\"^set\\\\w+\"", ")", ")", "{", "String", "withoutSetPrefix", "=", "methodName", ".", "substring", "(", "3",...
Removes the hungarian notation from setter method @param methodName The name of the method @return clean version without hungarian notation
[ "Removes", "the", "hungarian", "notation", "from", "setter", "method" ]
8d02b76f00bd2f8997a58d33146b98b2eec35452
https://github.com/sockeqwe/sqlbrite-dao/blob/8d02b76f00bd2f8997a58d33146b98b2eec35452/objectmapper-processor/src/main/java/com/hannesdorfmann/sqlbrite/objectmapper/processor/HungarianNotation.java#L35-L50
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/lemma/dict/DictionaryLemmatizer.java
DictionaryLemmatizer.apply
public String apply(final String word, final String postag) { String lemma = null; final List<String> keys = this.getDictKeys(word, postag); // lookup lemma as value of the map final String keyValue = this.dictMap.get(keys); if (keyValue != null) { lemma = keyValue; } else { lemma = "O"; } return lemma; }
java
public String apply(final String word, final String postag) { String lemma = null; final List<String> keys = this.getDictKeys(word, postag); // lookup lemma as value of the map final String keyValue = this.dictMap.get(keys); if (keyValue != null) { lemma = keyValue; } else { lemma = "O"; } return lemma; }
[ "public", "String", "apply", "(", "final", "String", "word", ",", "final", "String", "postag", ")", "{", "String", "lemma", "=", "null", ";", "final", "List", "<", "String", ">", "keys", "=", "this", ".", "getDictKeys", "(", "word", ",", "postag", ")",...
Lookup lemma in a dictionary. Outputs "O" if not found. @param word the token @param postag the postag @return the lemma
[ "Lookup", "lemma", "in", "a", "dictionary", ".", "Outputs", "O", "if", "not", "found", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/lemma/dict/DictionaryLemmatizer.java#L108-L119
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Validate.java
Validate.inclusiveBetween
@SuppressWarnings("boxing") public static void inclusiveBetween(final double start, final double end, final double value) { // TODO when breaking BC, consider returning value if (value < start || value > end) { throw new IllegalArgumentException(StringUtils.simpleFormat(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } }
java
@SuppressWarnings("boxing") public static void inclusiveBetween(final double start, final double end, final double value) { // TODO when breaking BC, consider returning value if (value < start || value > end) { throw new IllegalArgumentException(StringUtils.simpleFormat(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } }
[ "@", "SuppressWarnings", "(", "\"boxing\"", ")", "public", "static", "void", "inclusiveBetween", "(", "final", "double", "start", ",", "final", "double", "end", ",", "final", "double", "value", ")", "{", "// TODO when breaking BC, consider returning value", "if", "(...
Validate that the specified primitive value falls between the two inclusive values specified; otherwise, throws an exception. <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1);</pre> @param start the inclusive start value @param end the inclusive end value @param value the value to validate @throws IllegalArgumentException if the value falls outside the boundaries (inclusive) @since 3.3
[ "Validate", "that", "the", "specified", "primitive", "value", "falls", "between", "the", "two", "inclusive", "values", "specified", ";", "otherwise", "throws", "an", "exception", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L1078-L1084
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Validate.java
Validate.inclusiveBetween
public static void inclusiveBetween(final double start, final double end, final double value, final String message) { // TODO when breaking BC, consider returning value if (value < start || value > end) { throw new IllegalArgumentException(message); } }
java
public static void inclusiveBetween(final double start, final double end, final double value, final String message) { // TODO when breaking BC, consider returning value if (value < start || value > end) { throw new IllegalArgumentException(message); } }
[ "public", "static", "void", "inclusiveBetween", "(", "final", "double", "start", ",", "final", "double", "end", ",", "final", "double", "value", ",", "final", "String", "message", ")", "{", "// TODO when breaking BC, consider returning value", "if", "(", "value", ...
Validate that the specified primitive value falls between the two inclusive values specified; otherwise, throws an exception with the specified message. <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre> @param start the inclusive start value @param end the inclusive end value @param value the value to validate @param message the exception message if invalid, not null @throws IllegalArgumentException if the value falls outside the boundaries @since 3.3
[ "Validate", "that", "the", "specified", "primitive", "value", "falls", "between", "the", "two", "inclusive", "values", "specified", ";", "otherwise", "throws", "an", "exception", "with", "the", "specified", "message", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L1102-L1107
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Validate.java
Validate.exclusiveBetween
@SuppressWarnings("boxing") public static void exclusiveBetween(final long start, final long end, final long value) { // TODO when breaking BC, consider returning value if (value <= start || value >= end) { throw new IllegalArgumentException(StringUtils.simpleFormat(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } }
java
@SuppressWarnings("boxing") public static void exclusiveBetween(final long start, final long end, final long value) { // TODO when breaking BC, consider returning value if (value <= start || value >= end) { throw new IllegalArgumentException(StringUtils.simpleFormat(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } }
[ "@", "SuppressWarnings", "(", "\"boxing\"", ")", "public", "static", "void", "exclusiveBetween", "(", "final", "long", "start", ",", "final", "long", "end", ",", "final", "long", "value", ")", "{", "// TODO when breaking BC, consider returning value", "if", "(", "...
Validate that the specified primitive value falls between the two exclusive values specified; otherwise, throws an exception. <pre>Validate.exclusiveBetween(0, 2, 1);</pre> @param start the exclusive start value @param end the exclusive end value @param value the value to validate @throws IllegalArgumentException if the value falls out of the boundaries @since 3.3
[ "Validate", "that", "the", "specified", "primitive", "value", "falls", "between", "the", "two", "exclusive", "values", "specified", ";", "otherwise", "throws", "an", "exception", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L1172-L1178
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Validate.java
Validate.exclusiveBetween
public static void exclusiveBetween(final long start, final long end, final long value, final String message) { // TODO when breaking BC, consider returning value if (value <= start || value >= end) { throw new IllegalArgumentException(message); } }
java
public static void exclusiveBetween(final long start, final long end, final long value, final String message) { // TODO when breaking BC, consider returning value if (value <= start || value >= end) { throw new IllegalArgumentException(message); } }
[ "public", "static", "void", "exclusiveBetween", "(", "final", "long", "start", ",", "final", "long", "end", ",", "final", "long", "value", ",", "final", "String", "message", ")", "{", "// TODO when breaking BC, consider returning value", "if", "(", "value", "<=", ...
Validate that the specified primitive value falls between the two exclusive values specified; otherwise, throws an exception with the specified message. <pre>Validate.exclusiveBetween(0, 2, 1, "Not in range");</pre> @param start the exclusive start value @param end the exclusive end value @param value the value to validate @param message the exception message if invalid, not null @throws IllegalArgumentException if the value falls outside the boundaries @since 3.3
[ "Validate", "that", "the", "specified", "primitive", "value", "falls", "between", "the", "two", "exclusive", "values", "specified", ";", "otherwise", "throws", "an", "exception", "with", "the", "specified", "message", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L1196-L1201
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Validate.java
Validate.isInstanceOf
@GwtIncompatible("incompatible method") public static void isInstanceOf(final Class<?> type, final Object obj) { // TODO when breaking BC, consider returning obj if (!type.isInstance(obj)) { throw new IllegalArgumentException(StringUtils.simpleFormat(DEFAULT_IS_INSTANCE_OF_EX_MESSAGE, type.getName(), obj == null ? "null" : obj.getClass().getName())); } }
java
@GwtIncompatible("incompatible method") public static void isInstanceOf(final Class<?> type, final Object obj) { // TODO when breaking BC, consider returning obj if (!type.isInstance(obj)) { throw new IllegalArgumentException(StringUtils.simpleFormat(DEFAULT_IS_INSTANCE_OF_EX_MESSAGE, type.getName(), obj == null ? "null" : obj.getClass().getName())); } }
[ "@", "GwtIncompatible", "(", "\"incompatible method\"", ")", "public", "static", "void", "isInstanceOf", "(", "final", "Class", "<", "?", ">", "type", ",", "final", "Object", "obj", ")", "{", "// TODO when breaking BC, consider returning obj", "if", "(", "!", "typ...
Validates that the argument is an instance of the specified class, if not throws an exception. <p>This method is useful when validating according to an arbitrary class</p> <pre>Validate.isInstanceOf(OkClass.class, object);</pre> <p>The message of the exception is &quot;Expected type: {type}, actual: {obj_type}&quot;</p> @param type the class the object must be validated against, not null @param obj the object to check, null throws an exception @throws IllegalArgumentException if argument is not of specified class @see #isInstanceOf(Class, Object, String, Object...) @since 3.0
[ "Validates", "that", "the", "argument", "is", "an", "instance", "of", "the", "specified", "class", "if", "not", "throws", "an", "exception", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L1266-L1273
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/builder/MultilineRecursiveToStringStyle.java
MultilineRecursiveToStringStyle.spacer
private StringBuilder spacer(final int spaces) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < spaces; i++) { sb.append(" "); } return sb; }
java
private StringBuilder spacer(final int spaces) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < spaces; i++) { sb.append(" "); } return sb; }
[ "private", "StringBuilder", "spacer", "(", "final", "int", "spaces", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "spaces", ";", "i", "++", ")", "{", "sb", "....
Creates a StringBuilder responsible for the indenting. @param spaces how far to indent @return a StringBuilder with {spaces} leading space characters.
[ "Creates", "a", "StringBuilder", "responsible", "for", "the", "indenting", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/builder/MultilineRecursiveToStringStyle.java#L110-L116
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreaker.java
EventCountCircuitBreaker.performStateCheck
private boolean performStateCheck(final int increment) { CheckIntervalData currentData; CheckIntervalData nextData; State currentState; do { final long time = now(); currentState = state.get(); currentData = checkIntervalData.get(); nextData = nextCheckIntervalData(increment, currentData, currentState, time); } while (!updateCheckIntervalData(currentData, nextData)); // This might cause a race condition if other changes happen in between! // Refer to the header comment! if (stateStrategy(currentState).isStateTransition(this, currentData, nextData)) { currentState = currentState.oppositeState(); changeStateAndStartNewCheckInterval(currentState); } return !isOpen(currentState); }
java
private boolean performStateCheck(final int increment) { CheckIntervalData currentData; CheckIntervalData nextData; State currentState; do { final long time = now(); currentState = state.get(); currentData = checkIntervalData.get(); nextData = nextCheckIntervalData(increment, currentData, currentState, time); } while (!updateCheckIntervalData(currentData, nextData)); // This might cause a race condition if other changes happen in between! // Refer to the header comment! if (stateStrategy(currentState).isStateTransition(this, currentData, nextData)) { currentState = currentState.oppositeState(); changeStateAndStartNewCheckInterval(currentState); } return !isOpen(currentState); }
[ "private", "boolean", "performStateCheck", "(", "final", "int", "increment", ")", "{", "CheckIntervalData", "currentData", ";", "CheckIntervalData", "nextData", ";", "State", "currentState", ";", "do", "{", "final", "long", "time", "=", "now", "(", ")", ";", "...
Actually checks the state of this circuit breaker and executes a state transition if necessary. @param increment the increment for the internal counter @return a flag whether the circuit breaker is now closed
[ "Actually", "checks", "the", "state", "of", "this", "circuit", "breaker", "and", "executes", "a", "state", "transition", "if", "necessary", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreaker.java#L323-L342
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreaker.java
EventCountCircuitBreaker.createStrategyMap
private static Map<State, StateStrategy> createStrategyMap() { final Map<State, StateStrategy> map = new EnumMap<>(State.class); map.put(State.CLOSED, new StateStrategyClosed()); map.put(State.OPEN, new StateStrategyOpen()); return map; }
java
private static Map<State, StateStrategy> createStrategyMap() { final Map<State, StateStrategy> map = new EnumMap<>(State.class); map.put(State.CLOSED, new StateStrategyClosed()); map.put(State.OPEN, new StateStrategyOpen()); return map; }
[ "private", "static", "Map", "<", "State", ",", "StateStrategy", ">", "createStrategyMap", "(", ")", "{", "final", "Map", "<", "State", ",", "StateStrategy", ">", "map", "=", "new", "EnumMap", "<>", "(", "State", ".", "class", ")", ";", "map", ".", "put...
Creates the map with strategy objects. It allows access for a strategy for a given state. @return the strategy map
[ "Creates", "the", "map", "with", "strategy", "objects", ".", "It", "allows", "access", "for", "a", "strategy", "for", "a", "given", "state", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreaker.java#L420-L425
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/lemma/LemmatizerME.java
LemmatizerME.lemmatize
public String[][] lemmatize(int numTaggings, String[] toks, String[] tags) { Sequence[] bestSequences = model.bestSequences(numTaggings, toks, new Object[] { tags }, contextGenerator, sequenceValidator); String[][] lemmaClasses = new String[bestSequences.length][]; for (int i = 0; i < lemmaClasses.length; i++) { List<String> t = bestSequences[i].getOutcomes(); lemmaClasses[i] = t.toArray(new String[t.size()]); } return lemmaClasses; }
java
public String[][] lemmatize(int numTaggings, String[] toks, String[] tags) { Sequence[] bestSequences = model.bestSequences(numTaggings, toks, new Object[] { tags }, contextGenerator, sequenceValidator); String[][] lemmaClasses = new String[bestSequences.length][]; for (int i = 0; i < lemmaClasses.length; i++) { List<String> t = bestSequences[i].getOutcomes(); lemmaClasses[i] = t.toArray(new String[t.size()]); } return lemmaClasses; }
[ "public", "String", "[", "]", "[", "]", "lemmatize", "(", "int", "numTaggings", ",", "String", "[", "]", "toks", ",", "String", "[", "]", "tags", ")", "{", "Sequence", "[", "]", "bestSequences", "=", "model", ".", "bestSequences", "(", "numTaggings", "...
Generates a specified number of lemma classes for the input tokens and tags. @param numTaggings the number of analysis @param toks the sentence tokens @param tags the sentente tags @return the specified number of lemma classes for the input tokens
[ "Generates", "a", "specified", "number", "of", "lemma", "classes", "for", "the", "input", "tokens", "and", "tags", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/lemma/LemmatizerME.java#L112-L121
train
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/exception/DefaultExceptionContext.java
DefaultExceptionContext.getFormattedExceptionMessage
@Override @GwtIncompatible("incompatible method") public String getFormattedExceptionMessage(final String baseMessage){ final StringBuilder buffer = new StringBuilder(256); if (baseMessage != null) { buffer.append(baseMessage); } if (contextValues.size() > 0) { if (buffer.length() > 0) { buffer.append('\n'); } buffer.append("Exception Context:\n"); int i = 0; for (final Pair<String, Object> pair : contextValues) { buffer.append("\t["); buffer.append(++i); buffer.append(':'); buffer.append(pair.getKey()); buffer.append("="); final Object value = pair.getValue(); if (value == null) { buffer.append("null"); } else { String valueStr; try { valueStr = value.toString(); } catch (final Exception e) { valueStr = "Exception thrown on toString(): " + ExceptionUtils.getStackTrace(e); } buffer.append(valueStr); } buffer.append("]\n"); } buffer.append("---------------------------------"); } return buffer.toString(); }
java
@Override @GwtIncompatible("incompatible method") public String getFormattedExceptionMessage(final String baseMessage){ final StringBuilder buffer = new StringBuilder(256); if (baseMessage != null) { buffer.append(baseMessage); } if (contextValues.size() > 0) { if (buffer.length() > 0) { buffer.append('\n'); } buffer.append("Exception Context:\n"); int i = 0; for (final Pair<String, Object> pair : contextValues) { buffer.append("\t["); buffer.append(++i); buffer.append(':'); buffer.append(pair.getKey()); buffer.append("="); final Object value = pair.getValue(); if (value == null) { buffer.append("null"); } else { String valueStr; try { valueStr = value.toString(); } catch (final Exception e) { valueStr = "Exception thrown on toString(): " + ExceptionUtils.getStackTrace(e); } buffer.append(valueStr); } buffer.append("]\n"); } buffer.append("---------------------------------"); } return buffer.toString(); }
[ "@", "Override", "@", "GwtIncompatible", "(", "\"incompatible method\"", ")", "public", "String", "getFormattedExceptionMessage", "(", "final", "String", "baseMessage", ")", "{", "final", "StringBuilder", "buffer", "=", "new", "StringBuilder", "(", "256", ")", ";", ...
Builds the message containing the contextual information. @param baseMessage the base exception message <b>without</b> context information appended @return the exception message <b>with</b> context information appended, never null
[ "Builds", "the", "message", "containing", "the", "contextual", "information", "." ]
9e2dfbbda3668cfa5d935fe76479d1426c294504
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/exception/DefaultExceptionContext.java#L128-L166
train
ixa-ehu/ixa-pipe-pos
src/main/java/eus/ixa/ixa/pipe/pos/dict/MultiWordMatcher.java
MultiWordMatcher.getTokensWithMultiWords
public final String[] getTokensWithMultiWords(final String[] tokens) { final Span[] multiWordSpans = multiWordsToSpans(tokens); final List<String> tokenList = new ArrayList<String>(Arrays.asList(tokens)); int counter = 0; for (final Span mwSpan : multiWordSpans) { final int fromIndex = mwSpan.getStart() - counter; final int toIndex = mwSpan.getEnd() - counter; // System.err.println(fromIndex + " " + toIndex); // add to the counter the length of the sublist removed // to allow the fromIndex and toIndex to match wrt to the tokenList // indexes counter = counter + tokenList.subList(fromIndex, toIndex).size() - 1; // create the multiword joining the sublist final String multiWord = Joiner.on("#").join( tokenList.subList(fromIndex, toIndex)); // remove the sublist containing the tokens to be replaced in the span tokenList.subList(fromIndex, toIndex).clear(); // add the multiword containing the tokens in one Span tokenList.add(fromIndex, multiWord); } return tokenList.toArray(new String[tokenList.size()]); }
java
public final String[] getTokensWithMultiWords(final String[] tokens) { final Span[] multiWordSpans = multiWordsToSpans(tokens); final List<String> tokenList = new ArrayList<String>(Arrays.asList(tokens)); int counter = 0; for (final Span mwSpan : multiWordSpans) { final int fromIndex = mwSpan.getStart() - counter; final int toIndex = mwSpan.getEnd() - counter; // System.err.println(fromIndex + " " + toIndex); // add to the counter the length of the sublist removed // to allow the fromIndex and toIndex to match wrt to the tokenList // indexes counter = counter + tokenList.subList(fromIndex, toIndex).size() - 1; // create the multiword joining the sublist final String multiWord = Joiner.on("#").join( tokenList.subList(fromIndex, toIndex)); // remove the sublist containing the tokens to be replaced in the span tokenList.subList(fromIndex, toIndex).clear(); // add the multiword containing the tokens in one Span tokenList.add(fromIndex, multiWord); } return tokenList.toArray(new String[tokenList.size()]); }
[ "public", "final", "String", "[", "]", "getTokensWithMultiWords", "(", "final", "String", "[", "]", "tokens", ")", "{", "final", "Span", "[", "]", "multiWordSpans", "=", "multiWordsToSpans", "(", "tokens", ")", ";", "final", "List", "<", "String", ">", "to...
Get input text and join the multiwords found in the dictionary object. @param tokens the input text @return the output text with the joined multiwords
[ "Get", "input", "text", "and", "join", "the", "multiwords", "found", "in", "the", "dictionary", "object", "." ]
083c986103f95ae8063b8ddc89a2caa8047d29b9
https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/dict/MultiWordMatcher.java#L154-L175
train