java.util.SortedMap Java Examples

The following examples show how to use java.util.SortedMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MapDeserializer.java    From jvm-sandbox-repeater with Apache License 2.0 6 votes vote down vote up
private Map createMap()
  throws IOException
{
  
  if (_type == null)
    return new HashMap();
  else if (_type.equals(Map.class))
    return new HashMap();
  else if (_type.equals(SortedMap.class))
    return new TreeMap();
  else {
    try {
      return (Map) _ctor.newInstance();
    } catch (Exception e) {
      throw new IOExceptionWrapper(e);
    }
  }
}
 
Example #2
Source File: MemStoreFlusher.java    From hbase with Apache License 2.0 6 votes vote down vote up
private HRegion getBiggestMemStoreOfRegionReplica(
    SortedMap<Long, Collection<HRegion>> regionsBySize,
    Set<HRegion> excludedRegions) {
  synchronized (regionsInQueue) {
    for (Map.Entry<Long, Collection<HRegion>> entry : regionsBySize.entrySet()) {
      for (HRegion region : entry.getValue()) {
        if (excludedRegions.contains(region)) {
          continue;
        }

        if (RegionReplicaUtil.isDefaultReplica(region.getRegionInfo())) {
          continue;
        }
        return region;
      }
    }
  }
  return null;
}
 
Example #3
Source File: ConcurrentSkipListSubMapTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * headMap returns map with keys in requested range
 */
public void testHeadMapContents() {
    ConcurrentNavigableMap map = map5();
    SortedMap sm = map.headMap(four);
    assertTrue(sm.containsKey(one));
    assertTrue(sm.containsKey(two));
    assertTrue(sm.containsKey(three));
    assertFalse(sm.containsKey(four));
    assertFalse(sm.containsKey(five));
    Iterator i = sm.keySet().iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(one, k);
    k = (Integer)(i.next());
    assertEquals(two, k);
    k = (Integer)(i.next());
    assertEquals(three, k);
    assertFalse(i.hasNext());
    sm.clear();
    assertTrue(sm.isEmpty());
    assertEquals(2, map.size());
    assertEquals(four, map.firstKey());
}
 
Example #4
Source File: CSVRecordReader.java    From nifi with Apache License 2.0 6 votes vote down vote up
private List<RecordField> getRecordFields() {
    if (this.recordFields != null) {
        return this.recordFields;
    }

    // Use a SortedMap keyed by index of the field so that we can get a List of field names in the correct order
    final SortedMap<Integer, String> sortedMap = new TreeMap<>();
    for (final Map.Entry<String, Integer> entry : csvParser.getHeaderMap().entrySet()) {
        sortedMap.put(entry.getValue(), entry.getKey());
    }

    final List<RecordField> fields = new ArrayList<>();
    final List<String> rawFieldNames = new ArrayList<>(sortedMap.values());
    for (final String rawFieldName : rawFieldNames) {
        final Optional<RecordField> option = schema.getField(rawFieldName);
        if (option.isPresent()) {
            fields.add(option.get());
        } else {
            fields.add(new RecordField(rawFieldName, RecordFieldType.STRING.getDataType()));
        }
    }

    this.recordFields = fields;
    return fields;
}
 
Example #5
Source File: DefaultJournalCompactionStrategy.java    From journalkeeper with Apache License 2.0 6 votes vote down vote up
@Override
public long calculateCompactionIndex(SortedMap<Long, Long> snapshotTimestamps, Journal journal) {
    long index = -1;
    long now = System.currentTimeMillis();

    if (retentionMin > 0) {
        long compactTimestamp = now - retentionMin * 60 * 1000L;

        for (Map.Entry<Long, Long> entry : snapshotTimestamps.entrySet()) {
            long snapshotIndex = entry.getKey();
            long snapshotTimestamp = entry.getValue();
            if (snapshotTimestamp <= compactTimestamp) {
                index = snapshotIndex;
            } else {
                break;
            }
        }
        logger.info("Calculate journal compaction index: {}, current timestamp: {}.", index, ThreadSafeFormat.format(new Date(now)));
    }
    return index;
}
 
Example #6
Source File: TraceroutePolicyBasedRoutingTest.java    From batfish with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithNoPolicy() throws IOException {
  /*
   Construct TCP flow to 9.9.9.9, but don't set up PBR. Flow should take V1's static route out i1.
  */
  SortedMap<String, Configuration> configs = pbrNetwork(false);
  Batfish batfish = BatfishTestUtils.getBatfish(configs, _folder);
  batfish.computeDataPlane(batfish.getSnapshot());
  PacketHeaderConstraints header =
      PacketHeaderConstraints.builder()
          .setSrcIp("1.1.1.222")
          .setDstIp("9.9.9.9")
          .setIpProtocols(ImmutableSet.of(IpProtocol.TCP))
          .build();

  TracerouteQuestion question =
      new TracerouteQuestion(SOURCE_LOCATION_STR, header, false, DEFAULT_MAX_TRACES);
  TracerouteAnswerer answerer = new TracerouteAnswerer(question, batfish);
  Map<Flow, List<Trace>> traces = answerer.getTraces(batfish.getSnapshot(), question);

  assertThat(traces.entrySet(), hasSize(1));
  assertThat(
      traces.values().iterator().next(),
      contains(hasHop(hasOutputInterface(NodeInterfacePair.of("c1", "i1")))));
}
 
Example #7
Source File: FrequentSequenceMiner.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
/** Run BIDE algorithm */
public static SortedMap<Sequence, Integer> mineFrequentClosedSequencesBIDE(final String dataset,
		final String saveFile, final double minSupp) throws IOException {

	final SequenceDatabase sequenceDatabase = new SequenceDatabase();
	sequenceDatabase.loadFile(dataset);

	// Convert to absolute support (rounding down)
	final int absMinSupp = (int) (sequenceDatabase.size() * minSupp);

	final AlgoBIDEPlus algo = new AlgoBIDEPlus();
	algo.setShowSequenceIdentifiers(false);
	final SequentialPatterns patterns = algo.runAlgorithm(sequenceDatabase, saveFile, absMinSupp);
	// algo.printStatistics(sequenceDatabase.size());

	return toMap(patterns);
}
 
Example #8
Source File: InstructionsConverter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static SortedMap<String, Boolean> computeExportList (Map<Integer, String> exportInstructions, Project project) {
    SortedMap<String, Boolean> pkgMap = new TreeMap<String, Boolean>();
    SortedSet<String> pkgNames = FileUtilities.getPackageNames(project);
    for (String name : pkgNames) {
        pkgMap.put(name, Boolean.FALSE);
    }
    String exportIns = exportInstructions.get(EXPORT_PACKAGE);
    if (exportIns != null) {
        StringTokenizer strTok = new StringTokenizer(exportIns, DELIMITER);

        while(strTok.hasMoreTokens()) {
            String cur = strTok.nextToken();
            pkgMap.remove(cur);
            pkgMap.put(cur, Boolean.TRUE);
        }
    }

    return pkgMap;
}
 
Example #9
Source File: PartConnection.java    From libreveris with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Convenient method to connect parts across pages.
 * This method is to be used when merging the results of several pages.
 * Here we work directly with Audiveris Page entities
 *
 * @param pages the sequence of pages, as (audiveris) Page instances
 */
public static PartConnection connectScorePages (
        SortedMap<Integer, Page> pages)
{
    // Build candidates (here a candidate is a ScorePart)
    Set<List<Candidate>> sequences = new LinkedHashSet<>();

    for (Entry<Integer, Page> entry : pages.entrySet()) {
        Page page = entry.getValue();
        List<ScorePart> partList = page.getPartList();
        List<Candidate> parts = new ArrayList<>();

        for (ScorePart scorePart : partList) {
            parts.add(new ScorePartCandidate(scorePart, page));
        }

        sequences.add(parts);
    }

    return new PartConnection(sequences);
}
 
Example #10
Source File: CustomHTMLReporter.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private SortedMap<IClass, List<ITestResult>> sortByTestClass(IResultMap results) {
    SortedMap<IClass, List<ITestResult>> sortedResults = new TreeMap<IClass, List<ITestResult>>(CLASS_COMPARATOR);
    for (ITestResult result : results.getAllResults()) {
        List<ITestResult> resultsForClass = sortedResults.get(result.getTestClass());
        if (resultsForClass == null) {
            resultsForClass = new ArrayList<>();
            sortedResults.put(result.getTestClass(), resultsForClass);
        }
        int index = Collections.binarySearch(resultsForClass, result, RESULT_COMPARATOR);
        if (index < 0) {
            index = Math.abs(index + 1);
        }
        resultsForClass.add(index, result);
    }
    return sortedResults;
}
 
Example #11
Source File: LocaleExtensions.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static String toID(SortedMap<Character, Extension> map) {
    StringBuilder buf = new StringBuilder();
    Extension privuse = null;
    for (Entry<Character, Extension> entry : map.entrySet()) {
        char singleton = entry.getKey();
        Extension extension = entry.getValue();
        if (LanguageTag.isPrivateusePrefixChar(singleton)) {
            privuse = extension;
        } else {
            if (buf.length() > 0) {
                buf.append(LanguageTag.SEP);
            }
            buf.append(extension);
        }
    }
    if (privuse != null) {
        if (buf.length() > 0) {
            buf.append(LanguageTag.SEP);
        }
        buf.append(privuse);
    }
    return buf.toString();
}
 
Example #12
Source File: TreeSubMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * headMap returns map with keys in requested range
 */
public void testDescendingHeadMapContents() {
    NavigableMap map = dmap5();
    SortedMap sm = map.headMap(m4);
    assertTrue(sm.containsKey(m1));
    assertTrue(sm.containsKey(m2));
    assertTrue(sm.containsKey(m3));
    assertFalse(sm.containsKey(m4));
    assertFalse(sm.containsKey(m5));
    Iterator i = sm.keySet().iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(m1, k);
    k = (Integer)(i.next());
    assertEquals(m2, k);
    k = (Integer)(i.next());
    assertEquals(m3, k);
    assertFalse(i.hasNext());
    sm.clear();
    assertTrue(sm.isEmpty());
    assertEquals(2, map.size());
    assertEquals(m4, map.firstKey());
}
 
Example #13
Source File: AbstractPlacemarkDataController.java    From collect-earth with MIT License 6 votes vote down vote up
/**
 * Sort parameters based on schema order (BFS)
 * @param parameters Parameters to be sorted
 * @return The parameters sorted alphabetically
 */
public Map<String, String> sortParameters(Map<String, String> parameters) {
	NavigableMap<String, String> navigableParameters = new TreeMap<String, String>(parameters);
	//extract parameter names in order
	BalloonInputFieldsUtils collectParametersHandler = new BalloonInputFieldsUtils();
	Map<String, String> sortedParameterNameByNodePath = collectParametersHandler.getHtmlParameterNameByNodePath(earthSurveyService.getRootEntityDefinition());
	List<String> sortedParameterNames = new ArrayList<String>(sortedParameterNameByNodePath.values());
	
	//create a new map and put the parameters in order there
	Map<String, String> result = new LinkedHashMap<String, String>(navigableParameters.size());
	for (String parameterName : sortedParameterNames) {
		//get all the entries with key starting with parameterName
		SortedMap<String,String> subMap = new TreeMap<String, String>( navigableParameters.subMap(parameterName, parameterName + Character.MAX_VALUE) );
		Set<Entry<String,String>> entrySet = subMap.entrySet();
		for (Entry<String, String> entry : entrySet) {
				result.put(entry.getKey(), entry.getValue());
				navigableParameters.remove(entry.getKey());
		}
	}
	//add remaining parameters (if any)
	result.putAll(navigableParameters);
	return result;
}
 
Example #14
Source File: FrequentSequenceMiner.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
/** Convert frequent sequences to sorted Map<Sequence, Integer> */
public static SortedMap<Sequence, Integer> toMap(final SequentialPatterns patterns) {
	if (patterns == null) {
		return null;
	} else {
		final HashMap<Sequence, Integer> sequences = new HashMap<>();
		for (final List<SequentialPattern> level : patterns.levels) {
			for (final SequentialPattern pattern : level) {
				final Sequence seq = new Sequence();
				for (final Itemset set : pattern.getItemsets())
					seq.add(set.get(0)); // Assumes a seq is just singleton
											// itemsets
				sequences.put(seq, pattern.getAbsoluteSupport());
			}
		}
		// Sort patterns by support
		final Ordering<Sequence> comparator = Ordering.natural().reverse().onResultOf(Functions.forMap(sequences))
				.compound(Ordering.usingToString());
		return ImmutableSortedMap.copyOf(sequences, comparator);
	}
}
 
Example #15
Source File: LegacyTransformerDebug.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Returns a sorted list of all transformers sorted by name.
 * @param transformerName to restrict the collection to one entry
 * @return a new Collection of sorted transformers
 * @throws IllegalArgumentException if transformerName is not found.
 * @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
 */
@Deprecated
public Collection<ContentTransformer> sortTransformersByName(String transformerName)
{
    Collection<ContentTransformer> transformers = (transformerName != null)
            ? Collections.singleton(transformerRegistry.getTransformer(transformerName))
            : transformerRegistry.getAllTransformers();

    SortedMap<String, ContentTransformer> map = new TreeMap<String, ContentTransformer>();
    for (ContentTransformer transformer: transformers)
    {
        String name = transformer.getName();
        map.put(name, transformer);
    }
    Collection<ContentTransformer> sorted = map.values();
    return sorted;
}
 
Example #16
Source File: BgpFilterInactiveTest.java    From batfish with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoAdvertiseInactive() throws IOException {
  Batfish batfish =
      BatfishTestUtils.getBatfishFromTestrigText(
          TestrigText.builder()
              .setConfigurationFiles(
                  SNAPSHOT_PATH, AS1_NAME, AS2_NO_ADVERTISE_INACTIVE_NAME, AS3_NAME)
              .build(),
          _folder);
  batfish.computeDataPlane(batfish.getSnapshot());
  IncrementalDataPlane dataplane =
      (IncrementalDataPlane) batfish.loadDataPlane(batfish.getSnapshot());
  SortedMap<String, SortedMap<String, Set<AbstractRoute>>> routes =
      IncrementalBdpEngine.getRoutes(dataplane);

  assertRoute(routes, RoutingProtocol.STATIC, AS1_NAME, Prefix.ZERO, 0, STATIC_NEXT_HOP);
  assertRoute(
      routes,
      RoutingProtocol.STATIC,
      AS2_NO_ADVERTISE_INACTIVE_NAME,
      Prefix.ZERO,
      0,
      STATIC_NEXT_HOP);
  assertNoRoute(routes, AS3_NAME, Prefix.ZERO);
}
 
Example #17
Source File: Message.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * construct a full wire message including data and annotations payloads.
 */
public Message(int msgType, byte[] databytes, int serializer_id, int flags, int seq, SortedMap<String, byte[]> annotations, byte[] hmac)
{
	this(msgType, serializer_id, flags, seq);
	this.data = databytes;
	this.data_size = databytes.length;
	this.annotations = annotations;
	if(null==annotations)
		this.annotations = new TreeMap<String, byte[]>();
	
	if(hmac!=null)
		this.annotations.put("HMAC", this.hmac(hmac));		// do this last because it hmacs the other annotation chunks
	
	this.annotations_size = 0;
	for(Entry<String, byte[]> a: this.annotations.entrySet())
		this.annotations_size += a.getValue().length+6;
}
 
Example #18
Source File: AbstractQueryCommand.java    From buck with Apache License 2.0 5 votes vote down vote up
private SortedMap<String, Object> resolveAllUnconfiguredAttributesForTarget(
    CommandRunnerParams params, BuckQueryEnvironment env, QueryBuildTarget target)
    throws QueryException {
  Map<String, Object> attributes = getAllUnconfiguredAttributesForTarget(params, env, target);
  PatternsMatcher patternsMatcher = new PatternsMatcher(outputAttributes());

  SortedMap<String, Object> convertedAttributes = new TreeMap<>();
  if (!patternsMatcher.isMatchesNone()) {
    for (Map.Entry<String, Object> attribute : attributes.entrySet()) {
      String attributeName = attribute.getKey();
      String snakeCaseKey = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, attributeName);
      if (!patternsMatcher.matches(snakeCaseKey)) {
        continue;
      }

      Object jsonObject = attribute.getValue();
      if (!(jsonObject instanceof ListWithSelects)) {
        convertedAttributes.put(snakeCaseKey, jsonObject);
        continue;
      }

      convertedAttributes.put(
          snakeCaseKey, resolveUnconfiguredAttribute((ListWithSelects) jsonObject));
    }
  }

  if (patternsMatcher.matches(InternalTargetAttributeNames.DIRECT_DEPENDENCIES)) {
    convertedAttributes.put(
        InternalTargetAttributeNames.DIRECT_DEPENDENCIES,
        env.getNode(target).getParseDeps().stream()
            .map(Object::toString)
            .collect(ImmutableList.toImmutableList()));
  }

  return convertedAttributes;
}
 
Example #19
Source File: SymbolicPolynomial.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
/**
 * GenPolynomial subtraction.
 * 
 * @param S
 *            GenPolynomial.
 * @return this-S.
 */
@Override
public SymbolicPolynomial subtract(SymbolicPolynomial S) {
	if (S == null) {
		return this;
	}
	if (S.isZERO()) {
		return this;
	}
	if (this.isZERO()) {
		return S.negate();
	}
	assert (ring.nvar == S.ring.nvar);
	SymbolicPolynomial n = this.copy(); // new GenPolynomial(ring, val);
	SortedMap<ExpVectorSymbolic, IExpr> nv = n.val;
	SortedMap<ExpVectorSymbolic, IExpr> sv = S.val;
	for (Map.Entry<ExpVectorSymbolic, IExpr> me : sv.entrySet()) {
		ExpVectorSymbolic e = me.getKey();
		IExpr y = me.getValue(); // sv.get(e); // assert y != null
		IExpr x = nv.get(e);
		if (x != null) {
			x = x.subtract(y);
			if (!x.isZERO()) {
				nv.put(e, x);
			} else {
				nv.remove(e);
			}
		} else {
			nv.put(e, y.negate());
		}
	}
	return n;
}
 
Example #20
Source File: IndexerMetricsUtil.java    From hbase-indexer with Apache License 2.0 5 votes vote down vote up
public static void shutdownMetrics(String indexerName) {
    SortedMap<String, SortedMap<MetricName, Metric>> groupedMetrics = Metrics.defaultRegistry().groupedMetrics(
            new IndexerMetricPredicate(indexerName));
    for (SortedMap<MetricName, Metric> metricMap : groupedMetrics.values()) {
        for (MetricName metricName : metricMap.keySet()) {
            Metrics.defaultRegistry().removeMetric(metricName);
        }
    }
}
 
Example #21
Source File: TreeSubMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * subMap returns map with keys in requested range
 */
public void testSubMapContents() {
    NavigableMap map = map5();
    SortedMap sm = map.subMap(two, four);
    assertEquals(two, sm.firstKey());
    assertEquals(three, sm.lastKey());
    assertEquals(2, sm.size());
    assertFalse(sm.containsKey(one));
    assertTrue(sm.containsKey(two));
    assertTrue(sm.containsKey(three));
    assertFalse(sm.containsKey(four));
    assertFalse(sm.containsKey(five));
    Iterator i = sm.keySet().iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(two, k);
    k = (Integer)(i.next());
    assertEquals(three, k);
    assertFalse(i.hasNext());
    Iterator j = sm.keySet().iterator();
    j.next();
    j.remove();
    assertFalse(map.containsKey(two));
    assertEquals(4, map.size());
    assertEquals(1, sm.size());
    assertEquals(three, sm.firstKey());
    assertEquals(three, sm.lastKey());
    assertEquals("C", sm.remove(three));
    assertTrue(sm.isEmpty());
    assertEquals(3, map.size());
}
 
Example #22
Source File: WorkerFilesHash.java    From bazel with Apache License 2.0 5 votes vote down vote up
static HashCode getCombinedHash(SortedMap<PathFragment, HashCode> workerFilesMap) {
  Hasher hasher = Hashing.sha256().newHasher();
  for (Map.Entry<PathFragment, HashCode> workerFile : workerFilesMap.entrySet()) {
    hasher.putString(workerFile.getKey().getPathString(), Charset.defaultCharset());
    hasher.putBytes(workerFile.getValue().asBytes());
  }
  return hasher.hash();
}
 
Example #23
Source File: SubQueryDecorrelator.java    From flink with Apache License 2.0 5 votes vote down vote up
/** Creates a CorelMap with given contents. */
public static CorelMap of(
		com.google.common.collect.SortedSetMultimap<RelNode, CorRef> mapRefRelToCorVar,
		SortedMap<CorrelationId, RelNode> mapCorToCorRel,
		Map<RelNode, Set<CorrelationId>> mapSubQueryNodeToCorSet) {
	return new CorelMap(mapRefRelToCorVar, mapCorToCorRel, mapSubQueryNodeToCorSet);
}
 
Example #24
Source File: Sharded.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
public S getShardInfo(byte[] key) {
  SortedMap<Long, S> tail = nodes.tailMap(algo.hash(key));
  if (tail.isEmpty()) {
    return nodes.get(nodes.firstKey());
  }
  return tail.get(tail.firstKey());
}
 
Example #25
Source File: SimpleSeekableFormat.java    From RDFS with Apache License 2.0 5 votes vote down vote up
@Override
public void readMetaData(InputStream in, int metaDataBlockSize)
    throws IOException {

  // Read in the whole MetaDataBlock and store it in a DataInputStream.
  byte[] metaDataBlock = new byte[metaDataBlockSize];
  (new DataInputStream(in)).readFully(metaDataBlock);
  DataInputStream din = new DataInputStream(new ByteArrayInputStream(metaDataBlock));

  // verify magic header
  byte[] magicHeaderBytes = new byte[MAGIC_HEADER_BYTES.length];
  din.readFully(magicHeaderBytes);
  if (!Arrays.equals(magicHeaderBytes, MAGIC_HEADER_BYTES)) {
    throw new IOException("Wrong Magic Header Bytes");
  }

  // verify version
  int version = din.readInt();
  if (version > VERSION) {
    throw new IOException("Unknown version " + version);
  }

  switch (version) {
    case 1: {
      // one pair of offsets
      long uncompressedOffset = din.readLong();
      long compressedOffset = din.readLong();
      SortedMap<Long, Long> offsetPairs = new TreeMap<Long, Long>();
      offsetPairs.put(uncompressedOffset, compressedOffset);
      metaData.setOffsetPairs(offsetPairs);
      // the rest is thrown away
    }
  }
}
 
Example #26
Source File: TestAgendaItemsUpNext.java    From white-label-event-app with Apache License 2.0 5 votes vote down vote up
@Test
public void testOneGroupOfTwoInRange() {
    // 12 AM - 1 AM
    long start_time0_ms = new DateTime(2000, 1, 1, 0, 0, 0, 0, DTZ).getMillis();
    long start_time0_s = TimeUnit.MILLISECONDS.toSeconds(start_time0_ms);
    long end_time0_ms = start_time0_ms + TimeUnit.HOURS.toMillis(1);
    long end_time0_s = TimeUnit.MILLISECONDS.toSeconds(end_time0_ms);
    AgendaItem item0 = new AgendaItem();
    item0.setEpochStartTime(start_time0_s);
    item0.setEpochEndTime(end_time0_s);

    // 12 AM - 1 AM
    AgendaItem item1 = new AgendaItem();
    item1.setEpochStartTime(start_time0_s);
    item1.setEpochEndTime(end_time0_s);

    long look_ahead = TimeUnit.DAYS.toMillis(1);
    long now = start_time0_ms - look_ahead + 1;  // Just inside of range
    final List<AgendaItem> items_in = Arrays.asList(item0, item1);
    final SortedMap<DateRange, List<AgendaItem>> map =
        AgendaItems.upNext(items_in, now, TimeUnit.DAYS.toMillis(1), 0);

    assertEquals(1, map.size());
    final DateRange dr = map.firstKey();
    assertNotNull(dr);
    assertEquals(start_time0_ms, dr.start);
    assertEquals(end_time0_ms, dr.end);
    final List<AgendaItem> items_out = map.get(dr);
    assertEquals(2, items_out.size());
    assertSame(item0, items_out.get(0));
    assertSame(item1, items_out.get(1));
}
 
Example #27
Source File: HyperLogLogPlusTable.java    From kylin with Apache License 2.0 5 votes vote down vote up
public static double biasCorrection(int precision, double estimate) {
    double[] estimateVector = rawEstimateData[precision - 4];
    SortedMap<Double, Integer> estimateDistances = calcDistances(estimate, estimateVector);
    int[] nearestNeighbors = getNearestNeighbors(estimateDistances);
    double bias = getBias(precision, nearestNeighbors);
    return estimate - bias;
}
 
Example #28
Source File: DirectoryAnalyser.java    From alfresco-bulk-import with Apache License 2.0 5 votes vote down vote up
private Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> constructImportItems(final String                                             sourceRelativeParentDirectory,
                                                                                                  final Map<String, SortedMap<BigDecimal,Pair<File,File>>> categorisedFiles)
    throws InterruptedException
{
    Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> result = null;
    
    if (categorisedFiles != null)
    {
        final List<FilesystemBulkImportItem> directoryItems = new ArrayList<>();
        final List<FilesystemBulkImportItem> fileItems      = new ArrayList<>();
        
        result = new Pair<>(directoryItems, fileItems);
        
        for (final String parentName : categorisedFiles.keySet())
        {
            if (importStatus.isStopping() || Thread.currentThread().isInterrupted()) throw new InterruptedException(Thread.currentThread().getName() + " was interrupted. Terminating early.");
            
            final SortedMap<BigDecimal,Pair<File,File>>         itemVersions = categorisedFiles.get(parentName);
            final NavigableSet<FilesystemBulkImportItemVersion> versions     = constructImportItemVersions(itemVersions);
            final boolean                                       isDirectory  = versions.last().isDirectory();
            final FilesystemBulkImportItem                      item         = new FilesystemBulkImportItem(parentName,
                                                                                                            isDirectory,
                                                                                                            sourceRelativeParentDirectory,
                                                                                                            versions);
            
            if (isDirectory)
            {
                directoryItems.add(item);
            }
            else
            {
                fileItems.add(item);
            }
        }
    }
    
    return(result);
}
 
Example #29
Source File: StatisticsChart.java    From ade with GNU General Public License v3.0 5 votes vote down vote up
/** @return a map with all statistics sorted by name.
 * Double values are converted to strings using String.valueOf()
 */
public SortedMap<String, String> getAllStatisticsSorted() {
    final SortedMap<String, String> res = new TreeMap<String, String>();

    if (m_stringStats != null) {
        res.putAll(m_stringStats);
    }
    if (m_doubleStats != null) {
        for (Map.Entry<String, Double> val : m_doubleStats.entrySet()) {
            res.put(val.getKey(), String.valueOf(val.getValue()));
        }
    }
    return res;
}
 
Example #30
Source File: EnvHelp.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
public static <V> Map<String, V> filterAttributes(Map<String, V> attributes) {
    if (logger.traceOn()) {
        logger.trace("filterAttributes", "starts");
    }

    SortedMap<String, V> map = new TreeMap<String, V>(attributes);
    purgeUnserializable(map.values());
    hideAttributes(map);
    return map;
}