public void excluir(Oriundo oriundo) throws SQLException {
   Connection con =
       DriverManager.getConnection(
           new conexao().url,
           new conexao().config.getString("usuario"),
           new conexao().config.getString("senha"));
   PreparedStatement ps = null;
   String sqlExcluir = "DELETE FROM oriundo WHERE codigo=?";
   try {
     ps = con.prepareStatement(sqlExcluir);
     ps.setInt(1, oriundo.getCodigo());
     ps.executeUpdate();
     JOptionPane.showMessageDialog(
         null, "Ecluido Com Sucesso: ", "Mensagem do Sistema - Excluir", 1);
   } catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(
         null, "NumberFormaterExeption Erro: " + e.getMessage(), "ClasseDAO Func.Excluir", 0);
     e.printStackTrace();
   } catch (NullPointerException e) {
     JOptionPane.showMessageDialog(
         null, "NullPointerException Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } catch (SQLException e) {
     JOptionPane.showMessageDialog(
         null, "SQLException Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         null, "Exception Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } finally {
     ps.close();
     con.close();
   }
 }
  private boolean einlesen() {
    int eingabefaktor;

    // Faktor
    try {
      eingabefaktor = Integer.parseInt(feldFaktor.getText());
      if (eingabefaktor < 0) {
        System.out.println("Faktor < 0");
        feldFaktor.selectAll();
        return false;
      }
    } catch (NumberFormatException e) {
      System.out.println(e.toString());
      feldFaktor.selectAll();
      return false;
    }

    faktor = eingabefaktor;

    // Ist die Checkbox angekreuzt?
    NUREINSCHRITT = checkbox_nureinSchritt.isSelected();
    AUCHSTRAGEGIE2 = checkbox_auchStrategie2.isSelected();

    return true;
  }
  /**
   * read the transition matrix from the file
   *
   * @param fp
   * @return
   */
  public static Map<Integer, Set<Integer>> readTransitionMatrix(String fp) {
    Map<Integer, Set<Integer>> res = new HashMap<Integer, Set<Integer>>();

    if (fp == null || fp.length() == 0) return res;

    try {
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(new FileInputStream(new File(fp))));

      String line = null;
      while ((line = reader.readLine()) != null) {
        String[] fields = line.split(" ");
        int from = Integer.parseInt(fields[0]);
        int to = Integer.parseInt(fields[1]);

        if (res.containsKey(from)) {
          res.get(from).add(to);
        } else {
          Set<Integer> cset = new HashSet<Integer>();
          cset.add(to);

          res.put(from, cset);
        }
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (NumberFormatException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return Collections.unmodifiableMap(res);
  }
Exemple #4
0
 /**
  * Analyze the command line options to extract the optional specified strategy and debug level.
  *
  * @param args options to analyze
  */
 private static void analyzeArguments(String args[]) {
   int size = args.length;
   for (int i = 0; i < size; i++) {
     if (args[i].equals("-s")) {
       i++;
       if (i >= size || args[i].charAt(0) == '-') {
         stopError("Missing strategy after '-s'. May be one of:\n" + allStrategies());
       } else {
         Class strat = allStrategies.get(args[i]);
         if (strat == null) {
           stopError(
               "Unknown strategy '" + args[i] + "'. It should be one of:\n" + allStrategies());
         } else {
           strategyTag = args[i];
         }
       }
     } else if (args[i].equals("-v")) {
       int verb = 1;
       i++;
       if (i < size && args[i].charAt(0) != '-') {
         try {
           verb = Integer.decode(args[i]);
         } catch (NumberFormatException ex) {
           stopError("Non valid verbose level: " + ex.getMessage());
         }
       }
       setVerboseLevel(verb);
     } else {
       stopError("Unknown argument: " + args[i]);
     }
   }
 }
Exemple #5
0
 public static boolean isNumber(String n) {
   try {
     double d = Double.valueOf(n).doubleValue();
     return true;
   } catch (NumberFormatException e) {
     e.printStackTrace();
     return false;
   }
 }
 public static int parseInteger(String s) {
   try {
     return (Integer.parseInt(s));
   } catch (NumberFormatException ex) {
     JOptionPane.showMessageDialog(
         null, ex.getMessage(), "Invalid number", JOptionPane.ERROR_MESSAGE);
     return (-1);
   }
 }
Exemple #7
0
 /**
  * Return a integer parsed from the value associated with the given key, or "def" in key wasn't
  * found.
  */
 public static int parseProperty(Properties preferences, String key, int def) {
   String val = preferences.getProperty(key);
   if (val == null) return def;
   try {
     return Integer.parseInt(val);
   } catch (NumberFormatException nfe) {
     nfe.printStackTrace();
     return def;
   }
 }
Exemple #8
0
 public int getInt(String paramName, int defaultInt) {
   try {
     String temp = getString(paramName);
     if (temp == null) return defaultInt;
     else return Integer.parseInt(temp);
   } catch (NumberFormatException e) {
     e.printStackTrace();
   }
   return 0;
 }
Exemple #9
0
 public boolean getBoolean(String paramName, boolean defaultBoolean) {
   try {
     String temp = getString(paramName);
     if (temp == null) return defaultBoolean;
     else return Boolean.valueOf(temp).booleanValue();
   } catch (NumberFormatException e) {
     e.printStackTrace();
   }
   return false;
 }
 /**
  * Returns the editted value.
  *
  * @return the editted value.
  * @throws TagFormatException if the tag value cannot be retrieved with the expected type.
  */
 public TagValue getTagValue() throws TagFormatException {
   try {
     long numer = Long.parseLong(m_numer.getText());
     long denom = Long.parseLong(m_denom.getText());
     Rational rational = new Rational(numer, denom);
     return new TagValue(m_value.getTag(), rational);
   } catch (NumberFormatException e) {
     e.printStackTrace();
     throw new TagFormatException(
         m_numer.getText() + "/" + m_denom.getText() + " is not a valid rational");
   }
 }
Exemple #11
0
 @Override
 public Optional<Integer> getInt(String elementKey) {
   ConfigElement element = elements.get(elementKey);
   if (element == null || isNullOrEmpty(element.getValue())) {
     return Optional.absent();
   }
   try {
     return Optional.of(Integer.parseInt(element.getValue()));
   } catch (NumberFormatException e) {
     throw new RuntimeException(
         "can't access " + element + " as int" + " (parse exception " + e.getMessage() + ")");
   }
 }
  public static void main(String[] args) {
    int myPeerID;
    actualPeerProcess pp;

    try {
      myPeerID = Integer.parseInt(args[0]);
    } catch (NumberFormatException exp) {
      System.out.println("Exception converting string in main" + exp.getMessage());
      return;
    }

    pp = new actualPeerProcess(myPeerID);
    return;
  }
 private double calcMean(
     HashMap<Integer, String> singleGeneCaseValueMap,
     String groupType,
     String profileStableId) { // group type: altered or unaltered
   switch (groupType) {
     case "altered":
       int _index_altered = 0;
       double[] alteredArray = new double[alteredSampleIds.size()];
       for (Integer alteredSampleId : alteredSampleIds) {
         if (singleGeneCaseValueMap.containsKey(alteredSampleId)) {
           if (profileStableId.indexOf("rna_seq") != -1) {
             try {
               alteredArray[_index_altered] =
                   Math.log(Double.parseDouble(singleGeneCaseValueMap.get(alteredSampleId)))
                       / Math.log(2);
             } catch (NumberFormatException e) {
               e.getStackTrace();
             }
           } else {
             try {
               alteredArray[_index_altered] =
                   Double.parseDouble(singleGeneCaseValueMap.get(alteredSampleId));
             } catch (NumberFormatException e) {
               e.getStackTrace();
             }
           }
           _index_altered += 1;
         }
       }
       return StatUtils.mean(alteredArray);
     case "unaltered":
       int _index_unaltered = 0;
       double[] unalteredArray = new double[unalteredSampleIds.size()];
       for (Integer unalteredSampleId : unalteredSampleIds) {
         if (singleGeneCaseValueMap.containsKey(unalteredSampleId)) {
           if (profileStableId.indexOf("rna_seq") != -1) {
             try {
               unalteredArray[_index_unaltered] =
                   Math.log(Double.parseDouble(singleGeneCaseValueMap.get(unalteredSampleId)))
                       / Math.log(2);
             } catch (NumberFormatException e) {
               e.getStackTrace();
             }
           } else {
             try {
               unalteredArray[_index_unaltered] =
                   Double.parseDouble(singleGeneCaseValueMap.get(unalteredSampleId));
             } catch (NumberFormatException e) {
               e.getStackTrace();
             }
           }
           _index_unaltered += 1;
         }
       }
       return StatUtils.mean(unalteredArray);
     default:
       return Double.NaN; // error
   }
 }
 public List<Oriundo> listar() throws SQLException {
   List<Oriundo> resultado = new ArrayList<Oriundo>();
   conexao propCon = new conexao();
   Connection con =
       DriverManager.getConnection(
           new conexao().url,
           propCon.config.getString("usuario"),
           propCon.config.getString("senha"));
   PreparedStatement ps = null;
   ResultSet rs = null;
   String sqlListar = "SELECT * FROM oriundo Order by codigo DESC";
   Oriundo oriundo;
   try {
     ps = con.prepareStatement(sqlListar);
     rs = ps.executeQuery();
     // if(rs==null){
     // return null;
     // }
     while (rs.next()) {
       oriundo = new Oriundo();
       oriundo.setCodigo(rs.getInt("codigo"));
       oriundo.setDescricao(rs.getString("descricao"));
       oriundo.setData_cadastro(rs.getDate("data_cadastro"));
       oriundo.setDia_fechamento(rs.getInt("dia_fechamento"));
       oriundo.setDia_pag(rs.getInt("dia_pag"));
       resultado.add(oriundo);
     }
   } catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(
         null, "NumberFormaterExeption Erro: " + e.getMessage(), "ClasseDAO Func.Localizar", 0);
     e.printStackTrace();
   } catch (NullPointerException e) {
     JOptionPane.showMessageDialog(
         null, "NullPointerException Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } catch (SQLException e) {
     JOptionPane.showMessageDialog(
         null, "SQLException Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         null, "Exception Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } finally {
     ps.close();
     con.close();
   }
   return resultado;
 }
 private void feldFaktorActionPerformed(
     java.awt.event.ActionEvent evt) { // GEN-FIRST:event_feldFaktorActionPerformed
   try {
     int eingabefaktor = Integer.parseInt(feldFaktor.getText());
     if (eingabefaktor < 0) {
       System.out.println("Faktor < 0");
       feldFaktor.setSelectionStart(0);
       feldFaktor.setSelectionEnd(feldFaktor.getText().length());
     }
   } catch (NumberFormatException e) {
     System.out.println(e.toString());
     feldFaktor.setSelectionStart(0);
     feldFaktor.setSelectionEnd(feldFaktor.getText().length());
   }
 } // GEN-LAST:event_feldFaktorActionPerformed
    /**
     * Eclipse compiler hopefully only uses println(String).
     *
     * <p>{@inheritDoc}
     */
    public void println(String x) {
      if (x.startsWith("[completed ")) {
        int pos = x.lastIndexOf("#");
        int endpos = x.lastIndexOf("/");
        String fileno_str = x.substring(pos + 1, endpos - pos - 1);
        try {
          int fileno = Integer.parseInt(fileno_str);
          this.listener.progress(fileno, x);
        } catch (NumberFormatException _nfe) {
          Debug.log("could not parse eclipse compiler output: '" + x + "': " + _nfe.getMessage());
        }
      }

      super.println(x);
    }
 public void message(String s) {
   if (firstLine == null) firstLine = s;
   else {
     StringTokenizer st = new StringTokenizer(s, " ");
     try {
       st.nextToken();
       st.nextToken();
       st.nextToken();
       size = (new Integer(st.nextToken().trim())).longValue();
     } catch (NoSuchElementException e) {
       exception = new RunnerException(e.toString());
     } catch (NumberFormatException e) {
       exception = new RunnerException(e.toString());
     }
   }
 }
  /**
   * This method gets called when a property we're interested in is about to change. In case we
   * don't like the new value we throw a PropertyVetoException to prevent the actual change from
   * happening.
   *
   * @param evt a <tt>PropertyChangeEvent</tt> object describing the event source and the property
   *     that will change.
   * @exception PropertyVetoException if we don't want the change to happen.
   */
  public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
    if (evt.getPropertyName().equals(PROP_STUN_SERVER_ADDRESS)) {
      // make sure that we have a valid fqdn or ip address.

      // null or empty port is ok since it implies turning STUN off.
      if (evt.getNewValue() == null) return;

      String host = evt.getNewValue().toString();
      if (host.trim().length() == 0) return;

      boolean ipv6Expected = false;
      if (host.charAt(0) == '[') {
        // This is supposed to be an IPv6 litteral
        if (host.length() > 2 && host.charAt(host.length() - 1) == ']') {
          host = host.substring(1, host.length() - 1);
          ipv6Expected = true;
        } else {
          // This was supposed to be a IPv6 address, but it's not!
          throw new PropertyVetoException("Invalid address string" + host, evt);
        }
      }

      for (int i = 0; i < host.length(); i++) {
        char c = host.charAt(i);
        if (Character.isLetterOrDigit(c)) continue;

        if ((c != '.' && c != ':') || (c == '.' && ipv6Expected) || (c == ':' && !ipv6Expected))
          throw new PropertyVetoException(host + " is not a valid address nor host name", evt);
      }

    } // is prop_stun_server_address
    else if (evt.getPropertyName().equals(PROP_STUN_SERVER_PORT)) {

      // null or empty port is ok since it implies turning STUN off.
      if (evt.getNewValue() == null) return;

      String port = evt.getNewValue().toString();
      if (port.trim().length() == 0) return;

      try {
        Integer.valueOf(evt.getNewValue().toString());
      } catch (NumberFormatException ex) {
        throw new PropertyVetoException(port + " is not a valid port! " + ex.getMessage(), evt);
      }
    }
  }
  private double runTTest(HashMap<Integer, String> singleGeneCaseValueMap, String profileStableId)
      throws IllegalArgumentException {

    double[] unalteredArray = new double[unalteredSampleIds.size()];
    double[] alteredArray = new double[alteredSampleIds.size()];
    int _index_unaltered = 0, _index_altered = 0;

    for (Integer alteredSampleId : alteredSampleIds) {
      if (singleGeneCaseValueMap.containsKey(alteredSampleId)) {
        if (profileStableId.indexOf("rna_seq") != -1) {
          try {
            alteredArray[_index_altered] =
                Math.log(Double.parseDouble(singleGeneCaseValueMap.get(alteredSampleId)))
                    / Math.log(2);
          } catch (NumberFormatException e) {
            e.getStackTrace();
          }
        } else {
          try {
            alteredArray[_index_altered] =
                Double.parseDouble(singleGeneCaseValueMap.get(alteredSampleId));
          } catch (NumberFormatException e) {
            e.getStackTrace();
          }
        }
        _index_altered += 1;
      }
    }
    for (Integer unalteredSampleId : unalteredSampleIds) {
      if (singleGeneCaseValueMap.containsKey(unalteredSampleId)) {
        if (profileStableId.indexOf("rna_seq") != -1) {
          try {
            unalteredArray[_index_unaltered] =
                Math.log(Double.parseDouble(singleGeneCaseValueMap.get(unalteredSampleId)))
                    / Math.log(2);
          } catch (NumberFormatException e) {
            e.getStackTrace();
          }
        } else {
          try {
            unalteredArray[_index_unaltered] =
                Double.parseDouble(singleGeneCaseValueMap.get(unalteredSampleId));
          } catch (NumberFormatException e) {
            e.getStackTrace();
          }
        }
        _index_unaltered += 1;
      }
    }

    if (alteredArray.length < 2 || unalteredArray.length < 2) return Double.NaN;
    else {
      double pvalue = TestUtils.tTest(alteredArray, unalteredArray);
      return pvalue;
    }
  }
 public Oriundo localizar(Integer codigo) throws SQLException {
   Connection con =
       DriverManager.getConnection(
           new conexao().url,
           new conexao().config.getString("usuario"),
           new conexao().config.getString("senha"));
   PreparedStatement ps = null;
   ResultSet rs = null;
   String sqlLocalizar = "SELECT * FROM oriundo WHERE codigo=?";
   Oriundo oriundo = new Oriundo();
   try {
     ps = con.prepareStatement(sqlLocalizar);
     ps.setInt(1, codigo);
     rs = ps.executeQuery();
     // if(!rs.next()){
     // return null;
     // }
     oriundo.setCodigo(rs.getInt("codigo"));
     oriundo.setDescricao(rs.getString("descricao"));
     oriundo.setData_cadastro(rs.getDate("data_cadastro"));
     oriundo.setDia_fechamento(rs.getInt("dia_fechamento"));
     oriundo.setDia_pag(rs.getInt("dia_pag"));
     return oriundo;
   } catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(
         null, "NumberFormaterExeption Erro: " + e.getMessage(), "ClasseDAO Func.Localizar", 0);
     e.printStackTrace();
   } catch (NullPointerException e) {
     JOptionPane.showMessageDialog(
         null, "NullPointerException Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } catch (SQLException e) {
     JOptionPane.showMessageDialog(
         null, "SQLException Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         null, "Exception Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } finally {
     ps.close();
     con.close();
   }
   return oriundo;
 }
 private double calcSTDev(
     HashMap<Integer, String> singleGeneCaseValueMap, String groupType, String profileStableId) {
   switch (groupType) {
     case "altered":
       DescriptiveStatistics stats_altered = new DescriptiveStatistics();
       for (Integer alteredSampleId : alteredSampleIds) {
         if (singleGeneCaseValueMap.containsKey(alteredSampleId)) {
           if (profileStableId.indexOf("rna_seq") != -1) {
             try {
               stats_altered.addValue(
                   Math.log(Double.parseDouble(singleGeneCaseValueMap.get(alteredSampleId)))
                       / Math.log(2));
             } catch (NumberFormatException e) {
               e.getStackTrace();
             }
           } else {
             try {
               stats_altered.addValue(
                   Double.parseDouble(singleGeneCaseValueMap.get(alteredSampleId)));
             } catch (NumberFormatException e) {
               e.getStackTrace();
             }
           }
         }
       }
       return stats_altered.getStandardDeviation();
     case "unaltered":
       DescriptiveStatistics stats_unaltered = new DescriptiveStatistics();
       for (Integer unalteredSampleId : unalteredSampleIds) {
         if (singleGeneCaseValueMap.containsKey(unalteredSampleId)) {
           if (profileStableId.indexOf("rna_seq") != -1) {
             try {
               stats_unaltered.addValue(
                   Math.log(Double.parseDouble(singleGeneCaseValueMap.get(unalteredSampleId)))
                       / Math.log(2));
             } catch (NumberFormatException e) {
               e.getStackTrace();
             }
           } else {
             try {
               stats_unaltered.addValue(
                   Double.parseDouble(singleGeneCaseValueMap.get(unalteredSampleId)));
             } catch (NumberFormatException e) {
               e.getStackTrace();
             }
           }
         }
       }
       return stats_unaltered.getStandardDeviation();
     default:
       return Double.NaN; // error
   }
 }
Exemple #22
0
 public List<Object> readExcel(Workbook wb, Class clz, int readLine, int tailLine) {
   Sheet sheet = wb.getSheetAt(0); // 取第一张表
   List<Object> objs = null;
   try {
     Row row = sheet.getRow(readLine); // 开始行,主题栏
     objs = new ArrayList<Object>();
     Map<Integer, String> maps = getHeaderMap(row, clz); // 设定对应的字段顺序与方法名
     if (maps == null || maps.size() <= 0)
       throw new RuntimeException("要读取的Excel的格式不正确,检查是否设定了合适的行"); // 与order顺序不符
     for (int i = readLine + 1; i <= sheet.getLastRowNum() - tailLine; i++) { // 取数据
       row = sheet.getRow(i);
       Object obj = clz.newInstance(); //   调用无参结构
       for (Cell c : row) {
         int ci = c.getColumnIndex();
         String mn = maps.get(ci).substring(3); // 消除get
         mn = mn.substring(0, 1).toLowerCase() + mn.substring(1);
         Map<String, Object> params = new HashMap<String, Object>();
         if (!"enterDate".equals(mn)) c.setCellType(Cell.CELL_TYPE_STRING); // 设置单元格格式
         else c.setCellType(Cell.CELL_TYPE_NUMERIC);
         if (this.getCellValue(c).trim().equals("是")) {
           BeanUtils.copyProperty(obj, mn, 1);
         } else if (this.getCellValue(c).trim().equals("否")) {
           BeanUtils.copyProperty(obj, mn, 0);
         } else BeanUtils.copyProperty(obj, mn, this.getCellValue(c));
       }
       objs.add(obj);
     }
   } catch (InstantiationException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (IllegalAccessException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (InvocationTargetException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (NumberFormatException e) {
     e.printStackTrace();
     logger.error(e);
   }
   return objs;
 }
Exemple #23
0
  private void processFrames(Element element) {
    NodeList elements = element.getChildNodes();
    if (elements.getLength() > 0) {
      Map<String, ReferenceFrame> frames = new HashMap();
      for (ReferenceFrame f : FrameManager.getFrames()) {
        frames.put(f.getName(), f);
      }
      List<ReferenceFrame> reorderedFrames = new ArrayList();

      for (int i = 0; i < elements.getLength(); i++) {
        Node childNode = elements.item(i);
        if (childNode.getNodeName().equalsIgnoreCase(SessionElement.FRAME.getText())) {
          String frameName = getAttribute((Element) childNode, SessionAttribute.NAME.getText());

          ReferenceFrame f = frames.get(frameName);
          if (f != null) {
            reorderedFrames.add(f);
            try {
              String chr = getAttribute((Element) childNode, SessionAttribute.CHR.getText());
              final String startString =
                  getAttribute((Element) childNode, SessionAttribute.START.getText())
                      .replace(",", "");
              final String endString =
                  getAttribute((Element) childNode, SessionAttribute.END.getText())
                      .replace(",", "");
              int start = ParsingUtils.parseInt(startString);
              int end = ParsingUtils.parseInt(endString);
              org.broad.igv.feature.Locus locus = new Locus(chr, start, end);
              f.jumpTo(locus);
            } catch (NumberFormatException e) {
              e.printStackTrace(); // To change body of catch statement use File | Settings |
              // File Templates.
            }
          }
        }
      }
      if (reorderedFrames.size() > 0) {
        FrameManager.setFrames(reorderedFrames);
      }
    }
    IGV.getInstance().resetFrames();
  }
Exemple #24
0
 /**
  * @return a double parsed from the value associated with the given key in the given Properties.
  *     returns "def" in key wasn't found, or if a parsing error occured. If "value" contains a "%"
  *     sign, we use a <code>NumberFormat.getPercentInstance</code> to convert it to a double.
  */
 public static double parseProperty(Properties preferences, String key, double def) {
   NumberFormat formatPercent = NumberFormat.getPercentInstance(Locale.US); // for zoom factor
   String val = preferences.getProperty(key);
   if (val == null) return def;
   if (val.indexOf("%") == -1) { // not in percent format !
     try {
       return Double.parseDouble(val);
     } catch (NumberFormatException nfe) {
       nfe.printStackTrace();
       return def;
     }
   }
   // else it's a percent format -> parse it
   try {
     Number n = formatPercent.parse(val);
     return n.doubleValue();
   } catch (ParseException ex) {
     ex.printStackTrace();
     return def;
   }
 }
 public void atualizar(Oriundo oriundo) throws SQLException {
   Connection con =
       DriverManager.getConnection(
           new conexao().url,
           new conexao().config.getString("usuario"),
           new conexao().config.getString("senha"));
   PreparedStatement ps = null;
   String sqlAtualizar =
       "UPDATE oriundo SET descricao=?, data_cadastro=?, dia_fechamento=?, dia_pag=? WHERE codigo=?";
   try {
     ps = con.prepareStatement(sqlAtualizar);
     ps.setString(1, oriundo.getDescricao());
     ps.setDate(2, oriundo.getData_cadastro());
     ps.setInt(3, oriundo.getDia_fechamento());
     ps.setInt(4, oriundo.getDia_pag());
     ps.setInt(5, oriundo.getCodigo());
     ps.executeUpdate();
     JOptionPane.showMessageDialog(
         null, "Atualizado Com Sucesso: ", "Mensagem do Sistema - Atualizar", 1);
   } catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(
         null, "NumberFormaterExeption Erro: " + e.getMessage(), "ClasseDAO Func.Atualizar", 0);
     e.printStackTrace();
   } catch (NullPointerException e) {
     JOptionPane.showMessageDialog(
         null, "NullPointerException Erro: " + e.getMessage(), "ClasseDAO Func. Atualizar", 0);
     e.printStackTrace();
   } catch (SQLException e) {
     JOptionPane.showMessageDialog(
         null, "SQLException Erro: " + e.getMessage(), "ClasseDAO Func. Atualizar", 0);
     e.printStackTrace();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         null, "Exception Erro: " + e.getMessage(), "ClasseDAO Func. Atualizar", 0);
     e.printStackTrace();
   } finally {
     ps.close();
     con.close();
   }
 }
 public void salvar(Oriundo oriundo) throws SQLException {
   Connection con =
       DriverManager.getConnection(
           new conexao().url,
           new conexao().config.getString("usuario"),
           new conexao().config.getString("senha"));
   PreparedStatement ps = null;
   String sqlSalvar =
       "INSERT INTO oriundo (descricao, data_cadastro, dia_fechamento, dia_pag ) VALUES (?, ?, ?, ?)";
   try {
     ps = con.prepareStatement(sqlSalvar);
     ps.setString(1, oriundo.getDescricao());
     ps.setDate(2, oriundo.getData_cadastro());
     ps.setInt(3, oriundo.getDia_fechamento());
     ps.setInt(4, oriundo.getDia_pag());
     ps.executeUpdate();
     // JOptionPane.showMessageDialog(null, "Inserido Com Sucesso: ", "Mensagem do Sistema -
     // Salvar", 1);
   } catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(
         null, "NumberFormaterExeption Erro: " + e.getMessage(), "ClasseDAO Func.Salvar", 0);
     e.printStackTrace();
   } catch (NullPointerException e) {
     JOptionPane.showMessageDialog(
         null, "NullPointerException Erro: " + e.getMessage(), "ClasseDAO Func. Salvar", 0);
     e.printStackTrace();
   } catch (SQLException e) {
     JOptionPane.showMessageDialog(
         null, "SQLException Erro: " + e.getMessage(), "ClasseDAO Func. Salvar", 0);
     e.printStackTrace();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         null, "Exception Erro: " + e.getMessage(), "ClasseDAO Func. Salvar", 0);
     e.printStackTrace();
   } finally {
     ps.close();
     con.close();
   }
 }
Exemple #27
0
  protected void getDimensionsFromLogFile(BufferedReader reader, PicText text) {
    if (reader == null) {
      return;
    }
    String line = ""; // il rale si j'initialise pas ...
    boolean finished = false;
    while (!finished) {
      try {
        line = reader.readLine();
      } catch (IOException ioex) {
        ioex.printStackTrace();
        return;
      }
      if (line == null) {
        System.out.println("Size of text not found in log file...");
        return;
      }

      System.out.println(line);
      Matcher matcher = LogFilePattern.matcher(line);

      if (line != null && matcher.find()) {
        System.out.println("FOUND :" + line);
        finished = true;
        try {
          text.setDimensions(
              0.3515 * Double.parseDouble(matcher.group(1)), // height, pt->mm (1pt=0.3515 mm)
              0.3515 * Double.parseDouble(matcher.group(2)), // width
              0.3515 * Double.parseDouble(matcher.group(3))); // depth
          areDimensionsComputed = true;
        } catch (NumberFormatException e) {
          System.out.println("Logfile number format problem: $line" + e.getMessage());
        } catch (IndexOutOfBoundsException e) {
          System.out.println("Logfile regexp problem: $line" + e.getMessage());
        }
      }
    }
    return;
  }
Exemple #28
0
  public static Dice parse(String dt) {
    Dice ret = null;
    try {
      dt = dt.toUpperCase();
      String[] diceparts = dt.split(DICE_TOKEN_S);
      if (diceparts.length == 2) {
        int nThrows = Integer.valueOf(diceparts[0]), nFaces = 0, modifier = 0;
        String nFacesBld = "";
        OperatorType opType = null;
        char[] faceParts = diceparts[1].toCharArray();
        for (char c : faceParts) {
          String current = String.valueOf(c);
          if (Utils.isInteger(current)) {
            nFacesBld = nFacesBld.concat(current);
          } else if ((opType = OperatorType.parseOperator(c)) != null) {
            break;
          } else {
            break;
          }
        }
        nFaces = Integer.valueOf(nFacesBld);

        if (opType != null) {
          String[] bonusParts = diceparts[1].split(opType.toEscapedString());
          if ((bonusParts.length == 2) && Utils.isInteger(bonusParts[1])) {
            modifier = Integer.valueOf(bonusParts[1]);
          }
          ret = new Dice(nThrows, nFaces, opType, modifier);
        } else {
          ret = new Dice(nThrows, nFaces);
        }
      }
    } catch (NumberFormatException e) {
      e.printStackTrace();
      ret = null;
    }
    return ret;
  }
Exemple #29
0
  public static double TCSValue(
      int[][] alignmentInstance, AlignmentMaker am, Configuration config) {
    String filename =
        config.temporaryFileDirectory
            + "tmp"
            + alignmentInstance.hashCode()
            + "_"
            + am.hashCode()
            + "_"
            + config.hashCode()
            + "_"
            + am.in.hashCode();

    int oldVerbosity = am.in.verbosity;
    am.in.verbosity = -1;
    am.printOutput(alignmentInstance, filename);
    am.in.verbosity = oldVerbosity;

    String command =
        config.tcoffeeDirectory
            + "t_coffee -infile "
            + filename
            + " -evaluate -method proba_pair -output score_ascii -outfile=stdout";
    String result = "-1";
    try {
      result = execCmd(command);
      execCmd("rm " + filename);
    } catch (NumberFormatException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    // System.err.println("Command: \""+command+"\"\nPre Parse Line: \""+result+"\"");
    return Double.parseDouble(result) / 100.0;
  }
Exemple #30
0
  public VirtualMachine attach(Map arguments)
      throws IOException, IllegalConnectorArgumentsException {
    int pid = 0;
    try {
      pid = Integer.parseInt(argument(ARG_PID, arguments).value());
    } catch (NumberFormatException nfe) {
      throw (IllegalConnectorArgumentsException)
          new IllegalConnectorArgumentsException(nfe.getMessage(), ARG_PID).initCause(nfe);
    }

    checkProcessAttach(pid);

    VirtualMachine myVM = null;
    try {
      try {
        Class vmImplClass = loadVirtualMachineImplClass();
        myVM = createVirtualMachine(vmImplClass, pid);
      } catch (InvocationTargetException ite) {
        Class vmImplClass = handleVMVersionMismatch(ite);
        if (vmImplClass != null) {
          return createVirtualMachine(vmImplClass, pid);
        } else {
          throw ite;
        }
      }
    } catch (Exception ee) {
      if (DEBUG) {
        System.out.println("VirtualMachineImpl() got an exception:");
        ee.printStackTrace();
        System.out.println("pid = " + pid);
      }
      throw (IOException) new IOException().initCause(ee);
    }
    setVMDisposeObserver(myVM);
    return myVM;
  }