Java Code Examples for java.util.Arrays.fill()

The following are Jave code examples for showing how to use fill() of the java.util.Arrays class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: hadoop   File: TestFileQueue.java   View Source Code Vote up 6 votes
@BeforeClass
public static void setup() throws IOException {
  final Configuration conf = new Configuration();
  final FileSystem fs = FileSystem.getLocal(conf).getRaw();
  final Path p = new Path(System.getProperty("test.build.data", "/tmp"),
      "testFileQueue").makeQualified(fs);
  fs.delete(p, true);
  final byte[] b = new byte[BLOCK];
  for (int i = 0; i < NFILES; ++i) {
    Arrays.fill(b, (byte)('A' + i));
    paths[i] = new Path(p, "" + (char)('A' + i));
    OutputStream f = null;
    try {
      f = fs.create(paths[i]);
      f.write(b);
    } finally {
      if (f != null) {
        f.close();
      }
    }
  }
}
 
Example 2
Project: localcloud_fe   File: PermissionHelper.java   View Source Code Vote up 6 votes
private static void deliverPermissionResult(CordovaPlugin plugin, int requestCode, String[] permissions) {
    // Generate the request results
    int[] requestResults = new int[permissions.length];
    Arrays.fill(requestResults, PackageManager.PERMISSION_GRANTED);

    try {
        Method onRequestPermissionResult = CordovaPlugin.class.getDeclaredMethod(
                "onRequestPermissionResult", int.class, String[].class, int[].class);

        onRequestPermissionResult.invoke(plugin, requestCode, permissions, requestResults);
    } catch (NoSuchMethodException noSuchMethodException) {
        // Should never be caught since the plugin must be written for cordova-android 5.0.0+ if it
        // made it to this point
        LOG.e(LOG_TAG, "NoSuchMethodException when delivering permissions results", noSuchMethodException);
    } catch (IllegalAccessException illegalAccessException) {
        // Should never be caught; this is a public method
        LOG.e(LOG_TAG, "IllegalAccessException when delivering permissions results", illegalAccessException);
    } catch(InvocationTargetException invocationTargetException) {
        // This method may throw a JSONException. We are just duplicating cordova-android's
        // exception handling behavior here; all it does is log the exception in CordovaActivity,
        // print the stacktrace, and ignore it
        LOG.e(LOG_TAG, "InvocationTargetException when delivering permissions results", invocationTargetException);
    }
}
 
Example 3
Project: openjdk-jdk10   File: IntArrayCache.java   View Source Code Vote up 6 votes
static void check(final int[] array, final int fromIndex,
                  final int toIndex, final int value)
{
    if (DO_CHECKS) {
        // check zero on full array:
        for (int i = 0; i < array.length; i++) {
            if (array[i] != value) {
                logException("Invalid value at: " + i + " = " + array[i]
                        + " from: " + fromIndex + " to: " + toIndex + "\n"
                        + Arrays.toString(array), new Throwable());

                // ensure array is correctly filled:
                Arrays.fill(array, value);

                return;
            }
        }
    }
}
 
Example 4
Project: Tesseract-OCR-Scanner   File: QrUtils.java   View Source Code Vote up 6 votes
/**
 * YUV420sp
 *
 * @param inputWidth
 * @param inputHeight
 * @param scaled
 * @return
 */
public static byte[] getYUV420sp(int inputWidth, int inputHeight, Bitmap scaled) {
    int[] argb = new int[inputWidth * inputHeight];

    scaled.getPixels(argb, 0, inputWidth, 0, 0, inputWidth, inputHeight);

    /**
     * 需要转换成偶数的像素点,否则编码YUV420的时候有可能导致分配的空间大小不够而溢出。
     */
    int requiredWidth = inputWidth % 2 == 0 ? inputWidth : inputWidth + 1;
    int requiredHeight = inputHeight % 2 == 0 ? inputHeight : inputHeight + 1;

    int byteLength = requiredWidth * requiredHeight * 3 / 2;
    if (yuvs == null || yuvs.length < byteLength) {
        yuvs = new byte[byteLength];
    } else {
        Arrays.fill(yuvs, (byte) 0);
    }

    encodeYUV420SP(yuvs, argb, inputWidth, inputHeight);

    scaled.recycle();

    return yuvs;
}
 
Example 5
Project: jaer   File: HumanVsComputerThrottleController.java   View Source Code Vote up 6 votes
/**
 * Adds a throttle bump at a random location.
 */
public void addBump() {
    Arrays.fill(spedUpSegments, false);
    // increase throttle settings around randomly around some track point
    int center = getNextThrottleBumpPoint();
    int m = (int) (numPoints * getFractionOfTrackToSpeedUp());
    log.info("speeding up " + m + " of " + numPoints + " throttle settings around track point " + center);
    for (int i = 0; i < m; i++) {
        float dist = Math.abs(i - (m / 2));
        float factor = ((m / 2) - dist) / (m / 2);
        int ind = getIndexFrom(center, i);
        throttleValues[ind].throttle = clipThrottle(throttleValues[ind].throttle + (throttleChange * factor)); // increase throttle by tent around random center point
        throttleValues[ind].brake = false;
        spedUpSegments[ind] = true;
    }
}
 
Example 6
Project: jaer   File: ApsFrameExtractor.java   View Source Code Vote up 6 votes
@Override
public void resetFilter() {
    if (DavisChip.class.isAssignableFrom(chip.getClass())) {
        apsChip = (DavisChip) chip;
    } else {
        EventFilter.log.warning("The filter ApsFrameExtractor can only be used for chips that extend the ApsDvsChip class");
    }
    newFrame = false;
    width = chip.getSizeX(); // note that on initial construction width=0 because this constructor is called while
    // chip is still being built
    height = chip.getSizeY();
    maxIDX = width * height;
    maxADC = apsChip.getMaxADC();
    apsDisplay.setImageSize(width, height);
    resetBuffer = new float[width * height];
    signalBuffer = new float[width * height];
    displayFrame = new float[width * height];
    displayBuffer = new float[width * height];
    apsDisplayPixmapBuffer = new float[3 * width * height];
    Arrays.fill(resetBuffer, 0.0f);
    Arrays.fill(signalBuffer, 0.0f);
    Arrays.fill(displayFrame, 0.0f);
    Arrays.fill(displayBuffer, 0.0f);
    Arrays.fill(apsDisplayPixmapBuffer, 0.0f);
}
 
Example 7
Project: dremio-oss   File: StackTrace.java   View Source Code Vote up 6 votes
/**
 * Write the stack trace to a StringBuilder.
 * @param sb
 *          where to write it
 * @param indent
 *          how many double spaces to indent each line
 */
public void writeToBuilder(final StringBuilder sb, final int indent) {
  // create the indentation string
  final char[] indentation = new char[indent * 2];
  Arrays.fill(indentation, ' ');

  // write the stack trace in standard Java format
  for(StackTraceElement ste : stackTraceElements) {
    sb.append(indentation)
        .append("at ")
        .append(ste.getClassName())
        .append('.')
        .append(ste.getMethodName())
        .append('(')
        .append(ste.getFileName())
        .append(':')
        .append(Integer.toString(ste.getLineNumber()))
        .append(")\n");
  }
}
 
Example 8
Project: pprxmtr   File: AnimatedGIFWriter.java   View Source Code Vote up 5 votes
private void init_encoder(int bitsPerPixel) {
	clearCode = 1 << bitsPerPixel;
	endOfImage = clearCode + 1;
	codeLen = bitsPerPixel + 1;
	codeIndex = endOfImage + 1;
	// Reset arrays
	Arrays.fill(child, 0);
	Arrays.fill(siblings, 0);
	Arrays.fill(suffix, 0);
}
 
Example 9
Project: openjdk-jdk10   File: TimSortStackSize2.java   View Source Code Vote up 5 votes
private Integer [] createArray() {
    Integer [] a = new Integer[length];
    Arrays.fill(a, 0);
    int endRun = -1;
    for (long len : runs) {
        a[endRun += len] = 1;
    }
    a[length - 1] = 0;
    return a;
}
 
Example 10
Project: Sense-Hub-Android-Things   File: Rm3Connector.java   View Source Code Vote up 5 votes
private boolean sendIRCode(final IrCodeData irCode){
    if(irCode == null || irCode.getIrCodeLen() == 0)
    {
        Log.e(TAG, "RM3 doesn't have IR code. Please teach for it");
        return false;
    }
    int len = irCode.getIrCodeLen() + 4;
    int[] packet = new int[len];
    Arrays.fill(packet, 0x00);
    packet[0] = 0x02;
    packet[1] = 0x00;
    packet[2] = 0x00;
    packet[3] = 0x00;
    Log.d(TAG, "sendIRCode");
    for(int i = 4;i < len;i++) {
        packet[i] = irCode.getIrCodeData()[i - 4];
    }

    PacketData inputData = new PacketData(packet, len);
    PacketData outputData = sendPacket(RM3_CMD_SEND_DATA, inputData);
    if(outputData == null || outputData.getLength() == 0 || outputData.getLength() <= UDP_PACKAGE_SIZE) {
        Log.e(TAG, "sendIRCode: Failed to send IR code");
        Log.d(TAG, "sendIRCode: retry authorize");
        if(true == authorize()) {
            return sendIRCode(irCode);
        }
        return false;
    }
    Log.d(TAG, "sendIRCode: Succeed to send IR code");
    return true;
}
 
Example 11
Project: FlickLauncher   File: MultiStateAlphaController.java   View Source Code Vote up 5 votes
public MultiStateAlphaController(View view, int stateCount) {
    mTargetView = view;
    mAlphas = new float[stateCount];
    Arrays.fill(mAlphas, 1);

    mAm = (AccessibilityManager) view.getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
}
 
Example 12
Project: BaseClient   File: RegionRenderCache.java   View Source Code Vote up 5 votes
public RegionRenderCache(World worldIn, BlockPos posFromIn, BlockPos posToIn, int subIn)
{
    super(worldIn, posFromIn, posToIn, subIn);
    this.position = posFromIn.subtract(new Vec3i(subIn, subIn, subIn));
    boolean flag = true;
    this.combinedLights = allocateLights(8000);
    Arrays.fill((int[])this.combinedLights, (int) - 1);
    this.blockStates = allocateStates(8000);
}
 
Example 13
Project: greycat   File: HeapLongLongMap.java   View Source Code Vote up 5 votes
void reallocate(int newCapacity) {
    if (newCapacity > capacity) {
        //extend keys
        long[] new_keys = new long[newCapacity];
        if (keys != null) {
            System.arraycopy(keys, 0, new_keys, 0, capacity);
        }
        keys = new_keys;
        //extend values
        long[] new_values = new long[newCapacity];
        if (values != null) {
            System.arraycopy(values, 0, new_values, 0, capacity);
        }
        values = new_values;

        int[] new_nexts = new int[newCapacity];
        int[] new_hashes = new int[newCapacity * 2];
        Arrays.fill(new_nexts, 0, newCapacity, -1);
        Arrays.fill(new_hashes, 0, (newCapacity * 2), -1);
        hashs = new_hashes;
        nexts = new_nexts;
        for (int i = 0; i < mapSize; i++) {
            int new_key_hash = (int) HashHelper.longHash(key(i), newCapacity * 2);
            setNext(i, hash(new_key_hash));
            setHash(new_key_hash, i);
        }
        capacity = newCapacity;
    }
}
 
Example 14
Project: JinsMemeBRIDGE-Android   File: MemeOSC.java   View Source Code Vote up 5 votes
public synchronized void createBundle() {
  Arrays.fill(sndOSCBundleData, (byte) 0);
  oscBundleTotalSize = 0;

  byte[] bundlePrefix = "#bundle".getBytes();

  for (int i = 0; i < bundlePrefix.length; i++) {
    sndOSCBundleData[i] = bundlePrefix[i];
  }

  oscBundleTotalSize += 8; // #bundle
  oscBundleTotalSize += 8; // timetag
}
 
Example 15
Project: HCFCore   File: TObjectHash.java   View Source Code Vote up 5 votes
/**
 * initializes the Object set of this hash table.
 *
 * @param initialCapacity an <code>int</code> value
 * @return an <code>int</code> value
 */
public int setUp(int initialCapacity) {
    int capacity;

    capacity = super.setUp(initialCapacity);
    _set = new Object[capacity];
    Arrays.fill(_set, FREE);
    return capacity;
}
 
Example 16
Project: OpenJSharp   File: LambdaFormBuffer.java   View Source Code Vote up 5 votes
/** Replace duplicate names by nulls, and remove all nulls. */
private void clearDuplicatesAndNulls() {
    if (dups != null) {
        // Remove duplicates.
        assert(ownedCount() >= 1);
        for (Name dup : dups) {
            for (int i = firstChange; i < length; i++) {
                if (names[i] == dup && originalNames[i] != dup) {
                    names[i] = null;
                    assert(Arrays.asList(names).contains(dup));
                    break;  // kill only one dup
                }
            }
        }
        dups.clear();
    }
    // Now that we are done with originalNames, remove "killed" names.
    int oldLength = length;
    for (int i = firstChange; i < length; i++) {
        if (names[i] == null) {
            System.arraycopy(names, i + 1, names, i, (--length - i));
            --i;  // restart loop at this position
        }
    }
    if (length < oldLength) {
        Arrays.fill(names, length, oldLength, null);
    }
    assert(!Arrays.asList(names).subList(0, length).contains(null));
}
 
Example 17
Project: incubator-ratis   File: TestRestartRaftPeer.java   View Source Code Vote up 4 votes
@Test
public void restartFollower() throws Exception {
  cluster.start();
  RaftTestUtil.waitForLeader(cluster);
  final RaftPeerId leaderId = cluster.getLeader().getId();
  final RaftClient client = cluster.createClient(leaderId);

  // write some messages
  final byte[] content = new byte[1024];
  Arrays.fill(content, (byte) 1);
  final SimpleMessage message = new SimpleMessage(new String(content));
  for (int i = 0; i < 10; i++) {
    Assert.assertTrue(client.send(message).isSuccess());
  }

  // restart a follower
  RaftPeerId followerId = cluster.getFollowers().get(0).getId();
  LOG.info("Restart follower {}", followerId);
  cluster.restartServer(followerId, false);

  // write some more messages
  for (int i = 0; i < 10; i++) {
    Assert.assertTrue(client.send(message).isSuccess());
  }
  client.close();

  // make sure the restarted follower can catchup
  boolean catchup = false;
  long lastAppliedIndex = 0;
  for (int i = 0; i < 10 && !catchup; i++) {
    Thread.sleep(500);
    lastAppliedIndex = cluster.getServer(followerId).getImpl().getState().getLastAppliedIndex();
    catchup = lastAppliedIndex >= 20;
  }
  Assert.assertTrue("lastAppliedIndex=" + lastAppliedIndex, catchup);

  // make sure the restarted peer's log segments is correct
  cluster.restartServer(followerId, false);
  Assert.assertTrue(cluster.getServer(followerId).getImpl().getState().getLog()
      .getLastEntryTermIndex().getIndex() >= 20);
}
 
Example 18
Project: cv4j-desktop   File: Skeleton.java   View Source Code Vote up 4 votes
public void process(ByteProcessor binary) {
	int width = binary.getWidth();
	int height = binary.getHeight();
	byte[] pixels = binary.getGray();

	byte[] output = new byte[width*height];
	int[] distmap = new int[width*height];
	System.arraycopy(pixels, 0, output, 0, output.length);
	Arrays.fill(distmap, 0);
	
	// initialize distance value
	int offset =0;
	int pv = 0;
	for(int row=0; row<height; row++) {
		offset = row*width;
		for(int col=0; col<width; col++) {
			pv = pixels[offset+col];
			if(pv == 255) {
				distmap[offset+col] = 1;
			}
		}
	}

	// distance transform stage
	boolean stop = false;
	int level = 0;
	while(!stop) {
		stop = dt(pixels, output, distmap, level, width, height);
		System.arraycopy(output, 0, pixels, 0, output.length);
		level++;
	}

	// extract skeleton from DT image
	int dis = 0;
	int p1=0, p2=0, p3=0, p4=0;
	Arrays.fill(output, (byte)0);
	for(int row=1; row<height-1; row++) {
		offset = row*width;
		for(int col=1; col<width-1; col++) {
			dis = distmap[offset+col];
			p1 = distmap[offset+col-1];
			p2 = distmap[offset+col+1];
			p3 = distmap[offset-width+col];
			p4 = distmap[offset+width+col];
			
			if(dis == 0) {
				output[offset+col] = (byte)0;
			}
			else {
				if(dis < p1 || dis < p2 || dis < p3 || dis < p4) {
					output[offset+col] = (byte)0;
				}
				else {
					output[offset+col] = (byte)255;
				}
			}
		}
	}

	// update pixels and release memory
	binary.putGray(output);
	output = null;
	distmap = null;
}
 
Example 19
Project: matrix-toolkits-java   File: ICC.java   View Source Code Vote up 4 votes
private void factor() {
    int n = R.numRows();

    // Internal CRS matrix storage
    int[] colind = R.getColumnIndices();
    int[] rowptr = R.getRowPointers();
    double[] data = R.getData();

    // Temporary storage of a dense row
    double[] Rk = new double[n];

    // Find the indices to the diagonal entries
    int[] diagind = findDiagonalIndices(n, colind, rowptr);

    // Go down along the main diagonal
    for (int k = 0; k < n; ++k) {

        // Expand current row to dense storage
        Arrays.fill(Rk, 0);
        for (int i = rowptr[k]; i < rowptr[k + 1]; ++i)
            Rk[colind[i]] = data[i];

        for (int i = 0; i < k; ++i) {

            // Get the current diagonal entry
            double Rii = data[diagind[i]];

            if (Rii == 0)
                throw new RuntimeException("Zero pivot encountered on row "
                        + (i + 1) + " during ICC process");

            // Elimination factor
            double Rki = Rk[i] / Rii;

            if (Rki == 0)
                continue;

            // Traverse the sparse row i, reducing on row k
            for (int j = diagind[i] + 1; j < rowptr[i + 1]; ++j)
                Rk[colind[j]] -= Rki * data[j];
        }

        // Store the row back into the factorisation matrix
        if (Rk[k] == 0)
            throw new RuntimeException(
                    "Zero diagonal entry encountered on row " + (k + 1)
                            + " during ICC process");
        double sqRkk = Math.sqrt(Rk[k]);

        for (int i = diagind[k]; i < rowptr[k + 1]; ++i)
            data[i] = Rk[colind[i]] / sqRkk;
    }

    Rt = new UpperCompRowMatrix(R, diagind);
}
 
Example 20
Project: GitHub   File: FadeDrawable.java   View Source Code Vote up 4 votes
/**
 * Starts fading out all layers.
 */
public void fadeOutAllLayers() {
  mTransitionState = TRANSITION_STARTING;
  Arrays.fill(mIsLayerOn, false);
  invalidateSelf();
}