Esempio n. 1
1
  public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    StringTokenizer st;

    t = Integer.parseInt(br.readLine());
    while (t-- > 0) {
      st = new StringTokenizer(br.readLine());
      n = Integer.parseInt(st.nextToken());
      m = Integer.parseInt(st.nextToken());
      S = Integer.parseInt(st.nextToken());
      T = Integer.parseInt(st.nextToken());

      // build graph
      AdjList = new Vector<Vector<IntegerPair>>();
      for (i = 0; i < n; i++) AdjList.add(new Vector<IntegerPair>());

      while (m-- > 0) {
        st = new StringTokenizer(br.readLine());
        a = Integer.parseInt(st.nextToken());
        b = Integer.parseInt(st.nextToken());
        w = Integer.parseInt(st.nextToken());
        AdjList.get(a).add(new IntegerPair(b, w)); // bidirectional
        AdjList.get(b).add(new IntegerPair(a, w));
      }

      // SPFA from source S
      // initially, only S has dist = 0 and in the queue
      Vector<Integer> dist = new Vector<Integer>();
      for (i = 0; i < n; i++) dist.add(INF);
      dist.set(S, 0);
      Queue<Integer> q = new LinkedList<Integer>();
      q.offer(S);
      Vector<Boolean> in_queue = new Vector<Boolean>();
      for (i = 0; i < n; i++) in_queue.add(false);
      in_queue.set(S, true);

      while (!q.isEmpty()) {
        int u = q.peek();
        q.poll();
        in_queue.set(u, false);
        for (j = 0; j < AdjList.get(u).size(); j++) { // all outgoing edges from u
          int v = AdjList.get(u).get(j).first(), weight_u_v = AdjList.get(u).get(j).second();
          if (dist.get(u) + weight_u_v < dist.get(v)) { // if can relax
            dist.set(v, dist.get(u) + weight_u_v); // relax
            if (!in_queue.get(v)) { // add to the queue only if it's not in the queue
              q.offer(v);
              in_queue.set(v, true);
            }
          }
        }
      }

      pr.printf("Case #%d: ", caseNo++);
      if (dist.get(T) != INF) pr.printf("%d\n", dist.get(T));
      else pr.printf("unreachable\n");
    }

    pr.close();
  }
Esempio n. 2
1
  public ViewComponentInfo projectAbsoluteCoordinateRecursively(Integer ix, Integer iy) {
    // Miss
    if (!checkHit(ix, iy)) return null;

    if (this.viewType.endsWith("Spinner")) {
      this.isSpinner = true;
      return this;
    }

    // I'm hit and has child.
    if (this.children != null) {
      // Assumption : children never intersect

      ViewComponentInfo projected_child;

      if (this.isContainer || this.viewType.equals("android.widget.TabWidget")) {
        Vector<ViewComponentInfo> views = new Vector<ViewComponentInfo>();
        for (ViewComponentInfo child : children) {
          if (child.checkHit(ix, iy)) {
            child.isCollectionMember = true;
            views.add(child);
          }
        }
        if (views.size() == 1) {
          return views.firstElement();
        }
      }
      if (this.viewType.endsWith(("FrameLayout"))) {
        LinkedList<ViewComponentInfo> chlist = new LinkedList<ViewComponentInfo>(children);
        ViewComponentInfo child = getFrameContent(children);
        projected_child = child.projectAbsoluteCoordinateRecursively(ix, iy);
        if (projected_child != null) return projected_child;
      } else {
        Vector<ViewComponentInfo> views = new Vector<ViewComponentInfo>();
        for (ViewComponentInfo child : children) {
          projected_child = child.projectAbsoluteCoordinateRecursively(ix, iy);
          if (projected_child != null) views.add(projected_child);
        }
        if (views.size() == 1) {
          return views.firstElement();
        }
      }
    }

    // The point hit no child.
    // Thus return my self.
    if (this.viewType.endsWith("Layout")
        || this.viewType.endsWith("TextView")
        || this.viewType.endsWith("ScrollView")
        || this.viewType.endsWith("ViewStub")
        || this.viewType.endsWith("DialogTitle")
        || this.viewType.endsWith("ImageView")) {
      if (this.hasOnClickListener()) return this;
      else return null;
    }
    return this;
  }
Esempio n. 3
1
 /**
  * JobTracker.submitJob() kicks off a new job.
  *
  * <p>Create a 'JobInProgress' object, which contains both JobProfile and JobStatus. Those two
  * sub-objects are sometimes shipped outside of the JobTracker. But JobInProgress adds info that's
  * useful for the JobTracker alone.
  *
  * <p>We add the JIP to the jobInitQueue, which is processed asynchronously to handle
  * split-computation and build up the right TaskTracker/Block mapping.
  */
 public synchronized JobStatus submitJob(String jobFile) throws IOException {
   totalSubmissions++;
   JobInProgress job = new JobInProgress(jobFile, this, this.conf);
   synchronized (jobs) {
     synchronized (jobsByArrival) {
       synchronized (jobInitQueue) {
         jobs.put(job.getProfile().getJobId(), job);
         jobsByArrival.add(job);
         jobInitQueue.add(job);
         jobInitQueue.notifyAll();
       }
     }
   }
   return job.getStatus();
 }
Esempio n. 4
0
 /**
  * Gets the urlClassLoader that enables to access to the objects jar files.
  *
  * @return an URLClassLoader
  */
 public URLClassLoader getObjectsClassLoader() {
   if (objectsClassLoader == null) {
     try {
       if (isExecutionMode()) {
         URL[] listUrl = new URL[1];
         listUrl[0] = instance.getTangaraPath().toURI().toURL();
         objectsClassLoader = new URLClassLoader(listUrl);
       } else {
         File f = new File(instance.getTangaraPath().getParentFile(), "objects");
         File[] list = f.listFiles();
         Vector<URL> vector = new Vector<URL>();
         for (int i = 0; i < list.length; i++) {
           if (list[i].getName().endsWith(".jar")) vector.add(list[i].toURI().toURL());
         }
         File flib =
             new File(
                 instance.getTangaraPath().getParentFile().getAbsolutePath().replace("\\", "/")
                     + "/objects/lib");
         File[] listflib = flib.listFiles();
         for (int j = 0; j < listflib.length; j++) {
           if (listflib[j].getName().endsWith(".jar")) vector.add(listflib[j].toURI().toURL());
         }
         URL[] listUrl = new URL[vector.size()];
         for (int j = 0; j < vector.size(); j++) listUrl[j] = vector.get(j);
         objectsClassLoader = new URLClassLoader(listUrl);
       }
     } catch (Exception e1) {
       displayError("URL MAL FORMED " + e1);
       return null;
     }
   }
   return objectsClassLoader;
 }
 public void actionPerformed(ActionEvent evt) {
   // 删除原来的JTable(JTable使用scrollPane来包装)
   if (scrollPane != null) {
     jf.remove(scrollPane);
   }
   try (
   // 根据用户输入的SQL执行查询
   ResultSet rs = stmt.executeQuery(sqlField.getText())) {
     // 取出ResultSet的MetaData
     ResultSetMetaData rsmd = rs.getMetaData();
     Vector<String> columnNames = new Vector<>();
     Vector<Vector<String>> data = new Vector<>();
     // 把ResultSet的所有列名添加到Vector里
     for (int i = 0; i < rsmd.getColumnCount(); i++) {
       columnNames.add(rsmd.getColumnName(i + 1));
     }
     // 把ResultSet的所有记录添加到Vector里
     while (rs.next()) {
       Vector<String> v = new Vector<>();
       for (int i = 0; i < rsmd.getColumnCount(); i++) {
         v.add(rs.getString(i + 1));
       }
       data.add(v);
     }
     // 创建新的JTable
     JTable table = new JTable(data, columnNames);
     scrollPane = new JScrollPane(table);
     // 添加新的Table
     jf.add(scrollPane);
     // 更新主窗口
     jf.validate();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Esempio n. 6
0
  /** Create directory entries for every item */
  boolean mkdirs(String src) {
    src = normalizePath(new UTF8(src));

    // Use this to collect all the dirs we need to construct
    Vector v = new Vector();

    // The dir itself
    v.add(src);

    // All its parents
    String parent = DFSFile.getDFSParent(src);
    while (parent != null) {
      v.add(parent);
      parent = DFSFile.getDFSParent(parent);
    }

    // Now go backwards through list of dirs, creating along
    // the way
    boolean lastSuccess = false;
    int numElts = v.size();
    for (int i = numElts - 1; i >= 0; i--) {
      String cur = (String) v.elementAt(i);
      INode inserted = unprotectedMkdir(cur);
      if (inserted != null) {
        logEdit(OP_MKDIR, new UTF8(inserted.computeName()), null);
        lastSuccess = true;
      } else {
        lastSuccess = false;
      }
    }
    return lastSuccess;
  }
Esempio n. 7
0
  /**
   * Helper method to generate the signatures for binding the factory. Must account for the
   * inheritance relationships for any arguments that are classes. Ths, each argument can
   * potentially result in a range of values for type, and we have to handle the cross product of
   * all of these.
   */
  private static Vector makeFactoryNames(IXMLElement constructor) {
    String factoryName = XMLUtil.nameOf(constructor.getParent());
    Vector allPermutations = new Vector();
    for (Enumeration e = constructor.enumerateChildren(); e.hasMoreElements(); ) {
      IXMLElement element = (IXMLElement) e.nextElement();

      if (!element.getName().equals("arg")) {
        break;
      }

      String argType = XMLUtil.typeOf(element);
      Vector argTypeAlternates = new Vector();
      argTypeAlternates.add(argType);

      if (ModelAccessor.isClass(argType)) {
        List ancestors = ModelAccessor.getAncestors(argType);
        if (ancestors != null) argTypeAlternates.addAll(ancestors);
      }

      allPermutations.add(argTypeAlternates);
    }

    // Generate all the signatures
    Vector factoryNames = new Vector();
    makeFactoryNames(factoryName, allPermutations, 0, factoryNames);
    return factoryNames;
  }
Esempio n. 8
0
 private Vector readlinesfromfile(String fname) { // trims lines and removes comments
   Vector v = new Vector();
   try {
     BufferedReader br = new BufferedReader(new FileReader(new File(fname)));
     while (br.ready()) {
       String tmp = br.readLine();
       // Strip comments
       while (tmp.indexOf("/*") >= 0) {
         int i = tmp.indexOf("/*");
         v.add(tmp.substring(0, i));
         String rest = tmp.substring(i + 2);
         while (tmp.indexOf("*/") == -1) {
           tmp = br.readLine();
         }
         tmp = tmp.substring(tmp.indexOf("*/") + 2);
       }
       if (tmp.indexOf("//") >= 0) tmp = tmp.substring(0, tmp.indexOf("//"));
       // Strip spaces
       tmp = tmp.trim();
       v.add(tmp);
       //        System.out.println("Read line "+tmp);
     }
     br.close();
   } catch (Exception e) {
     System.out.println("Exception " + e + " occured");
   }
   return v;
 }
Esempio n. 9
0
 protected void validateColumn(int rowNo, int colNo, Vector v, DBConnection conn) {
   if (rowNo < 0 || rowNo > getRowCount() || colNo < 0 || colNo > getColumnCount()) return;
   DSColumnDescriptor col = _desc.getColumn(colNo);
   boolean remoteRules = false;
   for (int i = 0; i < col.getRuleCount(); i++) {
     try {
       ValidationRule r = col.getRule(i);
       if (r.getRuleType() == ValidationRule.TYPE_REMOTE) remoteRules = true;
       else r.evaluateRule(this, rowNo, colNo, conn);
     } catch (DataStoreException ex) {
       ex.setRowNo(rowNo);
       try {
         ex.setColumn(getColumnName(colNo));
       } catch (DataStoreException e) {
       }
       ;
       v.add(ex);
     }
   }
   if (remoteRules) {
     try {
       DataStoreRow r = getDataStoreRow(rowNo, BUFFER_STANDARD);
       r.getDSDataRow().setProxyRow(rowNo);
       DataStoreException ex[] = getDataSourceProxy().validateRemoteRules(this, r, rowNo, colNo);
       for (int i = 0; i < ex.length; i++) v.add(ex[i]);
     } catch (DataStoreException dex) {
     }
   }
 }
Esempio n. 10
0
  /**
   * Query a quiz list from the database. If there is no student user name specified, the list will
   * contain all quizzes that are used in the instructor's courses. Otherwise, the list will contain
   * all quizzes that the student has taken and from the instructor's courses which the student is
   * registered. Throws InvalidDBRequestException if any error occured to the database connection.
   *
   * @param instructor instructor's user name
   * @param student student's user name. Can be empty to get a list of all quizzes in the
   *     instructor's courses.
   * @return a vector containing the list of quizzes
   * @throws InvalidDBRequestException
   */
  public Vector getQuizList(String instructor, String student) throws InvalidDBRequestException {
    Vector list = new Vector();

    try {
      Connection db;

      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      if (!student.equals("")) {
        // get the list that contains all quizzes that the student has taken and from the
        // instructor's courses which the student is registered
        rs =
            stmt.executeQuery(
                "select courseTest.test_name, scores.start_time from scores, courseTest, course "
                    + "where courseTest.test_name = scores.test_name "
                    + "and courseTest.course_id = course.course_id "
                    + "and instructor = '"
                    + instructor
                    + "' and user_login = '******' "
                    + "order by scores.start_time");

        while (rs.next()) {
          list.add(rs.getString(1) + " <" + rs.getString(2) + ">");
        }
      } else {
        // get the list that contains all quizzes that are used in the instructor's courses
        rs =
            stmt.executeQuery(
                "select test_name from courseTest, course "
                    + "where courseTest.course_id = course.course_id "
                    + "and instructor = '"
                    + instructor
                    + "' ");

        while (rs.next()) {
          list.add(rs.getString(1));
        }
      }

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in getQuizList: " + e.getMessage());
      throw new InvalidDBRequestException("???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }

    return list;
  }
Esempio n. 11
0
 void BuildBinaryHeap(Woman[] array) { // the O(n) version, array is 0-based
   BinaryHeapSize = array.length;
   A = new Vector<Woman>();
   A.add(new Woman()); // dummy, this BinaryHeap is 1-based
   for (int i = 1; i <= BinaryHeapSize; i++) // copy the content
   A.add(array[i - 1]);
   for (int i = parent(BinaryHeapSize); i >= 1; i--) shiftDown(i);
 }
 /** addAll adds each element from the given collection */
 public void testAddAll() {
   List full = populatedArray(3);
   Vector v = new Vector();
   v.add(three);
   v.add(four);
   v.add(five);
   full.addAll(v);
   assertEquals(6, full.size());
 }
 /** containsAll returns true for collection with subset of elements */
 public void testContainsAll() {
   List full = populatedArray(3);
   Vector v = new Vector();
   v.add(one);
   v.add(two);
   assertTrue(full.containsAll(v));
   v.add(six);
   assertFalse(full.containsAll(v));
 }
Esempio n. 14
0
  // ParserListener methods
  public void noteEvent(Note note) {
    if (layer >= staves) {
      return;
    }
    // System.out.println(note.getMusicString() + " " + note.getMillisDuration() + " " +
    // note.getDecimalDuration());
    Vector<Chord> currChords = chords[layer];
    Iterator<NotePanel> currNote = currNotes[layer];

    if (!currNote.hasNext()) {
      System.err.println("Received noteEvent, but no PostScript notes are left");
      return;
    }

    if (note.getMillisDuration() > 0) {
      NotePanel notePanel = currNote.next();
      // time the last chord ended
      long tempTime = 0;
      for (int i = currChords.size() - 1; i >= 0; --i) {
        if (!currChords.get(i).isTie()) {
          tempTime = currChords.get(i).getTime() + currChords.get(i).getDuration();
          break;
        }
      }

      if (notePanel.isTie) {
        Chord chord = new Chord();
        // for each note in the last chord, set the next note as a tied note
        for (int i = 0; i < currChords.lastElement().size(); ++i) {
          notePanel.setTie(true).setTime(Math.min(tempTime, time - 1)).setTempo(tempo);
          chord.addNote(notePanel);
          notePanel = currNote.next();
        }
        currChords.add(chord);
      }

      while (notePanel.isRest) {
        notePanel
            .setTime(Math.min(tempTime, time - 1)) // hack, in case the rest should be trimmed
            .setTempo(tempo);
        tempTime += notePanel.getDuration();
        Chord chord = new Chord(notePanel);
        currChords.add(chord);
        // System.out.println("REST: " + notePanel.getMusicString() + " " +
        // notePanel.getDuration());
        notePanel = currNote.next();
      }

      notePanel.setNote(note).setTime(time).setTempo(tempo);
      if (currChords.isEmpty() || currChords.lastElement().getTime() != time) {
        Chord chord = new Chord(notePanel);
        currChords.add(chord);
      } else {
        currChords.lastElement().addNote(notePanel);
      }
    }
  }
Esempio n. 15
0
    void listContents(Vector v) {
      if (parent != null && blocks != null) {
        v.add(this);
      }

      for (Iterator it = children.values().iterator(); it.hasNext(); ) {
        INode child = (INode) it.next();
        v.add(child);
      }
    }
Esempio n. 16
0
 /**
  * This parses the "name" field passed in the header of the control file or the data files.
  * Example: Control File header = cfa001MyComputer Example: Data File header = dfa001MyComputer
  */
 public static Vector parsePrintFileName(String header) {
   final String METHOD_NAME = "parsePrintFileName(): ";
   Vector result = new Vector();
   String first3Chars = header.substring(0, 3);
   String jobNumber = header.substring(3, 6);
   String hostName = header.substring(6);
   result.add(first3Chars);
   result.add(jobNumber);
   result.add(hostName);
   return result;
 }
 public void fillPackageDetails(@NonNls String packageName, final AsyncCallback callback) {
   final Hashtable details = getPackageDetails(packageName);
   if (details == null) {
     final Vector<String> params = new Vector<String>();
     params.add(packageName);
     try {
       params.add(getPyPIPackages().get(packageName));
       myXmlRpcClient.executeAsync("release_data", params, callback);
     } catch (Exception ignored) {
       LOG.info(ignored);
     }
   } else callback.handleResult(details, null, "");
 }
Esempio n. 18
0
 public void addConnectionListener(NCCPConnection.ConnectionListener l) {
   if (!listeners.contains(l)) {
     ExpCoordinator.printer.print(
         new String("NCCPConnection.addConnectionListener to " + toString()), 6);
     listeners.add(l);
   }
 }
Esempio n. 19
0
  public boolean load() {
    try {
      if (new File(FILE_PATH).exists()) {
        FileInputStream FIS = new FileInputStream(FILE_PATH);
        JXMLBaseObject cobjXmlObj = new JXMLBaseObject();
        cobjXmlObj.InitXMLStream(FIS);
        FIS.close();

        Vector exps = new Vector();
        Element rootElmt = cobjXmlObj.GetElementByName(JCStoreTableModel.ROOT_NAME);
        for (Iterator i = rootElmt.getChildren().iterator(); i.hasNext(); ) {
          Element crtElmt = (Element) i.next();
          JCExpression exp = new JCExpression();
          exp.mId = crtElmt.getAttributeValue("id", "");
          exp.mName = crtElmt.getAttributeValue("name", "");
          exp.mShowValue = crtElmt.getAttributeValue("show", "");
          exp.mStoreValue = crtElmt.getAttributeValue("store", "");
          exps.add(exp);
        }
        if (mModel != null) {
          mModel.setExpression(exps);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }
Esempio n. 20
0
 // --------------------------------------------------------------------------
 // BEGIN LOCAL TS OPERATIONS
 public void out(Tuple t) {
   ts.add(t);
   checkRxns(t);
   synchronized (blocked) {
     blocked.notifyAll();
   }
 }
  /** INTERNAL: Transform the object-level value into a database-level value */
  public Object getFieldValue(Object objectValue, AbstractSession session) {
    DatabaseMapping mapping = getMapping();
    Object fieldValue = objectValue;
    if ((mapping != null)
        && (mapping.isDirectToFieldMapping() || mapping.isDirectCollectionMapping())) {
      // CR#3623207, check for IN Collection here not in mapping.
      if (objectValue instanceof Collection) {
        // This can actually be a collection for IN within expressions... however it would be better
        // for expressions to handle this.
        Collection values = (Collection) objectValue;
        Vector fieldValues = new Vector(values.size());
        for (Iterator iterator = values.iterator(); iterator.hasNext(); ) {
          Object value = iterator.next();
          if (!(value instanceof Expression)) {
            value = getFieldValue(value, session);
          }
          fieldValues.add(value);
        }
        fieldValue = fieldValues;
      } else {
        if (mapping.isDirectToFieldMapping()) {
          fieldValue = ((AbstractDirectMapping) mapping).getFieldValue(objectValue, session);
        } else if (mapping.isDirectCollectionMapping()) {
          fieldValue = ((DirectCollectionMapping) mapping).getFieldValue(objectValue, session);
        }
      }
    }

    return fieldValue;
  }
  void writeFiles(Vector allConfigs) {

    Hashtable allFiles = computeAttributedFiles(allConfigs);

    Vector allConfigNames = new Vector();
    for (Iterator i = allConfigs.iterator(); i.hasNext(); ) {
      allConfigNames.add(((BuildConfig) i.next()).get("Name"));
    }

    TreeSet sortedFiles = sortFiles(allFiles);

    startTag("Files", null);

    for (Iterator i = makeFilters(sortedFiles).iterator(); i.hasNext(); ) {
      doWriteFiles(sortedFiles, allConfigNames, (NameFilter) i.next());
    }

    startTag(
        "Filter",
        new String[] {
          "Name", "Resource Files",
          "Filter", "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe"
        });
    endTag("Filter");

    endTag("Files");
  }
Esempio n. 23
0
 /**
  * Registers a reaction on this tuple space.
  *
  * @param rxn The reaction to register
  * @param listener The reaction callback function
  */
 public void registerReaction(Reaction rxn, ReactionListener listener) {
   reactions.add(new RegisteredReaction(rxn, listener));
   for (int i = 0; i < ts.size(); i++) {
     Tuple t = (Tuple) ts.get(i);
     if (rxn.getTemplate().matches(t)) listener.reactionFired(t);
   }
 }
Esempio n. 24
0
 /**
  * Re-scans the bus for devices. <i>ScanForDevices()</i> is called automatically by <i>{@link
  * #open() open()}</i>. <i>You must terminate use of all USB devices before calling
  * scanForDevices()!</i> After calling <i>scanForDevices()</i> you can reestablish connections to
  * USB devices.
  *
  * @return This device manager, useful for chaining together multiple operations.
  * @throws OperationFailedException
  */
 public USBDeviceManager scanForDevices() {
   if (isOpen()) {
     deviceList.clear();
     final int MAX_DEVICES = 100;
     int devices[] = new int[1 + MAX_DEVICES * 2]; // device index-product ID pairs
     final int result =
         getDeviceByProductID(MIN_PRODUCT_ID, MAX_PRODUCT_ID, devices); // get all devices
     if (result != SUCCESS) throw new OperationFailedException(result);
     final int numDevices = devices[0];
     for (int index = 0; index < numDevices; index++) {
       USBDevice device = null;
       final int deviceIndex = devices[1 + index * 2];
       final int productID = devices[1 + index * 2 + 1];
       if (USB_AI16_Family.isSupportedProductID(productID)) {
         device = new USB_AI16_Family(productID, deviceIndex);
       } else if (USB_AO16_Family.isSupportedProductID(productID)) {
         device = new USB_AO16_Family(productID, deviceIndex);
       } else if (USB_CTR_15_Family.isSupportedProductID(productID)) {
         device = new USB_CTR_15_Family(productID, deviceIndex);
       } else if (USB_DA12_8A_Family.isSupportedProductID(productID)) {
         device = new USB_DA12_8A_Family(productID, deviceIndex);
       } else if (USB_DA12_8E_Family.isSupportedProductID(productID)) {
         device = new USB_DA12_8E_Family(productID, deviceIndex);
       } else if (USB_DIO_16_Family.isSupportedProductID(productID)) {
         device = new USB_DIO_16_Family(productID, deviceIndex);
       } else if (USB_DIO_32_Family.isSupportedProductID(productID)) {
         device = new USB_DIO_32_Family(productID, deviceIndex);
       } else if (USB_DIO_Family.isSupportedProductID(productID)) {
         device = new USB_DIO_Family(productID, deviceIndex);
       } // else if( USB_DIO_Family.isSupportedProductID( ...
       if (device != null) deviceList.add(device);
     } // for( int index ...
   } else throw new OperationFailedException(MESSAGE_NOT_OPEN);
   return this;
 } // scanForDevices()
Esempio n. 25
0
    // get a list of whitespace separated classnames from a property.
    private String[] parseClassNames(String propertyName) {
	String hands = getProperty(propertyName);
	if (hands == null) {
	    return new String[0];
	}
	hands = hands.trim();
	int ix = 0;
	Vector result = new Vector();
	while (ix < hands.length()) {
	    int end = ix;
	    while (end < hands.length()) {
		if (Character.isWhitespace(hands.charAt(end))) {
		    break;
		}
		if (hands.charAt(end) == ',') {
		    break;
		}
		end++;
	    }
	    String word = hands.substring(ix, end);
	    ix = end+1;
	    word = word.trim();
	    if (word.length() == 0) {
		continue;
	    }
	    result.add(word);
	}
	return (String[]) result.toArray(new String[result.size()]);
    }
Esempio n. 26
0
  /**
   * Put the JAIN-SIP stack in a state where it cannot receive any data and frees the network ports
   * used. That is to say remove JAIN-SIP <tt>ListeningPoint</tt>s and <tt>SipProvider</tt>s.
   */
  @SuppressWarnings("unchecked") // jain-sip legacy code
  private void stopListening() {
    try {
      this.secureJainSipProvider.removeSipListener(this);
      this.stack.deleteSipProvider(this.secureJainSipProvider);
      this.secureJainSipProvider = null;
      this.clearJainSipProvider.removeSipListener(this);
      this.stack.deleteSipProvider(this.clearJainSipProvider);
      this.clearJainSipProvider = null;

      Iterator<ListeningPoint> it = this.stack.getListeningPoints();
      Vector<ListeningPoint> lpointsToRemove = new Vector<ListeningPoint>();
      while (it.hasNext()) {
        lpointsToRemove.add(it.next());
      }

      it = lpointsToRemove.iterator();
      while (it.hasNext()) {
        this.stack.deleteListeningPoint(it.next());
      }

      this.stack.stop();
      if (logger.isTraceEnabled()) logger.trace("stopped listening");
    } catch (ObjectInUseException ex) {
      logger.fatal("Failed to stop listening", ex);
    }
  }
 /** Utility method to stuff an entire enumeration into a vector */
 public static Vector Enum2Vector(Enumeration e) {
   Vector v = new Vector();
   while (e.hasMoreElements()) {
     v.add(e.nextElement());
   }
   return v;
 }
 /**
  * INTERNAL: Convert all the class-name-based settings in this InheritancePolicy to actual
  * class-based settings. This method is used when converting a project that has been built with
  * class names to a project with classes. It will also convert referenced classes to the versions
  * of the classes from the classLoader.
  */
 public void convertClassNamesToClasses(ClassLoader classLoader) {
   Vector newParentInterfaces = new Vector();
   for (Iterator iterator = getParentInterfaceNames().iterator(); iterator.hasNext(); ) {
     String interfaceName = (String) iterator.next();
     Class interfaceClass = null;
     try {
       if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
         try {
           interfaceClass =
               (Class)
                   AccessController.doPrivileged(
                       new PrivilegedClassForName(interfaceName, true, classLoader));
         } catch (PrivilegedActionException exception) {
           throw ValidationException.classNotFoundWhileConvertingClassNames(
               interfaceName, exception.getException());
         }
       } else {
         interfaceClass =
             org.eclipse.persistence.internal.security.PrivilegedAccessHelper.getClassForName(
                 interfaceName, true, classLoader);
       }
     } catch (ClassNotFoundException exc) {
       throw ValidationException.classNotFoundWhileConvertingClassNames(interfaceName, exc);
     }
     newParentInterfaces.add(interfaceClass);
   }
   this.parentInterfaces = newParentInterfaces;
 }
  public AllMultilevelCoefs(CoefArgs args) throws IOException {
    this.args = args;
    files = new Vector<File>();
    keys = new Vector<String>();
    coefs = new Vector<MultilevelCoefs>();

    File dir = args.dir();
    for (int i = 0; i < args.keys.length; i++) {
      keys.add(args.keys[i]);
      File f = CoefArgs.coefFile(dir, args.keys[i]);
      files.add(f);

      coefs.add(new MultilevelCoefs(f));
      System.out.println(String.format("Loaded: %s", args.keys[i]));
    }
  }
Esempio n. 30
0
  /**
   * Gets a list of courses that belongs to an instructor. Throws InvalidDBRequestException if any
   * error occured to the database connection.
   *
   * @param name the instructor's user name
   * @return a vector containing the list of courses
   * @throws InvalidDBRequestException
   */
  public Vector getCourseList(String name) throws InvalidDBRequestException {
    Vector courseList = new Vector();

    try {
      Connection db;

      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      // get the course list
      rs =
          stmt.executeQuery(
              "select course_num, course_name from course where instructor = '"
                  + name
                  + "' order by course_num");
      while (rs.next()) courseList.add(rs.getString(1) + " - " + rs.getString(2));

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in getCourseList: " + e.getMessage());
      throw new InvalidDBRequestException("???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Server Error");
    }

    return courseList;
  }