private boolean isSourceOppositeToTargetInt( long sourceSense, long targetSense, POS sourcePOS, POS targetPOS) { long key; if (targetSense > sourceSense) { key = (targetSense << 32) + sourceSense; } else { key = (sourceSense << 32) + targetSense; } if ((POS.NOUN == sourcePOS) && (POS.NOUN == targetPOS)) { if (Arrays.binarySearch(noun_opp, key) >= 0) { log.trace("Found ! using ! (ANTONYM) between nouns"); return true; } } else { if ((POS.ADJECTIVE == sourcePOS) && (POS.ADJECTIVE == targetPOS)) { if (Arrays.binarySearch(adj_opp, key) >= 0) { log.trace("Found ! using ! (ANTONYM) between adjectives"); return true; } } else { if ((POS.ADVERB == sourcePOS) && (POS.ADVERB == targetPOS)) { if (Arrays.binarySearch(adv_opp, key) >= 0) { log.trace("Found ! using ! (ANTONYM) between adverbs"); return true; } } } } return false; }
private boolean isSourceSynonymTargetInt( long sourceSense, long targetSense, POS sourcePOS, POS targetPOS) { if (sourceSense == targetSense) { return true; } long key; if (targetSense > sourceSense) { key = (targetSense << 32) + sourceSense; } else { key = (sourceSense << 32) + targetSense; } if ((POS.ADJECTIVE == sourcePOS) && (POS.ADJECTIVE == targetPOS)) { if (Arrays.binarySearch(adj_syn, key) >= 0) { log.trace("Found = using & (SIMILAR_TO) between adjectives"); return true; } } if ((POS.NOUN == sourcePOS) && (POS.VERB == targetPOS)) { key = (targetSense << 32) + sourceSense; if (Arrays.binarySearch(nominalizations, key) >= 0) { log.trace("Found = using + (DERIVATION) between a noun and a verb"); return true; } } if ((POS.VERB == sourcePOS) && (POS.NOUN == targetPOS)) { key = (sourceSense << 32) + targetSense; if (Arrays.binarySearch(nominalizations, key) >= 0) { log.trace("Found = using + (DERIVATION) between a verb and a noun"); return true; } } return false; }
private static String keyTransform(String note, int key) { if (note.length() == 3) return note; if (key < 0) { char[] flatRange = Arrays.copyOfRange(circleOfFifths, 7 + key, 7); Arrays.sort(flatRange); if (Arrays.binarySearch(flatRange, note.charAt(0)) >= 0) return note.concat("@"); } if (key > 0) { char[] sharpRange = Arrays.copyOfRange(circleOfFifths, 0, key); Arrays.sort(sharpRange); if (Arrays.binarySearch(sharpRange, note.charAt(0)) >= 0) return note.concat("#"); } return note; }
public DictionaryEntry lookup(byte utfBytes[], int hashCode, int charLength) { int res = Arrays.binarySearch(hashCodes, hashCode); if (res < 0) { return null; } DictionaryEntry entry = entries[res]; if (Arrays.equals(entry.entryBytes, utfBytes)) { return entry; } int pos = res - 1; while ((pos >= 0) && (hashCodes[pos] == hashCode)) { entry = entries[pos]; if (Arrays.equals(entry.entryBytes, utfBytes)) { return entry; } --pos; } pos = res + 1; while ((pos < entries.length) && (hashCodes[pos] == hashCode)) { entry = entries[pos]; if (Arrays.equals(entry.entryBytes, utfBytes)) { return entry; } ++pos; } return UNKNOWN; }
private HashSet<Integer> getAdjPos(Node<Integer>[] sortedKeys, ArrayList<Node<Integer>> adj) { HashSet<Integer> result = new HashSet<Integer>(); for (Node<Integer> value : adj) { result.add(Arrays.binarySearch(sortedKeys, value)); } return result; }
public Iterator<Value> values(int fromIdx, int toIdx) { final int lId, gId; final int to = Math.min(toIdx, _len); if (sparse()) { int x = Arrays.binarySearch(_id, 0, sparseLen(), fromIdx); if (x < 0) x = -x - 1; lId = x; gId = x == sparseLen() ? _len : _id[x]; } else lId = gId = fromIdx; final Value v = new Value(lId, gId); final Value next = new Value(lId, gId); return new Iterator<Value>() { @Override public final boolean hasNext() { return next._gId < to; } @Override public final Value next() { if (!hasNext()) throw new NoSuchElementException(); v._gId = next._gId; v._lId = next._lId; next._lId++; if (sparse()) next._gId = next._lId < sparseLen() ? _id[next._lId] : _len; else next._gId++; return v; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
/** * Returns an int to int hash map with old row numbers mapped to new row numbers, which defines a * sorted order for this column * * @param validRows row numbers from which the sorted order is retrieved. */ public VIntIntHashMap getNewOrder(int[] validRows) { Object[] sortedValues = getValuesInRange(validRows[0], validRows[validRows.length - 1]); Object[] rawValues = getValues(validRows); // will hold the new order, the returned value. int[] newOrder = new int[validRows.length]; // a flag array. occupiedIndices[j] == true mean that the row number // stored at validRows[j] was already mapped to a value in tempMap boolean[] ocuupiedIndices = new boolean[validRows.length]; // for each valid row validRows[i] for (int i = 0; i < validRows.length; i++) { // finding the index of its mapped Object in values int newRow = Arrays.binarySearch(sortedValues, rawValues[i]); // because binarySearch can return the same index for items that are identical // checking for this option too. if (ocuupiedIndices[newRow]) { // if newRow index was already used - finding an alternative index newRow = getNewRow(rawValues[i], sortedValues, newRow, ocuupiedIndices); // marking the associated flag as true } ocuupiedIndices[newRow] = true; newOrder[newRow] = validRows[i]; } // end of for return VHashService.getMappedOrder(validRows, newOrder); }
// concurrent read/write access is allowed Object putAtomic( double key, Object value, Node b, boolean onlyIfAbsent, ConcurrentDoubleOrderedListMap orderedMap) { synchronized (b) { if (b.isMarked()) return Retry; synchronized (this) { if (isMarked()) return Retry; int len = len(); int pos = Arrays.binarySearch(keys, 0, len, key); if (pos >= 0) { Object old = vals[pos]; if (onlyIfAbsent) { if (old == null) { vals[pos] = value; return null; } else { return old; } } vals[pos] = value; return old; } pos = -(pos + 1); putAtomicReally(b, pos, key, value, orderedMap); return null; } } }
public void addNewsToDatabase(int id) // Временно, будет заменена на сервис { M_DB db = app.getDb(); if (!db.isOpen()) { db.open(); } int index = Arrays.binarySearch(tables, "News", String.CASE_INSENSITIVE_ORDER); String[] values = new String[DBcolumns.get(index).length]; if (id == 2) { values[1] = "Пираты освободили угнанный французский танкер, захватив часть груза"; values[2] = "1 января 2013 года"; values[3] = "Французский нефтяной танкер \"Гасконь\", захваченный ранее пиратами в территориальных водах Кот-д'Ивуара освобожден, сообщает ИТАР-ТАСС со ссылкой на владельца судна - компанию Sea Tankers.\n" + "\n" + "\"Он был освобожден в среду, рано утром. Пираты покинули корабль, который сейчас находится под контролем капитана\", - отметили в судоходной компании. Члены экипажа - 17 человек - получили во время захвата легкие ранения, и сейчас их осматривают врачи.\n" + "\n" + "Угнанный пиратами танкер перевозил дизельное топливо. Обычно пираты откачивают из захваченных судов топливо, которое потом продают на черном рынке.\n" + "\n" + "Как отметили в Sea Tankers, морские бандиты ушли не с пустыми руками. \"Была похищена часть груза\", - добавили в компании. Где именно сейчас находится \"Гасконь\" и куда держит курс, не сообщается из соображений безопасности. Владельцы судна также не стали объяснять, на каких условиях оно было освобождено, однако поблагодарили местные власти за содействие в этом вопросе."; } if (id == 3) { values[1] = "Во Владивостоке грязный снег сбрасывают в море"; values[2] = "15 января 2013 года"; values[3] = "В столице Приморья снег, убранный с городских трасс, не стесняются сбрасывать прямо в Амурский залив. Об этом в одной из социальных сетей рассказали очевидцы. За 40 минут приехало более 20 грузовиков. Снег загружают на площади Борцов за власть Советов, а сбрасывают в море за Набережной, возле автодрома «Аник».\n" + "Пресс-служба мэрии Владивостока сообщила о том, что грузовики, которые сбрасывают грязный снег в акваторию, МУП «Дороги Владивостока» не принадлежат. \n" + "Все машины этой организации имеют фирменный оранжевый логотип. Они счищают снег, складируют его на специально отведенных площадках, а затем вывозят на территорию выработанного буто-щебёночного карьера."; } values[0] = id + ""; db.addRec(tables[index], DBcolumns.get(index), values); if (db.isOpen()) { db.close(); } }
/** * Copy from the copy method in StructUtil. Did not want to drag that code in. maybe this actually * should go to struct. * * @param from * @param to * @param excludes * @return * @throws Exception */ public static <T extends struct> T xcopy(struct from, T to, String... excludes) throws Exception { Arrays.sort(excludes); for (Field f : from.fields()) { if (Arrays.binarySearch(excludes, f.getName()) >= 0) continue; Object o = f.get(from); if (o == null) continue; Field tof = to.getField(f.getName()); if (tof != null) try { tof.set(to, Converter.cnv(tof.getGenericType(), o)); } catch (Exception e) { System.out.println( "Failed to convert " + f.getName() + " from " + from.getClass() + " to " + to.getClass() + " value " + o + " exception " + e); } } return to; }
/** * Binary search of a key in a list. If there are several hits the last one is returned. * * @param a array to search into * @param e key to search for * @return index of the found hit or where the key ought to be inserted */ private int sortedLastIndexOf(final int[] a, final int e) { int i = Arrays.binarySearch(a, 0, rows, e); if (i >= 0) { while (++i < rows && a[i] == e) ; return i - 1; } return i; }
Object get(double key) { if (len() == 0) return null; int pos; if (key == keys[0]) pos = 0; else pos = Arrays.binarySearch(keys, 0, len(), key); if (pos < 0) return null; return vals[pos]; }
/* * Auxiliary Function for looking overlaps. * listOfIds has to be ordered since a binarySeach is done to look for currentZ in listOfIds * @param currentZ a current Id of an entity * @param listOfIds list of entities Ids (ordered listOfIds) * @return whether currentZ is in the listOfIds */ private static boolean find(int currentZ, ArrayList<Integer> listOfIds) { boolean found = false; int result = Arrays.binarySearch(listOfIds.toArray(), (Integer) currentZ); if (result > 0) { found = true; } return found; }
@Override public boolean isNA_impl(int i) { if (_len != sparseLen()) { int idx = Arrays.binarySearch(_id, 0, sparseLen(), i); if (idx >= 0) i = idx; else return false; } return isNA2(i); }
public static void main(String[] args) { Comparator<DataHolder> comp = new Comparator<DataHolder>() { public int compare(DataHolder o1, DataHolder o2) { return (o1.data < o2.data ? -1 : (o1.data == o2.data ? 0 : 1)); } }; DataHolder[] a = new DataHolderWithEquals[10]; for (int i = 0; i < a.length; i++) a[i] = new DataHolderWithEquals(i); Arrays.sort(a, comp); int location = Arrays.binarySearch(a, a[7], comp); printnb("Location of " + a[7] + " is " + location); if (location >= 0) print(", a[" + location + "] = " + a[location]); else print(); location = Arrays.binarySearch(a, a[5], comp); printnb("Location of " + a[5] + " is " + location); if (location >= 0) print(", a[" + location + "] = " + a[location]); }
protected Box createStbl(Track track, Movie movie, Map<Track, int[]> chunks) { SampleTableBox stbl = new SampleTableBox(); createStsd(track, stbl); createStts(track, stbl); createCtts(track, stbl); createStss(track, stbl); createSdtp(track, stbl); createStsc(track, chunks, stbl); createStsz(track, stbl); createStco(track, movie, chunks, stbl); Map<String, List<GroupEntry>> groupEntryFamilies = new HashMap<String, List<GroupEntry>>(); for (Map.Entry<GroupEntry, long[]> sg : track.getSampleGroups().entrySet()) { String type = sg.getKey().getType(); List<GroupEntry> groupEntries = groupEntryFamilies.get(type); if (groupEntries == null) { groupEntries = new ArrayList<GroupEntry>(); groupEntryFamilies.put(type, groupEntries); } groupEntries.add(sg.getKey()); } for (Map.Entry<String, List<GroupEntry>> sg : groupEntryFamilies.entrySet()) { SampleGroupDescriptionBox sgdb = new SampleGroupDescriptionBox(); String type = sg.getKey(); sgdb.setGroupEntries(sg.getValue()); SampleToGroupBox sbgp = new SampleToGroupBox(); sbgp.setGroupingType(type); SampleToGroupBox.Entry last = null; for (int i = 0; i < track.getSamples().size(); i++) { int index = 0; for (int j = 0; j < sg.getValue().size(); j++) { GroupEntry groupEntry = sg.getValue().get(j); long[] sampleNums = track.getSampleGroups().get(groupEntry); if (Arrays.binarySearch(sampleNums, i) >= 0) { index = j + 1; } } if (last == null || last.getGroupDescriptionIndex() != index) { last = new SampleToGroupBox.Entry(1, index); sbgp.getEntries().add(last); } else { last.setSampleCount(last.getSampleCount() + 1); } } stbl.addBox(sgdb); stbl.addBox(sbgp); } if (track instanceof CencEncryptedTrack) { createCencBoxes((CencEncryptedTrack) track, stbl, chunks.get(track)); } createSubs(track, stbl); return stbl; }
@Override boolean setNA_impl(int i) { if (isNA_impl(i)) return true; if (sparseLen() != _len) { int idx = Arrays.binarySearch(_id, 0, sparseLen(), i); if (idx >= 0) i = idx; else cancel_sparse(); // todo - do not necessarily cancel sparse here } return setNA_impl2(i); }
public final int readCharacter(final char[] allowed) throws IOException { // if we restrict to a limited set and the current character // is not in the set, then try again. char c; Arrays.sort(allowed); // always need to sort before binarySearch while (Arrays.binarySearch(allowed, c = (char) readVirtualKey()) < 0) ; return c; }
public static String prefixAttribute(final String attrName, boolean isXhtml) { if (isXhtml) { if (Arrays.binarySearch(XHTML_PREFIX_ATTRIBUTES, attrName) > -1) { return XHTML_ATTR_PREFIX + attrName; } else { return attrName; } } else { return attrName; } }
/** * Gets the method annotations for the given method, or null if no annotations are defined for * that method * * @param methodIdItem The method to get the annotations for * @return An <code>AnnotationSetItem</code> containing the method annotations, or null if none * are found */ @Nullable public AnnotationSetItem getMethodAnnotations(MethodIdItem methodIdItem) { if (methodAnnotations == null) { return null; } int index = Arrays.binarySearch(methodAnnotations, methodIdItem); if (index < 0) { return null; } return methodAnnotations[index].annotationSet; }
/** * Gets the parameter annotations for the given method, or null if no parameter annotations are * defined for that method * * @param methodIdItem The method to get the parameter annotations for * @return An <code>AnnotationSetRefList</code> containing the parameter annotations, or null if * none are found */ @Nullable public AnnotationSetRefList getParameterAnnotations(MethodIdItem methodIdItem) { if (parameterAnnotations == null) { return null; } int index = Arrays.binarySearch(parameterAnnotations, methodIdItem); if (index < 0) { return null; } return parameterAnnotations[index].annotationSet; }
/** * Gets the field annotations for the given field, or null if no annotations are defined for that * field * * @param fieldIdItem The field to get the annotations for * @return An <code>AnnotationSetItem</code> containing the field annotations, or null if none are * found */ @Nullable public AnnotationSetItem getFieldAnnotations(FieldIdItem fieldIdItem) { if (fieldAnnotations == null) { return null; } int index = Arrays.binarySearch(fieldAnnotations, fieldIdItem); if (index < 0) { return null; } return fieldAnnotations[index].annotationSet; }
@Override public ConfigurableWrapper addChild(Configurable configurable) { if (myComparator != null) { int index = Arrays.binarySearch(myKids, configurable, myComparator); LOG.assertTrue(index < 0, "similar configurable is already exist"); myKids = ArrayUtil.insert(myKids, -1 - index, configurable); } else { myKids = ArrayUtil.append(myKids, configurable); } return this; }
private boolean isSourceLessGeneralThanTargetInt( long sourceSense, long targetSense, POS sourcePOS, POS targetPOS) { long key = (sourceSense << 32) + targetSense; if ((POS.NOUN == sourcePOS) && (POS.NOUN == targetPOS)) { if (Arrays.binarySearch(noun_mg, key) >= 0) { log.trace( "Found < using @,#m,#s,#p (HYPERNYM, MEMBER_, SUBSTANCE_, PART_HOLONYM) between nouns"); return true; } } else { if ((POS.VERB == sourcePOS) && (POS.VERB == targetPOS)) { if (Arrays.binarySearch(verb_mg, key) >= 0) { log.trace("Found < using @ (HYPERNYM) between verbs"); return true; } } } return false; }
@Override public long at8_impl(int i) { if (_len != sparseLen()) { int idx = Arrays.binarySearch(_id, 0, sparseLen(), i); if (idx >= 0) i = idx; else return 0; } if (isNA2(i)) throw new RuntimeException("Attempting to access NA as integer value."); if (_ls == null) return (long) _ds[i]; return _ls[i] * PrettyPrint.pow10i(_xs[i]); }
/** {@inheritDoc} */ public boolean removeAll(float[] array) { Arrays.sort(array); boolean modified = false; TFloatIterator iter = iterator(); while (iter.hasNext()) { if (Arrays.binarySearch(array, iter.next()) >= 0) { iter.remove(); modified = true; } } return modified; }
// no concurrent read/write access is assumed Object put(double key, Object value, ConcurrentDoubleOrderedListMap orderedMap) { int len = len(); int pos = Arrays.binarySearch(keys, 0, len, key); if (pos >= 0) { Object old = vals[pos]; vals[pos] = value; return old; } else { pos = -(pos + 1); putReally(pos, key, value, orderedMap); return null; } }
/** {@inheritDoc} */ public boolean retainAll(byte[] array) { boolean changed = false; Arrays.sort(array); byte[] data = _data; for (int i = data.length; i-- > 0; ) { if (Arrays.binarySearch(array, data[i]) < 0) { remove(i, 1); changed = true; } } return changed; }
// Set & At on NewChunks are weird: only used after inflating some other // chunk. At this point the NewChunk is full size, no more appends allowed, // and the xs exponent array should be only full of zeros. Accesses must be // in-range and refer to the inflated values of the original Chunk. @Override boolean set_impl(int i, long l) { if (_ds != null) return set_impl(i, (double) l); if (sparseLen() != _len) { // sparse? int idx = Arrays.binarySearch(_id, 0, sparseLen(), i); if (idx >= 0) i = idx; else cancel_sparse(); // for now don't bother setting the sparse value } _ls[i] = l; _xs[i] = 0; _naCnt = -1; return true; }
/** * Inserts a new record. * * @param pre record PRE * @param id record ID * @param c number of inserted records */ public void insert(final int pre, final int id, final int c) { if (rows == 0 && pre == id && id == baseid + 1) { // no mapping and we append at the end => nothing to do baseid += c; return; } int pos = 0; int inc = c; int oid = pre; if (rows > 0) { pos = Arrays.binarySearch(pres, 0, rows, pre); if (pos < 0) { pos = -pos - 1; if (pos != 0) { // check if inserting into an existing id interval final int prev = pos - 1; final int prevcnt = nids[prev] - fids[prev] + 1; final int prevpre = pres[prev]; if (pre < prevpre + prevcnt) { // split the id interval final int split = pre - prevpre; final int fid = fids[prev] + split; // add a new next interval add(pos, pre, fid, nids[prev], incs[prev], oids[prev]); // shrink the previous interval nids[prev] = fid - 1; incs[prev] -= prevcnt - split; oid = oids[prev]; inc += incs[prev]; } else { oid = pre - incs[prev]; inc += incs[prev]; } } } else if (pos > 0) { oid = oids[pos]; inc += incs[pos - 1]; } increment(pos, c); } // add the new interval add(pos, pre, id, id + c - 1, inc, oid); }