com.google.common.collect.HashBasedTable Java Examples

The following examples show how to use com.google.common.collect.HashBasedTable. 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: DeviceManager.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the known {@link Device} list.
 *
 * @param deviceFilter A combination of the {@link DeviceFilter} constants
 *                     or the constant {@link DeviceManager#ALL_DEVICES}.
 * @return A copy of the list of {@link Device}s. Can be empty but not null.
 */
@NonNull
public Collection<Device> getDevices(@NonNull EnumSet<DeviceFilter> deviceFilter) {
    initDevicesLists();
    Table<String, String, Device> devices = HashBasedTable.create();
    if (mUserDevices != null && (deviceFilter.contains(DeviceFilter.USER))) {
        devices.putAll(mUserDevices);
    }
    if (mDefaultDevices != null && (deviceFilter.contains(DeviceFilter.DEFAULT))) {
        devices.putAll(mDefaultDevices);
    }
    if (mVendorDevices != null && (deviceFilter.contains(DeviceFilter.VENDOR))) {
        devices.putAll(mVendorDevices);
    }
    if (mSysImgDevices != null && (deviceFilter.contains(DeviceFilter.SYSTEM_IMAGES))) {
        devices.putAll(mSysImgDevices);
    }
    return Collections.unmodifiableCollection(devices.values());
}
 
Example #2
Source File: DiceRoll.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Sorts the specified collection of units in ascending order of their attack or defense strength.
 *
 * @param defending {@code true} if the units should be sorted by their defense strength;
 *     otherwise the units will be sorted by their attack strength.
 */
public static void sortByStrength(final List<Unit> units, final boolean defending) {
  // Pre-compute unit strength information to speed up the sort.
  final Table<UnitType, GamePlayer, Integer> strengthTable = HashBasedTable.create();
  for (final Unit unit : units) {
    final UnitType type = unit.getType();
    final GamePlayer owner = unit.getOwner();
    if (!strengthTable.contains(type, owner)) {
      if (defending) {
        strengthTable.put(type, owner, UnitAttachment.get(type).getDefense(owner));
      } else {
        strengthTable.put(type, owner, UnitAttachment.get(type).getAttack(owner));
      }
    }
  }
  final Comparator<Unit> comp =
      (u1, u2) -> {
        final int v1 = strengthTable.get(u1.getType(), u1.getOwner());
        final int v2 = strengthTable.get(u2.getType(), u2.getOwner());
        return Integer.compare(v1, v2);
      };
  units.sort(comp);
}
 
Example #3
Source File: CVPredictLoader.java    From bioasq with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
  super.initialize(context);
  String candidateProviderName = UimaContextHelper
          .getConfigParameterStringValue(context, "candidate-provider");
  candidateProvider = ProviderCache.getProvider(candidateProviderName, CandidateProvider.class);
  // load cv
  String cvPredictFile = UimaContextHelper.getConfigParameterStringValue(context,
          "cv-predict-file");
  List<String> lines;
  try {
    lines = Resources.readLines(getClass().getResource(cvPredictFile), Charsets.UTF_8);
  } catch (IOException e) {
    throw new ResourceInitializationException(e);
  }
  qid2uri2score = HashBasedTable.create();
  lines.stream().map(line -> line.split("\t"))
          .forEach(segs -> qid2uri2score.put(segs[0], segs[1], Double.parseDouble(segs[2])));
}
 
Example #4
Source File: DAbstractMetricIO.java    From blueflood with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch values for a list of {@link com.rackspacecloud.blueflood.types.Locator}
 * from the specified column family and range.
 *
 * This is a base behavior for most rollup types. IO subclasses can override
 * this behavior as they see fit.
 *
 * @param locators
 * @param columnFamily
 * @param range
 * @return
 */
protected <T extends Object> Table<Locator, Long, T> getValuesForLocators( final List<Locator> locators,
                                                                           String columnFamily,
                                                                           Range range ) {

    Table<Locator, Long, T> locatorTimestampRollup = HashBasedTable.create();

    Map<Locator, List<ResultSetFuture>> resultSetFuturesMap = selectForLocatorListAndRange(columnFamily, locators, range);

    for (Map.Entry<Locator, List<ResultSetFuture>> entry : resultSetFuturesMap.entrySet() ) {
        Locator locator = entry.getKey();
        List<ResultSetFuture> futures = entry.getValue();

        Table<Locator, Long, T> result = toLocatorTimestampValue(futures, locator,
                                                columnFamily,
                                                range);
        locatorTimestampRollup.putAll(result);
    }
    return locatorTimestampRollup;
}
 
Example #5
Source File: ChunkLoader.java    From factions-top with MIT License 6 votes vote down vote up
private Table<Integer, WorthType, Double> loadChunkWorth() throws SQLException {
    Table<Integer, WorthType, Double> target = HashBasedTable.create();
    ResultSet resultSet = selectChunkWorth.executeQuery();

    while (resultSet.next()) {
        int id = resultSet.getInt("id");
        int chunkId = resultSet.getInt("chunk_id");
        int worthId = resultSet.getInt("worth_id");
        double worth = resultSet.getDouble("worth");

        identityCache.setChunkWorthId(chunkId, worthId, id);
        identityCache.getWorthType(worthId).ifPresent(worthType ->
                target.put(chunkId, worthType, worth));
    }

    resultSet.close();
    return target;
}
 
Example #6
Source File: RunningContainers.java    From twill with Apache License 2.0 6 votes vote down vote up
RunningContainers(TwillRuntimeSpecification twillRuntimeSpec, String appId, TwillRunResources appMasterResources,
                  ZKClient zookeeperClient, Location applicationLocation,
                  Map<String, RuntimeSpecification> runnables,
                  EventHandler eventHandler) {
  containers = HashBasedTable.create();
  runnableInstances = Maps.newHashMap();
  completedContainerCount = Maps.newHashMap();
  startSequence = Lists.newLinkedList();
  containerLock = new ReentrantLock();
  containerChange = containerLock.newCondition();
  resourceReport = new DefaultResourceReport(appId, appMasterResources);
  zkClient = zookeeperClient;
  containerStats = HashMultimap.create();
  this.applicationLocation = applicationLocation;
  this.runnableNames = runnables.keySet();
  this.logLevels = new TreeMap<>();
  this.maxRetries = Maps.newHashMap(twillRuntimeSpec.getMaxRetries());
  this.numRetries = Maps.newHashMap();
  this.eventHandler = eventHandler;
}
 
Example #7
Source File: YarnTwillRunnerService.java    From twill with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance.
 *
 * @param config Configuration of the yarn cluster
 * @param zkConnect ZooKeeper connection string
 * @param locationFactory Factory to create {@link Location} instances that are readable and writable by this service
 */
public YarnTwillRunnerService(YarnConfiguration config, String zkConnect, LocationFactory locationFactory) {
  this.yarnConfig = config;
  this.locationFactory = locationFactory;
  this.zkClientService = getZKClientService(zkConnect);
  this.controllers = HashBasedTable.create();
  this.serviceDelegate = new AbstractIdleService() {
    @Override
    protected void startUp() throws Exception {
      YarnTwillRunnerService.this.startUp();
    }

    @Override
    protected void shutDown() throws Exception {
      YarnTwillRunnerService.this.shutDown();
    }
  };
}
 
Example #8
Source File: FetchIndexRequestHandler.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public Command handle(Transport transport, Command command) {
    FetchIndexRequest fetchIndexRequest = (FetchIndexRequest) command.getPayload();
    Connection connection = SessionHelper.getConnection(transport);

    if (connection == null || !connection.isAuthorized(fetchIndexRequest.getApp())) {
        logger.warn("connection is not exists, transport: {}, app: {}", transport, fetchIndexRequest.getApp());
        return BooleanAck.build(JoyQueueCode.FW_CONNECTION_NOT_EXISTS.getCode());
    }

    Table<String, Short, FetchIndexData> result = HashBasedTable.create();

    for (Map.Entry<String, List<Short>> entry : fetchIndexRequest.getPartitions().entrySet()) {
        String topic = entry.getKey();
        Consumer consumer = new Consumer(connection.getId(), topic, fetchIndexRequest.getApp(), Consumer.ConsumeType.JOYQUEUE);
        for (Short partition : entry.getValue()) {
            FetchIndexData fetchIndexData = fetchIndex(connection, consumer, partition);
            result.put(topic, partition, fetchIndexData);
        }
    }

    FetchIndexResponse fetchIndexResponse = new FetchIndexResponse();
    fetchIndexResponse.setData(result);
    return new Command(fetchIndexResponse);
}
 
Example #9
Source File: CommitAckRequestHandler.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public Command handle(Transport transport, Command command) {
    CommitAckRequest commitAckRequest = (CommitAckRequest) command.getPayload();
    Connection connection = SessionHelper.getConnection(transport);

    if (connection == null || !connection.isAuthorized(commitAckRequest.getApp())) {
        logger.warn("connection is not exists, transport: {}, app: {}", transport, commitAckRequest.getApp());
        return BooleanAck.build(JoyQueueCode.FW_CONNECTION_NOT_EXISTS.getCode());
    }

    Table<String, Short, JoyQueueCode> result = HashBasedTable.create();

    for (Map.Entry<String, Map<Short, List<CommitAckData>>> entry : commitAckRequest.getData().rowMap().entrySet()) {
        String topic = entry.getKey();
        for (Map.Entry<Short, List<CommitAckData>> partitionEntry : entry.getValue().entrySet()) {
            JoyQueueCode ackCode = commitAck(connection, topic, commitAckRequest.getApp(), partitionEntry.getKey(), partitionEntry.getValue());
            result.put(topic, partitionEntry.getKey(), ackCode);
        }
    }

    CommitAckResponse commitAckResponse = new CommitAckResponse();
    commitAckResponse.setResult(result);
    return new Command(commitAckResponse);
}
 
Example #10
Source File: FetchPartitionMessageRequestCodec.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public FetchPartitionMessageRequest decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    Table<String, Short, FetchPartitionMessageData> partitions = HashBasedTable.create();
    int topicSize = buffer.readShort();
    for (int i = 0; i < topicSize; i++) {
        String topic = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        int partitionSize = buffer.readShort();
        for (int j = 0; j < partitionSize; j++) {
            short partition = buffer.readShort();
            int count = buffer.readInt();
            long index = buffer.readLong();

            partitions.put(topic, partition, new FetchPartitionMessageData(count, index));
        }
    }

    FetchPartitionMessageRequest fetchPartitionMessageRequest = new FetchPartitionMessageRequest();
    fetchPartitionMessageRequest.setPartitions(partitions);
    fetchPartitionMessageRequest.setApp(Serializer.readString(buffer, Serializer.SHORT_SIZE));
    return fetchPartitionMessageRequest;
}
 
Example #11
Source File: DefaultMessageFetcher.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public void fetchPartitionAsync(BrokerNode brokerNode, final String topic, final String app, final short partition,
                                final long index, int count, long timeout, final PartitionFetchListener listener) {
    Table<String, Short, Long> partitionTable = HashBasedTable.create();
    partitionTable.put(topic, partition, index);
    batchFetchPartitionsAsync(brokerNode, partitionTable, app, count, timeout, new BatchPartitionFetchListener() {
        @Override
        public void onMessage(Table<String, Short, FetchMessageData> fetchMessageTable) {
            FetchMessageData fetchMessageData = fetchMessageTable.get(topic, partition);
            listener.onMessage(fetchMessageData);
        }

        @Override
        public void onException(Throwable cause) {
            listener.onException(cause);
        }
    });
}
 
Example #12
Source File: ClassifierPredictor.java    From bioasq with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
  super.initialize(context);
  String candidateProviderName = UimaContextHelper
          .getConfigParameterStringValue(context, "candidate-provider");
  candidateProvider = ProviderCache.getProvider(candidateProviderName, CandidateProvider.class);
  String scorerNames = UimaContextHelper.getConfigParameterStringValue(context, "scorers");
  scorers = ProviderCache.getProviders(scorerNames, Scorer.class).stream()
          .map(scorer -> (Scorer<? super T>) scorer).collect(toList());
  String classifierName = UimaContextHelper.getConfigParameterStringValue(context, "classifier");
  classifier = ProviderCache.getProvider(classifierName, ClassifierProvider.class);
  if ((featureFilename = UimaContextHelper.getConfigParameterStringValue(context, "feature-file",
          null)) != null) {
    feat2value = HashBasedTable.create();
  }
}
 
Example #13
Source File: CommitAckResponseCodec.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public CommitAckResponse decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    short size = buffer.readShort();
    Table<String, Short, JoyQueueCode> result = HashBasedTable.create();

    for (int i = 0; i < size; i++) {
        String topic = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        short partitionSize = buffer.readShort();
        for (int j = 0; j < partitionSize; j++) {
            short partition = buffer.readShort();
            result.put(topic, partition, JoyQueueCode.valueOf(buffer.readInt()));
        }
    }

    CommitAckResponse commitAckResponse = new CommitAckResponse();
    commitAckResponse.setResult(result);
    return commitAckResponse;
}
 
Example #14
Source File: FetchPartitionMessageRequestCodec.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public FetchPartitionMessageRequest decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    Table<String, Short, FetchPartitionMessageData> partitions = HashBasedTable.create();
    int topicSize = buffer.readShort();
    for (int i = 0; i < topicSize; i++) {
        String topic = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        int partitionSize = buffer.readShort();
        for (int j = 0; j < partitionSize; j++) {
            short partition = buffer.readShort();
            int count = buffer.readInt();
            long index = buffer.readLong();

            partitions.put(topic, partition, new FetchPartitionMessageData(count, index));
        }
    }

    FetchPartitionMessageRequest fetchPartitionMessageRequest = new FetchPartitionMessageRequest();
    fetchPartitionMessageRequest.setPartitions(partitions);
    fetchPartitionMessageRequest.setApp(Serializer.readString(buffer, Serializer.SHORT_SIZE));
    return fetchPartitionMessageRequest;
}
 
Example #15
Source File: FhirR4.java    From synthea with Apache License 2.0 6 votes vote down vote up
private static Table<String, String, String> loadMapping(String filename) {
  Table<String, String, String> mappingTable = HashBasedTable.create();

  List<LinkedHashMap<String, String>> csvData;
  try {
    csvData = SimpleCSV.parse(Utilities.readResource(filename));
  } catch (IOException e) {
    e.printStackTrace();
    return null;
  }

  for (LinkedHashMap<String, String> line : csvData) {
    String system = line.get("SYSTEM");
    String code = line.get("CODE");
    String url = line.get("URL");

    mappingTable.put(system, code, url);
  }

  return mappingTable;
}
 
Example #16
Source File: MapManager.java    From Rails with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Calculate the distances between a given tokenable city hex
 * and all other tokenable city hexes.
 * <p> Distances are cached.
 * @param initHex Start hex
 * @return Sorted integer list containing all occurring distances only once.
 */
public SortedSet<Integer> getCityDistances (MapHex initHex) {
    
    if (hexDistances == null) {
        hexDistances = HashBasedTable.create();
    }

    if (!hexDistances.containsRow(initHex)) {
        calculateHexDistances(initHex, initHex, 0);
    }
    
    ImmutableSortedSet.Builder<Integer> distances = 
            ImmutableSortedSet.naturalOrder();
    
    for (Entry<MapHex, Integer> otherHex:hexDistances.row(initHex).entrySet()) {
        if (otherHex.getKey().getCurrentTile().hasStations()) {
            distances.add(otherHex.getValue());
        }
    }
    return distances.build();
}
 
Example #17
Source File: ConfigurableFeatureManager.java    From OpenModsLib with MIT License 6 votes vote down vote up
public Table<String, String, Property> loadFromConfiguration(Configuration config) {
	final Table<String, String, Property> properties = HashBasedTable.create();
	for (Table.Cell<String, String, FeatureEntry> cell : features.cellSet()) {
		final FeatureEntry entry = cell.getValue();
		if (!entry.isConfigurable) continue;

		final String categoryName = cell.getRowKey();
		final String featureName = cell.getColumnKey();
		final Property prop = config.get(categoryName, featureName, entry.isEnabled);
		properties.put(categoryName, featureName, prop);
		if (!prop.wasRead()) continue;

		if (!prop.isBooleanValue()) prop.set(entry.isEnabled);
		else entry.isEnabled = prop.getBoolean(entry.isEnabled);
	}

	return ImmutableTable.copyOf(properties);
}
 
Example #18
Source File: AbstractBoomerangResults.java    From SPDS with Eclipse Public License 2.0 6 votes vote down vote up
public Table<Statement, Val, W> asStatementValWeightTable(ForwardQuery query) {
    final Table<Statement, Val, W> results = HashBasedTable.create();
    WeightedPAutomaton<Statement, INode<Val>, W> callAut = queryToSolvers.getOrCreate(query).getCallAutomaton();
    for (Entry<Transition<Statement, INode<Val>>, W> e : callAut.getTransitionsToFinalWeights().entrySet()) {
        Transition<Statement, INode<Val>> t = e.getKey();
        W w = e.getValue();
        if (t.getLabel().equals(Statement.epsilon()))
            continue;
        if (t.getStart().fact().value() instanceof Local
                && !t.getLabel().getMethod().equals(t.getStart().fact().m()))
            continue;
        if (t.getLabel().getUnit().isPresent())
            results.put(t.getLabel(), t.getStart().fact(), w);
    }
    return results;
}
 
Example #19
Source File: ConfigCommand.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static Table<Class<? extends FragmentOptions>, String, Pair<Object, Object>>
    diffConfigurations(BuildConfiguration config1, BuildConfiguration config2) {
  Table<Class<? extends FragmentOptions>, String, Pair<Object, Object>> diffs =
      HashBasedTable.create();

  for (Class<? extends FragmentOptions> fragment :
      Sets.union(
          config1.getOptions().getFragmentClasses(), config2.getOptions().getFragmentClasses())) {
    FragmentOptions options1 = config1.getOptions().get(fragment);
    FragmentOptions options2 = config2.getOptions().get(fragment);
    diffs.row(fragment).putAll(diffOptions(fragment, options1, options2));
  }

  diffs.row(UserDefinedFragment.class).putAll(diffStarlarkOptions(config1, config2));
  return diffs;
}
 
Example #20
Source File: ChartCell.java    From EasySRL with Apache License 2.0 6 votes vote down vote up
public ChartCellNbestFactory(final int nbest, final double nbestBeam, final int maxSentenceLength,
		final Collection<Category> categories) {
	super();
	this.nbest = nbest;
	this.nbestBeam = nbestBeam;
	final Random randomGenerator = new Random();

	// Build a hash for every possible dependency
	categoryToArgumentToHeadToModifierToHash = HashBasedTable.create();
	for (final Category c : categories) {
		for (int i = 1; i <= c.getNumberOfArguments(); i++) {
			final int[][] array = new int[maxSentenceLength][maxSentenceLength];
			categoryToArgumentToHeadToModifierToHash.put(c, i, array);
			for (int head = 0; head < maxSentenceLength; head++) {
				for (int child = 0; child < maxSentenceLength; child++) {
					array[head][child] = randomGenerator.nextInt();
				}
			}
		}
	}
}
 
Example #21
Source File: ImmutableCollectionSerializers.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public static void register(final Kryo kryo) {
  // register list
  final ImmutableListSerializer serializer = new ImmutableListSerializer();
  kryo.register(ImmutableList.class, serializer);
  kryo.register(ImmutableList.of().getClass(), serializer);
  kryo.register(ImmutableList.of(Integer.valueOf(1)).getClass(), serializer);
  kryo.register(ImmutableList.of(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)).subList(1, 2).getClass(), serializer);
  kryo.register(ImmutableList.of().reverse().getClass(), serializer);
  kryo.register(Lists.charactersOf("dremio").getClass(), serializer);

  final HashBasedTable baseTable = HashBasedTable.create();
  baseTable.put(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3));
  baseTable.put(Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6));
  ImmutableTable table = ImmutableTable.copyOf(baseTable);
  kryo.register(table.values().getClass(), serializer);
}
 
Example #22
Source File: CheckpointManager.java    From qmq with Apache License 2.0 6 votes vote down vote up
private ActionCheckpoint duplicateActionCheckpoint() {
    actionCheckpointGuard.lock();
    try {
        final Table<String, String, ConsumerGroupProgress> progresses = HashBasedTable.create();
        for (final ConsumerGroupProgress progress : actionCheckpoint.getProgresses().values()) {
            final Map<String, ConsumerProgress> consumers = progress.getConsumers();
            if (consumers == null) {
                continue;
            }

            final Map<String, ConsumerProgress> consumersCopy = new HashMap<>();
            for (final ConsumerProgress consumer : consumers.values()) {
                consumersCopy.put(consumer.getConsumerId(), new ConsumerProgress(consumer));
            }
            final String subject = progress.getSubject();
            final String group = progress.getGroup();
            progresses.put(subject, group, new ConsumerGroupProgress(subject, group, progress.isBroadcast(), progress.getPull(), consumersCopy));
        }
        final long offset = actionCheckpoint.getOffset();
        return new ActionCheckpoint(offset, progresses);
    } finally {
        actionCheckpointGuard.unlock();
    }
}
 
Example #23
Source File: Demographics.java    From synthea with Apache License 2.0 6 votes vote down vote up
/**
 * Get a Table of (State, CityId, Demographics), with the given restrictions on state and city.
 * 
 * @param state
 *          The state that is desired. Other states will be excluded from the results.
 * @return Table of (State, CityId, Demographics)
 * @throws IOException
 *           if any exception occurs in reading the demographics file
 */
public static Table<String, String, Demographics> load(String state) 
    throws IOException {
  String filename = Config.get("generate.demographics.default_file");
  String csv = Utilities.readResource(filename);
  
  List<? extends Map<String,String>> demographicsCsv = SimpleCSV.parse(csv);
  
  Table<String, String, Demographics> table = HashBasedTable.create();
  
  for (Map<String,String> demographicsLine : demographicsCsv) {
    String currCityId = demographicsLine.get("ID");
    String currState = demographicsLine.get("STNAME");
    
    // for now, only allow one state at a time
    if (state != null && state.equalsIgnoreCase(currState)) {
      Demographics parsed = csvLineToDemographics(demographicsLine);
      
      table.put(currState, currCityId, parsed);
    }
  }
  
  return table;
}
 
Example #24
Source File: GuavaTableUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTable_whenContains_returnsSuccessfully() {
    final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
    universityCourseSeatTable.put("Mumbai", "Chemical", 120);
    universityCourseSeatTable.put("Mumbai", "IT", 60);
    universityCourseSeatTable.put("Harvard", "Electrical", 60);
    universityCourseSeatTable.put("Harvard", "IT", 120);

    final boolean entryIsPresent = universityCourseSeatTable.contains("Mumbai", "IT");
    final boolean entryIsAbsent = universityCourseSeatTable.contains("Oxford", "IT");
    final boolean courseIsPresent = universityCourseSeatTable.containsColumn("IT");
    final boolean universityIsPresent = universityCourseSeatTable.containsRow("Mumbai");
    final boolean seatCountIsPresent = universityCourseSeatTable.containsValue(60);

    assertThat(entryIsPresent).isEqualTo(true);
    assertThat(entryIsAbsent).isEqualTo(false);
    assertThat(courseIsPresent).isEqualTo(true);
    assertThat(universityIsPresent).isEqualTo(true);
    assertThat(seatCountIsPresent).isEqualTo(true);
}
 
Example #25
Source File: FetchPartitionMessageResponseCodec.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public FetchPartitionMessageResponse decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    Table<String, Short, FetchPartitionMessageAckData> data = HashBasedTable.create();
    short topicSize = buffer.readShort();
    for (int i = 0; i < topicSize; i++) {
        String topic = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        int partitionSize = buffer.readShort();
        for (int j = 0; j < partitionSize; j++) {
            short partition = buffer.readShort();
            short messageSize = buffer.readShort();
            List<BrokerMessage> messages = Lists.newArrayListWithCapacity(messageSize);
            for (int k = 0; k < messageSize; k++) {
                messages.add(Serializer.readBrokerMessage(buffer));
            }
            JoyQueueCode code = JoyQueueCode.valueOf(buffer.readInt());
            FetchPartitionMessageAckData fetchPartitionMessageAckData = new FetchPartitionMessageAckData(messages, code);
            data.put(topic, partition, fetchPartitionMessageAckData);
        }
    }

    FetchPartitionMessageResponse fetchPartitionMessageResponse = new FetchPartitionMessageResponse();
    fetchPartitionMessageResponse.setData(data);
    return fetchPartitionMessageResponse;
}
 
Example #26
Source File: SaltStates.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public static Map<String, Map<String, String>> getPackageVersions(SaltConnector sc, Map<String, Optional<String>> packages) {
    if (packages.keySet().size() == 1) {
        Entry<String, Optional<String>> next = packages.entrySet().iterator().next();
        return getSinglePackageVersion(sc, next.getKey(), next.getValue());
    } else if (packages.keySet().size() > 1) {
        // Table<host, packageName, version>
        Table<String, String, String> packageTable = HashBasedTable.create();
        packages.entrySet().forEach(singlePackage -> {
            Map<String, Map<String, String>> singlePackageVersionByHost = getSinglePackageVersion(sc, singlePackage.getKey(), singlePackage.getValue());
            singlePackageVersionByHost.entrySet()
                    .stream()
                    .forEach(singlePackageVersionByHostEntry -> singlePackageVersionByHostEntry.getValue().entrySet()
                            .stream()
                            .forEach(singlePackageVersion -> packageTable.put(singlePackageVersionByHostEntry.getKey(),
                                    singlePackageVersion.getKey(), singlePackageVersion.getValue())));
        });
        return packageTable.rowMap();
    } else {
        return Collections.emptyMap();
    }
}
 
Example #27
Source File: FlatFile.java    From CardinalPGM with MIT License 5 votes vote down vote up
@Override
public Table getTable(String name) {
    if (tables.get(name) != null) return tables.get(name);
    else {
        Table toReturn = HashBasedTable.create();
        tables.put(name, toReturn);
        return toReturn;
    }
}
 
Example #28
Source File: GuavaTableUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenTable_whenGet_returnsSuccessfully() {
    final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
    universityCourseSeatTable.put("Mumbai", "Chemical", 120);
    universityCourseSeatTable.put("Mumbai", "IT", 60);
    universityCourseSeatTable.put("Harvard", "Electrical", 60);
    universityCourseSeatTable.put("Harvard", "IT", 120);

    final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");
    final Integer seatCountForNoEntry = universityCourseSeatTable.get("Oxford", "IT");

    assertThat(seatCount).isEqualTo(60);
    assertThat(seatCountForNoEntry).isEqualTo(null);
}
 
Example #29
Source File: SymbolWriter.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private Table<String, String, SymbolEntry> getAllSymbols() {
    Table<String, String, SymbolEntry> symbols = HashBasedTable.create();

    for (SymbolLoader symbolLoader : mSymbols) {
        symbols.putAll(symbolLoader.getSymbols());
    }

    return symbols;
}
 
Example #30
Source File: XmlTimeGraphDataProvider.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public @NonNull TmfModelResponse<@NonNull TimeGraphModel> fetchRowModel(@NonNull Map<@NonNull String, @NonNull Object> fetchParameters, @Nullable IProgressMonitor monitor) {
    Table<ITmfStateSystem, Integer, Long> table = HashBasedTable.create();

    // TODO server: Parameters validation should be handle separately. It
    // can be either in the data provider itself or before calling it. It
    // will avoid the creation of filters and the content of the map can be
    // use directly.
    SelectionTimeQueryFilter filter = FetchParametersUtils.createSelectionTimeQuery(fetchParameters);
    if (filter == null) {
        return new TmfModelResponse<>(null, ITmfResponse.Status.FAILED, CommonStatusMessage.INCORRECT_QUERY_PARAMETERS);
    }
    for (Long id : filter.getSelectedItems()) {
        Pair<ITmfStateSystem, Integer> pair = fIDToDisplayQuark.get(id);
        if (pair != null) {
            table.put(pair.getFirst(), pair.getSecond(), id);
        }
    }
    List<@NonNull ITimeGraphRowModel> allRows = new ArrayList<>();
    try {
        for (Entry<ITmfStateSystem, Map<Integer, Long>> ssEntry : table.rowMap().entrySet()) {
            Collection<@NonNull ITimeGraphRowModel> rows = createRows(ssEntry.getKey(), ssEntry.getValue(), filter.getTimesRequested(), fetchParameters, monitor);
            allRows.addAll(rows);
        }
    } catch (IndexOutOfBoundsException | TimeRangeException | StateSystemDisposedException e) {
        return new TmfModelResponse<>(null, Status.FAILED, CommonStatusMessage.STATE_SYSTEM_FAILED);
    }
    return new TmfModelResponse<>(new TimeGraphModel(allRows), Status.COMPLETED, CommonStatusMessage.COMPLETED);
}