コード例 #1
1
  /**
   * this is the core if the h2_OwnPreferences is not the first for CMP to call
   *
   * @param candidatesKB
   */
  public HashMap<Integer, RuleEngine> core(HashMap<Integer, rule_engine.RuleEngine> candidatesKB) {

    ArrayList<Integer> preference_count = new ArrayList<>();
    ArrayList<Integer> candidateID = new ArrayList<>();
    ArrayList<Integer> toberemoved = new ArrayList<>();
    for (int i : candidatesKB.keySet()) {
      if (!preference_count.isEmpty()) {
        if (countActiveOwnPreferences(candidatesKB.get(i)) < Collections.min(preference_count)) {
          preference_count.removeAll(preference_count);
          candidateID.removeAll(candidateID);
          preference_count.add(countActiveOwnPreferences(candidatesKB.get(i)));
          candidateID.add(i);
        } else if (countActiveOwnPreferences(candidatesKB.get(i))
            == Collections.min(preference_count)) {
          preference_count.add(countActiveOwnPreferences(candidatesKB.get(i)));
          candidateID.add(i);
        }
      } else {
        preference_count.add(countActiveOwnPreferences(candidatesKB.get(i)));
        candidateID.add(i);
      }
    }
    for (int i : candidatesKB.keySet()) {
      if (!candidateID.contains(i)) {

        toberemoved.add(i);
      }
    }
    for (int i : toberemoved) {
      candidatesKB.remove(i);
    }
    return candidatesKB;
  }
コード例 #2
0
ファイル: FileChecker.java プロジェクト: liu-ning/OSAT
  public static void main(String[] args) throws FileNotFoundException {

    // Change this value in order to load a different directory
    String directory = "C:/output/";

    File dir = new File(directory);
    File[] files = dir.listFiles(new XMLFilter());

    localTaz = new HashMap<String, TAZ>();

    for (File f : files) {
      String path = f.getPath();
      TAZ t = new TAZ(path);
      localTaz.put(t.getTAZ(), t);
    }

    // Change this value to change the output file
    PrintWriter results = new PrintWriter(new File("C:/longwalk.txt"));

    for (String i : localTaz.keySet()) {
      TAZ t = localTaz.get(i);
      for (String j : localTaz.keySet())
        if (t.getWalkDistance(j) > 1609.344) {
          results.println(i + "-" + j + " : " + t.getWalkDistance(j));
        }
    }
    results.flush();
    results.close();
  }
コード例 #3
0
  @Override
  public void typeCheck() {
    for (String type : mExtensions.keySet()) {
      int lineNum = mExtensions.get(type);
      Declaration d = mCompiler.getDeclaration(type);
      if (!(d instanceof ProtocolDeclaration)) {
        Compiler.typeError(fullName(), lineNum, type + " is not a Protocol");
      }
      if (type.equals(fullName())) {
        Compiler.typeError(fullName(), lineNum, fullName() + " cannot extend itself");
      }
      for (String f : ((ProtocolDeclaration) d).mOffsets.keySet()) {
        addFunction(f, lineNum);
      }
    }

    for (Declaration declaration : mImplementers.values()) {
      // TODO must not include static functions
      for (String f : mOffsets.keySet()) {
        if (!declaration.hasFunction(f)) {
          Compiler.typeError(
              declaration.fullName(),
              0,
              declaration.fullName() + " does not implement " + fullName() + ", missing " + f);
        }
      }
    }
  }
コード例 #4
0
  public void load(String key) {
    String idStr = "GPInitialPopulation";

    // Load last GUI settings from preferences
    HashMap settings = PreferencesManager.getAnalyserPageSettings(key + getClass().getName());

    Iterator iterator = settings.keySet().iterator();

    while (iterator.hasNext()) {
      String setting = (String) iterator.next();
      String value = (String) settings.get((Object) setting);

      this.loadCommon(setting, value);
    }

    HashMap settingsInitPop = PreferencesManager.getAnalyserPageSettings(key + idStr);

    Iterator iteratorInitPop = settingsInitPop.keySet().iterator();

    while (iteratorInitPop.hasNext()) {
      String settingInitPop = (String) iteratorInitPop.next();
      String valueInitPop = (String) settingsInitPop.get((Object) settingInitPop);

      GPPageInitialPopulationModule.load(valueInitPop);
    }
  }
コード例 #5
0
 /**
  * calculate the gene set similarity using the data given
  *
  * @param source
  * @param target
  * @param dataIn
  * @return
  */
 public double geneSetSim(
     HashSet<String> source, HashSet<String> target, HashMap<String, Double> dataIn) {
   double d = 0.0;
   HashMap<String, Double> back = new HashMap<String, Double>();
   for (int i = 0; i < source.size(); i++) {
     Object[] obj = source.toArray();
     double tmp = 0.0;
     for (int j = 0; j < target.size(); j++) {
       Object objt = target.toArray()[j];
       String key = obj[i].toString() + "->" + objt.toString();
       if (dataIn.keySet().contains(key)) {
         tmp = Math.max(tmp, dataIn.get(key).doubleValue());
         // 存储当前j所在基因的最大相似值
         Double dobj =
             back.containsKey(objt.toString())
                 ? Double.valueOf(
                     Math.max(
                         back.get(objt.toString()).doubleValue(), dataIn.get(key).doubleValue()))
                 : dataIn.get(key);
         back.put(objt.toString(), dobj);
       }
     }
     d += tmp;
   }
   for (String s : back.keySet()) {
     d += back.get(s).doubleValue();
   }
   return d / (source.size() + target.size() + 0.0001);
 }
コード例 #6
0
ファイル: AIMBuddy.java プロジェクト: nihed/magnetism
  /** @see com.levelonelabs.aim.XMLizable#writeState(Element) */
  public void writeState(Element emptyStateElement) {
    Document doc = emptyStateElement.getOwnerDocument();
    emptyStateElement.setAttribute("name", this.getName());
    emptyStateElement.setAttribute("group", this.getGroup());
    emptyStateElement.setAttribute("isBanned", Boolean.toString(this.isBanned()));

    Iterator roleit = roles.keySet().iterator();
    while (roleit.hasNext()) {
      String role = (String) roleit.next();
      Element roleElem = doc.createElement("role");
      roleElem.setAttribute("name", role);
      emptyStateElement.appendChild(roleElem);
    }

    Iterator prefs = preferences.keySet().iterator();
    while (prefs.hasNext()) {
      String pref = (String) prefs.next();
      Element prefElem = doc.createElement("preference");
      prefElem.setAttribute("name", pref);
      prefElem.setAttribute("value", (String) preferences.get(pref));
      emptyStateElement.appendChild(prefElem);
    }

    for (int i = 0; i < messages.size(); i++) {
      String message = (String) messages.get(i);
      Element messElem = doc.createElement("message");
      CDATASection data = doc.createCDATASection(message);
      messElem.appendChild(data);
      emptyStateElement.appendChild(messElem);
    }
  }
コード例 #7
0
  /**
   * Retorna a representação textual do contexto de execução.
   *
   * @return a representação textual do contexto de execução.
   */
  public String toString() {
    String resposta = null;
    Valor valor = null;
    Objeto objeto = null;
    Stack<HashMap<Id, Valor>> auxStack = new Stack<HashMap<Id, Valor>>();
    Stack<HashMap<ValorRef, Objeto>> auxStackObjeto = new Stack<HashMap<ValorRef, Objeto>>();

    while (!pilha.empty()) {
      HashMap<Id, Valor> aux = pilha.pop();
      auxStack.push(aux);
      for (Id id : aux.keySet()) {
        valor = aux.get(id);
        resposta = id + " " + valor + "\n";
      }
    }
    while (!auxStack.empty()) {
      pilha.push(auxStack.pop());
    }
    while (!pilhaObjeto.empty()) {
      HashMap<ValorRef, Objeto> aux = pilhaObjeto.pop();
      auxStackObjeto.push(aux);
      for (ValorRef valorRef : aux.keySet()) {
        objeto = aux.get(valorRef);
        resposta = valorRef + " " + objeto + "\n";
      }
    }
    while (!auxStackObjeto.empty()) {
      pilhaObjeto.push(auxStackObjeto.pop());
    }
    return resposta;
  }
コード例 #8
0
  public String getStorableRepr() {
    // MAKE THIS INSERT A ? when there aren't any values to put in
    String storableRepr = "";

    storableRepr += "existantElements|?";

    for (java.util.Iterator iter = existantElements.iterator(); iter.hasNext(); ) {
      storableRepr += ((String) iter.next()) + "?";
    }
    storableRepr += "|";

    storableRepr += "nonExistantElements|?";
    for (java.util.Iterator iter = nonExistantElements.iterator(); iter.hasNext(); ) {
      storableRepr += ((String) iter.next()) + "?";
    }
    storableRepr += "|";

    storableRepr += "propertyValues|?";
    for (java.util.Iterator iter = propertyValues.keySet().iterator(); iter.hasNext(); ) {
      String propertyKey = (String) iter.next();
      String valueRepr = (String) propertyValues.get(propertyKey);
      storableRepr += propertyKey + ":" + valueRepr + "?";
    }
    storableRepr += "|";

    storableRepr += "elementPositions|?";
    for (java.util.Iterator iter = elementPositions.keySet().iterator(); iter.hasNext(); ) {
      String elementKey = (String) iter.next();
      Integer valueRepr = (Integer) elementPositions.get(elementKey);
      storableRepr += elementKey + ":" + valueRepr + "?";
    }
    storableRepr += "|";

    return storableRepr;
  }
コード例 #9
0
ファイル: Process.java プロジェクト: blacklensama/1709
 private void updateLastActivePlace(CustomedPlace p) {
   if (lastActivePlace != null) {
     lastActivePlace.setInvalid(false);
     // 把输入弧置为invalid
     Set<String> pSet = ttpList.keySet();
     for (Iterator<String> it = pSet.iterator(); it.hasNext(); ) {
       String id = (String) it.next();
       String idArray[] = id.split(",");
       if (null != idArray
           && idArray.length > 1
           && null != idArray[1]
           && idArray[1].equals(String.valueOf(lastActivePlace.getId()))) {
         TransitionToPlace ttp = ttpList.get(id);
         if (ttp != null) ttp.invalid = true;
       }
     }
     // 把输出弧置为invalid
     pSet = pttList.keySet();
     for (Iterator<String> it = pSet.iterator(); it.hasNext(); ) {
       String id = (String) it.next();
       String idArray[] = id.split(",");
       if (null != idArray
           && idArray.length > 1
           && null != idArray[0]
           && idArray[0].equals(String.valueOf(lastActivePlace.getId()))) {
         PlaceToTransition ptt = pttList.get(id);
         if (ptt != null) ptt.invalid = true;
       }
     }
   }
   lastActivePlace = p;
 }
コード例 #10
0
  /** This methods extracts the scores from the target and decoy hits. */
  protected void extract() {
    // Initialize the score lists
    targetScores = new ArrayList<Double>();
    decoyScores = new ArrayList<Double>();
    omxFileTarget = new OmssaOmxFile(targetFile.getAbsolutePath());
    // Initialize the spectrum iterators
    HashMap<MSSpectrum, MSHitSet> targetResults = omxFileTarget.getSpectrumToHitSetMap();
    Iterator<MSSpectrum> targetIter = targetResults.keySet().iterator();

    // Target hits
    while (targetIter.hasNext()) {
      MSSpectrum msSpectrum = targetIter.next();
      MSHitSet msHitSet = targetResults.get(msSpectrum);
      List<MSHits> targetHits = msHitSet.MSHitSet_hits.MSHits;
      double lowestEValue = Double.POSITIVE_INFINITY;
      String peptideSequence = "";
      for (MSHits targetHit : targetHits) {
        if (targetHit.MSHits_evalue < lowestEValue) {
          lowestEValue = targetHit.MSHits_evalue;
          peptideSequence = targetHit.MSHits_pepstring;
        }
      }
      if (lowestEValue < Double.POSITIVE_INFINITY) {
        targetScores.add(lowestEValue);
        //    	     	String spectrumTitle =
        // formatSpectrumTitle(msSpectrum.MSSpectrum_ids.MSSpectrum_ids_E.get(0).toString());
        //    	    	searchHits.add(new CustomSearchHit(lowestEValue, peptideSequence,
        // spectrumTitle));
      }
    }

    // Sort the target scores ascending.
    Collections.sort(targetScores);

    // Help the GC:
    omxFileTarget = null;
    targetResults = null;
    targetIter = null;

    // Decoy
    omxFileDecoy = new OmssaOmxFile(decoyFile.getAbsolutePath());
    HashMap<MSSpectrum, MSHitSet> decoyResults = omxFileDecoy.getSpectrumToHitSetMap();
    Iterator<MSSpectrum> decoyIter = decoyResults.keySet().iterator();

    // Decoy hits
    while (decoyIter.hasNext()) {
      MSSpectrum msSpectrum = decoyIter.next();
      MSHitSet msHitSet = decoyResults.get(msSpectrum);
      List<MSHits> decoyHits = msHitSet.MSHitSet_hits.MSHits;
      double lowestEValue = Double.POSITIVE_INFINITY;
      for (MSHits decoyHit : decoyHits) {
        if (decoyHit.MSHits_evalue < lowestEValue) {
          lowestEValue = decoyHit.MSHits_evalue;
        }
      }
      if (lowestEValue < Double.POSITIVE_INFINITY) {
        decoyScores.add(lowestEValue);
      }
    }
  }
コード例 #11
0
ファイル: AlgebraView.java プロジェクト: avilleret/geogebra
  /** set labels on the tree */
  protected void setTreeLabels() {
    switch (getTreeMode()) {
      case DEPENDENCY:
        indNode.setUserObject(app.getPlain("FreeObjects"));
        model.nodeChanged(indNode);

        depNode.setUserObject(app.getPlain("DependentObjects"));
        model.nodeChanged(depNode);

        auxiliaryNode.setUserObject(app.getPlain("AuxiliaryObjects"));
        model.nodeChanged(auxiliaryNode);
        break;
      case TYPE:
        DefaultMutableTreeNode node;
        for (String key : typeNodesMap.keySet()) {
          node = typeNodesMap.get(key);
          node.setUserObject(app.getPlain(key));
          model.nodeChanged(node);
        }
        break;
      case LAYER:
        for (Integer key : layerNodesMap.keySet()) {
          node = layerNodesMap.get(key);
          node.setUserObject(app.getPlain("LayerA", key.toString()) + "TODO" + key);
          model.nodeChanged(node);
        }
        break;
      case ORDER:
        model.nodeChanged(rootOrder);
        break;
    }
  }
コード例 #12
0
 /**
  * Run the randomization test
  *
  * @param baseline
  * @param target
  * @return
  */
 public double test(HashMap<String, Double> target, HashMap<String, Double> baseline) {
   double[] b = new double[baseline.keySet().size()]; // baseline
   double[] t = new double[target.keySet().size()]; // target
   int c = 0;
   for (String key : baseline.keySet()) {
     b[c] = baseline.get(key).doubleValue();
     t[c] = target.get(key).doubleValue();
     c++;
   }
   double trueDiff = Math.abs(BasicStats.mean(b) - BasicStats.mean(t));
   double pvalue = 0.0;
   double[] pb = new double[baseline.keySet().size()]; // permutation of baseline
   double[] pt = new double[target.keySet().size()]; // permutation of target
   for (int i = 0; i < nPermutation; i++) {
     char[] bits = randomBitVector(b.length).toCharArray();
     for (int j = 0; j < b.length; j++) {
       if (bits[j] == '0') {
         pb[j] = b[j];
         pt[j] = t[j];
       } else {
         pb[j] = t[j];
         pt[j] = b[j];
       }
     }
     double pDiff = Math.abs(BasicStats.mean(pb) - BasicStats.mean(pt));
     if (pDiff >= trueDiff) pvalue += 1.0;
   }
   return pvalue / nPermutation;
 }
コード例 #13
0
ファイル: Warp.java プロジェクト: Riderj/ModTweaker
 public void apply() {
   if (type == RemoveType.BOTH) {
     for (Object key : ThaumcraftHelper.warpList.keySet()) {
       oldMap.put(key, ThaumcraftHelper.warpList.get(key));
     }
     ThaumcraftHelper.warpList.clear();
   } else if (type == RemoveType.ITEMS) {
     for (Object key : ThaumcraftHelper.warpList.keySet()) {
       if (key instanceof List) {
         oldMap.put(key, ThaumcraftHelper.warpList.get(key));
       }
     }
     for (Object key : oldMap.keySet()) {
       ThaumcraftHelper.warpList.remove(key);
     }
   } else if (type == RemoveType.RESEARCH) {
     for (Object key : ThaumcraftHelper.warpList.keySet()) {
       if (key instanceof String) {
         oldMap.put(key, ThaumcraftHelper.warpList.get(key));
       }
     }
     for (Object key : oldMap.keySet()) {
       ThaumcraftHelper.warpList.remove(key);
     }
   }
 }
コード例 #14
0
  public <B> void write(XElement element, ModeSettingsConverter<Location, B> converter) {
    Set<String> keys = new HashSet<String>();
    if (lastMaximizedLocation != null) {
      keys.addAll(lastMaximizedLocation.keySet());
    }
    if (lastMaximizedMode != null) {
      keys.addAll(lastMaximizedMode.keySet());
    }

    if (!keys.isEmpty()) {
      XElement xmaximized = element.addElement("maximized");

      for (String key : keys) {
        Path mode = lastMaximizedMode.get(key);
        Location location = lastMaximizedLocation.get(key);

        if (mode != null || location != null) {
          XElement xitem = xmaximized.addElement("item");
          xitem.addString("id", key);
          if (mode != null) {
            xitem.addElement("mode").setString(mode.toString());
          }
          if (location != null) {
            converter.writePropertyXML(
                converter.convertToSetting(location), xitem.addElement("location"));
          }
        }
      }
    }
  }
コード例 #15
0
  public void add_shapes_to_set(TreeSet<SegmentNode> ts[]) {
    SegmentNode int_entry[], p;

    for (Iterator<AllocNode> it_pts = pt_objs.keySet().iterator(); it_pts.hasNext(); ) {
      int_entry = find_points_to(it_pts.next());
      for (int i = 0; i < HeapInsIntervalManager.Divisions; ++i) {
        p = int_entry[i];
        while (p != null) {
          ts[0].add(p);
          p = p.next;
        }
      }
    }

    for (Iterator<HeapInsNode> it_flow = flowto.keySet().iterator(); it_flow.hasNext(); ) {
      int_entry = find_flowto(it_flow.next());
      for (int i = 0; i < HeapInsIntervalManager.Divisions; ++i) {
        p = int_entry[i];
        while (p != null) {
          ts[0].add(p);
          p = p.next;
        }
      }
    }
  }
コード例 #16
0
  /** Prints the sample collections that will be used in testing (for exporting purposes) */
  @Test(groups = "doc")
  @SuppressWarnings("unchecked")
  public void printSampleCollections() {
    String objective = "Sample Collections";
    System.out.println(String.format("Printing %s...", objective));

    for (DataType dataType : SAMPLE_COLLECTIONS.keySet()) {
      HashMap<DataType, Object> sampleValueMap =
          (HashMap<DataType, Object>) SAMPLE_COLLECTIONS.get(dataType);

      if (dataType.getName() == DataType.Name.MAP) {
        DataType typeArgument = sampleValueMap.keySet().iterator().next();
        HashMap<DataType, Object> sampleMap =
            (HashMap<DataType, Object>) sampleValueMap.get(typeArgument);

        Object mapKey = SAMPLE_DATA.get(typeArgument);
        Object mapValue = sampleMap.get(typeArgument);
        System.out.println(String.format("%1$-30s {%2$s : %3$s}", dataType, mapKey, mapValue));
      } else {
        DataType typeArgument = sampleValueMap.keySet().iterator().next();
        Object sampleValue = sampleValueMap.get(typeArgument);

        System.out.println(String.format("%1$-30s %2$s", dataType, sampleValue));
      }
    }

    System.out.println(String.format("\nEnd of %s\n\n", objective));
  }
コード例 #17
0
ファイル: EntranceActivity.java プロジェクト: dnlgby/Car_Data
  @Override
  public void onClick(View v) {
    if (v.getId() == R.id.app_connect_button) {
      // Intent intent = new Intent(getBaseContext(), CollectDataActivity.class);
      // startActivity(intent);;
      BluetoothHelper bluetoothHelper = BluetoothHelper.getInstance();
      final HashMap<String, String> pairedDevices = bluetoothHelper.GetPairedDevices();

      if (pairedDevices.isEmpty())
        Toast.makeText(this, "No paired devices found.", Toast.LENGTH_LONG).show();
      else
        SimpleDialogs.ChooseOption(
            this,
            pairedDevices.keySet().toArray(new String[pairedDevices.keySet().size()]),
            new DialogResponse() {
              @Override
              public void onDialogResponse(String deviceName) {
                String deviceAddress = pairedDevices.get(deviceName);
                Toast.makeText(
                        EntranceActivity.this, "Choosed device:" + deviceAddress, Toast.LENGTH_LONG)
                    .show();
                EntranceActivity.this.ConnectDevice(deviceAddress);
              }
            });
    }

    if (v.getId() == R.id.app_last_trips_button) {
      Intent intent = new Intent(getBaseContext(), LastTripsActivity.class);
      startActivity(intent);
    }
  }
コード例 #18
0
  public static HashMap<String, Integer> cutRanked(HashMap<String, Integer> content) {
    HashMap<String, Integer> elements = new HashMap<>();
    elements.putAll(content);

    while (elements.size() > 15) {
      String minimumKey = (String) elements.keySet().toArray()[0];
      int minimum = elements.get(minimumKey);

      for (String string : elements.keySet())
        if (elements.get(string) < minimum
            || (elements.get(string) == minimum && string.compareTo(minimumKey) < 0)) {
          minimumKey = string;
          minimum = elements.get(string);
        }

      elements.remove(minimumKey);
    }

    for (String string : new ArrayList<>(elements.keySet()))
      if (string != null)
        if (string.length() > 40) {
          int value = elements.get(string);
          elements.remove(string);
          elements.put(string.substring(0, 40), value);
        }

    return elements;
  }
コード例 #19
0
  public String getStatusLine() {
    StringBuffer sb = new StringBuffer();
    sb.append("********************\n");
    sb.append("**" + ExceptionUtil.sdf.format(new Date()) + "**\n");
    sb.append("********************\n");

    Set<String> set = statusMap.keySet();
    for (String key : set) {
      String value = statusMap.get(key);
      sb.append(key + " : " + value + "\n");
    }
    Set<String> set2 = addMap.keySet();
    for (String key : set2) {
      Long value = addMap.get(key);
      sb.append(key + " : " + value + "\n");
    }
    sb.append("====================\n");
    for (String boltkey : stbolt) {
      Long num1 = 1l;
      Long time1 = 1l;
      num1 = addMap.get(boltkey + ".W");
      time1 = addMap.get(boltkey + ".T");
      String line =
          "Message Num in " + boltkey + " :" + num1 + " avg time for 1W:" + time1 / (num1);
      sb.append(line + "\n");
    }
    sb.append("********************\n");
    return sb.toString();
  }
コード例 #20
0
  private static void mergeConfigMaps(
      final Map<String, String> source, final HashMap<String, String> destination) {
    checkNotNull(source, "source");
    checkNotNull(destination, "destination");

    if (source.isEmpty()) {
      return;
    }

    final Sets.SetView<String> sharedKeys =
        Sets.intersection(source.keySet(), destination.keySet());
    final Sets.SetView<String> newKeys = Sets.difference(source.keySet(), destination.keySet());

    // skip empty values in the source map
    // if they are already in the destination in order to
    // prevent overwrites of populated keys with empty ones
    sharedKeys
        .stream()
        .filter(key -> !source.get(key).trim().isEmpty() && !key.startsWith("#"))
        .forEach(key -> destination.put(key, source.get(key)));

    // Add new keys regardless of whether or not they're empty
    newKeys
        .stream()
        .filter(key -> !key.startsWith("#"))
        .forEach(key -> destination.put(key, source.get(key).trim()));
  }
コード例 #21
0
  private static List<String> getOTUSAtThreshold(
      HashMap<String, HashMap<String, Integer>> map, int threshold) throws Exception {

    HashMap<String, Integer> countMap = new HashMap<String, Integer>();

    for (String s : map.keySet()) {
      HashMap<String, Integer> innerMap = map.get(s);

      for (String possibleOtu : innerMap.keySet()) {
        Integer oldCount = countMap.get(possibleOtu);

        if (oldCount == null) oldCount = 0;

        oldCount += innerMap.get(possibleOtu);

        countMap.put(possibleOtu, oldCount);
      }
    }

    List<String> otuList = new ArrayList<String>();

    for (String s : countMap.keySet()) if (countMap.get(s) >= threshold) otuList.add(s);

    return otuList;
  }
コード例 #22
0
  public XMLComparePreferencePage() {
    super();

    fIdMaps = new HashMap();
    XMLPlugin plugin = XMLPlugin.getDefault();
    HashMap PluginIdMaps = plugin.getIdMaps();
    Set keySet = PluginIdMaps.keySet();
    for (Iterator iter = keySet.iterator(); iter.hasNext(); ) {
      String key = (String) iter.next();
      fIdMaps.put(key, ((HashMap) PluginIdMaps.get(key)).clone());
    }
    fIdMapsInternal = plugin.getIdMapsInternal();

    fIdExtensionToName = new HashMap();
    HashMap PluginIdExtensionToName = plugin.getIdExtensionToName();
    keySet = PluginIdExtensionToName.keySet();
    for (Iterator iter = keySet.iterator(); iter.hasNext(); ) {
      String key = (String) iter.next();
      fIdExtensionToName.put(key, PluginIdExtensionToName.get(key));
    }

    fOrderedElements = new HashMap();
    HashMap PluginOrderedElements = plugin.getOrderedElements();
    keySet = PluginOrderedElements.keySet();
    for (Iterator iter = keySet.iterator(); iter.hasNext(); ) {
      String key = (String) iter.next();
      fOrderedElements.put(key, ((ArrayList) PluginOrderedElements.get(key)).clone());
    }

    fOrderedElementsInternal = plugin.getOrderedElementsInternal();
  }
コード例 #23
0
  private XYZDataset createDataSet(HashBasedTable<String, String, Double> data) {

    MatrixSeries series =
        new MatrixSeries(
            "DataTable", roomToCodeMapping.keySet().size(), roomToCodeMapping.keySet().size());

    for (String source : roomToCodeMapping.keySet()) {
      Integer sourceId = roomToCodeMapping.get(source);

      for (String destination : roomToCodeMapping.keySet()) {

        Integer destinationId = roomToCodeMapping.get(destination);
        if (!data.contains(source, destination)) {
          series.update(sourceId, destinationId, -1.0);
        } else {
          double value;
          if (type == MarkovDataDialog.HeatMapType.COMPARISON)
            value = (data.get(source, destination) + 1.0) / 2; // Scale to 0 to 1 for comparison
          else value = data.get(source, destination);
          if (value < 0 || value > 1) {
            System.out.println(
                "***********Problem in value=" + value + "(" + source + "," + destination + ")");
          }
          series.update(sourceId, destinationId, value);
        }
      }
    }

    System.out.println("Room size = " + roomToCodeMapping.keySet().size());
    return new MatrixSeriesCollection(series);
  }
コード例 #24
0
  public HashMap<String, Double> getScore(
      HashMap<String, Integer> dicts,
      HashMap<String, HashMap<String, Integer>> values,
      boolean sw) {

    int topKsize = 1;
    if (sw) topKsize = Integer.MAX_VALUE;
    HashMap<String, Double> topK = new HashMap<String, Double>();
    Iterator<String> iditer = dicts.keySet().iterator();
    while (iditer.hasNext()) {
      String id = iditer.next();
      HashMap<String, Integer> hm = values.get(id);
      int div = 0;
      div = hm.keySet().size();
      double score = div;
      if (topK.keySet().size() < topKsize && div > 1) {
        topK.put(id, score);
      } else {
        String[] keys = topK.keySet().toArray(new String[topK.keySet().size()]);
        for (String key : keys) {
          if (topK.get(key) < score) {
            topK.remove(key);
            topK.put(id, score);
          }
        }
      }
    }
    return topK;
  }
コード例 #25
0
  // Time = O(n^2)
  public static Tuple getTriangle(int[] A) {
    if (A.length < 3) {
      return null;
    }

    HashMap<Integer, Integer> counts = new HashMap<>();
    for (int a : A) {
      incrementCount(counts, a, 1);
    }

    for (int a : counts.keySet()) {
      incrementCount(counts, a, -1);
      for (int b : counts.keySet()) {
        incrementCount(counts, b, -1);

        double c_d = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
        int c = (int) c_d;
        if ((c_d - c) == 0 && counts.containsKey(c) && counts.get(c) > 0) {
          return new Tuple(a, b, c);
        }
        incrementCount(counts, b, 1);
      }
      incrementCount(counts, a, 1);
    }
    return null;
  }
コード例 #26
0
 /** dump the <x,y> pairs it computed found */
 public void dumpMemory() {
   Double[] keys = memory.keySet().toArray(new Double[memory.keySet().size()]);
   Arrays.sort(keys);
   for (Double key : keys) {
     System.err.println(key + "\t" + memory.get(key));
   }
 }
コード例 #27
0
  @Override
  public void modifyWeight() {

    WeightInterface cI = WeightFactory.getParser(config);
    HashMap<String, Double> significant;
    String key = (String) config.prop.get("dateLimit");

    if (key != null && !key.equals("") && config.prop.get("cutoff").equals("linear")) {
      significant = cI.findDateSignificanceWords();
      if (significant != null && significant.size() > 0) {
        for (String word : significant.keySet()) {
          if (tfidf.containsKey(word)) {
            double number = tfidf.get(word);
            number = number * (significant.get(word) + 1);
            tfidf.put(word, number);
          }
        }
      }
    }
    key = (String) config.prop.get("counterLimit");
    if (key != null && !key.equals("")) {
      significant = cI.findCounterSignificanceWords();
      for (String word : significant.keySet()) {
        if (tfidf.containsKey(word)) {
          double number = tfidf.get(word);
          number = number * (significant.get(word) + 1);
          tfidf.put(word, number);
        }
      }
    }
  }
コード例 #28
0
ファイル: B572.java プロジェクト: suhasesturi/programs-java
 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)));
 }
コード例 #29
0
ファイル: FindWinner.java プロジェクト: cf1497/Google
  public static List<String> findTopKWinner(int time, Vector<LogEntry> logs, int k) {
    List<String> result = new ArrayList<String>();

    HashMap<String, Integer> map = new HashMap<String, Integer>();
    for (LogEntry log : logs) {
      if (log.time <= time) {
        if (map.containsKey(log.candidate)) map.put(log.candidate, map.get(log.candidate) + 1);
        else map.put(log.candidate, 1);
      }
    }

    ArrayList<Integer> a = new ArrayList<Integer>();
    for (String str : map.keySet()) a.add(map.get(str));

    // find top K in a

    // method1: Using PriorityQuene.  time complexity: (nlgn+k)

    // method2: Using quick select

    quickSelect(a, 0, a.size() - 1, a.size() - k + 1);
    System.out.println(a);

    for (int i = a.size() - k; i < a.size(); i++) {
      int value = a.get(i);
      for (String str : map.keySet()) {
        if (map.get(str) == value) result.add(str);
      }
    }

    return result;
  }
コード例 #30
0
  /** Dumps the entire contents of the cache to the Log. */
  protected void DumpMapData() {
    String Helper;
    Iterator<String> GroupIter;
    Iterator<SearchMap> PatternIterator;
    Iterator<String> CDIterator;
    SearchGroup tmpSearchGroup;
    SearchMap tmpSearchMap;
    String PrintHelper;
    int counter = 0;

    OpenRate.getOpenRateFrameworkLog()
        .info("Dumping Map Data for RegexMatchCache <" + getSymbolicName() + ">");
    OpenRate.getOpenRateFrameworkLog().info("Groups:");

    // Iterate thorough the entries in the group
    GroupIter = GroupCache.keySet().iterator();
    while (GroupIter.hasNext()) {
      Helper = GroupIter.next();
      OpenRate.getOpenRateFrameworkLog().info("  " + Helper);
    }

    // Now dump the data
    GroupIter = GroupCache.keySet().iterator();
    while (GroupIter.hasNext()) {
      Helper = GroupIter.next();
      OpenRate.getOpenRateFrameworkLog().info("Dumping group map data for <" + Helper + ">");
      tmpSearchGroup = GroupCache.get(Helper);
      PatternIterator = tmpSearchGroup.SearchGroup.iterator();

      while (PatternIterator.hasNext()) {
        OpenRate.getOpenRateFrameworkLog().info("===ENTRY " + counter + "===");
        counter++;
        PrintHelper = "  (";

        tmpSearchMap = PatternIterator.next();
        for (int i = 0; i < tmpSearchMap.matchPattern.length; i++) {
          PrintHelper =
              PrintHelper
                  + "["
                  + tmpSearchMap.matchType[i]
                  + ":"
                  + tmpSearchMap.matchPattern[i]
                  + ":"
                  + tmpSearchMap.matchValue[i]
                  + "] ";
        }

        // dump the result array
        PrintHelper += ") --> (";

        CDIterator = tmpSearchMap.Results.iterator();
        while (CDIterator.hasNext()) {
          PrintHelper = PrintHelper + CDIterator.next() + ",";
        }

        PrintHelper += ")";
        OpenRate.getOpenRateFrameworkLog().info(PrintHelper);
      }
    }
  }