Example usage for java.lang Double Double

List of usage examples for java.lang Double Double

Introduction

In this page you can find the example usage for java.lang Double Double.

Prototype

@Deprecated(since = "9")
public Double(String s) throws NumberFormatException 

Source Link

Document

Constructs a newly allocated Double object that represents the floating-point value of type double represented by the string.

Usage

From source file:com.pdpsoft.web.DoubleConverter.java

/**
 * Convert the specified input object into an output object of the
 * specified type./*from  w w w.  j a v a 2s . c om*/
 *
 * @param type  Data type to which this value should be converted
 * @param value The input value to be converted
 * @throws org.apache.commons.beanutils.ConversionException if conversion cannot be performed
 *                             successfully
 */
public Object convert(Class type, Object value) {
    if (value == null) {
        if (useDefault) {
            return (defaultValue);
        } else {
            throw new ConversionException("No value specified");
        }
    }

    if (value instanceof Double) {
        return (value);
    } else if (value instanceof Number) {
        return ((Number) value).doubleValue();
    }

    try {
        // avoid to return 0
        if (StringUtils.isEmpty(String.valueOf(value))) {
            return null;
        } else
            return (new Double(value.toString()));
    } catch (Exception e) {
        if (useDefault) {
            return (defaultValue);
        } else {
            throw new ConversionException(e);
        }
    }

}

From source file:edu.uci.ics.jung.algorithms.scoring.VoltageScorer.java

/**
 * Creates an instance with the specified graph, edge weights, source vertices
 * (each of whose 'voltages' are tied to 1), and sinks.
 * @param g the input graph//from   ww  w .j  a v a2s  .c o m
 * @param edge_weights the edge weights, representing conductivity
 * @param sources the vertices whose voltages are tied to 1
 * @param sinks the vertices whose voltages are tied to 0
 */
public VoltageScorer(Hypergraph<V, E> g, Transformer<E, ? extends Number> edge_weights, Collection<V> sources,
        Collection<V> sinks) {
    super(g, edge_weights);

    Map<V, Double> unit_voltages = new HashMap<V, Double>();
    for (V v : sources)
        unit_voltages.put(v, new Double(1.0));
    this.source_voltages = unit_voltages;
    this.sinks = sinks;
    initialize();
}

From source file:mx.unam.ecologia.gye.coalescence.app.EvaluateAncestry.java

protected static final void process(CompoundSequence mrca, List leaves) {
    try {/*www .j a v  a2  s.c  o m*/

        PrintWriter pw = new PrintWriter(System.out);
        HaplotypeFreqSet len1 = new HaplotypeFreqSet(new CompoundSequenceLengthComparator());
        HaplotypeFreqSet len2 = new HaplotypeFreqSet(new CompoundSequenceLengthComparator());
        HaplotypeFreqSet ident = new HaplotypeFreqSet(new CompoundSequenceIdentityComparator());

        for (int i = 0; i < leaves.size(); i++) {
            UniParentalGene upgene = (UniParentalGene) leaves.get(i);
            CompoundSequence h = upgene.getCompoundSequence();
            len1.add(h);
            ident.add(h);
            CompoundSequence cs = h.getCopy();
            cs.setLocus(true);
            len2.add(cs);
        }

        //Identity
        pw.println("IDENTITY");
        ident.sort(new CSAncestryComparator());
        CompoundSequence cs = ident.get(0);
        pw.println("MA: " + ident.contains(cs));
        pw.println("MF: " + (ident.findMostFrequent() + 1));
        pw.println(ident.toFullString());

        pw.println();
        pw.println();
        pw.println("MULTILOCUS");
        pw.println("MA: " + len1.contains(cs));
        pw.println("MF: " + (len1.findMostFrequent() + 1));
        pw.println(len1.toResumeString());

        pw.println();
        pw.println();
        pw.println("LOCUS");
        cs.setLocus(true);
        pw.println("MA: " + len2.contains(cs));
        pw.println("MF: " + (len2.findMostFrequent() + 1));
        pw.println(len2.toResumeString());
        pw.flush();

        SparseGraph sg = new SparseGraph();

        List<CompoundSequence> ht = len1.getHaplotypes();
        //add vertices
        List<SparseVertex> vertices = new ArrayList<SparseVertex>(ht.size());

        for (Iterator<CompoundSequence> iter = ht.iterator(); iter.hasNext();) {
            CompoundSequence cseq = iter.next();
            SparseVertex sv = new SparseVertex();
            sv.addUserDatum("seq", cseq, UserData.SHARED);
            sv.addUserDatum("freq", len1.getFrequency(cseq), UserData.SHARED);
            if (cseq.equals(cs)) {
                sv.addUserDatum("mf", true, UserData.SHARED);
            }
            sg.addVertex(sv);
            vertices.add(sv);
        }
        //add edges
        for (int i = 0; i < ht.size(); i++) {
            for (int j = 0; j <= i; j++) {
                double d = DistanceCalculator.calculateMultilocusLengthDistance(ht.get(i), ht.get(j));
                UndirectedSparseEdge ue = new UndirectedSparseEdge(vertices.get(i), vertices.get(j));
                ue.setUserDatum(EDGE_WEIGHT_KEY, new Double(d), UserData.SHARED);
                if (d != 0) {
                    sg.addEdge(ue);
                }
            }
        }

        //System.out.println(sg.toString());
        //System.out.println(GraphMatrixOperations.graphToSparseMatrix(sg,EDGE_WEIGHT_KEY));
        visualizeGraph(sg);

        //Prim
        SparseGraph nsg = new SparseGraph();
        FibonacciHeap<Vertex, Double> q = new FibonacciHeap<Vertex, Double>();
        Map<Vertex, Vertex> pi = new HashMap<Vertex, Vertex>((int) (ht.size() * 1.3));
        //System.out.println("Have structures");
        Vertex r = null;
        for (SparseVertex u : vertices) {
            q.add(u, Double.MAX_VALUE);
            u.copy(nsg);
            if (r == null) {
                r = u;
            } else {
                //start from max freq
                r = (((Integer) r.getUserDatum("freq")).compareTo((Integer) u.getUserDatum("freq")) > 0) ? r
                        : u;
            }
        }
        q.decreaseKey(r, 0d);
        //System.out.println("initialized starting loop");
        do {
            Vertex u = (Vertex) q.popMin();
            Set<Vertex> s = u.getNeighbors();
            for (Vertex v : s) {
                Edge e = u.findEdge(v);
                double w = (Double) e.getUserDatum(EDGE_WEIGHT_KEY);
                if (q.contains(v) && w < q.getPriority(v)) {
                    pi.put(v, u);
                    q.decreaseKey(v, w);
                }
            }
        } while (q.size() > 0);

        //put edges

        for (Map.Entry<Vertex, Vertex> entry : pi.entrySet()) {
            Vertex v = entry.getKey();
            Vertex u = entry.getValue();
            u.findEdge(v).copy(nsg);
        }

        /*
        for(SparseVertex sv:vertices) {
          //edges
          Set s =  sv.getIncidentEdges();
          Edge[] edges = (Edge[])s.toArray(new Edge[s.size()]);
          //sort
          Arrays.sort(edges,new Comparator<Edge>() {
            public int compare(Edge o1, Edge o2) {
              return ((Double)o2.getUserDatum(EDGE_WEIGHT_KEY)).compareTo((Double)o1.getUserDatum(EDGE_WEIGHT_KEY));
            }
          });
          System.out.println(Arrays.toString(edges));
          //just leave the edge with the lowest weight
          for(Edge e:edges) {
            if(sv.degree() > 1 && e.getOpposite(sv).degree() > 1) {
              sg.removeEdge(e);
              System.out.println("Removing " + e.toString() + "::w="+e.getUserDatum(EDGE_WEIGHT_KEY));
            }
          }
                
          System.out.println(sv.toString());
        }
         */
        visualizeGraph(nsg);
    } catch (Exception ex) {
        log.error("process()", ex);
    }

}

From source file:net.chaosserver.timelord.data.TimelordTaskDay.java

/**
 * Sets the number of hours associated with this day.
 * @param hours new value for hours./*from ww w .  jav  a  2 s.  c o m*/
 */
public void setHours(double hours) {
    double oldHours = this.hours;
    this.hours = hours;

    propertyChangeSupport.firePropertyChange("hours", new Double(oldHours), new Double(this.hours));

    if (log.isTraceEnabled()) {
        log.trace("Firing property change [hours]");
    }
}

From source file:grafici.StatistichePieChart.java

/**
 * Creates a sample dataset.//w  w w .j  a  v  a 2 s.  c  o m
 * 
 * @return A sample dataset.
 */
private static PieDataset createDataset(Table results, int indexVariabile, int indexValore) {
    DefaultPieDataset dataset = new DefaultPieDataset();
    for (TableItem item : results.getItems()) {
        dataset.setValue(item.getText(indexVariabile), new Double(item.getText(indexValore)));
        dataset.sortByKeys(SortOrder.ASCENDING);
    }
    return dataset;
}

From source file:org.jfree.data.category.junit.CategoryToPieDatasetTest.java

/**
 * Some checks for the getValue() method.
 *///  w  ww.j a  v a2 s .c  o m
public void testGetValue() {
    DefaultCategoryDataset underlying = new DefaultCategoryDataset();
    underlying.addValue(1.1, "R1", "C1");
    underlying.addValue(2.2, "R1", "C2");
    CategoryToPieDataset d1 = new CategoryToPieDataset(underlying, TableOrder.BY_ROW, 0);
    assertEquals(d1.getValue("C1"), new Double(1.1));
    assertEquals(d1.getValue("C2"), new Double(2.2));

    // check negative index throws exception
    try {
        /* Number n = */ d1.getValue(-1);
        fail("Expected IndexOutOfBoundsException.");
    } catch (IndexOutOfBoundsException e) {
        // this is expected
    }

    // check index == getItemCount() throws exception
    try {
        /* Number n = */ d1.getValue(d1.getItemCount());
        fail("Expected IndexOutOfBoundsException.");
    } catch (IndexOutOfBoundsException e) {
        // this is expected
    }

    // test null source
    CategoryToPieDataset p1 = new CategoryToPieDataset(null, TableOrder.BY_COLUMN, 0);
    try {
        /* Number n = */ p1.getValue(0);
        fail("Expected IndexOutOfBoundsException.");
    } catch (IndexOutOfBoundsException e) {
        // this is expected
    }
}

From source file:com.xpn.xwiki.objects.classes.NumberClass.java

@Override
public BaseProperty fromString(String value) {
    BaseProperty property = newProperty();
    String ntype = getNumberType();
    Number nvalue = null;/*from   w  w w  .j  a v  a2  s .co  m*/

    try {
        if (ntype.equals("integer")) {
            if ((value != null) && (!value.equals(""))) {
                nvalue = new Integer(value);
            }
        } else if (ntype.equals("float")) {
            if ((value != null) && (!value.equals(""))) {
                nvalue = new Float(value);
            }
        } else if (ntype.equals("double")) {
            if ((value != null) && (!value.equals(""))) {
                nvalue = new Double(value);
            }
        } else {
            if ((value != null) && (!value.equals(""))) {
                nvalue = new Long(value);
            }
        }
    } catch (NumberFormatException e) {
        LOG.warn("Invalid number entered for property " + getName() + " of class " + getObject().getName()
                + ": " + value);
        // Returning null makes sure that the old value (if one exists) will not be discarded/replaced
        return null;
    }

    property.setValue(nvalue);
    return property;
}

From source file:com.stainlesscode.mediapipeline.packetdecoder.MultispeedAudioPacketDecoder.java

@SuppressWarnings("unchecked")
public void decodePacket(IPacket packet) {
    if (LogUtil.isDebugEnabled()) {
        LogUtil.debug("buffer size = " + engineRuntime.getAudioFrameBuffer().size());
        LogUtil.debug("decode audio packet " + packet.getTimeStamp());
    }/* ww  w  . j a  va2  s.co  m*/

    try {
        if (nextFrame) {
            if (LogUtil.isDebugEnabled()) {
                LogUtil.debug("starting a new frame");
            }
            samples = (IAudioSamples) engineRuntime.getAudioSamplePool().borrowObject();
            nextFrame = false;
        }

        int offset = 0;

        /*
         * Keep going until we've processed all data
         */
        while (offset < packet.getSize()) {
            int bytesDecoded = engineRuntime.getAudioCoder().decodeAudio(samples, packet, offset);
            if (bytesDecoded < 0)
                throw new RuntimeException("got error decoding audio");
            offset += bytesDecoded;
            if (LogUtil.isDebugEnabled())
                LogUtil.debug("decoded " + offset + " total bytes from packet");
        }

        /*
         * Some decoder will consume data in a packet, but will not be able
         * to construct a full set of samples yet. Therefore you should
         * always check if you got a complete set of samples from the
         * decoder
         */
        if (samples.isComplete()) {

            int modulo = 0;
            speed = new Double(engineRuntime.getPlaySpeed()).intValue();
            if (speed > 0) {
                modulo = (multispeedPacketCounter++) % speed;
                if (LogUtil.isDebugEnabled()) {
                    LogUtil.debug("speed factor is " + speed);
                    LogUtil.debug("modulo is " + modulo);
                }
            }

            if (modulo == 0) {
                try {
                    engineRuntime.getAudioFrameBuffer().add(samples);
                    if (LogUtil.isDebugEnabled())
                        LogUtil.debug("---> Decoded an audio frame");
                    nextFrame = true;
                } catch (BufferOverflowException e) {
                    e.printStackTrace();
                }
            }
        }

        if (packet != null)
            engineRuntime.getPacketPool().returnObject(packet);

    } catch (NoSuchElementException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:components.ConversionPanel.java

ConversionPanel(Converter myController, String myTitle, Unit[] myUnits, ConverterRangeModel myModel) {
    if (MULTICOLORED) {
        setOpaque(true);//from w  ww.  ja va2  s.  c  o  m
        setBackground(new Color(0, 255, 255));
    }
    setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(myTitle),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));

    //Save arguments in instance variables.
    controller = myController;
    units = myUnits;
    title = myTitle;
    sliderModel = myModel;

    //Create the text field format, and then the text field.
    numberFormat = NumberFormat.getNumberInstance();
    numberFormat.setMaximumFractionDigits(2);
    NumberFormatter formatter = new NumberFormatter(numberFormat);
    formatter.setAllowsInvalid(false);
    formatter.setCommitsOnValidEdit(true);//seems to be a no-op --
    //aha -- it changes the value property but doesn't cause the result to
    //be parsed (that happens on focus loss/return, I think).
    //
    textField = new JFormattedTextField(formatter);
    textField.setColumns(10);
    textField.setValue(new Double(sliderModel.getDoubleValue()));
    textField.addPropertyChangeListener(this);

    //Add the combo box.
    unitChooser = new JComboBox();
    for (int i = 0; i < units.length; i++) { //Populate it.
        unitChooser.addItem(units[i].description);
    }
    unitChooser.setSelectedIndex(0);
    sliderModel.setMultiplier(units[0].multiplier);
    unitChooser.addActionListener(this);

    //Add the slider.
    slider = new JSlider(sliderModel);
    sliderModel.addChangeListener(this);

    //Make the text field/slider group a fixed size
    //to make stacked ConversionPanels nicely aligned.
    JPanel unitGroup = new JPanel() {
        public Dimension getMinimumSize() {
            return getPreferredSize();
        }

        public Dimension getPreferredSize() {
            return new Dimension(150, super.getPreferredSize().height);
        }

        public Dimension getMaximumSize() {
            return getPreferredSize();
        }
    };
    unitGroup.setLayout(new BoxLayout(unitGroup, BoxLayout.PAGE_AXIS));
    if (MULTICOLORED) {
        unitGroup.setOpaque(true);
        unitGroup.setBackground(new Color(0, 0, 255));
    }
    unitGroup.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
    unitGroup.add(textField);
    unitGroup.add(slider);

    //Create a subpanel so the combo box isn't too tall
    //and is sufficiently wide.
    JPanel chooserPanel = new JPanel();
    chooserPanel.setLayout(new BoxLayout(chooserPanel, BoxLayout.PAGE_AXIS));
    if (MULTICOLORED) {
        chooserPanel.setOpaque(true);
        chooserPanel.setBackground(new Color(255, 0, 255));
    }
    chooserPanel.add(unitChooser);
    chooserPanel.add(Box.createHorizontalStrut(100));

    //Put everything together.
    setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
    add(unitGroup);
    add(chooserPanel);
    unitGroup.setAlignmentY(TOP_ALIGNMENT);
    chooserPanel.setAlignmentY(TOP_ALIGNMENT);
}

From source file:com.tecapro.inventory.common.util.CheckUtil.java

public boolean isDouble(String value) {
    if (value == null) {
        return false;
    }/*  w ww . j  a va  2s  . c o m*/
    try {
        new Double(convertUtil.trim(value)).doubleValue();
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}