id
stringlengths
7
14
text
stringlengths
1
37.2k
10873724_103
@Override public JClass apply(String nodeName, JsonNode node, JsonNode parent, JPackage jpackage, Schema schema) { boolean uniqueItems = node.has("uniqueItems") && node.get("uniqueItems").asBoolean(); boolean rootSchemaIsArray = !schema.isGenerated(); JType itemType; if (node.has("items")) { itemType = ruleFactory.getSchemaRule().apply(makeSingular(nodeName), node.get("items"), node, jpackage, schema); } else { itemType = jpackage.owner().ref(Object.class); } JClass arrayType; if (uniqueItems) { arrayType = jpackage.owner().ref(Set.class).narrow(itemType); } else { arrayType = jpackage.owner().ref(List.class).narrow(itemType); } if (rootSchemaIsArray) { schema.setJavaType(arrayType); } return arrayType; }
10899610_2
@Override public String generate(String givenNames, String surname) { Assert.hasText(givenNames, "Given name is required"); Assert.hasText(surname, "Surname is required"); int wordsSize = 0; wordsSize += givenNames.length(); wordsSize += surname.length(); if (wordsSize < DEFAULT_SIZE) { return StringUtils.upperCase(new StringBuilder().append(givenNames).append(surname).toString()); } // Character number to take from given names int fromGivenNames = 4; int fromSurname = 4; if (givenNames.length() < 4) { fromGivenNames = givenNames.length(); fromSurname += (4 - givenNames.length()); } if (surname.length() < 4) { fromSurname = surname.length(); fromGivenNames += (4 - surname.length()); } StringBuilder builder = new StringBuilder(); builder.append(givenNames.substring(0, fromGivenNames)); builder.append(surname.substring(0, fromSurname)); return StringUtils.upperCase(builder.toString()); }
10912209_41
@Factory public static Matcher<WebDriver> hasCookie(String name) { return new HasCookieMatcher(name); }
10932418_13
public long addComment(long app, long record, String text, List<MentionDto> mentions) throws DBException { JsonParser parser = new JsonParser(); String json; try { json = parser.generateForAddComment(app, record, text, mentions); } catch (IOException e) { throw new ParseException("failed to encode to json"); } String response = request("POST", "record/comment.json", json); try { return parser.jsonToId(response); } catch (IOException e) { throw new ParseException("failed to parse json to id list"); } }
10937119_2
public long getId(final String agent) { try { return worker.getId(agent); } catch (final InvalidUserAgentError e) { LOGGER.error("Invalid user agent ({})", agent); throw new SnowizardException(Response.Status.BAD_REQUEST, "Invalid User-Agent header", e); } catch (final InvalidSystemClock e) { LOGGER.error("Invalid system clock", e); throw new SnowizardException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage(), e); } }
10945339_20
@JniMethod ;
10953866_26
public void populate(Result result) { // process job-level stats and properties NavigableMap<byte[], byte[]> infoValues = result.getFamilyMap(Constants.INFO_FAM_BYTES); this.jobId = ByteUtil.getValueAsString(JobHistoryKeys.KEYS_TO_BYTES .get(JobHistoryKeys.JOBID), infoValues); this.user = ByteUtil.getValueAsString(JobHistoryKeys.KEYS_TO_BYTES .get(JobHistoryKeys.USER), infoValues); this.jobName = ByteUtil.getValueAsString(JobHistoryKeys.KEYS_TO_BYTES .get(JobHistoryKeys.JOBNAME),infoValues); this.priority = ByteUtil.getValueAsString(JobHistoryKeys.KEYS_TO_BYTES .get(JobHistoryKeys.JOB_PRIORITY), infoValues); this.status = ByteUtil.getValueAsString(JobHistoryKeys.KEYS_TO_BYTES .get(JobHistoryKeys.JOB_STATUS), infoValues); this.hadoopVersion = getHadoopVersionFromResult(JobHistoryKeys.hadoopversion, infoValues); this.version = ByteUtil.getValueAsString(Constants.VERSION_COLUMN_BYTES, infoValues); this.cost = ByteUtil.getValueAsDouble(Constants.JOBCOST_BYTES, infoValues); // times this.submitTime = ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES .get(JobHistoryKeys.SUBMIT_TIME), infoValues); this.launchTime = ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES .get(JobHistoryKeys.LAUNCH_TIME), infoValues); this.finishTime = ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES .get(JobHistoryKeys.FINISH_TIME), infoValues); this.megabyteMillis = ByteUtil.getValueAsLong(Constants.MEGABYTEMILLIS_BYTES, infoValues); this.cost = ByteUtil.getValueAsDouble(Constants.JOBCOST_BYTES, infoValues); // task counts this.totalMaps = ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.TOTAL_MAPS), infoValues); this.totalReduces = ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.TOTAL_REDUCES), infoValues); this.finishedMaps = ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FINISHED_MAPS), infoValues); this.finishedReduces = ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FINISHED_REDUCES), infoValues); this.failedMaps = ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FAILED_MAPS), infoValues); this.failedReduces = ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FAILED_REDUCES), infoValues); this.config = JobHistoryService.parseConfiguration(infoValues); this.queue = this.config.get(Constants.HRAVEN_QUEUE); this.counters = JobHistoryService.parseCounters(Constants.COUNTER_COLUMN_PREFIX_BYTES, infoValues); this.mapCounters = JobHistoryService.parseCounters(Constants.MAP_COUNTER_COLUMN_PREFIX_BYTES, infoValues); this.reduceCounters = JobHistoryService.parseCounters(Constants.REDUCE_COUNTER_COLUMN_PREFIX_BYTES, infoValues); // populate stats from counters for this job based on // hadoop version if (this.hadoopVersion == HadoopVersion.TWO) { // map file bytes read this.mapFileBytesRead = getCounterValueAsLong(this.mapCounters, Constants.FILESYSTEM_COUNTER_HADOOP2, Constants.FILES_BYTES_READ); // map file bytes written this.mapFileBytesWritten = getCounterValueAsLong(this.mapCounters, Constants.FILESYSTEM_COUNTER_HADOOP2, Constants.FILES_BYTES_WRITTEN); // reduce file bytes read this.reduceFileBytesRead = getCounterValueAsLong(this.reduceCounters, Constants.FILESYSTEM_COUNTER_HADOOP2, Constants.FILES_BYTES_READ); // hdfs bytes read this.hdfsBytesRead = getCounterValueAsLong(this.counters, Constants.FILESYSTEM_COUNTER_HADOOP2, Constants.HDFS_BYTES_READ); // hdfs bytes written this.hdfsBytesWritten = getCounterValueAsLong(this.counters, Constants.FILESYSTEM_COUNTER_HADOOP2, Constants.HDFS_BYTES_WRITTEN); // map slot millis this.mapSlotMillis = getCounterValueAsLong(this.counters, Constants.JOB_COUNTER_HADOOP2, Constants.SLOTS_MILLIS_MAPS); // reduce slot millis this.reduceSlotMillis = getCounterValueAsLong(this.counters, Constants.JOB_COUNTER_HADOOP2, Constants.SLOTS_MILLIS_REDUCES); // reduce shuffle bytes this.reduceShuffleBytes = getCounterValueAsLong(this.reduceCounters, Constants.TASK_COUNTER_HADOOP2, Constants.REDUCE_SHUFFLE_BYTES); } else { // presume it's hadoop1 // map file bytes read this.mapFileBytesRead = getCounterValueAsLong(this.mapCounters, Constants.FILESYSTEM_COUNTERS, Constants.FILES_BYTES_READ); // map file bytes written this.mapFileBytesWritten = getCounterValueAsLong(this.mapCounters, Constants.FILESYSTEM_COUNTERS, Constants.FILES_BYTES_WRITTEN); // reduce file bytes read this.reduceFileBytesRead = getCounterValueAsLong(this.reduceCounters, Constants.FILESYSTEM_COUNTERS, Constants.FILES_BYTES_READ); // hdfs bytes read this.hdfsBytesRead = getCounterValueAsLong(this.counters, Constants.FILESYSTEM_COUNTERS, Constants.HDFS_BYTES_READ); // hdfs bytes written this.hdfsBytesWritten = getCounterValueAsLong(this.counters, Constants.FILESYSTEM_COUNTERS, Constants.HDFS_BYTES_WRITTEN); // map slot millis this.mapSlotMillis = getCounterValueAsLong(this.counters, Constants.JOBINPROGRESS_COUNTER, Constants.SLOTS_MILLIS_MAPS); // reduce slot millis this.reduceSlotMillis = getCounterValueAsLong(this.counters, Constants.JOBINPROGRESS_COUNTER, Constants.SLOTS_MILLIS_REDUCES); // reduce shuffle bytes this.reduceShuffleBytes = getCounterValueAsLong(this.reduceCounters, Constants.TASK_COUNTER, Constants.REDUCE_SHUFFLE_BYTES); } // populate the task-level data // TODO: make sure to properly implement setTasks(...) before adding TaskDetails //populateTasks(result.getFamilyMap(Constants.TASK_FAM_BYTES)); }
10974543_2
public int checkValue(final int amount) { if (amount == 0) { throw new IllegalArgumentException("value is 0"); } return 0; }
10983382_14
@Override public Sequence tail() { CircularArraySequence<T> tempSequence = new CircularArraySequence<T>(this); if (backingArray[front]!=null){ tempSequence.backingArray[front] = null; tempSequence.fillCount-=1; if (front == backingArray.length-1){ tempSequence.front = 0; } else{ tempSequence.front+=1; } } return tempSequence; }
10989097_1
@Override final public boolean incrementToken() throws IOException { if (currentEntry == null) { currentEntry = currentIterator.next(); currentCount = 0; String result = String.format("%s_%d", currentEntry.getKey(), currentCount); termAtt.setEmpty().append(result); return true; } else { if (currentCount < currentEntry.getValue()) { String result = String.format("%s_%d", currentEntry.getKey(), ++currentCount); termAtt.setEmpty().append(result); return true; } else if (currentIterator.hasNext()) { Map.Entry<String, Integer> currentEntry = currentIterator.next(); currentCount = 0; String result = String.format("%s_%d", currentEntry.getKey(), currentCount); termAtt.setEmpty().append(result); return true; } else { return false; } } }
11036770_0
public static URI create(String s) { return URI.create(s.replace(" ", "%20")); }
11074539_112
@Override public void remove() { throw new UnsupportedOperationException(); }
11125589_88
@Override public void saveAccountInfo(OidcKeycloakAccount account) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { throw new IllegalStateException(String.format("Went to save Keycloak account %s, but already have %s", account, authentication)); } logger.debug("Saving account info {}", account); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(new KeycloakAuthenticationToken(account, true)); SecurityContextHolder.setContext(context); }
11128472_1
@Programmatic public InvoiceItem findFirstItemWithCharge(final Charge charge) { for (InvoiceItem item : getItems()) { if (item.getCharge().equals(charge)) { return item; } } return null; }
11140459_23
public ParcelableDescriptor analyze(ASTType astType) { ASTAnnotation parcelASTAnnotation = astType.getASTAnnotation(Parcel.class); return analyze(astType, parcelASTAnnotation); }
11144122_0
public String say() { return hello; }
11152828_62
public List<AbbyyProcess> split(AbbyyProcess process, int splitSize) { if (process.getNumberOfImages() == 0) { throw new IllegalArgumentException("Cannot split the process, it has no images: " + process.getName()); } if (process.getNumberOfImages() <= splitSize) { List<AbbyyProcess> sp = new ArrayList<AbbyyProcess>(); sp.add(process); return sp; } else { mergingObserver.setParentProcess(process); List<AbbyyProcess> subProcesses = createSubProcesses(process, splitSize); for(AbbyyProcess subProcess : subProcesses){ subProcess.setMerger(mergingObserver); mergingObserver.addSubProcess(subProcess); } return subProcesses; } }
11159652_55
@Override public void importRules(List<Rule> rules) { pushQuite(); try { if (rules.size() > 1) { LOGGER.warn("Importing a " + this.getClass().getSimpleName() + " with " + rules.size() + " rules"); } Rule rule = rules.get(0); // TODO Parse metainfostring?! RasterSymbolizer rs = (RasterSymbolizer) rule.symbolizers().get(0); // Alle RasterRulesLIstColorMaps haben eine singuläre // ChannelSelection { ChannelSelection channelSelection = rs.getChannelSelection(); if (channelSelection != null) { SelectedChannelType grayChannel = channelSelection .getGrayChannel(); if (grayChannel != null) { band = Integer.valueOf(grayChannel.getChannelName()) - 1; } } } ColorMap cm = rs.getColorMap(); importColorMap(cm); // Analyse the filters... org.opengis.filter.Filter filter = rule.getFilter(); filter = parseAbstractRlSettings(filter); } finally { popQuite(); } }
11161563_1
@Override public Boolean fromString(String string, ConverterContext context) { if (string.equalsIgnoreCase(getTrue())) { return Boolean.TRUE; } else if (string.equalsIgnoreCase("true")) { // in case the application runs under different locale, we still consider "true" is true. NON-NLS return Boolean.TRUE; } else if (string.equalsIgnoreCase(getFalse())) { return Boolean.FALSE; } else if (string.equalsIgnoreCase("false")) { // in case the application runs under different locale, we still consider "false" is false. NON-NLS return Boolean.FALSE; } else { return null; } }
11164718_0
public void setCounts(MLSJSONObject ichnaeaQueryObj) { mCellCount = ichnaeaQueryObj.getCellCount(); mWifiCount = ichnaeaQueryObj.getWifiCount(); }
11178914_16
public void removeIdAndRevision() { remove(table.getPrimaryKeyColumn().get()); if (table.getRevisionColumn().isPresent()) { remove(table.getRevisionColumn().get().getColumnName()); } }
11194069_0
boolean isValid() { try { new URL(this.uri); } catch (MalformedURLException ex) { return false; } return this.command != null; }
11198387_9
@Override public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) { return new Provider<T>() { @Override public T get() { Map<Key<?>, Object> map = getScopeMapForCurrentThread(); checkState(map != null, "No scope map found for the current thread. Forgot to call enterScope()?"); return getScopedObject(key, unscoped, map); } @Override public String toString() { return String.format("%s[%s]", unscoped, ThreadScope.this); } }; }
11206901_5
@Override public String getHtmlFragment(JRHtmlExporterContext context, JRGenericPrintElement element) { Map<String, Object> contextMap = new HashMap<String, Object>(); contextMap.put("mapCanvasId", "map_canvas_" + element.hashCode()); if (context.getExporter() instanceof JRXhtmlExporter) { contextMap.put("xhtml", "xhtml"); JRXhtmlExporter xhtmlExporter = (JRXhtmlExporter) context.getExporter(); contextMap.put("elementX", xhtmlExporter.toSizeUnit(element.getX())); contextMap.put("elementY", xhtmlExporter.toSizeUnit(element.getY())); } else { JRHtmlExporter htmlExporter = (JRHtmlExporter) context.getExporter(); contextMap.put("elementX", htmlExporter.toSizeUnit(element.getX())); contextMap.put("elementY", htmlExporter.toSizeUnit(element.getY())); } contextMap.put("elementId", element.getKey()); contextMap.put("elementWidth", element.getWidth()); contextMap.put("elementHeight", element.getHeight()); if (element.getModeValue() == ModeEnum.OPAQUE) { contextMap.put("backgroundColor", JRColorUtil.getColorHexa(element.getBackcolor())); } WmsRequestBuilder requestBuilder = WmsMapElementImageProvider.mapRequestBuilder(element); try { contextMap.put("wmsMapUrl", requestBuilder.toMapUrl()); } catch (MalformedURLException e) { throw new RuntimeException("Unable to build WMS map service url", e); } return VelocityUtil.processTemplate(MAP_ELEMENT_HTML_TEMPLATE, contextMap); }
11217397_26
public FormValidation doCheckIncludeRegex(@QueryParameter String value) { String v = Util.fixEmpty(value); if (v != null) { try { Pattern.compile(v); } catch (PatternSyntaxException pse) { return FormValidation.error(pse.getMessage()); } } return FormValidation.ok(); }
11219096_12
@Override public boolean add(final Card card) { if (size() == MAX_CARDS) { throw new IllegalStateException("Card deck is already filled with " + MAX_CARDS + " cards."); } if (contains(card)) { throw new IllegalArgumentException("Card " + card + " is already contained in card deck."); } return super.add(card); }
11226198_7
public V getUnchecked() { try { return get(); } catch (Throwable pokemon) { Util.pokeball(pokemon); } return null; }
11233417_148
@Override public SVAnnotation build() { final GenomeInterval changeInterval = svTandemDup.getGenomeInterval(); // Go over the different cases from most to least pathogenic step and return most pathogenic one. if (changeInterval.overlapsWith(transcript.getTXRegion())) { return new SVAnnotation(svTandemDup, transcript, buildEffectSet(Sets.immutableEnumSet( VariantEffect.TRANSCRIPT_AMPLIFICATION, VariantEffect.STRUCTURAL_VARIANT, VariantEffect.DIRECT_TANDEM_DUPLICATION ))); } else if (so.overlapsWithUpstreamRegion(changeInterval)) { return new SVAnnotation(svTandemDup, transcript, buildEffectSet(Sets.immutableEnumSet( VariantEffect.STRUCTURAL_VARIANT, VariantEffect.UPSTREAM_GENE_VARIANT ))); } else if (so.overlapsWithDownstreamRegion(changeInterval)) { return new SVAnnotation(svTandemDup, transcript, buildEffectSet(Sets.immutableEnumSet( VariantEffect.STRUCTURAL_VARIANT, VariantEffect.DOWNSTREAM_GENE_VARIANT ))); } else { return new SVAnnotation(svTandemDup, transcript, buildEffectSet(Sets.immutableEnumSet( VariantEffect.STRUCTURAL_VARIANT, VariantEffect.INTERGENIC_VARIANT ))); } }
11254311_793
static MD5Hash getFileClient(String nnHostPort, String queryString, List<File> localPaths, Storage dstStorage, boolean getChecksum) throws IOException { String str = HttpConfig.getSchemePrefix() + nnHostPort + "/getimage?" + queryString; LOG.info("Opening connection to " + str); // // open connection to remote server // URL url = new URL(str); return doGetUrl(url, localPaths, dstStorage, getChecksum); }
11267509_1
public static <T> ListenableFuture<T> submit(final RequestBuilder<T> requestBuilder) { return transformFromTargetAndResult(submitInternal(requestBuilder)); }
11275102_1
public static long computeArraySUID(String name) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); try { dout.writeUTF(name); dout.writeInt(Modifier.PUBLIC | Modifier.FINAL | Modifier.ABSTRACT); dout.flush(); } catch (IOException ex) { throw new Error(ex); } MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException ex) { throw new Error(ex); } byte[] hashBytes = md.digest(bout.toByteArray()); long hash = 0; for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) { hash = (hash << 8) | (hashBytes[i] & 0xFF); } return hash; }
11281607_27
@Override public void addMessageHandler(MessageHandler handler) { checkConnectionState(State.CLOSED); synchronized (handlerManager) { handlerManager.addMessageHandler(handler); } }
11286308_6
@Override public boolean isValid() { // Must have exactly 9 numeric digits if (this.financialID.length() != 9 || !this.financialID.matches("\\d+")) { return false; } List<Character> firstDigits = Lists.charactersOf("123568"); boolean validFirstDigit = firstDigits .stream() .map(c -> financialID.charAt(0) == c).filter(b -> b) .findAny() .orElse(false); List<String> firstDoubleDigits = Lists.newArrayList("45", "70", "71", "72", "74", "75", "77", "79", "90", "91", "98", "99"); boolean validDoubleDigits = firstDoubleDigits .stream() .map(c -> financialID.substring(0, 2).equals(c)) .filter(b -> b) .findAny() .orElse(false); if(!validFirstDigit && !validDoubleDigits){ return false; } int checkSum = 0; for (int i = 1; i < this.financialID.length(); i++) { int digit = Character.getNumericValue(this.financialID.charAt(i - 1)); checkSum += (10 - i) * digit; } int lastDigit = Character.getNumericValue(this.financialID.charAt(8)); int val = (checkSum / 11) * 11; checkSum -= val; if (checkSum == 0 || checkSum == 1) { checkSum = 0; } else { checkSum = 11 - checkSum; } if (checkSum == lastDigit) { return true; } else { return false; } }
11290309_30
public byte[] read(Integer length) throws IOException { if (length == null) { return readToEof(); } else { return readTo(length); } }
11304836_0
@Override public Map<K, V> loadAll(final Iterable<? extends K> keys) throws CacheLoaderException { final Map<K, V> result = new HashMap<K, V>(); for (final K k : keys) { final V v = load(k); if (v != null) { result.put(k, v); } } return result; }
11304845_34
@Override public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (o.getClass() != getClass()) { return false; } MethodSignature other = (MethodSignature) o; return other.internal.equals(internal); }
11309044_135
@Override public long dot(MapKL<K> m) { long s = 0; for (MapKL.Entry<K> e : m.entrySet()) { K key = e.getKey(); if (this.containsKey(key)) { s += this.get(key) * e.getValue(); } } return s; }
11324849_308
public static double getEditDistance(CharSequence s, CharSequence t) { return getEditDistance(s, t, DEFAULT_OPERATIONS_WEIGHTS); }
11335237_371
public T next() { return function.evaluate(iterator.next()); }
11337147_387
public Finder create(final Class<? extends ServerResource> clazz) { final Finder finder = finders.get(clazz); if (finder == null) { throw new RuntimeException("Finder unimplemented for class " + clazz); } return finder; }
11344750_180
public static DoubleMatrixDataset<String, String> weightedCorrelationColumnsOf2Datasets(DoubleMatrixDataset<String, String> d1, DoubleMatrixDataset<String, String> d2, DoubleMatrixDataset<String, String> rowWeigths) throws Exception { if (d1.rows() != d2.rows() || d1.rows() != rowWeigths.rows()) { throw new Exception("When correlating two datasets both should have identical number of rows. d1 has: " + d1.rows() + " d2 has: " + d2.rows() + " weights has: " + rowWeigths.rows() + " rows"); } final DoubleMatrix2D d1Matrix = d1.getMatrix(); final DoubleMatrix2D d2Matrix = d2.getMatrix(); final DoubleMatrix1D weigths = rowWeigths.getCol(0); final double sumOfWeights = weigths.zSum(); final DoubleMatrixDataset<String, String> correlations = new DoubleMatrixDataset<>(d2.getHashColsCopy(), d1.getHashColsCopy()); final DoubleMatrix2D corMatrix = correlations.getMatrix(); final int d1NrCols = d1.columns(); final int d2NrCols = d2.columns(); final int nrRows = d1.rows(); //final DoubleMatrix1D[] d1Cols = new DoubleMatrix1D[d1NrCols]; final double[] d1ColsWeightedMean = new double[d1NrCols]; for (int i = d1NrCols; --i >= 0;) { //d1Cols[i] = d1Matrix.viewColumn(i); d1ColsWeightedMean[i] = weightedMean(d1Matrix.viewColumn(i), weigths); } //final DoubleMatrix1D[] d2Cols = new DoubleMatrix1D[d2NrCols]; final double[] d2ColsWeightedMean = new double[d2NrCols]; for (int i = d2NrCols; --i >= 0;) { //d2Cols[i] = d2Matrix.viewColumn(i); d2ColsWeightedMean[i] = weightedMean(d2Matrix.viewColumn(i), weigths); } for (int d1c = d1NrCols; --d1c >= 0;) { //final DoubleMatrix1D col1 = d1Cols[i]; final double wmX = d1ColsWeightedMean[d1c]; for (int d2c = d2NrCols; --d2c >= 0;) { //final DoubleMatrix1D col2 = d2Cols[j]; final double wmY = d2ColsWeightedMean[d2c]; double covXX = 0; double covXY = 0; double covYY = 0; for (int r = 0; r < nrRows; ++r) { final double weight = weigths.getQuick(r); final double d1eMinWmx = d1Matrix.getQuick(r, d1c) - wmX; final double d2eMinWmy = d2Matrix.getQuick(r, d2c) - wmY; covXX += weight * d1eMinWmx * d1eMinWmx; covXY += weight * d1eMinWmx * d2eMinWmy; covYY += weight * d2eMinWmy * d2eMinWmy; } covXX /= sumOfWeights; covXY /= sumOfWeights; covYY /= sumOfWeights; final double corr = covXY / (Math.sqrt(covXX * covYY)); corMatrix.setQuick(d2c, d1c, corr); } } return correlations; }
11367662_1
@Override public <T> T resolve(final Class<T> clazz) { final Object component = resolve(clazz, true); return clazz.cast(component); }
11369509_12
@Override public void unregisterProtoFile(String fileName) { log.debugf("Unregistering proto file : %s", fileName); writeLock.lock(); try { FileDescriptor fileDescriptor = fileDescriptors.remove(fileName); if (fileDescriptor != null) { unregisterFileDescriptorTypes(fileDescriptor); } else { throw new IllegalArgumentException("File " + fileName + " does not exist"); } } finally { writeLock.unlock(); } }
11384368_4
public static String getContentAsString(final FileObject file, final Charset charset) throws IOException { try (final FileContent content = file.getContent()) { return content.getString(charset); } }
11392749_29
public static StringOperator replace(@NotNull final String what, @NotNull final String with) { return new StringOperator() { @Override public String apply(final String arg) { return Strings.replace(arg, what, with); } }; }
11395286_13
@Override public void setProgressEndpoints(double begin, double end) { if (Double.isNaN(begin) || Double.isNaN(end) || begin < 0.0 || (begin > end)) { throw new IllegalArgumentException( "invalid progress endpoints (begin == " + begin + ", end == " + end + ")"); } if (hasBegun.get()) { throw new IllegalStateException( "endpoints must be set before running the AbstractTask" ); } else { beginProgress = begin; endProgress = end; } }
11397182_17
public static AllowedMechanisms fromBinaryEncoding(final byte[] binary) throws IllegalArgumentException { final ArrayList<Long> mechs = new ArrayList<>(); try { final LongBuffer lb = ByteBuffer.wrap(binary).order(ByteOrder.LITTLE_ENDIAN).asLongBuffer(); while (lb.hasRemaining()) { mechs.add(lb.get()); } } catch (BufferUnderflowException ex) { throw new IllegalArgumentException("Unable to parse allowed mechanisms value: " + ex.getMessage()); } return new AllowedMechanisms(mechs); }
11416570_5
public static byte[] macAddress() { byte[] override = getOverride(); return override != null ? override : realMacAddress(); }
11429654_9
public Object read() throws IOException { char[] buffer = new char[BUFFER_LENGTH]; reader.mark(BUFFER_LENGTH); int count = 0; int textEnd; while (true) { int r = reader.read(buffer, count, buffer.length - count); if (r == -1) { // the input is exhausted; return the remaining characters textEnd = count; break; } count += r; int possibleMarker = findPossibleMarker(buffer, count); if (possibleMarker != 0) { // return the characters that precede the marker textEnd = possibleMarker; break; } if (count < marker.length()) { // the buffer contains only the prefix of a marker so we must read more continue; } // we've read a marker so return the value that follows reader.reset(); String json = reader.readLine().substring(marker.length()); return jsonParser.parse(json); } if (count == 0) { return null; } // return characters reader.reset(); count = reader.read(buffer, 0, textEnd); return new String(buffer, 0, count); }
11450329_1
@Override public void createFriendship(final Node following, final Node followed) { // try to find the replica node of the user followed Node followedReplica = null; for (Relationship followship : following.getRelationships( SocialGraphRelationshipType.FOLLOW, Direction.OUTGOING)) { followedReplica = followship.getEndNode(); if (NeoUtils.getNextSingleNode(followedReplica, SocialGraphRelationshipType.REPLICA).equals(followed)) { break; } followedReplica = null; } // user is following already if (followedReplica != null) { return; } // create replica final Node newReplica = this.graph.createNode(); following.createRelationshipTo(newReplica, SocialGraphRelationshipType.FOLLOW); newReplica.createRelationshipTo(followed, SocialGraphRelationshipType.REPLICA); // check if followed user is the first in following's ego network if (NeoUtils.getNextSingleNode(following, SocialGraphRelationshipType.GRAPHITY) == null) { following.createRelationshipTo(newReplica, SocialGraphRelationshipType.GRAPHITY); } else { // search for insertion index within following replica layer final long followedTimestamp = getLastUpdateByReplica(newReplica); long crrTimestamp; Node prevReplica = following; Node nextReplica = null; while (true) { // get next user nextReplica = NeoUtils.getNextSingleNode(prevReplica, SocialGraphRelationshipType.GRAPHITY); if (nextReplica != null) { crrTimestamp = getLastUpdateByReplica(nextReplica); // step on if current user has newer status updates if (crrTimestamp > followedTimestamp) { prevReplica = nextReplica; continue; } } // insertion position has been found break; } // insert followed user's replica into following's ego network if (nextReplica != null) { prevReplica.getSingleRelationship( SocialGraphRelationshipType.GRAPHITY, Direction.OUTGOING).delete(); newReplica.createRelationshipTo(nextReplica, SocialGraphRelationshipType.GRAPHITY); } prevReplica.createRelationshipTo(newReplica, SocialGraphRelationshipType.GRAPHITY); } }
11451879_32
public static String getName(Network object) { if (isFilled(object.getName())) return object.getName(); return object.getObjectId(); }
11452433_6
@Override public T readFrom( Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream ) throws IOException, WebApplicationException { InputStreamReader reader = new InputStreamReader( entityStream, "UTF-8" ); Type jsonType; if (type.equals(genericType) || genericType == null) { jsonType = type; } else { jsonType = genericType; } try { return gson.fromJson( reader, jsonType ); } finally { reader.close(); } }
11453959_8
@SuppressWarnings("unchecked") public static <T> Class<T> defineClass(String className, byte[] b, Class<?> neighbor, ClassLoader loader) throws Exception { Class<T> c = (Class<T>) DefineClassHelper.defineClass(className, b, 0, b.length, neighbor, loader, PROTECTION_DOMAIN); // Force static initializers to run. Class.forName(className, true, loader); return c; }
11459376_4
protected Iterable<Row<String, String>> getRows(EnumSet<?> columns) throws Exception { int shardCount = config.getShardCount(); List<Future<Rows<String, String>>> futures = new ArrayList<Future<Rows<String, String>>>(); for (int i = 0; i < shardCount; i++) { futures.add(cassandra.selectAsync(generateSelectByShardCql(columns, i))); } List<Row<String, String>> rows = new LinkedList<Row<String, String>>(); for (Future<Rows<String, String>> f: futures) { Rows<String, String> shardRows = f.get(); Iterables.addAll(rows, shardRows); } return rows; }
11479356_0
public static Builder newBuilder() { return new Builder(); }
11480369_2
@Override public Object getProperty(String key) { return getProperty(key, null); }
11500828_55
public static <T> T getSingle(Iterator<T> iterator, String notFoundMessage) { T result = getSingleOrNull(iterator); if (result == null) { throw new NotFoundException(notFoundMessage); } return result; }
11525787_7
private MetricValue readQueueLength() { MetricValue value = null; Counter queueLength = metricRegistry .counter(MetricName.QUEUE_LENGTH.getName()); if (queueLength != null) { value = MetricValue.tuples(Long.valueOf( queueLength.getCount()).intValue()); } return value; }
11527775_8
@Override public int hashCode() { return Objects.hash(inner); }
11543457_128
public static FeedLocationStore get(){ return instance; }
11543691_11
@Override public List<Path> getClasspath() { String classpath = p.getProperty(CLASSPATH); if (classpath != null) { return parsePathList(classpath); } String classpathFile = p.getProperty(CLASSPATH_FILE); if (classpathFile != null) { return readPathList(Paths.get(classpathFile)); } throw new IllegalArgumentException("Missing required property: " + CLASSPATH); }
11553940_10
void writeGetMethods(JClassType target, SourceWriter writer) throws UnableToCompleteException { String targetType = target.getQualifiedSourceName(); writer.println("public List<EventHandlerMethod<%s, ?>> getMethods() {", targetType); writer.indent(); // Write a list that we will add all handlers to before returning writer.println("List<%1$s> methods = new LinkedList<%1$s>();", String.format("EventHandlerMethod<%s, ?>", targetType)); // Iterate over each method in the target, looking for methods annotated with @Subscribe for (JMethod method : target.getInheritableMethods()) { if (method.getAnnotation(Subscribe.class) == null) { continue; } checkValidity(target, method); // Generate a list of types that should be handled by this method. Normally, this is a single // type equal to the method's first argument. If the argument in a MultiEvent, this list of // types comes from the @EventTypes annotation on the parameter. final List<String> paramTypes = new LinkedList<String>(); final boolean isMultiEvent; if (getFirstParameterType(method).equals(MultiEvent.class.getCanonicalName())) { isMultiEvent = true; for (Class<?> type : method.getParameters()[0].getAnnotation(EventTypes.class).value()) { paramTypes.add(type.getCanonicalName()); } } else { isMultiEvent = false; paramTypes.add(getFirstParameterType(method)); } // Add an implementation of EventHandlerMethod to the list for each type this method handles for (String paramType : paramTypes) { writer.println("methods.add(new EventHandlerMethod<%s, %s>() {", targetType, paramType); writer.indent(); { // Implement invoke() by calling the method, first checking filters if provided writer.println("public void invoke(%s instance, %s arg) {", targetType, paramType); String invocation = String.format( isMultiEvent ? "instance.%s(new MultiEvent(arg));" : "instance.%s(arg);", method.getName()); if (method.getAnnotation(When.class) != null) { writer.indentln("if (%s) { %s }", getFilter(method), invocation); } else { writer.indentln(invocation); } writer.println("}"); // Implement acceptsArgument using instanceof writer.println("public boolean acceptsArgument(Object arg) {"); writer.indentln("return arg instanceof %s;", paramType); writer.println("}"); // Implement getDispatchOrder as the inverse of the method's priority writer.println("public int getDispatchOrder() {"); writer.indentln("return %d;", method.getAnnotation(WithPriority.class) != null ? -method.getAnnotation(WithPriority.class).value() : 0); writer.println("}"); } writer.outdent(); writer.println("});"); } } // Return the list of EventHandlerMethods writer.println("return methods;"); writer.outdent(); writer.println("}"); }
11558041_0
@Override public MobileSeries[] getAllSeries() throws VideoServiceException { try { return httpClient.get(new URL(MOBILE_URL + "keyword=index&d=" + idevice.getDeviceId()), MobileSeries[].class); } catch (MalformedURLException e) { throw new VideoServiceException(e); } catch (IOException e) { throw new VideoServiceException(e); } catch (UnauthorizedException e) { throw new VideoServiceException(e); } }
11566581_2
@Override @SuppressWarnings({ "rawtypes", "unchecked" }) public void process(Exchange exchange) throws Exception { String processInstanceId = exchange.getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID, String.class); String businessKey = exchange.getProperty(EXCHANGE_HEADER_BUSINESS_KEY, String.class); Map<String, Object> processVariables = ExchangeUtils.prepareVariables(exchange, parameters); if (messageName != null) { HashMap<String, Object> correlationKeys = new HashMap<String, Object>(); if (correlationKeyName != null) { Class clazz = String.class; String correlationKeyType = exchange.getProperty(EXCHANGE_HEADER_CORRELATION_KEY_TYPE, String.class); if (correlationKeyType != null) { clazz = Class.forName(correlationKeyType); } Object correlationKey = exchange.getProperty(EXCHANGE_HEADER_CORRELATION_KEY, clazz); if (correlationKey == null) { throw new RuntimeException("Missing value for correlation key for message '" + messageName + "'"); } correlationKeys.put(correlationKeyName, correlationKey); } // if we have process instance we try to send the message to this // one: if (processInstanceId != null) { ExecutionQuery query = runtimeService.createExecutionQuery() // .processInstanceId(processInstanceId) // .messageEventSubscriptionName(messageName); if (processDefinitionKey != null) { query.processDefinitionKey(processDefinitionKey); } Execution execution = query.singleResult(); if (execution == null) { throw new RuntimeException("Couldn't find waiting process instance with id '" + processInstanceId + "' for message '" + messageName + "'"); } runtimeService.messageEventReceived(messageName, execution.getId(), processVariables); } else if (businessKey != null) { // if we have businessKey, use it to correlate runtimeService.correlateMessage(messageName, businessKey, correlationKeys, processVariables); } else { // otherwise we just send the message to the engine to let the // engine // decide what to do // this can either correlate to a waiting instance or start a // new // process Instance runtimeService.correlateMessage(messageName, correlationKeys, processVariables); } } else { // signal a ReceiveTask needs a processInstance to be addressed // (hint: this should be best done by a message in the ReceiveTask // as this is possible from 7.1 on - this was introduced with 7.0 // where this was not yet possible) if (processInstanceId == null && businessKey != null) { ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey( businessKey); if (processDefinitionKey != null) { query.processDefinitionKey(processDefinitionKey); } ProcessInstance processInstance = query.singleResult(); if (processInstance != null) { processInstanceId = processInstance.getId(); } } if (processInstanceId == null) { throw new RuntimeException("Could not find the process instance via the provided properties (" + EXCHANGE_HEADER_PROCESS_INSTANCE_ID + "= '" + processInstanceId + "', " + EXCHANGE_HEADER_BUSINESS_KEY + "= '" + businessKey + "'"); } ExecutionQuery query = runtimeService.createExecutionQuery().processInstanceId( processInstanceId).activityId(activityId); if (processDefinitionKey != null) { query.processDefinitionKey(processDefinitionKey); } Execution execution = query.singleResult(); if (execution == null) { throw new RuntimeException("Couldn't find process instance with id '" + processInstanceId + "' waiting in activity '" + activityId + "'"); } runtimeService.signal(execution.getId(), processVariables); } }
11602449_2
public void validateOrderDate( @XPath(value = "/order:order/order:date", namespaces = @NamespacePrefix(prefix = "order", uri = "http://fabric8.com/examples/order/v7")) String date) throws OrderValidationException { final Calendar calendar = new GregorianCalendar(); try { calendar.setTime(DATE_FORMAT.parse(date)); if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { LOGGER.warn("Order validation failure: order date " + date + " should not be a Sunday"); throw new OrderValidationException("Order date should not be a Sunday: " + date); } } catch (ParseException e) { throw new OrderValidationException("Invalid order date: " + date); } }
11608365_5
public static void unregister(XAResourceProducer producer) { final ProducerHolder holder = new ProducerHolder(producer); if (!resources.remove(holder)) { if (log.isDebugEnabled()) { log.debug("resource with uniqueName '{}' has not been registered", holder.getUniqueName()); } } }
11613195_0
public Map<String, String> getThumbnailsForCollection(int start, int limit, int errorHandlingPolicy) throws TechnicalRuntimeException, IOException, EuropeanaApiProblem { return getThumbnailsForCollection(CommonMetadata.EDM_FIELD_THUMBNAIL_LARGE, start, limit, errorHandlingPolicy); }
11629470_0
@GET @Transactional public Note get() { try { return manager.createQuery("select n from Note n", Note.class).getSingleResult(); } catch (NoResultException e) { Note note = new Note(); note.setContent("Default message"); manager.persist(note); return note; } }
11656984_397
@Override public String toString() { return new StringBuilder().append(getClass().getSimpleName()) .append(" [path=") .append(path) .append(", cancel=") .append(cancel) .append(", refs=") .append(refs) .append("]") .toString(); }
11660383_23
@Override public void write(Job t, String contentType, HttpOutputMessage outputMessage) throws IOException { throw new UnsupportedOperationException(); }
11662606_6
public static String join(Collection<?> collection, String delimiter) { if (collection == null || collection.isEmpty()) { return EMPTY_STRING; } else if (delimiter == null) { delimiter = EMPTY_STRING; } StringBuilder builder = new StringBuilder(); Iterator<?> it = collection.iterator(); while (it.hasNext()) { builder.append(it.next()).append(delimiter); } int length = builder.length(); builder.delete(length - delimiter.length(), length); return builder.toString(); }
11664357_10
public static boolean isTrue(String tagValue) { return ("yes".equals(tagValue) || "1".equals(tagValue) || "true".equals(tagValue)); }
11666990_3
@Override public void transformPage(View view, float position) { int pageWidth = view.getWidth(); if (position < 0) { view.setAlpha(1 + position * 2); } else { view.setAlpha(1); view.setTranslationX((int) (pageWidth * -position * 0.7)); view.setScaleX(1 - position / 8); view.setScaleY(1 - position / 8); } }
11668780_7
public void newData(@Nonnull ChangesAdapter adapter, @Nonnull List<T> values, boolean force) { checkNotNull(adapter); checkNotNull(values); final ImmutableList<H> list = FluentIterable.from(values) .transform(mDetector) .toList(); int firstListPosition = 0; int secondListPosition = 0; int counter = 0; int toRemove = 0; for (;firstListPosition < mItems.size(); ++firstListPosition) { final H first = mItems.get(firstListPosition); final int indexOf = indexOf(list, secondListPosition, first); if (indexOf >= 0) { int itemsInserted = indexOf - secondListPosition; counter = notify(adapter, counter, toRemove, itemsInserted); toRemove = 0; secondListPosition = indexOf + 1; final H second = list.get(indexOf); if (force || !mDetector.same(first, second)) { adapter.notifyItemRangeChanged(counter, 1); } counter += 1; } else { toRemove += 1; } } int itemsInserted = values.size() - secondListPosition; notify(adapter, counter, toRemove, itemsInserted); mItems = list; }
11694419_2
@Override public void cleanup() { super.cleanup(); notifier.cleanup(); }
11695624_11
void parseArgs(String... args) throws IllegalArgumentException { List<String> rest = null; rest = Args.parse(this, args); if (rest == null || rest.size() != 1) { //exit("Invalid syntax"); throw new IllegalArgumentException("missing input"); } context = parseContext(); String input = rest.get(0); url = parseInputAsURL(input); }
11700816_3
@Override public boolean Validator(File file) throws FileNotFoundException, IOException, IllegalAccessException, InstantiationException { // Write your own elaborate validator to see if your LoadFile routine can deal with it String ext = getFileExtension(file); if (ext.equalsIgnoreCase(getExtention())) { String loadedString; Scanner sc = new Scanner(file); if (sc.hasNextLine()) { //workaround for binary img file sc.nextLine(); sc.nextLine(); loadedString = sc.nextLine(); if (loadedString.contains("\t")) { //check for tabs instead of spaces loadedString = loadedString.trim().replaceAll("\t", " "); } if (loadedString.trim().equalsIgnoreCase("Time explicit") | loadedString.trim().equalsIgnoreCase("Wavelength explicit") | loadedString.trim().equalsIgnoreCase("FLIM image")) { loadedString = sc.nextLine(); if (loadedString.trim().contains("NumberOfRecordsPerDatapoint")) { return true; } else { return false; } } else { return false; } } else { return false; } } else { return false; } }
11711223_9
private static String splitLine(String str, final int col) { if (str.length() < col) { return str; } // scan from `col` to left for (int i = col - 1; i > 0; i--) { if (str.charAt(i) == ' ') { return str.substring(0, i) + "\n" + splitLine(str.substring(i + 1), col); } } // we reached to beginning of the string and it contains no whitespaces before the `col` // but it's longer than `col` so we should replace first space after rightmost column // with a newline to make it shorter for (int i = col; i < str.length(); i++) { if (str.charAt(i) == ' ') { return str.substring(0, i) + "\n" + splitLine(str.substring(i + 1), col); } } // string has no spaces to split return str; }
11719739_6
public URL findResource(String resource) throws MojoFailureException { URL res = null; // first search relatively to the base directory try { final Path p = basedir.resolve(resource); res = toURL(p.toAbsolutePath()); } catch (final InvalidPathException e) { // no-op - can be caused by resource being a URI on windows when Path.resolve is called } if (res != null) { return res; } // if not found, search for absolute location on file system, or relative to execution dir try { res = toURL(Paths.get(resource)); } catch (final InvalidPathException e) { // no-op - can be caused by resource being a URI on windows when Paths.get is called } if (res != null) { return res; } // if not found, try the classpaths final String cpResource = resource.startsWith("/") ? resource.substring(1) : resource; // tries compile claspath of project res = compileClassPath.getResource(cpResource); if (res != null) { return res; } // tries this plugin classpath res = pluginClassPath.getResource(cpResource); if (res != null) { return res; } // otherwise, tries to return a valid URL try { res = new URL(resource); res.openStream().close(); return res; } catch (Exception e) { throw new MojoFailureException("Resource " + resource + " not found in file system, classpath or URL: " + e.getMessage(), e); } }
11724937_0
@Override public Future<RecordMetadata> send(ProducerRecord<K, V> record) { return send(record, null); }
11736323_36
public void putAll(Map<? extends String, ? extends Object> arg0) { inner.putAll(convertToTypedObjects(arg0)); }
11738699_2
public void stop() { // AstericsErrorHandling.instance.getLogger().fine("Invoking thread // <"+Thread.currentThread().getName()+">, : .stop called"); if (runningTaskFuture != null && !runningTaskFuture.isDone()) { runningTaskFuture.cancel(true); } active = false; count = 0; runningTaskFuture = null; }
11754395_21
@Override public Promise<HttpClientResponseAndBody> requestAbsAndReadBody(HttpMethod method, String absoluteURI) { return requestAbsAndReadBody(method, absoluteURI, null); }
11765760_0
public void parsePullRequestChains(PullRequests<? extends PullRequest> pullRequests) { Map<String, PullRequest> pullRequestsMap = Maps.newHashMap(); for (PullRequest pullRequest : pullRequests.getPullRequests()) { pullRequestsMap.put(pullRequest.getSource().getBranch().getName(), pullRequest); } for (PullRequest pullRequest : pullRequestsMap.values()) { List<String> chain = Lists.newArrayList(); PullRequestTarget destination = pullRequest.getDestination(); String branchName = destination.getBranch().getName(); chain.add(branchName); do { PullRequest destinationPullRequest = pullRequestsMap.get(branchName); if (destinationPullRequest != null) { branchName = destinationPullRequest.getDestination().getBranch().getName(); chain.add(branchName); } else { break; } } while (pullRequestsMap.containsKey(branchName)); pullRequest.setBranchChain(chain); } }
11769277_196
@POST @Path("/{id}/content_manipulation_lock") @RolesAllowed({ Role.ADMIN, Role.PROVIDER }) public Object contentManipulationLockCreate(@PathParam("id") @AuditId String id) throws ObjectNotFoundException { if (StringUtils.isBlank(id)) { throw new RequiredFieldException("id"); } if (ContentManipulationLockService.API_ID_ALL.equals(id)) { if (!authenticationUtilService.isUserInRole(Role.ADMIN)) { throw new NotAuthorizedException("admin permission required"); } contentManipulationLockService.createLockAll(); } else { Map<String, Object> entity = entityService.get(id); if (entity == null) throw new ObjectNotFoundException(); String usernameOfProviderWeChange = entity.get(ProviderService.NAME).toString(); authenticationUtilService.checkProviderManagementPermission(usernameOfProviderWeChange); contentManipulationLockService.createLock(id); } return Response.ok().build(); }
11797725_37
@Override public void channelInactive(ChannelHandlerContext ctx) { Attribute<FixSession> fixSessionAttribute = ctx.channel().attr(FIX_SESSION_KEY); if (fixSessionAttribute != null) { FixSession session = fixSessionAttribute.getAndSet(null); if (session != null) { ctx.fireChannelRead(new LogoutEvent(session)); sessionRepository.removeSession(session.getId()); getLogger().info("Fix Session Closed. {}", session); } } }
11799054_68
protected static int readAfterString(byte[] header, int off) { int start = readToString(header, off); int len = header[start + 2] & 0xFF; return start + len*2 + 3; }
11816589_0
void execute() { System.out.println(message); }
11851236_37
public CompletableFuture<Void> close() { log.info("Shutting down."); final CompletableFuture<Void> closeFuture; if (this.isClosed.compareAndSet(false, true)) { closeFuture = new CompletableFuture<>(); this.channelPool.close().addListener((GenericFutureListener<Future<Void>>) closePoolFuture -> { if (ApnsClient.this.shouldShutDownEventLoopGroup) { ApnsClient.this.eventLoopGroup.shutdownGracefully().addListener(future -> closeFuture.complete(null)); } else { closeFuture.complete(null); } }); } else { closeFuture = CompletableFuture.completedFuture(null); } return closeFuture; }
11862260_1
@RequestMapping(value = "result/{buildKey}.json", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @ResponseBody public BambooResultResponse getBambooBuildResponse(@PathVariable("buildKey") String buildKey, @RequestParam(value = "os_authType", required = false) String authType, @RequestParam(value = "os_username", required = false) String username, @RequestParam(value = "os_password", required = false) String password) { return simulator.getBuildResponse(); }
11880356_8
public float getFloat(String fieldName) throws DbfException { return getNumber(fieldName).floatValue(); }
11896265_5
@GET @Path( "/default" ) public Response defaultElement() throws IOException { IElement defaultElement = coreService.getDefaultElement(); if ( defaultElement != null ) { try { String url = defaultElement.getPluginId() + API_ROOT + defaultElement.getId(); return CpkUtils.redirect( url ); } catch ( URISyntaxException ex ) { logger.error( ex ); return Response.serverError().build(); } } else { return Response.ok( DEFAULT_NO_DASHBOARD_MESSAGE.getBytes( getEncoding() ) ).build(); } }
11904180_16
public Scheme createScheme( String format, Fields fields, Properties properties ) { LOG.info( "creating {} format with properties {} and fields {}", format, properties, fields ); String selectQuery = properties.getProperty( FORMAT_SELECT_QUERY ); String countQuery = properties.getProperty( FORMAT_COUNT_QUERY ); String separator = properties.getProperty( FORMAT_SEPARATOR, DEFAULT_SEPARATOR ); long limit = -1; String limitProperty = properties.getProperty( FORMAT_LIMIT ); if( limitProperty != null && !limitProperty.isEmpty() ) limit = Long.parseLong( limitProperty ); String[] columnNames = getColumnNames(fields, properties, separator); boolean tableAlias = getTableAlias(properties); if( selectQuery != null ) { if( countQuery == null ) throw new IllegalArgumentException( "no count query for select query given" ); return createScheme( fields, selectQuery, countQuery, limit, columnNames, tableAlias ); } String conditions = properties.getProperty( FORMAT_CONDITIONS ); String updateByProperty = properties.getProperty( FORMAT_UPDATE_BY ); String[] updateBy = null; if( updateByProperty != null && !updateByProperty.isEmpty() ) updateBy = updateByProperty.split( separator ); Fields updateByFields = null; if( updateByProperty != null && !updateByProperty.isEmpty() ) updateByFields = new Fields( updateBy ); String[] orderBy = null; String orderByProperty = properties.getProperty( FORMAT_ORDER_BY ); if( orderByProperty != null && !orderByProperty.isEmpty() ) orderBy = orderByProperty.split( separator ); return createUpdatableScheme( fields, limit, columnNames, tableAlias, conditions, updateBy, updateByFields, orderBy ); }
11916042_2
@Override public void patch( final DiscoveryResult orig, final List<? extends Location> locations, final Map<String, Object> context ) { final DiscoveryResult result = orig; final ProjectVersionRef ref = result.getSelectedRef(); try { final MavenPomView pomView = (MavenPomView) context.get( POM_VIEW_CTX_KEY ); // TODO: find a way to detect an assembly/distro pom, and turn deps from provided scope to compile scope. final String assemblyOnPomProjectPath = join( PATHS, "|" ); if ( pomView.resolveXPathToNode( assemblyOnPomProjectPath, false ) == null ) { return; } logger.debug( "Detected pom-packaging project with an assembly that produces artifacts without classifiers..." + "Need to flip provided-scope deps to compile scope here." ); for ( final ProjectRelationship<?, ?> rel : result.getAcceptedRelationships() ) { if ( !rel.isManaged() && rel instanceof DependencyRelationship && ( (DependencyRelationship) rel ).getScope() == DependencyScope.provided ) { // flip provided scope to compile scope...is this dangerous?? // if the project has packaging == pom and a series of assemblies, it's likely to be a distro project, and not meant for consumption via maven // also, if something like type == zip is used for a dependency, IIRC transitive deps are not traversed during the build. // so this SHOULD be safe. final DependencyRelationship dep = (DependencyRelationship) rel; logger.debug( "Fixing scope for: {}", dep ); result.removeDiscoveredRelationship( dep ); final Set<ProjectRef> excludes = dep.getExcludes(); final ProjectRef[] excludedRefs = excludes == null ? new ProjectRef[0] : excludes.toArray( new ProjectRef[excludes.size()] ); final DependencyRelationship replacement = new SimpleDependencyRelationship( dep.getSources(), dep.getPomLocation(), ref, dep.getTargetArtifact(), DependencyScope.embedded, dep.getIndex(), false, dep.isInherited(), dep.isOptional(), excludedRefs ); result.addDiscoveredRelationship( replacement ); } } } catch ( final GalleyMavenException e ) { logger.error( String.format( "Failed to build/query MavenPomView for: %s from: %s. Reason: %s", ref, locations, e.getMessage() ), e ); } catch ( final InvalidVersionSpecificationException e ) { logger.error( String.format( "Failed to build/query MavenPomView for: %s from: %s. Reason: %s", ref, locations, e.getMessage() ), e ); } catch ( final InvalidRefException e ) { logger.error( String.format( "Failed to build/query MavenPomView for: %s from: %s. Reason: %s", ref, locations, e.getMessage() ), e ); } }
11943595_64
public MutableSchema addTable(Table table) { _tables.add(table); return this; }
11971122_38
public PaaSInstance getPaaSInstance() { return paaSInstance; }
11974846_4
@Override public void preModifyColumn(ObserverContext<MasterCoprocessorEnvironment> c, byte[] tableName, HColumnDescriptor descriptor) throws IOException { requirePermission("modifyColumn", tableName, null, null, Action.ADMIN, Action.CREATE); }
11976306_9
public static String getAlias(final Dictionary<String, Object> config) { String alias = getValue(config, DECRYPTOR_ALIAS); for (Enumeration<String> e = config.keys(); e.hasMoreElements();) { final String key = e.nextElement(); String value = getValue(config, key); String newAlias = getAlias(value); if (newAlias != null) { if (alias == null) { alias = newAlias; } else { if (!alias.equals(newAlias)) { throw new RuntimeException("Only one alias is supported but found at least two: " + newAlias + ", " + alias); } } } } return alias; }
11992364_6
static String cutFieldName(final String string, final int from) { final int nextIndex = from + 1; final int len = string.length(); if (len > nextIndex) { char c = string.charAt(nextIndex); if (c >= 'A' && c <= 'Z') { return string.substring(from); } } char[] buffer = new char[len - from]; string.getChars(from, len, buffer, 0); char c = buffer[0]; if (c >= 'A' && c <= 'Z') { buffer[0] = (char) (c + 0x20); } return new String(buffer); }
12002935_3
protected void applyModifications(Element modificationsRoot, Element targetRoot) { for(Object object : modificationsRoot.elements()){ if(object instanceof Element){ Element modificationElement = (Element) object; String copy = modificationElement.attributeValue("sdk-copy"); if("true".equals(copy)){ addModification(targetRoot, modificationElement); } else { Element targetElement = targetRoot.element(modificationElement.getName()); if(targetElement == null) { targetElement = targetRoot.addElement(modificationElement.getName()); } applyModifications(modificationElement, targetElement); } } } }