Example usage for org.apache.commons.lang ArrayUtils toPrimitive

List of usage examples for org.apache.commons.lang ArrayUtils toPrimitive

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils toPrimitive.

Prototype

public static boolean[] toPrimitive(Boolean[] array) 

Source Link

Document

Converts an array of object Booleans to primitives.

Usage

From source file:aldenjava.opticalmapping.data.data.OptMapDataReader.java

private DataNode parseFA01() throws IOException {
    if (nextline == null)
        return null;
    String name = nextline.substring(1);
    StringBuilder zeroOneString = new StringBuilder();
    String s;/*from   ww  w.j  a v  a  2s .c om*/
    while ((s = br.readLine()) != null) {
        if (s.startsWith(">")) {
            nextline = s;
            break;
        } else
            zeroOneString = zeroOneString.append(s);
    }

    if (zeroOneString.length() == 0)
        return null;
    else {
        long ref_size = zeroOneString.length();
        long zero = 0;
        List<Long> refl = new ArrayList<Long>();
        List<Long> refp = new ArrayList<Long>();
        for (long i = 0; i < ref_size; i++) {
            if (zeroOneString.charAt((int) i) == '0')
                zero++;
            else if (zeroOneString.charAt((int) i) == '1') {
                refl.add(zero);
                refp.add(i);
                zero = 0;
            }
        }
        refl.add(zero);
        return new DataNode(name, zeroOneString.length(),
                ArrayUtils.toPrimitive(refp.toArray(new Long[refp.size()])));
    }
}

From source file:com.runwaysdk.generation.loader.RunwayClassLoader.java

/**
 *
 *///from w  w  w.  j a v a2  s . c  o  m
protected Class<?> findClass(final String name) throws ClassNotFoundException {
    String mod = name.replace('.', '/') + ".class";
    URL res = this.findResource(mod);
    if (res != null) {
        try {
            Class<?> clazz = null;

            Byte[] objectArray = FileIO.getBytesFromStream(res.openStream());
            byte[] classBytes = ArrayUtils.toPrimitive(objectArray);
            if (implementsReloadable(classBytes)) {
                clazz = defineClass(name, classBytes, 0, classBytes.length);
                classes.put(name, clazz);
                return clazz;
            }
        } catch (IOException e1) {
            throw new ClassNotFoundException("Error reading class " + name);
        }
        // throw new ClassNotFoundException("Unable to find class " + name);
    }
    return null;
}

From source file:edu.isi.misd.scanner.network.modules.master.processors.glore.GloreAggregateProcessor.java

/**
 * Camel {@link org.apache.camel.Processor} implementation -- 
 * the majority of the work is handled in this function implementation.
 *//*from  w  w w.  j a v a  2  s .c om*/
@Override
public void process(Exchange exchange) throws Exception {
    // creates the aggregate ServiceResponses object
    super.process(exchange);

    // fail fast - treating GLORE as transactional for now,
    // so if any part of the request fails, the entire request fails.
    List<ServiceResponse> errorResponses = getErrorResponses(exchange);
    if (!errorResponses.isEmpty()) {
        ServiceResponses responses = new ServiceResponses();
        responses.getServiceResponse().addAll(errorResponses);
        exchange.getIn().setBody(responses);

        // signal complete
        exchange.setProperty("status", "complete");
        return;
    }

    List<GloreLogisticRegressionRequest> gloreRequestList = getTypedResponses(exchange,
            GloreLogisticRegressionRequest.class);
    if (gloreRequestList.isEmpty()) {
        ErrorUtils.setHttpError(exchange, new NullPointerException("Null Glore aggregate results"), 500);
        return;
    }

    GloreLogisticRegressionRequest request = gloreRequestList.get(0);
    GloreData gloreData = request.getGloreData();
    if (gloreData == null) {
        ErrorUtils.setHttpError(exchange, new NullPointerException("Null Glore state data"), 500);
        return;
    }

    // replace the getFeatures with the standardized input parameters
    LogisticRegressionInputParameters params = request.getLogisticRegressionInput().getInputParameters();
    ArrayList<String> independentVariables = new ArrayList<>(params.getIndependentVariableName());
    int features = independentVariables.size() + 1;

    int iter = gloreData.getIteration();
    Matrix beta0, beta1;

    if ("computeCovarianceMatrix".equalsIgnoreCase(gloreData.getState())) {
        if (log.isDebugEnabled()) {
            log.debug("Compute covariance matrix");
        }
        ArrayList<double[][]> D_values = new ArrayList<double[][]>();
        for (GloreLogisticRegressionRequest gloreRequest : gloreRequestList) {
            Matrix D = GloreUtils.convertMatrixTypeToMatrix(gloreRequest.getGloreData().getD());
            D_values.add(D.getArray());
        }
        Matrix temp_b = new Matrix(row_sums_two_dim(D_values, features));
        Matrix temp_c = diag(0.0000001, features);

        temp_b = temp_b.plus(temp_c);
        Matrix cov_matrix = temp_b.inverse();

        if (log.isDebugEnabled()) {
            log.debug("Covariance matrix:" + GloreUtils.matrixToString(cov_matrix, 8, 6));
        }

        gloreData.setCovarianceMatrix(GloreUtils.convertMatrixToMatrixType(cov_matrix));
        gloreData.setState("computeSDMatrix");

    } else if ("computeSDMatrix".equalsIgnoreCase(gloreData.getState())) {
        if (log.isDebugEnabled()) {
            log.debug("Compute SD matrix");
        }

        Matrix cov_matrix = GloreUtils.convertMatrixTypeToMatrix(gloreData.getCovarianceMatrix());

        Matrix SD = new Matrix(1, features);
        for (int i = 0; i < features; i++) {
            SD.set(0, i, Math.sqrt(cov_matrix.get(i, i)));
        }
        if (log.isDebugEnabled()) {
            log.debug("SD Matrix: " + GloreUtils.matrixToString(SD, 8, 6));
        }

        int totalRows = 0;
        double[] M = new double[features];
        double[] STD = new double[features];

        for (GloreLogisticRegressionRequest gloreRequest : gloreRequestList) {
            double[] tempM = ArrayUtils.toPrimitive(gloreRequest.getGloreData().getM().toArray(new Double[0]));
            double[] tempSTD = ArrayUtils
                    .toPrimitive(gloreRequest.getGloreData().getSTD().toArray(new Double[0]));
            int tempRows = gloreRequest.getGloreData().getRows();
            M[0] = 0;
            STD[0] = 0;
            for (int i = 1; i < features; i++) {
                M[i] = M[i] + tempM[i];
                STD[i] = STD[i] + tempSTD[i];
                totalRows = totalRows + tempRows;
            }
        }

        for (int i = 0; i < features; i++) {
            M[i] = M[i] / totalRows;
            STD[i] = Math.sqrt(STD[i] / totalRows - Math.pow(M[i], 2));
        }

        gloreData.setState("complete");

        // prepare GLORE outputs            
        GloreLogisticRegressionResponse gloreResponse = new GloreLogisticRegressionResponse();
        LogisticRegressionResponse lrResponse = new LogisticRegressionResponse();
        LogisticRegressionOutput output = new LogisticRegressionOutput();
        // need to decide how best to handle the DataSetID
        //response.setDataSetID("GLORE server");  
        lrResponse.setInput(request.getLogisticRegressionInput());
        lrResponse.getOutput().add(output);
        List<Coefficient> target = output.getCoefficient();
        Matrix fBeta = GloreUtils.convertMatrixTypeToMatrix(gloreData.getBeta());

        // set intercept
        Coefficient coefficient = new Coefficient();
        coefficient.setB(GloreUtils.df(fBeta.get(0, 0)));
        coefficient.setSE(GloreUtils.df(SD.get(0, 0)));
        coefficient.setTStatistics(GloreUtils.df(fBeta.get(0, 0) / SD.get(0, 0)));
        coefficient.setDegreeOfFreedom(1);
        coefficient.setPValue(GloreUtils.df(ztest(fBeta.get(0, 0) / SD.get(0, 0))));
        coefficient.setName("Intercept");
        //add two more attributes
        coefficient.setM(GloreUtils.df(M[0]));
        coefficient.setSTD(GloreUtils.df(STD[0]));

        target.add(coefficient);

        //set the rest of the attributes
        for (int i = 1; i < fBeta.getColumnPackedCopy().length; i++) {
            coefficient = new Coefficient();
            coefficient.setB(GloreUtils.df(fBeta.get(i, 0)));
            coefficient.setSE(GloreUtils.df(SD.get(0, i)));
            coefficient.setTStatistics(GloreUtils.df(fBeta.get(i, 0) / SD.get(0, i)));
            coefficient.setDegreeOfFreedom(1);
            coefficient.setPValue(GloreUtils.df(ztest(fBeta.get(i, 0) / SD.get(0, i))));
            coefficient.setName(independentVariables.get(i - 1));

            //add two more attributes
            coefficient.setM(GloreUtils.df(M[i - 1]));
            coefficient.setSTD(GloreUtils.df(STD[i - 1]));

            target.add(coefficient);
        }
        gloreResponse.setLogisticRegressionResponse(lrResponse);

        // format the service response objects and set as the result body
        ServiceResponseData responseData = new ServiceResponseData();
        responseData.setAny(gloreResponse);
        ServiceResponse response = new ServiceResponse();
        response.setServiceResponseData(responseData);
        Calendar start = exchange.getProperty(BaseConstants.EXECUTION_START, Calendar.class);
        Calendar end = Calendar.getInstance();
        ServiceResponseMetadata responseMetadata = MessageUtils.createServiceResponseMetadata(exchange,
                ServiceRequestStateType.COMPLETE, "The distributed GLORE analysis completed successfully.",
                MessageUtils.formatEventDuration(start, end));
        response.setServiceResponseMetadata(responseMetadata);
        ServiceResponses responses = new ServiceResponses();
        responses.getServiceResponse().add(response);
        exchange.getIn().setBody(responses);

        // signal complete
        exchange.setProperty("status", "complete");
        return;
    } else {
        if (iter == 0) {
            if (log.isDebugEnabled()) {
                log.debug("Primary iteration phase");
            }
            // init beta vectors
            beta0 = new Matrix(features, 1, -1.0);
            beta1 = new Matrix(features, 1, 0.0);
            if (log.isDebugEnabled()) {
                log.debug("Initial iteration value: " + GloreUtils.max_abs((beta1.minus(beta0)).getArray()));
            }
            gloreData.setState("iteration");
        } else {
            beta1 = GloreUtils.convertMatrixTypeToMatrix(gloreData.getBeta());
        }

        beta0 = beta1.copy();
        /* beta1<-beta0+solve(rowSums(d,dims=2)+
           diag(0.0000001,m))%*%(rowSums(e,dims=2)) */
        ArrayList<double[]> E_values = new ArrayList<double[]>();
        for (GloreLogisticRegressionRequest gloreRequest : gloreRequestList) {
            Matrix E = GloreUtils.convertMatrixTypeToMatrix(gloreRequest.getGloreData().getE());
            double[] e = new double[features];
            for (int i = 0; i < features; i++) {
                e[i] = E.get(i, 0);
            }
            E_values.add(e);
        }
        Matrix temp_a = new Matrix(row_sums_one_dim(E_values, features));

        ArrayList<double[][]> D_values = new ArrayList<double[][]>();
        for (GloreLogisticRegressionRequest gloreRequest : gloreRequestList) {
            Matrix D = GloreUtils.convertMatrixTypeToMatrix(gloreRequest.getGloreData().getD());
            D_values.add(D.getArray());
        }
        Matrix temp_b = new Matrix(row_sums_two_dim(D_values, features));

        Matrix temp_c = diag(0.0000001, features);
        temp_b = temp_b.plus(temp_c);
        temp_b = temp_b.inverse();
        temp_b = temp_b.times(temp_a);
        beta1 = beta0.plus(temp_b);
        if (log.isDebugEnabled()) {
            log.debug("beta1:" + GloreUtils.matrixToString(beta1, 10, 12));
        }

        gloreData.setBeta(GloreUtils.convertMatrixToMatrixType(beta1));
        if (log.isDebugEnabled()) {
            log.debug("Iteration " + iter + " value: " + GloreUtils.max_abs((beta1.minus(beta0)).getArray()));
        }

        if (iter > 0) {
            if ((GloreUtils.max_abs((beta1.minus(beta0)).getArray()) < epsilon) || (iter >= max_iter)) {
                if (iter >= max_iter) {
                    log.info("Hit maximum number of iterations (" + max_iter
                            + ") without converging, iterations stopped.");
                }
                if (log.isDebugEnabled()) {
                    log.debug("Iteration final value: " + GloreUtils.max_abs((beta1.minus(beta0)).getArray()));
                }
                gloreData.setState("computeCovarianceMatrix");
            }
        }
        gloreData.setIteration(iter + 1);
    }

    exchange.getIn().setBody(request);
}

From source file:au.org.ala.delta.intkey.ui.MultiStateInputDialog.java

/**
 * ctor//from  w ww  . j a  v a 2s.c  o  m
 * 
 * @param owner
 *            Owner frame of dialog
 * @param ch
 *            the character whose states are being set
 * @param initialSelectedStates
 *            initial states that should be selected in the dialog. In
 *            general this should be any states already set for the
 *            character. In the case that this is a controlling character
 *            being set before its dependent character, all states that make
 *            the dependent character applicable should be selected.
 * @param dependentCharacter
 *            the dependent character - if the dialog is being used to set a
 *            controlling character before its dependent character, this
 *            argument should be a reference to the dependent character. In
 *            all other cases it should be null.
 * @param imageSettings
 *            image settings
 * @param displayNumbering
 *            true if numbering should be displayed
 * @param enableImagesButton
 *            the if the images button should be enabled
 * @param imagesStartScaled
 *            true if images should start scaled.
 */
public MultiStateInputDialog(Frame owner, MultiStateCharacter ch, Set<Integer> initialSelectedStates,
        au.org.ala.delta.model.Character dependentCharacter, ImageSettings imageSettings,
        boolean displayNumbering, boolean enableImagesButton, boolean imagesStartScaled, boolean advancedMode) {
    super(owner, ch, imageSettings, displayNumbering, enableImagesButton, imagesStartScaled, advancedMode);

    ResourceMap resourceMap = Application.getInstance().getContext()
            .getResourceMap(MultiStateInputDialog.class);
    resourceMap.injectFields(this);

    setTitle(title);
    setPreferredSize(new Dimension(600, 350));

    if (dependentCharacter != null) {
        _pnlControllingCharacterMessage = new JPanel();
        _pnlControllingCharacterMessage.setFocusable(false);
        _pnlControllingCharacterMessage.setBorder(new EmptyBorder(5, 0, 0, 0));
        _pnlMain.add(_pnlControllingCharacterMessage, BorderLayout.SOUTH);
        _pnlControllingCharacterMessage.setLayout(new BorderLayout(0, 0));

        _lblWarningIcon = new JLabel("");
        _lblWarningIcon.setFocusable(false);
        _lblWarningIcon.setIcon(UIManager.getIcon("OptionPane.warningIcon"));
        _pnlControllingCharacterMessage.add(_lblWarningIcon, BorderLayout.WEST);

        _txtControllingCharacterMessage = new JTextArea();
        _txtControllingCharacterMessage.setText(MessageFormat.format(setControllingCharacterMessage,
                _formatter.formatCharacterDescription(dependentCharacter),
                _formatter.formatCharacterDescription(ch)));
        _txtControllingCharacterMessage.setFocusable(false);
        _txtControllingCharacterMessage.setBorder(new EmptyBorder(0, 5, 0, 0));
        _txtControllingCharacterMessage.setEditable(false);
        _pnlControllingCharacterMessage.add(_txtControllingCharacterMessage);
        _txtControllingCharacterMessage.setWrapStyleWord(true);
        _txtControllingCharacterMessage.setFont(UIManager.getFont("Button.font"));
        _txtControllingCharacterMessage.setLineWrap(true);
        _txtControllingCharacterMessage.setBackground(SystemColor.control);
    }

    _scrollPane = new JScrollPane();
    _pnlMain.add(_scrollPane, BorderLayout.CENTER);

    _list = new JList();
    _scrollPane.setViewportView(_list);

    _listModel = new DefaultListModel();
    for (int i = 0; i < ch.getNumberOfStates(); i++) {
        _listModel.addElement(_formatter.formatState(ch, i + 1));
    }

    _list.setModel(_listModel);

    _list.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() > 1) {
                // Treat double click on a list item as the ok button being
                // pressed.
                _okPressed = true;
                handleBtnOKClicked();
            }
        }

    });

    // Select the list items that correspond to the initial selected states.
    if (initialSelectedStates != null) {
        List<Integer> listIndiciesToSelect = new ArrayList<Integer>();
        for (int stateNumber : new ArrayList<Integer>(initialSelectedStates)) {
            listIndiciesToSelect.add(stateNumber - 1);
        }

        Integer[] wrappedPrimitivesList = listIndiciesToSelect
                .toArray(new Integer[initialSelectedStates.size()]);
        _list.setSelectedIndices(ArrayUtils.toPrimitive(wrappedPrimitivesList));
    }

    _inputData = new HashSet<Integer>();

}

From source file:com.kylinolap.job.engine.JobEngine.java

public double getPercentileJobStepDuration(double percentile) {
    Collection<Double> values = JOB_DURATION.values();
    Double[] all = (Double[]) values.toArray(new Double[values.size()]);
    Percentile p = new Percentile(percentile);
    return p.evaluate(ArrayUtils.toPrimitive(all));
}

From source file:de.codesourcery.eve.skills.ui.model.FilteringTreeModel.java

@Override
public void addChildren(ITreeNode parent, Collection<ITreeNode> nodes) {
    delegate.addChildren(parent, nodes);

    if (!isPathToRootVisible(parent)) { // children cannot be visible if their parent is hidden
        return;/*from   ww w . j  a va2  s .  c  o m*/
    }

    final List<Integer> childIndices = new ArrayList<Integer>();

    final List<ITreeNode> children = new ArrayList<ITreeNode>();

    for (ITreeNode child : nodes) {
        if (isHidden(child)) {
            continue;
        }
        childIndices.add(getIndexOfChild(parent, child));
        children.add(child);
    }

    if (!childIndices.isEmpty()) {
        final int[] indices = ArrayUtils.toPrimitive(childIndices.toArray(new Integer[childIndices.size()]));

        final Object[] childs = children.toArray(new ITreeNode[children.size()]);

        fireEvent(EventType.ADDED, new TreeModelEvent(this, parent.getPathToRoot(), indices, childs));
    }

}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.util.StatHelper.java

/**
 * Returns a new double array of nulls and non-Double.NaN values only
 *
 * @param x     a double array//  w w w. j  ava2s .c  om
 * @return      a double array
 */
private static double[] removeInvalidValues(Double[] x) {
    List<Double> dl = new ArrayList<Double>();
    for (Double d : x) {
        if (d != null && !Double.isNaN(d)) {
            dl.add(d);
        }
    }
    return ArrayUtils.toPrimitive(dl.toArray(new Double[dl.size()]));
}

From source file:com.ec.android.module.bluetooth40.base.BaseBluetoothControlActivity.java

protected void writeContent(Byte[] bytes) {

    if (mWriteCharacteristic != null) {
        mWriteCharacteristic.setValue(ArrayUtils.toPrimitive(bytes));
        mBluetoothLeService.writeCharacteristic(mWriteCharacteristic);
    }//from  ww  w . j a  va 2 s.co m

}

From source file:com.google.gwt.benchmark.dashboard.server.controller.BenchmarkController.java

private BenchmarkResultsTable createResponse(String benchmarkName, List<BenchmarkGraph> graphs, int week,
        int year) {
    Collections.sort(graphs, new Comparator<BenchmarkGraph>() {

        @Override/*  ww  w  .j a v  a 2s .  co  m*/
        public int compare(BenchmarkGraph o1, BenchmarkGraph o2) {
            return o1.getRunnerId().compareTo(o2.getRunnerId());
        }
    });
    String weekName = String.format("Week: %d Year: %d", week, year);
    List<String> allRunnerIds = new ArrayList<String>();

    List<String> commitIds = new ArrayList<String>();
    List<double[]> runnerResultList = new ArrayList<>();

    boolean first = true;

    for (BenchmarkGraph benchmarkGraph : graphs) {
        if (first) {
            commitIds.addAll(benchmarkGraph.getCommitIds());
            first = false;
        } else {
            // if an update is in progress some graph entities might have been updated
            // and some not. In this case we are just going to return an empty response
            if (commitIds.size() != benchmarkGraph.getCommitIds().size()) {
                return BenchmarkResultsTable.create(benchmarkName, weekName, year, week,
                        Collections.<String>emptyList(), Collections.<String>emptyList(),
                        Collections.<double[]>emptyList());
            }
        }

        allRunnerIds.add(benchmarkGraph.getRunnerId());
        Double[] runsPerSecond = benchmarkGraph.getRunsPerSecond().toArray(new Double[] {});
        double[] runs = ArrayUtils.toPrimitive(runsPerSecond);
        runnerResultList.add(runs);
    }

    return BenchmarkResultsTable.create(benchmarkName, weekName, year, week, commitIds, allRunnerIds,
            runnerResultList);
}

From source file:io.joynr.util.JoynrUtil.java

public static void writeResource(Byte[] byteResource, String fileName) throws IOException {
    writeResource(ArrayUtils.toPrimitive(byteResource), fileName);
}