/** {@inheritDoc} */
 public void putAll(Map<? extends Integer, ? extends Integer> map) {
   ensureCapacity(map.size());
   // could optimize this for cases when map instanceof THashMap
   for (Map.Entry<? extends Integer, ? extends Integer> entry : map.entrySet()) {
     this.put(entry.getKey().intValue(), entry.getValue().intValue());
   }
 }
Beispiel #2
1
 private Map<String, Object> query(HttpServletRequest req) {
   final Map<String, Object> map = new HashMap<>();
   for (Map.Entry<String, String[]> entry : req.getParameterMap().entrySet()) {
     map.put(entry.getKey(), entry.getValue());
   }
   return map;
 }
Beispiel #3
0
 /* Retorna um Map com os utilizadores existentes no sistema */
 public HashMap<String, User> getUsers() {
   HashMap<String, User> r = new HashMap<>();
   for (Map.Entry<String, User> entry : users.entrySet()) {
     r.put(entry.getKey(), entry.getValue());
   }
   return r;
 }
 public boolean equals(Object object) {
   if (!(object instanceof Map.Entry)) {
     return false;
   }
   Map.Entry entry = (Map.Entry) object;
   return compare(key, entry.getKey()) && compare(value, entry.getValue());
 }
Beispiel #5
0
  /*
   * Termina a realização da Tarefa.
   * Retorna true se foi terminada com sucesso false caso contrário
   */
  public boolean endTask(String id) throws InterruptedException {
    Map<String, Integer> objectsToSupply;
    String type;
    lock.lock();
    try {
      if (!this.tasksRunning.containsKey(Integer.valueOf(id))) {
        return false;
      } else {
        type = this.tasksRunning.get(Integer.valueOf(id));
        objectsToSupply = this.tasks.get(type).getObjects();
      }
    } finally {
      lock.unlock();
    }

    // Supply de todos os objetos
    for (Map.Entry<String, Integer> entry : objectsToSupply.entrySet()) {
      warehouse.supply(entry.getKey(), entry.getValue());
    }

    lock.lock();
    try {
      this.tasksRunning.remove(Integer.valueOf(id));
      this.tasks.get(type).signalP();
    } finally {
      lock.unlock();
    }

    return true;
  }
  private static InputStream generateSoundsJSON() throws IOException {
    OpenSecurity.logger.info(
        Minecraft.getMinecraft().mcDataDir + "\\mods\\OpenSecurity\\sounds\\alarms\\");

    JsonObject root = new JsonObject();
    for (Map.Entry<String, String> entry : sound_map.entrySet()) {
      JsonObject event = new JsonObject();
      event.addProperty("category", "master"); // put under the "record" category for sound options
      JsonArray sounds = new JsonArray(); // array of sounds (will only ever be one)
      JsonObject sound =
          new JsonObject(); // sound object (instead of primitive to use 'stream' flag)
      sound.addProperty(
          "name",
          new File(".")
              + "\\mods\\OpenSecurity\\sounds\\alarms\\"
              + entry.getValue().substring(0, entry.getValue().lastIndexOf('.'))); // path to file
      sound.addProperty("stream", false); // prevents lag for large files
      sounds.add(sound);
      event.add("sounds", sounds);
      root.add(
          entry.getValue().substring(0, entry.getValue().lastIndexOf('.')),
          event); // event name (same as name sent to ItemCustomRecord)
    }
    // System.out.println(new Gson().toJson(root));
    return new ByteArrayInputStream(new Gson().toJson(root).getBytes());
  }
  /**
   * Compares the specified Object with this Map for equality, as per the definition in the Map
   * interface.
   *
   * @param o object to be compared for equality with this hashtable
   * @return true if the specified Object is equal to this Map
   * @see Map#equals(Object)
   * @since 1.2
   */
  public synchronized boolean equals(Object o) {
    if (o == this) return true;

    if (!(o instanceof Map)) return false;
    Map<?, ?> t = (Map<?, ?>) o;
    if (t.size() != size()) return false;

    try {
      for (Map.Entry<K, V> e : entrySet()) {
        K key = e.getKey();
        V value = e.getValue();
        if (value == null) {
          if (!(t.get(key) == null && t.containsKey(key))) return false;
        } else {
          if (!value.equals(t.get(key))) return false;
        }
      }
    } catch (ClassCastException unused) {
      return false;
    } catch (NullPointerException unused) {
      return false;
    }

    return true;
  }
  /**
   * Prints the given map with nice line breaks.
   *
   * @param out the stream to print to
   * @param key the key that maps to the map in some other map
   * @param map the map to print
   */
  public static synchronized void debugPrint(PrintStream out, Object key, Map map) {
    debugPrintIndent(out);
    out.println(key + " = ");

    debugPrintIndent(out);
    out.println("{");
    ++debugIndent;

    for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();
      String childKey = (String) entry.getKey();
      Object childValue = entry.getValue();
      if (childValue instanceof Map) {
        verbosePrint(out, childKey, (Map) childValue);
      } else {
        debugPrintIndent(out);

        String typeName = (childValue != null) ? childValue.getClass().getName() : null;

        out.println(childKey + " = " + childValue + " class: " + typeName);
      }
    }
    --debugIndent;
    debugPrintIndent(out);
    out.println("}");
  }
Beispiel #9
0
 public static void main(String[] args) {
   try {
     if (args.length == 1) {
       URL url = new URL(args[0]);
       System.out.println("Content-Type: " + url.openConnection().getContentType());
       // 				Vector links = extractLinks(url);
       // 				for (int n = 0; n < links.size(); n++) {
       // 					System.out.println((String) links.elementAt(n));
       // 				}
       Set links = extractLinksWithText(url).entrySet();
       Iterator it = links.iterator();
       while (it.hasNext()) {
         Map.Entry en = (Map.Entry) it.next();
         String strLink = (String) en.getKey();
         String strText = (String) en.getValue();
         System.out.println(strLink + " \"" + strText + "\" ");
       }
       return;
     } else if (args.length == 2) {
       writeURLtoFile(new URL(args[0]), args[1]);
       return;
     }
   } catch (Exception e) {
     System.err.println("An error occured: ");
     e.printStackTrace();
     // 			System.err.println(e.toString());
   }
   System.err.println("Usage: java SaveURL <url> [<file>]");
   System.err.println("Saves a URL to a file.");
   System.err.println("If no file is given, extracts hyperlinks on url to console.");
 }
Beispiel #10
0
  /**
   * Get the value of the entry at the specified index in the archive.
   *
   * @param index The index.
   * @return The entry value at that index.
   */
  public byte[] getEntryValue(int index) {
    Set<Map.Entry<String, File>> entrySet = entries.entrySet();
    int i = 0;

    for (Map.Entry<String, File> entry : entrySet) {
      if (i == index) {
        File entryFile = entry.getValue();

        if (entryFile != null) {
          try {
            return FileUtils.readFile(entryFile);
          } catch (IOException e) {
            throw new IllegalStateException(
                "Unexpected error reading Archive file '" + entryFile.getAbsolutePath() + "'.", e);
          }
        } else {
          return null;
        }
      }

      i++;
    }

    throw new ArrayIndexOutOfBoundsException(index);
  }
Beispiel #11
0
  /**
   * Output the entries to the specified output folder on the file system.
   *
   * @param outputFolder The target output folder.
   * @throws java.io.IOException Write failure.
   */
  public void toFileSystem(File outputFolder) throws IOException {
    AssertArgument.isNotNull(outputFolder, "outputFolder");

    if (outputFolder.isFile()) {
      throw new IOException(
          "Cannot write Archive entries to '"
              + outputFolder.getAbsolutePath()
              + "'.  This is a normal file i.e. not a directory.");
    }
    if (!outputFolder.exists()) {
      outputFolder.mkdirs();
    }

    Set<Map.Entry<String, File>> entrySet = entries.entrySet();
    for (Map.Entry<String, File> entry : entrySet) {
      File archEntryFile = entry.getValue();
      byte[] fileBytes;
      File entryFile = new File(outputFolder, entry.getKey());

      if (archEntryFile != null) {
        fileBytes = FileUtils.readFile(archEntryFile);
        entryFile.getParentFile().mkdirs();
        FileUtils.writeFile(fileBytes, entryFile);
      } else {
        entryFile.mkdirs();
      }
    }
  }
Beispiel #12
0
  public CloudScriptObject eval(Context context) throws CloudScriptException {
    CloudScriptClass clazz = context.getCurrentClass();

    for (Map.Entry<String, String> entry : data.entrySet()) {
      final String key = entry.getKey();
      final String value = entry.getValue();

      if (!clazz.hasMethod(key)) {
        clazz.addMethod(
            key,
            new Method() {
              public CloudScriptObject call(
                  CloudScriptObject receiver, CloudScriptObject arguments[])
                  throws CloudScriptException {
                ValueObject content = new ValueObject(value);
                int numValue;

                try {
                  numValue = Integer.parseInt(value);
                  content = new ValueObject(numValue);
                } catch (NumberFormatException e) {
                }

                return content;
              }
            });
      }
    }
    return new ValueObject(this.content);
  }
 public void setHashMap(int start, List<LinkedHashMap<Integer, Double>> hMap) {
   for (int i = 0; i < hMap.size(); i++) {
     for (Map.Entry<Integer, Double> entry : hMap.get(i).entrySet()) {
       featureList.get(i).put(start + entry.getKey(), entry.getValue());
     }
   }
 }
  public void testIteration() {
    assertTrue(_nbhm.isEmpty());
    assertThat(_nbhm.put("k1", "v1"), nullValue());
    assertThat(_nbhm.put("k2", "v2"), nullValue());

    String str1 = "";
    for (Iterator<Map.Entry<String, String>> i = _nbhm.entrySet().iterator(); i.hasNext(); ) {
      Map.Entry<String, String> e = i.next();
      str1 += e.getKey();
    }
    assertThat("found all entries", str1, anyOf(is("k1k2"), is("k2k1")));

    String str2 = "";
    for (Iterator<String> i = _nbhm.keySet().iterator(); i.hasNext(); ) {
      String key = i.next();
      str2 += key;
    }
    assertThat("found all keys", str2, anyOf(is("k1k2"), is("k2k1")));

    String str3 = "";
    for (Iterator<String> i = _nbhm.values().iterator(); i.hasNext(); ) {
      String val = i.next();
      str3 += val;
    }
    assertThat("found all vals", str3, anyOf(is("v1v2"), is("v2v1")));

    assertThat(
        "toString works", _nbhm.toString(), anyOf(is("{k1=v1, k2=v2}"), is("{k2=v2, k1=v1}")));
  }
  /**
   * {@inheritDoc}
   *
   * @param ctx
   */
  @Override
  public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {
    super.prepareMarshal(ctx);

    if (ownedVals != null) {
      ownedValKeys = ownedVals.keySet();

      ownedValVals = ownedVals.values();

      for (Map.Entry<IgniteTxKey, CacheVersionedValue> entry : ownedVals.entrySet()) {
        GridCacheContext cacheCtx = ctx.cacheContext(entry.getKey().cacheId());

        entry.getKey().prepareMarshal(cacheCtx);

        entry.getValue().prepareMarshal(cacheCtx.cacheObjectContext());
      }
    }

    if (retVal != null && retVal.cacheId() != 0) {
      GridCacheContext cctx = ctx.cacheContext(retVal.cacheId());

      assert cctx != null : retVal.cacheId();

      retVal.prepareMarshal(cctx);
    }

    if (filterFailedKeys != null) {
      for (IgniteTxKey key : filterFailedKeys) {
        GridCacheContext cctx = ctx.cacheContext(key.cacheId());

        key.prepareMarshal(cctx);
      }
    }
  }
 /** PUBLIC: Add all of the elements. */
 public void putAll(Map map) {
   Iterator entriesIterator = map.entrySet().iterator();
   while (entriesIterator.hasNext()) {
     Map.Entry entry = (Map.Entry) entriesIterator.next();
     put(entry.getKey(), entry.getValue());
   }
 }
  private String searchOperator(int index) {
    String key = null;
    Set<Map.Entry<String, String>> set = Controller.oprHash.entrySet();
    String str = tokens[index];

    if ((str + tokens[index + 1]).equalsIgnoreCase("plusplus")) return "plus plus";
    if ((str + tokens[index + 1]).equalsIgnoreCase("minusminus")) return "minus minus";

    for (Map.Entry<String, String> me : set) {
      if ((key = me.getKey()).equalsIgnoreCase(str)) {
        tIndex++;
        return key;
      } else if (key.startsWith(str)) {
        String tempStr = str;
        for (int i = index + 1; i < tokens.length; i++) {
          tempStr = tempStr + " " + tokens[i];
          if (key.equalsIgnoreCase(tempStr)) {
            tIndex = i + 1;
            return key;
          }
        }
      }
    }
    return null;
  }
  public static <K, V extends Comparable<? super V>> Map<K, V> getSortedMap(Map<K, V> rankTerm) {
    System.out.println("Started Sorting..." + "@ " + new Date());

    List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(rankTerm.entrySet());
    Collections.sort(
        list,
        new Comparator<Map.Entry<K, V>>() {
          public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            // return (o1.getValue()).compareTo(o2.getValue());
            return Double.parseDouble(o1.getValue().toString())
                    > Double.parseDouble(o2.getValue().toString())
                ? -1
                : Double.parseDouble(o1.getValue().toString())
                        == Double.parseDouble(o2.getValue().toString())
                    ? 0
                    : 1;
          }
        });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list) {
      result.put(entry.getKey(), entry.getValue());
    }
    System.out.println("Stopped Sorting..." + "@ " + new Date());
    return result;
  }
Beispiel #19
0
 public void writeFoundWordsFile() throws IOException {
   PrintWriter pw = new PrintWriter(new FileWriter("src\\LW_5\\output2.txt"));
   for (Map.Entry entry : wordsNumStr.entrySet()) {
     pw.println("Word : " + entry.getKey() + ", String number : " + entry.getValue());
   }
   pw.close();
 }
Beispiel #20
0
  /**
   * Select/Deselect pack(s) based on packsData mapping. This is related to the onSelect and
   * onDeselect attributes for packs. User is not allowed to has a required pack for onSelect and
   * onDeselect.
   *
   * @param packsData
   */
  private void selectionUpdate(Map<String, String> packsData) {
    RulesEngine rules = installData.getRules();
    for (Map.Entry<String, String> packData : packsData.entrySet()) {
      int value, packPos;
      String packName = packData.getKey();
      String condition = packData.getValue();

      if (condition != null && !rules.isConditionTrue(condition)) {
        return; // Do nothing if condition is false
      }

      Pack pack;

      if (packName.startsWith("!")) {
        packName = packName.substring(1);
        pack = nameToPack.get(packName);
        packPos = getPos(packName);
        value = DESELECTED;
      } else {
        pack = nameToPack.get(packName);
        packPos = getPos(packName);
        value = SELECTED;
      }
      if (!pack.isRequired() && dependenciesResolved(pack)) {
        checkValues[packPos] = value;
      }
    }
  }
Beispiel #21
0
  public static void testDetermineMergeParticipantsAndMergeCoords4() {
    Address a = Util.createRandomAddress(),
        b = Util.createRandomAddress(),
        c = Util.createRandomAddress(),
        d = Util.createRandomAddress();
    org.jgroups.util.UUID.add(a, "A");
    org.jgroups.util.UUID.add(b, "B");
    org.jgroups.util.UUID.add(c, "C");
    org.jgroups.util.UUID.add(d, "D");

    View v1 = View.create(a, 1, a, b);
    View v2 = View.create(c, 1, c, d);

    Map<Address, View> map = new HashMap<>();
    map.put(a, v1);
    map.put(b, v1);
    map.put(d, v2);

    StringBuilder sb = new StringBuilder("map:\n");
    for (Map.Entry<Address, View> entry : map.entrySet())
      sb.append(entry.getKey() + ": " + entry.getValue() + "\n");
    System.out.println(sb);

    Collection<Address> merge_participants = Util.determineMergeParticipants(map);
    System.out.println("merge_participants = " + merge_participants);
    assert merge_participants.size() == 3;
    assert merge_participants.contains(a)
        && merge_participants.contains(c)
        && merge_participants.contains(d);

    Collection<Address> merge_coords = Util.determineMergeCoords(map);
    System.out.println("merge_coords = " + merge_coords);
    assert merge_coords.size() == 2;
    assert merge_coords.contains(a) && merge_coords.contains(c);
  }
Beispiel #22
0
 /** @return mapping from pack to row position */
 public Map<Pack, Integer> getPacksToRowNumbers() {
   Map<Pack, Integer> packsToRowNumbers = new HashMap<Pack, Integer>();
   for (Map.Entry<String, Integer> entry : nameToRow.entrySet()) {
     packsToRowNumbers.put(nameToPack.get(entry.getKey()), entry.getValue());
   }
   return packsToRowNumbers;
 }
Beispiel #23
0
  /**
   * Compares the specified Object with this Map for equality, as per the definition in the Map
   * interface.
   *
   * @param o object to be compared for equality with this hashtable
   * @return true if the specified Object is equal to this Map
   * @see Map#equals(Object)
   * @since 1.2
   */
  public synchronized boolean equals(Object o) {
    if (o == this) return true;

    if (!(o instanceof Map)) return false;
    Map<K, V> t = (Map<K, V>) o;
    if (t.size() != size()) return false;

    try {
      Iterator<Map.Entry<K, V>> i = entrySet().iterator();
      while (i.hasNext()) {
        Map.Entry<K, V> e = i.next();
        K key = e.getKey();
        V value = e.getValue();
        if (value == null) {
          if (!(t.get(key) == null && t.containsKey(key))) return false;
        } else {
          if (!value.equals(t.get(key))) return false;
        }
      }
    } catch (ClassCastException unused) {
      return false;
    } catch (NullPointerException unused) {
      return false;
    }

    return true;
  }
Beispiel #24
0
  static void itTest4(Map s, int size, int pos) {
    IdentityHashMap seen = new IdentityHashMap(size);
    reallyAssert(s.size() == size);
    int sum = 0;
    timer.start("Iter XEntry            ", size);
    Iterator it = s.entrySet().iterator();
    Object k = null;
    Object v = null;
    for (int i = 0; i < size - pos; ++i) {
      Map.Entry x = (Map.Entry) (it.next());
      k = x.getKey();
      v = x.getValue();
      seen.put(k, k);
      if (x != MISSING) ++sum;
    }
    reallyAssert(s.containsKey(k));
    it.remove();
    reallyAssert(!s.containsKey(k));
    while (it.hasNext()) {
      Map.Entry x = (Map.Entry) (it.next());
      Object k2 = x.getKey();
      seen.put(k2, k2);
      if (x != MISSING) ++sum;
    }

    reallyAssert(s.size() == size - 1);
    s.put(k, v);
    reallyAssert(seen.size() == size);
    timer.finish();
    reallyAssert(sum == size);
    reallyAssert(s.size() == size);
  }
    public boolean equals(Object o) {
      if (!(o instanceof Map.Entry)) return false;
      Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;

      return (key == null ? e.getKey() == null : key.equals(e.getKey()))
          && (value == null ? e.getValue() == null : value.equals(e.getValue()));
    }
Beispiel #26
0
  /**
   * Send Conference POST request to API endpoint which is used for allocating new conferences in
   * reservation system.
   *
   * @param ownerEmail email of new conference owner
   * @param mucRoomName full name of MUC room that is hosting the conference.
   *     {room_name}@{muc.server.net}
   * @return <tt>ApiResult</tt> that contains system response. It will contain <tt>Conference</tt>
   *     instance filled with data from the reservation system if everything goes OK.
   * @throws FaultTolerantRESTRequest.RetryExhaustedException When the number of retries to submit
   *     the request for the conference data is reached
   * @throws UnsupportedEncodingException When the room data have the encoding that does not play
   *     with UTF8 standard
   */
  public ApiResult createNewConference(String ownerEmail, String mucRoomName)
      throws FaultTolerantRESTRequest.RetryExhaustedException, UnsupportedEncodingException {
    Conference conference = new Conference(mucRoomName, ownerEmail, new Date());

    HttpPost post = new HttpPost(baseUrl + "/conference");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    Map<String, Object> jsonMap = conference.createJSonMap();

    for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
      nameValuePairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
    }

    post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF8"));

    logger.info("Sending post: " + jsonMap);

    CreateConferenceResponseParser conferenceResponseParser =
        new CreateConferenceResponseParser(conference);

    FaultTolerantRESTRequest faultTolerantRESTRequest =
        new FaultTolerantRESTRequest(post, conferenceResponseParser, retriesCreate, httpClient);

    return faultTolerantRESTRequest.submit();
  }
Beispiel #27
0
  /** Special version of remove for EntrySet using {@code Map.Entry.equals()} for matching. */
  final Entry<K, V> removeMapping(Object o) {
    if (!(o instanceof Map.Entry)) return null;

    Map.Entry<K, V> entry = (Map.Entry<K, V>) o;
    Object key = entry.getKey();
    int hash = (key == null) ? 0 : hash(key);
    int i = indexFor(hash, table.length);
    Entry<K, V> prev = table[i];
    Entry<K, V> e = prev;

    while (e != null) {
      Entry<K, V> next = e.next;
      if (e.hash == hash && e.equals(entry)) {
        modCount++;
        size--;
        if (prev == e) table[i] = next;
        else prev.next = next;
        e.recordRemoval(this);
        return e;
      }
      prev = e;
      e = next;
    }

    return e;
  }
Beispiel #28
0
  public static void main(String[] args) throws Exception {
    BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
    int N = Integer.parseInt(rd.readLine());
    Map<String, Integer> terms = new LinkedHashMap<String, Integer>(N * 2);

    for (int i = 0; i < N; i++) {
      String term = rd.readLine();
      Integer count = terms.get(term);
      count = (count == null) ? 1 : count + 1;
      terms.put(term, count);
    }

    int K = Integer.parseInt(rd.readLine());
    rd.close();

    Queue<TermCount> sortedTerms =
        new PriorityQueue<TermCount>(
            K,
            new Comparator<TermCount>() {
              @Override
              public int compare(TermCount x, TermCount y) {
                return (x.count == y.count) ? x.term.compareTo(y.term) : y.count - x.count;
              }
            });

    for (Map.Entry<String, Integer> entry : terms.entrySet()) {
      sortedTerms.add(new TermCount(entry.getKey(), entry.getValue()));
    }

    PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    for (int i = 0; i < K; i++) {
      pw.println(sortedTerms.poll().term);
    }
    pw.close();
  }
 StringBuilder addCanonicalHeaders(
     SortedMap<String, String> sortedFormattedHeaders, StringBuilder builder) {
   for (Map.Entry<String, String> entry : sortedFormattedHeaders.entrySet()) {
     builder.append(entry.getKey()).append(':').append(entry.getValue()).append('\n');
   }
   return builder;
 }
  int Query() {
    int minimum = 100001;

    visited = new boolean[V];
    Arrays.fill(visited, false);

    depth = new int[V];
    Arrays.fill(depth, -1);

    low = new int[V];
    Arrays.fill(low, -1);

    parent = new int[V];
    Arrays.fill(parent, -1);

    articulationPoints = new TreeMap<Integer, Boolean>();

    getArticulationPoints(0, 0);

    for (Map.Entry<Integer, Boolean> entry : articulationPoints.entrySet()) {
      int i = (int) entry.getKey();
      if (RatingScore[i] < minimum) {
        minimum = RatingScore[i];
      }
    }

    return minimum != 100001 ? minimum : -1;
  }