Example usage for java.util LinkedHashMap size

List of usage examples for java.util LinkedHashMap size

Introduction

In this page you can find the example usage for java.util LinkedHashMap size.

Prototype

int size();

Source Link

Document

Returns the number of key-value mappings in this map.

Usage

From source file:org.opencb.opencga.storage.mongodb.variant.load.variants.MongoDBVariantMerger.java

protected LinkedHashMap<String, Integer> getSamplesPosition(Integer fileId) {
    if (!samplesPositionMap.containsKey(fileId)) {
        synchronized (samplesPositionMap) {
            if (!samplesPositionMap.containsKey(fileId)) {
                LinkedHashMap<String, Integer> samplesPosition = new LinkedHashMap<>();
                for (Integer sampleId : studyConfiguration.getSamplesInFiles().get(fileId)) {
                    samplesPosition.put(studyConfiguration.getSampleIds().inverse().get(sampleId),
                            samplesPosition.size());
                }/*from  ww  w  . j a v a 2  s.  c  o  m*/
                samplesPositionMap.put(fileId, samplesPosition);
            }
        }
    }
    return samplesPositionMap.get(fileId);
}

From source file:org.fao.fenix.wds.web.rest.crowdprices.CrowdPricesDataRESTService.java

private String createGeoJsonDisabled(List<List<String>> table) {

    String s = "{ \"type\":\"FeatureCollection\",\"features\":[";
    int i = 0;//from  w  w  w  .  j  a v  a  2s.  c o m
    LinkedHashMap<String, List<List<String>>> markets = getCrowdPricesPoints(table);
    for (String marketname : markets.keySet()) {
        String popupcontent = "<b>" + marketname
                + "</b><br> No available data for that market in the current selection";
        String lat = "";
        String lon = "";
        for (List<String> row : markets.get(marketname)) {
            lon = row.get(1);
            lat = row.get(2);
        }
        //         System.out.println("popup: " + popupcontent);
        s += "{\"type\":\"Feature\",\"properties\":{\"iconurl\":\"images/marker-icon-disabled.png\","
                + "\"name\":\"Countrys\"," + "\"popupContent\":\"" + popupcontent
                + " \"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[" + lon + "," + lat + "]}}";
        if (i < markets.size() - 1) {
            s += ",";
        }
        i++;
    }
    s += "]}";
    return s;
}

From source file:org.apache.axis2.engine.MessageContextSaveCTest.java

/**
 * Compare two mappings containing object graph info.
 * This uses the class name and object ID.
 * <p/>/*  w  w w.j  a  va2s.  c o m*/
 * Strict comparison includes the object hash codes. If
 * you expect the same object to be represented in
 * both maps, you may want to use Strict checking.
 * <p/>
 *
 * @param map1   The first object graph info map
 * @param map2   The second object graph info map
 * @param strict TRUE if strict comparison
 * @return Outcome of the comparison: TRUE if equivalent, FALSE otherwise
 */
private boolean compareObjectGraphInfo(LinkedHashMap map1, LinkedHashMap map2, boolean strict) {
    String title = "MessageContextSaveCTest: compareObjectGraphInfo(): ";

    if ((map1 != null) && (map2 != null)) {
        if (map1.size() != map2.size()) {
            log.debug(title + "Object graph info mappings are different sizes.");
            return false;
        }

        Iterator it = map1.keySet().iterator();

        while (it.hasNext()) {
            // the key is the class name associated with the object
            String key = (String) it.next();

            // skip certain objects, those will always be unique
            if ((key.indexOf("MessageContext") == -1) && (key.indexOf("OperationContext") == -1)
                    && (key.indexOf("ConfigurationContext") == -1)
                    && (key.indexOf("AxisConfiguration") == -1)) {
                // the class names listed above were not found
                // so we're dealing with the other objects
                MetaDataEntry value1 = (MetaDataEntry) map1.get(key);
                MetaDataEntry value2 = (MetaDataEntry) map2.get(key);

                if ((value1 != null) && (value2 != null)) {
                    // check the object identification
                    String name1 = value1.getName();
                    String name2 = value2.getName();

                    if ((name1 != null) && (name2 != null)) {
                        if (name1.equals(name2) == false) {
                            log.debug(title + "name1 [" + name1 + "]  !=   name2 [" + name2 + "]");
                            return false;
                        }
                    } else if ((name1 == null) && (name2 == null)) {
                        // ok
                    } else {
                        // mismatch
                        log.debug(title + "name1 [" + name1 + "]  !=   name2 [" + name2 + "]");
                        return false;
                    }

                    // Strict testing means checking the object hashcodes.
                    // Use this option when you expect the same
                    // objects in the map.
                    if (strict) {
                        String code1 = value1.getExtraName();
                        String code2 = value2.getExtraName();

                        if ((code1 != null) && (code2 != null)) {
                            if (code1.equals(code2) == false) {
                                log.debug(title + "name [" + name1 + "]  code1 [" + code1 + "]  !=   code2 ["
                                        + code2 + "]");
                                return false;
                            }
                        } else if ((code1 == null) && (code2 == null)) {
                            // ok
                        } else {
                            // mismatch
                            log.debug(title + "name [" + name1 + "]code1 [" + code1 + "]  !=   code2 [" + code2
                                    + "]");
                            return false;
                        }
                    }
                } else if ((value1 == null) && (value2 == null)) {
                    // ok
                } else {
                    // mismatch
                    log.debug(title + "value1 [" + value1 + "]  !=   value2 [" + value2 + "]");
                    return false;
                }
            }
        }

        return true;

    } else if ((map1 == null) && (map2 == null)) {
        return true;
    } else {
        log.debug(title + "mismatch: one or more of the maps are null.  ");
        return false;
    }

}

From source file:org.eclipse.scanning.test.scan.nexus.MandelbrotRemoteTest.java

private void checkNexusFile(IRunnableDevice<ScanModel> scanner, int... sizes)
        throws NexusException, ScanningException, DatasetException {

    final ScanModel mod = ((AbstractRunnableDevice<ScanModel>) scanner).getModel();
    assertEquals(DeviceState.READY, scanner.getDeviceState());

    String filePath = ((AbstractRunnableDevice<ScanModel>) scanner).getModel().getFilePath();
    NexusFile nf = fileFactory.newNexusFile(filePath);
    nf.openToRead();//  ww  w  . j  av a 2  s  .co m

    TreeFile nexusTree = NexusUtils.loadNexusTree(nf);
    NXroot rootNode = (NXroot) nexusTree.getGroupNode();
    NXentry entry = rootNode.getEntry();
    NXinstrument instrument = entry.getInstrument();

    // check that the scan points have been written correctly
    assertSolsticeScanGroup(entry, false, false, sizes);

    LinkedHashMap<String, List<String>> detectorDataFields = new LinkedHashMap<>();
    // axis for additional dimensions of a datafield, e.g. image
    detectorDataFields.put(NXdetector.NX_DATA, Arrays.asList("real", "imaginary"));
    detectorDataFields.put("spectrum", Arrays.asList("spectrum_axis"));
    detectorDataFields.put("value", Collections.emptyList());

    String detectorName = mod.getDetectors().get(0).getName();
    NXdetector detector = instrument.getDetector(detectorName);
    // map of detector data field to name of nxData group where that field is the @signal field
    Map<String, String> expectedDataGroupNames = detectorDataFields.keySet().stream().collect(Collectors
            .toMap(Function.identity(), x -> detectorName + (x.equals(NXdetector.NX_DATA) ? "" : "_" + x)));

    // validate the NXdata generated by the NexusDataBuilder
    Map<String, NXdata> nxDataGroups = entry.getChildren(NXdata.class);
    assertEquals(detectorDataFields.size(), nxDataGroups.size());
    assertTrue(nxDataGroups.keySet().containsAll(expectedDataGroupNames.values()));

    for (String nxDataGroupName : nxDataGroups.keySet()) {
        NXdata nxData = entry.getData(nxDataGroupName);
        String sourceFieldName = nxDataGroupName.equals(detectorName) ? NXdetector.NX_DATA
                : nxDataGroupName.substring(nxDataGroupName.indexOf('_') + 1);
        assertSignal(nxData, sourceFieldName);
        // check the nxData's signal field is a link to the data node of the detector
        DataNode dataNode = detector.getDataNode(sourceFieldName);
        IDataset dataset = dataNode.getDataset().getSlice();
        assertSame(dataNode, nxData.getDataNode(sourceFieldName));

        int[] shape = dataset.getShape();

        for (int i = 0; i < sizes.length; i++)
            assertEquals(sizes[i], shape[i]);

        // Make sure none of the numbers are NaNs. The detector
        // is expected to fill this scan with non-nulls.
        final PositionIterator it = new PositionIterator(shape);
        while (it.hasNext()) {
            int[] next = it.getPos();
            assertFalse(Double.isNaN(dataset.getDouble(next)));
        }

        // Check axes
        final IPosition pos = mod.getPositionIterable().iterator().next();
        final Collection<String> names = pos.getNames();

        // Append _value_demand to each name in list, then add detector axis fields to result
        List<String> expectedAxesNames = Stream.concat(names.stream().map(x -> x + "_value_set"),
                detectorDataFields.get(sourceFieldName).stream()).collect(Collectors.toList());
        assertAxes(nxData, expectedAxesNames.toArray(new String[expectedAxesNames.size()]));

        int[] defaultDimensionMappings = IntStream.range(0, sizes.length).toArray();
        int i = -1;
        for (String positionerName : names) {

            i++;
            NXpositioner positioner = instrument.getPositioner(positionerName);
            assertNotNull(positioner);
            dataNode = positioner.getDataNode("value_set");

            dataset = dataNode.getDataset().getSlice();
            shape = dataset.getShape();
            assertEquals(1, shape.length);
            assertEquals(sizes[i], shape[0]);

            String nxDataFieldName = positionerName + "_value_set";
            assertSame(dataNode, nxData.getDataNode(nxDataFieldName));
            assertIndices(nxData, nxDataFieldName, i);
            assertTarget(nxData, nxDataFieldName, rootNode,
                    "/entry/instrument/" + positionerName + "/value_set");

            // Actual values should be scanD
            dataNode = positioner.getDataNode(NXpositioner.NX_VALUE);
            dataset = dataNode.getDataset().getSlice();
            shape = dataset.getShape();
            assertArrayEquals(sizes, shape);

            nxDataFieldName = positionerName + "_" + NXpositioner.NX_VALUE;
            assertSame(dataNode, nxData.getDataNode(nxDataFieldName));
            assertIndices(nxData, nxDataFieldName, defaultDimensionMappings);
            assertTarget(nxData, nxDataFieldName, rootNode,
                    "/entry/instrument/" + positionerName + "/" + NXpositioner.NX_VALUE);
        }
    }
}

From source file:com.grarak.kerneladiutor.FileBrowserActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    fileBrowserActivity = this;
    boolean dark = Utils.getBoolean("darktheme", false, this);
    if (dark)//from w w  w  . j  ava 2 s . co  m
        super.setTheme(R.style.AppThemeDark);
    setContentView(R.layout.activity_filebrowser);

    setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    ActionBar actionBar;
    if ((actionBar = getSupportActionBar()) != null)
        actionBar.setDisplayHomeAsUpEnabled(true);

    String fileType = getIntent().getExtras().getString(FILE_TYPE_ARG);
    String externalStorage = Utils.getExternalStorage();

    LinkedHashMap<String, Fragment> fragments = new LinkedHashMap<>();
    internalStorage = StorageFragment.newInstance(Environment.getExternalStorageDirectory().getPath(),
            fileType);
    fragments.put(getString(R.string.internal_storage), internalStorage);
    if (externalStorage != null) {
        this.externalStorage = StorageFragment.newInstance(externalStorage, fileType);
        fragments.put(getString(R.string.external_storage), this.externalStorage);
    }

    mViewPager = (ViewPager) findViewById(R.id.view_pager);
    mViewPager.setAdapter(new Adapter(getSupportFragmentManager(), fragments));
    if (dark)
        mViewPager.setBackgroundColor(getResources().getColor(R.color.card_background_dark));

    final SlidingTabLayout mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
    mSlidingTabLayout.setCustomTabView(R.layout.tab_indicator, android.R.id.text1);
    for (int i = 0; i < fragments.keySet().toArray().length; i++)
        mSlidingTabLayout.setContentDescription(i, (String) fragments.keySet().toArray()[i]);
    mSlidingTabLayout.setSelectedIndicatorColors(
            getResources().getColor(fragments.size() > 1 ? R.color.white : R.color.color_primary));
    mSlidingTabLayout.setDistributeEvenly(true);
    mSlidingTabLayout.setViewPager(mViewPager);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setStatusBarColor(getResources().getColor(R.color.color_primary_dark));
    }
}

From source file:org.opencms.ui.dialogs.CmsNewDialog.java

/**
 * Initializes the view selector, using the given view id as an initial value.<p>
 *
 * @param startId the start view/*w  w  w .  j a  v a  2 s. com*/
 *
 * @return the start view
 */
private CmsElementView initViews(CmsUUID startId) {

    Map<CmsUUID, CmsElementView> viewMap = OpenCms.getADEManager().getElementViews(A_CmsUI.getCmsObject());
    List<CmsElementView> viewList = new ArrayList<CmsElementView>(viewMap.values());
    Collections.sort(viewList, new Comparator<CmsElementView>() {

        public int compare(CmsElementView arg0, CmsElementView arg1) {

            return ComparisonChain.start().compare(arg0.getOrder(), arg1.getOrder()).result();
        }

    });
    m_viewSelector.setItemCaptionMode(ItemCaptionMode.EXPLICIT);
    m_typeHelper = createTypeHelper();
    m_typeHelper.precomputeTypeLists(A_CmsUI.getCmsObject(), m_folderResource.getRootPath(),
            A_CmsUI.getCmsObject().getRequestContext().removeSiteRoot(m_folderResource.getRootPath()), viewList,
            null);

    // also collect types in LinkedHashMap to preserve order and ensure uniqueness
    LinkedHashMap<String, CmsResourceTypeBean> allTypes = Maps.newLinkedHashMap();

    for (CmsElementView view : viewList) {

        if (view.hasPermission(A_CmsUI.getCmsObject(), m_folderResource)) {

            List<CmsResourceTypeBean> typeBeans = m_typeHelper.getPrecomputedTypes(view);

            if (typeBeans.isEmpty()) {
                continue;
            }
            for (CmsResourceTypeBean typeBean : typeBeans) {
                allTypes.put(typeBean.getType(), typeBean);
            }
            m_viewSelector.addItem(view.getId());
            m_viewSelector.setItemCaption(view.getId(),
                    view.getTitle(A_CmsUI.getCmsObject(), A_CmsUI.get().getLocale()));
        }
    }
    m_viewSelector.addItem(VIEW_ALL.getId());
    m_viewSelector.setItemCaption(VIEW_ALL.getId(), CmsVaadinUtils.getMessageText(Messages.GUI_VIEW_ALL_0));
    m_allTypes = Lists.newArrayList(allTypes.values());
    if (allTypes.size() <= 8) {
        startId = ID_VIEW_ALL;
    }
    if (m_viewSelector.getItem(startId) == null) {
        startId = (CmsUUID) (m_viewSelector.getItemIds().iterator().next());
    }

    m_viewSelector.addValueChangeListener(new ValueChangeListener() {

        private static final long serialVersionUID = 1L;

        public void valueChange(ValueChangeEvent event) {

            CmsUUID viewId = (CmsUUID) (event.getProperty().getValue());
            CmsElementView selectedView;
            if (viewId.equals(ID_VIEW_ALL)) {
                selectedView = VIEW_ALL;
            } else {
                selectedView = OpenCms.getADEManager().getElementViews(A_CmsUI.getCmsObject())
                        .get(event.getProperty().getValue());
            }
            init(selectedView, m_defaultLocationCheckbox.getValue().booleanValue());
            if (selectedView != VIEW_ALL) {
                VaadinService.getCurrentRequest().getWrappedSession().setAttribute(SETTING_STANDARD_VIEW,
                        (event.getProperty().getValue()));
            }
        }
    });
    if (startId.equals(ID_VIEW_ALL)) {
        return VIEW_ALL;
    } else {
        return OpenCms.getADEManager().getElementViews(A_CmsUI.getCmsObject()).get(startId);
    }
}

From source file:hydrograph.ui.tooltip.tooltips.ComponentTooltip.java

/**
 * Show errors balloon in case property is having errors.
 * /*from w w  w. j  a  va2  s.com*/
 * @param propertyInfo
 * @param lblLinkProperty
 */
private void showErrors(PropertyToolTipInformation propertyInfo, Control lblLinkProperty) {
    if (propertyInfo.getErrorMessage() != null) {
        logger.debug("ComponentTooltip.showErrors() - Showing error balloon on property "
                + propertyInfo.getPropertyName() + ", Error: " + propertyInfo.getErrorMessage());
        ControlDecoration lblDecorator = WidgetUtility.addDecorator(lblLinkProperty,
                propertyInfo.getErrorMessage());
        if (LIST.equalsIgnoreCase(propertyInfo.getTooltipDataType())) {
            ArrayList<String> keyFieldList;
            LinkedHashMap<String, Object> secondaryKeysList;
            if (KEY_FIELDS.equalsIgnoreCase(propertyInfo.getPropertyName())
                    || OPERATION_FIELDS.equalsIgnoreCase(propertyInfo.getPropertyName())) {
                keyFieldList = (ArrayList<String>) propertyInfo.getPropertyValue();
                if (keyFieldList.size() == 0) {
                    lblDecorator.show();
                } else {
                    lblDecorator.hide();
                }
            }
            if (SECONDARY_KEYS.equalsIgnoreCase(propertyInfo.getPropertyName())
                    || KEY_FIELDS_SORT_COMPONENT.equalsIgnoreCase(propertyInfo.getPropertyName())) {
                secondaryKeysList = (LinkedHashMap<String, Object>) propertyInfo.getPropertyValue();
                if (secondaryKeysList.size() == 0) {
                    lblDecorator.show();
                } else {
                    lblDecorator.hide();
                }
            }

        } else if (propertyInfo.getPropertyValue() != null
                && StringUtils.equalsIgnoreCase(propertyInfo.getPropertyName().toString(), "PORT")) {
            if (propertyInfo.getPropertyValue().toString().matches(Constants.PORT_VALIDATION_REGEX)
                    || ParameterUtil.isParameter(propertyInfo.getPropertyValue().toString())) {
                lblDecorator.hide();
            } else {
                lblDecorator.show();
            }
        } else {
            if (propertyInfo.getPropertyValue() != null && (!propertyInfo.getPropertyValue().equals(""))) {
                lblDecorator.hide();
            } else {
                lblDecorator.show();
            }
        }
    }
}

From source file:org.opencb.opencga.storage.hadoop.variant.converters.HBaseToVariantConverter.java

protected Variant convert(Variant variant, List<VariantTableStudyRow> rows,
        Map<Integer, Map<Integer, VariantStats>> stats, VariantAnnotation annotation) {
    if (annotation == null) {
        annotation = new VariantAnnotation();
        annotation.setConsequenceTypes(Collections.emptyList());
    }//from  w w w . j a  v  a2 s.  co m
    if (failOnEmptyVariants && rows.isEmpty()) {
        throw new IllegalStateException("No Row columns supplied for row " + variant);
    }
    for (VariantTableStudyRow row : rows) {
        Map<String, String> attributesMap = new HashMap<>();
        Integer studyId = row.getStudyId();
        QueryResult<StudyConfiguration> queryResult = scm.getStudyConfiguration(studyId, scmOptions);
        if (queryResult.getResult().isEmpty()) {
            throw new IllegalStateException("No study found for study ID: " + studyId);
        }
        StudyConfiguration studyConfiguration = queryResult.first();

        LinkedHashMap<String, Integer> returnedSamplesPosition = getReturnedSamplesPosition(studyConfiguration);
        if (mutableSamplesPosition) {
            returnedSamplesPosition = new LinkedHashMap<>(returnedSamplesPosition);
        }
        //            Do not throw any exception. It may happen that the study is not loaded yet or no samples are required!
        //            if (returnedSamplesPosition.isEmpty()) {
        //                throw new IllegalStateException("No samples found for study!!!");
        //            }

        BiMap<String, Integer> loadedSamples = StudyConfiguration.getIndexedSamples(studyConfiguration);

        List<String> format = Arrays.asList(VariantMerger.GT_KEY, VariantMerger.GENOTYPE_FILTER_KEY);
        int gtIdx = format.indexOf(VariantMerger.GT_KEY);
        int ftIdx = format.indexOf(VariantMerger.GENOTYPE_FILTER_KEY);

        int loadedSamplesSize = loadedSamples.size();
        calculatePassCallRates(row, attributesMap, loadedSamplesSize);

        Integer nSamples = returnedSamplesPosition.size();

        @SuppressWarnings("unchecked")
        List<String>[] samplesDataArray = new List[nSamples];

        Set<Integer> sampleWithVariant = new HashSet<>();
        BiMap<Integer, String> mapSampleIds = studyConfiguration.getSampleIds().inverse();
        for (String genotype : row.getGenotypes()) {
            sampleWithVariant.addAll(row.getSampleIds(genotype));
            if (genotype.equals(VariantTableStudyRow.OTHER)) {
                continue; // skip OTHER -> see Complex type
            }
            for (Integer sampleId : row.getSampleIds(genotype)) {
                String sampleName = mapSampleIds.get(sampleId);
                Integer sampleIdx = returnedSamplesPosition.get(sampleName);
                if (sampleIdx == null) {
                    continue; //Sample may not be required. Ignore this sample.
                }
                List<String> lst = Arrays.asList(genotype, VariantMerger.PASS_VALUE);
                samplesDataArray[sampleIdx] = lst;
            }
        }

        // Load Secondary Index
        List<VariantProto.AlternateCoordinate> s2cgt = row.getComplexVariant().getSecondaryAlternatesList();
        int secondaryAlternatesCount = row.getComplexVariant().getSecondaryAlternatesCount();
        List<AlternateCoordinate> secAltArr = new ArrayList<AlternateCoordinate>(secondaryAlternatesCount);
        if (secondaryAlternatesCount > 0) {
            for (VariantProto.AlternateCoordinate altcoord : s2cgt) {
                VariantType vart = VariantType.valueOf(altcoord.getType().name());
                String chr = StringUtils.isEmpty(altcoord.getChromosome()) ? variant.getChromosome()
                        : altcoord.getChromosome();
                Integer start = altcoord.getStart() == 0 ? variant.getStart() : altcoord.getStart();
                Integer end = altcoord.getEnd() == 0 ? variant.getEnd() : altcoord.getEnd();
                String reference = StringUtils.isEmpty(altcoord.getReference()) ? "" : altcoord.getReference();
                String alternate = StringUtils.isEmpty(altcoord.getAlternate()) ? "" : altcoord.getAlternate();
                AlternateCoordinate alt = new AlternateCoordinate(chr, start, end, reference, alternate, vart);
                secAltArr.add(alt);
            }
        }
        // Load complex genotypes
        for (Entry<Integer, String> entry : row.getComplexVariant().getSampleToGenotype().entrySet()) {
            sampleWithVariant.add(entry.getKey());
            Integer samplePosition = getSamplePosition(returnedSamplesPosition, mapSampleIds, entry.getKey());
            if (samplePosition == null) {
                continue; //Sample may not be required. Ignore this sample.
            }
            String genotype = entry.getValue();
            String returnedGenotype;
            // FIXME: Decide what to do with lists of genotypes
            if (simpleGenotypes) {
                returnedGenotype = getSimpleGenotype(genotype);
                logger.debug("Return simplified genotype: {} -> {}", genotype, returnedGenotype);
            } else {
                returnedGenotype = genotype;
            }
            samplesDataArray[samplePosition] = Arrays.asList(returnedGenotype, VariantMerger.PASS_VALUE);
        }

        // Fill gaps (with HOM_REF)
        int gapCounter = 0;
        for (int i = 0; i < samplesDataArray.length; i++) {
            if (samplesDataArray[i] == null) {
                ++gapCounter;
                samplesDataArray[i] = Arrays.asList(VariantTableStudyRow.HOM_REF, VariantMerger.PASS_VALUE);
            }
        }

        // Set pass field
        int passCount = loadedSamplesSize;
        for (Entry<String, SampleList> entry : row.getComplexFilter().getFilterNonPass().entrySet()) {
            String filterString = entry.getKey();
            passCount -= entry.getValue().getSampleIdsCount();
            for (Integer id : entry.getValue().getSampleIdsList()) {
                Integer samplePosition = getSamplePosition(returnedSamplesPosition, mapSampleIds, id);
                if (samplePosition == null) {
                    continue; // Sample may not be required. Ignore this sample.
                }
                samplesDataArray[samplePosition].set(ftIdx, filterString);
            }
        }

        // Check pass count
        if (passCount != row.getPassCount()) {
            String message = String.format(
                    "Error parsing variant %s. Pass count %s does not match filter fill count: %s using %s loaded samples.",
                    row.toString(), row.getPassCount(), passCount, loadedSamplesSize);
            wrongVariant(message);
        }

        // Check homRef count
        int homRefCount = loadedSamplesSize;
        homRefCount -= sampleWithVariant.size();
        if (homRefCount != row.getHomRefCount()) {
            String message = "Wrong number of HomRef samples for variant " + variant + ". Got " + homRefCount
                    + ", expect " + row.getHomRefCount() + ". Samples number: " + samplesDataArray.length
                    + " , ";
            message += "'" + VariantTableStudyRow.HOM_REF + "':" + row.getHomRefCount() + " , ";
            for (String studyColumn : VariantTableStudyRow.GENOTYPE_COLUMNS) {
                message += "'" + studyColumn + "':" + row.getSampleIds(studyColumn) + " , ";
            }
            wrongVariant(message);
        }

        List<List<String>> samplesData = Arrays.asList(samplesDataArray);

        StudyEntry studyEntry;
        if (studyNameAsStudyId) {
            studyEntry = new StudyEntry(studyConfiguration.getStudyName());
        } else {
            studyEntry = new StudyEntry(Integer.toString(studyConfiguration.getStudyId()));
        }
        studyEntry.setSortedSamplesPosition(returnedSamplesPosition);
        studyEntry.setSamplesData(samplesData);
        studyEntry.setFormat(format);
        studyEntry.setFiles(Collections.singletonList(new FileEntry("", "", attributesMap)));
        studyEntry.setSecondaryAlternates(secAltArr);

        Map<Integer, VariantStats> convertedStatsMap = stats.get(studyConfiguration.getStudyId());
        if (convertedStatsMap != null) {
            Map<String, VariantStats> statsMap = new HashMap<>(convertedStatsMap.size());
            for (Entry<Integer, VariantStats> entry : convertedStatsMap.entrySet()) {
                String cohortName = studyConfiguration.getCohortIds().inverse().get(entry.getKey());
                statsMap.put(cohortName, entry.getValue());
            }
            studyEntry.setStats(statsMap);
        }

        variant.addStudyEntry(studyEntry);
    }
    variant.setAnnotation(annotation);
    if (StringUtils.isNotEmpty(annotation.getId())) {
        variant.setId(annotation.getId());
    } else {
        variant.setId(variant.toString());
    }
    if (failOnEmptyVariants && variant.getStudies().isEmpty()) {
        throw new IllegalStateException("No Studies registered for variant!!! " + variant);
    }
    return variant;
}

From source file:ubic.gemma.core.datastructure.matrix.ExpressionDataMatrixColumnSort.java

/**
 * Divide the biomaterials up into chunks based on the experimental factor given, keeping everybody in order. If the
 * factor is continuous, there is just one chunk.
 *
 * @return ordered map of fv->bm where fv is of ef, or null if it couldn't be done properly.
 *//*from  w ww  .  j  a v  a  2s.  c o m*/
private static LinkedHashMap<FactorValue, List<BioMaterial>> chunkOnFactor(ExperimentalFactor ef,
        List<BioMaterial> bms) {

    if (bms == null) {
        return null;
    }

    LinkedHashMap<FactorValue, List<BioMaterial>> chunks = new LinkedHashMap<>();

    /*
     * Get the factor values in the order we have things right now
     */
    for (BioMaterial bm : bms) {
        for (FactorValue fv : bm.getFactorValues()) {
            if (!ef.getFactorValues().contains(fv)) {
                continue;
            }
            if (chunks.keySet().contains(fv)) {
                continue;
            }
            chunks.put(fv, new ArrayList<BioMaterial>());
        }
    }

    /*
     * What if bm doesn't have a value for the factorvalue. Need a dummy value.
     */
    FactorValue dummy = FactorValue.Factory.newInstance(ef);
    dummy.setValue("");
    dummy.setId(-1L);
    chunks.put(dummy, new ArrayList<BioMaterial>());

    for (BioMaterial bm : bms) {
        boolean found = false;
        for (FactorValue fv : bm.getFactorValues()) {
            if (ef.getFactorValues().contains(fv)) {
                found = true;
                assert chunks.containsKey(fv);
                chunks.get(fv).add(bm);
            }
        }

        if (!found) {
            if (ExpressionDataMatrixColumnSort.log.isDebugEnabled())
                ExpressionDataMatrixColumnSort.log
                        .debug(bm + " has no value for factor=" + ef + "; using dummy value");
            chunks.get(dummy).add(bm);
        }

    }

    if (chunks.get(dummy).size() == 0) {
        if (ExpressionDataMatrixColumnSort.log.isDebugEnabled())
            ExpressionDataMatrixColumnSort.log.debug("removing dummy");
        chunks.remove(dummy);
    }

    ExpressionDataMatrixColumnSort.log
            .debug(chunks.size() + " chunks for " + ef + ", from current chunk of size " + bms.size());

    /*
     * Sanity check
     */
    int total = 0;
    for (FactorValue fv : chunks.keySet()) {
        List<BioMaterial> chunk = chunks.get(fv);
        total += chunk.size();
    }

    assert total == bms.size() : "expected " + bms.size() + ", got " + total;

    return chunks;
}

From source file:lob.VisualisationGUI.java

public void updatePriceTable(LinkedHashMap<Float, Long> askTree, LinkedHashMap<Float, Long> bidTree) {
    //Clear old entries
    clearTable(jTable2);//from  w  w w  .ja  v a 2 s. co m

    //Get the number of points on each side
    int numberAskPoints = askTree.size();
    int numberBidPoints = bidTree.size();

    int currentTableRow = 7;

    //Fill ask entries
    for (Map.Entry<Float, Long> entry : askTree.entrySet()) {

        float key = entry.getKey();
        long value = entry.getValue();
        jTable2.getModel().setValueAt(key, currentTableRow, 2);
        jTable2.getModel().setValueAt(value, currentTableRow, 1);
        currentTableRow--;
        if (currentTableRow < 1)
            break;
    }

    //Fill bid entries
    currentTableRow = 8 + numberBidPoints;
    for (Map.Entry<Float, Long> entry : bidTree.entrySet()) {

        float key = entry.getKey();
        long value = entry.getValue();
        jTable2.getModel().setValueAt(key, currentTableRow, 0);
        jTable2.getModel().setValueAt(value, currentTableRow, 1);
        currentTableRow--;
        if (currentTableRow < 9)
            break;
    }

}