Example #1
0
 public static void main(String[] args) throws IOException {
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   String[] temp = in.readLine().split(" ");
   int n = Integer.parseInt(temp[0]);
   int s = Integer.parseInt(temp[1]);
   HashMap<Integer, Integer> buy = new HashMap<>();
   HashMap<Integer, Integer> sell = new HashMap<>();
   for (int i = 1; i <= n; i++) {
     temp = in.readLine().split(" ");
     int p = Integer.parseInt(temp[1]);
     int q = Integer.parseInt(temp[2]);
     if (temp[0].charAt(0) == 'B') {
       if (buy.containsKey(p)) buy.put(p, buy.get(p) + q);
       else buy.put(p, q);
     } else {
       if (sell.containsKey(p)) sell.put(p, sell.get(p) + q);
       else sell.put(p, q);
     }
   }
   ArrayList<Integer> buyArr = new ArrayList<>();
   ArrayList<Integer> sellArr = new ArrayList<>();
   for (Integer i : buy.keySet()) buyArr.add(i);
   for (Integer i : sell.keySet()) sellArr.add(i);
   Collections.sort(buyArr, Comparator.reverseOrder());
   Collections.sort(sellArr);
   for (int i = Math.min(s, sellArr.size()) - 1; i >= 0; i--)
     System.out.println("S " + sellArr.get(i) + " " + sell.get(sellArr.get(i)));
   for (int i = 0; i < s && i < buyArr.size(); i++)
     System.out.println("B " + buyArr.get(i) + " " + buy.get(buyArr.get(i)));
 }
  public final String correct(String word) {
    if (nWords.containsKey(word)) return word;
    ArrayList<String> list = edits(word);
    HashMap<Integer, String> candidates = new HashMap<Integer, String>();
    for (String s : list) if (nWords.containsKey(s)) candidates.put(nWords.get(s), s);

    if (candidates.size() > 0) return candidates.get(Collections.max(candidates.keySet()));
    return candidates.size() > 0 ? candidates.get(Collections.max(candidates.keySet())) : word;
  }
Example #3
0
  /**
   * Build a list of installed plugins.
   *
   * @return a list of plugin names and version numbers.
   */
  public static EventList<NameAndVersion> findInstalledPlugins() {
    EventList<NameAndVersion> plugins = new BasicEventList<NameAndVersion>();
    if (!PluginCore.userPluginDir.exists()) return plugins;
    String[] files =
        PluginCore.userPluginDir.list(
            new FilenameFilter() {
              public boolean accept(File dir, String name) {
                return name.endsWith(".jar");
              }
            });

    HashMap<String, PluginDescriptor> urls = new HashMap<String, PluginDescriptor>();
    Collection<PluginDescriptor> descriptors =
        PluginCore.getManager().getRegistry().getPluginDescriptors();
    for (PluginDescriptor desc : descriptors) {
      if ((desc.getPluginClassName() == null)
          || !desc.getPluginClassName().equals("net.sf.jabref.plugin.core.JabRefPlugin")) {
        urls.put(desc.getId(), desc);
      }
    }

    for (String file1 : files) {
      File file = new File(PluginCore.userPluginDir, file1);
      String[] nav = getNameAndVersion(file);
      if (nav != null) {
        VersionNumber vn = nav[1] != null ? new VersionNumber(nav[1]) : null;
        NameAndVersion nameAndVersion = new NameAndVersion(nav[0], vn, true, file);
        for (Iterator<String> it = urls.keySet().iterator(); it.hasNext(); ) {
          String loc = it.next();
          if (loc.contains(nav[0])) {
            PluginDescriptor desc = urls.get(loc);
            // System.out.println("Accounted for: "+desc.getId()+" "+desc.getVersion().toString());
            if (!PluginCore.getManager().isPluginEnabled(urls.get(loc)))
              nameAndVersion.setStatus(BAD);
            else nameAndVersion.setStatus(LOADED);
            it.remove();
          }
        }
        plugins.add(nameAndVersion);
      }
    }

    for (String url : urls.keySet()) {
      PluginDescriptor desc = urls.get(url);
      File location = new File(desc.getLocation().getFile());
      if (location.getPath().contains(PluginCore.userPluginDir.getPath()))
        continue; // This must be a loaded user dir plugin that's been deleted.
      // System.out.println("File: "+desc.getLocation().getFile());
      NameAndVersion nameAndVersion =
          new NameAndVersion(
              desc.getId(), new VersionNumber(desc.getVersion().toString()), false, location);
      if (!PluginCore.getManager().isPluginEnabled(urls.get(url))) nameAndVersion.setStatus(BAD);
      else nameAndVersion.setStatus(LOADED);
      plugins.add(nameAndVersion);
    }
    return plugins;
  }
  /** Gets all Genomic Data. */
  private ProfileDataSummary getGenomicData(
      String cancerStudyId,
      HashMap<String, GeneticProfile> defaultGeneticProfileSet,
      SampleList defaultSampleSet,
      String geneListStr,
      ArrayList<SampleList> sampleList,
      HttpServletRequest request,
      HttpServletResponse response)
      throws IOException, ServletException, DaoException {

    // parse geneList, written in the OncoPrintSpec language (except for changes by XSS clean)
    double zScore =
        ZScoreUtil.getZScore(
            new HashSet<String>(defaultGeneticProfileSet.keySet()),
            new ArrayList<GeneticProfile>(defaultGeneticProfileSet.values()),
            request);
    double rppaScore = ZScoreUtil.getRPPAScore(request);

    ParserOutput theOncoPrintSpecParserOutput =
        OncoPrintSpecificationDriver.callOncoPrintSpecParserDriver(
            geneListStr,
            new HashSet<String>(defaultGeneticProfileSet.keySet()),
            new ArrayList<GeneticProfile>(defaultGeneticProfileSet.values()),
            zScore,
            rppaScore);

    ArrayList<String> geneList = new ArrayList<String>();
    geneList.addAll(theOncoPrintSpecParserOutput.getTheOncoPrintSpecification().listOfGenes());

    ArrayList<ProfileData> profileDataList = new ArrayList<ProfileData>();
    Set<String> warningUnion = new HashSet<String>();

    for (GeneticProfile profile : defaultGeneticProfileSet.values()) {
      try {
        GetProfileData remoteCall =
            new GetProfileData(
                profile, geneList, StringUtils.join(defaultSampleSet.getSampleList(), " "));
        ProfileData pData = remoteCall.getProfileData();
        warningUnion.addAll(remoteCall.getWarnings());
        profileDataList.add(pData);
      } catch (IllegalArgumentException e) {
        e.getStackTrace();
      }
    }

    ProfileMerger merger = new ProfileMerger(profileDataList);
    ProfileData mergedProfile = merger.getMergedProfile();

    ProfileDataSummary dataSummary =
        new ProfileDataSummary(
            mergedProfile,
            theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(),
            zScore,
            rppaScore);
    return dataSummary;
  }
Example #5
0
  /**
   * Reads the data from database and writes into detectors hashmap
   *
   * @throws SQLException
   */
  public void readDataIntoDetectorListFromDatabase() throws SQLException {

    // TestConfiguration.dbSetup();

    PeMSStationAggregateReader stationAggregateReader =
        new PeMSStationAggregateReader(oraDatabase.doConnect());
    ArrayList<Long> vdsIDs = new ArrayList<Long>();

    for (int key : detectors.keySet()) {
      vdsIDs.add((long) key);
    }
    List<PeMSStationAggregate> stationsAggregate =
        stationAggregateReader.read(
            this.timeInterval, vdsIDs, PeMSAggregate.AggregationLevel.PEMS_5MIN);

    // Read absolute detector info into the hashmap
    VDSReader stationReader = new VDSReader(oraDatabase.doConnect());
    for (int key : detectors.keySet()) {
      VDS station = stationReader.read((long) key);
      Detector d = detectors.get(key);
      d.setAbsolutePM(station.getAbsolutePostmile());
      d.setDetectorLength(station.getDetectorLength());
      d.setDetectorName(station.getDetectorName());
      d.setFreewayDirection(station.getDirection());
      d.setFreewayNumber(station.getFreewayNum());
      d.setLatitude(station.getPosition().getPoint().get(0).getLat());
      d.setLongitude(station.getPosition().getPoint().get(0).getLng());
      d.setNumberOfLanes(station.getLaneCount());
    }

    // Read 5 minute data into the hashmap
    for (int i = 0; i < stationsAggregate.size(); i++) {
      // find the detector corresponding to the current ID in the data vector and fill the fields
      // accordingly
      Detector d = detectors.get((int) stationsAggregate.get(i).getVdsId());
      d.addDatumToSpeed(stationsAggregate.get(i).getTotal().getAvgSpeed());
      d.addDatumToFlow(
          stationsAggregate.get(i).getTotal().getFlow()
              * 12
              / d
                  .getNumberOfLanes()); // to get the hourly rate at 5 minute granularity, multiply
                                        // by 12
      d.addDatumToDensity(
          stationsAggregate.get(i).getTotal().getFlow()
              * 12
              / stationsAggregate.get(i).getTotal().getAvgSpeed()
              / d.getNumberOfLanes());
      if (i < detectors.size()) {
        d.setHealthStatus(stationsAggregate.get(i).getTotal().getObserved());
      }
    }
  }
Example #6
0
 private HashMap<String, Float> normalizeScores(HashMap<String, Float> scores) {
   Iterator<String> keys = scores.keySet().iterator();
   float mean = 0f;
   while (keys.hasNext()) {
     String key = (String) keys.next();
     mean += ((scores.get(key)) * (scores.get(key)));
   }
   mean = (float) Math.sqrt(mean);
   keys = scores.keySet().iterator();
   while (keys.hasNext()) {
     String key = (String) keys.next();
     scores.put(key, scores.get(key) / (float) mean);
   }
   return scores;
 }
  public void save() {
    for (String key : fields.keySet()) {
      JComponent comp = fields.get(key);

      if (comp instanceof JTextField) {
        JTextField c = (JTextField) comp;

        if (c.getText().trim().equals("")) {
          sketch.configFile.unset(key);
        } else {
          sketch.configFile.set(key, c.getText());
        }
      } else if (comp instanceof JTextArea) {
        JTextArea c = (JTextArea) comp;

        if (c.getText().trim().equals("")) {
          sketch.configFile.unset(key);
        } else {
          sketch.configFile.set(key, c.getText());
        }
      }
    }

    sketch.saveConfig();
  }
Example #8
0
  public void exportMainlineDataToText() throws IOException {

    for (int key : detectors.keySet()) {

      Double[] flow =
          MyUtilities.scaleVector(
              detectors.get(key).getFlowDataArray(),
              (double) detectors.get(key).getNumberOfLanes());
      Double[] speed = detectors.get(key).getSpeedDataArray();
      Double[] density =
          MyUtilities.scaleVector(
              detectors.get(key).getDensityDataArray(),
              (double) detectors.get(key).getNumberOfLanes());

      PrintWriter outFlow = new PrintWriter(new FileWriter(key + "_flw.txt"));
      PrintWriter outSpeed = new PrintWriter(new FileWriter(key + "_spd.txt"));
      PrintWriter outDensity = new PrintWriter(new FileWriter(key + "_dty.txt"));

      for (int i = 0; i < flow.length; i++) {

        outFlow.println(flow[i]);
        outSpeed.println(speed[i]);
        outDensity.println(density[i]);
      }

      outFlow.close();
      outSpeed.close();
      outDensity.close();
    }
  }
  public static void countPairs(Integer[] arr) {

    HashMap<Integer, Integer> seenElements = new HashMap<Integer, Integer>();

    // ArrayList<Integer> countList = new ArrayList<Integer

    for (int i = 0; i < arr.length; i++) {

      if (!seenElements.containsKey(arr[i])) {
        seenElements.put(arr[i], 1);
      } else {

        seenElements.put(arr[i], seenElements.get(arr[i]) + 1);
      }
    }

    BigInteger count = null;
    for (int element : seenElements.keySet()) {
      if (seenElements.get(element) > 1) {
        System.out.println("count is :" + seenElements.get(element));
        count.add(
            factorial(seenElements.get(element)).divide(factorial(seenElements.get(element) - 2)));
        System.out.println(count);
      }
    }

    if (count == null) {
      System.out.println("0");
    }
  }
    /** Displays the labels and the values for the panel. */
    protected void displayPnlFields(HashMap hmPnl) {
      if (hmPnl == null || hmPnl.isEmpty()) return;

      Iterator keySetItr = hmPnl.keySet().iterator();
      String strLabel = "";
      String strValue = "";

      // if the file is empty, then create an empty set of textfields.
      if (hmPnl == null || hmPnl.isEmpty()) {
        displayNewTxf("", "");
        return;
      }

      Container container = getParent();
      if (container != null) container.setVisible(false);
      try {
        // Get each set of label and value, and display them.
        while (keySetItr.hasNext()) {
          strLabel = (String) keySetItr.next();
          strValue = (String) hmPnl.get(strLabel);

          displayNewTxf(strLabel, strValue);
        }

        if (container != null) container.setVisible(true);
        revalidate();
        repaint();
      } catch (Exception e) {
        Messages.writeStackTrace(e);
        // e.printStackTrace();
        Messages.postDebug(e.toString());
      }
    }
Example #11
0
 public void evaluation(String[] args) throws IOException {
   String devPath = args[0];
   String hmmTransPath = args[1];
   String hmmEmitPath = args[2];
   String hmmPriorPath = args[3];
   // alpha al = new alpha();
   loadParameter(hmmTransPath, hmmEmitPath, hmmPriorPath);
   File devf = new File(devPath);
   FileReader devFr = new FileReader(devf);
   BufferedReader devBr = new BufferedReader(devFr);
   String line;
   while ((line = devBr.readLine()) != null) {
     double likelihood1 = 0;
     String[] observations = line.split(" ");
     Iterator<String> it = prior.keySet().iterator();
     String state = it.next();
     alphaRecord = new HashMap<Integer, HashMap<String, Double>>();
     // sum all state
     likelihood1 = getAlpha(state, observations.length, line);
     // System.out.println(getAlpha(state, 1 , line));
     while (it.hasNext()) {
       state = it.next();
       double likelihood2 = getAlpha(state, observations.length, line);
       likelihood1 = Util.logSum(likelihood1, likelihood2);
     }
     System.out.println(likelihood1);
   }
   devBr.close();
 }
  private static LinkedHashMap sortHashMapByValuesD(HashMap passedMap) {
    List mapKeys = new ArrayList(passedMap.keySet());
    List mapValues = new ArrayList(passedMap.values());
    Collections.sort(mapValues);
    Collections.sort(mapKeys);

    LinkedHashMap sortedMap = new LinkedHashMap();

    Iterator valueIt = mapValues.iterator();
    while (valueIt.hasNext()) {
      Object val = valueIt.next();
      Iterator keyIt = mapKeys.iterator();

      while (keyIt.hasNext()) {
        Object key = keyIt.next();
        String comp1 = passedMap.get(key).toString();
        String comp2 = val.toString();

        if (comp1.equals(comp2)) {
          passedMap.remove(key);
          mapKeys.remove(key);
          sortedMap.put(key, val);
          break;
        }
      }
    }
    return sortedMap;
  }
  private void removeMonster(String monsterType) {
    Monster monster = null;

    ArrayList deadMonsters = new ArrayList();

    try {
      for (String key : monsters.keySet()) {
        monster = (Monster) monsters.get(key);
        if (monster.getName().equals(monsterType)) {
          deadMonsters.add(key);
          break;
        }
      }

      if (deadMonsters.size() > 0) {
        for (int i = 0; i < deadMonsters.size(); i++) {
          // EIError.debugMsg((String) deadMonsters.get(i));
          monsters.remove((String) deadMonsters.get(i));
        }
      }
    } catch (ConcurrentModificationException concEx) {
      // another thread was trying to modify monsters while iterating
      // we'll continue and the new item can be grabbed on the next update
    }
  }
  public void removeAllMonsters() {
    Monster monster = null;

    ArrayList deadMonsters = new ArrayList();

    try {
      for (String key : monsters.keySet()) {
        monster = (Monster) monsters.get(key);
        if (!monster.getName().equals("Pig")
            && !monster.getName().equals("BlueThorn")
            && !monster.getName().equals("VineThorn")) {
          deadMonsters.add(key);
          if (gameController.multiplayerMode == gameController.multiplayerMode.SERVER
              && registry.getNetworkThread() != null) {
            if (registry.getNetworkThread().readyForUpdates()) {
              UpdateMonster um = new UpdateMonster(monster.getId());
              um.mapX = monster.getMapX();
              um.mapY = monster.getMapY();
              um.action = "Die";
              registry.getNetworkThread().sendData(um);
            }
          }
        }
      }

      if (deadMonsters.size() > 0) {
        for (int i = 0; i < deadMonsters.size(); i++) {
          monsters.remove((String) deadMonsters.get(i));
        }
      }
    } catch (ConcurrentModificationException concEx) {
      // another thread was trying to modify monsters while iterating
      // we'll continue and the new item can be grabbed on the next update
    }
  }
  /**
   * Compares this LTS to another for debugging purposes.
   *
   * @param other the other LTS to compare to
   * @return <code>true</code> if these are equivalent
   */
  public boolean compare(LetterToSound other) {

    // compare letter index table
    //
    for (Iterator i = letterIndex.keySet().iterator(); i.hasNext(); ) {
      String key = (String) i.next();
      Integer thisIndex = (Integer) letterIndex.get(key);
      Integer otherIndex = (Integer) other.letterIndex.get(key);
      if (!thisIndex.equals(otherIndex)) {
        if (RiTa.PRINT_LTS_INFO) System.err.println("[WARN] LTSengine -> Bad index: " + key);
        return false;
      }
    }

    // compare states
    //
    for (int i = 0; i < stateMachine.length; i++) {
      State state = getState(i);
      State otherState = other.getState(i);
      if (!state.compare(otherState)) {
        if (RiTa.PRINT_LTS_INFO) System.err.println("[WARN] LTSengine -> Bad state: " + i);
        return false;
      }
    }

    return true;
  }
  @Override
  public void update() {
    if (!transmitting) {
      super.update();

      ArrayList deadMonsters = new ArrayList();

      Monster monster = null;

      try {
        for (String key : monsters.keySet()) {
          monster = (Monster) monsters.get(key);
          if (monster != null) {
            monster.update();
            if (monster.getIsDead()) {
              deadMonsters.add(key);
            }
          }
        }

        if (deadMonsters.size() > 0) {
          for (int i = 0; i < deadMonsters.size(); i++) {
            // EIError.debugMsg((String) deadMonsters.get(i));
            monsters.remove((String) deadMonsters.get(i));
          }
        }
      } catch (ConcurrentModificationException concEx) {
        // another thread was trying to modify monsters while iterating
        // we'll continue and the new item can be grabbed on the next update
      }
    }
  }
  public boolean handleClick(Player p, Point clickPoint) {
    Point mousePos = new Point(this.panelToMapX(clickPoint.x), this.panelToMapY(clickPoint.y));

    Monster monster = null;

    try {
      for (String key : monsters.keySet()) {
        monster = (Monster) monsters.get(key);
        if (monster != null) {
          if (monster.isInside(mousePos) && !monster.getIsHiding()) {
            if (selectedMob != monster) {
              SoundClip cl = new SoundClip("Misc/Click");
              selectedMob = monster;
            }
            return true;
          }
        }
      }
    } catch (ConcurrentModificationException concEx) {
      // another thread was trying to modify monsters while iterating
      // we'll continue and the new item can be grabbed on the next update
    }

    return false;
  }
  public Monster getMostAggroInPanel(Point p) {
    Monster monster = null;
    Monster mostAggroMonster = null;

    double mostAggro = 0;

    try {
      for (String key : monsters.keySet()) {
        monster = (Monster) monsters.get(key);
        if (!monster.getName().equals("Pig")
            && !monster.getName().equals("BlueThorn")
            && !monster.getName().equals("VineThorn")) {
          if (monster.getIsInPanel()) {
            double distance = p.distance(monster.getCenterPoint());
            if (monster.getPlayerDamage() > mostAggro) {
              mostAggroMonster = monster;
              mostAggro = monster.getPlayerDamage();
            }
          }
        }
      }
    } catch (ConcurrentModificationException concEx) {
      // another thread was trying to modify monsters while iterating
      // we'll continue and the new item can be grabbed on the next update
    }

    return mostAggroMonster;
  }
  public Monster getClosestWithinMax(Point p, int r) {
    Monster monster = null;
    Monster closestMonster = null;

    double closestDistance = 0;

    try {
      for (String key : monsters.keySet()) {
        monster = (Monster) monsters.get(key);
        if (!monster.getName().equals("Pig")
            && !monster.getName().equals("BlueThorn")
            && !monster.getName().equals("VineThorn")) {
          if (monster.getIsInPanel()) {
            double distance = p.distance(monster.getCenterPoint());
            if ((distance < closestDistance || closestDistance == 0) && distance <= r) {
              closestMonster = monster;
              closestDistance = distance;
            }
          }
        }
      }
    } catch (ConcurrentModificationException concEx) {
      // another thread was trying to modify monsters while iterating
      // we'll continue and the new item can be grabbed on the next update
    }

    return closestMonster;
  }
Example #20
0
  private static void getTopDocuments(int num, HashMap<String, Float> scoremap, String filename)
      throws FileNotFoundException {
    PrintWriter out = new PrintWriter(filename);
    Iterator<String> itr = scoremap.keySet().iterator();
    ArrayList<String> urls = new ArrayList<String>();
    ArrayList<Float> scores = new ArrayList<Float>();

    while (itr.hasNext()) {
      String key = itr.next();
      if (scores.size() < num) {
        scores.add(scoremap.get(key));
        urls.add(key);
      } else {
        int index = scores.indexOf(Collections.min(scores));
        if (scores.get(index) < scoremap.get(key)) {
          scores.set(index, scoremap.get(key));
          urls.set(index, key);
        }
      }
    }

    while (scores.size() > 0) {
      int index = scores.indexOf(Collections.max(scores));
      out.println(urls.get(index) + "\t" + scores.get(index));
      urls.remove(index);
      scores.remove(index);
    }
    out.close();
  }
Example #21
0
  public static void main(String[] args) throws Exception {
    BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));

    // HashMap is a class that implements the Map interface

    HashMap dictionary = new HashMap(); // creates an empty HashMap

    // put() a <key,value> pair into the Map

    String key = "foo";
    String value = "meta-syntactic variable used in programming examples";
    dictionary.put(key, value); // word is the key, definition is the mapped value

    // get()  the value by supplying the key

    System.out.println("The defintion of foo: " + dictionary.get(key));

    // Write a loop to repeatedly prompt user for (key,value) pairs until user types "quit"
    // put each pair into the Map as follows:

    while (true) {
      System.out.print("\nEnter a word: ");
      String word = kbd.readLine();

      if (word.equals("quit")) break;

      System.out.print("Enter its defintion: ");
      String definition = kbd.readLine();

      // YOUR CODE BELOW: ( 1 line of code ) to put a key/value pair into the dictionary
    }

    // Write a loop to retrieve and print all the keys and values from the Map
    // each line of output should be:  definition of <word> is: <definition>
    // We do this by first grabbing the set of keys via a call to .keySet() on the HashMap
    // Then we need a way to retrieve each individual key in that keySet.

    // For this we introduce the Set and Iterator. A call to dictionary.keySet() produces a
    // reference to the set of keys in the map. On that set we add a .iterator() call to get
    // an iterator.  Once the iterator is initialized we can grab the next element in the set via
    // a call to .next(). We can query the iterator to see if we have traversed the entire set
    // yet via a call to boolean method hasNext().

    // You may recognize some similarity to a Tokenizer that visits all the tokens one after
    // another and keeps track of when the stream has been exhausted.

    Iterator iter = dictionary.keySet().iterator();

    while (iter.hasNext()) {
      // retrieve the next  key from the HashMap by calling .next() on the iterator. Store that key
      // into a String
      // (remember to cast as String)

      // now use that key to .get() the associated value from the HashMap. Store it in a String
      // (again cast result as String)

      System.out.println("the defintion of " + key + ": " + value);
    }
  }
Example #22
0
  // 從DF算出IDF = log(N/(1+DF))
  public static HashMap<String, Double> IDF(HashMap<String, Integer> DF) {

    HashMap<String, Double> idf = new HashMap<String, Double>();
    for (String term : DF.keySet()) {
      idf.put(term, Math.log10((double) (1095 / (double) (1 + DF.get(term)))));
    }
    return idf;
  }
Example #23
0
  // 輸入TF 跟IDF算出TFIDF,並除以長度算出uni vector
  public static HashMap<String, Double> TFIDF(
      HashMap<String, Double> normalTF, HashMap<String, Double> IDF) {

    HashMap<String, Double> TFIDF = new HashMap<String, Double>();
    HashMap<String, Double> uniVector = new HashMap<String, Double>();
    for (String term : normalTF.keySet()) {
      TFIDF.put(term, (normalTF.get(term)) * IDF.get(term));
    }
    double length = 0;
    for (String term : TFIDF.keySet()) {
      length += Math.pow(TFIDF.get(term), 2);
    }
    length = Math.pow(length, 0.5);
    for (String term : TFIDF.keySet()) {
      uniVector.put(term, TFIDF.get(term) / length);
    }
    return uniVector;
  }
  public ArrayList<String> attackDamageAndKnockBack(
      Actor source,
      Arc2D.Double arc,
      Point mapPoint,
      int damage,
      int knockBackX,
      int knockBackY,
      int maxHits,
      String weaponType) {
    int dmg = 0;
    int hits = 0;
    Monster monster = null;
    ArrayList<String> monstersHit = new ArrayList<String>();

    try {
      for (String key : monsters.keySet()) {
        monster = (Monster) monsters.get(key);

        if (weaponType != null) {
          if (weaponType.equals("Net")) {
            damage = 1;
          }
        }

        dmg =
            monster.attackDamageAndKnockBack(
                source, arc, mapPoint, damage, knockBackX, knockBackY, weaponType);
        if (dmg > 0) {
          if (weaponType != null) {
            if (weaponType.equals("FangClaw")) {
              monster.poison(10);
            }
          }
          monstersHit.add(monster.getName());
          hits++;
        }
        if (hits >= maxHits) {
          break;
        }
      }
    } catch (ConcurrentModificationException concEx) {
      // another thread was trying to modify monsters while iterating
      // we'll continue and the new item can be grabbed on the next update
    }

    if (hits == 0) {
      if (source != null) {
        SoundClip cl = new SoundClip(registry, "Weapon/Miss", source.getCenterPoint());
      } else {
        SoundClip cl = new SoundClip("Weapon/Miss");
      }
    }

    return monstersHit;
  }
Example #25
0
  void send(String msg) {
    Iterator it = clients.keySet().iterator();

    while (it.hasNext()) {
      try {
        DataOutputStream out = (DataOutputStream) clients.get(it.next());
        out.writeUTF(msg);
      } catch (IOException e) {
      }
    }
  }
 /**
  * The main program for the DictCachService class
  *
  * @param args The command line arguments
  */
 public static void main(String[] args) {
   HashMap h = DictCachService.getInstance().getDictSql("select * from tab");
   HashMap h2 = DictCachService.getInstance().getDictSql("select * from tab");
   HashMap hash = DictCachService.getInstance().getDictSql("select code ,name from t_kouan");
   Iterator itor1 = hash.keySet().iterator();
   while (itor1.hasNext()) {
     String code = (String) itor1.next();
     String text = (String) hash.get(code);
     System.out.println(code + "  " + text);
   }
 }
  /**
   * This method is used to get String[] of the propertise file name that are cached.
   *
   * @return String[].
   */
  public static String[] getCachedPropertiesFilenames() {
    synchronized (cachedPropertyFiles) {
      int i = 0;
      String[] filenames = new String[cachedPropertyFiles.size()];

      for (Iterator e = cachedPropertyFiles.keySet().iterator(); e.hasNext(); i++) {
        filenames[i++] = (String) e.next();
      }
      return filenames;
    }
  }
Example #28
0
 private static void writeDuplicates() {
   Main.status("Writing duplicates.");
   if (!dup_post_list.isEmpty()) {
     Main.status(String.format("%s\t%s", "older_post", "newer_post"));
     for (Post post : dup_post_list.keySet()) {
       Main.status(String.format("%s\t%s", post.post_id, dup_post_list.get(post).post_id));
     }
   } else {
     Main.status("There are no duplicates.");
   }
   Main.status("Writing duplicates done.");
 }
Example #29
0
  public void exportDetectors() throws IOException { // doesn't work, remove when done

    for (int key : detectors.keySet()) {

      Detector d = detectors.get(key);
      FileOutputStream fileOut = new FileOutputStream("Detector " + key + ".ser");
      ObjectOutputStream out = new ObjectOutputStream(fileOut);
      out.writeObject(d);
      out.close();
      fileOut.close();
    }
  }
Example #30
0
 /** Reads fundamental diagram parameters from AIMSUN generated xml */
 public void readFundamentalDiagramsFromXML_AIMSUN() {
   for (int key : detectors.keySet()) {
     Detector d = detectors.get(key);
     // find the corresponding FD profile
     int i;
     for (i = 0;
         i
             < this.mainScenario
                 .getFundamentalDiagramProfileSet()
                 .getFundamentalDiagramProfile()
                 .size();
         i++) {
       if (Integer.parseInt(
               this.mainScenario
                   .getFundamentalDiagramProfileSet()
                   .getFundamentalDiagramProfile()
                   .get(i)
                   .getLinkId())
           == d.getLinkAssoc()) {
         break;
       }
     }
     BigDecimal vf =
         this.mainScenario
             .getFundamentalDiagramProfileSet()
             .getFundamentalDiagramProfile()
             .get(i)
             .getFundamentalDiagram()
             .get(0)
             .getFreeFlowSpeed();
     BigDecimal q_max =
         this.mainScenario
             .getFundamentalDiagramProfileSet()
             .getFundamentalDiagramProfile()
             .get(i)
             .getFundamentalDiagram()
             .get(0)
             .getCapacity();
     BigDecimal rhojam =
         this.mainScenario
             .getFundamentalDiagramProfileSet()
             .getFundamentalDiagramProfile()
             .get(i)
             .getFundamentalDiagram()
             .get(0)
             .getJamDensity();
     double w =
         q_max.doubleValue() / (rhojam.doubleValue() - q_max.doubleValue() / vf.doubleValue());
     d.getFdParams().setFD(vf.doubleValue(), w, q_max.doubleValue() / d.getNumberOfLanes());
     detectors.put(key, d);
   }
 }