code
stringlengths
73
34.1k
label
stringclasses
1 value
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...
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...
java
public void remove(String name) { EndpointService<L, S> service = endpointServices.remove(name); if (service != null) { service.stop(); log.infoRemovedEndpointService(service.toString()); } }
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) ...
java
public void stopHawkularAgent() { synchronized (agentServiceStatus) { if (agentServiceStatus.get() == ServiceStatus.STOPPED) { log.infoStoppedAlready(); return; // we are already stopped } else if (agentServiceStatus.get() == ServiceStatus.STOPPING) { ...
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.ge...
java
public static <L> Builder<L> builder(Resource<L> template) { return new Builder<L>(template); }
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 instanc...
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 (directParent...
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); } } retur...
java
private List<String> getDomainHostServers(ModelControllerClient mcc, String hostName) { return getChildrenNames(PathAddress.EMPTY_ADDRESS.append("host", hostName), "server", mcc); }
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 (JavaAge...
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); ...
java
public static void ensureEndsWithSlash(StringBuilder str) { if (str.length() == 0 || str.charAt(str.length() - 1) != '/') { str.append('/'); } }
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, bufferSiz...
java
public static String base64Encode(String plainTextString) { String encoded = new String(Base64.getEncoder().encode(plainTextString.getBytes())); return encoded; }
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 (containerI...
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); ...
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(); ...
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 ...
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, ap...
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.g...
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_R...
java
public Double getProcessorMetric(String processorNumber, ID metricToCollect) { CentralProcessor processor = getProcessor(); if (processor == null) { return null; } int processorIndex; try { processorIndex = Integer.parseInt(processorNumber); ...
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_S...
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(me...
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 ...
java
public Double getMetric(PlatformResourceType type, String name, ID metricToCollect) { switch (type) { case OPERATING_SYSTEM: { return getOperatingSystemMetric(metricToCollect); } case MEMORY: { return getMemoryMetric(metricToCollect); ...
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 : a...
java
public Set<ResourceType<L>> getChildren(ResourceType<L> resourceType) { Set<ResourceType<L>> directChildren = index.successorsOf(resourceType); return Collections.unmodifiableSet(directChildren); }
java
public Set<ResourceType<L>> getParents(ResourceType<L> resourceType) { Set<ResourceType<L>> directParents = index.predecessorsOf(resourceType); return Collections.unmodifiableSet(directParents); }
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 gr...
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(); configur...
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(); ...
java
private void destroyPingExecutor() { synchronized (pingExecutor) { if (!pingExecutor.isShutdown()) { try { log.debugf("Shutting down WebSocket ping executor"); pingExecutor.shutdown(); if (!pingExecutor.awaitTermination(1, T...
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; }
java
public void addProperty(String name, Object value) { if (value != null) { properties.put(name, value); } else { removeProperty(name); } }
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); }
java
public void addSocketBinding(String socketBindingGroupName, String socketBindingName, int port) throws Exception { addSocketBinding(socketBindingGroupName, socketBindingName, null, port); }
java
public void setSocketBindingPort(String socketBindingGroupName, String socketBindingName, int port) throws Exception { setSocketBindingPortExpression(socketBindingGroupName, socketBindingName, null, port); }
java
public void setStandardSocketBindingInterface(String socketBindingName, String interfaceName) throws Exception { setStandardSocketBindingInterfaceExpression(socketBindingName, null, interfaceName); }
java
public void setSocketBindingPort(String socketBindingGroupName, String socketBindingName, String interfaceName) throws Exception { setSocketBindingInterfaceExpression(socketBindingGroupName, socketBindingName, null, interfaceName); }
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 (cla...
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; }
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 ==...
java
public ZonedDateTime intoZonedDateTimeOrUse(ZoneId fallback){ try { return intoZonedDateTime(); } catch (RuntimeException ex) { return intoLocalDateTime().atZone(fallback); } }
java
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 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 allMorp...
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 lemma...
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("Outp...
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.equalsIgnoreC...
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...
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...
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.addArgum...
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...
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 ...
java
public List<String> getTokenList() { checkTokenized(); final List<String> list = new ArrayList<>(tokens.length); list.addAll(Arrays.asList(tokens)); return list; }
java
public StrTokenizer reset(final String input) { reset(); if (input != null) { this.chars = input.toCharArray(); } else { this.chars = null; } return this; }
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 { ...
java
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 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( ...
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 ...
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++) { ...
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...
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; }
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(); }
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; }
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; }
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 (p...
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 an...
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")...
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....
java
@SafeVarargs public static Function<CharSequence, TemporalAccessor> orderedParseAttempter(Function<CharSequence, TemporalAccessor>... parsers) { return date -> { RuntimeException first = null; for (Function<CharSequence, TemporalAccessor> parser : parsers) { try { ret...
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; } e...
java
public ReflectionToStringBuilder setExcludeFieldNames(final String... excludeFieldNamesParam) { if (excludeFieldNamesParam == null) { this.excludeFieldNames = null; } else { //clone and remove nulls this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam);...
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); }
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 = (un...
java
public static boolean truncatedEquals(final Date date1, final Date date2, final int field) { return truncatedCompareTo(date1, date2, field) == 0; }
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); }
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); }
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[] { l...
java
public static <T> Builder<T> newSorter(Serializer<T> serializer, Comparator<T> comparator) { return new Builder<T>(serializer, comparator); }
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); ...
java
public CloseableIterator<T> mergeSortedChunks(List<File> sortedChunks) throws IOException { return mergeSortedChunksNoPartialMerge(partialMerge(sortedChunks)); }
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("Chu...
java
public File writeSortedChunk(Iterator<T> input) throws IOException { List<T> chunk = readChunk(input); return writeInternalSortedChunk(chunk); }
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; }
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); } el...
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 = ...
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...
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); } }
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_BET...
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); } }
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, ty...
java
private StringBuilder spacer(final int spaces) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < spaces; i++) { sb.append(" "); } return sb; }
java
private boolean performStateCheck(final int increment) { CheckIntervalData currentData; CheckIntervalData nextData; State currentState; do { final long time = now(); currentState = state.get(); currentData = checkIntervalData.get(); nextDa...
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; }
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.l...
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) { ...
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.getS...
java