public Map<Integer, Integer> numCedulas(int valor) throws Exception {

    int cem;
    int cinquenta;
    int vinte;
    int dez;
    int aux;

    cem = valor / 100;
    aux = valor % 100;

    cinquenta = aux / 50;
    aux = aux % 50;

    vinte = aux / 20;
    aux = aux % 20;

    dez = aux / 10;
    aux = aux % 10;

    if (aux != 0) {
      throw new Exception("Valor inválido");
    }

    cedulas.replace(100, cem);
    cedulas.replace(50, cinquenta);
    cedulas.replace(20, vinte);
    cedulas.replace(10, dez);

    return cedulas;
  }
Esempio n. 2
0
 Map<Character, Double> getProbabilities(String text) {
   Map<Character, Double> probabilityMap = new HashMap<>();
   char[] chars = text.toCharArray();
   for (char ch : chars) {
     if (probabilityMap.containsKey(ch)) probabilityMap.replace(ch, probabilityMap.get(ch) + 1.0);
     else probabilityMap.put(ch, 1.0);
   }
   probabilityMap.forEach((k, v) -> probabilityMap.replace(k, v / text.length()));
   return probabilityMap;
 }
  private void prepareData(GitData gitData, List<Repository> repositories, User user)
      throws IOException {
    UserDetail userDetail = new UserDetail();
    userDetail.setName(user.getLogin());
    userDetail.setAvatarUrl(user.getAvatarUrl());
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy");
    userDetail.setCreatedAt(simpleDateFormat.format(user.getCreatedAt()));
    userDetail.setEmail(user.getEmail());
    userDetail.setFollower(user.getFollowers());
    userDetail.setDiskUsage(user.getDiskUsage());

    gitData.setUser(userDetail);

    Map<String, Integer> usedLanguages = new HashMap<>();
    for (Repository repository : repositories) {
      String language = (repository.getLanguage() == null) ? "Unknown" : repository.getLanguage();
      if (usedLanguages.containsKey(language)) {
        int count = usedLanguages.get(language);
        usedLanguages.replace(language, ++count);
      } else {
        usedLanguages.put(language, 1);
      }
    }

    gitData.setUsedLanguages(usedLanguages);
  }
 public String execute() {
   listBooks.clear();
   System.out.println(searchKey + " " + searchDesc);
   if (searchDesc == null) {
     return ERROR;
   } else {
     if (searchKey.equals("BookName")) {
       bookResult = readBook.readBookByName(searchDesc);
     } else if (searchKey.equals("ISBN")) {
       bookResult.add(readBook.readBookByIsbn(searchDesc));
     } else if (searchKey.equals("Writer")) {
       bookResult = readBook.readBookByWriter(searchDesc);
     } else if (searchKey.equals("Publisher")) {
       bookResult = readBook.readBookByPublisher(searchDesc);
     } else if (searchKey.equals("PublishYear")) {
       bookResult = readBook.readBookByYear(searchDesc);
     } else if (searchKey.equals("Category")) {
       bookResult = readBook.getBookByCat(searchDesc);
     } else return ERROR;
   }
   int minimum =
       (page + 1) * pageSize > bookResult.size() ? bookResult.size() : (page + 1) * pageSize;
   System.out.println(page);
   for (int i = page * pageSize; i < minimum; i++) {
     listBooks.add(bookResult.get(i));
   }
   ActionContext actionContext = ActionContext.getContext();
   Map<String, Object> session = actionContext.getSession();
   if (session.get("listSize") != null) session.remove("listSize");
   session.put("listSize", bookResult.size());
   session.replace("page", page);
   return SUCCESS;
 }
Esempio n. 5
0
  public static LayoutContent displayHome(spark.Request request, Configuration cfg) {
    String html = "";
    Map<String, String> root = Tools.listLayoutMap();
    root.replace("msg", DBH.getMsg(request.session().id()));
    Template temp;
    try {
      temp = cfg.getTemplate("user-home.htm");
      Writer out = new StringWriter();
      temp.process(root, out);
      html = out.toString();
    } catch (IOException | TemplateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      html = e.getMessage();
    }
    HashMap<String, String> options = new HashMap<String, String>();
    options.put("addBtn", Tools.getAddBtn("/tramites/agregar", "Iniciar Trámite"));
    options.put(
        "toolBar",
        Tools.getToolbarItem("/tramites/agregar", "Iniciar Trámite", "", "btn red darken-3")
            + Tools.getToolbarItem("/tramites", "Trámites", "", "btn green darken-3"));

    LayoutContent lc = new LayoutContent(html, options);
    return lc;
  }
  @Override
  public synchronized void alterDatabase(String databaseName, Database newDatabase) {
    String newDatabaseName = newDatabase.getName();

    if (databaseName.equals(newDatabaseName)) {
      if (databases.replace(databaseName, newDatabase) == null) {
        throw new SchemaNotFoundException(databaseName);
      }
      return;
    }

    Database database = databases.get(databaseName);
    if (database == null) {
      throw new SchemaNotFoundException(databaseName);
    }
    if (databases.putIfAbsent(newDatabaseName, database) != null) {
      throw new SchemaAlreadyExistsException(newDatabaseName);
    }
    databases.remove(databaseName);

    rewriteKeys(relations, name -> new SchemaTableName(newDatabaseName, name.getTableName()));
    rewriteKeys(views, name -> new SchemaTableName(newDatabaseName, name.getTableName()));
    rewriteKeys(partitions, name -> name.withSchemaName(newDatabaseName));
    rewriteKeys(tablePrivileges, name -> name.withDatabase(newDatabaseName));
  }
Esempio n. 7
0
  /**
   * Agrupa les estadístiques realitzant mitjes aritmètiques (AVG)
   *
   * <p>PRECONDICIÓ: És necessari que la llista estigui ordenada per 'keyAgrupadora'.
   *
   * @param llistaEstadistiques List de Maps a agrupar
   * @param keyAgrupadora key per la qual s'aplicarà el Group By (típicament el codi de pregunta, o
   *     de qüestionari)
   * @param keyTotalAgrupacions key que s'afegirà a cada Map resultant indicant la quantitat de Maps
   *     agrupats (COUNT)
   * @param keysAgrupades conjunt de keys a agrupar (AVG)
   * @return
   */
  private List<Map<String, Object>> agrupaEstadistiquesPer(
      List<Map<String, Object>> llistaEstadistiques,
      String keyAgrupadora,
      String keyTotalAgrupacions,
      Set<String> keysAgrupades) {
    List<Map<String, Object>> llistaEstadistiquesAgrupat = new ArrayList<Map<String, Object>>();
    Map<String, Object> mapAux = new HashMap<String, Object>();

    // index acumulador (per saber quants Maps iguals hi ha hagut, és a dir, per saber entre quant
    // dividir)
    int n = 1;

    for (Map<String, Object> map : llistaEstadistiques) {
      if (mapAux.isEmpty()) mapAux = new HashMap<String, Object>(map);
      else {
        // comparam els maps, per veure si els hem de juntar.
        if ((map.get(keyAgrupadora)).equals(mapAux.get(keyAgrupadora))) {
          // Hem d'agrupar map amb mapAux i deixar el resultat a mapAux
          for (String clau : keysAgrupades)
            mapAux.put(clau, ((Float) mapAux.get(clau)) + ((Float) map.get(clau)));
          n++;
        } else {
          // Dividim entre el total d'instàncies i enviam a la llista d'agrupats
          for (String clau : keysAgrupades) mapAux.replace(clau, ((Float) mapAux.get(clau)) / n);

          // Afegim el num total d'agrupacions trobades
          if (keyTotalAgrupacions != null) mapAux.put(keyTotalAgrupacions, new Integer(n));
          llistaEstadistiquesAgrupat.add(mapAux);

          // Actualitzam el nou mapAux i l'index acumulador
          mapAux = new HashMap<String, Object>(map);
          n = 1;
        }
      }
    }

    // inserim el darrer mapAux del procés
    if (!mapAux.isEmpty()) {
      for (String clau : keysAgrupades) mapAux.replace(clau, ((Float) mapAux.get(clau)) / n);
      if (keyTotalAgrupacions != null) mapAux.put(keyTotalAgrupacions, new Integer(n));
      llistaEstadistiquesAgrupat.add(mapAux);
    }

    return llistaEstadistiquesAgrupat;
  }
Esempio n. 8
0
  public void setCustomizationVariable(String type, byte value) {
    if (customizationVariables.containsKey(type)) {
      customizationVariables.replace(type, value);
    } else {
      customizationVariables.put(type, value);
    }

    setCustomization(getCustomizationBytes());
  }
  /**
   * Web service endpoint to update a single 'SimpleObject' entity. The HTTP request body is
   * expected to contain a 'SimpleObject' in JSON format. The object is updated in the data
   * repository.
   *
   * <p>If updated successfully, the persisted Greeting is returned as JSON with HTTP status 200.
   *
   * <p>If not found, the service returns an empty response body and HTTP status 404.
   *
   * <p>If not updated successfully, the service returns an empty response body with HTTP status
   * 500.
   *
   * @param simpleObject The SimpleObject to be updated.
   * @return A ResponseEntity containing a single SimpleObject, if updated successfully, and a HTTP
   *     status code as described in the method comment.
   * @throws Exception Thrown if a problem occurs completing the request.
   */
  @RequestMapping(
      value = "/tutorial/simple/{id}",
      method = RequestMethod.PUT,
      consumes = MediaType.APPLICATION_JSON_VALUE,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<SimpleObject> updateSimpleObject(@RequestBody SimpleObject simpleObject) {

    SimpleObject savedSimpleObject = simpleObjectMap.replace(simpleObject.getId(), simpleObject);
    return new ResponseEntity<>(savedSimpleObject, HttpStatus.OK);
  }
 @Override
 public void addHeartbeat(Heartbeat gb, Instant timestamp) {
   LOGGER.debug(
       "Updating exsisting heartbeat for customer {} and network, current timestamp: {}",
       new Object[] {gb.getCustomer(), gb.getNetwork(), timestamp.toString()});
   if (heartbeatMap.containsKey(gb)) {
     heartbeatMap.replace(gb, timestamp);
   } else {
     heartbeatMap.put(gb, timestamp);
   }
 }
Esempio n. 11
0
  // Function who delete an item and display a message
  public void deleteItem(Item i) {
    int numberOfOccurenceItem = inventory.get(i);

    if (numberOfOccurenceItem > 1) {
      inventory.replace(i, (numberOfOccurenceItem - 1));
      displayBlue("Un exemplaire de l'objet à été supprimé!");
    } else {
      inventory.remove(i);
      displayBlue("L'objet à été supprimé de l'inventaire!");
    }
  }
  /**
   * 预先计算出每个关键字出现的概率
   *
   * @param map 所有分类总的数据集
   * @param keyProbablityMap 每个特征值key的出现概率
   */
  public void preCalculateKeyProbablity(
      Map<String, ArrayList<ArrayList<String>>> map, Map<String, Double> keyProbablityMap) {
    if (map == null || keyProbablityMap == null) {
      return;
    }

    Object[] classes = map.keySet().toArray();
    String key = "";
    int totleKeyCount = 0;
    int mapSize = map.size();
    for (int i = 0; i < mapSize; i++) {
      ArrayList<ArrayList<String>> classify = map.get(classes[i]);
      ArrayList<String> featureVector = null; // 分类中的某一特征向量
      int classifySize = classify.size();
      for (int j = 0; j < classifySize; j++) {
        featureVector = classify.get(j);
        int featureVectorSize = featureVector.size();
        for (int k = 0; k < featureVectorSize; k++) {
          key = featureVector.get(k);
          totleKeyCount++;
          if (keyProbablityMap.get(key) == null) {
            keyProbablityMap.put(key, 1.0);
          } else {
            keyProbablityMap.replace(key, keyProbablityMap.get(key) + 1.0);
          }
        }
      }
    }

    if (totleKeyCount == 0) {
      return;
    }

    Set<String> keys = keyProbablityMap.keySet();
    for (String string : keys) {
      keyProbablityMap.replace(string, keyProbablityMap.get(string) / totleKeyCount);
    }
  }
Esempio n. 13
0
  public Map<String, Double> getPlaceStatsForUser(User u) {
    DBObject queryObject = new BasicDBObject("authorName", u.getUsername());
    String map =
        "function(){"
            + "var place = this.place;"
            + "if(place != null){"
            + "if(place === ''){"
            + "place = 'Empty';"
            + "}"
            + "else if(place !== 'Sofia' && place !== 'Plovdiv' && place !== 'Varna' && place !== 'Burgas'){"
            + "place = 'Other';"
            + "}"
            + "}"
            + "else {"
            + "place = 'Empty';"
            + "}"
            + "emit(place, 1);"
            + "}";

    String reduce = "function(k, v){ return Array.sum(v); }";
    DBCollection collection = datastore.getCollection(Message.class);
    MapReduceCommand mrc =
        new MapReduceCommand(
            collection, map, reduce, null, MapReduceCommand.OutputType.INLINE, queryObject);

    MapReduceOutput output = collection.mapReduce(mrc);
    Integer count = collection.find(queryObject).count();

    Map<String, Double> result = new HashMap<>();
    result.put("Total", count.doubleValue());
    result.put("Burgas", 0.0);
    result.put("Varna", 0.0);
    result.put("Sofia", 0.0);
    result.put("Plovdiv", 0.0);
    result.put("Other", 0.0);
    result.put("Empty", 0.0);
    output
        .results()
        .forEach((DBObject o) -> result.replace((String) o.get("_id"), (Double) o.get("value")));

    return result;
  }
Esempio n. 14
0
  public Statistics getStatistics() {
    int totalMatches = 0;
    int totalSets = 0;
    int totalPoints = 0;
    int totalPlayers = 0;

    Map<Player, Integer> scoreboard = new HashMap<>();

    List<Match> matches = matchManager.all();
    totalMatches = matches.size();
    for (Match match : matches) {
      List<Set> sets = match.getSets();
      totalSets += sets.size();
      for (Set set : sets) {
        totalPoints += set.getScorePlayer1();
        totalPoints += set.getScorePlayer2();
      }

      System.out.println("Match.getWinner() = " + match.getWinner());
      if (match.getWinner() != null) {
        if (scoreboard.containsKey(match.getWinner())) {
          int current = scoreboard.get(match.getWinner());
          scoreboard.replace(match.getWinner(), ++current);
        } else {
          scoreboard.put(match.getWinner(), 1);
        }
      }
    }

    List<Player> players = playerManager.all();
    totalPlayers = players.size();

    Statistics statistics = new Statistics();
    statistics.setTotalMatches(totalMatches);
    statistics.setTotalSets(totalSets);
    statistics.setTotalPoints(totalPoints);
    statistics.setTotalPlayers(totalPlayers);
    statistics.setPlayerWins(sortByValue(scoreboard));
    return statistics;
  }
  @Override
  public synchronized void alterTable(String databaseName, String tableName, Table newTable) {
    SchemaTableName oldName = new SchemaTableName(databaseName, tableName);
    SchemaTableName newName = new SchemaTableName(newTable.getDbName(), newTable.getTableName());

    // if the name did not change, this is a simple schema change
    if (oldName.equals(newName)) {
      if (relations.replace(oldName, newTable) == null) {
        throw new TableNotFoundException(oldName);
      }
      return;
    }

    // remove old table definition and add the new one
    Table table = relations.get(oldName);
    if (table == null) {
      throw new TableNotFoundException(oldName);
    }

    if (relations.putIfAbsent(newName, newTable) != null) {
      throw new TableAlreadyExistsException(newName);
    }
    relations.remove(oldName);
  }
Esempio n. 16
0
  /** constructASGraph Task 3 */
  private void annotateASGraph() {
    // algorithm 1
    // phase 2
    for (Map.Entry<String, ASPath> entry : asPathMap.entrySet()) {
      ASPath path = entry.getValue();
      AS[] ases = path.getAses();
      if (ases.length == 1) {
        continue;
      }
      int j = 0;
      int maxdegree = 0;
      for (int i = 0; i < ases.length; i++) {
        if (ases[i].getDegree() > maxdegree) {
          maxdegree = ases[i].getDegree();
          j = i;
        }
      }
      for (int i = 0; i < j; i++) {
        Map<Integer, Integer> transitMap = ases[i].getTransit();
        if (transitMap.containsKey(ases[i + 1].getNumber())) {
          Integer transit = transitMap.get(ases[i + 1].getNumber());
          transit = transit + 1;
          transitMap.replace(ases[i + 1].getNumber(), transit);
        } else {
          System.err.println(
              "AS "
                  + ases[i].getNumber()
                  + " do not contain transit of AS "
                  + ases[i + 1].getNumber());
          transitMap.put(ases[i + 1].getNumber(), 1);
        }
      }

      for (int i = j; i < ases.length - 1; i++) {
        Map<Integer, Integer> transitMap = ases[i + 1].getTransit();
        if (transitMap.containsKey(ases[i].getNumber())) {
          Integer transit = transitMap.get(ases[i].getNumber());
          transit = transit + 1;
          transitMap.replace(ases[i].getNumber(), transit);
        } else {
          System.err.println(
              "AS "
                  + ases[i + 1].getNumber()
                  + " do not contain transit of AS "
                  + ases[i].getNumber());
          transitMap.put(ases[i].getNumber(), 1);
        }
      }
    }
    // phase 3
    for (Map.Entry<String, ASPath> entry : asPathMap.entrySet()) {
      ASPath path = entry.getValue();
      AS[] ases = path.getAses();
      if (ases.length == 1) {
        continue;
      }
      for (int i = 0; i < ases.length - 1; i++) {
        Map<Integer, Integer> transFor_ui = ases[i].getTransit();
        Map<Integer, Integer> transFor_ui1 = ases[i + 1].getTransit();
        Integer ui = ases[i].getNumber();
        Integer ui1 = ases[i + 1].getNumber();
        Map<Integer, Relationship> edge_ui = ases[i].getEdge();
        Map<Integer, Relationship> edge_ui1 = ases[i + 1].getEdge();

        if ((transFor_ui1.get(ui) > Constants.L && transFor_ui.get(ui1) > Constants.L)
            || (transFor_ui.get(ui1) <= Constants.L
                && transFor_ui.get(ui1) > 0
                && transFor_ui1.get(ui) <= Constants.L
                && transFor_ui1.get(ui) > 0)) {
          edge_ui.replace(ui1, Relationship.S2S);
          edge_ui1.replace(ui, Relationship.S2S);
        } else if (transFor_ui1.get(ui) > Constants.L || transFor_ui.get(ui1) == 0) {
          edge_ui.replace(ui1, Relationship.P2C);
          edge_ui1.replace(ui, Relationship.C2P);
        } else if (transFor_ui.get(ui1) > Constants.L || transFor_ui1.get(ui) == 0) {
          edge_ui.replace(ui1, Relationship.C2P);
          edge_ui1.replace(ui, Relationship.P2C);
        }
      }
    }

    // algorithm 2, annotating p2p relationship
    // Phase 2
    for (Map.Entry<String, ASPath> entry : asPathMap.entrySet()) {
      ASPath path = entry.getValue();
      AS[] ases = path.getAses();
      if (ases.length == 1) {
        continue;
      }
      int j = 0;
      int maxdegree = 0;
      for (int i = 0; i < ases.length; i++) {
        if (ases[i].getDegree() > maxdegree) {
          maxdegree = ases[i].getDegree();
          j = i;
        }
      }

      for (int i = 0; i < j - 2; i++) {
        Map<Integer, Integer> notPeer_ui = ases[i].getNotpeering();
        if (notPeer_ui.containsKey(ases[i + 1].getNumber())) {
          notPeer_ui.replace(ases[i + 1].getNumber(), 1);
        } else {
          System.err.println(
              "AS "
                  + ases[i].getNumber()
                  + " do not contain notpeer of AS "
                  + ases[i + 1].getNumber());
          notPeer_ui.put(ases[i + 1].getNumber(), 1);
        }
      }

      for (int i = j + 1; i < ases.length - 1; i++) {
        Map<Integer, Integer> notPeer_ui = ases[i].getNotpeering();
        if (notPeer_ui.containsKey(ases[i + 1].getNumber())) {
          notPeer_ui.replace(ases[i + 1].getNumber(), 1);
        } else {
          System.err.println(
              "AS "
                  + ases[i].getNumber()
                  + " do not contain notpeer of AS "
                  + ases[i + 1].getNumber());
          notPeer_ui.put(ases[i + 1].getNumber(), 1);
        }
      }

      if (j > 0 && j < ases.length - 1) {
        Map<Integer, Relationship> edgeMap_uj = ases[j].getEdge();
        Map<Integer, Relationship> edgeMap_uj_1 = ases[j - 1].getEdge();
        if (edgeMap_uj_1.get(ases[j].getNumber()) != Relationship.S2S
            && edgeMap_uj.get(ases[j + 1].getNumber()) != Relationship.S2S) {
          if (ases[j - 1].getDegree() > ases[j + 1].getDegree()) {
            ases[j].getNotpeering().replace(ases[j + 1].getNumber(), 1);
          } else {
            ases[j - 1].getNotpeering().replace(ases[j].getNumber(), 1);
          }
        }
      }
    }

    // Phase 3
    for (Map.Entry<String, ASPath> entry : asPathMap.entrySet()) {
      ASPath path = entry.getValue();
      AS[] ases = path.getAses();
      if (ases.length == 1) {
        continue;
      }

      for (int j = 0; j < ases.length - 1; j++) {
        Map<Integer, Integer> notPeering_uj = ases[j].getNotpeering();
        Map<Integer, Integer> notPeering_uj1 = ases[j + 1].getNotpeering();
        AS uj = ases[j];
        AS uj1 = ases[j + 1];
        if (notPeering_uj.get(uj1.getNumber()) != 1
            && notPeering_uj1.get(uj.getNumber()) != 1
            && (int) (uj.getDegree() / uj1.getDegree()) < Constants.R
            && (double) ((double) uj.getDegree() / (double) uj1.getDegree())
                > (double) ((double) 1 / (double) Constants.R)) {
          uj.getEdge().replace(uj1.getNumber(), Relationship.P2P);
          uj1.getEdge().replace(uj.getNumber(), Relationship.P2P);
        }
      }
    }

    // output
    int counter = 0;
    for (Map.Entry<String, ASPath> entry : asPathMap.entrySet()) {
      ASPath path = entry.getValue();
      AS[] ases = path.getAses();
      if (ases.length == 1) continue;
      for (int i = 0; i < ases.length - 1; i++) {
        switch (ases[i].getEdge().get(ases[i + 1].getNumber())) {
          case P2P:
            System.out.println(ases[i].getNumber() + " " + ases[i + 1].getNumber() + " p2p");
            break;
          case C2P:
            System.out.println(ases[i].getNumber() + " " + ases[i + 1].getNumber() + " c2p");
            break;
          case S2S:
            System.out.println(ases[i].getNumber() + " " + ases[i + 1].getNumber() + " s2s");
            break;
          case P2C:
            System.out.println(ases[i].getNumber() + " " + ases[i + 1].getNumber() + " p2c");
            break;
          case UNKOWN:
            System.out.println(ases[i].getNumber() + " " + ases[i + 1].getNumber() + " unkown");
          default:
            break;
        }
        // System.out.println(ases[i+1].getNumber() + " " + ases[i].getNumber() +
        // ases[i+1].getEdge().get(ases[i].getNumber()));
      }
      if (counter > 10) {
        break;
      }
      counter++;
    }
  }
 public String prepare() {
   ActionContext actionContext = ActionContext.getContext();
   Map<String, Object> session = actionContext.getSession();
   session.replace("page", page);
   return SUCCESS;
 }
Esempio n. 18
0
  public DiaryEntry updateDiaryEntry(DiaryEntry updatedEntry) {
    diaryEntries.replace(updatedEntry.getEntryId(), updatedEntry);

    if (diaryEntries.containsValue(updatedEntry)) return updatedEntry;
    else throw new RuntimeException();
  }
Esempio n. 19
0
  // Function to alter a characteristics passed in parameter
  public void alterCharacteristic(Characteristic characteristicToAlter, int valueAlteration) {
    int characteristicValue = characs.get(characteristicToAlter);
    characteristicValue = characteristicValue + valueAlteration;

    characs.replace(characteristicToAlter, characteristicValue);
  }
 /**
  * Updates the IP prefix status in the local public IP prefix table.
  *
  * @param ipPprefix the IP prefix to update
  * @param b the new value for the IP prefix
  */
 private void updateIpPrefixStatus(IpPrefix ipPprefix, boolean b) {
   localPublicIpPrefixes.replace(ipPprefix, b);
 }
Esempio n. 21
0
 @Override
 public void clearMusic(Object o) {
   pauseAudio();
   myMusic.replace(o, myMusic.get(o), null);
 }
Esempio n. 22
0
  private void calculateArmorProtection(CreatureObject creature, boolean equipping) {
    int wornArmourPieces = 0, forceProtection = 0;
    Map<String, Float> protection = new TreeMap<String, Float>();

    for (SWGObject item : new ArrayList<SWGObject>(creature.getEquipmentList())) {
      Map<String, Object> attributes = new TreeMap<String, Object>(item.getAttributes());
      boolean incPieceCount = false;

      if (item.getStringAttribute("protection_level") != null) {
        forceProtection = getForceProtection(item);
        break;
      }

      for (Entry<String, Object> e : attributes.entrySet()) {
        if (e.getKey().startsWith("cat_armor_standard_protection")) {
          String protectionType =
              e.getKey().replace("cat_armor_standard_protection.armor_eff_", "");
          float modifier =
              Float.parseFloat(
                      core.scriptService
                          .getMethod(
                              "scripts/equipment/",
                              "slot_protection",
                              creature.getSlotNameForObject(item))
                          .__call__()
                          .asString())
                  / 100;
          Float protectionAmount = Float.parseFloat((String) e.getValue()) * modifier;

          if (protection.containsKey(protectionType))
            protection.replace(protectionType, protection.get(protectionType) + protectionAmount);
          else protection.put(protectionType, protectionAmount);
          incPieceCount = true;
        } else if (e.getKey().startsWith("cat_armor_special_protection")) {
          String protectionType =
              e.getKey().replace("cat_armor_special_protection.special_protection_type_", "");
          float modifier =
              Float.parseFloat(
                      core.scriptService
                          .getMethod(
                              "scripts/equipment/",
                              "slot_protection",
                              creature.getSlotNameForObject(item))
                          .__call__()
                          .asString())
                  / 100;
          Float protectionAmount = Float.parseFloat((String) e.getValue()) * modifier;

          if (protection.containsKey(protectionType))
            protection.replace(protectionType, protection.get(protectionType) + protectionAmount);
          else protection.put(protectionType, protectionAmount);
          incPieceCount = true;
        }
      }
      if (incPieceCount) wornArmourPieces++;
    }

    if (protection.size() == 0) {
      protection.put("kinetic", (float) 0);
      protection.put("energy", (float) 0);
      protection.put("heat", (float) 0);
      protection.put("cold", (float) 0);
      protection.put("acid", (float) 0);
      protection.put("electricity", (float) 0);
    }

    for (Entry<String, Float> e : protection.entrySet()) {
      core.skillModService.deductSkillMod(
          creature, e.getKey(), creature.getSkillModBase(e.getKey()));
      core.skillModService.addSkillMod(creature, e.getKey(), forceProtection);
      if (wornArmourPieces >= 3)
        core.skillModService.addSkillMod(creature, e.getKey(), (int) e.getValue().floatValue());
    }
  }
  @Test
  public void testSearchPosting() throws DataNotFoundException {
    postingService.writePosting("first_blog", testMixedPosting1);
    postingService.writePosting("first_blog", testTextPosting1);
    postingService.writePosting("first_blog", testSinglePosting1);
    postingService.writePosting("second_blog", testMixedPosting2);
    postingService.writePosting("second_blog", testTextPosting2);
    postingService.writePosting("second_blog", testSinglePosting2);
    postingService.writePosting("third_blog", testMixedPosting3);
    postingService.writePosting("third_blog", testTextPosting3);
    postingService.writePosting("third_blog", testSinglePosting3);

    Map<String, Object> searchInfo1 = new HashMap<String, Object>(); // expected - 6
    searchInfo1.put("target", "all");
    searchInfo1.put("searchType", "writer");
    searchInfo1.put("searchText", "1");
    searchInfo1.put("startRow", 1);
    searchInfo1.put("endRow", 10);

    Map<String, Object> searchInfo2 = new HashMap<String, Object>(); // expected - 3
    searchInfo2.put("target", "posting");
    searchInfo2.put("searchType", "title");
    searchInfo2.put("searchText", "secon");
    searchInfo2.put("startRow", 1);
    searchInfo2.put("endRow", 10);

    // problem1 : 모든 테이블마다 startRow & endRow num이 적용됨. 통합 적용 필요!!!
    Map<String, Object> searchInfo3 =
        new HashMap<String, Object>(); // expected - count = 9, list = 4
    searchInfo3.put("target", "all");
    searchInfo3.put("searchType", "tags");
    searchInfo3.put("searchText", "tes");
    searchInfo3.put("startRow", 1);
    searchInfo3.put("endRow", 4);

    Map<String, Object> searchInfo4 =
        new HashMap<String, Object>(); // expected - count = 4, list = 3
    searchInfo4.put("target", "all");
    searchInfo4.put("searchType", "contents");
    searchInfo4.put("searchText", "first");
    searchInfo4.put("startRow", 2);
    searchInfo4.put("endRow", 4);

    Map<String, Object> searchInfo5 =
        new HashMap<String, Object>(); // expected - count = 1, list = 1
    searchInfo5.put("target", "all");
    searchInfo5.put("contentType", PostingContent.MIXED_IMAGE_FILE_CONTENT);
    searchInfo5.put("startRow", 1);
    searchInfo5.put("endRow", 10);

    Map<String, Object> searchInfo6 =
        new HashMap<String, Object>(); // expected - count = 3, list = 2
    searchInfo6.put("target", "posting");
    searchInfo6.put("blogName", "first_blog");
    searchInfo6.put("searchType", "title");
    searchInfo6.put("searchText", "first");
    searchInfo6.put("startRow", 2);
    searchInfo6.put("endRow", 3);

    System.out.println("1------------------------------------------------------------------");
    int count = postingService.getPostingCount(searchInfo1);
    assertEquals(6, count);
    Posting[] postings = postingService.getPostingList(searchInfo1);
    assertEquals(count, postings.length);
    System.out.println("------------------------------------------------------------------1");

    System.out.println("2------------------------------------------------------------------");
    count = postingService.getPostingCount(searchInfo2);
    assertEquals(3, count);
    postings = postingService.getPostingList(searchInfo2);
    assertEquals(count, postings.length);
    System.out.println("------------------------------------------------------------------2");

    System.out.println("3------------------------------------------------------------------");
    count = postingService.getPostingCount(searchInfo3);
    assertEquals(9, count);
    postings = postingService.getPostingList(searchInfo3);
    assertEquals(4, postings.length);
    System.out.println("------------------------------------------------------------------3");

    System.out.println("4------------------------------------------------------------------");
    count = postingService.getPostingCount(searchInfo4);
    assertEquals(4, count);
    postings = postingService.getPostingList(searchInfo4);
    assertEquals(3, postings.length);
    System.out.println("------------------------------------------------------------------4");

    System.out.println("5------------------------------------------------------------------");
    count = postingService.getPostingCount(searchInfo5);
    assertEquals(1, count);
    postings = postingService.getPostingList(searchInfo5);
    assertEquals(count, postings.length);
    System.out.println("------------------------------------------------------------------5");

    System.out.println("6------------------------------------------------------------------");
    count = postingService.getPostingCount(searchInfo6);
    assertEquals(3, count);
    searchInfo6.replace("blogName", "first_blog"); // getPostingCount()에서 바뀌었기 때문에 원래 값으로 초기화.
    postings = postingService.getPostingList(searchInfo6);
    assertEquals(2, postings.length);
    System.out.println("------------------------------------------------------------------6");
  }
 @Override
 public void update(String sessionId) {
   session2instant.replace(sessionId, now());
 }