List of usage examples for java.util Arrays binarySearch
public static int binarySearch(Object[] a, Object key)
From source file:org.conqat.engine.commons.statistics.RankedMetric.java
/** * For a node this reads the metric value and determines the weighted rank. * This also stores the rank at key {@link #rankWriteKey}. * /*from w w w. ja va2 s . c o m*/ * {@link #setUpRanks(IConQATNode, int)} must be called before this method * can be used. * * @return the rank of the metric at this node is a value >= 0 and < * rankCount * @throws ConQATException * if a value is non-numeric * @see #setUpRanks(IConQATNode, int) */ public double determineWeightedRank(IConQATNode node) throws ConQATException { CCSMPre.isFalse(rankUpperLimits == null, "Ranks must be set up before calling this method."); double value = getValue(node); int rank = Arrays.binarySearch(rankUpperLimits, value); if (rank < 0) { // value was not found in limits array rank = -(rank + 1); } else if (rank > 0) { // value was found in limits array // it may happen that the upper limits of multiple ranks are equal. // For example 6-ranking the values 0,1,1,1,3,8,50 results in the // following rank limits: 0.3333333333333335, 1.0, 1.0, // 4.66666666666667, 36.00000000000005, infty. Now a binary search // for 1.0 may return either of the two ranks, the binary search // function makes no guarantees for which one it returns. Hence, we // iterate towards the beginning of the array to always return the // first value (the lowest rank). for (int i = rank - 1; i >= 0; i--) { if (rankUpperLimits[i] == rankUpperLimits[rank]) { rank = i; } } } double result = weight * rank; node.setValue(rankWriteKey, result); return result; }
From source file:com.music.util.music.ChordUtils.java
private static void initializeChords() { for (Scale scale : Scale.values()) { List<Chord> scaleChords = new ArrayList<Chord>(); List<Chord> scaleSeventhChords = new ArrayList<Chord>(); List<Chord> scaleOtherChords = new ArrayList<Chord>(); int[][] chordDefs = new int[][] { Chords.MAJOR, Chords.MINOR, Chords.DIMINISHED, Chords.AUGMENTED }; for (int note : scale.getDefinition()) { int chordType = -1; int[] chordDef = null; int[] seventhChordDef = null; int[] otherChordDef = null; for (int i = 0; i < chordDefs.length; i++) { if (isScaleChord(chordDefs[i], scale, note)) { chordType = i;//from w w w .j ava 2 s. c o m if (chordType == 0) { chordDef = Chords.MAJOR; seventhChordDef = Chords.MAJOR_SEVENTH; otherChordDef = Chords.SIXTH; } if (chordType == 1) { chordDef = Chords.MINOR; seventhChordDef = Chords.MINOR_SEVENTH; otherChordDef = Chords.MINOR_SIXTH; } if (chordType == 2) { chordDef = Chords.DIMINISHED; seventhChordDef = Chords.DIMINISHED_SEVENTH; otherChordDef = Chords.DIMINISHED; // nothing specific - use default } if (chordType == 3) { chordDef = Chords.AUGMENTED; seventhChordDef = Chords.SEVENTH_SHARP_FIFTH; otherChordDef = Chords.AUGMENTED; // nothing specific - use default } if (chordDef != null) { // chords in some scales (e.g. Turkish) may not be classified in the above 4 groups. Skip those ToneType firstToneType = ToneType .forDegree(Arrays.binarySearch(scale.getDefinition(), note)); Chord chord = getChordDef(note, chordDef); chord.setChordType(ChordType.values()[chordType]); chord.setFirstToneType(firstToneType); scaleChords.add(chord); Chord seventhChord = getChordDef(note, seventhChordDef); seventhChord.setFirstToneType(firstToneType); chord.setChordType(ChordType.values()[chordType]); scaleSeventhChords.add(seventhChord); Chord otherChord = getChordDef(note, otherChordDef); otherChord.setFirstToneType(firstToneType); chord.setChordType(ChordType.values()[chordType]); scaleOtherChords.add(otherChord); } } } } chords.put(scale, scaleChords); seventhChords.put(scale, scaleSeventhChords); otherChords.put(scale, scaleOtherChords); } }
From source file:org.acegisecurity.acl.basic.AbstractBasicAclEntry.java
public int togglePermission(int permissionToToggle) { this.mask ^= permissionToToggle; if (Arrays.binarySearch(validPermissions, this.mask) < 0) { throw new IllegalArgumentException("Resulting permission set will be invalid."); } else {//ww w . j ava 2 s. co m return this.mask; } }
From source file:org.apache.hadoop.hbase.replication.regionserver.SerialReplicationChecker.java
private boolean canPush(Entry entry, byte[] row) throws IOException { String encodedNameAsString = Bytes.toString(entry.getKey().getEncodedRegionName()); long seqId = entry.getKey().getSequenceId(); ReplicationBarrierResult barrierResult = MetaTableAccessor.getReplicationBarrierResult(conn, entry.getKey().getTableName(), row, entry.getKey().getEncodedRegionName()); LOG.debug("Replication barrier for {}: {}", entry, barrierResult); long[] barriers = barrierResult.getBarriers(); int index = Arrays.binarySearch(barriers, seqId); if (index == -1) { LOG.debug("{} is before the first barrier, pass", entry); // This means we are in the range before the first record openSeqNum, this usually because the // wal is written before we enable serial replication for this table, just return true since // we can not guarantee the order. pushed.getUnchecked(encodedNameAsString).setValue(seqId); return true; }//w w w. j a va 2 s . c o m // The sequence id range is left closed and right open, so either we decrease the missed insert // point to make the index start from 0, or increase the hit insert point to make the index // start from 1. Here we choose the latter one. if (index < 0) { index = -index - 1; } else { index++; } if (index == 1) { // we are in the first range, check whether we have parents for (byte[] regionName : barrierResult.getParentRegionNames()) { if (!isParentFinished(regionName)) { LOG.debug("Parent {} has not been finished yet for entry {}, give up", Bytes.toStringBinary(regionName), entry); return false; } } if (isLastRangeAndOpening(barrierResult, index)) { LOG.debug("{} is in the last range and the region is opening, give up", entry); return false; } LOG.debug("{} is in the first range, pass", entry); recordCanPush(encodedNameAsString, seqId, barriers, 1); return true; } // check whether the previous range is finished if (!isRangeFinished(barriers[index - 1], encodedNameAsString)) { LOG.debug("Previous range for {} has not been finished yet, give up", entry); return false; } if (isLastRangeAndOpening(barrierResult, index)) { LOG.debug("{} is in the last range and the region is opening, give up", entry); return false; } LOG.debug("The previous range for {} has been finished, pass", entry); recordCanPush(encodedNameAsString, seqId, barriers, index); return true; }
From source file:com.jgeppert.struts2.jquery.components.Head.java
private static String validateLocal(String[] locals, String local) { String retString = "en"; // Array must be sorted for binarySearch Arrays.sort(locals);/*from w ww . ja v a 2 s. c o m*/ if (Arrays.binarySearch(locals, local) > 0) { retString = local; } else if (local.length() > 2 && Arrays.binarySearch(locals, local.substring(0, 2)) > 0) { retString = local.substring(0, 2); } return retString; }
From source file:de.tap.easy_xkcd.fragments.comics.FavoritesFragment.java
public void importFavorites(Intent intent) { String filePath = intent.getStringExtra(FilePickerActivity.RESULT_FILE_PATH); try {/* w ww . ja v a 2 s .c o m*/ File file = new File(filePath); InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file)); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; Stack<Integer> newFavorites = new Stack<>(); while ((line = bufferedReader.readLine()) != null) { String[] numberTitle = line.split(" - "); int number = Integer.parseInt(numberTitle[0]); if (Arrays.binarySearch(favorites, number) < 0) { newFavorites.push(number); databaseManager.setFavorite(number, true); if (number <= ((MainActivity) getActivity()).getDatabaseManager().getHighestInDatabase()) ((MainActivity) getActivity()).getDatabaseManager().setFavorite(number, true); } if (!prefHelper.fullOfflineEnabled()) { new DownloadImageTask(newFavorites).execute(); } } } catch (Exception e) { e.printStackTrace(); Toast.makeText(getActivity(), "Import failed", Toast.LENGTH_SHORT).show(); } }
From source file:org.apache.jackrabbit.oak.plugins.index.solr.server.EmbeddedSolrServerProvider.java
private void checkSolrConfiguration(String solrHomePath, String coreName) throws IOException { File solrHomePathFile = new File(solrHomePath); log.info("checking configuration at {}", solrHomePathFile.getAbsolutePath()); // check if solrHomePath exists if (!solrHomePathFile.exists()) { if (!solrHomePathFile.mkdirs()) { throw new IOException("could not create solrHomePath directory"); } else {//from ww w . jav a 2s . c o m // copy all the needed files to the just created directory copy("/solr/solr.xml", solrHomePath); copy("/solr/zoo.cfg", solrHomePath); } } else if (!solrHomePathFile.isDirectory()) { throw new IOException( "a non directory file with the specified name already exists for the given solrHomePath '" + solrHomePath); } File solrCorePathFile = new File(solrHomePathFile, coreName); if (!solrCorePathFile.exists()) { if (!new File(solrCorePathFile, "conf").mkdirs()) { throw new IOException("could not create nested core directory in solrHomePath/solrCoreName/conf"); } String solrCoreDir = solrCorePathFile.getAbsolutePath(); File coreProperties = new File(new File(solrCoreDir), "core.properties"); assert coreProperties.createNewFile(); FileOutputStream out = new FileOutputStream(coreProperties); IOUtils.writeBytes(out, ("name=" + coreName).getBytes("UTF-8")); out.flush(); out.close(); String coreConfDir = solrCoreDir + "/conf/"; copy("/solr/oak/conf/currency.xml", coreConfDir); copy("/solr/oak/conf/schema.xml", coreConfDir); copy("/solr/oak/conf/solrconfig.xml", coreConfDir); } else if (!solrCorePathFile.isDirectory()) { throw new IOException( "a non directory file with the specified name already exists for the given Solr core path'" + solrCorePathFile.getAbsolutePath()); } // clean data dir File solrDataPathFile = new File(solrHomePathFile + "/" + coreName + "/data/index"); if (solrDataPathFile.exists()) { log.debug("deleting stale lock files"); File[] locks = solrDataPathFile.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return "write.lock".equals(name); } }); log.debug("found {} lock files", locks.length); // remove eventaul previous lock files (e.g. due to ungraceful shutdown) if (locks.length > 0) { for (File f : locks) { FileUtils.forceDelete(f); log.debug("deleted {}", f.getAbsolutePath()); } } } // check if the a core with the given coreName exists String[] files = solrHomePathFile.list(); Arrays.sort(files); if (Arrays.binarySearch(files, coreName) < 0) { throw new IOException("could not find a directory with the coreName '" + coreName + "' in the solrHomePath '" + solrHomePath + "'"); } }
From source file:org.fhcrc.cpl.viewer.gui.SpectrumComponent.java
protected void copyChartData() { if (null == _chart || null == _spectrum) return;//from w w w.j a v a2 s . com XYPlot xyplot; if (_chart.getPlot() instanceof XYPlot) { xyplot = _chart.getXYPlot(); } else { // UNDONE: return; } ValueAxis domainAxis = xyplot.getDomainAxis(); Range range = domainAxis.getRange(); double min = range.getLowerBound(); double max = range.getUpperBound(); float[] x = _spectrum[0]; float[] y = _spectrum[1]; int start = Arrays.binarySearch(x, (float) min); if (start < 0) start = -(start + 1); int end = Arrays.binarySearch(x, (float) max); if (end < 0) end = -(end + 1); StringBuffer sb = new StringBuffer(20 * (end - start)); for (int i = start; i < end; i++) sb.append(x[i]).append('\t').append(y[i]).append('\n'); StringSelection sel = new StringSelection(sb.toString()); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel, sel); }
From source file:dk.dma.ais.packet.AisPacketFiltersStateful.java
/** * Return false if this message is known to be related to a target with a navstat outside the given list. *//*from w w w . j a va2 s . c om*/ public Predicate<AisPacket> filterOnTargetNavigationalStatus(Integer[] navstats) { final int[] list = ArrayUtils.toPrimitive(navstats); Arrays.sort(list); return new Predicate<AisPacket>() { public boolean test(AisPacket p) { aisPacketStream.add(p); // Update state final int mmsi = getMmsi(p); // Get MMSI in question final int navstat = getNavstat(mmsi); // Extract navstat no. - if we know it return navstat < 0 ? false : Arrays.binarySearch(list, navstat) >= 0; } public String toString() { return "navstat in " + skipBrackets(Arrays.toString(list)); } }; }