Example usage for java.util Arrays fill

List of usage examples for java.util Arrays fill

Introduction

In this page you can find the example usage for java.util Arrays fill.

Prototype

public static void fill(Object[] a, Object val) 

Source Link

Document

Assigns the specified Object reference to each element of the specified array of Objects.

Usage

From source file:edu.harvard.i2b2.crc.dao.setfinder.EncounterSetCollectionSpringDao.java

/**
 * function to add patient to patient set without out creating new db
 * session//from www.j a  v a 2  s . c  o  m
 * 
 * @param patientId
 */
public void addEncounter(long encounterId, long patientId) {
    setIndex++;

    QtPatientEncCollection collElement = new QtPatientEncCollection();
    int patientSetCollId = 0;
    collElement.setPatientId(patientId);
    collElement.setEncounterId(encounterId);
    collElement.setQtQueryResultInstance(resultInstance);
    collElement.setSetIndex(setIndex);

    patientEncColl[batchDataIndex++] = collElement;

    if ((setIndex % 1000) == 0) {
        InsertStatementSetter batchSetter = new InsertStatementSetter(patientEncColl, batchDataIndex);
        jdbcTemplate.batchUpdate(insert_sql, batchSetter);

        Arrays.fill(patientEncColl, null);
        batchDataIndex = 0;
    }
}

From source file:com.cloudera.oryx.app.serving.als.model.LocalitySensitiveHashTest.java

@Test
public void testCandidateIndicesOneBit() {
    int features = 10;
    LocalitySensitiveHash lsh = new LocalitySensitiveHash(0.1, features, 8);
    assertEquals(1, lsh.getMaxBitsDiffering());

    float[] zeroVec = new float[features];
    int[] zeroCandidates = lsh.getCandidateIndices(zeroVec);
    assertEquals(1 + lsh.getNumHashes(), zeroCandidates.length);
    assertEquals(0, zeroCandidates[0]);//from  w  w  w . j a v a 2s .c  om
    for (int i = 1; i < zeroCandidates.length; i++) {
        assertEquals(1L << (i - 1), zeroCandidates[i]);
    }

    float[] oneVec = new float[features];
    Arrays.fill(oneVec, 1.0f);
    int[] oneCandidates = lsh.getCandidateIndices(oneVec);
    for (int i = 1; i < oneCandidates.length; i++) {
        assertEquals(oneCandidates[0] ^ (1L << (i - 1)), oneCandidates[i]);
    }
}

From source file:com.igormaznitsa.jhexed.swing.editor.ui.exporters.PNGImageExporter.java

public BufferedImage generateImage() throws IOException {
    final int DEFAULT_CELL_WIDTH = 48;
    final int DEFAULT_CELL_HEIGHT = 48;

    final int imgWidth = this.docOptions.getImage() == null ? DEFAULT_CELL_WIDTH * this.docOptions.getColumns()
            : Math.round(this.docOptions.getImage().getSVGWidth());
    final int imgHeight = this.docOptions.getImage() == null ? DEFAULT_CELL_HEIGHT * this.docOptions.getRows()
            : Math.round(this.docOptions.getImage().getSVGHeight());

    final BufferedImage result;
    if (exportData.isBackgroundImageExport() && this.docOptions.getImage() != null) {
        result = this.docOptions.getImage().rasterize(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
    } else {// w w  w .  j ava 2s  . co m
        result = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
    }

    final Graphics2D gfx = result.createGraphics();
    gfx.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    gfx.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    final HexEngine<Graphics2D> engine = new HexEngine<Graphics2D>(DEFAULT_CELL_WIDTH, DEFAULT_CELL_HEIGHT,
            this.docOptions.getHexOrientation());

    final List<HexFieldLayer> reversedNormalizedStack = new ArrayList<HexFieldLayer>();
    for (int i = this.exportData.getLayers().size() - 1; i >= 0; i--) {
        final LayerExportRecord rec = this.exportData.getLayers().get(i);
        if (rec.isAllowed()) {
            reversedNormalizedStack.add(rec.getLayer());
        }
    }

    if (Thread.currentThread().isInterrupted())
        return null;

    final HexFieldValue[] stackOfValues = new HexFieldValue[reversedNormalizedStack.size()];

    engine.setModel(new HexEngineModel<HexFieldValue[]>() {

        @Override
        public int getColumnNumber() {
            return docOptions.getColumns();
        }

        @Override
        public int getRowNumber() {
            return docOptions.getRows();
        }

        @Override
        public HexFieldValue[] getValueAt(final int col, final int row) {
            Arrays.fill(stackOfValues, null);

            for (int index = 0; index < reversedNormalizedStack.size(); index++) {
                stackOfValues[index] = reversedNormalizedStack.get(index).getHexValueAtPos(col, row);
            }
            return stackOfValues;
        }

        @Override
        public HexFieldValue[] getValueAt(final HexPosition pos) {
            return this.getValueAt(pos.getColumn(), pos.getRow());
        }

        @Override
        public void setValueAt(int col, int row, HexFieldValue[] value) {
        }

        @Override
        public void setValueAt(HexPosition pos, HexFieldValue[] value) {
        }

        @Override
        public boolean isPositionValid(final int col, final int row) {
            return col >= 0 && col < docOptions.getColumns() && row >= 0 && row < docOptions.getRows();
        }

        @Override
        public boolean isPositionValid(final HexPosition pos) {
            return this.isPositionValid(pos.getColumn(), pos.getRow());
        }

        @Override
        public void attachedToEngine(final HexEngine<?> engine) {
        }

        @Override
        public void detachedFromEngine(final HexEngine<?> engine) {
        }
    });

    final HexRect2D visibleSize = engine.getVisibleSize();
    final float xcoeff = (float) result.getWidth() / visibleSize.getWidth();
    final float ycoeff = (float) result.getHeight() / visibleSize.getHeight();
    engine.setScale(xcoeff, ycoeff);

    final Image[][] cachedIcons = new Image[this.exportData.getLayers().size()][];
    engine.setRenderer(new ColorHexRender() {

        private final Stroke stroke = new BasicStroke(docOptions.getLineWidth());

        @Override
        public Stroke getStroke() {
            return this.stroke;
        }

        @Override
        public Color getFillColor(HexEngineModel<?> model, int col, int row) {
            return null;
        }

        @Override
        public Color getBorderColor(HexEngineModel<?> model, int col, int row) {
            return exportData.isExportHexBorders() ? docOptions.getColor() : null;
        }

        @Override
        public void drawExtra(HexEngine<Graphics2D> engine, Graphics2D g, int col, int row, Color borderColor,
                Color fillColor) {
        }

        @Override
        public void drawUnderBorder(final HexEngine<Graphics2D> engine, final Graphics2D g, final int col,
                final int row, final Color borderColor, final Color fillColor) {
            final HexFieldValue[] stackValues = (HexFieldValue[]) engine.getModel().getValueAt(col, row);
            for (int i = 0; i < stackValues.length; i++) {
                final HexFieldValue valueToDraw = stackValues[i];
                if (valueToDraw == null) {
                    continue;
                }
                g.drawImage(cachedIcons[i][valueToDraw.getIndex()], 0, 0, null);
            }
        }

    });

    final Path2D hexShape = ((ColorHexRender) engine.getRenderer()).getHexPath();
    final int cellWidth = hexShape.getBounds().width;
    final int cellHeight = hexShape.getBounds().height;

    for (int layerIndex = 0; layerIndex < reversedNormalizedStack.size()
            && !Thread.currentThread().isInterrupted(); layerIndex++) {
        final HexFieldLayer theLayer = reversedNormalizedStack.get(layerIndex);
        final Image[] cacheLineForLayer = new Image[theLayer.getHexValuesNumber()];
        for (int valueIndex = 1; valueIndex < theLayer.getHexValuesNumber(); valueIndex++) {
            cacheLineForLayer[valueIndex] = theLayer.getHexValueForIndex(valueIndex).makeIcon(cellWidth,
                    cellHeight, hexShape, true);
        }
        cachedIcons[layerIndex] = cacheLineForLayer;
    }

    engine.drawWithThreadInterruptionCheck(gfx);
    if (Thread.currentThread().isInterrupted())
        return null;

    if (this.exportData.isCellCommentariesExport()) {
        final Iterator<Entry<HexPosition, String>> iterator = this.cellComments.iterator();
        gfx.setFont(new Font("Arial", Font.BOLD, 12));
        while (iterator.hasNext() && !Thread.currentThread().isInterrupted()) {
            final Entry<HexPosition, String> item = iterator.next();
            final HexPosition pos = item.getKey();
            final String text = item.getValue();
            final float x = engine.calculateX(pos.getColumn(), pos.getRow());
            final float y = engine.calculateY(pos.getColumn(), pos.getRow());

            final Rectangle2D textBounds = gfx.getFontMetrics().getStringBounds(text, gfx);

            final float dx = x - ((float) textBounds.getWidth() - engine.getCellWidth()) / 2;

            gfx.setColor(Color.BLACK);
            gfx.drawString(text, dx, y);
            gfx.setColor(Color.WHITE);
            gfx.drawString(text, dx - 2, y - 2);
        }
    }

    gfx.dispose();

    return result;
}

From source file:gui.EventReader.java

public EventReader(int refreshTime, boolean autoRefresh, String worldID, String worldName, boolean playSounds,
        HashMap allEvents, JButton workingButton, JCheckBox refreshSelector, OverlayGui overlayGui) {

    //setDaemon(true); //??

    this.overlayGui = overlayGui;

    this.playThread = null;

    this.timerStamps = new Date[GW2EventerGui.EVENT_COUNT];

    this.playSoundsList = new HashMap();

    this.workingButton = workingButton;
    this.refreshSelector = refreshSelector;

    this.autoRefresh = autoRefresh;
    this.sleepTime = refreshTime;
    this.worldID = worldID;
    this.worldName = worldName;
    this.playSounds = playSounds;
    this.allEvents = allEvents;

    this.markedBs = new boolean[GW2EventerGui.EVENT_COUNT];
    Arrays.fill(this.markedBs, Boolean.FALSE);
}

From source file:edu.byu.nlp.stats.DirichletDistribution.java

public static double[] sampleSymmetric(double alpha, int len, RandomGenerator rnd) {
    double[] alphavec = new double[len];
    Arrays.fill(alphavec, alpha);
    return sample(alphavec, rnd);
}

From source file:com.googlecode.concurrentlinkedhashmap.MultiThreadedTest.java

@Test(dataProvider = "builder")
public void weightedConcurrency(Builder<Integer, List<Integer>> builder) {
    final ConcurrentLinkedHashMap<Integer, List<Integer>> map = builder.weigher(Weighers.<Integer>list())
            .maximumWeightedCapacity(threads).concurrencyLevel(threads).build();
    final Queue<List<Integer>> values = new ConcurrentLinkedQueue<List<Integer>>();
    for (int i = 1; i <= threads; i++) {
        Integer[] array = new Integer[i];
        Arrays.fill(array, Integer.MIN_VALUE);
        values.add(Arrays.asList(array));
    }/*w  w w .  j a v  a2s . co  m*/
    executeWithTimeOut(map, new Callable<Long>() {
        @Override
        public Long call() throws Exception {
            return timeTasks(threads, new Runnable() {
                @Override
                public void run() {
                    List<Integer> value = values.poll();
                    for (int i = 0; i < iterations; i++) {
                        map.put(i % 10, value);
                    }
                }
            });
        }
    });
}

From source file:kieker.tools.opad.timeseries.forecast.AbstractRForecaster.java

protected IForecastResult createNaNForecast(final ITimeSeries<Double> timeseries, final int numForecastSteps) {
    final ITimeSeries<Double> tsForecast = this.prepareForecastTS();
    final ITimeSeries<Double> tsLower = this.prepareForecastTS();
    final ITimeSeries<Double> tsUpper = this.prepareForecastTS();
    final Double fcQuality = Double.NaN;

    final Double[] nanArray = new Double[numForecastSteps];
    Arrays.fill(nanArray, Double.NaN);
    tsForecast.appendAll(nanArray);/* ww  w . jav  a 2s . c om*/
    tsLower.appendAll(nanArray);
    tsUpper.appendAll(nanArray);

    return new ForecastResult(tsForecast, this.getTsOriginal(), this.getConfidenceLevel(), fcQuality, tsLower,
            tsUpper, this.strategy);
}

From source file:com.weblyzard.lib.string.nilsimsa.Nilsimsa.java

/**
 * resets the Hash computation
 */
private void reset() {
    count = 0;
    Arrays.fill(acc, (byte) 0);
    Arrays.fill(lastch, -1);
}

From source file:gr.aueb.cs.nlp.wordtagger.data.structure.features.FeatureBuilder.java

/**
 * Based on a model generate features for each word. This method generates only ambitag features.
 * @param set, the input wordset, the operation is inplace meaning that it will erase any features 
 * the words of the set already have//from www  . j a v  a2  s . co  m
 * @param lookBehind, the previous words that should be taken into account for word generation,
 * any woord with value %newarticle% is ignored and used in order to stop feature generation 
 * and force a zero padding
 * @param lookAhead, words ahead of the word to be taken into account, works same as lookbehind
 */
public void generateFeats(List<Word> set, int lookBehind, int lookAhead) {
    if (featHeader == null) {

    }
    for (int i = 0; i < set.size(); i++) {
        Word w = set.get(i);
        double[] feats = ambiFeats(w, suffixLength);
        double[] featsBack = new double[0];
        boolean backwardDummy = true;
        for (int j = 1; j <= lookBehind; j++) {
            backwardDummy &= i - j >= 0 && !set.get(i - j).equals("%newarticle%");
            if (backwardDummy) {
                Word prev = set.get(i - j);
                featsBack = ArrayUtils.addAll(featsBack, ambiFeats(prev, suffixLength));
            } else {
                double[] dummy = new double[generator.getCategories().size() * (suffixLength + 1)];
                Arrays.fill(dummy, 0.0);
                featsBack = ArrayUtils.addAll(featsBack, dummy);
            }
        }

        double[] featsForw = new double[0];
        boolean forwardDummy = true;
        for (int j = 1; j <= lookAhead; j++) {
            forwardDummy &= i + j < set.size() && !set.get(i + j).equals("%newarticle%");
            if (forwardDummy) {
                Word next = set.get(i + j);
                featsForw = ArrayUtils.addAll(featsForw, ambiFeats(next, suffixLength));
            } else {
                double[] dummy = new double[generator.getCategories().size() * (suffixLength + 1)];
                Arrays.fill(dummy, 0.0);
                if (featsForw.length == 0) {
                    featsForw = dummy;
                } else {
                    featsForw = ArrayUtils.addAll(featsForw, dummy);
                }
            }
        }

        feats = ArrayUtils.addAll(feats, featsBack);
        feats = ArrayUtils.addAll(feats, featsForw);
        feats = ArrayUtils.addAll(feats, simpleFeats(w));
        w.setFeatureVec(new FeatureVector(feats));
    }
}

From source file:com.espertech.esper.core.EPPreparedExecuteMethod.java

/**
 * Ctor./*w ww.  j a v a  2s. co  m*/
 * @param statementSpec is a container for the definition of all statement constructs that
 * may have been used in the statement, i.e. if defines the select clauses, insert into, outer joins etc.
 * @param services is the service instances for dependency injection
 * @param statementContext is statement-level information and statement services
 * @throws ExprValidationException if the preparation failed
 */
public EPPreparedExecuteMethod(StatementSpecCompiled statementSpec, EPServicesContext services,
        StatementContext statementContext) throws ExprValidationException {
    boolean queryPlanLogging = services.getConfigSnapshot().getEngineDefaults().getLogging()
            .isEnableQueryPlan();
    if (queryPlanLogging) {
        queryPlanLog.info("Query plans for Fire-and-forget query '" + statementContext.getExpression() + "'");
    }

    this.statementSpec = statementSpec;
    this.exprEvaluatorContext = statementContext;

    validateExecuteQuery();

    int numStreams = statementSpec.getStreamSpecs().size();
    EventType[] typesPerStream = new EventType[numStreams];
    String[] namesPerStream = new String[numStreams];
    processors = new NamedWindowProcessor[numStreams];
    StreamJoinAnalysisResult streamJoinAnalysisResult = new StreamJoinAnalysisResult(numStreams);
    Arrays.fill(streamJoinAnalysisResult.getNamedWindow(), true);

    for (int i = 0; i < numStreams; i++) {
        final StreamSpecCompiled streamSpec = statementSpec.getStreamSpecs().get(i);
        NamedWindowConsumerStreamSpec namedSpec = (NamedWindowConsumerStreamSpec) streamSpec;

        String streamName = namedSpec.getWindowName();
        if (namedSpec.getOptionalStreamName() != null) {
            streamName = namedSpec.getOptionalStreamName();
        }
        namesPerStream[i] = streamName;

        processors[i] = services.getNamedWindowService().getProcessor(namedSpec.getWindowName());
        typesPerStream[i] = processors[i].getTailView().getEventType();

        if (processors[i].isVirtualDataWindow()) {
            streamJoinAnalysisResult.getViewExternal()[i] = processors[i].getVirtualDataWindow();
        }
    }

    // compile filter to optimize access to named window
    filters = new FilterSpecCompiled[numStreams];
    if (statementSpec.getFilterRootNode() != null) {
        LinkedHashMap<String, Pair<EventType, String>> tagged = new LinkedHashMap<String, Pair<EventType, String>>();
        for (int i = 0; i < numStreams; i++) {
            try {
                StreamTypeServiceImpl types = new StreamTypeServiceImpl(typesPerStream, namesPerStream,
                        new boolean[numStreams], services.getEngineURI(), false);
                filters[i] = FilterSpecCompiler.makeFilterSpec(typesPerStream[i], namesPerStream[i],
                        Collections.singletonList(statementSpec.getFilterRootNode()), null, tagged, tagged,
                        types, statementContext.getMethodResolutionService(),
                        statementContext.getTimeProvider(), statementContext.getVariableService(),
                        statementContext.getEventAdapterService(), services.getEngineURI(), null,
                        statementContext, Collections.singleton(i));
            } catch (Exception ex) {
                log.warn("Unexpected exception analyzing filter paths: " + ex.getMessage(), ex);
            }
        }
    }

    boolean[] isIStreamOnly = new boolean[namesPerStream.length];
    Arrays.fill(isIStreamOnly, true);
    StreamTypeService typeService = new StreamTypeServiceImpl(typesPerStream, namesPerStream, isIStreamOnly,
            services.getEngineURI(), true);
    EPStatementStartMethod.validateNodes(statementSpec, statementContext, typeService, null);

    resultSetProcessor = ResultSetProcessorFactory.getProcessor(statementSpec, statementContext, typeService,
            null, new boolean[0], true);

    if (statementSpec.getSelectClauseSpec().isDistinct()) {
        if (resultSetProcessor.getResultEventType() instanceof EventTypeSPI) {
            eventBeanReader = ((EventTypeSPI) resultSetProcessor.getResultEventType()).getReader();
        }
        if (eventBeanReader == null) {
            eventBeanReader = new EventBeanReaderDefaultImpl(resultSetProcessor.getResultEventType());
        }
    }

    if (numStreams > 1) {
        Viewable[] viewablePerStream = new Viewable[numStreams];
        for (int i = 0; i < numStreams; i++) {
            viewablePerStream[i] = processors[i].getTailView();
        }
        JoinSetComposerDesc joinSetComposerDesc = statementContext.getJoinSetComposerFactory().makeComposer(
                statementSpec.getOuterJoinDescList(), statementSpec.getFilterRootNode(), typesPerStream,
                namesPerStream, viewablePerStream, SelectClauseStreamSelectorEnum.ISTREAM_ONLY,
                streamJoinAnalysisResult, statementContext, queryPlanLogging, null);
        joinComposer = joinSetComposerDesc.getJoinSetComposer();
        if (joinSetComposerDesc.getPostJoinFilterEvaluator() != null) {
            joinFilter = new JoinSetFilter(joinSetComposerDesc.getPostJoinFilterEvaluator());
        } else {
            joinFilter = null;
        }
    } else {
        joinComposer = null;
        joinFilter = null;
    }
}