Пример #1
1
 public void toString0(StringBuilder sb, String indentString) {
   sb.append(indentString);
   sb.append("  value: ");
   sb.append(value);
   sb.append("\n");
   toString1(sb, indentString);
 }
Пример #2
1
 private CIJobStatus deleteCI(CIJob job, List<String> builds) throws PhrescoException {
   S_LOGGER.debug("Entering Method CIManagerImpl.deleteCI(CIJob job)");
   S_LOGGER.debug("Job name " + job.getName());
   cli = getCLI(job);
   String deleteType = null;
   List<String> argList = new ArrayList<String>();
   S_LOGGER.debug("job name " + job.getName());
   S_LOGGER.debug("Builds " + builds);
   if (CollectionUtils.isEmpty(builds)) { // delete job
     S_LOGGER.debug("Job deletion started");
     S_LOGGER.debug("Command " + FrameworkConstants.CI_JOB_DELETE_COMMAND);
     deleteType = DELETE_TYPE_JOB;
     argList.add(FrameworkConstants.CI_JOB_DELETE_COMMAND);
     argList.add(job.getName());
   } else { // delete Build
     S_LOGGER.debug("Build deletion started");
     deleteType = DELETE_TYPE_BUILD;
     argList.add(FrameworkConstants.CI_BUILD_DELETE_COMMAND);
     argList.add(job.getName());
     StringBuilder result = new StringBuilder();
     for (String string : builds) {
       result.append(string);
       result.append(",");
     }
     String buildNos = result.substring(0, result.length() - 1);
     argList.add(buildNos);
     S_LOGGER.debug("Command " + FrameworkConstants.CI_BUILD_DELETE_COMMAND);
     S_LOGGER.debug("Build numbers " + buildNos);
   }
   try {
     int status = cli.execute(argList);
     String message = deleteType + " deletion started in jenkins";
     if (status == FrameworkConstants.JOB_STATUS_NOTOK) {
       deleteType = deleteType.substring(0, 1).toLowerCase() + deleteType.substring(1);
       message = "Error while deleting " + deleteType + " in jenkins";
     }
     S_LOGGER.debug("Delete CI Status " + status);
     S_LOGGER.debug("Delete CI Message " + message);
     return new CIJobStatus(status, message);
   } finally {
     if (cli != null) {
       try {
         cli.close();
       } catch (IOException e) {
         if (debugEnabled) {
           S_LOGGER.error(
               "Entered into catch block of CIManagerImpl.deleteCI(CIJob job) "
                   + e.getLocalizedMessage());
         }
       } catch (InterruptedException e) {
         if (debugEnabled) {
           S_LOGGER.error(
               "Entered into catch block of CIManagerImpl.deleteCI(CIJob job) "
                   + e.getLocalizedMessage());
         }
       }
     }
   }
 }
Пример #3
1
 private String getCIJobPath(ApplicationInfo appInfo) {
   StringBuilder builder = new StringBuilder(Utility.getProjectHome());
   builder.append(appInfo.getAppDirName());
   builder.append(File.separator);
   builder.append(FOLDER_DOT_PHRESCO);
   builder.append(File.separator);
   builder.append(CI_JOB_INFO_NAME);
   return builder.toString();
 }
 /**
  * atomically remove elements from an array or has many relationship
  *
  * @param path the path to get
  * @param primaryId id of the object with the relation
  * @param field name of the relation or array field to delete from
  * @param idsToDelete list of ids to atomically remove from field. ids should be same type as the
  *     primary id of the related type (most likely String or Integer)
  * @param cascadeDeletes true if related objects specified in idsToDelete should also be deleted
  * @param callback callback to be called when the server returns. may execute in a separate thread
  */
 public <T> void deleteIdsFrom(
     String path,
     String primaryId,
     String field,
     List<T> idsToDelete,
     boolean cascadeDeletes,
     StackMobRawCallback callback) {
   StringBuilder ids = new StringBuilder();
   for (int i = 0; i < idsToDelete.size(); i++) {
     ids.append(idsToDelete.get(i).toString());
     if (i < idsToDelete.size() - 1) {
       ids.append(",");
     }
   }
   List<Map.Entry<String, String>> headers = new ArrayList<Map.Entry<String, String>>();
   if (cascadeDeletes) {
     headers.add(new Pair<String, String>("X-StackMob-CascadeDelete", "true"));
   }
   new StackMobRequestWithoutPayload(
           this.executor,
           this.session,
           HttpVerbWithoutPayload.DELETE,
           StackMobOptions.headers(headers),
           StackMobRequest.EmptyParams,
           String.format("%s/%s/%s/%s", path, primaryId, field, ids.toString()),
           callback,
           this.redirectedCallback)
       .setUrlFormat(this.host)
       .sendRequest();
 }
Пример #5
0
  private void setSvnCredential(CIJob job) throws JDOMException, IOException {
    S_LOGGER.debug("Entering Method CIManagerImpl.setSvnCredential");
    try {
      String jenkinsTemplateDir = Utility.getJenkinsTemplateDir();
      String credentialFilePath = jenkinsTemplateDir + job.getRepoType() + HYPHEN + CREDENTIAL_XML;
      if (debugEnabled) {
        S_LOGGER.debug("credentialFilePath ... " + credentialFilePath);
      }
      File credentialFile = new File(credentialFilePath);

      SvnProcessor processor = new SvnProcessor(credentialFile);

      //			DataInputStream in = new DataInputStream(new FileInputStream(credentialFile));
      //			while (in.available() != 0) {
      //				System.out.println(in.readLine());
      //			}
      //			in.close();

      processor.changeNodeValue("credentials/entry//userName", job.getUserName());
      processor.changeNodeValue("credentials/entry//password", job.getPassword());
      processor.writeStream(new File(Utility.getJenkinsHome() + File.separator + job.getName()));

      // jenkins home location
      String jenkinsJobHome = System.getenv(JENKINS_HOME);
      StringBuilder builder = new StringBuilder(jenkinsJobHome);
      builder.append(File.separator);

      processor.writeStream(new File(builder.toString() + CI_CREDENTIAL_XML));
    } catch (Exception e) {
      S_LOGGER.error(
          "Entered into the catch block of CIManagerImpl.setSvnCredential "
              + e.getLocalizedMessage());
    }
  }
Пример #6
0
 public final void print() {
   StringBuilder sb = new StringBuilder();
   sb.append("I: ").append(_iteration).append("[");
   double[][] c = clusters();
   for (int i = 0; i < c.length; i++) sb.append(c[i][2]).append(",");
   sb.append("]");
   Log.debug(Sys.KMEAN, sb);
 }
Пример #7
0
  public static String getUnderscorePropertyName(String camelCaseName) {
    StringBuilder sb = new StringBuilder();

    for (char c : camelCaseName.toCharArray()) {
      if (Character.isUpperCase(c)) sb.append('_').append(Character.toLowerCase(c));
      else sb.append(c);
    }

    return (sb.toString());
  }
Пример #8
0
 private StringBuilder stats(StringBuilder sb, JsonElement json) {
   if (json == null) {
     return sb.append(" / / ");
   } else {
     JsonObject obj = json.getAsJsonObject();
     return sb.append(
         String.format(
             "%4.1f / %4.1f / %4.1f",
             obj.get(MIN).getAsDouble(), obj.get(MAX).getAsDouble(), obj.get(MEAN).getAsDouble()));
   }
 }
Пример #9
0
    public String getCacheString() {
      StringBuilder sb = new StringBuilder();

      sb.append(name).append(":");

      for (Map.Entry<String, String> tagEntry : tags.entries()) {
        sb.append(tagEntry.getKey()).append("=");
        sb.append(tagEntry.getValue()).append(":");
      }

      return (sb.toString());
    }
Пример #10
0
 @When("^I read json string from a file$")
 public void i_read_json_string_from_a_file() throws Throwable {
   FileInputStream fin =
       new FileInputStream(
           new File(System.getProperty("user.dir") + "//src//test//resources//sample.json"));
   InputStreamReader in = new InputStreamReader(fin);
   BufferedReader bufferedReader = new BufferedReader(in);
   StringBuilder sb = new StringBuilder();
   String line;
   while ((line = bufferedReader.readLine()) != null) {
     sb.append(line);
   }
   json = sb.toString();
 }
Пример #11
0
 @When("^I read the json data file \"(.*?)\"$")
 public void i_read_the_json_data_file(String arg1) throws Throwable {
   FileInputStream fin =
       new FileInputStream(
           new File(System.getProperty("user.dir") + "//src//test//resources//" + arg1));
   InputStreamReader in = new InputStreamReader(fin);
   BufferedReader bufferedReader = new BufferedReader(in);
   StringBuilder sb = new StringBuilder();
   String line;
   while ((line = bufferedReader.readLine()) != null) {
     sb.append(line);
   }
   json = sb.toString();
   System.out.println(json);
 }
Пример #12
0
  private void setMailCredential(CIJob job) {
    if (debugEnabled) {
      S_LOGGER.debug("Entering Method CIManagerImpl.setMailCredential");
    }
    try {
      String jenkinsTemplateDir = Utility.getJenkinsTemplateDir();
      String mailFilePath = jenkinsTemplateDir + MAIL + HYPHEN + CREDENTIAL_XML;
      if (debugEnabled) {
        S_LOGGER.debug("configFilePath ... " + mailFilePath);
      }
      File mailFile = new File(mailFilePath);

      SvnProcessor processor = new SvnProcessor(mailFile);

      //			DataInputStream in = new DataInputStream(new FileInputStream(mailFile));
      //			while (in.available() != 0) {
      //				System.out.println(in.readLine());
      //			}
      //			in.close();

      // Mail have to go with jenkins running email address
      InetAddress ownIP = InetAddress.getLocalHost();
      processor.changeNodeValue(
          CI_HUDSONURL,
          HTTP_PROTOCOL
              + PROTOCOL_POSTFIX
              + ownIP.getHostAddress()
              + COLON
              + job.getJenkinsPort()
              + FORWARD_SLASH
              + CI
              + FORWARD_SLASH);
      processor.changeNodeValue("smtpAuthUsername", job.getSenderEmailId());
      processor.changeNodeValue("smtpAuthPassword", job.getSenderEmailPassword());
      processor.changeNodeValue("adminAddress", job.getSenderEmailId());

      // jenkins home location
      String jenkinsJobHome = System.getenv(JENKINS_HOME);
      StringBuilder builder = new StringBuilder(jenkinsJobHome);
      builder.append(File.separator);

      processor.writeStream(new File(builder.toString() + CI_MAILER_XML));
    } catch (Exception e) {
      S_LOGGER.error(
          "Entered into the catch block of CIManagerImpl.setMailCredential "
              + e.getLocalizedMessage());
    }
  }
Пример #13
0
 @Then("^I print it as a string$")
 public void i_print_it_as_a_string() throws Throwable {
   FileInputStream fin = new FileInputStream(new File("output.json"));
   InputStreamReader in = new InputStreamReader(fin);
   BufferedReader bufferedReader = new BufferedReader(in);
   StringBuilder sb = new StringBuilder();
   String line;
   while ((line = bufferedReader.readLine()) != null) {
     sb.append(line);
   }
   String json = sb.toString();
   System.out.println(json);
   Gson gson = new Gson();
   Employee employee = gson.fromJson(json, Employee.class);
   //		System.out.println(employee.getFirstName());
 }
Пример #14
0
  private URL buildUrl(Collection<String> guysIdentifiers) {
    Validate.notEmpty(guysIdentifiers);
    StringBuilder sb =
        new StringBuilder(
            "http://scb.sanger.ac.uk/api/sample_data"
                + "?experiment_id=1&mean_expression=1&pivot=1&variable=bgplvm_2d_0&variable=bgplvm_2d_1&variable=day");
    for (String guysIdentifier : guysIdentifiers) {
      sb.append(MessageFormat.format("&gene_id={0}", guysIdentifier));
    }

    try {
      return new URL(sb.toString());
    } catch (MalformedURLException e) {
      throw new RuntimeException(e);
    }
  }
  /** @return a string representation of the object. */
  @Override
  public String toString() {

    StringBuilder stringBuilder = new StringBuilder();

    if (wrappedStack instanceof ItemStack) {
      ItemStack itemStack = (ItemStack) wrappedStack;
      try {
        stringBuilder.append(
            String.format(
                "%sxitemStack[%s:%s:%s:%s]",
                stackSize,
                itemStack.itemID,
                itemStack.getItemDamage(),
                itemStack.getUnlocalizedName(),
                itemStack.getItem().getClass().getCanonicalName()));
      } catch (ArrayIndexOutOfBoundsException e) {
        // NOOP
      }
    } else if (wrappedStack instanceof OreStack) {
      OreStack oreStack = (OreStack) wrappedStack;
      stringBuilder.append(String.format("%sxoreStack.%s", stackSize, oreStack.oreName));
    } else if (wrappedStack instanceof EnergyStack) {
      EnergyStack energyStack = (EnergyStack) wrappedStack;
      stringBuilder.append(String.format("%sxenergyStack.%s", stackSize, energyStack.energyName));
    } else if (wrappedStack instanceof FluidStack) {
      FluidStack fluidStack = (FluidStack) wrappedStack;
      stringBuilder.append(
          String.format("%sxfluidStack.%s", stackSize, fluidStack.getFluid().getName()));
    } else {
      stringBuilder.append("null");
    }

    return stringBuilder.toString();
  }
Пример #16
0
  private String generatePostToFeedHtml(
      final String shortMessage, final String originalMessage, final FeedType type)
      throws UnsupportedEncodingException {
    final StringBuilder sb = new StringBuilder(MAX_LENGTH + OFFSET);
    final String start = "<p style=\"white-space: normal;width:150px\"><img style=\"float:left;\" ";
    switch (type) {
      case error:
        sb.append(start)
            .append("src=\"")
            .append(ServerInfoImpl.getFullServerURL(this.getThreadLocalRequest()))
            .append("/resources/images/symbol-error.png\" width=\"35\" height=\"35\">");

        break;
      case system:
        sb.append(start)
            .append("src=\"")
            .append(ServerInfoImpl.getFullServerURL(this.getThreadLocalRequest()))
            .append("/resources/images/logo.png\"  width=\"40\" height=\"40\">");
        break;
      case info:
        sb.append(start)
            .append("src=\"")
            .append(ServerInfoImpl.getFullServerURL(this.getThreadLocalRequest()))
            .append("/resources/images/info.png\" width=\"35\" height=\"35\">");
        break;
      case data:
        sb.append(start)
            .append("src=\"")
            .append(ServerInfoImpl.getFullServerURL(this.getThreadLocalRequest()))
            .append("/resources/images/point_ok.png\" width=\"40\" height=\"40\">");
        break;
      default:
        sb.append(start)
            .append("src=\"")
            .append(ServerInfoImpl.getFullServerURL(this.getThreadLocalRequest()))
            .append("/resources/images/logo.png\" width=\"40\" height=\"40\">");
    }

    final String shortenedOriginal =
        originalMessage.length() > MAX_LENGTH
            ? originalMessage.substring(0, MAX_LENGTH)
            : originalMessage;

    sb.append("<a href=\"#\" onclick=\"window.open('feed.html?content=")
        .append(URLEncoder.encode(shortenedOriginal, Const.CONST_ENCODING))
        .append("');\">")
        .append("<span>")
        .append(new Date())
        .append("</span>")
        .append("<br /></a>")
        .append(shortMessage)
        .append("</p>");
    return sb.toString();
  }
Пример #17
0
 public LinkedList parseFile(String fileName, Class theClass) {
   LinkedList object = null;
   String nextLine = "";
   String jsonFile;
   StringBuilder sb = new StringBuilder();
   try {
     BufferedReader reader = new BufferedReader(new FileReader(fileName));
     while ((nextLine = reader.readLine()) != null) {
       sb.append(nextLine);
     }
     jsonFile = sb.toString();
     if (jsonFile.indexOf("{") == 0) {
       jsonFile = jsonFile.substring(1, jsonFile.length() - 1);
     }
     object = (LinkedList) gson.fromJson(jsonFile, theClass);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return object;
 }
Пример #18
0
 /**
  * Annotate the used and ignored columns in the job parameter JSON For both the used and the
  * ignored columns, the following rules apply: If the number of columns is less or equal than
  * 100, a dense list of used columns is reported. If the number of columns is greater than 100,
  * the number of columns is reported. If the number of columns is 0, a "N/A" is reported.
  *
  * @return JsonObject annotated with used/ignored columns
  */
 @Override
 public JsonObject toJSON() {
   JsonObject jo = super.toJSON();
   if (!jo.has("source") || source == null) return jo;
   HashMap<String, int[]> map = new HashMap<String, int[]>();
   map.put("used_cols", cols);
   map.put("ignored_cols", ignored_cols);
   for (String key : map.keySet()) {
     int[] val = map.get(key);
     if (val != null) {
       if (val.length > 100) jo.getAsJsonObject("source").addProperty("num_" + key, val.length);
       else if (val.length > 0) {
         StringBuilder sb = new StringBuilder();
         for (int c : val) sb.append(c + ",");
         jo.getAsJsonObject("source")
             .addProperty(key, sb.toString().substring(0, sb.length() - 1));
       } else {
         jo.getAsJsonObject("source").add(key, JsonNull.INSTANCE);
       }
     }
   }
   return jo;
 }
Пример #19
0
    public String getCacheString() {
      StringBuilder sb = new StringBuilder();
      if (m_startAbsolute != null) sb.append(m_startAbsolute).append(":");

      if (start_relative != null) sb.append(start_relative.toString()).append(":");

      if (m_endAbsolute != null) sb.append(m_endAbsolute).append(":");

      if (end_relative != null) sb.append(end_relative.toString()).append(":");

      return (sb.toString());
    }
Пример #20
0
 @Override
 public String build(Response response, JsonObject t, String contextName) {
   int n = t.get(Constants.TREE_COUNT).getAsInt();
   StringBuilder sb = new StringBuilder();
   if (n > 0) {
     sb.append("<h3>Trees</h3>");
     sb.append(t.get(Constants.TREE_COUNT)).append(" trees with min/max/mean depth of ");
     stats(sb, t.get(TREE_DEPTH)).append(" and leaf of ");
     stats(sb, t.get(TREE_LEAVES)).append(".<br>");
     for (int i = 0; i < n; ++i) {
       sb.append(
               RFTreeView.link(_modelKey.value(), i, _dataKey.value(), Integer.toString(i + 1)))
           .append(" ");
     }
   } else {
     sb.append("<h3>No trees yet...</h3>");
   }
   return sb.toString();
 }
Пример #21
0
  @Override
  @SuppressWarnings("empty-statement")
  protected Clan doInBackground() throws Exception {
    if (bestMatch == null) { // use fallBack
      // URL URL = new
      // URL("http://worldoftanks."+gui.getServerRegion()+"/uc/clans/?type=table&offset=0&limit=10&order_by="+this.searchType+"&search="+this.clanTagName+"&echo=2&id=clans_index");
      // TODO: does API support orderBy ?!?
      URL URL =
          new URL(
              "http://worldoftanks."
                  + gui.getServerRegion()
                  + "/uc/clans/api/1.1/?source_token=Intellect_Soft-WoT_Mobile-unofficial_stats&search="
                  + this.fallbackInput.replace(" ", "%20")
                  + "&offset=0&limit=10");
      URLConnection URLConnection = URL.openConnection();
      URLConnection.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
      URLConnection.setRequestProperty("Accept-Language", "en-us;q=0.5,en;q=0.3");
      URLConnection.setRequestProperty("Accept-Encoding", "paco");
      URLConnection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
      URLConnection.setRequestProperty("Connection", "close");
      URLConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
      // timeout after 10 seconds
      URLConnection.setConnectTimeout(10000);

      BufferedReader clanBufferedReader = null;
      StringBuilder data = new StringBuilder(3000);
      try {
        clanBufferedReader =
            new BufferedReader(new InputStreamReader(URLConnection.getInputStream(), "UTF8"));
        for (String line; (line = clanBufferedReader.readLine()) != null; data.append(line)) ;
      } finally {
        if (clanBufferedReader != null) clanBufferedReader.close();
      }

      JsonParser jsonParser = new JsonParser();
      JsonObject json = jsonParser.parse(data.toString()).getAsJsonObject();

      if (!"ok".equalsIgnoreCase(json.get("status").getAsString())) {
        throw new ClanAPIException(json.get("status_code").getAsString(), this.gui);
      }

      JsonArray results = json.get("data").getAsJsonObject().get("items").getAsJsonArray();
      JsonObject json_clan = null;
      for (JsonElement e : results) {
        JsonObject o = e.getAsJsonObject();
        if (fallbackInput.equalsIgnoreCase(o.get(this.searchType).getAsString())) {
          json_clan = o;
          break;
        }
      }
      if (json_clan == null) {
        throw new ClanNotFoundException(this.gui);
      }
      String name = json_clan.get("name").getAsString();
      String tag = json_clan.get("abbreviation").getAsString();
      long ID = json_clan.get("id").getAsLong();
      int member_count = json_clan.get("member_count").getAsInt();
      ImageIcon emblem =
          new ImageIcon(
              new URL("http://worldoftanks.eu" + json_clan.get("clan_emblem_url").getAsString()));
      bestMatch = new PossibleClan(name, tag, ID, member_count, emblem);
    }

    // get provinces
    GetProvinces provinceWorker = new GetProvinces(bestMatch.getID(), this.gui);
    provinceWorker.execute();

    // get members
    // URL = new
    // URL("http://worldoftanks."+gui.getServerRegion()+"/uc/clans/"+clanID+"/members/?type=table&offset=0&limit=100&order_by=name&search=&echo=1&id=clan_members_index");
    URL URL =
        new URL(
            "http://worldoftanks."
                + gui.getServerRegion()
                + "/uc/clans/"
                + bestMatch.getID()
                + "/api/1.1/?source_token=Intellect_Soft-WoT_Mobile-unofficial_stats");
    URLConnection URLConnection = URL.openConnection();
    URLConnection.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
    URLConnection.setRequestProperty("Accept-Language", "en-us;q=0.5,en;q=0.3");
    URLConnection.setRequestProperty("Accept-Encoding", "paco");
    URLConnection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    URLConnection.setRequestProperty("Connection", "close");
    URLConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
    // timeout after 15 seconds
    URLConnection.setConnectTimeout(15000);

    BufferedReader membersBufferedReader = null;
    StringBuilder members_data = new StringBuilder(10000);
    try {
      membersBufferedReader =
          new BufferedReader(new InputStreamReader(URLConnection.getInputStream(), "UTF8"));
      for (String line;
          (line = membersBufferedReader.readLine()) != null;
          members_data.append(line)) ;
    } finally {
      if (membersBufferedReader != null) membersBufferedReader.close();
    }

    JsonParser jsonParser = new JsonParser();
    JsonObject members_json = jsonParser.parse(members_data.toString()).getAsJsonObject();

    if (!"ok".equalsIgnoreCase(members_json.get("status").getAsString())) {
      throw new ClanAPIException(members_json.get("status_code").getAsString(), this.gui);
    }

    JsonArray members = members_json.get("data").getAsJsonObject().get("members").getAsJsonArray();

    GetPlayerData[] workers = new GetPlayerData[members.size()];
    players = new ArrayList<Player>(members.size());
    for (int i = 0; i < members.size(); i++) {
      JsonObject member = members.get(i).getAsJsonObject();
      workers[i] = new GetPlayerData(member.get("account_id").getAsLong(), this.gui);
      workers[i].execute();
    } // TODO: see if there's some sort of "worker pool" with a getAll() or getFirst()

    // In the meantime see if GetProvinces is ready
    this.provinces = provinceWorker.get();

    ArrayList<Vehicle> vehicles = new ArrayList<Vehicle>(5000);
    long start = System.currentTimeMillis();
    for (GetPlayerData w : workers) {
      Player p = w.get();
      players.add(p);
      vehicles.addAll(p.getVehicles());
      // TODO: update progress bar
      // TODO: sort by tier already here ?!? (implementation details)
    }
    vehicles.trimToSize();
    System.out.printf(
        "Vs:" + vehicles.size() + "\nOverall time: %dms%n", System.currentTimeMillis() - start);
    vehicles = Utils.sortVehiclesByTier(vehicles);
    vehicles = Utils.sortVehiclesByClass(vehicles);
    vehicles = Utils.sortVehiclesByNation(vehicles);

    if (players.size() > 20) { // some small logical optimizations
      double avg_top_eff = 0D, avg_eff = 0D, avg_top_wr = 0D, avg_wr = 0D;
      players = Utils.sortPlayersByEfficiency(players);
      for (int i = 0; i < players.size(); i++) {
        if (i == 20) avg_top_eff = avg_eff / 20D;
        avg_eff += players.get(i).getEfficiency();
      }
      avg_eff /= players.size();

      players = Utils.sortPlayersByWinrate(players);
      for (int i = 0; i < players.size(); i++) {
        if (i == 20) avg_top_wr = avg_wr / 20D;
        avg_wr += players.get(i).getAvg_wr();
      }
      avg_wr /= players.size();

      return new Clan(
          bestMatch.getName(),
          bestMatch.getClanTag(),
          bestMatch.getID(),
          players,
          vehicles,
          avg_wr,
          avg_top_wr,
          avg_eff,
          avg_top_eff,
          bestMatch.getEmblem());
    } else {
      double avg_eff = 0D, avg_wr = 0D; // top=all
      players = Utils.sortPlayersByEfficiency(players);
      for (int i = 0; i < players.size(); i++) {
        avg_eff += players.get(i).getEfficiency();
      }
      avg_eff /= players.size();

      players = Utils.sortPlayersByWinrate(players);
      for (int i = 0; i < players.size(); i++) {
        avg_wr += players.get(i).getAvg_wr();
      }
      avg_wr /= players.size();

      return new Clan(
          bestMatch.getName(),
          bestMatch.getClanTag(),
          bestMatch.getID(),
          players,
          vehicles,
          avg_wr,
          avg_wr,
          avg_eff,
          avg_eff,
          bestMatch.getEmblem());
    }
  }
Пример #22
0
 @Override
 public String build(Response response, JsonObject cm, String contextName) {
   StringBuilder sb = new StringBuilder();
   if (cm.has(JSON_CM_MATRIX)) {
     sb.append("<h3>Confusion matrix - ")
         .append(cm.get(JSON_CM_TYPE).getAsString())
         .append("</h3>");
     sb.append("<dl class='dl-horizontal'>");
     sb.append("<dt>classification error</dt><dd>")
         .append(String.format("%5.3f %%", 100 * cm.get(JSON_CM_CLASS_ERR).getAsFloat()))
         .append("</dd>");
     long rows = cm.get(JSON_CM_ROWS).getAsLong();
     long skippedRows = cm.get(JSON_CM_ROWS_SKIPPED).getAsLong();
     sb.append("<dt>used / skipped rows </dt><dd>")
         .append(
             String.format(
                 "%d / %d (%3.1f %%)",
                 rows, skippedRows, (double) skippedRows * 100 / (skippedRows + rows)))
         .append("</dd>");
     sb.append("<dt>trees used</dt><dd>" + cm.get(JSON_CM_TREES).getAsInt()).append("</dd>");
     sb.append("</dl>");
     sb.append("<table class='table table-striped table-bordered table-condensed'>");
     sb.append("<tr><th>Actual \\ Predicted</th>");
     JsonArray header = (JsonArray) cm.get(JSON_CM_HEADER);
     for (JsonElement e : header) sb.append("<th>" + e.getAsString() + "</th>");
     sb.append("<th>Error</th></tr>");
     int classes = header.size();
     long[] totals = new long[classes];
     JsonArray matrix = (JsonArray) cm.get(JSON_CM_MATRIX);
     long sumTotal = 0;
     long sumError = 0;
     for (int crow = 0; crow < classes; ++crow) {
       JsonArray row = (JsonArray) matrix.get(crow);
       long total = 0;
       long error = 0;
       sb.append("<tr><th>" + header.get(crow).getAsString() + "</th>");
       for (int ccol = 0; ccol < classes; ++ccol) {
         long num = row.get(ccol).getAsLong();
         total += num;
         totals[ccol] += num;
         if (ccol == crow) {
           sb.append("<td style='background-color:LightGreen'>");
         } else {
           sb.append("<td>");
           error += num;
         }
         sb.append(num);
         sb.append("</td>");
       }
       sb.append("<td>");
       sb.append(String.format("%5.3f = %d / %d", (double) error / total, error, total));
       sb.append("</td></tr>");
       sumTotal += total;
       sumError += error;
     }
     sb.append("<tr><th>Totals</th>");
     for (int i = 0; i < totals.length; ++i) sb.append("<td>" + totals[i] + "</td>");
     sb.append("<td><b>");
     sb.append(
         String.format("%5.3f = %d / %d", (double) sumError / sumTotal, sumError, sumTotal));
     sb.append("</b></td></tr>");
     sb.append("</table>");
   } else {
     sb.append("<div class='alert alert-info'>");
     sb.append("Confusion matrix is being computed into the key:</br>");
     sb.append(cm.get(JSON_CONFUSION_KEY).getAsString());
     sb.append("</div>");
   }
   return sb.toString();
 }
Пример #23
0
  private String valueToHtml(final Entity entity, final Entity point, final Value value) {
    final StringBuilder sb = new StringBuilder(SIZE);
    if (!(Double.compare(value.getDoubleValue(), Const.CONST_IGNORED_NUMBER_VALUE) == 0)) {
      sb.append("<img style=\"float:left\" src=\"")
          .append(ServerInfoImpl.getFullServerURL(this.getThreadLocalRequest()));

      switch (value.getAlertState()) {
        case LowAlert:
          sb.append("/resources/images/point_low.png\">");
          break;
        case HighAlert:
          sb.append("/resources/images/point_high.png\">");
          break;
        case IdleAlert:
          sb.append("/resources/images/point_idle.png\">");
          break;
        case OK:
          sb.append("/resources/images/point_ok.png\">");
          break;
      }
    }

    if (entity != null && point != null) {

      sb.append("&nbsp;");

      if (!(Double.compare(value.getDoubleValue(), Const.CONST_IGNORED_NUMBER_VALUE) == 0)) {
        sb.append("Alert&nbsp;Status:").append(value.getAlertState().name());
        sb.append("<br>Value:").append(value.getDoubleValue());
      }

      if (!Utils.isEmptyString(value.getNote())) {
        sb.append("<br>Note:").append(value.getNote());
      }

      sb.append("<a href=\"#\" onclick=\"window.open('report.html?uuid=")
          .append(point.getKey())
          .append("', 'Report',")
          .append("'height=800,width=800,toolbar=0,status=0,location=0' );\" >")
          .append("&nbsp;[more]</a>");
    }

    return sb.toString();
  }