Example usage for java.text DecimalFormatSymbols DecimalFormatSymbols

List of usage examples for java.text DecimalFormatSymbols DecimalFormatSymbols

Introduction

In this page you can find the example usage for java.text DecimalFormatSymbols DecimalFormatSymbols.

Prototype

public DecimalFormatSymbols(Locale locale) 

Source Link

Document

Create a DecimalFormatSymbols object for the given locale.

Usage

From source file:jsdp.app.inventory.univariate.StochasticLotSizing.java

static void simulate(Distribution[] distributions, double fixedOrderingCost, double holdingCost,
        double penaltyCost, double proportionalOrderingCost, double initialInventory,
        BackwardRecursionImpl recursion, double confidence, double errorTolerance) {
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
    DecimalFormat df = new DecimalFormat("#.00", otherSymbols);

    sS_Policy policy = new sS_Policy(recursion, distributions.length);
    double[][] optimalPolicy = policy.getOptimalPolicy(initialInventory);
    double[] s = optimalPolicy[0];
    double[] S = optimalPolicy[1];
    for (int i = 0; i < distributions.length; i++) {
        System.out.println("S[" + (i + 1) + "]:" + df.format(S[i]) + "\ts[" + (i + 1) + "]:" + df.format(s[i]));
    }/*  w w  w. j av a2  s. c om*/

    double[] results = SimulatePolicies.simulate_sS(distributions, fixedOrderingCost, holdingCost, penaltyCost,
            proportionalOrderingCost, initialInventory, S, s, confidence, errorTolerance);
    System.out.println();
    System.out.println("Simulated cost: " + df.format(results[0]) + " Confidence interval=("
            + df.format(results[0] - results[1]) + "," + df.format(results[0] + results[1]) + ")@"
            + df.format(confidence * 100) + "% confidence");
    System.out.println();
}

From source file:fr.cs.examples.attitude.EarthObservation_day_night_switch_with_fixed_transitions.java

/** Program entry point.
 * @param args program arguments (unused here)
 *//*from w w  w. j  ava 2s  .  c  om*/
public static void main(String[] args) {
    try {

        // configure Orekit
        Autoconfiguration.configureOrekit();
        final SortedSet<String> output = new TreeSet<String>();

        //----------------------------------------
        //  Initial state definition : date, orbit
        //----------------------------------------
        final AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 02, 00, 00, 00.000,
                TimeScalesFactory.getUTC());
        final Vector3D position = new Vector3D(-6142438.668, 3492467.560, -25767.25680);
        final Vector3D velocity = new Vector3D(505.8479685, 942.7809215, 7435.922231);
        final Orbit initialOrbit = new KeplerianOrbit(new PVCoordinates(position, velocity),
                FramesFactory.getEME2000(), initialDate, Constants.EIGEN5C_EARTH_MU);

        //------------------------------
        // Attitudes sequence definition
        //------------------------------
        final AttitudesSequence attitudesSequence = new AttitudesSequence();

        // Attitude laws definition
        //-------------------------

        // Mode : day
        final AttitudeProvider dayObservationLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(40), 0);

        // Mode : night
        final AttitudeProvider nightRestingLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH);

        // Mode : day-night rdv 1
        final AttitudeProvider dayNightRdV1Law = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(20), 0);

        // Mode : day-night rdv 2
        final AttitudeProvider dayNightRdV2Law = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), 0, 0);

        // Mode : night-day rdv 1
        final AttitudeProvider nightDayRdV1Law = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), 0, 0);

        // Mode : night-day rdv 2
        final AttitudeProvider nightDayRdV2Law = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(20), 0);

        // Event detectors definition
        //---------------------------
        final PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
        final PVCoordinatesProvider earth = CelestialBodyFactory.getEarth();

        // Detectors : end day-night rdv 2
        final DateDetector endDayNightRdV2Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to night law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-day-night-2 night-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endDayNightRdV2Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to night law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-day-night-2 night-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detectors : end day-night rdv 1
        final DateDetector endDayNightRdV1Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to day-night rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-day-night-1 day-night-rdv2-mode");
                            endDayNightRdV2Event_increase.addEventDate(s.getDate().shiftedBy(20));
                            endDayNightRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(20));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endDayNightRdV1Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to day-night rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-day-night-1 day-night-rdv2-mode");
                            endDayNightRdV2Event_increase.addEventDate(s.getDate().shiftedBy(20));
                            endDayNightRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(20));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detector : eclipse entry
        final EventDetector dayNightEvent = new EclipseDetector(sun, 696000000., earth,
                Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new EventHandler<EclipseDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final EclipseDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to day-night rdv 1 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " eclipse-entry day-night-rdv1-mode");
                            endDayNightRdV1Event_increase.addEventDate(s.getDate().shiftedBy(40));
                            endDayNightRdV1Event_decrease.addEventDate(s.getDate().shiftedBy(40));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(EclipseDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detectors : end night-day rdv 2
        final DateDetector endNightDayRdV2Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to day law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-night-day-2 day-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endNightDayRdV2Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to day law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-night-day-2 day-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detectors : end night-day rdv 1
        final DateDetector endNightDayRdV1Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to night-day rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-night-day-1 night-day-rdv2-mode");
                            endNightDayRdV2Event_increase.addEventDate(s.getDate().shiftedBy(40));
                            endNightDayRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(40));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endNightDayRdV1Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to night-day rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-night-day-1 night-day-rdv2-mode");
                            endNightDayRdV2Event_increase.addEventDate(s.getDate().shiftedBy(40));
                            endNightDayRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(40));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detector : eclipse exit
        final EventDetector nightDayEvent = new EclipseDetector(sun, 696000000., earth,
                Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new EventHandler<EclipseDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final EclipseDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to night-day rdv 1 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " eclipse-exit night-day-rdv1-mode");
                            endNightDayRdV1Event_increase.addEventDate(s.getDate().shiftedBy(20));
                            endNightDayRdV1Event_decrease.addEventDate(s.getDate().shiftedBy(20));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(EclipseDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Attitude sequences definition
        //------------------------------
        attitudesSequence.addSwitchingCondition(dayObservationLaw, dayNightEvent, false, true, dayNightRdV1Law);
        attitudesSequence.addSwitchingCondition(dayNightRdV1Law, endDayNightRdV1Event_increase, true, false,
                dayNightRdV2Law);
        attitudesSequence.addSwitchingCondition(dayNightRdV1Law, endDayNightRdV1Event_decrease, false, true,
                dayNightRdV2Law);
        attitudesSequence.addSwitchingCondition(dayNightRdV2Law, endDayNightRdV2Event_increase, true, false,
                nightRestingLaw);
        attitudesSequence.addSwitchingCondition(dayNightRdV2Law, endDayNightRdV2Event_decrease, false, true,
                nightRestingLaw);
        attitudesSequence.addSwitchingCondition(nightRestingLaw, nightDayEvent, true, false, nightDayRdV1Law);
        attitudesSequence.addSwitchingCondition(nightDayRdV1Law, endNightDayRdV1Event_increase, true, false,
                nightDayRdV2Law);
        attitudesSequence.addSwitchingCondition(nightDayRdV1Law, endNightDayRdV1Event_decrease, false, true,
                nightDayRdV2Law);
        attitudesSequence.addSwitchingCondition(nightDayRdV2Law, endNightDayRdV2Event_increase, true, false,
                dayObservationLaw);
        attitudesSequence.addSwitchingCondition(nightDayRdV2Law, endNightDayRdV2Event_decrease, false, true,
                dayObservationLaw);

        // Initialisation
        //---------------
        if (dayNightEvent.g(new SpacecraftState(initialOrbit)) >= 0) {
            // initial position is in daytime
            attitudesSequence.resetActiveProvider(dayObservationLaw);
            System.out
                    .println("# " + (initialDate.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY)
                            + " begin with day law");
        } else {
            // initial position is in nighttime
            attitudesSequence.resetActiveProvider(nightRestingLaw);
            System.out
                    .println("# " + (initialDate.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY)
                            + " begin with night law");
        }

        //----------------------
        // Propagator definition
        //----------------------

        // Propagator : consider the analytical Eckstein-Hechler model
        final Propagator propagator = new EcksteinHechlerPropagator(initialOrbit, attitudesSequence,
                Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS, Constants.EIGEN5C_EARTH_MU,
                Constants.EIGEN5C_EARTH_C20, Constants.EIGEN5C_EARTH_C30, Constants.EIGEN5C_EARTH_C40,
                Constants.EIGEN5C_EARTH_C50, Constants.EIGEN5C_EARTH_C60);
        // Register the switching events to the propagator
        attitudesSequence.registerSwitchEvents(propagator);

        propagator.setMasterMode(10.0, new OrekitFixedStepHandler() {
            private DecimalFormat f1 = new DecimalFormat("0.0000000000000000E00",
                    new DecimalFormatSymbols(Locale.US));
            private Vector3DFormat f2 = new Vector3DFormat(" ", " ", " ", f1);
            private PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
            private PVCoordinatesProvider moon = CelestialBodyFactory.getMoon();
            private Frame eme2000 = FramesFactory.getEME2000();
            private Frame itrf2005 = FramesFactory.getITRF(IERSConventions.IERS_2010, true);

            private String printVector3D(final String name, final Vector3D v) {
                return name + " " + f2.format(v);
            }

            private String printRotation(final String name, final Rotation r) {
                return name + " " + f1.format(r.getQ1()) + " " + f1.format(r.getQ2()) + " "
                        + f1.format(r.getQ3()) + " " + f1.format(r.getQ0());
            }

            private String printRotation2(final String name, final Rotation r) {
                return name + " " + f1.format(-r.getQ1()) + " " + f1.format(-r.getQ2()) + " "
                        + f1.format(-r.getQ3()) + " " + f1.format(-r.getQ0());
            }

            public void init(final SpacecraftState s0, final AbsoluteDate t) {
            }

            public void handleStep(SpacecraftState currentState, boolean isLast) throws PropagationException {
                try {
                    // the Earth position in spacecraft should be along spacecraft Z axis
                    // during nigthtime and away from it during daytime due to roll and pitch offsets
                    final Vector3D earth = currentState.toTransform().transformPosition(Vector3D.ZERO);
                    final double pointingOffset = Vector3D.angle(earth, Vector3D.PLUS_K);

                    // the g function is the eclipse indicator, its an angle between Sun and Earth limb,
                    // positive when Sun is outside of Earth limb, negative when Sun is hidden by Earth limb
                    final double eclipseAngle = dayNightEvent.g(currentState);

                    final double endNightDayTimer1 = endNightDayRdV1Event_decrease.g(currentState);
                    final double endNightDayTimer2 = endNightDayRdV2Event_decrease.g(currentState);
                    final double endDayNightTimer1 = endDayNightRdV1Event_decrease.g(currentState);
                    final double endDayNightTimer2 = endDayNightRdV2Event_decrease.g(currentState);

                    output.add(currentState.getDate() + " " + FastMath.toDegrees(eclipseAngle) + " "
                            + endNightDayTimer1 + " " + endNightDayTimer2 + " " + endDayNightTimer1 + " "
                            + endDayNightTimer2 + " " + FastMath.toDegrees(pointingOffset));
                    final AbsoluteDate date = currentState.getDate();
                    final PVCoordinates pv = currentState.getPVCoordinates(eme2000);
                    final Rotation lvlhRot = new Rotation(pv.getPosition(), pv.getMomentum(), Vector3D.MINUS_K,
                            Vector3D.MINUS_J);
                    final Rotation earthRot = eme2000.getTransformTo(itrf2005, date).getRotation();
                    System.out.println("Scenario::setVectorMap 0x960b7e0 "
                            + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " "
                            + printVector3D("sun", sun.getPVCoordinates(date, eme2000).getPosition()) + " "
                            + printVector3D("moon", moon.getPVCoordinates(date, eme2000).getPosition()) + " "
                            + printVector3D("satPos", pv.getPosition()) + " "
                            + printVector3D("satVel", pv.getVelocity()) + " "
                            + printVector3D("orbMom", pv.getMomentum()));
                    System.out.println("Scenario::setQuatMap 0x960b7e0 "
                            + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " "
                            + printRotation("earthFrame", earthRot) + " "
                            + printRotation("LVLHFrame", lvlhRot));
                    System.out.println("Scenario::computeStep 0x960b7e0 "
                            + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY));
                    System.out.println("  -> " + printRotation2("", currentState.getAttitude().getRotation())
                            + " " + printVector3D("", currentState.getAttitude().getSpin()));
                } catch (OrekitException oe) {
                    throw new PropagationException(oe);
                }
            }
        });

        //----------
        // Propagate
        //----------

        // Propagate from the initial date for the fixed duration
        propagator.propagate(initialDate.shiftedBy(1.75 * 3600.));

        //--------------
        // Print results
        //--------------

        // we print the lines according to lexicographic order, which is chronological order here
        // to make sure out of orders calls between step handler and event handlers don't mess things up
        for (final String line : output) {
            System.out.println(line);
        }

    } catch (OrekitException oe) {
        System.err.println(oe.getMessage());
    }
}

From source file:com.magestore.app.pos.service.config.POSConfigService.java

private DecimalFormat quantityFormat(ConfigQuantityFormat quantityFormat) {
    // khi to interger format
    // khi to float format
    String pattern = "###,###.#";
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
    symbols.setDecimalSeparator(quantityFormat.getDecimalSymbol().charAt(0));
    symbols.setGroupingSeparator(quantityFormat.getGroupSymbol().charAt(0));
    DecimalFormat format = new DecimalFormat(pattern, symbols);
    format.setGroupingSize(quantityFormat.getGroupLength());
    format.setMaximumFractionDigits(quantityFormat.getPrecision());
    format.setMinimumFractionDigits(0);//from   www  .j av  a 2 s.  c  om
    return format;
}

From source file:Visao.grafico.GraficoRelatorioEstoque.java

private void PreencherTabelaFiltrada() {
    //JOptionPane.showMessageDialog(null, "Size! " + jListFiltrar.getSelectedIndices().length + jListFiltrar.getModel().getSize());
    Locale brasil = new Locale("pt", "BR");
    DecimalFormat decformat = new DecimalFormat("#,##0.00", new DecimalFormatSymbols(brasil));
    ConexaoBD con = ConexaoBD.getConexao(0);
    String query = "";
    String whereSql = "";
    String andSql = "";
    ResultSet rs;/*from   w w w  .  j  av a  2  s  .  co m*/

    int mat_gem = 0;

    linhas = new ArrayList();
    colunas = new String[] { "Id", "Fazenda", "Projeto", "Material Genetico",

            "Area total", "Media geral m/ha", "Media ponderada mdc/ha", "Volume madeira praa total",
            "Volume carvao praa total",

            "Volume madeira estimada total", "Volume madeira transportada total",
            "Volume madeira processada total", "Toneladas de madeira estimada totais",
            "Toneladas de madeira transportada totais",

            "Volume carvo estimado total", "Volume carvo produzido total",
            "Volume carvo transportado total", "Toneladas de carvo estimado total",
            "Toneladas de carvo produzido total", "Toneladas de carvo transportado total" };

    /*id, fazenda, material material, area, m3ha, mdcha*/
    id = 0;

    //defini quantidade de colunas
    /*colunas = new String[tamanho];
              
    //carrega nomes das colunas selecionadas ou todas.
    for(int i = 0; i < tamanho; i++)
    {
    colunas[i] = (String) jTableRelatorioGrafico.getColumnName(i);
    }*/

    //Controle e definio das variaveis da clausula where like. Filtros
    if (jComboBoxMatGen.getSelectedItem().equals("-")) {
        filtro_matgen = "";
        mat_gem = list_mat_gen.size();
    } else {
        filtro_matgen = jComboBoxMatGen.getSelectedItem().toString();
        mat_gem = 1;
        //list_mat_gen.clear();
        //list_mat_gen.add(filtro_matgen);
    }

    //faz busca a partir dos filtros acima
    //System.out.println("list_fazendas: "+list_fazendas.size());
    //System.out.println("list_mat_gen: "+list_mat_gen.size());
    //System.out.println("mat_gem: "+mat_gem);
    for (int i = 0; i < list_fazendas.size(); i++) {
        for (int j = 0; j < mat_gem; j++) {
            //for(int k = 0; k < list_projeto.size(); k++){

            whereSql = "where fazenda = '" + list_fazendas.get(i) + "'";
            //System.out.println("list_projeto: "+list_mat_gen.size());
            //if(list_mat_gen.size()>1){
            if (filtro_matgen.equals("")) {
                whereSql += "and material_genetico = '" + list_mat_gen.get(j) + "'";
                //System.out.println("list_mat_gen: "+list_mat_gen.get(j));
            } else {
                whereSql += " and material_genetico = '" + filtro_matgen + "'";
                //System.out.println("filtro_matgen: "+filtro_matgen);
            }

            query = "SELECT * FROM estoque_principal " + whereSql + " ORDER BY fazenda,projeto,upc,talhao ASC";

            //System.out.println("Query: "+query);

            fazenda = "";
            projeto = "";
            material_genetico = "";
            areaTotal = 0;
            m3_haMedia = 0;
            mdc_haMedia = 0;
            vol_mad_pracaTotal = 0;
            vol_carv_pracaTotal = 0;
            vol_mad_estTotal = 0;
            vol_mad_transpTotal = 0;
            vol_mad_procTotal = 0;
            madeira_fornoTotal = 0;
            mad_ton_estTotal = 0;
            mad_ton_transpTotal = 0;
            mdc_estTotal = 0;
            mdc_prodTotal = 0;
            mdc_transpTotal = 0;
            carv_ton_estTotal = 0;
            carv_ton_prodTotal = 0;
            carv_ton_transpTotal = 0;
            media_idades = 0;
            cont = 0;
            //System.out.println("Query: " + query);
            //carrega dados do banco de dados dependendo da consulta sql
            rs = con.consultaSql(query);
            //cria um objeto coluna de acordo com as colunas selecionadas para cada linha encontrada na consulta
            Object[] coluna = new Object[TAMANHO];
            try {
                while (rs.next()) {

                    //coluna[31] = decformat.format(rs.getString("vol_mad_estimado"));
                    //System.out.println("Add Dados ["+31+"]: "+coluna[31]);
                    projeto = rs.getString("projeto");
                    //area total
                    if (rs.getString("area") != null) {
                        areaTotal += Float.valueOf(rs.getString("area"));
                    }

                    //media aritmetica  m3/ha
                    if (rs.getString("m3_ha") != null && Float.valueOf(rs.getString("m3_ha")) > 0) {
                        //m3_haMedia += Float.valueOf(rs.getString("m3_ha"));
                        m3_haMedia += Float.valueOf(rs.getString("m3_ha"))
                                * Float.valueOf(rs.getString("area"));
                    }

                    //media ponderada mdc/ha
                    if (rs.getString("mdc_ha") != null && Float.valueOf(rs.getString("mdc_ha")) > 0) {
                        mdc_haMedia += Float.valueOf(rs.getString("mdc_ha"))
                                * Float.valueOf(rs.getString("area"));
                    }

                    //madeira praa total
                    if (rs.getString("madeira_praca") != null
                            && Float.valueOf(rs.getString("madeira_praca")) > 0) {
                        vol_mad_pracaTotal += Float.valueOf(rs.getString("madeira_praca"));
                    }

                    //carvo praa total
                    if (rs.getString("carvao_praca") != null
                            && Float.valueOf(rs.getString("carvao_praca")) > 0) {
                        vol_carv_pracaTotal += Float.valueOf(rs.getString("carvao_praca"));
                    }

                    //Volumes totais de madeira
                    if (rs.getString("vol_mad_estimado") != null) {
                        vol_mad_estTotal += Float.valueOf(rs.getString("vol_mad_estimado"));
                    }
                    if (rs.getString("vol_mad_transp") != null) {
                        vol_mad_transpTotal += Float.valueOf(rs.getString("vol_mad_transp"));
                    }
                    if (rs.getString("madeira_forno") != null) {
                        madeira_fornoTotal += Float.valueOf(rs.getString("madeira_forno"));
                    }

                    //Toneladas totais de madeira
                    if (rs.getString("mad_ton_estimado") != null) {
                        mad_ton_estTotal += Float.valueOf(rs.getString("mad_ton_estimado"));
                    }
                    if (rs.getString("mad_ton_transp") != null) {
                        mad_ton_transpTotal += Float.valueOf(rs.getString("mad_ton_transp"));
                    }

                    //Volumes totais de carvao
                    if (rs.getString("mdc_estimado") != null) {
                        mdc_estTotal += Float.valueOf(rs.getString("mdc_estimado"));
                    }
                    if (rs.getString("mdc_prod") != null) {
                        mdc_prodTotal += Float.valueOf(rs.getString("mdc_prod"));
                    }
                    if (rs.getString("mdc_transp") != null) {
                        mdc_transpTotal += Float.valueOf(rs.getString("mdc_transp"));
                    }

                    //Toneladas totais de carvao
                    if (rs.getString("carv_ton_estimado") != null) {
                        carv_ton_estTotal += Float.valueOf(rs.getString("carv_ton_estimado"));
                    }
                    if (rs.getString("carv_ton_prod") != null) {
                        carv_ton_prodTotal += Float.valueOf(rs.getString("carv_ton_prod"));
                    }
                    if (rs.getString("carv_ton_transp") != null) {
                        carv_ton_transpTotal += Float.valueOf(rs.getString("carv_ton_transp"));
                    }

                    if (rs.getString("idade_hoje") != null) {
                        media_idades += Float.valueOf(rs.getString("idade_hoje"));
                        cont++;
                    }
                    //System.out.printf("\nCalculo m3ha: "+ m3_haMedia); 
                }

                if (areaTotal > 0) {
                    mdc_haMedia = mdc_haMedia / areaTotal;
                    m3_haMedia = m3_haMedia / areaTotal;

                    fazenda = list_fazendas.get(i).toString();
                    System.out.println("list_mat_gen: " + list_mat_gen.size());
                    if (mat_gem > 1) {
                        material_genetico = list_mat_gen.get(j).toString();
                    } else {
                        material_genetico = jComboBoxMatGen.getSelectedItem().toString();
                    }

                    System.out.println("material_genetico: " + material_genetico);

                    coluna[0] = id;
                    coluna[1] = fazenda;
                    coluna[2] = projeto;
                    coluna[3] = material_genetico;

                    coluna[4] = areaTotal;
                    coluna[5] = m3_haMedia;
                    coluna[6] = mdc_haMedia;

                    coluna[7] = vol_mad_pracaTotal;
                    coluna[8] = vol_carv_pracaTotal;

                    coluna[9] = vol_mad_estTotal;
                    coluna[10] = vol_mad_transpTotal;
                    coluna[11] = madeira_fornoTotal;
                    coluna[12] = mad_ton_estTotal;
                    coluna[13] = mad_ton_transpTotal;

                    coluna[14] = mdc_estTotal;
                    coluna[15] = mdc_prodTotal;
                    coluna[16] = mdc_transpTotal;
                    coluna[17] = carv_ton_estTotal;
                    coluna[18] = carv_ton_prodTotal;
                    coluna[19] = carv_ton_transpTotal;
                    //coluna[20]=media_idades;

                    //adiciona a cada linha os valores de cada objeto coluna
                    linhas.add(coluna);
                    id++;
                } else {
                    mdc_haMedia = 0;
                    m3_haMedia = 0;
                }

                //System.out.printf("\nlinha m3ha: "+ linhas.get(id));                     
                //System.out.printf("\nCalculo m3ha: "+ m3_haMedia); 

            } catch (SQLException ex) {
                Logger.getLogger(GerarRelatorioEstoqueBasico.class.getName()).log(Level.SEVERE, null,
                        "Erro ao Preencher Tabela Filtrada ! " + ex);
                JOptionPane.showMessageDialog(null, "Erro ao Preencher Tabela Filtrada ! " + ex);
            }
        }
        //}
    }
    //System.out.printf("\nLinha m3ha: "+ linhas.get(0));   

    MontarTabela();
    con.fecharConexao();
}

From source file:org.mitre.ccv.mapred.CalculateCosineDistanceMatrix.java

/**
 * Writes out the matrix in row major (packed) order. No labels are outputed.
 *
 * @param jobConf/*from w w w  .  j  a  v  a  2 s . c  o  m*/
 * @param input
 * @param output
 * @param digits
 * @throws IOException
 */
public static void printRowMajorMatrix(JobConf jobConf, String input, String output, int digits)
        throws IOException {
    JobConf conf = new JobConf(jobConf, CalculateCosineDistanceMatrix.class);

    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(digits);
    //format.setMinimumFractionDigits(fractionDigits);
    format.setGroupingUsed(false);

    final Path inputPath = new Path(input);
    final FileSystem fs = inputPath.getFileSystem(conf);
    final Path qInputPath = fs.makeQualified(inputPath);
    final Path outputPath = new Path(output);
    Path[] paths = FileUtils.ls(conf, qInputPath.toString() + Path.SEPARATOR + "part-*");

    FSDataOutputStream fos = fs.create(outputPath, true); // throws nothing!
    final Writer writer = new OutputStreamWriter(fos);
    final Text key = new Text();
    final DenseVectorWritable value = new DenseVectorWritable();
    for (int idx = 0; idx < paths.length; idx++) {
        SequenceFile.Reader reader = new SequenceFile.Reader(fs, paths[idx], conf);
        boolean hasNext = reader.next(key, value);
        while (hasNext) {

            final DenseVector vector = value.get();
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < vector.getCardinality(); i++) {
                final String s = format.format(vector.get(i)); // format the number
                sb.append(s);
                sb.append(' ');
            }
            writer.write(sb.toString());
            hasNext = reader.next(key, value);
        }
        try {
            writer.flush();
            reader.close();
        } catch (IOException ioe) {
            // closing the SequenceFile.Reader will throw an exception if the file is over some unknown size
            LOG.debug("Probably caused by closing the SequenceFile.Reader. All is well", ioe);
        }
    }
    try {
        writer.close();
        fos.flush();
        fos.close();
    } catch (IOException ioe) {
        LOG.debug("Caused by distributed cache output stream.", ioe);
    }
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.XYAreaLineChartExpression.java

protected void configureChart(final JFreeChart chart) {
    super.configureChart(chart);

    final XYPlot plot = chart.getXYPlot();

    if (isSharedRangeAxis() == false) {
        final ValueAxis linesAxis = plot.getRangeAxis(1);
        if (linesAxis instanceof NumberAxis) {
            final NumberAxis numberAxis = (NumberAxis) linesAxis;
            numberAxis.setAutoRangeIncludesZero(isLineAxisIncludesZero());
            numberAxis.setAutoRangeStickyZero(isLineAxisStickyZero());

            if (getLinePeriodCount() > 0) {
                if (getLineTicksLabelFormat() != null) {
                    final FastDecimalFormat formatter = new FastDecimalFormat(getLineTicksLabelFormat(),
                            getResourceBundleFactory().getLocale());
                    numberAxis.setTickUnit(new FastNumberTickUnit(getLinePeriodCount(), formatter));
                } else {
                    numberAxis.setTickUnit(new FastNumberTickUnit(getLinePeriodCount()));
                }/* www  . j  a va 2s. com*/
            } else {
                if (getLineTicksLabelFormat() != null) {
                    final DecimalFormat formatter = new DecimalFormat(getLineTicksLabelFormat(),
                            new DecimalFormatSymbols(getResourceBundleFactory().getLocale()));
                    numberAxis.setNumberFormatOverride(formatter);
                }
            }
        } else if (linesAxis instanceof DateAxis) {
            final DateAxis numberAxis = (DateAxis) linesAxis;

            if (getLinePeriodCount() > 0 && getLineTimePeriod() != null) {
                if (getLineTicksLabelFormat() != null) {
                    final SimpleDateFormat formatter = new SimpleDateFormat(getLineTicksLabelFormat(),
                            new DateFormatSymbols(getResourceBundleFactory().getLocale()));
                    numberAxis.setTickUnit(new DateTickUnit(getDateUnitAsInt(getLineTimePeriod()),
                            (int) getLinePeriodCount(), formatter));
                } else {
                    numberAxis.setTickUnit(new DateTickUnit(getDateUnitAsInt(getLineTimePeriod()),
                            (int) getLinePeriodCount()));
                }
            } else if (getRangeTickFormatString() != null) {
                final SimpleDateFormat formatter = new SimpleDateFormat(getRangeTickFormatString(),
                        new DateFormatSymbols(getResourceBundleFactory().getLocale()));
                numberAxis.setDateFormatOverride(formatter);
            }
        }

        if (linesAxis != null) {
            final Font labelFont = Font.decode(getLabelFont());
            linesAxis.setLabelFont(labelFont);
            linesAxis.setTickLabelFont(labelFont);

            if (getLineTitleFont() != null) {
                linesAxis.setLabelFont(getLineTitleFont());
            }
            if (getLineTickFont() != null) {
                linesAxis.setTickLabelFont(getLineTickFont());
            }
            final int level = getRuntime().getProcessingContext().getCompatibilityLevel();
            if (ClassicEngineBoot.isEnforceCompatibilityFor(level, 3, 8)) {
                final double lineRangeMinimumVal = lineRangeMinimum == null ? 0 : lineRangeMinimum;
                final double lineRangeMaximumVal = lineRangeMaximum == null ? 0 : lineRangeMaximum;
                if (lineRangeMinimum != null) {
                    linesAxis.setLowerBound(getLineRangeMinimum());
                }
                if (lineRangeMaximum != null) {
                    linesAxis.setUpperBound(getRangeMaximum());
                }
                if (lineRangeMinimumVal == 0 && lineRangeMaximumVal == 1) {
                    linesAxis.setLowerBound(0);
                    linesAxis.setUpperBound(1);
                    linesAxis.setAutoRange(true);
                }
            } else {
                if (lineRangeMinimum != null) {
                    linesAxis.setLowerBound(lineRangeMinimum);
                }
                if (lineRangeMaximum != null) {
                    linesAxis.setUpperBound(lineRangeMaximum);
                }
                linesAxis.setAutoRange(isLineAxisAutoRange());
            }
        }
    }

    final XYLineAndShapeRenderer linesRenderer = (XYLineAndShapeRenderer) plot.getRenderer(1);
    if (linesRenderer != null) {
        //set stroke with line width
        linesRenderer.setStroke(translateLineStyle(getLineWidth(), getLineStyle()));
        //hide shapes on line
        linesRenderer.setShapesVisible(isMarkersVisible());
        linesRenderer.setBaseShapesFilled(isMarkersVisible());

        //set colors for each line
        for (int i = 0; i < lineSeriesColor.size(); i++) {
            final String s = (String) lineSeriesColor.get(i);
            linesRenderer.setSeriesPaint(i, parseColorFromString(s));
        }
    }
}

From source file:com.itude.mobile.mobbl.core.util.StringUtilities.java

public static String formatVolume(String stringToFormat) {
    if (stringToFormat == null || stringToFormat.length() == 0) {
        return null;
    }/*from  w  w w .j av  a  2 s. c  o m*/

    String result = null;

    DecimalFormat formatter = new DecimalFormat();
    formatter.setDecimalFormatSymbols(new DecimalFormatSymbols(getDefaultFormattingLocale()));

    formatter.setGroupingUsed(true);
    formatter.setGroupingSize(3);
    formatter.setMaximumFractionDigits(0);

    result = formatter.format(Double.parseDouble(stringToFormat));

    return result;
}

From source file:net.sf.morph.transform.converters.TextToNumberConverter.java

/**
 * Remove any characters that should be ignored when performing the
 * conversion./* w w  w . j a v a 2 s.  com*/
 * 
 * @param string
 *            the input string
 * @param locale
 *            the locale
 * @return <code>string</code>, with all characters that should be
 *         ignored removed
 */
private StringBuffer removeIgnoredCharacters(String string, Locale locale) {
    StringBuffer charactersToParse = new StringBuffer();
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
    for (int i = 0; i < string.length(); i++) {
        char currentChar = string.charAt(i);
        if (getWhitespaceHandling() == WHITESPACE_IGNORE && Character.isWhitespace(currentChar)) {
            continue;
        }
        if (getCurrencyHandling() == CURRENCY_IGNORE
                && Character.getType(currentChar) == Character.CURRENCY_SYMBOL) {
            continue;
        }
        if (getPercentageHandling() == PERCENTAGE_IGNORE) {
            if (currentChar == symbols.getPercent()) {
                continue;
            }
        }
        if (getParenthesesHandling() == PARENTHESES_IGNORE) {
            if (currentChar == LEFT_PARENTHESES || currentChar == RIGHT_PARENTHESES) {
                continue;
            }
        }
        charactersToParse.append(currentChar);
    }
    return charactersToParse;
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.CategoricalChartExpressionTest.java

private void assertTickUnitSizeByPattern(String pattern, double tickUnitSize) {
    NumberAxis axis = new NumberAxis();
    DecimalFormat formatter = new DecimalFormat(pattern, new DecimalFormatSymbols(new Locale("en_US")));
    expression.standardTickUnitsApplyFormat(axis, formatter);
    final TickUnits standardTickUnits = (TickUnits) axis.getStandardTickUnits();
    // first n standard tick unit elements should be removed
    Assert.assertEquals(tickUnitSize, standardTickUnits.get(0).getSize(), 0.0000000001);
}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

public get_geocaches_ret get_geocaches_v3(Coordinate[] location, int count_p, int max_p, int rec_depth,
        Handler h, int zoom_level) {
    this.main_aagtl.set_bar_slow(h, "get geocaches", "downloading ...", count_p, max_p, true);

    Coordinate c1 = location[0];// w w w .  ja  va  2  s .  c  o m
    Coordinate c2 = location[1];

    Coordinate center = new Coordinate((c1.lat + c2.lat) / 2, (c1.lon + c2.lon) / 2);
    double dist = (center.distance_to(c1) / 1000) / 2;
    //System.out.println("distance is " + dist + " meters");

    if (dist > 100) {
        // dist too large
        count_p = count_p + 1;
        get_geocaches_ret r = new get_geocaches_ret();
        r.count_p = count_p;
        r.points = null;
        return r;
    }

    // use "." as comma seperator!!
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
    otherSymbols.setDecimalSeparator('.');
    otherSymbols.setGroupingSeparator(',');
    DecimalFormat format_lat_lon = new DecimalFormat("#.#####", otherSymbols);
    // use "." as comma seperator!!

    String lat_str = format_lat_lon.format(center.lat);
    String lon_str = format_lat_lon.format(center.lon);
    String dist_str = format_lat_lon.format(dist);
    String url = "http://www.geocaching.com/seek/nearest.aspx?lat=" + lat_str + "&lng=" + lon_str + "&dist="
            + dist_str;
    //System.out.println("url=" + url);

    List<NameValuePair> values_list = new ArrayList<NameValuePair>();
    //values_list.add(new BasicNameValuePair("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"));
    //values_list.add(new BasicNameValuePair("Pragma", "no-cache"));
    // ByteArrayOutputStream bs = new ByteArrayOutputStream();
    String the_page = get_reader_stream(url, values_list, null, true);

    get_geocaches_ret r2 = new get_geocaches_ret();
    r2.count_p = count_p;
    r2.points = null;

    Boolean cont = true;
    Source source = null;

    List<GeocacheCoordinate> gc_list = new ArrayList<GeocacheCoordinate>();
    count_p = 0;
    max_p = 0;
    while (cont) {
        source = new Source(the_page);
        List<? extends Segment> segments = (source
                .getFirstElement("id", "ctl00_ContentBody_ResultsPanel", false).getContent()
                .getFirstElement("class", "PageBuilderWidget", false).getContent().getAllElements("b"));
        if (segments.size() < 3) {
            // no results
            return r2;
        }

        int count = Integer.parseInt(segments.get(0).getTextExtractor().toString());
        int page_current = Integer.parseInt(segments.get(1).getTextExtractor().toString());
        int page_max = Integer.parseInt(segments.get(2).getTextExtractor().toString());
        //System.out.println("count=" + count + " cur=" + page_current + " max=" + page_max);
        max_p = count;

        String guid = "";
        String gccode = "";
        Boolean disabled = false;
        List<? extends Segment> segments2 = (source.getFirstElement("class", "SearchResultsTable Table", false)
                .getContent().getAllElements(HTMLElementName.TR));
        // displaySegments(segments2);
        try {
            for (Segment s_ : segments2) {
                guid = "";
                disabled = false;
                gccode = null;
                try {
                    List<? extends Segment> segments3 = s_.getAllElements("class", "Merge", false);
                    // displaySegments(segments2);
                    guid = segments3.get(0).getFirstElement(HTMLElementName.A).getAttributeValue("href");
                    guid = guid.split("guid=", 3)[1];
                    //System.out.println("guid=:" + guid);

                    try {
                        // <a href="/seek/cache_details.aspx?guid=d9dbf39a-e2e6-4640-b951-d1d6307b16bd" class="lnk  Strike"><span>Cineasten sehen mehr</span></a>
                        if (segments3.get(1).getFirstElement(HTMLElementName.A).getAttributeValue("class")
                                .equalsIgnoreCase("lnk  Strike")) {
                            // System.out.println("disabled=:" + disabled);
                            disabled = true;
                        }
                    } catch (Exception e3) {
                    }

                    gccode = segments3.get(1).getFirstElement("class", "small", false).getTextExtractor()
                            .toString();
                    gccode = gccode.split("\\|")[1].trim();
                    //System.out.println("gccode=:" + gccode);
                } catch (Exception e2) {
                    e2.printStackTrace();
                }

                if (gccode != null) {
                    GeocacheCoordinate c__ = null;
                    c__ = new GeocacheCoordinate(0, 0, gccode);
                    if (disabled) {
                        c__.status = GeocacheCoordinate.STATUS_DISABLED;
                    }

                    String url2 = "http://www.geocaching.com/seek/cdpf.aspx?guid=" + guid;
                    //System.out.println("url=" + url);

                    values_list = new ArrayList<NameValuePair>();
                    //values_list.add(new BasicNameValuePair("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"));
                    //values_list.add(new BasicNameValuePair("Pragma", "no-cache"));
                    // bs = new ByteArrayOutputStream();
                    String the_page2 = get_reader_stream(url2, values_list, null, true);
                    c__ = CacheDownloader.__parse_cache_page_print(the_page2, c__);
                    if (c__ != null) {
                        gc_list.add(c__);
                        count_p = count_p + 1;
                        this.main_aagtl.set_bar_slow(h, "get geocaches", c__.title, count_p, max_p, true);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        cont = false;

        // ----------- check for paging ----------------
        // ----------- and run through pages -----------
        //
        if (page_current < page_max) {
            FormFields formFields = source.getFormFields();
            String vs1 = null;
            try {
                vs1 = formFields.getValues("__VIEWSTATE1").get(0);
            } catch (Exception e) {

            }
            String vs = null;
            try {
                vs = formFields.getValues("__VIEWSTATE").get(0);
            } catch (Exception e) {

            }

            //System.out.println("vs=" + vs);
            //System.out.println("vs1=" + vs1);

            List<NameValuePair> values_list2 = new ArrayList<NameValuePair>();
            values_list2.add(new BasicNameValuePair("__EVENTTARGET", "ctl00$ContentBody$pgrTop$ctl08"));
            values_list2.add(new BasicNameValuePair("__VIEWSTATEFIELDCOUNT", "2"));
            values_list2.add(new BasicNameValuePair("__VIEWSTATE", vs));
            values_list2.add(new BasicNameValuePair("__VIEWSTATE1", vs1));
            // ByteArrayOutputStream bs = new ByteArrayOutputStream();
            the_page = get_reader_stream(url, values_list2, null, true);
            cont = true;
        }
        // ----------- check for paging ----------------
        // ----------- and run through pages -----------
    }

    int jk;
    r2.count_p = gc_list.size();
    r2.points = new GeocacheCoordinate[gc_list.size()];

    for (jk = 0; jk < gc_list.size(); jk++) {
        r2.points[jk] = gc_list.get(jk);
    }
    // gc_list.clear();

    return r2;
}