Java Code Examples for java.util.Vector.remove()

The following are Jave code examples for showing how to use remove() of the java.util.Vector 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: AgentWorkbench   File: TableModel.java   View Source Code Vote up 7 votes
/**
 * Converts the table data to a Vector of Object Vectors
 * @param addHeaders If true, an additional vector containing the column headers will be added
 * @param isTimeSeriesData If true, the first column is interpreted as timestamps and converted to a time format
 * @return The table data as a Vector of Object Vectors
 */
public Vector<Vector<Object>> getTableDataAsObjectVector(boolean addHeaders, boolean isTimeSeriesData){
	Vector<Vector<Object>> dataVector = new Vector<Vector<Object>>();
	
	DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
	
	if(addHeaders == true){
		dataVector.addElement(new Vector<Object>(Arrays.asList(columnTitles.toArray())));
	}
	
	
	Collection<Vector<Number>> treeMapData = this.getTableModelDataVector().getKeyRowVectorTreeMap().values();
	for(Vector<Number> numberVector : treeMapData){
		Vector<Object> objectVector = new Vector<Object>(Arrays.asList(numberVector.toArray()));
		
		if(isTimeSeriesData == true){
			long timestamp = (long) objectVector.get(0);
			String dateTime = dateFormat.format(new Date(timestamp));
			objectVector.remove(0);
			objectVector.insertElementAt(dateTime, 0);
		}
		
		dataVector.addElement(objectVector);
	}
	return dataVector;
}
 
Example 2
Project: jdk8u-jdk   File: SystemTray.java   View Source Code Vote up 7 votes
/**
 * Removes the specified <code>TrayIcon</code> from the
 * <code>SystemTray</code>.
 *
 * <p> All icons added by the application are automatically
 * removed from the <code>SystemTray</code> upon application exit
 * and also when the desktop system tray becomes unavailable.
 *
 * <p> If <code>trayIcon</code> is <code>null</code> or was not
 * added to the system tray, no exception is thrown and no action
 * is performed.
 *
 * @param trayIcon the <code>TrayIcon</code> to be removed
 * @see #add(TrayIcon)
 * @see TrayIcon
 */
public void remove(TrayIcon trayIcon) {
    if (trayIcon == null) {
        return;
    }
    TrayIcon[] oldArray = null, newArray = null;
    synchronized (this) {
        oldArray = systemTray.getTrayIcons();
        Vector<TrayIcon> icons = (Vector<TrayIcon>)AppContext.getAppContext().get(TrayIcon.class);
        // TrayIcon with no peer is not contained in the array.
        if (icons == null || !icons.remove(trayIcon)) {
            return;
        }
        trayIcon.removeNotify();
        newArray = systemTray.getTrayIcons();
    }
    firePropertyChange("trayIcons", oldArray, newArray);
}
 
Example 3
Project: Java-Air-Reservation   File: ChooseSeat.java   View Source Code Vote up 7 votes
private void loadSeats(){
    try {
        Flight f = new Flight(fl.getFlight_no());
        Tickets tk = new Tickets();
        ResultSet rs = tk.getforleg(fl.getLeg_no());
        Vector tickets =  new Vector();
        for(int i=1; i<f.getMax_seats();i++){
            tickets.addElement(i);
        }
        while(rs.next()){
            tickets.remove(rs.getInt("seat_no"));
        }
        jComboBox1.removeAllItems();
        for(Object s : tickets){
            jComboBox1.addItem(s.toString());
        }
    } catch (SQLException ex) {
        Logger.getLogger(ChooseSeat.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 4
Project: OpenJSharp   File: SystemTray.java   View Source Code Vote up 7 votes
/**
 * Removes the specified <code>TrayIcon</code> from the
 * <code>SystemTray</code>.
 *
 * <p> All icons added by the application are automatically
 * removed from the <code>SystemTray</code> upon application exit
 * and also when the desktop system tray becomes unavailable.
 *
 * <p> If <code>trayIcon</code> is <code>null</code> or was not
 * added to the system tray, no exception is thrown and no action
 * is performed.
 *
 * @param trayIcon the <code>TrayIcon</code> to be removed
 * @see #add(TrayIcon)
 * @see TrayIcon
 */
public void remove(TrayIcon trayIcon) {
    if (trayIcon == null) {
        return;
    }
    TrayIcon[] oldArray = null, newArray = null;
    synchronized (this) {
        oldArray = systemTray.getTrayIcons();
        Vector<TrayIcon> icons = (Vector<TrayIcon>)AppContext.getAppContext().get(TrayIcon.class);
        // TrayIcon with no peer is not contained in the array.
        if (icons == null || !icons.remove(trayIcon)) {
            return;
        }
        trayIcon.removeNotify();
        newArray = systemTray.getTrayIcons();
    }
    firePropertyChange("trayIcons", oldArray, newArray);
}
 
Example 5
Project: ramus   File: AbstractSector.java   View Source Code Vote up 7 votes
/**
 * Метод повертає набір під’єднаних секторв, які мають зв’язок з потоком.
 *
 * @param point
 * @param v
 */

protected void getStreamedSectors(final Crosspoint point,
                                  final Vector<Sector> v) {
    if (point == null)
        return;
    final int oLen = v.size();
    point.getSectors(v);
    final int len = v.size();
    final Vector<Sector> r = new Vector<Sector>();
    for (int i = oLen; i < len; i++)
        if (!v.get(i).getFunction().equals(getFunction())
                || v.get(i).getStream() == null
                || !v.get(i).getStream().equals(getStream()))
            r.add(v.get(i));
    for (int i = 0; i < r.size(); i++)
        v.remove(r.get(i));
}
 
Example 6
Project: QN-ACTR-Release   File: PopulationMixParametricAnalysis.java   View Source Code Vote up 7 votes
/**
 * Sets the value for the specified property
 *
 * @param propertyName the name of the property to be set. The supported properties are: <br>
 * - FROM_PROPERTY  <br>
 * - TO_PROPERTY  <br>
 * - STEPS_PROPERTY <br>
 * - REFERENCE_CLASS_PROPERTY
 * @param value the value to be set
 */
@Override
public void setProperty(String propertyName, String value) {
	if (propertyName.equals(FROM_PROPERTY)) {
		initialValue = Double.parseDouble(value);
	} else if (propertyName.equals(TO_PROPERTY)) {
		finalValue = Double.parseDouble(value);
	} else if (propertyName.equals(STEPS_PROPERTY)) {
		numberOfSteps = Integer.parseInt(value);
		if (numberOfSteps > MAX_STEP_NUMBER) {
			numberOfSteps = MAX_STEP_NUMBER;
		}
	} else if (propertyName.equals(REFERENCE_CLASS_PROPERTY)) {
		classKey = classDef.getClassByName(value);
		Vector temp = classDef.getClosedClassKeys();
		temp.remove(classKey);
		otherClassKey = temp.get(0);
	}
}
 
Example 7
Project: SuperMarketManageSystem   File: XiaoShouPaiHang.java   View Source Code Vote up 7 votes
private void updateTable(Iterator iterator) {
	int rowCount = dftm.getRowCount();
	for (int i = 0; i < rowCount; i++) {
		dftm.removeRow(0);
	}
	while (iterator.hasNext()) {
		Vector vector = new Vector();
		List view = (List) iterator.next();
		Vector row=new Vector(view);
		int rowSize = row.size();
		for(int i=rowSize-2;i<rowSize;i++){
			Object colValue = row.get(i);
			row.remove(i);
			row.insertElementAt(colValue, 2);
		}
		vector.addAll(row);
		dftm.addRow(vector);
	}
}
 
Example 8
Project: QN-ACTR-Release   File: EngineConvex2D.java   View Source Code Vote up 7 votes
/**
 * This function return a vector that contains the same point of the parameter one but
 * the points are orderet from the point whith the biggest X to the point whith the smallest X
 * @param v The vector to order
 * @return The vector ordered
 */
private Vector<Point2D> orderByX(Vector<Point2D> v) {
	Vector<Point2D> r = (Vector<Point2D>) v.clone();
	boolean again = true;

	while (again) {
		again = false;
		for (int k = 0; k < r.size() - 1; k++) {
			//Take the points
			Point2D p1 = r.get(k);
			Point2D p2 = r.get(k + 1);

			if (p1.getX() < p2.getX()) {
				//swap
				r.remove(k);
				r.insertElementAt(p2, k);
				r.remove(k + 1);
				r.insertElementAt(p1, k + 1);
				again = true;
			}
		}
	}
	return r;
}
 
Example 9
Project: tap17-muggl-javaee   File: AndConstraint.java   View Source Code Vote up 7 votes
@Override
   public String toTexString(){
StringBuffer sb = new StringBuffer();
sb.append("(");
Vector<ComposedConstraint> alternatives = new Vector<ComposedConstraint>();
alternatives.add(left);
alternatives.add(right);
for (int i = 0; i < alternatives.size(); i++){
    ComposedConstraint constraint = alternatives.get(i);
    if (constraint instanceof AndConstraint){
	alternatives.remove(i);
	alternatives.add(i, ((AndConstraint)constraint).right);
	alternatives.add(i, ((AndConstraint)constraint).left);
	i--;
    } else {
	if (i > 0)
	    sb.append("\\wedge ");
	sb.append(constraint.toTexString());
    }
}
sb.append(")");
return sb.toString();
   }
 
Example 10
Project: tap17-muggl-javaee   File: OrConstraint.java   View Source Code Vote up 7 votes
@Override
   public String toTexString(){
StringBuffer sb = new StringBuffer();
sb.append("(");
Vector<ComposedConstraint> alternatives = new Vector<ComposedConstraint>();
alternatives.add(left);
alternatives.add(right);
for (int i = 0; i < alternatives.size(); i++){
    ComposedConstraint constraint = alternatives.get(i);
    if (constraint instanceof OrConstraint){
	alternatives.remove(i);
	alternatives.add(i, ((OrConstraint)constraint).right);
	alternatives.add(i, ((OrConstraint)constraint).left);
	i--;
    } else {
	if (i > 0)
	    sb.append("\\vee ");
	sb.append(constraint.toTexString());
    }
}
sb.append(")");
return sb.toString();
   }
 
Example 11
Project: AgentWorkbench   File: PredictiveStaticLoadBalancing.java   View Source Code Vote up 6 votes
/**
 * Sort agent class metric description vector descending.
 *
 * @param acmdv the agent class metric description vector
 * @return the sorted (descending) agent class metric description vector
 */
private Vector<AgentClassMetricDescription> sortAgentClassMetricDescriptionVectorDescending(Vector<AgentClassMetricDescription> acmdv){
	Vector<AgentClassMetricDescription> sortedAcmdv = new Vector<AgentClassMetricDescription>();
	
	//copy
	for(int i = 0; i < acmdv.size(); i++){
		sortedAcmdv.add(acmdv.get(i));;
	}
	
	for(int indexA = 0; indexA < sortedAcmdv.size()-1; indexA++){
		for(int indexB = 1; indexB < sortedAcmdv.size()-indexA; indexB++){
			double metricA = 0;
			double metricB = 0;
			
			if(currProject.getAgentClassLoadMetrics().isUseRealLoadMetric() == true){
				metricA = sortedAcmdv.get(indexB-1).getRealMetric();
				metricB = sortedAcmdv.get(indexB).getRealMetric();
			}else{
				metricA = sortedAcmdv.get(indexB-1).getUserPredictedMetric();
				metricB = sortedAcmdv.get(indexB).getUserPredictedMetric();	
			}
			//compare and reorder
			if(metricA < metricB){
				AgentClassMetricDescription acmdvTemp = sortedAcmdv.get(indexB-1);
				sortedAcmdv.remove(indexB-1);
				sortedAcmdv.add(indexB, acmdvTemp);	
			}
		}
	}
	return sortedAcmdv;	
}
 
Example 12
Project: AgentWorkbench   File: CsvDataController.java   View Source Code Vote up 6 votes
/**
 * This method imports data from a CSV file
 */
public void doImport(){

	if (this.getFile()==null) {
		System.err.println("No CSV file specified for import!");
	}else{
		CsvFileReader fileReader = new CsvFileReader(this.separator);
		Vector<Vector<Object>> importedData = fileReader.importData(this.file);
		if(importedData != null){
			Vector<Object> headlines;
			if(this.hasHeadlines()){
				headlines = importedData.get(0);
				importedData.remove(0);
			}else{
				headlines = new Vector<Object>();
				int columnCount = importedData.get(0).size();
				for(int i=0; i<columnCount; i++){
					headlines.addElement("Column "+(i+1));
				}
			}
			
			DefaultTableModel tableModel = new DefaultTableModel();
			tableModel.setDataVector(importedData, headlines);
			this.setTableModel(tableModel);
		}
	}
}
 
Example 13
Project: rapidminer   File: BayBoostStream.java   View Source Code Vote up 6 votes
/**
 * This helper method takes as input the traing set and the set of models trained so far. It
 * re-estimates the model weights one by one, which means that it changes the contents of the
 * modelInfo container. Works with crisp base classifiers, only!
 *
 * @param exampleSet
 *            the training set to be used to tune the weights
 * @param modelInfo
 *            the <code>Vector</code> of <code>Model</code>s, each with its biasMatrix
 * @return <code>true</code> iff the <code>ExampleSet</code> contains at least one example that
 *         is not yet explained deterministically (otherwise: nothing left to learn)
 */
private boolean adjustBaseModelWeights(ExampleSet exampleSet, Vector<BayBoostBaseModelInfo> modelInfo)
		throws OperatorException {

	for (int j = 0; j < modelInfo.size(); j++) {
		BayBoostBaseModelInfo consideredModelInfo = modelInfo.get(j);
		Model consideredModel = consideredModelInfo.getModel();
		ContingencyMatrix cm = consideredModelInfo.getContingencyMatrix();
		// double[][] oldBiasMatrix = (double[][]) consideredModelInfo[1];

		BayBoostStream.createOrReplacePredictedLabelFor(exampleSet, consideredModel);
		exampleSet = consideredModel.apply(exampleSet);
		if (exampleSet.getAttributes().getPredictedLabel().isNominal() == false) {
			// Only the case of nominal base classifiers is supported!
			throw new UserError(this, 101, new Object[] { exampleSet.getAttributes().getLabel(),
			"BayBoostStream base learners" });
		}

		WeightedPerformanceMeasures wp = new WeightedPerformanceMeasures(exampleSet);
		ContingencyMatrix cmNew = wp.getContingencyMatrix();
		// double[][] newBiasMatrix = wp.createLiftRatioMatrix();
		if (isModelUseful(cm) == false) {
			modelInfo.remove(j);
			j--;
			log("Discard base model because of low advantage.");
		} else {
			consideredModelInfo = new BayBoostBaseModelInfo(consideredModel, cmNew);
			modelInfo.set(j, consideredModelInfo);

			boolean stillUncoveredExamples = WeightedPerformanceMeasures.reweightExamples(exampleSet, cmNew, false) > 0;
			if (stillUncoveredExamples == false) {
				return false;
			}
		}
	}
	return true;
}
 
Example 14
Project: geomapapp   File: DBTableConfigDialog.java   View Source Code Vote up 6 votes
public void initVectors(){
	hiddenV = new Vector<String>();
	visibleV = new Vector<String>();
	Vector<String> v = (Vector<String>) ds.header.clone();
	for (int i = 0; i < ds.tm.indexH.size(); i++){
		visibleV.add(ds.header.get(ds.tm.indexH.get(i)));
		v.remove(visibleV.get(visibleV.size()-1));
	}
	v.trimToSize();
	for (int i =0; i < v.size(); i++)
		hiddenV.add(v.get(i));
}
 
Example 15
Project: AgentWorkbench   File: DynFormBase.java   View Source Code Vote up 5 votes
/**
 * For a 'multiple' cardinality of a slot, the needed nodes will be created.
 *
 * @param currNode the curr node
 * @param nodesNeeded the nodes needed
 * @return the multiple nodes as needed
 */
private Vector<DefaultMutableTreeNode> getMultipleNodesAsNeeded(DefaultMutableTreeNode currNode, int nodesNeeded) {
	
	// --- Get the Vector of all currently available nodes of this kind -------------
	Vector<DefaultMutableTreeNode> nodesAvailableVector = this.getMultipleNodesAvailable(currNode);
	int nodesAvailableCounter = nodesAvailableVector.size();
	
	// --- Get the kind of the DynTyp-object ----------------------------------------
	DynType dt = (DynType) currNode.getUserObject();
	String typeName = dt.getTypeName();
	boolean isInnerClass = false;
	
	if (typeName.equals(DynType.typeClass) || typeName.equals(DynType.typeInnerClassType)) {
		isInnerClass = true;
	} else if (typeName.equals(DynType.typeRawType)) {
		isInnerClass = false;
	} else if (typeName.equals(DynType.typeCyclic)) {
		return nodesAvailableVector;
	}
	
	// --- If the number of nodes is different to the 'numberOfSlotsNeeded' ---------  
	if (nodesAvailableCounter<nodesNeeded) {
		// --- Consider the number of nodes found is smaller than needed -------
		Vector<DefaultMutableTreeNode> nodesNew = new Vector<DefaultMutableTreeNode>();
		while (nodesAvailableVector.size()+nodesNew.size()<nodesNeeded) {
			DefaultMutableTreeNode newNode = this.addSingleMultipleNode(currNode, isInnerClass);
			nodesNew.add(newNode);
		}
		Collections.reverse(nodesNew);
		nodesAvailableVector.addAll(nodesNew);
		
	} else if (nodesAvailableCounter>nodesNeeded) {
		// --- Consider the number of nodes found is greater than needed -------
		while (nodesAvailableVector.size()>nodesNeeded && nodesAvailableVector.size()>1) {
			DefaultMutableTreeNode delNode = nodesAvailableVector.get(nodesAvailableVector.size()-1);
			this.removeMultiple(delNode);
			nodesAvailableVector.remove(nodesAvailableVector.size()-1);
		}
	}
	return nodesAvailableVector;
}
 
Example 16
Project: openjdk-jdk10   File: Whitespace.java   View Source Code Vote up 5 votes
/**
 * Orders a set or rules by priority, removes redundant rules and rules
 * that are shadowed by stronger, contradicting rules.
 */
private static int prioritizeRules(Vector rules) {
    WhitespaceRule currentRule;
    int defaultAction = PRESERVE_SPACE;

    // Sort all rules with regard to priority
    quicksort(rules, 0, rules.size()-1);

    // Check if there are any "xsl:strip-space" elements at all.
    // If there are no xsl:strip elements we can ignore all xsl:preserve
    // elements and signal that all whitespaces should be preserved
    boolean strip = false;
    for (int i = 0; i < rules.size(); i++) {
        currentRule = (WhitespaceRule)rules.elementAt(i);
        if (currentRule.getAction() == STRIP_SPACE) {
            strip = true;
        }
    }
    // Return with default action: PRESERVE_SPACE
    if (!strip) {
        rules.removeAllElements();
        return PRESERVE_SPACE;
    }

    // Remove all rules that are contradicted by rules with higher priority
    for (int idx = 0; idx < rules.size(); ) {
        currentRule = (WhitespaceRule)rules.elementAt(idx);

        // Remove this single rule if it has no purpose
        if (findContradictingRule(rules,currentRule) != null) {
            rules.remove(idx);
        }
        else {
            // Remove all following rules if this one overrides all
            if (currentRule.getStrength() == RULE_ALL) {
                defaultAction = currentRule.getAction();
                for (int i = idx; i < rules.size(); i++) {
                    rules.removeElementAt(i);
                }
            }
            // Skip to next rule (there might not be any)...
            idx++;
        }
    }

    // The rules vector could be empty if first rule has strength RULE_ALL
    if (rules.size() == 0) {
        return defaultAction;
    }

    // Now work backwards and strip away all rules that have the same
    // action as the default rule (no reason the check them at the end).
    do {
        currentRule = (WhitespaceRule)rules.lastElement();
        if (currentRule.getAction() == defaultAction) {
            rules.removeElementAt(rules.size() - 1);
        }
        else {
            break;
        }
    } while (rules.size() > 0);

    // Signal that whitespace detection predicate must be used.
    return defaultAction;
}
 
Example 17
Project: jdk8u-jdk   File: SetOfIntegerSyntax.java   View Source Code Vote up 5 votes
/**
 * Accumulate the given range (lb .. ub) into the canonical array form
 * into the given vector of int[] objects.
 */
private static void accumulate(Vector ranges, int lb,int ub) {
    // Make sure range is non-null.
    if (lb <= ub) {
        // Stick range at the back of the vector.
        ranges.add(new int[] {lb, ub});

        // Work towards the front of the vector to integrate the new range
        // with the existing ranges.
        for (int j = ranges.size()-2; j >= 0; -- j) {
        // Get lower and upper bounds of the two ranges being compared.
            int[] rangea = (int[]) ranges.elementAt (j);
            int lba = rangea[0];
            int uba = rangea[1];
            int[] rangeb = (int[]) ranges.elementAt (j+1);
            int lbb = rangeb[0];
            int ubb = rangeb[1];

            /* If the two ranges overlap or are adjacent, coalesce them.
             * The two ranges overlap if the larger lower bound is less
             * than or equal to the smaller upper bound. The two ranges
             * are adjacent if the larger lower bound is one greater
             * than the smaller upper bound.
             */
            if (Math.max(lba, lbb) - Math.min(uba, ubb) <= 1) {
                // The coalesced range is from the smaller lower bound to
                // the larger upper bound.
                ranges.setElementAt(new int[]
                                       {Math.min(lba, lbb),
                                            Math.max(uba, ubb)}, j);
                ranges.remove (j+1);
            } else if (lba > lbb) {

                /* If the two ranges don't overlap and aren't adjacent but
                 * are out of order, swap them.
                 */
                ranges.setElementAt (rangeb, j);
                ranges.setElementAt (rangea, j+1);
            } else {
            /* If the two ranges don't overlap and aren't adjacent and
             * aren't out of order, we're done early.
             */
                break;
            }
        }
    }
}
 
Example 18
Project: OpenJSharp   File: XWindowPeer.java   View Source Code Vote up 5 votes
static Vector<XWindowPeer> collectJavaToplevels() {
    Vector<XWindowPeer> javaToplevels = new Vector<XWindowPeer>();
    Vector<Long> v = new Vector<Long>();
    X11GraphicsEnvironment ge =
        (X11GraphicsEnvironment)GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] gds = ge.getScreenDevices();
    if (!ge.runningXinerama() && (gds.length > 1)) {
        for (GraphicsDevice gd : gds) {
            int screen = ((X11GraphicsDevice)gd).getScreen();
            long rootWindow = XlibWrapper.RootWindow(XToolkit.getDisplay(), screen);
            v.add(rootWindow);
        }
    } else {
        v.add(XToolkit.getDefaultRootWindow());
    }
    final int windowsCount = windows.size();
    while ((v.size() > 0) && (javaToplevels.size() < windowsCount)) {
        long win = v.remove(0);
        XQueryTree qt = new XQueryTree(win);
        try {
            if (qt.execute() != 0) {
                int nchildren = qt.get_nchildren();
                long children = qt.get_children();
                // XQueryTree returns window children ordered by z-order
                for (int i = 0; i < nchildren; i++) {
                    long child = Native.getWindow(children, i);
                    XBaseWindow childWindow = XToolkit.windowToXWindow(child);
                    // filter out Java non-toplevels
                    if ((childWindow != null) && !(childWindow instanceof XWindowPeer)) {
                        continue;
                    } else {
                        v.add(child);
                    }
                    if (childWindow instanceof XWindowPeer) {
                        XWindowPeer np = (XWindowPeer)childWindow;
                        javaToplevels.add(np);
                        // XQueryTree returns windows sorted by their z-order. However,
                        // if WM has not handled transient for hint for a child window,
                        // it may appear in javaToplevels before its owner. Move such
                        // children after their owners.
                        int k = 0;
                        XWindowPeer toCheck = javaToplevels.get(k);
                        while (toCheck != np) {
                            XWindowPeer toCheckOwnerPeer = toCheck.getOwnerPeer();
                            if (toCheckOwnerPeer == np) {
                                javaToplevels.remove(k);
                                javaToplevels.add(toCheck);
                            } else {
                                k++;
                            }
                            toCheck = javaToplevels.get(k);
                        }
                    }
                }
            }
        } finally {
            qt.dispose();
        }
    }
    return javaToplevels;
}
 
Example 19
Project: openjdk-jdk10   File: SetOfIntegerSyntax.java   View Source Code Vote up 5 votes
/**
 * Accumulate the given range (lb .. ub) into the canonical array form into
 * the given vector of int[] objects.
 */
private static void accumulate(Vector<int[]> ranges, int lb,int ub) {
    // Make sure range is non-null.
    if (lb <= ub) {
        // Stick range at the back of the vector.
        ranges.add(new int[] {lb, ub});

        // Work towards the front of the vector to integrate the new range
        // with the existing ranges.
        for (int j = ranges.size()-2; j >= 0; -- j) {
        // Get lower and upper bounds of the two ranges being compared.
            int[] rangea = ranges.elementAt (j);
            int lba = rangea[0];
            int uba = rangea[1];
            int[] rangeb = ranges.elementAt (j+1);
            int lbb = rangeb[0];
            int ubb = rangeb[1];
            /*
             * If the two ranges overlap or are adjacent, coalesce them. The
             * two ranges overlap if the larger lower bound is less than or
             * equal to the smaller upper bound. The two ranges are adjacent
             * if the larger lower bound is one greater than the smaller
             * upper bound.
             */
            if (Math.max(lba, lbb) - Math.min(uba, ubb) <= 1) {
                // The coalesced range is from the smaller lower bound to
                // the larger upper bound.
                ranges.setElementAt(new int[]
                                       {Math.min(lba, lbb),
                                            Math.max(uba, ubb)}, j);
                ranges.remove (j+1);
            } else if (lba > lbb) {

                /* If the two ranges don't overlap and aren't adjacent but
                 * are out of order, swap them.
                 */
                ranges.setElementAt (rangeb, j);
                ranges.setElementAt (rangea, j+1);
            } else {
                /*
                 * If the two ranges don't overlap and aren't adjacent and
                 * aren't out of order, we're done early.
                 */
                break;
            }
        }
    }
}
 
Example 20
Project: crush   File: APEXCamera.java   View Source Code Vote up 5 votes
@Override
public void validate(Vector<Scan<?,?>> scans) throws Exception {
	
	final APEXScan<?,?> firstScan = (APEXScan<?,?>) scans.get(0);
	final APEXSubscan<?,?> firstSubscan = firstScan.get(0);
	final EquatorialCoordinates reference = firstScan.equatorial;
	final String sourceName = firstScan.getSourceName();
	
	final double pointingTolerance = getPointSize() / 5.0;
	
	final boolean isChopped = firstSubscan.getChopper() != null;
	

	if(isChopped) {
		info("Chopped photometry reduction mode.");
		info("Target is [" + sourceName + "] at " + reference.toString());
		setOption("chopped");
	}
	else if(sourceName.equalsIgnoreCase("SKYDIP")) {
		info("Skydip reduction mode.");
		setOption("skydip");
		
		if(scans.size() > 1) {
			info("Ignoring all but first scan in list (for skydip).");
			scans.clear();
			scans.add(firstScan);
		}
	}
	
	if(firstScan.type.equalsIgnoreCase("POINT")) if(scans.size() == 1) {
		setPointing(firstScan);
	}
	
	if(hasOption("nochecks")) return;
	
	// Make sure the rest of the list conform to the first scan...
	for(int i=scans.size(); --i > 0; ) {
		APEXScan<?,?> scan = (APEXScan<?,?>) scans.get(i);
		APEXSubscan<?,?> subscan = scan.get(0);
		
		// Throw out any subsequent skydips...
		if(scan.getSourceName().equalsIgnoreCase("SKYDIP")) {
		    warning("Scan " + scan.getID() + " is a skydip. Dropping from dataset.");
			scans.remove(i);
		}
		
		boolean subscanChopped = subscan.getChopper() != null;
		
		if(subscanChopped != isChopped) {	
			if(isChopped) warning("Scan " + scan.getID() + " is not a chopped scan. Dropping from dataset.");
			else warning("Scan " + scan.getID() + " is a chopped scan. Dropping from dataset.");
			scans.remove(i);
			continue;
		}
		
		if(isChopped) {
			if(!scan.isNonSidereal) {
				if(scan.equatorial.distanceTo(reference) > pointingTolerance) {
					warning("Scan " + scan.getID() + " observed at a different position. Dropping from dataset.");
					CRUSH.suggest(this, "           (You can use 'moving' to keep and reduce anyway.)");
					scans.remove(i);
				}
			}
			else if(!scan.getSourceName().equalsIgnoreCase(sourceName)) {
				warning("Scan " + scan.getID() + " is on a different object. Dropping from dataset.");
				scans.remove(i);
			}
		}
	}
	
	
	super.validate(scans);		
}