Example usage for java.util TreeMap get

List of usage examples for java.util TreeMap get

Introduction

In this page you can find the example usage for java.util TreeMap get.

Prototype

public V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:org.apache.hadoop.yarn.client.api.impl.AMRMClientImpl.java

private void addResourceRequest(Priority priority, String resourceName, Resource capability, T req,
        boolean relaxLocality, String labelExpression) {
    Map<String, TreeMap<Resource, ResourceRequestInfo>> remoteRequests = this.remoteRequestsTable.get(priority);
    if (remoteRequests == null) {
        remoteRequests = new HashMap<String, TreeMap<Resource, ResourceRequestInfo>>();
        this.remoteRequestsTable.put(priority, remoteRequests);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Added priority=" + priority);
        }/*  www .java 2s .c om*/
    }
    TreeMap<Resource, ResourceRequestInfo> reqMap = remoteRequests.get(resourceName);
    if (reqMap == null) {
        // capabilities are stored in reverse sorted order. smallest last.
        reqMap = new TreeMap<Resource, ResourceRequestInfo>(
                new ResourceReverseMemoryThenCpuThenGpuComparator());
        remoteRequests.put(resourceName, reqMap);
    }
    ResourceRequestInfo resourceRequestInfo = reqMap.get(capability);
    if (resourceRequestInfo == null) {
        resourceRequestInfo = new ResourceRequestInfo(priority, resourceName, capability, relaxLocality);
        reqMap.put(capability, resourceRequestInfo);
    }

    resourceRequestInfo.remoteRequest
            .setNumContainers(resourceRequestInfo.remoteRequest.getNumContainers() + 1);

    if (relaxLocality) {
        resourceRequestInfo.containerRequests.add(req);
    }

    if (ResourceRequest.ANY.equals(resourceName)) {
        resourceRequestInfo.remoteRequest.setNodeLabelExpression(labelExpression);
    }

    // Note this down for next interaction with ResourceManager
    addResourceRequestToAsk(resourceRequestInfo.remoteRequest);

    if (LOG.isDebugEnabled()) {
        LOG.debug("addResourceRequest:" + " applicationId=" + " priority=" + priority.getPriority()
                + " resourceName=" + resourceName + " numContainers="
                + resourceRequestInfo.remoteRequest.getNumContainers() + " #asks=" + ask.size());
    }
}

From source file:net.spfbl.core.Analise.java

public static void load() {
    long time = System.currentTimeMillis();
    File file = new File("./data/analise.set");
    if (file.exists()) {
        try {/* w w w .ja v a 2s  .  c om*/
            TreeSet<Analise> set;
            FileInputStream fileInputStream = new FileInputStream(file);
            try {
                set = SerializationUtils.deserialize(fileInputStream);
            } finally {
                fileInputStream.close();
            }
            for (Analise analise : set) {
                try {
                    if (analise.semaphoreSet == null) {
                        analise.semaphoreSet = new Semaphore(1);
                    }
                    analise.ipSet.addAll(analise.processSet);
                    analise.processSet.clear();
                    add(analise);
                } catch (Exception ex) {
                    Server.logError(ex);
                }
            }
            Server.logLoad(time, file);
        } catch (Exception ex) {
            Server.logError(ex);
        }
    }
    time = System.currentTimeMillis();
    file = new File("./data/cluster.map");
    if (file.exists()) {
        try {
            TreeMap<String, Short[]> map;
            FileInputStream fileInputStream = new FileInputStream(file);
            try {
                map = SerializationUtils.deserialize(fileInputStream);
            } finally {
                fileInputStream.close();
            }
            for (String token : map.keySet()) {
                Short[] value = map.get(token);
                if (token.contains("#") || token.contains(".H.")) {
                    String hostname = token.replace("#", "0");
                    hostname = hostname.replace(".H.", ".0a.");
                    if (Domain.isHostname(hostname)) {
                        clusterMap.put(token, value);
                    }
                } else if (Owner.isOwnerCPF(token.substring(1))) {
                    String ownerID = Owner.normalizeID(token.substring(1));
                    clusterMap.put(ownerID, value);
                } else if (Owner.isOwnerID(token)) {
                    String ownerID = Owner.normalizeID(token);
                    clusterMap.put(ownerID, value);
                } else if (Subnet.isValidCIDR(token)) {
                    clusterMap.put(token, value);
                } else if (Domain.isHostname(token)) {
                    String hostname = Domain.normalizeHostname(token, true);
                    if (Domain.isOfficialTLD(hostname) && !hostname.endsWith(".br")) {
                        clusterMap.put(hostname, value);
                    }
                }
            }
            Server.logLoad(time, file);
        } catch (Exception ex) {
            Server.logError(ex);
        }
    }
}

From source file:com.opengamma.bloombergexample.loader.DemoEquityOptionCollarPortfolioLoader.java

private void addNodes(ManageablePortfolioNode rootNode, String underlying, boolean includeUnderlying,
        Period[] expiries) {/*from  w ww.  ja  v  a 2s .  c  om*/
    ExternalId ticker = ExternalSchemes.bloombergTickerSecurityId(underlying);
    ManageableSecurity underlyingSecurity = null;
    if (includeUnderlying) {
        underlyingSecurity = getOrLoadEquity(ticker);
    }

    ExternalIdBundle bundle = underlyingSecurity == null ? ExternalIdBundle.of(ticker)
            : underlyingSecurity.getExternalIdBundle();
    HistoricalTimeSeriesInfoDocument timeSeriesInfo = getOrLoadTimeSeries(ticker, bundle);
    double estimatedCurrentStrike = getOrLoadMostRecentPoint(timeSeriesInfo);
    Set<ExternalId> optionChain = getOptionChain(ticker);

    //TODO: reuse positions/nodes?
    String longName = underlyingSecurity == null ? "" : underlyingSecurity.getName();
    String formattedName = MessageFormatter.format("[{}] {}", underlying, longName);
    ManageablePortfolioNode equityNode = new ManageablePortfolioNode(formattedName);

    BigDecimal underlyingAmount = VALUE_OF_UNDERLYING.divide(BigDecimal.valueOf(estimatedCurrentStrike),
            BigDecimal.ROUND_HALF_EVEN);

    if (includeUnderlying) {
        addPosition(equityNode, underlyingAmount, ticker);
    }

    TreeMap<LocalDate, Set<BloombergTickerParserEQOption>> optionsByExpiry = new TreeMap<LocalDate, Set<BloombergTickerParserEQOption>>();
    for (ExternalId optionTicker : optionChain) {
        s_logger.debug("Got option {}", optionTicker);

        BloombergTickerParserEQOption optionInfo = BloombergTickerParserEQOption.getOptionParser(optionTicker);
        s_logger.debug("Got option info {}", optionInfo);

        LocalDate key = optionInfo.getExpiry();
        Set<BloombergTickerParserEQOption> set = optionsByExpiry.get(key);
        if (set == null) {
            set = new HashSet<BloombergTickerParserEQOption>();
            optionsByExpiry.put(key, set);
        }
        set.add(optionInfo);
    }
    Set<ExternalId> tickersToLoad = new HashSet<ExternalId>();

    BigDecimal expiryCount = BigDecimal.valueOf(expiries.length);
    BigDecimal defaultAmountAtExpiry = underlyingAmount.divide(expiryCount, BigDecimal.ROUND_DOWN);
    BigDecimal spareAmountAtExpiry = defaultAmountAtExpiry.add(BigDecimal.ONE);
    int spareCount = underlyingAmount.subtract(defaultAmountAtExpiry.multiply(expiryCount)).intValue();

    for (int i = 0; i < expiries.length; i++) {
        Period bucketPeriod = expiries[i];

        ManageablePortfolioNode bucketNode = new ManageablePortfolioNode(bucketPeriod.toString().substring(1));

        LocalDate nowish = LocalDate.now().withDayOfMonth(20); //This avoids us picking different options every time this script is run
        LocalDate targetExpiry = nowish.plus(bucketPeriod);
        LocalDate chosenExpiry = optionsByExpiry.floorKey(targetExpiry);
        if (chosenExpiry == null) {
            s_logger.warn("No options for {} on {}", targetExpiry, underlying);
            continue;
        }
        s_logger.info("Using time {} for bucket {} ({})",
                new Object[] { chosenExpiry, bucketPeriod, targetExpiry });

        Set<BloombergTickerParserEQOption> optionsAtExpiry = optionsByExpiry.get(chosenExpiry);
        TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> optionsByStrike = new TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (BloombergTickerParserEQOption option : optionsAtExpiry) {
            //        s_logger.info("option {}", option);
            double key = option.getStrike();
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(key);
            if (pair == null) {
                pair = Pair.of(null, null);
            }
            if (option.getOptionType() == OptionType.CALL) {
                pair = Pair.of(option, pair.getSecond());
            } else {
                pair = Pair.of(pair.getFirst(), option);
            }
            optionsByStrike.put(key, pair);
        }

        //cascading collar?
        BigDecimal amountAtExpiry = spareCount-- > 0 ? spareAmountAtExpiry : defaultAmountAtExpiry;

        s_logger.info(" est strike {}", estimatedCurrentStrike);
        Double[] strikes = optionsByStrike.keySet().toArray(new Double[0]);

        int strikeIndex = Arrays.binarySearch(strikes, estimatedCurrentStrike);
        if (strikeIndex < 0) {
            strikeIndex = -(1 + strikeIndex);
        }
        s_logger.info("strikes length {} index {} strike of index {}",
                new Object[] { Integer.valueOf(strikes.length), Integer.valueOf(strikeIndex),
                        Double.valueOf(strikes[strikeIndex]) });

        int minIndex = strikeIndex - _numOptions;
        minIndex = Math.max(0, minIndex);
        int maxIndex = strikeIndex + _numOptions;
        maxIndex = Math.min(strikes.length - 1, maxIndex);

        s_logger.info("min {} max {}", Integer.valueOf(minIndex), Integer.valueOf(maxIndex));
        StringBuffer sb = new StringBuffer("strikes: [");
        for (int j = minIndex; j <= maxIndex; j++) {
            sb.append(" ");
            sb.append(strikes[j]);
        }
        sb.append(" ]");
        s_logger.info(sb.toString());

        //Short Calls
        ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> calls = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (int j = minIndex; j < strikeIndex; j++) {
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike
                    .get(strikes[j]);
            if (pair == null) {
                throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]);
            }
            calls.add(pair);
        }
        spreadOptions(bucketNode, calls, OptionType.CALL, -1, tickersToLoad, amountAtExpiry, includeUnderlying,
                calls.size());

        // Long Puts
        ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> puts = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (int j = strikeIndex + 1; j <= maxIndex; j++) {
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike
                    .get(strikes[j]);
            if (pair == null) {
                throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]);
            }
            puts.add(pair);
        }
        spreadOptions(bucketNode, puts, OptionType.PUT, 1, tickersToLoad, amountAtExpiry, includeUnderlying,
                puts.size());

        if (bucketNode.getChildNodes().size() + bucketNode.getPositionIds().size() > 0) {
            equityNode.addChildNode(bucketNode); //Avoid generating empty nodes   
        }
    }

    for (ExternalId optionTicker : tickersToLoad) {
        ManageableSecurity loaded = getOrLoadSecurity(optionTicker);
        if (loaded == null) {
            throw new OpenGammaRuntimeException("Unexpected option type " + loaded);
        }

        //TODO [LAPANA-29] Should be able to do this for index options too
        if (includeUnderlying) {
            try {
                HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(optionTicker,
                        loaded.getExternalIdBundle());
                if (loadedTs == null) {
                    throw new OpenGammaRuntimeException("Failed to get time series for " + loaded);
                }
            } catch (Exception ex) {
                s_logger.error("Failed to get time series for " + loaded, ex);
            }
        }
    }

    if (equityNode.getPositionIds().size() + equityNode.getChildNodes().size() > 0) {
        rootNode.addChildNode(equityNode);
    }
}

From source file:com.cyberway.issue.crawler.admin.StatisticsTracker.java

protected void writeMimetypesReportTo(PrintWriter writer) {
    // header/*  w w  w. jav a 2  s .  c  o  m*/
    writer.print("[#urls] [#bytes] [mime-types]\n");
    TreeMap fd = getReverseSortedCopy(getFileDistribution());
    for (Iterator i = fd.keySet().iterator(); i.hasNext();) {
        Object key = i.next();
        // Key is mime type.
        writer.print(Long.toString(((LongWrapper) fd.get(key)).longValue));
        writer.print(" ");
        writer.print(Long.toString(getBytesPerFileType((String) key)));
        writer.print(" ");
        writer.print((String) key);
        writer.print("\n");
    }
}

From source file:io.mapzone.arena.analytics.graph.ui.GraphPanel.java

@Override
public void createContents(final Composite parent) {
    try {//from   ww  w .j a va2s .c  o  m
        if (!featureLayer.isPresent()) {
            tk().createFlowText(parent, i18n.get("noFeatures"));
            return;
        }
        // this.parent = parent;
        parent.setLayout(FormLayoutFactory.defaults().create());

        MdToolbar2 toolbar = tk().createToolbar(parent, SWT.TOP);
        new NodeStylerItem(toolbar);
        new EdgeStylerItem(toolbar);

        final TreeMap<String, GraphFunction> functions = Maps.newTreeMap();
        for (Class<GraphFunction> cl : AVAILABLE_FUNCTIONS) {
            try {
                GraphFunction function = cl.newInstance();
                functions.put(function.title(), function);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        final Composite functionContainer = tk().createComposite(parent, SWT.NONE);

        final ComboViewer combo = new ComboViewer(parent,
                SWT.SINGLE | SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY);
        combo.setContentProvider(new ArrayContentProvider());
        combo.setInput(functions.keySet());
        combo.addSelectionChangedListener(ev -> {
            String selected = SelectionAdapter.on(ev.getSelection()).first(String.class).get();
            GraphFunction function = functions.get(selected);

            FormDataFactory.on(functionContainer).top(combo.getCombo(), 5).height(function.preferredHeight())
                    .left(0).right(100);

            UIUtils.disposeChildren(functionContainer);
            // create panel
            //                Section section = tk().createSection( functionContainer, function.description(), ExpandableComposite.TREE_NODE, Section.SHORT_TITLE_BAR, Section.FOCUS_TITLE, SWT.BORDER );
            //                section.setBackground( UIUtils.getColor( 235,  235, 235) );
            //                ((Composite)section.getClient()).setLayout( FormLayoutFactory.defaults().create() );

            IPanelSection section = tk().createPanelSection(functionContainer, function.description(),
                    SWT.Expand, IPanelSection.EXPANDABLE);
            section.getControl().setBackground(UIUtils.getColor(235, 235, 235));
            section.getBody().setBackground(UIUtils.getColor(235, 235, 235));
            section.setExpanded(true);
            section.getBody().setLayout(FormLayoutFactory.defaults().create());

            //
            graph.clear();
            function.createContents(tk(), section.getBody(), graph);
            if (!section.isExpanded()) {
                section.setExpanded(true);
            }

            FormDataFactory.on(section.getBody()).fill();

            // functionContainer.layout();
            parent.layout();
        });

        //
        // mapContainer
        mapContainer = tk().createComposite(parent, SWT.NONE);
        mapContainer.setLayout(new FillLayout());
        if (mapViewer != null) {
            mapViewer.dispose();
        }
        createMapViewer();

        // layout
        on(toolbar.getControl()).left(0, 3).right(100, -3).top(0, 5);

        final Label selectLabel = tk().createLabel(parent, i18n.get("selectFunction"), SWT.NONE);
        on(selectLabel).top(toolbar.getControl(), 8).left(1);
        on(combo.getCombo()).top(selectLabel, 2).left(1);
        on(functionContainer).top(combo.getCombo(), 5).height(0).left(0).right(100);
        on(mapContainer).fill().top(functionContainer, 5);
    } catch (Exception e) {
        StatusDispatcher.handleError("", e);
    }
}

From source file:com.askjeffreyliu.camera2barcode.camera.CameraSource.java

private Size getBestAspectPictureSize(android.util.Size[] supportedPictureSizes) {
    float targetRatio = Utils.getScreenRatio(mContext);
    Size bestSize = null;/*from ww  w  .  j av  a  2s . c  o m*/
    TreeMap<Double, List> diffs = new TreeMap<>();

    for (android.util.Size size : supportedPictureSizes) {
        float ratio = (float) size.getWidth() / size.getHeight();
        double diff = Math.abs(ratio - targetRatio);
        if (diff < maxRatioTolerance) {
            if (diffs.keySet().contains(diff)) {
                //add the value to the list
                diffs.get(diff).add(size);
            } else {
                List newList = new ArrayList<>();
                newList.add(size);
                diffs.put(diff, newList);
            }
        }
    }

    //diffs now contains all of the usable sizes
    //now let's see which one has the least amount of
    for (Map.Entry entry : diffs.entrySet()) {
        List<android.util.Size> entries = (List) entry.getValue();
        for (android.util.Size s : entries) {
            if (bestSize == null) {
                bestSize = new Size(s.getWidth(), s.getHeight());
            } else if (bestSize.getWidth() < s.getWidth() || bestSize.getHeight() < s.getHeight()) {
                bestSize = new Size(s.getWidth(), s.getHeight());
            }
        }
    }
    return bestSize;
}

From source file:cc.slda.DisplayTopic.java

@SuppressWarnings("unchecked")
public int run(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(Settings.HELP_OPTION, false, "print the help message");
    options.addOption(OptionBuilder.withArgName(Settings.PATH_INDICATOR).hasArg()
            .withDescription("input beta file").create(Settings.INPUT_OPTION));
    options.addOption(OptionBuilder.withArgName(Settings.PATH_INDICATOR).hasArg()
            .withDescription("term index file").create(ParseCorpus.INDEX));
    options.addOption(OptionBuilder.withArgName(Settings.INTEGER_INDICATOR).hasArg()
            .withDescription("display top terms only (default - 10)").create(TOP_DISPLAY_OPTION));

    String betaString = null;//from  w  w  w  . j av  a2  s  .  co  m
    String indexString = null;
    int topDisplay = TOP_DISPLAY;

    CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(Settings.HELP_OPTION)) {
            formatter.printHelp(ParseCorpus.class.getName(), options);
            System.exit(0);
        }

        if (line.hasOption(Settings.INPUT_OPTION)) {
            betaString = line.getOptionValue(Settings.INPUT_OPTION);
        } else {
            throw new ParseException("Parsing failed due to " + Settings.INPUT_OPTION + " not initialized...");
        }

        if (line.hasOption(ParseCorpus.INDEX)) {
            indexString = line.getOptionValue(ParseCorpus.INDEX);
        } else {
            throw new ParseException("Parsing failed due to " + ParseCorpus.INDEX + " not initialized...");
        }

        if (line.hasOption(TOP_DISPLAY_OPTION)) {
            topDisplay = Integer.parseInt(line.getOptionValue(TOP_DISPLAY_OPTION));
        }
    } catch (ParseException pe) {
        System.err.println(pe.getMessage());
        formatter.printHelp(ParseCorpus.class.getName(), options);
        System.exit(0);
    } catch (NumberFormatException nfe) {
        System.err.println(nfe.getMessage());
        System.exit(0);
    }

    JobConf conf = new JobConf(DisplayTopic.class);
    FileSystem fs = FileSystem.get(conf);

    Path indexPath = new Path(indexString);
    Preconditions.checkArgument(fs.exists(indexPath) && fs.isFile(indexPath), "Invalid index path...");

    Path betaPath = new Path(betaString);
    Preconditions.checkArgument(fs.exists(betaPath) && fs.isFile(betaPath), "Invalid beta path...");

    SequenceFile.Reader sequenceFileReader = null;
    try {
        IntWritable intWritable = new IntWritable();
        Text text = new Text();
        Map<Integer, String> termIndex = new HashMap<Integer, String>();
        sequenceFileReader = new SequenceFile.Reader(fs, indexPath, conf);
        while (sequenceFileReader.next(intWritable, text)) {
            termIndex.put(intWritable.get(), text.toString());
        }

        PairOfIntFloat pairOfIntFloat = new PairOfIntFloat();
        // HMapIFW hmap = new HMapIFW();
        HMapIDW hmap = new HMapIDW();
        TreeMap<Double, Integer> treeMap = new TreeMap<Double, Integer>();
        sequenceFileReader = new SequenceFile.Reader(fs, betaPath, conf);
        while (sequenceFileReader.next(pairOfIntFloat, hmap)) {
            treeMap.clear();

            System.out.println("==============================");
            System.out.println(
                    "Top ranked " + topDisplay + " terms for Topic " + pairOfIntFloat.getLeftElement());
            System.out.println("==============================");

            Iterator<Integer> itr1 = hmap.keySet().iterator();
            int temp1 = 0;
            while (itr1.hasNext()) {
                temp1 = itr1.next();
                treeMap.put(-hmap.get(temp1), temp1);
                if (treeMap.size() > topDisplay) {
                    treeMap.remove(treeMap.lastKey());
                }
            }

            Iterator<Double> itr2 = treeMap.keySet().iterator();
            double temp2 = 0;
            while (itr2.hasNext()) {
                temp2 = itr2.next();
                if (termIndex.containsKey(treeMap.get(temp2))) {
                    System.out.println(termIndex.get(treeMap.get(temp2)) + "\t\t" + -temp2);
                } else {
                    System.out.println("How embarrassing! Term index not found...");
                }
            }
        }
    } finally {
        IOUtils.closeStream(sequenceFileReader);
    }

    return 0;
}

From source file:ANNFileDetect.EncogTestClass.java

public MLData runNet(String fileToExamine, BasicNetwork nn, boolean wantGraph, int graphMinima)
        throws IOException {
    double[] output = new double[] { 0.0 };
    System.out.println("File: " + fileToExamine);
    TreeMap<Double, Integer> ht = new TreeMap<Double, Integer>();
    FileOperations fo = new FileOperations();
    int inputNeurons = nn.getInputCount();
    int outputNeurons = nn.getOutputCount();
    byte[] file = fo.fileToByte(fileToExamine);
    filebytes = file.length;/*from  www. j  av a 2 s. com*/
    double[][] fileMatrix = fo.DoubleMatrix(file, inputNeurons, 0);
    double[][] Output = new double[fileMatrix.length][];
    for (int i = 0; i < fileMatrix.length; i++) {
        Output[i] = output;
    }
    MLDataSet trainingSet = new BasicMLDataSet(fileMatrix, Output);
    MLData out = null;
    double[] average = new double[outputNeurons];
    for (MLDataPair pair : trainingSet) {
        out = nn.compute(pair.getInput());
        //System.out.println("Output Computed for file: " + fileToExamine + ": ");
        for (int a = 0; a < outputNeurons; a++) {
            average[a] = (average[a] + out.getData(a)) / 2;
            Double tst = hashDbl(out.getData(a));
            if (ht.containsKey(tst)) {
                ht.put(tst, (ht.get(tst) + 1));
            } else {
                ht.put(tst, 1);
            }
        }
    }
    if (wantGraph) {
        drawchart(ht, fileToExamine, graphMinima);
    } else {
        createReport(ht, fileToExamine);
    }

    for (int i = 0; i < average.length; i++) {
        System.out.println("Neuron" + i + ": " + average[i]);
    }
    return out;
}

From source file:com.opengamma.examples.bloomberg.loader.DemoEquityOptionCollarPortfolioLoader.java

private void addNodes(final ManageablePortfolioNode rootNode, final String underlying,
        final boolean includeUnderlying, final Period[] expiries) {
    final ExternalId ticker = ExternalSchemes.bloombergTickerSecurityId(underlying);
    ManageableSecurity underlyingSecurity = null;
    if (includeUnderlying) {
        underlyingSecurity = getOrLoadEquity(ticker);
    }//from  w w w .jav  a 2s.c  om

    final ExternalIdBundle bundle = underlyingSecurity == null ? ExternalIdBundle.of(ticker)
            : underlyingSecurity.getExternalIdBundle();
    final HistoricalTimeSeriesInfoDocument timeSeriesInfo = getOrLoadTimeSeries(ticker, bundle);
    final double estimatedCurrentStrike = getOrLoadMostRecentPoint(timeSeriesInfo);
    final Set<ExternalId> optionChain = getOptionChain(ticker);

    //TODO: reuse positions/nodes?
    final String longName = underlyingSecurity == null ? "" : underlyingSecurity.getName();
    final String formattedName = MessageFormatter.format("[{}] {}", underlying, longName).getMessage();
    final ManageablePortfolioNode equityNode = new ManageablePortfolioNode(formattedName);

    final BigDecimal underlyingAmount = VALUE_OF_UNDERLYING.divide(BigDecimal.valueOf(estimatedCurrentStrike),
            BigDecimal.ROUND_HALF_EVEN);

    if (includeUnderlying) {
        addPosition(equityNode, underlyingAmount, ticker);
    }

    final TreeMap<LocalDate, Set<BloombergTickerParserEQOption>> optionsByExpiry = new TreeMap<LocalDate, Set<BloombergTickerParserEQOption>>();
    for (final ExternalId optionTicker : optionChain) {
        s_logger.debug("Got option {}", optionTicker);

        final BloombergTickerParserEQOption optionInfo = BloombergTickerParserEQOption
                .getOptionParser(optionTicker);
        s_logger.debug("Got option info {}", optionInfo);

        final LocalDate key = optionInfo.getExpiry();
        Set<BloombergTickerParserEQOption> set = optionsByExpiry.get(key);
        if (set == null) {
            set = new HashSet<BloombergTickerParserEQOption>();
            optionsByExpiry.put(key, set);
        }
        set.add(optionInfo);
    }
    final Set<ExternalId> tickersToLoad = new HashSet<ExternalId>();

    final BigDecimal expiryCount = BigDecimal.valueOf(expiries.length);
    final BigDecimal defaultAmountAtExpiry = underlyingAmount.divide(expiryCount, BigDecimal.ROUND_DOWN);
    final BigDecimal spareAmountAtExpiry = defaultAmountAtExpiry.add(BigDecimal.ONE);
    int spareCount = underlyingAmount.subtract(defaultAmountAtExpiry.multiply(expiryCount)).intValue();

    for (final Period bucketPeriod : expiries) {
        final ManageablePortfolioNode bucketNode = new ManageablePortfolioNode(
                bucketPeriod.toString().substring(1));

        final LocalDate nowish = LocalDate.now().withDayOfMonth(20); //This avoids us picking different options every time this script is run
        final LocalDate targetExpiry = nowish.plus(bucketPeriod);
        final LocalDate chosenExpiry = optionsByExpiry.floorKey(targetExpiry);
        if (chosenExpiry == null) {
            s_logger.info("No options for {} on {}", targetExpiry, underlying);
            continue;
        }
        s_logger.info("Using time {} for bucket {} ({})",
                new Object[] { chosenExpiry, bucketPeriod, targetExpiry });

        final Set<BloombergTickerParserEQOption> optionsAtExpiry = optionsByExpiry.get(chosenExpiry);
        final TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> optionsByStrike = new TreeMap<>();
        for (final BloombergTickerParserEQOption option : optionsAtExpiry) {
            //        s_logger.info("option {}", option);
            final double key = option.getStrike();
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(key);
            if (pair == null) {
                pair = Pair.of(null, null);
            }
            if (option.getOptionType() == OptionType.CALL) {
                pair = Pair.of(option, pair.getSecond());
            } else {
                pair = Pair.of(pair.getFirst(), option);
            }
            optionsByStrike.put(key, pair);
        }

        //cascading collar?
        final BigDecimal amountAtExpiry = spareCount-- > 0 ? spareAmountAtExpiry : defaultAmountAtExpiry;

        s_logger.info(" est strike {}", estimatedCurrentStrike);
        final Double[] strikes = optionsByStrike.keySet().toArray(new Double[0]);

        int strikeIndex = Arrays.binarySearch(strikes, estimatedCurrentStrike);
        if (strikeIndex < 0) {
            strikeIndex = -(1 + strikeIndex);
        }
        s_logger.info("strikes length {} index {} strike of index {}",
                new Object[] { Integer.valueOf(strikes.length), Integer.valueOf(strikeIndex),
                        Double.valueOf(strikes[strikeIndex]) });

        int minIndex = strikeIndex - _numOptions;
        minIndex = Math.max(0, minIndex);
        int maxIndex = strikeIndex + _numOptions;
        maxIndex = Math.min(strikes.length - 1, maxIndex);

        s_logger.info("min {} max {}", Integer.valueOf(minIndex), Integer.valueOf(maxIndex));
        final StringBuffer sb = new StringBuffer("strikes: [");
        for (int j = minIndex; j <= maxIndex; j++) {
            sb.append(" ");
            sb.append(strikes[j]);
        }
        sb.append(" ]");
        s_logger.info(sb.toString());

        //Short Calls
        final ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> calls = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (int j = minIndex; j < strikeIndex; j++) {
            final Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike
                    .get(strikes[j]);
            if (pair == null) {
                throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]);
            }
            calls.add(pair);
        }
        spreadOptions(bucketNode, calls, OptionType.CALL, -1, tickersToLoad, amountAtExpiry, includeUnderlying,
                calls.size());

        // Long Puts
        final ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> puts = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (int j = strikeIndex + 1; j <= maxIndex; j++) {
            final Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike
                    .get(strikes[j]);
            if (pair == null) {
                throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]);
            }
            puts.add(pair);
        }
        spreadOptions(bucketNode, puts, OptionType.PUT, 1, tickersToLoad, amountAtExpiry, includeUnderlying,
                puts.size());

        if (bucketNode.getChildNodes().size() + bucketNode.getPositionIds().size() > 0) {
            equityNode.addChildNode(bucketNode); //Avoid generating empty nodes
        }
    }

    for (final ExternalId optionTicker : tickersToLoad) {
        final ManageableSecurity loaded = getOrLoadSecurity(optionTicker);
        if (loaded == null) {
            throw new OpenGammaRuntimeException("Unexpected option type " + loaded);
        }

        //TODO [LAPANA-29] Should be able to do this for index options too
        if (includeUnderlying) {
            try {
                final HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(optionTicker,
                        loaded.getExternalIdBundle());
                if (loadedTs == null) {
                    throw new OpenGammaRuntimeException("Failed to get time series for " + loaded);
                }
            } catch (final Exception ex) {
                s_logger.info("Failed to get time series for " + loaded, ex);
            }
        }
    }

    if (equityNode.getPositionIds().size() + equityNode.getChildNodes().size() > 0) {
        rootNode.addChildNode(equityNode);
    }
}

From source file:com.cyberway.issue.crawler.admin.StatisticsTracker.java

protected void writeResponseCodeReportTo(PrintWriter writer) {
    // Build header.
    writer.print("[rescode] [#urls]\n");
    TreeMap scd = getReverseSortedCopy(getStatusCodeDistribution());
    for (Iterator i = scd.keySet().iterator(); i.hasNext();) {
        Object key = i.next();//from   w  w w .j ava2s .  c  o m
        writer.print((String) key);
        writer.print(" ");
        writer.print(Long.toString(((LongWrapper) scd.get(key)).longValue));
        writer.print("\n");
    }
}