Example usage for java.lang Byte SIZE

List of usage examples for java.lang Byte SIZE

Introduction

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

Prototype

int SIZE

To view the source code for java.lang Byte SIZE.

Click Source Link

Document

The number of bits used to represent a byte value in two's complement binary form.

Usage

From source file:ubic.gemma.analysis.expression.coexpression.Gene2GenePopulationServiceImpl.java

/**
 * Algorithm:/*w w  w .  j  ava 2 s.  com*/
 * <ol>
 * <li>Initialize byte array large enough to hold all the EE information (ceil(numeeids /Byte.SIZE))
 * <li>Flip the bit at the right location.
 * </ol>
 * 
 * @param idsToFlip
 * @param eeIdOrder
 * @return
 */
private byte[] computeSupportingDatasetVector(Collection<Long> idsToFlip, Map<Long, Integer> eeIdOrder) {
    byte[] supportVector = new byte[(int) Math.ceil(eeIdOrder.size() / (double) Byte.SIZE)];
    for (int i = 0, j = supportVector.length; i < j; i++) {
        supportVector[i] = 0x0;
    }

    for (Long id : idsToFlip) {
        BitUtil.set(supportVector, eeIdOrder.get(id));
    }
    assert BitUtil.count(supportVector) == idsToFlip.size();
    return supportVector;
}

From source file:it.unimi.dsi.webgraph.algo.HyperBall.java

/** Creates a new HyperBall instance.
 * /*w w w .  j a  va  2s  . co  m*/
 * @param g the graph whose neighbourhood function you want to compute.
 * @param gt the transpose of <code>g</code>, or <code>null</code>.
 * @param log2m the logarithm of the number of registers per counter.
 * @param pl a progress logger, or <code>null</code>.
 * @param numberOfThreads the number of threads to be used (0 for automatic sizing).
 * @param bufferSize the size of an I/O buffer in bytes (0 for {@link #DEFAULT_BUFFER_SIZE}).
 * @param granularity the number of node per task in a multicore environment (it will be rounded to the next multiple of 64), or 0 for {@link #DEFAULT_GRANULARITY}.
 * @param external if true, results of an iteration will be stored on disk.
 * @param doSumOfDistances whether the sum of distances from each node should be computed.
 * @param doSumOfInverseDistances whether the sum of inverse distances from each node should be computed.
 * @param discountFunction an array (possibly <code>null</code>) of discount functions. 
 * @param seed the random seed passed to {@link HyperLogLogCounterArray#HyperLogLogCounterArray(long, long, int, long)}.
 */
public HyperBall(final ImmutableGraph g, final ImmutableGraph gt, final int log2m, final ProgressLogger pl,
        final int numberOfThreads, final int bufferSize, final int granularity, final boolean external,
        final boolean doSumOfDistances, final boolean doSumOfInverseDistances,
        final Int2DoubleFunction[] discountFunction, final long seed) throws IOException {
    super(g.numNodes(), g.numNodes(), ensureRegisters(log2m), seed);

    info("Seed : " + Long.toHexString(seed));

    gotTranspose = gt != null;
    localNextMustBeChecked = gotTranspose
            ? IntSets.synchronize(new IntOpenHashSet(Hash.DEFAULT_INITIAL_SIZE, Hash.VERY_FAST_LOAD_FACTOR))
            : null;

    numNodes = g.numNodes();
    try {
        numArcs = g.numArcs();
    } catch (UnsupportedOperationException e) {
        // No number of arcs. We have to enumerate.
        long a = 0;
        final NodeIterator nodeIterator = g.nodeIterator();
        for (int i = g.numNodes(); i-- != 0;) {
            nodeIterator.nextInt();
            a += nodeIterator.outdegree();
        }
        numArcs = a;
    }
    squareNumNodes = (double) numNodes * numNodes;

    cumulativeOutdegrees = new EliasFanoCumulativeOutdegreeList(g, numArcs, Math.max(0, 64 / m - 1));

    modifiedCounter = new boolean[numNodes];
    modifiedResultCounter = external ? null : new boolean[numNodes];
    if (gt != null) {
        mustBeChecked = new boolean[numNodes];
        nextMustBeChecked = new boolean[numNodes];
        if (gt.numNodes() != g.numNodes())
            throw new IllegalArgumentException("The graph and its transpose have a different number of nodes");
        if (gt.numArcs() != g.numArcs())
            throw new IllegalArgumentException("The graph and its transpose have a different number of arcs");
    }

    this.pl = pl;
    this.external = external;
    this.doSumOfDistances = doSumOfDistances;
    this.doSumOfInverseDistances = doSumOfInverseDistances;
    this.discountFunction = discountFunction == null ? new Int2DoubleFunction[0] : discountFunction;
    this.numberOfThreads = numberOfThreads(numberOfThreads);
    this.granularity = numberOfThreads == 1 ? numNodes
            : granularity == 0 ? DEFAULT_GRANULARITY : ((granularity + Long.SIZE - 1) & ~(Long.SIZE - 1));
    this.bufferSize = Math.max(1, (bufferSize == 0 ? DEFAULT_BUFFER_SIZE : bufferSize)
            / ((Long.SIZE / Byte.SIZE) * (counterLongwords + 1)));

    info("Relative standard deviation: "
            + Util.format(100 * HyperLogLogCounterArray.relativeStandardDeviation(log2m)) + "% (" + m
            + " registers/counter, " + registerSize + " bits/register, " + Util.format(m * registerSize / 8.)
            + " bytes/counter)");
    if (external)
        info("Running " + this.numberOfThreads + " threads with a buffer of " + Util.formatSize(this.bufferSize)
                + " counters");
    else
        info("Running " + this.numberOfThreads + " threads");

    thread = new IterationThread[this.numberOfThreads];

    if (external) {
        info("Creating update list...");
        updateFile = File.createTempFile(HyperBall.class.getName(), "-temp");
        updateFile.deleteOnExit();
        fileChannel = (randomAccessFile = new RandomAccessFile(updateFile, "rw")).getChannel();
    } else {
        updateFile = null;
        fileChannel = null;
    }

    nodes = new AtomicInteger();
    arcs = new AtomicLong();
    modified = new AtomicInteger();
    unwritten = new AtomicInteger();

    neighbourhoodFunction = new DoubleArrayList();
    sumOfDistances = doSumOfDistances ? new float[numNodes] : null;
    sumOfInverseDistances = doSumOfInverseDistances ? new float[numNodes] : null;
    discountedCentrality = new float[this.discountFunction.length][];
    for (int i = 0; i < this.discountFunction.length; i++)
        discountedCentrality[i] = new float[numNodes];

    info("HyperBall memory usage: " + Util.formatSize2(usedMemory()) + " [not counting graph(s)]");

    if (!external) {
        info("Allocating result bit vectors...");
        // Allocate vectors that will store the result.
        resultBits = new long[bits.length][];
        resultRegisters = new LongBigList[bits.length];
        for (int i = bits.length; i-- != 0;)
            resultRegisters[i] = (LongArrayBitVector.wrap(resultBits[i] = new long[bits[i].length]))
                    .asLongBigList(registerSize);
    } else {
        resultBits = null;
        resultRegisters = null;
    }

    lock = new ReentrantLock();
    allWaiting = lock.newCondition();
    start = lock.newCondition();
    aliveThreads = this.numberOfThreads;

    if (this.numberOfThreads == 1)
        (thread[0] = new IterationThread(g, gt, 0)).start();
    else
        for (int i = 0; i < this.numberOfThreads; i++)
            (thread[i] = new IterationThread(g.copy(), gt != null ? gt.copy() : null, i)).start();

    // We wait for all threads being read to start.
    lock.lock();
    try {
        if (aliveThreads != 0)
            allWaiting.await();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } finally {
        lock.unlock();
    }
}

From source file:edu.vu.isis.ammo.dash.provider.IncidentSyncAdaptor.java

public ArrayList<File> mediaSerialize(Cursor cursor) {
    logger.debug("::mediaSerialize");
    ArrayList<File> paths = new ArrayList<File>();
    if (1 > cursor.getCount())
        return paths;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream eos = new DataOutputStream(baos);

    for (boolean more = cursor.moveToFirst(); more; more = cursor.moveToNext()) {
        MediaWrapper iw = new MediaWrapper();
        iw.setEventId(cursor.getString(cursor.getColumnIndex(MediaTableSchemaBase.EVENT_ID)));
        iw.setDataType(cursor.getString(cursor.getColumnIndex(MediaTableSchemaBase.DATA_TYPE)));
        iw.setData(cursor.getString(cursor.getColumnIndex(MediaTableSchemaBase.DATA)));
        iw.setCreatedDate(cursor.getLong(cursor.getColumnIndex(MediaTableSchemaBase.CREATED_DATE)));
        iw.setModifiedDate(cursor.getLong(cursor.getColumnIndex(MediaTableSchemaBase.MODIFIED_DATE)));
        iw.set_ReceivedDate(cursor.getLong(cursor.getColumnIndex(MediaTableSchemaBase._RECEIVED_DATE)));
        iw.set_Disposition(cursor.getInt(cursor.getColumnIndex(MediaTableSchemaBase._DISPOSITION)));

        Gson gson = new Gson();

        try {/* w ww. ja v  a2  s .com*/
            eos.writeBytes(gson.toJson(iw));
            eos.writeByte(0);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        // not a reference field name :event id eventId event_id\n 
        try {
            String fileName = iw.getData();
            File dataFile = new File(fileName);
            int dataSize = (int) dataFile.length();
            byte[] buffData = new byte[dataSize];
            FileInputStream fileStream = new FileInputStream(dataFile);
            int ret = 0;
            for (int position = 0; (ret > -1 && dataSize > position); position += ret) {
                ret = fileStream.read(buffData, position, dataSize - position);
            }
            fileStream.close();

            eos.writeBytes("data");
            eos.writeByte(0);

            ByteBuffer dataSizeBuf = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);
            dataSizeBuf.order(ByteOrder.LITTLE_ENDIAN);
            dataSizeBuf.putInt(dataSize);

            // write the media back out
            eos.write(dataSizeBuf.array());
            eos.write(buffData);
            eos.write(dataSizeBuf.array());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // not a reference field name :created date createdDate created_date\n 
        // not a reference field name :modified date modifiedDate modified_date\n 
        // MediaTableSchemaBase._DISPOSITION;

        //           try {
        // TODO write to content provider using openFile
        // if (!applCacheMediaDir.exists() ) applCacheMediaDir.mkdirs();

        // File outfile = new File(applCacheMediaDir, Integer.toHexString((int) System.currentTimeMillis())); 
        //              BufferedOutputStream bufferedOutput = new BufferedOutputStream(new FileOutputStream(outfile), 8192);
        //              bufferedOutput.write(baos.toByteArray());
        //              bufferedOutput.flush();
        //              bufferedOutput.close();

        //           } catch (FileNotFoundException e) {
        //              e.printStackTrace();
        //           } catch (IOException e) {
        //              e.printStackTrace();
        //           }
    }
    return paths;
}

From source file:it.unimi.dsi.webgraph.algo.HyperBall.java

private long usedMemory() {
    long bytes = 0;
    for (long[] a : bits)
        bytes += a.length * ((long) Long.SIZE / Byte.SIZE);
    if (!external)
        bytes *= 2;//from  ww w  .  j  av a 2 s  .c  o m
    if (sumOfDistances != null)
        bytes += sumOfDistances.length * ((long) Float.SIZE / Byte.SIZE);
    if (sumOfInverseDistances != null)
        bytes += sumOfInverseDistances.length * ((long) Float.SIZE / Byte.SIZE);
    for (int i = discountFunction.length; i-- != 0;)
        bytes += discountedCentrality[i].length * ((long) Float.SIZE / Byte.SIZE);
    // We use bits, so usedMemory() can be called before allocation.
    if (modifiedCounter != null)
        bytes += modifiedCounter.length;
    if (modifiedResultCounter != null)
        bytes += modifiedResultCounter.length;
    if (nextMustBeChecked != null)
        bytes += nextMustBeChecked.length;
    if (mustBeChecked != null)
        bytes += mustBeChecked.length;
    return bytes;
}

From source file:com.googlecode.networklog.AppFragment.java

public void updateAppThroughputBps() {
    if (groupDataBuffer == null) {
        return;/*from w  ww . j  a va  2  s  .co  m*/
    }

    synchronized (groupDataBuffer) {
        for (GroupItem item : groupDataBuffer) {
            if (NetworkLogService.throughputBps) {
                item.uploadThroughput *= Byte.SIZE;
                item.downloadThroughput *= Byte.SIZE;
                item.totalThroughput *= Byte.SIZE;
            } else {
                item.uploadThroughput /= Byte.SIZE;
                item.downloadThroughput /= Byte.SIZE;
                item.totalThroughput /= Byte.SIZE;
            }

            if (NetworkLogService.invertUploadDownload) {
                item.throughputString = StringUtils.formatToBytes(item.downloadThroughput)
                        + (NetworkLogService.throughputBps ? "bps/" : "B/")
                        + StringUtils.formatToBytes(item.uploadThroughput)
                        + (NetworkLogService.throughputBps ? "bps" : "B");
            } else {
                item.throughputString = StringUtils.formatToBytes(item.uploadThroughput)
                        + (NetworkLogService.throughputBps ? "bps/" : "B/")
                        + StringUtils.formatToBytes(item.downloadThroughput)
                        + (NetworkLogService.throughputBps ? "bps" : "B");
            }
        }

        refreshAdapter();
    }
}

From source file:gephi.spade.panel.fcsFile.java

/**
 * readBinIntData ---/*from  w ww .j av  a2s.c o m*/
 * <p>
 * Reads binary integers in list mode in the DATA segment and updates
 * eventList.
 * </p>
 *
 * <p>
 * Assumes that the bits for the values are byte-aligned. It needs to be
 * fixed if that is not the case.
 * </p>
 *
 * @param data
 *            <code>ByteBuffer</code> containing the DATA segment of the
 *            underlying file.
 */
private void readBinIntData(ByteBuffer data) {
    // Allocate the eventList
    eventList = new double[parameters][totalEvents];

    int numBytes, value, range, currByte;

    final int totalEvents = this.totalEvents;
    final int parameters = this.parameters;

    for (int i = 0; i < totalEvents; i++) {
        for (int j = 0; j < parameters; j++) {
            // Calculate the number of bytes used from the number of bits
            // used
            // Round up to the next full byte
            numBytes = (int) Math.ceil(((double) channelBits[j]) / Byte.SIZE);

            // Get the range of the current parameter - will let us build
            // the mask
            range = (int) channelRange[j];

            // Initialize the current value to 0
            value = 0;

            if (littleEndianP) {
                // If the byte order is little endian, then build the value
                // to the left.
                for (int k = 0; k < numBytes; k++) {
                    // Get the next 8 bits masking to make sure Java doesn't
                    // prepend 1's
                    currByte = (data.get() & 0xFF);

                    // Shift the 8 bits into position
                    currByte <<= (8 * k);

                    // Or the 8 bits with the current value
                    value |= currByte;
                }
            } else {
                // Otherwise, the byte order is big endian, so build the
                // value to the right.
                for (int k = 0; k < numBytes; k++) {
                    // Left shift the previous bits in value to make room
                    value <<= 8;

                    // Grab the next 8 bits masking to make sure Java
                    // doesn't prepend 1's
                    value |= (data.get() & 0xFF);
                }
            }

            /**
             * From the FCS specification: --- The remaining bits are
             * usually unused and set to "0"; however, some file writers
             * store non-data information in that bit-space. Implementers
             * must use a bit mask when reading these list mode parameter
             * values to insure that erroneous values are not read from the
             * unused bits.
             */
            // Mask the value based on the range
            value &= (range - 1);

            // Store the value into the array
            eventList[j][i] = value;
        }
    }
}

From source file:org.nd4j.linalg.util.ArrayUtil.java

/**
 *
 * @param doubleArray/*from  w  w  w. j av  a2 s. co  m*/
 * @return
 */
public static byte[] toByteArray(double[] doubleArray) {
    int times = Double.SIZE / Byte.SIZE;
    byte[] bytes = new byte[doubleArray.length * times];
    for (int i = 0; i < doubleArray.length; i++) {
        ByteBuffer.wrap(bytes, i * times, times).putDouble(doubleArray[i]);
    }
    return bytes;
}

From source file:org.eclipse.dataset.AbstractDataset.java

/**
 * @param dtype//  www  .  j  av a2 s  .c  om
 * @param isize
 *            number of elements in an item
 * @return length of single item in bytes
 */
public static int getItemsize(final int dtype, final int isize) {
    int size;

    switch (dtype) {
    case BOOL:
        size = 1; // How is this defined?
        break;
    case INT8:
    case ARRAYINT8:
        size = Byte.SIZE / 8;
        break;
    case INT16:
    case ARRAYINT16:
    case RGB:
        size = Short.SIZE / 8;
        break;
    case INT32:
    case ARRAYINT32:
        size = Integer.SIZE / 8;
        break;
    case INT64:
    case ARRAYINT64:
        size = Long.SIZE / 8;
        break;
    case FLOAT32:
    case ARRAYFLOAT32:
    case COMPLEX64:
        size = Float.SIZE / 8;
        break;
    case FLOAT64:
    case ARRAYFLOAT64:
    case COMPLEX128:
        size = Double.SIZE / 8;
        break;
    default:
        size = 0;
        break;
    }

    return size * isize;
}

From source file:org.nd4j.linalg.util.ArrayUtil.java

/**
 *
 * @param byteArray//from  www  .  java2 s.c  o  m
 * @return
 */
public static double[] toDoubleArray(byte[] byteArray) {
    int times = Double.SIZE / Byte.SIZE;
    double[] doubles = new double[byteArray.length / times];
    for (int i = 0; i < doubles.length; i++) {
        doubles[i] = ByteBuffer.wrap(byteArray, i * times, times).getDouble();
    }
    return doubles;
}

From source file:org.nd4j.linalg.util.ArrayUtil.java

/**
 *
 * @param doubleArray//from  w ww .j a v  a2  s.  c om
 * @return
 */
public static byte[] toByteArray(float[] doubleArray) {
    int times = Float.SIZE / Byte.SIZE;
    byte[] bytes = new byte[doubleArray.length * times];
    for (int i = 0; i < doubleArray.length; i++) {
        ByteBuffer.wrap(bytes, i * times, times).putFloat(doubleArray[i]);
    }
    return bytes;
}