Java Code Examples for com.google.common.collect.Iterables#indexOf()

The following examples show how to use com.google.common.collect.Iterables#indexOf() . 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: BuildPaths.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Removes the hash from the buck-out path. Used temporarily to create links.
 *
 * @param path Hashed buck-out path
 * @param target Build target that generated {@code path}
 * @return A path without the hash directory or {@code Optional.empty()} if the hash was not
 *     found.
 */
// TODO(gabrielrc): Remove this once we removed all hardcoded buck paths.
public static Optional<Path> removeHashFrom(Path path, BuildTarget target) {
  String hash = TargetConfigurationHasher.hash(target.getTargetConfiguration());
  int index = Iterables.indexOf(path, p -> p.endsWith(hash));
  if (index == -1) { // hash not found
    return Optional.empty();
  }
  Path pathWithoutHash =
      path.subpath(0, index).resolve(path.subpath(index + 1, path.getNameCount()));
  if (path.isAbsolute()) {
    // Path.subpath(0, n) doesn't include the root
    return Optional.of(path.getRoot().resolve(pathWithoutHash));
  }
  return Optional.of(pathWithoutHash);
}
 
Example 2
Source File: DatePartitionHiveVersionFinder.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Create a {@link TimestampedHiveDatasetVersion} from a {@link Partition}. The hive table is expected
 * to be date partitioned by {@link #partitionKeyName}. The partition value format must be {@link #pattern}
 *
 * @throws IllegalArgumentException when {@link #partitionKeyName} is not found in the <code></code>
 * @throws IllegalArgumentException when a value can not be found for {@link #partitionKeyName} in the <code>partition</code>
 * @throws IllegalArgumentException if the partition value can not be parsed with {@link #pattern}
 * {@inheritDoc}
 */
@Override
protected TimestampedHiveDatasetVersion getDatasetVersion(Partition partition) {

  int index = Iterables.indexOf(partition.getTable().getPartitionKeys(), this.partitionKeyNamePredicate);

  if (index == -1) {
    throw new IllegalArgumentException(String
        .format("Failed to find partition key %s in the table %s", this.partitionKeyName,
            partition.getTable().getCompleteName()));
  }

  if (index >= partition.getValues().size()) {
    throw new IllegalArgumentException(String
        .format("Failed to find partition value for key %s in the partition %s", this.partitionKeyName,
            partition.getName()));
  }
  return new TimestampedHiveDatasetVersion(
      this.formatter.parseDateTime(partition.getValues().get(index).trim().substring(0, this.pattern.length())),
      partition);
}
 
Example 3
Source File: FjTypeSystem.java    From xsemantics with Eclipse Public License 1.0 5 votes vote down vote up
protected Result<Expression> applyRuleRNew(final RuleEnvironment G, final RuleApplicationTrace _trace_, final New exp) throws RuleFailedException {
  New exp1 = null; // output parameter
  exp1 = this.<New>clone(exp);
  final Predicate<Expression> _function = new Predicate<Expression>() {
    public boolean apply(final Expression it) {
      Boolean _isValue = FjTypeSystem.this.isValueInternal(_trace_, it);
      return (!(_isValue).booleanValue());
    }
  };
  final int indexOfNextToReduce = Iterables.<Expression>indexOf(exp1.getArgs(), _function);
  /* { indexOfNextToReduce < 0 } or { val nextToReduce = exp1.args.get(indexOfNextToReduce) G |- nextToReduce ~> var Expression expi exp1.args.set(indexOfNextToReduce, expi) } */
  {
    RuleFailedException previousFailure = null;
    try {
      /* indexOfNextToReduce < 0 */
      if (!(indexOfNextToReduce < 0)) {
        sneakyThrowRuleFailedException("indexOfNextToReduce < 0");
      }
    } catch (Exception e) {
      previousFailure = extractRuleFailedException(e);
      final Expression nextToReduce = exp1.getArgs().get(indexOfNextToReduce);
      /* G |- nextToReduce ~> var Expression expi */
      Expression expi = null;
      Result<Expression> result = reduceInternal(G, _trace_, nextToReduce);
      checkAssignableTo(result.getFirst(), Expression.class);
      expi = (Expression) result.getFirst();
      
      exp1.getArgs().set(indexOfNextToReduce, expi);
    }
  }
  return new Result<Expression>(exp1);
}
 
Example 4
Source File: TreeModelAdapter.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public int getIndexOfChild(Object parent, Object child) {
    if (parent == null || child == null)
        return -1;

    Collection<Object> childrenIds;
    if (parent == rootNode) {
        childrenIds = datasource.getRootItemIds();
    } else {
        Entity entity = ((Node) parent).getEntity();
        childrenIds = datasource.getChildren(entity.getId());
    }
    final Entity childEntity = ((Node) child).getEntity();
    return Iterables.indexOf(childrenIds, id -> childEntity.getId().equals(id));
}
 
Example 5
Source File: ArtifactFunctionTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
private TreeFileArtifact createFakeExpansionTreeFileArtifact(
    ActionTemplate<?> actionTemplate, String parentRelativePath, String content)
    throws Exception {
  int actionIndex = Iterables.indexOf(actions, actionTemplate::equals);
  Preconditions.checkState(actionIndex >= 0, "%s not registered", actionTemplate);
  TreeFileArtifact treeFileArtifact =
      TreeFileArtifact.createTemplateExpansionOutput(
          actionTemplate.getOutputTreeArtifact(),
          parentRelativePath,
          ActionTemplateExpansionValue.key(ALL_OWNER, actionIndex));
  Path path = treeFileArtifact.getPath();
  path.getParentDirectory().createDirectoryAndParents();
  writeFile(path, content);
  return treeFileArtifact;
}
 
Example 6
Source File: SceneAccessLayer.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * find matched request from scene
 * @param request incoming request that we'd like match in existing scene
 * @return position of list of HttpExchanges from the scene. return -1 if no match found
 *
 * */
private int findMatchRequest(final RecordedHttpRequest request) {
  if (_scene.isSequential()) {
    List<RecordedHttpExchange> exchangeList = _scene.getRecordedHttpExchangeList();
    // In sequential playback mode, only test the request at the current sequence index
    if (_sequencePosition < exchangeList.size() && _matchRule
        .test(request, exchangeList.get(_sequencePosition).getRecordedHttpRequest())) {
      return _sequencePosition;
    }
    return -1;
  } else {
    return Iterables.indexOf(_scene.getRecordedHttpExchangeList(),
        input -> _matchRule.test(request, input.getRecordedHttpRequest()));
  }
}
 
Example 7
Source File: NotificationStore.java    From notification with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the index in notifications that matches the given ID or is the parent of a child
 * notification, or -1 if the notification was not found.
 *
 * @param notifications Notifications to search through
 * @param id Notification ID to find
 * @return the position of the notification or -1 if not found
 */
public static int indexOf(final Iterable<Notification> notifications, final String id) {

  Objects.requireNonNull(notifications, "notifications == null");

  if (Strings.isNullOrEmpty(id)) {
    return -1;
  }

  return Iterables.indexOf(
      notifications,
      notification -> {
        // first check that the ID matches
        final Optional<String> notificationId = notification.getId();
        if (!notificationId.isPresent()) {
          return false;
        } else if (id.equals(notificationId.get())) {
          return true;
        }

        // then check to see if the notification is included in any rolled up notifications
        final Collection<Notification> children = notification.getNotifications();
        if (children.isEmpty()) {
          return false;
        }
        return indexOf(children, id) != -1;
      });
}
 
Example 8
Source File: IntegrationTestBase.java    From j2cl with Apache License 2.0 5 votes vote down vote up
protected List<String> runTest(String testName) throws Exception {
  File executable = getTestDataFile(testName + testMode.postfix);
  assertTrue("Missing the test in classpath", executable.exists());
  List<String> logs = runTestBinary(executable.getAbsolutePath());

  // Cleanup log message for jsunit until "Start" log.
  if (testMode.isJ2cl()) {
    int startIndex = Iterables.indexOf(logs, x -> x.endsWith("  Start"));
    logs = logs.subList(startIndex, logs.size());
  }

  return logs;
}
 
Example 9
Source File: IdentifierUtils.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
private static YangInstanceIdentifier firstIdentifierOf(final YangInstanceIdentifier id,
        final Predicate<PathArgument> match) {
    final int idx = Iterables.indexOf(id.getPathArguments(), match);
    Preconditions.checkArgument(idx != -1, "Failed to find %s in %s", match, id);
    // we want the element at index idx to be included in the list
    return YangInstanceIdentifier.create(Iterables.limit(id.getPathArguments(), idx + 1));
}
 
Example 10
Source File: GamaListCollectionWrapper.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int indexOf(final Object o) {
	return Iterables.indexOf(wrapped, (o1) -> Objects.equal(o, o1));
}
 
Example 11
Source File: PurchaseLog.java    From log-synth with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
    Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: -count <number>G|M|K [ -users number ]  log-file user-profiles");
        return;
    }

    Joiner withTab = Joiner.on("\t");

    // first generate lots of user definitions
    //noinspection UnstableApiUsage
    SchemaSampler users = new SchemaSampler(Resources.asCharSource(Resources.getResource("user-schema.txt"), Charsets.UTF_8).read());
    File userFile = File.createTempFile("user", "tsv");
    BufferedWriter out = Files.newBufferedWriter(userFile.toPath(), Charsets.UTF_8);
    for (int i = 0; i < opts.users; i++) {
        out.write(withTab.join(users.sample()));
        out.newLine();
    }
    out.close();

    // now generate a session for each user
    Splitter onTabs = Splitter.on("\t");
    Splitter onComma = Splitter.on(",");

    Random gen = new Random();
    //noinspection UnstableApiUsage
    SchemaSampler intermediate = new SchemaSampler(Resources.asCharSource(Resources.getResource("hit_step.txt"), Charsets.UTF_8).read());

    final int COUNTRY = Iterables.indexOf(users.getFieldNames(), "country"::equals);
    final int CAMPAIGN = Iterables.indexOf(intermediate.getFieldNames(), "campaign_list"::equals);
    final int SEARCH_TERMS = Iterables.indexOf(intermediate.getFieldNames(),"search_keywords"::equals);
    Preconditions.checkState(COUNTRY >= 0, "Need country field in user schema");
    Preconditions.checkState(CAMPAIGN >= 0, "Need campaign_list field in step schema");
    Preconditions.checkState(SEARCH_TERMS >= 0, "Need search_keywords field in step schema");

    out = Files.newBufferedWriter(new File(opts.out).toPath(), Charsets.UTF_8);

    for (String line : Files.readAllLines(userFile.toPath(), Charsets.UTF_8)) {
        long t = (long) (TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS) * gen.nextDouble());
        List<String> user = Lists.newArrayList(onTabs.split(line));

        // pick session length
        int n = (int) Math.floor(-30 * Math.log(gen.nextDouble()));

        for (int i = 0; i < n; i++) {
            // time on page
            int dt = (int) Math.floor(-20000 * Math.log(gen.nextDouble()));
            t += dt;

            // hit specific values
            JsonNode step = intermediate.sample();

            // check for purchase
            double p = 0.01;
            List<String> campaigns = Lists.newArrayList(onComma.split(step.get("campaign_list").asText()));
            List<String> keywords = Lists.newArrayList(onComma.split(step.get("search_keywords").asText()));
            if ((user.get(COUNTRY).equals("us") && campaigns.contains("5")) ||
                    (user.get(COUNTRY).equals("jp") && campaigns.contains("7")) ||
                    keywords.contains("homer") || keywords.contains("simpson")) {
                p = 0.5;
            }

            String events = gen.nextDouble() < p ? "1" : "-";

            out.write(Long.toString(t));
            out.write("\t");
            out.write(line);
            out.write("\t");
            out.write(withTab.join(step));
            out.write("\t");
            out.write(events);
            out.write("\n");
        }
    }
    out.close();
}
 
Example 12
Source File: DruidQuery.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * @return index of the timestamp ref or -1 if not present
 */
protected int getTimestampFieldIndex() {
  return Iterables.indexOf(this.getRowType().getFieldList(),
      input -> druidTable.timestampFieldName.equals(input.getName()));
}
 
Example 13
Source File: SymbolTable.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** Gets a unique index for the symbol in this scope. */
public int getIndexOfSymbol(Symbol sym) {
  return Iterables.indexOf(
      ownSymbols.values(), Predicates.equalTo(sym));
}
 
Example 14
Source File: JGraphTab.java    From binnavi with Apache License 2.0 4 votes vote down vote up
private Color selectTabBackGroundColor(final int seed) {

    final int insertionPosition =
        Iterables.indexOf(moduleIdCount.keySet(), Predicates.equalTo(seed));

    switch (insertionPosition) {
      case 0:
        return Color.getHSBColor((float) 0.55, (float) 0.2, (float) 0.8);
      case 1:
        return Color.getHSBColor((float) 0.6, (float) 0.2, (float) 0.8);
      case 2:
        return Color.getHSBColor((float) 0.65, (float) 0.2, (float) 0.8);
      case 3:
        return Color.getHSBColor((float) 0.7, (float) 0.2, (float) 0.8);
      case 4:
        return Color.getHSBColor((float) 0.75, (float) 0.2, (float) 0.8);
      case 5:
        return Color.getHSBColor((float) 0.8, (float) 0.2, (float) 0.8);
      case 6:
        return Color.getHSBColor((float) 0.85, (float) 0.2, (float) 0.8);
      case 7:
        return Color.getHSBColor((float) 0.9, (float) 0.2, (float) 0.8);
      case 8:
        return Color.getHSBColor((float) 0.95, (float) 0.2, (float) 0.8);
      case 9:
        return Color.getHSBColor(1, (float) 0.2, (float) 0.8);
      case 10:
        return Color.getHSBColor((float) 0.05, (float) 0.2, (float) 0.8);
      case 11:
        return Color.getHSBColor((float) 0.1, (float) 0.2, (float) 0.8);
      case 12:
        return Color.getHSBColor((float) 0.15, (float) 0.2, (float) 0.8);
      case 13:
        return Color.getHSBColor((float) 0.2, (float) 0.2, (float) 0.8);
      case 14:
        return Color.getHSBColor((float) 0.25, (float) 0.2, (float) 0.8);
      case 15:
        return Color.getHSBColor((float) 0.3, (float) 0.2, (float) 0.8);
      case 16:
        return Color.getHSBColor((float) 0.35, (float) 0.2, (float) 0.8);
      case 17:
        return Color.getHSBColor((float) 0.4, (float) 0.2, (float) 0.8);
      case 18:
        return Color.getHSBColor((float) 0.45, (float) 0.2, (float) 0.8);
      case 19:
        return Color.getHSBColor((float) 0.5, (float) 0.2, (float) 0.8);
      default:
        return Color.WHITE;
    }
  }
 
Example 15
Source File: DesktopAbstractBox.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
public int indexOf(Component child) {
    return Iterables.indexOf(ownComponents, c -> c == child);
}
 
Example 16
Source File: DesktopScrollBoxLayout.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
public int indexOf(Component child) {
    return Iterables.indexOf(components, c -> c == child);
}
 
Example 17
Source File: DesktopWindow.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
public int indexOf(Component component) {
    return Iterables.indexOf(ownComponents, c -> c == component);
}
 
Example 18
Source File: ExonumIterables.java    From exonum-java-binding with Apache License 2.0 3 votes vote down vote up
/**
 * Returns an index of the first element matching the predicate or {@code OptionalInt.empty()}
 * if no such element exists.
 *
 * @param list a list to search in
 * @param p a predicate that an element must match
 * @param <T> the type of elements
 */
static <T> OptionalInt indexOf(Iterable<T> list, Predicate<? super T> p) {
  int i = Iterables.indexOf(list, p::test);
  if (i == -1) {
    return OptionalInt.empty();
  }
  return OptionalInt.of(i);
}