/** Finds the matching entry. */ @Override public final void generateController(String name, ArrayList<E> controllerList) { updateIfModifiedNow(); Thread thread = Thread.currentThread(); ClassLoader oldLoader = thread.getContextClassLoader(); try { thread.setContextClassLoader(getParentClassLoader()); String key = nameToKey(name); ExpandVersion version = _expandManager.getPrimaryVersion(key); if (version == null) version = _expandManager.getVersion(key); if (version == null) return; E controller = createController(version); if (controller != null) { controller.addExpandCleanupFileSet(_expandCleanupFileSet); controllerList.add(controller); // _controllerNames.add(name); // server/1d19 } } finally { thread.setContextClassLoader(oldLoader); } }
@SuppressWarnings("unchecked") @Override public <E extends Entry<K, V>> E put(E entry) { if (entry.getKey() == null) { return updateNullEntry(entry); } if (entry.getValue() == null) { return remove(entry.getKey()); } Object result = root.put(conf, entry); if (result == null) { this.size++; return null; } if (result instanceof Split) { Split<K, V> split = (Split<K, V>) result; this.root = new InnerNode<K, V>(conf, root, split.getKey(), split.getGreater()); this.size++; return null; } else { return (E) result; } }
/** * @see * edu.buffalo.cse.green.RefactorHandler#handleMove(edu.buffalo.cse.green.editor.model.RootModel, * org.eclipse.jdt.core.IJavaElement, org.eclipse.jdt.core.IJavaElement) */ public void handleMove(RootModel root, E sourceElement, E targetElement) { root.changeProjectElement(sourceElement, targetElement); try { List<IJavaElement> packages = root.getElementsOfKind(PACKAGE_FRAGMENT); // look through packages to match up source and destination elements for (IJavaElement packElement : packages) { IPackageFragment packFrag = (IPackageFragment) packElement; if (JavaModelListener.sameElements( packFrag.getAncestor(JAVA_PROJECT), sourceElement.getPrimaryElement())) { for (IPackageFragment packFrags : targetElement.getPackageFragments()) { // check for the same name of the two packages if (packFrag.getElementName().equals(packFrags.getElementName())) { PackageRefactorHandler.instance().handleMove(root, packFrag, packFrags); } } } } root.dispose(); } catch (JavaModelException e) { e.printStackTrace(); } }
private void ensureUnique(E e) { Object remove = this.uniqueClasses.remove(e.getClass()); if (remove != null) { this.list.remove(remove); } this.uniqueClasses.put(e.getClass(), e); }
/** * Called by the base class to add attributes to the meta data. * * @param metaData the meta data instance receiving the attributes. * @param ebXML the ebXML instance containing the attributes. */ protected void addAttributesFromEbXML(C metaData, E ebXML) { metaData.setComments(ebXML.getDescription()); metaData.setTitle(ebXML.getName()); metaData.setEntryUuid(ebXML.getId()); metaData.setLogicalUuid(ebXML.getLid()); metaData.setVersion(ebXML.getVersionInfo()); }
/** * Returns an enum instance for the requested value. * * @param pref error prefix * @param name name * @param names allowed names * @param <E> token type * @return enum * @throws BaseXException database exception */ public static <E extends Enum<E>> E value(final String pref, final byte[] name, final E[] names) throws BaseXException { final String n = string(name); for (final E nm : names) if (n.equals(nm.toString())) return nm; throw new BaseXException("%: Unexpected element: \"%\".", pref, name); }
public static <T extends Collection<E>, E extends Number> int countOdds(T list) { int count = 0; for (E elem : list) { count += elem.longValue() % 2; } return count; }
/** * Adds an action to the action set. * * @param action The action * @since jEdit 4.0pre1 */ public void addAction(E action) { actions.put(action.getName(), action); if (context != null) { context.actionNames = null; context.actionHash.put(action.getName(), this); } } // }}}
/** * @param boundType * @return * @see javax.xml.bind.annotation.adapters.XmlAdapter#marshal(java.lang.Object) */ @Override public S marshal(final Map<K, V> boundType) { // Do not generate an empty tag for an empty map if ((boundType == null) || boundType.isEmpty()) { return null; } // Sort incoming map // Default sort SortedMap<K, V> sortedMap = CollectionUtil.newSortedMap(); // Specified sort if (comparator != null) { sortedMap = CollectionUtil.newSortedMap(comparator); } sortedMap.putAll(boundType); // Convert to a list final List<E> list = CollectionUtil.newList(); for (final Map.Entry<K, V> entry : sortedMap.entrySet()) { final E entryEntity = newEntryTypeInstance(); entryEntity.setKey(entry.getKey()); entryEntity.setValue(entry.getValue()); list.add(entryEntity); } final S map = newValueTypeInstance(); setValueTypeArray(map, list); return map; }
@SuppressWarnings("unchecked") private void formSplitComponent( V u, V v, V current, List<E> coveredEdges, List<V> coveredVertices, SplitComponent<V, E> component, Graph<V, E> graph) { if (coveredVertices.contains(current)) return; coveredVertices.add(current); component.addVertex(current); for (E e : graph.allEdges(current)) { if (coveredEdges.contains(e)) continue; coveredEdges.add(e); component.addEdge(e); V other = e.getDestination() == current ? e.getOrigin() : e.getDestination(); if (other != u && other != v) { formSplitComponent(u, v, other, coveredEdges, coveredVertices, component, graph); } else component.addVertex(other); } }
private E removeEntry(BinaryNode node, E entry, BinaryNode father) { E result = null; if (entry.compareTo(node.getData()) == 0) { result = node.getData(); decSize(); if (!hasLeft(node)) { // der er ikke et venstre barn if (node.equals(father.getLeft())) { father.setLeft(right(node)); } else { father.setRight(right(node)); } } else if (!hasRight(node)) { // der er ikke et højre barn if (node.equals(father.getLeft())) { father.setLeft(left(node)); } else { father.setRight(left(node)); } } else { // der er både højre og venstre barn} removeNodeTwoChildren(node); } } else if (entry.compareTo(node.getData()) < 0) { if (hasLeft(node)) removeEntry((BinaryNode) left(node), entry, node); } else { if (hasRight(node)) removeEntry((BinaryNode) right(node), entry, node); } return result; }
/* * (non-Javadoc) * @see de.hpi.bpt.hypergraph.abs.IHyperGraph#addEdge(java.util.Collection) */ @SuppressWarnings("unchecked") public E addEdge(Collection<V> vs) { E e = (E) new AbstractHyperEdge<V>(this); e.addVertices(vs); return e; }
/* * (non-Javadoc) * @see de.hpi.bpt.hypergraph.abs.IHyperGraph#addEdge(de.hpi.bpt.hypergraph.abs.IVertex) */ @SuppressWarnings("unchecked") public E addEdge(V v) { E e = (E) new AbstractHyperEdge<V>(this); e.addVertex(v); return e; }
/** INTERNAL: Rehashes the hashset to a bigger size. */ @SuppressWarnings("unchecked") protected void rehash(int newCapacity) { int oldCapacity = objects.length; @SuppressWarnings("unchecked") E[] newObjects = (E[]) new Object[newCapacity]; for (E o : objects) { if (o == null || o == deletedObject) continue; int hash = o.hashCode(); int index = (hash & 0x7FFFFFFF) % newCapacity; int offset = 1; // search for the object while (newObjects[index] != null) { // no need to test for duplicates index = ((index + offset) & 0x7FFFFFFF) % newCapacity; offset = offset * 2 + 1; if (offset == -1) offset = 2; } newObjects[index] = (E) o; } objects = newObjects; freecells = objects.length - elements; }
/** * Compare the {@linkplain Entity} objects returning the desired ordering. * * @param e1 The first {@linkplain Entity} to be used in the comparison. * @param e2 The second {@linkplain Entity} to be used in the comparison. * @return -1 if e1 is less than e2; 0 if e1 and e2 are equal 1 if e2 is greater than e1 */ @Override public int compare(E e1, E e2) { Fitness f1 = e1.getFitness(); Fitness f2 = e2.getFitness(); return f1.compareTo(f2); }
/** * This function is actually responsible for querying the database. * * @return list of entity objects currently in view * @throws DatabaseException */ private List<E> getData(Database db) throws DatabaseException { // TODO: move the row level security to the entitymapper... FormModel<E> model = getModel(); // set form level rights boolean formReadonly = model.isReadonly() || !model.getLogin().canWrite(model.create().getClass()); model.setReadonly(formReadonly); // load the rows List<E> visibleRecords = new ArrayList<E>(); // load all records and select rows that can be visible // List allRecords = view.getDatabase().find( view.getEntityClass(), // allRules ); List<E> allRecords = pager.getPage(db); for (E record : allRecords) { boolean rowReadonly = formReadonly || !model.getLogin().canWrite(record.getClass()); if (rowReadonly) record.setReadonly(true); // else // recordreadonly = false; visibleRecords.add(record); } return visibleRecords; }
protected FloatArrayPartition initScoreStore() { FloatArrayPartition p = new StaticFloatArrayPartition(elementStore.getIndexStart(), elementStore.capacity()); try { if (scoreScanner != null) { long startTime = System.currentTimeMillis(); ElementScoreHandler handler = new ElementScoreHandler(p); scoreScanner.scan(handler); for (int i = p.getIndexStart(), end = p.getIndexEnd(); i < end; i++) { float score = p.get(i); if (score < Score.MIN_SCORE_FLOAT) { score = Score.MIN_SCORE_FLOAT; p.set(i, score); } if (elementStore.hasIndex(i)) { E element = elementStore.getElement(i); if (element != null) { element.setScore(score); } } } long totalTime = System.currentTimeMillis() - startTime; logger.info(getName() + " load element scores: " + totalTime + " ms"); } } catch (Exception e) { logger.warn(getName() + " faileld to load element scores", e); } return p; }
/** * Handles the event publication by pushing it to the real subscriber's subscription method. * * @param event The event to publish. */ @Override public void onEvent(final E event) { try { final Object obj = getProxiedSubscriber(); if (obj == null) return; // has been garbage collected getSubscriptionMethod().invoke(obj, event); } catch (final IllegalAccessException exc) { log.error( "Exception during event handling:\n\t[Event] " + event.getClass().getName() + ":" + event + "\n\t[Subscriber] " + getProxiedSubscriber() + "\n\t[Method] " + getSubscriptionMethod(), exc); } catch (final InvocationTargetException exc) { log.error( "Exception during event handling:\n\t[Event] " + event.getClass().getName() + event + "\n\t[Subscriber] " + getProxiedSubscriber() + "\n\t[Method] " + getSubscriptionMethod(), exc.getCause()); } }
public String getUnity(PmiStatsType pmiStatsType, E statistic) { String unity = (pmiStatsType.isUnit()) ? "_" + statistic.getUnit() + " " : " "; if ("N/A".equals(statistic.getUnit()) || statistic.getUnit() == null) { unity = " "; } return unity.toLowerCase(); }
@Override public boolean remove(Object o) { if (o == null) { throw new NullPointerException("Argument is null"); } for (int i = 0; i < elements.length; i++) { E element = elements[i]; if (element == null) { continue; } if (element.equals(o)) { int updatedSize = elements.length - 1; E[] updatedArray = createNewArray(elements.length - 1); if (i == 0) { System.arraycopy(elements, 1, updatedArray, 0, updatedSize); } else if (i == elements.length - 1) { System.arraycopy(elements, 0, updatedArray, 0, updatedSize); } else { System.arraycopy(elements, 0, updatedArray, 0, i); System.arraycopy(elements, i + 1, updatedArray, i, updatedSize - i); } elements = updatedArray; return true; } } return false; }
@Override void setRange(E start, E end) { int startOrdinal = start.ordinal(); int startIndex = startOrdinal / BIT_IN_LONG; int startInBits = startOrdinal % BIT_IN_LONG; int endOrdinal = end.ordinal(); int endIndex = endOrdinal / BIT_IN_LONG; int endInBits = endOrdinal % BIT_IN_LONG; if (startIndex == endIndex) { long range = (-1L >>> (BIT_IN_LONG - (endInBits - startInBits + 1))) << startInBits; size -= Long.bitCount(bits[startIndex]); bits[startIndex] |= range; size += Long.bitCount(bits[startIndex]); } else { long range = (-1L >>> startInBits) << startInBits; size -= Long.bitCount(bits[startIndex]); bits[startIndex] |= range; size += Long.bitCount(bits[startIndex]); // endInBits + 1 is the number of consecutive ones. // 63 - endInBits is the following zeros of the right most one. range = -1L >>> (BIT_IN_LONG - (endInBits + 1)); size -= Long.bitCount(bits[endIndex]); bits[endIndex] |= range; size += Long.bitCount(bits[endIndex]); for (int i = (startIndex + 1); i <= (endIndex - 1); i++) { size -= Long.bitCount(bits[i]); bits[i] = -1L; size += Long.bitCount(bits[i]); } } }
/** * Retrieves and removes the head of this queue, waiting if necessary until an element with an * expired delay is available on this queue. * * @return the head of this queue * @throws InterruptedException {@inheritDoc} */ public E take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (; ; ) { E first = q.peek(); if (first == null) available.await(); else { long delay = first.getDelay(TimeUnit.NANOSECONDS); if (delay <= 0) return q.poll(); else if (leader != null) available.await(); else { Thread thisThread = Thread.currentThread(); leader = thisThread; try { available.awaitNanos(delay); } finally { if (leader == thisThread) leader = null; } } } } } finally { if (leader == null && q.peek() != null) available.signal(); lock.unlock(); } }
public void add(E newData) { innerList.add(newData); // 如果放进来的是第一个元素,那就是根节点,无需其它才做 if (innerList.size() == 1) { } else { int currentIndex = innerList.size() - 1; int parentIndex = (currentIndex - 1) / 2; E parent = innerList.get(parentIndex); while (currentIndex != 0 && parent.compareTo(newData) < 0) { E tmp = parent; innerList.set(parentIndex, innerList.get(currentIndex)); innerList.set(currentIndex, tmp); currentIndex = parentIndex; parentIndex = (currentIndex - 1) / 2; parent = innerList.get(parentIndex); } } System.out.println("add执行完毕,当前的数组:"); for (E e : innerList) { System.out.print(e + " "); } System.out.println(""); }
/** * Retrieves and removes the head of this queue, waiting if necessary until an element with an * expired delay is available on this queue, or the specified wait time expires. * * @return the head of this queue, or <tt>null</tt> if the specified waiting time elapses before * an element with an expired delay becomes available * @throws InterruptedException {@inheritDoc} */ public E poll(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (; ; ) { E first = q.peek(); if (first == null) { if (nanos <= 0) return null; else nanos = available.awaitNanos(nanos); } else { long delay = first.getDelay(TimeUnit.NANOSECONDS); if (delay <= 0) return q.poll(); if (nanos <= 0) return null; if (nanos < delay || leader != null) nanos = available.awaitNanos(nanos); else { Thread thisThread = Thread.currentThread(); leader = thisThread; try { long timeLeft = available.awaitNanos(delay); nanos -= delay - timeLeft; } finally { if (leader == thisThread) leader = null; } } } } } finally { if (leader == null && q.peek() != null) available.signal(); lock.unlock(); } }
/** * Adds the given edge to those to be displayed in the viewer. Note that the edge must connect * nodes that have already been added to the viewer. This version will use the locations of the * two nodes to calculate their distance of separation. * * @param edge Edge to add to the display. * @return True if edge was added successfully. False if edge contains nodes that have not been * added to the viewer. */ public boolean addEdge(E edge) { Particle p1 = nodes.get(edge.getNode1()); if (p1 == null) { System.err.println("Warning: Node1 not found when creating edge."); return false; } Particle p2 = nodes.get(edge.getNode2()); if (p2 == null) { System.err.println("Warning: Node2 not found when creating edge."); return false; } // Only add edge if it does not already exist in the collection if (!edges.containsKey(edge)) { float x1 = p1.position().x(); float y1 = p1.position().y(); float x2 = p2.position().x(); float y2 = p2.position().y(); // Strength, damping, reset length edges.put( edge, physics.makeSpring( p1, p2, EDGE_STRENGTH, DAMPING, (float) Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)))); } return true; }
/** * Check an object with points can be reconstruct from an XML correctly. * * @since v2.5.0 - ylar - Creation */ @Test public void testCompleteGraphic() throws Exception { InputStream xml = getClass().getResourceAsStream(getXmlFilePathCase1()); assertThat(xml).isNotNull(); E result = deserialize(xml, getGraphicClass()); E expected = getExpectedDeserializeCompleteGraphicCopy(); assertThat(result).isNotNull(); assertThat(expected).isNotNull(); assertThat(result.getUuid()).isNotEmpty().isEqualTo(expected.getUuid()); checkGraphicInterfaceFields(result, expected); if (result instanceof DragGraphic) { checkDragGraphicInterface((DragGraphic) result, (DragGraphic) expected); } if (result instanceof GraphicArea) { checkDragGraphicAreaInterface((GraphicArea) result, (GraphicArea) expected); } // Additional tests additionalTestsForDeserializeCompleteGraphic(result, expected); }
public String toString2() { StringBuffer sb = new StringBuffer(); for (E e : this) { sb.append(e.toString() + "\n"); } return sb.toString(); }
protected void checkDeserialization() throws Exception { deserializedGraphic = deserialize(serializationGraphic, getGraphicClass()); assertThat(deserializedGraphic) .isInstanceOfAny(Graphic.class, AbstractGraphic.class, getGraphicClass()); assertThat(deserializedGraphic.getUuid()).isEqualTo(graphic.getUuid()); assertThat(deserializedGraphic).isEqualToComparingFieldByFieldRecursively(graphic); }
/** * @see * edu.buffalo.cse.green.RefactorHandler#handleMove(edu.buffalo.cse.green.editor.model.RootModel, * org.eclipse.jdt.core.IJavaElement, org.eclipse.jdt.core.IJavaElement) */ public void handleMove(RootModel root, E sourceElement, E targetElement) { // get all types represented in the diagram String scuId = sourceElement.getHandleIdentifier(); String tcuId = targetElement.getHandleIdentifier(); String scuName = scuId.substring(scuId.indexOf('{') + 1, scuId.indexOf(".java")); String tcuName = tcuId.substring(tcuId.indexOf('{') + 1, tcuId.indexOf(".java")); List<IJavaElement> cuTypes = root.getElementsOfKind(TYPE); // see if any types belong to the compilation unit // that is undergoing the move event for (IJavaElement oType : cuTypes) { if (JavaModelListener.sameElements(sourceElement, oType.getAncestor(COMPILATION_UNIT))) { String oId = oType.getHandleIdentifier(); String oName = oId.substring(oId.indexOf('[')); oName = oName.replaceAll("\\[" + scuName, "[" + tcuName); IJavaElement nType = JavaCore.create(tcuId + oName); TypeModel oModel = (TypeModel) root.getModelFromElement(oType); TypeModel nModel = root.createTypeModel((IType) nType); if (oModel != null) { // TODO We tried to catch a ResourceException, // but it is caught in MemberModel oModel.removeFromParent(); nModel.setLocation(oModel.getLocation()); nModel.setSize(oModel.getSize()); } } } }
private E findStartingNodeForDeletion(E element) { if (root == null) return null; TreeNode<E> parent = null; TreeNode<E> current = root; while (current != null) { if (element.compareTo(current.element) < 0) { parent = current; current = current.left; } else if (element.compareTo(current.element) > 0) { parent = current; current = current.right; } else break; } if (current == null) return null; if (current.left == null) { if (parent == null) { return null; } else { return parent.element; } } else { TreeNode<E> parentOfRightMost = current; TreeNode<E> rightMost = current.left; while (rightMost.right != null) { parentOfRightMost = rightMost; rightMost = rightMost.right; } return parentOfRightMost.element; } }