Example usage for java.lang Double longValue

List of usage examples for java.lang Double longValue

Introduction

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

Prototype

public long longValue() 

Source Link

Document

Returns the value of this Double as a long after a narrowing primitive conversion.

Usage

From source file:org.n52.ifgicopter.spf.input.HistoryPostgisInputPlugin.java

/**
 * @return/*from  w w  w. j  a v  a 2s .co m*/
 * 
 */
@Override
protected JPanel makeControlPanel() {
    if (this.controlPanel == null) {
        this.controlPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));

        JButton startButton = new JButton("Start");
        startButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        start();
                    }
                });
            }
        });
        this.controlPanel.add(startButton);
        JButton stopButton = new JButton("Stop");
        stopButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        stop();
                    }
                });
            }
        });
        this.controlPanel.add(stopButton);

        JLabel sleepTimeLabel = new JLabel("Time between points in seconds:");
        this.controlPanel.add(sleepTimeLabel);
        double spinnerMin = 0.1d;
        double spinnerMax = 10000.0d;
        SpinnerModel model = new SpinnerNumberModel(2.0d, spinnerMin, spinnerMax, 0.1d);
        JSpinner sleepTimeSpinner = new JSpinner(model);
        sleepTimeSpinner.setToolTipText("Select time using controls or manual input within the range of "
                + spinnerMin + " to " + spinnerMax + ".");
        sleepTimeSpinner.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                Object source = e.getSource();
                if (source instanceof JSpinner) {
                    final JSpinner spinner = (JSpinner) source;

                    EventQueue.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            Double value = (Double) spinner.getValue();
                            value = Double.valueOf(value.doubleValue() * 1000d);
                            setSleepTimeMillis(value.longValue());
                        }
                    });
                } else
                    log.warn("Unsupported ChangeEvent, need JSpinner as source: " + e);
            }
        });
        // catch text change events without loosing the focus
        // JSpinner.DefaultEditor editor = (DefaultEditor) sleepTimeSpinner.getEditor();
        // not implemented, can be done using KeyEvent, but then it hast to be checked where in the text
        // field the keystroke was etc. --> too complicated.

        this.controlPanel.add(sleepTimeSpinner);

        JLabel whereLabel = new JLabel("Where clause: ");
        this.whereField = new JTextField(this.where);
        this.whereField.setPreferredSize(new Dimension(200, 20));
        this.whereField.setToolTipText("Insert a valid SQL 'WHERE' clause here.");
        this.whereButton = new JButton("Load data");
        this.whereButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        updateWhere();

                        loadAllData();
                    }
                });
            }
        });

        this.controlPanel.add(whereLabel);
        this.controlPanel.add(this.whereField);
        this.controlPanel.add(this.whereButton);
    }

    return this.controlPanel;
}

From source file:com.streamsets.datacollector.execution.runner.common.TestProductionPipeline.java

@Test
public void testRateLimit() throws Exception {
    final TestProducer p = new TestProducer();
    MockStages.setSourceCapture(p);// w w  w.  ja v  a  2s  . c o  m

    final ProductionPipeline pipeline = createProductionPipeline(DeliveryGuarantee.AT_MOST_ONCE, true, 10L,
            false/*source not committer*/);
    pipeline.registerStatusListener(new MyStateListener());
    final Exchanger<Double> rate = new Exchanger<>();
    new Thread() {
        @Override
        public void run() {
            try {
                long start = System.nanoTime();
                pipeline.run();
                rate.exchange(p.count.doubleValue() * 1000 * 1000 * 1000 / (System.nanoTime() - start));
            } catch (Exception ex) {

            }
        }
    }.start();
    Thread.sleep(10000);
    pipeline.stop();
    Double rateAchieved = rate.exchange(0.0);
    // To account for the slight loss of precision, we compare the "long-ified" versions.
    Assert.assertTrue(rateAchieved.longValue() <= 10);
}

From source file:org.globus.workspace.groupauthz.DecisionLogic.java

/**
 *
 * @param dn may not be null/* www.  j av a 2s . c  om*/
 * @param rights may not be null
 * @param bindings may not be null, can be zerolen array
 * @param elapsedMins may not be null or negative
 * @param reservedMins may not be null or negative
 * @param numWorkspaces number of OTHER, current workspaces
 * @param chargeRatio ratio to compute the real minutes charge, typically <= 1.0 and > 0
 * @return Decision Integer
 * @throws AuthorizationException processing problem
 * @throws ResourceRequestDeniedException error w/ explanation to client
 */
public Integer decide(String dn, GroupRights rights, VirtualMachine[] bindings, Long elapsedMins,
        Long reservedMins, int numWorkspaces, double chargeRatio)

        throws AuthorizationException, ResourceRequestDeniedException {

    if (!HashUtil.isInitialized()) {
        throw new AuthorizationException(
                "Cannot give an authorization " + "decision without a properly initialized hashing system");
    }

    if (dn == null) {
        throw new IllegalArgumentException("dn is null");
    }

    if (rights == null) {
        throw new IllegalArgumentException("rights is null");
    }

    if (bindings == null) {
        throw new IllegalArgumentException("bindings is null");
    }

    if (elapsedMins == null) {
        throw new IllegalArgumentException("elapsedMins is null");
    } else if (elapsedMins.longValue() < 0) {
        throw new IllegalArgumentException("elapsedMins is negative");
    }

    if (reservedMins == null) {
        throw new IllegalArgumentException("reservedMins is null");
    } else if (reservedMins.longValue() < 0) {
        throw new IllegalArgumentException("reservedMins is negative");
    }

    if (chargeRatio <= 0) {
        throw new IllegalArgumentException("expecting charge ratio to be positive");
    }

    final StringBuffer buf = new StringBuffer("\n\nConsidering caller: '");
    buf.append(dn).append("'.\nCurrent elapsed minutes: ").append(elapsedMins)
            .append(".\nCurrent reserved minutes: ").append(reservedMins)
            .append(".\nNumber of VMs in request: ").append(bindings.length)
            .append(".\nCharge ratio for request: ").append(chargeRatio)
            .append(".\nNumber of VMs caller is already currently running: ").append(numWorkspaces)
            .append(".\nRights:\n").append(rights).append("\n\n");

    final int maxCurrentPolicy = (int) rights.getMaxWorkspaceNumber();
    if (maxCurrentPolicy > 0) {

        if (numWorkspaces + bindings.length > maxCurrentPolicy) {

            final StringBuffer newbuf = new StringBuffer("\nDenied: Request for ");
            newbuf.append(bindings.length).append(" workspaces");

            if (numWorkspaces != 0) {
                newbuf.append(", together with number of currently " + "running workspaces (")
                        .append(numWorkspaces).append("),");
            }

            newbuf.append(" exceeds the maximum, which is ").append(maxCurrentPolicy)
                    .append(" concurrently running workspaces.");

            final String msg = newbuf.toString();
            buf.append(msg);
            logger.warn(buf.toString());
            throw new ResourceRequestDeniedException(msg);
        }
    }

    long requestDur = 0;
    for (int i = 0; i < bindings.length; i++) {

        final VirtualMachineDeployment dep = bindings[i].getDeployment();
        if (dep == null) {
            final String msg = "ERROR: No deployment information in " + "binding, can't make decision.";
            buf.append(msg);
            logger.error(buf.toString());
            throw new AuthorizationException(msg);
        }

        final long seconds = dep.getMinDuration();
        requestDur += seconds / 60;
    }

    final Double doubleRequestDur = requestDur * chargeRatio;
    requestDur = doubleRequestDur.longValue();

    if (bindings.length > 1) {
        buf.append("Duration total of all requests in group: ");
    } else {
        buf.append("Duration request: ");
    }

    buf.append(requestDur).append("\n");

    // zero or below means no check should be made
    if (rights.getMaxCPUs() > 0) {
        final long maxCPUs = rights.getMaxCPUs();
        for (int i = 0; i < bindings.length; i++) {

            final VirtualMachineDeployment dep = bindings[i].getDeployment();
            if (dep == null) {
                final String msg = "ERROR: No deployment information in " + "binding, can't make decision.";
                buf.append(msg);
                logger.error(buf.toString());
                throw new AuthorizationException(msg);
            }
            final long currentCPUs = dep.getIndividualCPUCount();
            if (currentCPUs > maxCPUs) {

                buf.append("\nDenied: Requested CPU count (").append(currentCPUs)
                        .append(") + is greater or equal to maximum CPU count (").append(maxCPUs)
                        .append(").\n");

                logger.warn(buf.toString());

                throw new ResourceRequestDeniedException("You requested too many CPUs (" + currentCPUs
                        + "), the " + "maximum is " + maxCPUs + " CPUs.");
            }
        }
    }

    // zero or below means no check should be made
    if (rights.getMaxReservedMinutes() > 0) {
        final long max = rights.getMaxReservedMinutes();
        final long current = reservedMins.longValue();
        if (requestDur + current > max) {

            buf.append("\nDenied: Request duration (").append(requestDur).append(") + current reserved tally (")
                    .append(current).append(") + is greater or equal to maximum reserved (").append(max)
                    .append(").\n");

            logger.warn(buf.toString());

            throw new ResourceRequestDeniedException("Your request is for too much time (" + requestDur
                    + "), the " + "maximum reserved at once is " + max + " minutes.  You currently have "
                    + current + " other reserved minutes.");
        }
    }

    // zero or below means no check should be made
    if (rights.getMaxElapsedReservedMinutes() > 0) {
        final long max = rights.getMaxElapsedReservedMinutes();
        final long currentElapsed = elapsedMins.longValue();
        final long currentReserved = reservedMins.longValue();
        final long tally = currentElapsed + currentReserved;
        if (requestDur + tally > max) {

            buf.append("\nDenied: Request duration (").append(requestDur)
                    .append(") + current reserved+elapsed tally (").append(tally)
                    .append(") + is greater or equal to maximum reserved+elapsed (").append(max).append(").\n");

            logger.warn(buf.toString());

            throw new ResourceRequestDeniedException("Your request is for too much time (" + requestDur
                    + "), this would exceed the " + "maximum you can have both used in the "
                    + "past and have reserved currently. " + "This maximum is " + max
                    + " minutes.  You currently have " + currentElapsed + " elapsed minutes " + "and "
                    + currentReserved + " reserved minutes and the request for " + requestDur
                    + " minutes would exceed this.");
        }
    }

    final String dnhash;
    if (rights.isDirHashMode()) {
        try {
            dnhash = HashUtil.hashDN(dn);
        } catch (NoSuchAlgorithmException e) {
            final String msg = "ERROR: DN hash required but it " + "is not available: " + e.getMessage();
            buf.append(msg);
            logger.error(buf.toString());
            throw new AuthorizationException(msg);
        }
    } else {
        dnhash = null;
    }

    for (int i = 0; i < bindings.length; i++) {

        final VirtualMachinePartition[] parts = bindings[i].getPartitions();

        if (parts == null) {
            final String msg = "ERROR: No partition information in " + "binding, can't make decision.";
            buf.append(msg);
            logger.error(buf.toString());
            throw new AuthorizationException(msg);
        }

        checkImages(parts, rights, buf, dn, dnhash);
    }

    buf.append("\n");
    logger.info(buf.toString());
    return Decision.PERMIT;
}

From source file:FeeBooster.java

private GridPane rbfGrid(Transaction tx) {
    // Setup grid
    GridPane grid = new GridPane();
    grid.setAlignment(Pos.CENTER);/*from w w w  .j a v  a 2  s.c  om*/
    grid.setHgap(10);
    grid.setVgap(10);
    grid.setPadding(new Insets(25, 25, 25, 25));
    int inGridHeight = 0;
    int outGridHeight = 0;

    // Add inputs to table
    Label inputHdrLbl = new Label("Inputs");
    grid.add(inputHdrLbl, 0, inGridHeight);
    inGridHeight++;
    for (int i = 0; i < tx.getInputs().size(); i++) {
        // Add input to table
        TxInput in = tx.getInputs().get(i);
        Text inputTxt = new Text("Txid: " + in.getTxid() + "\nIndex: " + in.getVout());
        grid.add(inputTxt, 0, inGridHeight);
        inGridHeight++;
    }

    // Add outputs to table
    Label outputHdrLbl = new Label("Outputs");
    grid.add(outputHdrLbl, 1, outGridHeight);
    outGridHeight++;
    ToggleGroup outputGroup = new ToggleGroup();
    for (int i = 0; i < tx.getOutputs().size(); i++) {
        // Add output to table
        TxOutput out = tx.getOutputs().get(i);
        Text outputTxt = new Text("Amount " + out.getValue() + " Satoshis\nAddress: " + out.getAddress());
        outputTxt.setUserData(i);
        grid.add(outputTxt, 1, outGridHeight);

        // Add radio button to table
        RadioButton radio = new RadioButton();
        radio.setUserData(i);
        radio.setToggleGroup(outputGroup);
        radio.setSelected(true);
        grid.add(radio, 2, outGridHeight);
        outGridHeight++;
    }

    // Set gridheight
    int gridheight = (inGridHeight < outGridHeight) ? outGridHeight : inGridHeight;
    gridheight++;

    // Fee
    Text fee = new Text("Fee Paid: " + tx.getFee() + " Satoshis");
    grid.add(fee, 0, gridheight);

    // Recommended fee from bitcoinfees.21.co
    JSONObject apiResult = Utils.getFromAnAPI("http://bitcoinfees.21.co/api/v1/fees/recommended", "GET");
    int fastestFee = apiResult.getInt("fastestFee");
    long recommendedFee = fastestFee * tx.getSize();
    Text recFeeTxt = new Text("Recommended Fee: " + recommendedFee + " Satoshis");
    grid.add(recFeeTxt, 1, gridheight);
    gridheight += 2;

    // Instructions
    Text instructions = new Text(
            "Choose an output to deduct an additional fee from. Then increase the fee below.");
    grid.add(instructions, 0, gridheight, 3, 1);
    gridheight++;

    // Fee spinner
    Spinner feeSpin = new Spinner((double) tx.getFee(), (double) tx.getTotalAmt(), (double) tx.getFee());
    feeSpin.setEditable(true);
    grid.add(feeSpin, 0, gridheight);
    feeSpin.valueProperty().addListener(new ChangeListener() {
        @Override
        public void changed(ObservableValue observable, Object oldValue, Object newValue) {
            double oldVal = (double) oldValue;
            double newVal = (double) newValue;
            Double step = newVal - oldVal;
            tx.setFee(tx.getFee() + step.longValue());
            fee.setText("Fee Paid: " + tx.getFee() + " Satoshis");
            int output = (int) outputGroup.getSelectedToggle().getUserData();
            TxOutput out = tx.getOutputs().get(output);
            out.decreaseValueBy(step.longValue());
            for (int i = 0; i < grid.getChildren().size(); i++) {
                Node child = grid.getChildren().get(i);
                if (grid.getRowIndex(child) == output + 1 && grid.getColumnIndex(child) == 1) {
                    ((Text) child)
                            .setText("Amount " + out.getValue() + " Satoshis\nAddress: " + out.getAddress());
                }
            }
        }
    });

    // Set to recommended fee button
    Button recFeeBtn = new Button("Set fee to recommended");
    grid.add(recFeeBtn, 1, gridheight);
    gridheight++;
    recFeeBtn.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            long prevFee = tx.getFee();
            long step = recommendedFee - prevFee;
            feeSpin.increment((int) step);
        }
    });

    // Next Button
    Button nextBtn = new Button("Next");
    grid.add(nextBtn, 1, gridheight);
    nextBtn.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            if (sceneCursor == scenes.size() - 1) {
                Scene scene = new Scene(unsignedTxGrid(tx), 900, 500);
                scenes.add(scene);
                sceneCursor++;
                stage.setScene(scene);
            } else {
                sceneCursor++;
                stage.setScene(scenes.get(sceneCursor));
            }
        }
    });
    HBox btnHbox = new HBox(10);

    // Back Button
    Button backBtn = new Button("Back");
    backBtn.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            sceneCursor--;
            stage.setScene(scenes.get(sceneCursor));
        }
    });
    btnHbox.getChildren().add(backBtn);
    btnHbox.getChildren().add(nextBtn);

    // Cancel Button
    Button cancelBtn = new Button("Cancel");
    cancelBtn.setOnAction(cancelEvent);
    btnHbox.getChildren().add(cancelBtn);
    grid.add(btnHbox, 1, gridheight);

    return grid;
}

From source file:FeeBooster.java

private GridPane cpfpGrid(Transaction tx) {
    // Setup Grid
    GridPane grid = new GridPane();
    grid.setAlignment(Pos.CENTER);//w w w .  j av  a 2  s .  c  o m
    grid.setHgap(10);
    grid.setVgap(10);
    grid.setPadding(new Insets(25, 25, 25, 25));
    int gridheight = 0;

    // Add outputs to table
    Label outputHdrLbl = new Label("Outputs");
    grid.add(outputHdrLbl, 1, gridheight);
    gridheight++;
    ToggleGroup outputGroup = new ToggleGroup();
    for (int i = 0; i < tx.getOutputs().size(); i++) {
        // Add output to table
        TxOutput out = tx.getOutputs().get(i);
        Text outputTxt = new Text("Amount " + out.getValue() + " Satoshis\nAddress: " + out.getAddress());
        outputTxt.setUserData(i);
        grid.add(outputTxt, 0, gridheight);

        // Add radio button to table
        RadioButton radio = new RadioButton();
        radio.setUserData(i);
        radio.setToggleGroup(outputGroup);
        radio.setSelected(true);
        grid.add(radio, 1, gridheight);
        gridheight++;
    }

    // Fee
    Text fee = new Text("Fee to Pay: " + tx.getFee() + " Satoshis");
    grid.add(fee, 0, gridheight);

    // Recommended fee from bitcoinfees.21.co
    JSONObject apiResult = Utils.getFromAnAPI("http://bitcoinfees.21.co/api/v1/fees/recommended", "GET");
    int fastestFee = apiResult.getInt("fastestFee");
    long recommendedFee = fastestFee * tx.getSize() + fastestFee * 300;
    Text recFeeTxt = new Text("Recommended Fee: " + recommendedFee + " Satoshis");
    grid.add(recFeeTxt, 1, gridheight);
    gridheight += 2;

    // Instructions
    Text instructions = new Text("Choose an output to spend from. Set the total transaction fee below.");
    grid.add(instructions, 0, gridheight, 3, 1);
    gridheight++;

    // Fee spinner
    Spinner feeSpin = new Spinner((double) tx.getFee(), (double) tx.getTotalAmt(), (double) tx.getFee());
    feeSpin.setEditable(true);
    grid.add(feeSpin, 0, gridheight);
    feeSpin.valueProperty().addListener(new ChangeListener() {
        @Override
        public void changed(ObservableValue observable, Object oldValue, Object newValue) {
            double oldVal = (double) oldValue;
            double newVal = (double) newValue;
            Double step = newVal - oldVal;
            tx.setFee(tx.getFee() + step.longValue());
            fee.setText("Fee to Pay: " + tx.getFee() + " Satoshis");
        }
    });

    // Set to recommended fee button
    Button recFeeBtn = new Button("Set fee to recommended");
    grid.add(recFeeBtn, 1, gridheight);
    gridheight++;
    recFeeBtn.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            long prevFee = tx.getFee();
            long step = recommendedFee - prevFee;
            feeSpin.increment((int) step);
        }
    });

    // Output address
    Label recvAddr = new Label("Address to pay to");
    grid.add(recvAddr, 0, gridheight);
    TextField outAddr = new TextField();
    grid.add(outAddr, 1, gridheight);
    gridheight++;

    // Next Button
    Button nextBtn = new Button("Next");
    nextBtn.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {

            if (sceneCursor == scenes.size() - 1) {
                // Referenced output
                int output = (int) outputGroup.getSelectedToggle().getUserData();
                TxOutput refout = tx.getOutputs().get(output);

                // Create output for CPFP transaction
                TxOutput out = null;
                long outval = refout.getValue() - ((Double) feeSpin.getValue()).longValue();
                if (Utils.validateAddress(outAddr.getText())) {
                    byte[] decodedAddr = Utils.base58Decode(outAddr.getText());
                    boolean isP2SH = decodedAddr[0] == 0x00;
                    byte[] hash160 = Arrays.copyOfRange(decodedAddr, 1, decodedAddr.length - 4);
                    if (isP2SH) {
                        byte[] script = new byte[hash160.length + 3];
                        script[0] = (byte) 0xa9;
                        script[1] = (byte) 0x14;
                        System.arraycopy(hash160, 0, script, 2, hash160.length);
                        script[script.length - 1] = (byte) 0x87;
                        out = new TxOutput(outval, script);
                    } else {
                        byte[] script = new byte[hash160.length + 5];
                        script[0] = (byte) 0x76;
                        script[1] = (byte) 0xa9;
                        script[2] = (byte) 0x14;
                        System.arraycopy(hash160, 0, script, 3, hash160.length);
                        script[script.length - 2] = (byte) 0x88;
                        script[script.length - 1] = (byte) 0xac;
                        out = new TxOutput(outval, script);
                    }
                } else {
                    Alert alert = new Alert(Alert.AlertType.ERROR, "Invalid Address");
                    alert.showAndWait();
                    return;
                }

                // Create CPFP Transaction
                Transaction cpfpTx = new Transaction();
                TxInput in = new TxInput(tx.getHash(), output, new byte[] { (0x00) }, 0xffffffff);
                cpfpTx.addOutput(out);
                cpfpTx.addInput(in);

                // Create Scene
                Scene scene = new Scene(unsignedTxGrid(cpfpTx), 900, 500);
                scenes.add(scene);
                sceneCursor++;
                stage.setScene(scene);
            } else {
                sceneCursor++;
                stage.setScene(scenes.get(sceneCursor));
            }
        }
    });
    HBox btnHbox = new HBox(10);

    // Back Button
    Button backBtn = new Button("Back");
    backBtn.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            sceneCursor--;
            stage.setScene(scenes.get(sceneCursor));
        }
    });
    btnHbox.getChildren().add(backBtn);
    btnHbox.getChildren().add(nextBtn);

    // Cancel Button
    Button cancelBtn = new Button("Cancel");
    cancelBtn.setOnAction(cancelEvent);
    btnHbox.getChildren().add(cancelBtn);
    grid.add(btnHbox, 1, gridheight);

    return grid;
}

From source file:info.raack.appliancedetection.evaluation.web.EvaluationController.java

@RequestMapping(value = "/evaluation/{id}", method = RequestMethod.GET)
public void getEvaluationData(@PathVariable("id") String simulationId,
        @RequestParam("algorithmId") int algorithmId,
        @RequestParam(value = "start", required = false) Double startMillis,
        @RequestParam(value = "end", required = false) Double endMillis,
        @RequestParam(value = "ticks", required = false) Integer ticks, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    // TODO - for now, just use the naive algorithm's energy measurements.

    Date start = null;/*from  w  w w. ja  v  a2s.c  o m*/
    Date end = null;

    if (startMillis != null && endMillis != null) {
        start = new Date(startMillis.longValue());
        end = new Date(endMillis.longValue());
    } else if (startMillis != null && endMillis == null) {
        // if only start or end are provided, create a one day span
        Calendar c = new GregorianCalendar();
        c.setTimeInMillis(startMillis.longValue());
        start = c.getTime();
    } else if (startMillis == null && endMillis != null) {
        // if only start or end are provided, create a one day span
        Calendar c = new GregorianCalendar();
        c.setTimeInMillis(endMillis.longValue());
        end = c.getTime();

    }

    if (ticks == null) {
        ticks = 300;
    }

    Evaluation evaluation = simulationService.getEvaluation(algorithmId, simulationId, start, end, true);

    if (evaluation == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    EvaluationWrapper wrapper = new EvaluationWrapper(evaluation);

    JsonSerializer<EnergyTimestep> dateSerializer = new JsonSerializer<EnergyTimestep>() {
        // serialize date to milliseconds since epoch
        public JsonElement serialize(EnergyTimestep energyTimestep, Type me, JsonSerializationContext arg2) {
            JsonArray object = new JsonArray();
            object.add(new JsonPrimitive(energyTimestep.getStartTime().getTime()));
            object.add(new JsonPrimitive(energyTimestep.getEnergyConsumed()));
            return object;
        }
    };

    String dataJS = new GsonBuilder().registerTypeAdapter(EnergyTimestep.class, dateSerializer)
            .excludeFieldsWithModifiers(Modifier.STATIC).setExclusionStrategies(new ExclusionStrategy() {

                // skip logger
                public boolean shouldSkipClass(Class<?> clazz) {
                    return clazz.equals(Logger.class);
                }

                public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                    // skip simulation of simulated appliance
                    return (fieldAttributes.getName().equals("simulation")
                            && fieldAttributes.getDeclaringClass() == SimulatedAppliance.class) ||
                    // skip simulation second data
                    (fieldAttributes.getName().equals("secondData")
                            && fieldAttributes.getDeclaringClass() == Simulation.class) ||
                    // skip endTime of energytimestep
                    (fieldAttributes.getName().equals("endTime")
                            && fieldAttributes.getDeclaringClass() == EnergyTimestep.class) ||
                    // skip userAppliance, detectionAlgorithmId of appliance state transition
                    ((fieldAttributes.getName().equals("userAppliance")
                            || fieldAttributes.getName().equals("detectionAlgorithmId"))
                            && fieldAttributes.getDeclaringClass() == ApplianceStateTransition.class);
                }
            }).create().toJson(wrapper);

    response.getWriter().write(dataJS);
    response.setContentType("application/json");
}

From source file:org.n52.ifgicopter.spf.input.FakeInputPlugin.java

/**
 * //from  ww w  .j a  v  a2 s.c  om
 * @return
 */
private JPanel makeControlPanel() {
    if (this.controlPanel == null) {
        this.controlPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));

        JButton startButton = new JButton("Start");
        startButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        start();
                    }
                });
            }
        });
        this.controlPanel.add(startButton);
        JButton stopButton = new JButton("Stop");
        stopButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        stop();
                    }
                });
            }
        });
        this.controlPanel.add(stopButton);

        JLabel sleepTimeLabel = new JLabel("Time between points in seconds:");
        this.controlPanel.add(sleepTimeLabel);
        double spinnerMin = 0.1d;
        double spinnerMax = 10000.0d;
        SpinnerModel model = new SpinnerNumberModel(DEFAULT_INTERVAL_MILLIS / SECONDS_TO_MILLISECONDS,
                spinnerMin, spinnerMax, 0.1d);
        JSpinner sleepTimeSpinner = new JSpinner(model);
        sleepTimeSpinner.setToolTipText("Select time using controls or manual input within the range of "
                + spinnerMin + " to " + spinnerMax + ".");

        sleepTimeSpinner.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                Object source = e.getSource();
                if (source instanceof JSpinner) {
                    final JSpinner spinner = (JSpinner) source;

                    EventQueue.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            Double value = (Double) spinner.getValue();
                            value = Double.valueOf(value.doubleValue() * SECONDS_TO_MILLISECONDS);
                            FakeInputPlugin.this.sleepTimeMillis = value.longValue();
                        }
                    });
                } else
                    log.warn("Unsupported ChangeEvent, need JSpinner as source: " + e);
            }
        });
        // catch text change events without loosing the focus
        // JSpinner.DefaultEditor editor = (DefaultEditor) sleepTimeSpinner.getEditor();
        // not implemented, can be done using KeyEvent, but then it hast to be checked where in the text
        // field the keystroke was etc. --> too complicated.

        this.controlPanel.add(sleepTimeSpinner);
    }

    return this.controlPanel;
}

From source file:org.sonar.server.issue.index.IssueIndex.java

private Optional<Long> getMinCreatedAt(Map<String, QueryBuilder> filters, QueryBuilder esQuery) {
    String facetNameAndField = IssueIndexDefinition.FIELD_ISSUE_FUNC_CREATED_AT;
    SearchRequestBuilder esRequest = client.prepareSearch(INDEX_TYPE_ISSUE).setSize(0);
    BoolQueryBuilder esFilter = boolQuery();
    filters.values().stream().filter(Objects::nonNull).forEach(esFilter::must);
    if (esFilter.hasClauses()) {
        esRequest.setQuery(QueryBuilders.filteredQuery(esQuery, esFilter));
    } else {//from  w w  w.  ja  v a 2  s .c o m
        esRequest.setQuery(esQuery);
    }
    esRequest.addAggregation(AggregationBuilders.min(facetNameAndField).field(facetNameAndField));
    Min minValue = esRequest.get().getAggregations().get(facetNameAndField);

    Double actualValue = minValue.getValue();
    if (actualValue.isInfinite()) {
        return Optional.empty();
    }
    return Optional.of(actualValue.longValue());
}

From source file:org.richfaces.tests.metamer.ftest.AbstractWebDriverTest.java

public static <T extends Number & Comparable<T>> Number countMedian(List<T> values) {
    assertTrue(values.size() > 0);/* ww  w  .ja va  2s. c  om*/
    if (values.size() == 1) {
        return values.get(0);
    }

    final List<T> copy = Lists.newArrayList(values);
    Collections.sort(copy);

    int middleIndex = (copy.size() - 1) / 2;

    double result = copy.get(middleIndex).doubleValue();
    if (copy.size() % 2 == 0) {
        result = (result + copy.get(middleIndex + 1).doubleValue()) / 2.0;
    }
    final Double median = Double.valueOf(result);
    return new Number() {
        private static final long serialVersionUID = 1L;

        @Override
        public int intValue() {
            return median.intValue();
        }

        @Override
        public long longValue() {
            return median.longValue();
        }

        @Override
        public float floatValue() {
            return median.floatValue();

        }

        @Override
        public double doubleValue() {
            return median.doubleValue();

        }

        @Override
        public String toString() {
            return median.doubleValue() + " from values(sorted) " + copy.toString() + '.';
        }
    };
}

From source file:org.eumetsat.usd.gcp.server.data.NetCDFCalibrationDataManager.java

/**
 * Add several calibration records from a certain source.
 * /*  www. j  a v a 2  s.  com*/
 * @param userID
 *            id of the user making the request.
 * @param ncfile
 *            netCDF file handler to read conversion parameters.
 * @param sourceName
 *            name of the data source.
 * @param sourceURL
 *            URL of the data source.
 * @param dateArray
 *            array of dates.
 * @param offsetArray
 *            array of offsets.
 * @param offsetSeArray
 *            array of standard deviations for offset.
 * @param slopeArray
 *            array of slopes.
 * @param slopeSeArray
 *            array of standard deviations for slope.
 * @param covarianceArray
 *            array of covariances.
 * @param channelNum
 *            channel number.
 * @param sceneTb
 *            scene brightness temperature.
 * @param radToTbConvFormula
 *            rad to tb conversion formula.
 * @param tbToRadConvFormula
 *            tb to rad conversion formula.
 * @param convVarsNames
 *            conversion variables names.
 * @throws DatasetReadException
 *             when dataset could not be opened for reading.
 * @throws InvalidFormatException
 *             when dataset has an invalid format.
 * @throws InvalidFilenameException
 *             when dataset has an invalid filename.
 * @throws VariableReadException
 * @throws ChannelNotFoundException
 * @throws VariableNotFoundException
 */
private final void addCalibrationRecords(final String userID, final NetcdfFile ncfile, final String sourceName,
        final String sourceURL, final Array dateArray, final Array offsetArray, final Array offsetSeArray,
        final Array slopeArray, final Array slopeSeArray, final Array covarianceArray, final int channelNum,
        final double sceneTb, final String radToTbConvFormula, final String tbToRadConvFormula,
        final Set<String> convVarsNames) throws BadArgumentException, InvalidFilenameException,
        DatasetReadException, VariableNotFoundException, ChannelNotFoundException, VariableReadException {
    // Check dimensions consistency.
    if ((dateArray.getShape()[0] != offsetArray.getShape()[0])
            || (dateArray.getShape()[0] != slopeArray.getShape()[0])
            || (dateArray.getShape()[0] != offsetSeArray.getShape()[0])
            || (dateArray.getShape()[0] != slopeSeArray.getShape()[0])
            || (dateArray.getShape()[0] != covarianceArray.getShape()[0])) {
        throw new BadArgumentException("array dimensions mismatch.");
    }

    // Sweep arrays and add each record into the map.
    for (int i = 0; i < dateArray.getShape()[0]; i++) {
        Double dateDouble = dateArray.getDouble(i) * 1e3; // in [ms]
        Date date = new Date(dateDouble.longValue());

        // Read the conversion variables.
        Map<String, Double> convVars = new HashMap<String, Double>();
        for (String convVarName : convVarsNames) {
            // TODO: [Remove workaround when formulas are changed]
            // Restore 'c1' and 'c2', if they are in the formula...
            if (convVarName.equals(configManager.getGlobalAttributesNames().getC1())) {
                convVars.put(C1_VARNAME, NetcdfUtils.readDouble(ncfile, convVarName, i, channelNum));

            } else if (convVarName.equals(configManager.getGlobalAttributesNames().getC2())) {
                convVars.put(C2_VARNAME, NetcdfUtils.readDouble(ncfile, convVarName, i, channelNum));
            } else {
                convVars.put(convVarName, NetcdfUtils.readDouble(ncfile, convVarName, i, channelNum));
            }
        }

        // Create calibration record.
        CalibrationRecord calRecord = new CalibrationRecordImpl(radToTbConvFormula, tbToRadConvFormula,
                convVars, TB_VARNAME, RAD_VARNAME, offsetArray.getDouble(i), offsetSeArray.getDouble(i),
                slopeArray.getDouble(i), slopeSeArray.getDouble(i), covarianceArray.getDouble(i), sceneTb);

        // Add calibration record, if valid, to data for this user.
        if (calRecord.isValid()) {
            dataForUser(userID).addRecord(date, sourceName, sourceURL, calRecord);

            // TODO: to be checked.
            // if single-point, add a second one, with same value, and shifted one second, so that
            // it can be plotted by dygraphs.
            if (dateArray.getShape()[0] == 1) {
                DateTime dt = new DateTime(date);
                dt = dt.plus(Seconds.ONE);

                dataForUser(userID).addRecord(dt.toDate(), sourceName, sourceURL, calRecord);
            }
        }
    }
}