Java Code Examples for com.google.common.collect.Lists#newArrayListWithExpectedSize()

The following examples show how to use com.google.common.collect.Lists#newArrayListWithExpectedSize() . These examples are extracted from open source projects. 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
private String getCallStack(String methodIdTag, boolean isFilter) {
    List<String> methodIdStr = METHOD_ID_SPLITTER.splitToList(methodIdTag);
    List<Integer> methodIds = Lists.newArrayListWithExpectedSize(methodIdStr.size());
    for (String idStr : methodIdStr) {
        methodIds.add(Integer.valueOf(idStr));
    }

    StringBuilder builder = new StringBuilder();
    List<MethodInfo> methodInfos = isFilter ? getFilterMethodInfos(methodIds) : getMethodInfos(methodIds);
    if (methodInfos.size() <= 1) {
        return "";
    }
    for (MethodInfo methodInfo : methodInfos) {
        builder.append(methodInfo).append(";");
    }
    if (builder.length() != 0) {
        builder.delete(builder.length() - 1, builder.length());
    }

    return builder.toString();
}
 
Example 2
Source Project: javaide   File: EcjParser.java    License: GNU General Public License v3.0 6 votes vote down vote up
@NonNull
@Override
public Iterable<ResolvedAnnotation> getAnnotations() {
    AnnotationBinding[] annotations = mBinding.getAnnotations();
    int count = annotations.length;
    if (count > 0) {
        List<ResolvedAnnotation> result = Lists.newArrayListWithExpectedSize(count);
        for (AnnotationBinding annotation : annotations) {
            if (annotation != null) {
                result.add(new EcjResolvedAnnotation(annotation));
            }
        }
        return result;
    }

    // No external annotations for variables

    return Collections.emptyList();
}
 
Example 3
Source Project: phoenix   File: BaseResultIterators.java    License: Apache License 2.0 6 votes vote down vote up
private List<Scan> addNewScan(List<List<Scan>> parallelScans, List<Scan> scans, Scan scan,
        byte[] startKey, boolean crossedRegionBoundary, HRegionLocation regionLocation) {
    boolean startNewScan = scanGrouper.shouldStartNewScan(plan, scans, startKey, crossedRegionBoundary);
    if (scan != null) {
        if (regionLocation.getServerName() != null) {
            scan.setAttribute(BaseScannerRegionObserver.SCAN_REGION_SERVER, regionLocation.getServerName().getVersionedBytes());
        }
        if (useStatsForParallelization || crossedRegionBoundary) {
            scans.add(scan);
        }
    }
    if (startNewScan && !scans.isEmpty()) {
        parallelScans.add(scans);
        scans = Lists.newArrayListWithExpectedSize(1);
    }
    return scans;
}
 
Example 4
Source Project: phoenix   File: ScanRanges.java    License: Apache License 2.0 6 votes vote down vote up
private static List<byte[]> getPointKeys(List<List<KeyRange>> ranges, int[] slotSpan, RowKeySchema schema, Integer bucketNum) {
    if (ranges == null || ranges.isEmpty()) {
        return Collections.emptyList();
    }
    boolean isSalted = bucketNum != null;
    int count = 1;
    int offset = isSalted ? 1 : 0;
    // Skip salt byte range in the first position if salted
    for (int i = offset; i < ranges.size(); i++) {
        count *= ranges.get(i).size();
    }
    List<byte[]> keys = Lists.newArrayListWithExpectedSize(count);
    int[] position = new int[ranges.size()];
    int maxKeyLength = SchemaUtil.getMaxKeyLength(schema, ranges);
    int length;
    byte[] key = new byte[maxKeyLength];
    do {
        length = ScanUtil.setKey(schema, ranges, slotSpan, position, Bound.LOWER, key, offset, offset, ranges.size(), offset);
        if (isSalted) {
            key[0] = SaltingUtil.getSaltingByte(key, offset, length, bucketNum);
        }
        keys.add(Arrays.copyOf(key, length + offset));
    } while (incrementKey(ranges, position));
    return keys;
}
 
Example 5
Source Project: termsuite-core   File: CompoundUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns all possible components for a compound word 
 * by combining its atomic components.
 * 
 * E.g. ab|cd|ef returns
 * 		abcdef,
 * 		ab, cdef,
 * 		abcd, ef,
 * 		cd
 * 
 * 
 * @param word the compound word
 * @return
 * 			the list of all possible component lemmas
 */
public static List<Component> allSizeComponents(Word word) {
	Set<Component> components = Sets.newHashSet();
	for(int nbComponents=word.getComponents().size();
			nbComponents > 0 ;
			nbComponents--) {
		
		for(int startIndex = 0;
				startIndex <= word.getComponents().size() - nbComponents;
				startIndex++) {
			List<Component> toMerge = Lists.newArrayListWithExpectedSize(nbComponents);
			
			for(int i = 0; i<nbComponents; i++) 
				toMerge.add(word.getComponents().get(startIndex + i));
			
			components.add(merge(word, toMerge));
		}
	}
	return Lists.newArrayList(components);
}
 
Example 6
private void mergeClass(Element item, String containingClass) {
    ClassInfo cls = createClass(containingClass);
    List<ResolvedAnnotation> annotations = createAnnotations(item);
    if (cls.annotations == null) {
        cls.annotations = Lists.newArrayListWithExpectedSize(annotations.size());
    }
    cls.annotations.addAll(annotations);
}
 
Example 7
Source Project: presto   File: ParquetTypeVisitor.java    License: Apache License 2.0 5 votes vote down vote up
private static <T> List<T> visitFields(GroupType group, ParquetTypeVisitor<T> visitor)
{
    List<T> results = Lists.newArrayListWithExpectedSize(group.getFieldCount());
    for (Type field : group.getFields()) {
        results.add(visitField(field, visitor));
    }

    return results;
}
 
Example 8
Source Project: bazel   File: ReverseDepsUtility.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * We use a memory-efficient trick to keep reverseDeps memory usage low. Edges in Bazel are
 * dominant over the number of nodes.
 *
 * <p>Most of the nodes have zero or one reverse dep. That is why we use immutable versions of the
 * lists for those cases. In case of the size being > 1 we switch to an ArrayList. That is because
 * we also have a decent number of nodes for which the reverseDeps are huge (for example almost
 * everything depends on BuildInfo node).
 *
 * <p>We also optimize for the case where we have only one dependency. In that case we keep the
 * object directly instead of a wrapper list.
 */
@SuppressWarnings("unchecked") // Cast to SkyKey and List.
static void addReverseDeps(InMemoryNodeEntry entry, Collection<SkyKey> newReverseDeps) {
  if (newReverseDeps.isEmpty()) {
    return;
  }
  List<Object> dataToConsolidate = entry.getReverseDepsDataToConsolidateForReverseDepsUtil();
  if (dataToConsolidate != null) {
    maybeDelayReverseDepOp(entry, newReverseDeps, Op.ADD);
    return;
  }
  Object reverseDeps = entry.getReverseDepsRawForReverseDepsUtil();
  int reverseDepsSize = isSingleReverseDep(entry) ? 1 : ((List<SkyKey>) reverseDeps).size();
  int newSize = reverseDepsSize + newReverseDeps.size();
  if (newSize == 1) {
    entry.setSingleReverseDepForReverseDepsUtil(Iterables.getOnlyElement(newReverseDeps));
  } else if (reverseDepsSize == 0) {
    entry.setReverseDepsForReverseDepsUtil(Lists.newArrayList(newReverseDeps));
  } else if (reverseDepsSize == 1) {
    List<SkyKey> newList = Lists.newArrayListWithExpectedSize(newSize);
    newList.add((SkyKey) reverseDeps);
    newList.addAll(newReverseDeps);
    entry.setReverseDepsForReverseDepsUtil(newList);
  } else {
    ((List<SkyKey>) reverseDeps).addAll(newReverseDeps);
  }
}
 
Example 9
Source Project: yql-plus   File: BytecodeInvocable.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public final BytecodeExpression invoke(final Location loc, List<BytecodeExpression> args) {
    final List<BytecodeExpression> argsCopy = Lists.newArrayListWithExpectedSize(args.size());
    for (BytecodeExpression arg : args) {
        Preconditions.checkNotNull(arg);
        argsCopy.add(arg);
    }
    return new BaseTypeExpression(returnType) {
        @Override
        public void generate(CodeEmitter code) {
            BytecodeInvocable.this.generate(loc, code, argsCopy);
        }
    };
}
 
Example 10
/**
 * Creates a {@link ResourceVisibilityLookup} for the set of libraries.
 * <p>
 * NOTE: The {@link Provider} class can be used to share/cache {@link ResourceVisibilityLookup}
 * instances, e.g. when you have library1 and library2 each referencing libraryBase, the {@link
 * Provider} will ensure that a the libraryBase data is shared.
 *
 * @param libraries the list of libraries
 * @param provider  an optional manager instance for caching of individual libraries, if any
 * @return a corresponding {@link ResourceVisibilityLookup}
 */
@NonNull
public static ResourceVisibilityLookup create(@NonNull List<AndroidLibrary> libraries,
        @Nullable Provider provider) {
    List<ResourceVisibilityLookup> list = Lists.newArrayListWithExpectedSize(libraries.size());
    for (AndroidLibrary library : libraries) {
        ResourceVisibilityLookup v = provider != null ? provider.get(library) : create(library);
        if (!v.isEmpty()) {
            list.add(v);
        }
    }
    return new MultipleLibraryResourceVisibility(list);
}
 
Example 11
Source Project: intellij   File: DirectoryStructure.java    License: Apache License 2.0 5 votes vote down vote up
private static DirectoryStructure computeRootDirectoryStructure(
    Project project,
    WorkspaceRoot workspaceRoot,
    ProjectViewSet projectViewSet,
    AtomicBoolean cancelled)
    throws ExecutionException, InterruptedException {
  FileOperationProvider fileOperationProvider = FileOperationProvider.getInstance();
  ImportRoots importRoots =
      ImportRoots.builder(workspaceRoot, Blaze.getBuildSystem(project))
          .add(projectViewSet)
          .build();
  Collection<WorkspacePath> rootDirectories = importRoots.rootDirectories();
  Set<WorkspacePath> excludeDirectories = importRoots.excludeDirectories();
  List<ListenableFuture<PathStructurePair>> futures =
      Lists.newArrayListWithExpectedSize(rootDirectories.size());
  for (WorkspacePath rootDirectory : rootDirectories) {
    futures.add(
        walkDirectoryStructure(
            workspaceRoot,
            excludeDirectories,
            fileOperationProvider,
            FetchExecutor.EXECUTOR,
            rootDirectory,
            cancelled));
  }
  ImmutableMap.Builder<WorkspacePath, DirectoryStructure> result = ImmutableMap.builder();
  for (PathStructurePair pair : Futures.allAsList(futures).get()) {
    if (pair != null) {
      result.put(pair.path, pair.directoryStructure);
    }
  }
  return new DirectoryStructure(result.build());
}
 
Example 12
Source Project: javaide   File: LintDriver.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void registerCustomDetectors(Collection<Project> projects) {
    // Look at the various projects, and if any of them provide a custom
    // lint jar, "add" them (this will replace the issue registry with
    // a CompositeIssueRegistry containing the original issue registry
    // plus JarFileIssueRegistry instances for each lint jar
    Set<File> jarFiles = Sets.newHashSet();
    for (Project project : projects) {
        jarFiles.addAll(mClient.findRuleJars(project));
        for (Project library : project.getAllLibraries()) {
            jarFiles.addAll(mClient.findRuleJars(library));
        }
    }

    jarFiles.addAll(mClient.findGlobalRuleJars());

    if (!jarFiles.isEmpty()) {
        List<IssueRegistry> registries = Lists.newArrayListWithExpectedSize(jarFiles.size());
        registries.add(mRegistry);
        for (File jarFile : jarFiles) {
            try {
                IssueRegistry registry = JarFileIssueRegistry.get(mClient, jarFile);
                if (myCustomIssues == null) {
                    myCustomIssues = Sets.newHashSet();
                }
                myCustomIssues.addAll(registry.getIssues());
                registries.add(registry);
            } catch (Throwable e) {
                mClient.log(e, "Could not load custom rule jar file %1$s", jarFile);
            }
        }
        if (registries.size() > 1) { // the first item is mRegistry itself
            mRegistry = new CompositeIssueRegistry(registries);
        }
    }
}
 
Example 13
Source Project: kylin   File: TupleExpressionVisitor.java    License: Apache License 2.0 5 votes vote down vote up
private RexCallTupleExpression getRexCallTupleExpression(RexCall call) {
    List<TupleExpression> children = Lists.newArrayListWithExpectedSize(call.getOperands().size());
    for (RexNode rexNode : call.operands) {
        children.add(rexNode.accept(this));
    }

    DataType dataType = DataType.getType(OLAPTable.DATATYPE_MAPPING.get(call.type.getSqlTypeName()));
    RexCallTupleExpression tuple = new RexCallTupleExpression(dataType, children);
    tuple.setDigest(call.toString());
    return tuple;
}
 
Example 14
Source Project: immutables   File: Constitution.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Actual abstract value type that is definitive model for the value type.
 * @return abstract value type name forms
 */
@Value.Lazy
public NameForms typeAbstract() {
  if (protoclass().kind().isConstructor()) {
    return typeValue();
  }

  List<String> classSegments = Lists.newArrayListWithExpectedSize(2);
  Element e = SourceNames.collectClassSegments(protoclass().sourceElement(), classSegments);
  verify(e instanceof PackageElement);

  String packageOf = ((PackageElement) e).getQualifiedName().toString();
  String relative = DOT_JOINER.join(classSegments);
  boolean relativeAlreadyQualified = false;

  if (!implementationPackage().equals(packageOf)) {
    relative = DOT_JOINER.join(packageOf, relative);
    relativeAlreadyQualified = true;
  }

  return ImmutableConstitution.NameForms.builder()
      .simple(names().typeAbstract)
      .relativeRaw(relative)
      .packageOf(packageOf)
      .genericArgs(generics().args())
      .relativeAlreadyQualified(relativeAlreadyQualified)
      .visibility(protoclass().visibility())
      .build();
}
 
Example 15
Source Project: phoenix   File: SubselectRewriter.java    License: Apache License 2.0 5 votes vote down vote up
private SelectStatement applyOrderBy(SelectStatement statement, List<OrderByNode> orderBy) throws SQLException {
    List<OrderByNode> orderByRewrite = Lists.<OrderByNode> newArrayListWithExpectedSize(orderBy.size());
    for (OrderByNode orderByNode : orderBy) {
        ParseNode node = orderByNode.getNode();
        orderByRewrite.add(NODE_FACTORY.orderBy(node.accept(this), orderByNode.isNullsLast(), orderByNode.isAscending()));
    }
    
    return NODE_FACTORY.select(statement, orderByRewrite);
}
 
Example 16
Source Project: javaide   File: NodeUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
@NonNull
private static List<Node> getElementChildren(@NonNull NodeList children) {
    List<Node> results = Lists.newArrayListWithExpectedSize(children.getLength());

    final int len = children.getLength();
    for (int i = 0; i < len; i++) {
        Node child = children.item(i);
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            results.add(child);
        }
    }

    return results;
}
 
Example 17
@Override
public void readFields(DataInput input) throws IOException {
    byte[] schemaNameBytes = Bytes.readByteArray(input);
    byte[] tableNameBytes = Bytes.readByteArray(input);
    PName schemaName = PNameFactory.newName(schemaNameBytes);
    PName tableName = PNameFactory.newName(tableNameBytes);
    PTableType tableType = PTableType.values()[WritableUtils.readVInt(input)];
    PIndexState indexState = null;
    if (tableType == PTableType.INDEX) {
        int ordinal = WritableUtils.readVInt(input);
        if (ordinal >= 0) {
            indexState = PIndexState.values()[ordinal];
        }
    }
    long sequenceNumber = WritableUtils.readVLong(input);
    long timeStamp = input.readLong();
    byte[] pkNameBytes = Bytes.readByteArray(input);
    PName pkName = pkNameBytes.length == 0 ? null : PNameFactory.newName(pkNameBytes);
    Integer bucketNum = WritableUtils.readVInt(input);
    int nColumns = WritableUtils.readVInt(input);
    List<PColumn> columns = Lists.newArrayListWithExpectedSize(nColumns);
    for (int i = 0; i < nColumns; i++) {
        PColumn column = new PColumnImpl();
        column.readFields(input);
        columns.add(column);
    }
    int nIndexes = WritableUtils.readVInt(input);
    List<PTable> indexes = Lists.newArrayListWithExpectedSize(nIndexes);
    for (int i = 0; i < nIndexes; i++) {
        PTable index = new PTableImpl();
        index.readFields(input);
        indexes.add(index);
    }
    boolean isImmutableRows = input.readBoolean();
    Map<String, byte[][]> guidePosts = new HashMap<String, byte[][]>();
    int size = WritableUtils.readVInt(input);
    for (int i=0; i<size; i++) {
        String key = WritableUtils.readString(input);
        int valueSize = WritableUtils.readVInt(input);
        byte[][] value = new byte[valueSize][];
        for (int j=0; j<valueSize; j++) {
            value[j] = Bytes.readByteArray(input);
        }
        guidePosts.put(key, value);
    }
    byte[] dataTableNameBytes = Bytes.readByteArray(input);
    PName dataTableName = dataTableNameBytes.length == 0 ? null : PNameFactory.newName(dataTableNameBytes);
    byte[] defaultFamilyNameBytes = Bytes.readByteArray(input);
    PName defaultFamilyName = defaultFamilyNameBytes.length == 0 ? null : PNameFactory.newName(defaultFamilyNameBytes);
    boolean disableWAL = input.readBoolean();
    boolean multiTenant = input.readBoolean();
    ViewType viewType = null;
    String viewExpression = null;
    PName baseSchemaName = null;
    PName baseTableName = null;
    if (tableType == PTableType.VIEW) {
        viewType = ViewType.fromSerializedValue(input.readByte());
        byte[] viewExpressionBytes = Bytes.readByteArray(input);
        viewExpression = viewExpressionBytes.length == 0 ? null : (String)PDataType.VARCHAR.toObject(viewExpressionBytes);
        byte[] baseSchemaNameBytes = Bytes.readByteArray(input);
        baseSchemaName = baseSchemaNameBytes.length == 0 ? null : PNameFactory.newName(baseSchemaNameBytes);
        byte[] baseTableNameBytes = Bytes.readByteArray(input);
        baseTableName = baseTableNameBytes.length == 0 ? null : PNameFactory.newName(baseTableNameBytes);
    }
    PTableStats stats = new PTableStatsImpl(guidePosts);
    try {
        init(schemaName, tableName, tableType, indexState, timeStamp, sequenceNumber, pkName,
             bucketNum.equals(NO_SALTING) ? null : bucketNum, columns, stats, dataTableName,
             indexes, isImmutableRows, baseSchemaName, baseTableName, defaultFamilyName,
             viewExpression, disableWAL, multiTenant, viewType);
    } catch (SQLException e) {
        throw new RuntimeException(e); // Impossible
    }
}
 
Example 18
Source Project: JGiven   File: CaseArgumentAnalyser.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Finds for each JoinedArgs set the best fitting name.
 * <p>
 * First it is tried to find a name from the explicitParameterNames list, by comparing the argument values
 * with the explicit case argument values. If no matching value can be found, the name of the argument is taken.
 */
private List<String> findArgumentNames( List<List<JoinedArgs>> joinedArgs, List<List<String>> explicitParameterValues,
        List<String> explicitParameterNames ) {
    List<String> argumentNames = Lists.newArrayListWithExpectedSize( joinedArgs.get( 0 ).size() );
    Multiset<String> paramNames = TreeMultiset.create();

    arguments:
    for( int iArg = 0; iArg < joinedArgs.get( 0 ).size(); iArg++ ) {
        parameters:
        for( int iParam = 0; iParam < explicitParameterNames.size(); iParam++ ) {
            String paramName = explicitParameterNames.get( iParam );

            boolean formattedValueMatches = true;
            boolean valueMatches = true;
            for( int iCase = 0; iCase < joinedArgs.size(); iCase++ ) {
                JoinedArgs args = joinedArgs.get( iCase ).get( iArg );

                String parameterValue = explicitParameterValues.get( iCase ).get( iParam );

                String formattedValue = args.words.get( 0 ).getFormattedValue();
                if( !formattedValue.equals( parameterValue ) ) {
                    formattedValueMatches = false;
                }

                String value = args.words.get( 0 ).getValue();
                if( !value.equals( parameterValue ) ) {
                    valueMatches = false;
                }

                if( !formattedValueMatches && !valueMatches ) {
                    continue parameters;
                }
            }

            // on this point either all formatted values match or all values match (or both)
            argumentNames.add( paramName );
            paramNames.add( paramName );
            continue arguments;
        }

        argumentNames.add( null );
    }

    Set<String> usedNames = Sets.newHashSet();
    for( int iArg = 0; iArg < joinedArgs.get( 0 ).size(); iArg++ ) {
        String name = argumentNames.get( iArg );
        if( name == null || paramNames.count( name ) > 1 ) {
            String origName = getArgumentName( joinedArgs, iArg );
            name = findFreeName( usedNames, origName );
            argumentNames.set( iArg, name );
        }
        usedNames.add( name );

    }

    return argumentNames;
}
 
Example 19
@Test
@Description("Tests the correct order of targets with applied overdue filter based on selected distribution set. The system expects to have an order based on installed, assigned DS.")
public void targetSearchWithOverdueFilterAndOrderByDistributionSet() {

    final Long lastTargetQueryAlwaysOverdue = 0L;
    final Long lastTargetQueryNotOverdue = Instant.now().toEpochMilli();
    final Long lastTargetNull = null;

    final Long[] overdueMix = { lastTargetQueryAlwaysOverdue, lastTargetQueryNotOverdue,
            lastTargetQueryAlwaysOverdue, lastTargetNull, lastTargetQueryAlwaysOverdue };

    final List<Target> notAssigned = Lists.newArrayListWithExpectedSize(overdueMix.length);
    List<Target> targAssigned = Lists.newArrayListWithExpectedSize(overdueMix.length);
    List<Target> targInstalled = Lists.newArrayListWithExpectedSize(overdueMix.length);

    for (int i = 0; i < overdueMix.length; i++) {
        notAssigned.add(targetManagement
                .create(entityFactory.target().create().controllerId("not" + i).lastTargetQuery(overdueMix[i])));
        targAssigned.add(targetManagement.create(
                entityFactory.target().create().controllerId("assigned" + i).lastTargetQuery(overdueMix[i])));
        targInstalled.add(targetManagement.create(
                entityFactory.target().create().controllerId("installed" + i).lastTargetQuery(overdueMix[i])));
    }

    final DistributionSet ds = testdataFactory.createDistributionSet("a");

    targAssigned = assignDistributionSet(ds, targAssigned).getAssignedEntity().stream().map(Action::getTarget)
            .collect(Collectors.toList());
    targInstalled = assignDistributionSet(ds, targInstalled).getAssignedEntity().stream().map(Action::getTarget)
            .collect(Collectors.toList());
    targInstalled = testdataFactory
            .sendUpdateActionStatusToTargets(targInstalled, Status.FINISHED, Collections.singletonList("installed"))
            .stream().map(Action::getTarget).collect(Collectors.toList());

    final Slice<Target> result = targetManagement.findByFilterOrderByLinkedDistributionSet(PAGE, ds.getId(),
            new FilterParams(null, Boolean.TRUE, null, null, Boolean.FALSE, new String[0]));

    final Comparator<TenantAwareBaseEntity> byId = (e1, e2) -> Long.compare(e2.getId(), e1.getId());

    assertThat(result.getNumberOfElements()).isEqualTo(9);
    final List<Target> expected = new ArrayList<>();
    expected.addAll(targInstalled.stream().sorted(byId)
            .filter(item -> lastTargetQueryAlwaysOverdue.equals(item.getLastTargetQuery()))
            .collect(Collectors.toList()));
    expected.addAll(targAssigned.stream().sorted(byId)
            .filter(item -> lastTargetQueryAlwaysOverdue.equals(item.getLastTargetQuery()))
            .collect(Collectors.toList()));
    expected.addAll(notAssigned.stream().sorted(byId)
            .filter(item -> lastTargetQueryAlwaysOverdue.equals(item.getLastTargetQuery()))
            .collect(Collectors.toList()));

    assertThat(result.getContent()).usingElementComparator(controllerIdComparator())
            .containsExactly(expected.toArray(new Target[0]));

}
 
Example 20
private void generateExpectedGeneCounts(final EnsemblGeneData geneData)
{
    GcRatioCounts gcRatioCounts = new GcRatioCounts();
    int readLength = mConfig.ReadLength;

    if(geneData.length() - 1 < readLength)
    {
        final String bases = mConfig.RefGenome.getBaseString(geneData.Chromosome, geneData.GeneStart, geneData.GeneEnd);
        gcRatioCounts.addGcRatio(calcGcRatio(bases));
    }
    else
    {
        // rather than measure GC content for each shifting read, just apply diffs to from the base lost and added
        List<int[]> readRegions = Lists.newArrayListWithExpectedSize(1);
        int[] geneRegion = new int[] { 0, 0 };
        readRegions.add(geneRegion);

        final String geneBases = mConfig.RefGenome.getBaseString(geneData.Chromosome, geneData.GeneStart, geneData.GeneEnd);

        final String initialBases = geneBases.substring(0, readLength);
        int gcCount = calcGcCount(initialBases);
        double baseLength = mConfig.ReadLength;
        double gcRatio = gcCount / baseLength;
        gcRatioCounts.addGcRatio(gcRatio);

        for (int startPos = 1; startPos <= geneBases.length() - readLength; ++startPos)
        {
            int prevStartPos = startPos - 1;
            int endPos = startPos + readLength - 1;
            int countAdjust = (isGC(geneBases.charAt(prevStartPos)) ? -1 : 0) + (isGC(geneBases.charAt(endPos)) ? 1 : 0);

            if (gcCount > readLength || gcCount < 0)
            {
                ISF_LOGGER.error("gene({}) gcCount error", geneData.GeneId);
                return;
            }

            gcCount += countAdjust;
            gcRatio = gcCount / baseLength;
            gcRatioCounts.addGcRatio(gcRatio);
        }
    }

    sumVectors(gcRatioCounts.getCounts(), mTotalExpectedCounts);

    writeExpectedGcRatios(mWriter, geneData.GeneId, gcRatioCounts.getCounts());
}