예제 #1
0
 /**
  * @param props
  * @exception IllegalArgumentException
  */
 public synchronized void copyFrom(Dictionary props) throws IllegalArgumentException {
   Enumeration keys = props.keys();
   Enumeration values = props.elements();
   while (keys.hasMoreElements()) {
     put(keys.nextElement(), values.nextElement());
   }
 }
예제 #2
0
  /** @param aProperties the updated properties. */
  @SuppressWarnings("rawtypes")
  final void setProperties(final Dictionary aProperties) {
    final Map<String, String> newProps = new HashMap<String, String>();

    Enumeration keys = aProperties.keys();
    while (keys.hasMoreElements()) {
      final String key = (String) keys.nextElement();
      if (!KNOWN_KEYS.contains(key) && !IGNORED_KEYS.contains(key)) {
        LOG.log(Level.WARNING, "Unknown/unsupported profile key: " + key);
        continue;
      }

      final String value = aProperties.get(key).toString();
      newProps.put(key, value.trim());
    }

    // Verify whether all known keys are defined...
    final List<String> checkedKeys = new ArrayList<String>(KNOWN_KEYS);
    checkedKeys.removeAll(newProps.keySet());
    if (!checkedKeys.isEmpty()) {
      throw new IllegalArgumentException(
          "Profile settings not complete! Missing keys are: " + checkedKeys.toString());
    }

    this.properties.putAll(newProps);

    LOG.log(
        Level.INFO,
        "New device profile settings applied for {1} ({0}) ...", //
        new Object[] {getType(), getDescription()});
  }
예제 #3
0
파일: Filter.java 프로젝트: gitmo/uni
  public static void main(String[] args) throws IOException {
    PrintWriter out = null;

    if (args.length < 1) {
      System.err.println("Usage: java Filter input [output]");
      System.exit(2); // POSIX
    } else if (args.length < 2)
      // Optional arg: use stdout if no output file given.
      out = new PrintWriter(System.out);
    else
      // Wrap a BufferedWriter around the FileWriter as it may be costly.
      out = new PrintWriter(new BufferedWriter(new FileWriter(args[1])));

    StreamTokenizer tokenizer = null;
    String res = resourceLoc(args[0]);
    try {
      tokenizer = new StreamTokenizer(new FileReader(res));
      tokenizer.lowerCaseMode(true);
    } catch (FileNotFoundException e) {
      System.err.printf("Input file %s was not found.\n", res);
      System.exit(-1);
    }

    Dictionary dictionary = new Dictionary();
    while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
      if (tokenizer.ttype == StreamTokenizer.TT_WORD && dictionary.contains(tokenizer.sval))
        out.println(tokenizer.sval);
    }

    out.close();
  }
  @Override
  public List<List<Node<String>>> search() {
    boolean canStart = checkWords(wordsPair);
    canStart &= checkDictionary(dictionary);
    if (!canStart) {
      return null;
    }

    Tree.Node<String> root = new Tree.Node<>();
    root.setData(wordsPair[0]);

    Tree<String> tree = new Tree<>();
    tree.setRootElement(root);

    String word = root.getItem();
    dictionary.remove(word);

    Node<String> currentNode = root;
    List<Node<String>> nodes = new ArrayList<>();

    while (!word.equals(wordsPair[1]) && currentNode != null) {
      // потенциальные слова
      List<String> words = generateCandidates(word);

      // отсекаем слова, которых нет в словаре
      for (Iterator<String> iterator = words.iterator(); iterator.hasNext(); ) {
        String s = iterator.next();
        if (!dictionary.contains(s)) {
          iterator.remove();
        }
      }

      // удаляем полученные слова из словаря (для исключения цикличности поиска)
      for (String c : words) {
        if (!c.equals(wordsPair[1])) {
          dictionary.remove(c);
        }
      }

      // формируем очередной уровень дерева
      for (String c : words) {
        Node<String> n = new Node<>(c);
        currentNode.addChild(n);

        if (c.equals(wordsPair[1])) {
          nodes.add(n);
        }
      }

      currentNode = tree.getNextElement(currentNode, !nodes.isEmpty());

      if (currentNode != null) {
        word = currentNode.getItem();
      } else if (nodes.isEmpty()) {
        return null;
      }
    }

    return tree.getPaths(nodes);
  }
예제 #5
0
  /**
   * Implements the <tt>ListCellRenderer</tt> method. Returns this panel that has been configured to
   * display bundle name, version and description.
   *
   * @param table the parent table
   * @param value the value of the rendered cell
   * @param isSelected indicates if the rendered cell is selected
   * @param hasFocus indicates if the rendered cell has the focus
   * @param rowIndex the row index of the rendered cell
   * @param vColIndex the column index of the rendered cell
   * @return the rendering component
   */
  public Component getTableCellRendererComponent(
      JTable table,
      Object value,
      boolean isSelected,
      boolean hasFocus,
      int rowIndex,
      int vColIndex) {
    Bundle bundle = (Bundle) value;

    Dictionary<?, ?> headers = bundle.getHeaders();
    Object bundleName = headers.get(Constants.BUNDLE_NAME);
    Object bundleVersion = headers.get(Constants.BUNDLE_VERSION);
    Object bundleDescription = headers.get(Constants.BUNDLE_DESCRIPTION);

    Icon stateIcon = getStateIcon(bundle.getState());

    if (bundleName != null) this.nameLabel.setText(bundleName.toString());
    else this.nameLabel.setText("unknown");

    if (bundleVersion != null) this.versionLabel.setText(bundleVersion.toString());
    else this.versionLabel.setText("");

    if (bundleDescription != null) this.descriptionLabel.setText(bundleDescription.toString());
    else this.descriptionLabel.setText("");

    if (stateIcon != null) this.stateLabel.setIcon(stateIcon);

    this.nameVersionPanel.remove(systemLabel);

    if (PluginManagerActivator.isSystemBundle(bundle)) this.nameVersionPanel.add(systemLabel);

    this.isSelected = isSelected;

    return this;
  }
  public ServiceRegistrationImpl(
      BundleImpl bundle,
      long serviceId,
      String[] classNames,
      Object service,
      Dictionary<String, ?> properties) {
    this.bundle = bundle;
    this.serviceId = serviceId;
    this.classNames = classNames;
    this.service = service;

    if ((properties == null) || properties.isEmpty()) this.properties = EMPTY_PROPERTIES;
    else {
      Enumeration<String> keys = properties.keys();
      Map<String, Object> thisProperties = newCaseInsensitiveMapInstance();

      while (keys.hasMoreElements()) {
        String key = keys.nextElement();

        if (Constants.OBJECTCLASS.equalsIgnoreCase(key)
            || Constants.SERVICE_ID.equalsIgnoreCase(key)) continue;
        else if (thisProperties.containsKey(key)) throw new IllegalArgumentException(key);
        else thisProperties.put(key, properties.get(key));
      }

      this.properties = thisProperties.isEmpty() ? EMPTY_PROPERTIES : thisProperties;
    }
  }
  public static void main(String[] args) {
    Dictionary dico = new Dictionary();
    System.out.print("Parsing dictionary.");
    dico.ParseLettersValuesFile("lettervalues.txt");
    dico.Parse("enable1.txt");
    System.out.println("\t\t done.");

    Hand hand = null;
    try {
      System.out.print("Parsing hand.");
      Scanner scan = new Scanner(new FileReader("hand"));
      hand = new Hand(scan.nextLine(), dico.getLettersValues());
      scan.close();
      System.out.println("\t\t done.");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    System.out.println("Searching for the word (or combination of words) with the maximal value.");
    Word result = dico.getWordWithMaxValue(hand);
    System.out.println("\t\t done.");
    System.out.println("Writing result.");
    PrintWriter w;
    try {
      w = new PrintWriter("result.txt", "UTF-8");
      for (String s : result.getWord().split(" ")) {
        w.println(s);
      }
      w.print(result.getValue());
      w.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
  }
예제 #8
0
 public void close() {
   final HashSet<Dictionary> dictionaries = CollectionUtils.newHashSet();
   dictionaries.addAll(mDictionaries.values());
   for (final Dictionary dictionary : dictionaries) {
     dictionary.close();
   }
   mMainDictionary = null;
 }
예제 #9
0
 /**
  * Registers the full and simple class name of the specified event and sets the default priority
  * of the event class.
  *
  * @param event an event belonging to the event class to register the class name for etc.
  */
 private void registerEventNames(Event event) {
   if (!HiddenAccess.isCriticalEvent(event)) {
     HiddenAccess.setDefaultPriority(event);
   }
   final Class<?> type = event.getClass();
   eventNames.put(type.getName(), event); // full name with package name
   eventNames.put(type.getSimpleName(), event); // only the class name
 }
예제 #10
0
  /**
   * * First time that I hit a -1 in dictionary
   *
   * @param dict
   * @param target
   * @return
   */
  private int rangeHelper(Dictionary dict, int target) {
    int curIndex = 1;

    while (dict.get(curIndex) != null && dict.get(curIndex).intValue() <= target) {
      curIndex *= 2;
    }

    return curIndex / 2;
  }
예제 #11
0
  public static void getTrainData() {
    // Build SURF dictionary

    File folder = new File(inDataPath + "Arbys");
    System.out.println(folder.getPath());
    Dictionary dictionary = Dictionary.build(100, folder);
    dictionary.saveCenters(outDataPath);
    dictionary.saveToDatabase(outDataPath);
  }
예제 #12
0
  static Dictionary<String, RTFAttribute> attributesByKeyword() {
    Dictionary<String, RTFAttribute> d = new Hashtable<String, RTFAttribute>(attributes.length);

    for (RTFAttribute attribute : attributes) {
      d.put(attribute.rtfName(), attribute);
    }

    return d;
  }
예제 #13
0
 public boolean isValidWord(final CharSequence word) {
   if (word == null || word.length() == 0) {
     return false;
   }
   return mMainDict.isValidWord(word)
       || (mUserDictionary != null && mUserDictionary.isValidWord(word))
       || (mAutoDictionary != null && mAutoDictionary.isValidWord(word))
       || (mContactsDictionary != null && mContactsDictionary.isValidWord(word));
 }
예제 #14
0
  /**
   * Internal match routine. Dictionary parameter must support case-insensitive get.
   *
   * @param properties A dictionary whose keys are used in the match.
   * @return If the Dictionary's keys match the filter, return <code>true</code>. Otherwise, return
   *     <code>false</code>.
   */
  private boolean match0(Dictionary properties) {
    switch (op) {
      case AND:
        {
          FilterImpl[] filters = (FilterImpl[]) value;
          for (int i = 0, size = filters.length; i < size; i++) {
            if (!filters[i].match0(properties)) {
              return false;
            }
          }

          return true;
        }

      case OR:
        {
          FilterImpl[] filters = (FilterImpl[]) value;
          for (int i = 0, size = filters.length; i < size; i++) {
            if (filters[i].match0(properties)) {
              return true;
            }
          }

          return false;
        }

      case NOT:
        {
          FilterImpl filter = (FilterImpl) value;

          return !filter.match0(properties);
        }

      case SUBSTRING:
      case EQUAL:
      case GREATER:
      case LESS:
      case APPROX:
      case SUBSET:
      case SUPERSET:
        {
          Object prop = (properties == null) ? null : properties.get(attr);

          return compare(op, prop, value);
        }

      case PRESENT:
        {
          Object prop = (properties == null) ? null : properties.get(attr);

          return prop != null;
        }
    }

    return false;
  }
예제 #15
0
 private void updateLabelSizes() {
   Dictionary labelTable = getLabelTable();
   if (labelTable != null) {
     Enumeration labels = labelTable.elements();
     while (labels.hasMoreElements()) {
       JComponent component = (JComponent) labels.nextElement();
       component.setSize(component.getPreferredSize());
     }
   }
 }
 @Activate
 protected void activate(BundleContext context) {
   log.info("activating SSE");
   Dictionary<String, Object> properties = new Hashtable<String, Object>();
   properties.put(
       EventConstants.EVENT_TOPIC, ReplicationEvent.getTopic(ReplicationEventType.PACKAGE_QUEUED));
   registration =
       context.registerService(EventHandler.class.getName(), new SSEListener(), properties);
   log.info("SSE activated : {}", registration != null);
 }
예제 #17
0
 private static void addOrReplaceDictionary(
     final ConcurrentHashMap<String, Dictionary> dictionaries,
     final String key,
     final Dictionary dict) {
   final Dictionary oldDict =
       (dict == null) ? dictionaries.remove(key) : dictionaries.put(key, dict);
   if (oldDict != null && dict != oldDict) {
     oldDict.close();
   }
 }
 public AuthServiceTracker(BundleContext context) throws InvalidSyntaxException {
   super(context, getAuthFilter(), null);
   // TODO: Filters are case sensitive, we should be too
   if (NoneAuthenticationService.AUTH_TYPE.equalsIgnoreCase(getAuthName())) {
     Dictionary<String, String> properties = new Hashtable<String, String>();
     properties.put(ServerConstants.CONFIG_AUTH_NAME, getAuthName());
     // TODO: shouldn't we always register the none-auth service?
     context.registerService(
         IAuthenticationService.class, new NoneAuthenticationService(), properties);
   }
 }
  public boolean isWordsValid() {

    if (keyWord != null) {
      System.out.println("keyword: " + board.getWordString(keyWord, map));
      if (!dic.lookUp(board.getWordString(keyWord, map))) return false;
    }
    for (int i = 0; i < wordList.size(); i++) {
      System.out.println("word: " + board.getWordString(wordList.get(i), map));
      if (!dic.lookUp(board.getWordString(wordList.get(i), map))) return false;
    }
    return true;
  }
예제 #20
0
  /**
   * Returns a list of errors for the given line.
   *
   * @require line is not null
   * @ensure result is a list of every error as determined from this SpellChecker's dictionary.
   */
  private ArrayList<Error> generateErrorList(String line) {
    /*
     * errors holds the list of errors for this line
     * currentIndex records the position of the current word in the text
     * error holds each error before being added to the list of errors.
     */
    ArrayList<Error> errors = new ArrayList<Error>();
    int currentIndex = 0;
    Error error;

    /* words is the list of space-separated strings in the text */
    String[] words = line.split("\\s"); // "\s" is regex for whitespace
    for (String word : words) {
      /* loop invariant: 	errors holds the list of misspelled words
       * which have been discovered thus far.
       * 					currentIndex holds the position in the text at
       * which the current word begins.
       * 					error holds information about the misspelled
       * word discovered this iteration.
       */

      /*
       * specWord holds word with leading and trailing non-letters
       * removed
       */
      String specWord = stripToSpec(word);
      if (specWord.equals("")) { // Disregard the empty string
        continue;
      }

      if (!dictionary.lookup(specWord)) {
        /*
         * currentIndex is the index of the word starting after the
         * previously found word.
         */
        currentIndex = line.indexOf(specWord, currentIndex);

        /*
         * Generate a new error to be added to the list
         */
        error = new Error(currentIndex, specWord, dictionary.getCorrections(specWord));
        errors.add(error);

        /*
         * Advance the currentIndex to the start of the next word
         */
        currentIndex += word.length();
      }
    }

    return errors;
  }
예제 #21
0
  /**
   * Updates the UIs for the labels in the label table by calling {@code updateUI} on each label.
   * The UIs are updated from the current look and feel. The labels are also set to their preferred
   * size.
   *
   * @see #setLabelTable
   * @see JComponent#updateUI
   */
  protected void updateLabelUIs() {
    Dictionary labelTable = getLabelTable();

    if (labelTable == null) {
      return;
    }
    Enumeration labels = labelTable.keys();
    while (labels.hasMoreElements()) {
      JComponent component = (JComponent) labelTable.get(labels.nextElement());
      component.updateUI();
      component.setSize(component.getPreferredSize());
    }
  }
예제 #22
0
  /** load saved model */
  public boolean loadModel() {
    if (!readOthersFile(dir + File.separator + modelName + othersSuffix)) return false;

    if (!readTAssignFile(dir + File.separator + modelName + tassignSuffix)) return false;

    // read dictionary
    Dictionary dict = new Dictionary();
    if (!dict.readWordMap(dir + File.separator + wordMapFile)) return false;

    data.localDict = dict;

    return true;
  }
  public static void main(String[] args) {
    Dictionary<Integer> d = new TabellaHashLL<Integer>(5, new HashDivisione());
    d.insert(1, "A1");
    d.insert(2, "A2");
    d.insert(3, "A3");
    d.insert(4, "A4");
    d.insert(5, "A5");
    d.insert(6, "A6");
    d.insert(7, "A7");

    for (Integer x : d) {
      System.out.print(x + " ");
    }
  }
예제 #24
0
 public DefaultMutableTreeNode createDictionaryNode(Dictionary dictionary) {
   DefaultMutableTreeNode dn = new DefaultMutableTreeNode(dictionary);
   if (dictionary.getRecords() != null) {
     for (Record record : dictionary.getRecords()) {
       dn.add(createRecordNode(record));
     }
   }
   if (dictionary.getSubdictionaries() != null) {
     for (Dictionary sub : dictionary.getSubdictionaries()) {
       dn.add(createDictionaryNode(sub));
     }
   }
   return dn;
 }
예제 #25
0
  public static void toJSON(ConfigurationAdmin admin, Writer osw, String filter) throws Exception {

    Configuration[] list = admin.listConfigurations(filter);
    Encoder encoder = codec.enc().to(osw);

    Protocol p = new Protocol();
    p.version = 1;
    p.date = new Date();
    p.size = list.length;
    encoder.put(p).append('\n');

    if (list != null)
      for (Configuration c : list) {
        Dictionary<String, Object> d = c.getProperties();
        Export export = new Export();
        export.values = new HashMap<String, Object>();
        export.factoryPid = c.getFactoryPid();
        export.pid = c.getPid();

        for (Enumeration<String> e = d.keys(); e.hasMoreElements(); ) {
          String k = e.nextElement();
          Object v = d.get(k);

          if (!(v instanceof String)) {

            if (export.types == null) export.types = new HashMap<String, Type>();

            Type type = new Type();

            Class<?> clazz = v.getClass();
            if (v instanceof Collection) {
              Collection<?> coll = (Collection<?>) v;
              clazz = String.class;
              if (coll.size() > 0) type.vectorOf = shortName(coll.iterator().next().getClass());
              else type.vectorOf = shortName(String.class);
            } else if (v.getClass().isArray()) {
              type.arrayOf = shortName(clazz.getComponentType());
            } else type.scalar = shortName(v.getClass());

            export.types.put(k, type);
          }
          export.values.put(k, v);
        }

        encoder.mark().put(export);
        // encoder.put(encoder.digest());
        encoder.append('\n');
      }
    osw.flush();
  }
예제 #26
0
  public boolean addWord(String str, long fileid, long pos) {
    /*
     * Filter out certain strings. e.g. words that are either very rare (e.g.
     * spelling mistakes) or extremely common "stop words".
     * http://en.wikipedia.org/wiki/Stop_words
     *
     * Our definition of stop words is completely arbitrary. It has more to do
     * with what kind of computation we can do on a single appengine node.
     *
     * Ideally we would not ignore any words, but that will require sharding the
     * word index across a number of serving machines.
     */
    if (str.length() < 3) return false;
    int freq = dict.getFrequency(str);
    if (freq == 0 || freq > 90000) return false;

    ArrayList<FilePositions> fplist = idx.get(str);
    if (fplist == null) {
      fplist = new ArrayList<FilePositions>();
      idx.put(str, fplist);
    }

    if (fplist.size() == 0 || fplist.get(fplist.size() - 1).fileid != fileid) {
      FilePositions fp = new FilePositions();
      fp.fileid = fileid;
      fp.poslist = new ArrayList<Long>();
      fplist.add(fp);
    }
    fplist.get(fplist.size() - 1).poslist.add(pos);
    return true;
  }
 @Override
 public void run(String... arg0) throws Exception {
   dictionary.set("java", "object oriented");
   /*dictionary.set("linux", "rulez");
   dictionary.set("mac", "beutifull");
   dictionary.set("solaris", "old but gold");
   dictionary.set("red hat", "new and fit");
   dictionary.set("debian", "just old");*/
   Writer writer = new Writer(dictionary, "Mr. Writer");
   Reader reader1 = new Reader(dictionary, "Mrs Reader 1");
   Reader reader2 = new Reader(dictionary, "Mrs Reader 2");
   Reader reader3 = new Reader(dictionary, "Mrs Reader 3");
   Reader reader4 = new Reader(dictionary, "Mrs Reader 4");
   Reader reader5 = new Reader(dictionary, "Mrs Reader 5");
   log.info("Inciando thread de writer");
   writer.setPriority(Thread.MAX_PRIORITY);
   writer.start();
   log.info("Inciando thread de reader Mrs Reader 1");
   reader1.start();
   log.info("Inciando thread de reader Mrs Reader 2");
   reader2.start();
   log.info("Inciando thread de reader Mrs Reader 3");
   reader3.start();
   log.info("Inciando thread de reader Mrs Reader 4");
   reader4.start();
   log.info("Inciando thread de reader Mrs Reader 5");
   reader5.start();
 }
      public String get(Object key) {
        if (!(key instanceof String)) return null;

        String sKey = (String) key;
        if (Constants.EXPORT_PACKAGE.equalsIgnoreCase(sKey)
            || Constants.PROVIDE_CAPABILITY.equalsIgnoreCase(sKey)) {
          String systemProvideHeader =
              getEquinoxContainer()
                  .getConfiguration()
                  .getConfiguration(
                      EquinoxConfiguration.PROP_SYSTEM_PROVIDE_HEADER,
                      EquinoxConfiguration.SYSTEM_PROVIDE_HEADER_SYSTEM_EXTRA);
          boolean useSystemExtra =
              systemProvideHeader.equals(EquinoxConfiguration.SYSTEM_PROVIDE_HEADER_SYSTEM_EXTRA);
          boolean useSystem =
              systemProvideHeader.equals(EquinoxConfiguration.SYSTEM_PROVIDE_HEADER_SYSTEM)
                  || useSystemExtra;
          String systemProp =
              useSystem
                  ? (Constants.EXPORT_PACKAGE.equalsIgnoreCase(sKey)
                      ? Constants.FRAMEWORK_SYSTEMPACKAGES
                      : Constants.FRAMEWORK_SYSTEMCAPABILITIES)
                  : null;
          String systemExtraProp =
              useSystemExtra
                  ? (Constants.EXPORT_PACKAGE.equalsIgnoreCase(sKey)
                      ? Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA
                      : Constants.FRAMEWORK_SYSTEMCAPABILITIES_EXTRA)
                  : null;
          return getExtra(sKey, systemProp, systemExtraProp);
        }

        return headers.get(key);
      }
예제 #29
0
  /**
   * Add to the currentList Strings that are one character deletion away from the input string.
   *
   * @param word The misspelled word
   * @param numSuggestions is the maximum number of suggestions to return
   * @return the list of spelling suggestions
   */
  @Override
  public List<String> suggestions(String word, int numSuggestions) {

    // initial variables
    List<String> queue = new LinkedList<String>(); // String to explore
    HashSet<String> visited =
        new HashSet<
            String>(); // to avoid exploring the same  												   // string multiple times
    List<String> retList = new LinkedList<String>(); // words to return

    // insert first node
    queue.add(word);
    visited.add(word);

    // TODO: Implement the remainder of this method, see assignment for algorithm
    while ((!queue.isEmpty()) & (retList.size() != numSuggestions)) {
      String current = ((LinkedList<String>) queue).removeFirst();
      List<String> muta = distanceOne(current, true);
      for (String m : muta) {
        if (!visited.contains(m)) {
          visited.add(m);
          queue.add(m);
          if (dict.isWord(m)) retList.add(m);
        }
      }
    }

    return retList;
  }
예제 #30
0
 @Override
 public int hashCode() {
   int tresult = dictionary.hashCode();
   tresult = 31 * tresult + word.hashCode();
   tresult = 31 * tresult + translation.hashCode();
   return tresult;
 }