Пример #1
1
 /**
  * This is for debug only: print out training matrices in a CSV type format so that the matrices
  * can be examined in a spreadsheet program for debugging purposes.
  */
 private void WriteCSVfile(
     List<String> rowNames, List<String> colNames, float[][] buf, String fileName) {
   p("tagList.size()=" + tagList.size());
   try {
     FileWriter fw = new FileWriter(fileName + ".txt");
     PrintWriter bw = new PrintWriter(new BufferedWriter(fw));
     // write the first title row:
     StringBuffer sb = new StringBuffer(500);
     for (int i = 0, size = colNames.size(); i < size; i++) {
       sb.append("," + colNames.get(i));
     }
     bw.println(sb.toString());
     // loop on remaining rows:
     for (int i = 0, size = buf.length; i < size; i++) {
       sb.delete(0, sb.length());
       sb.append(rowNames.get(i));
       for (int j = 0, size2 = buf[i].length; j < size2; j++) {
         sb.append("," + buf[i][j]);
       }
       bw.println(sb.toString());
     }
     bw.close();
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
 }
  public GElement generateGraph(String dotFile) throws IOException {

    BufferedReader br = new BufferedReader(new FileReader(dotFile));
    graph = null;

    /**
     * The problem here is that DOT sometime inserts a '\' at the end of a long line so we have to
     * skip it and continue to parse until a "real" EOL is reached. Example: statement ->
     * compoundStatement [pos="e,3264,507 3271,2417 3293,2392 ... 3237,565 3234,560 32\ 39,545
     * 3243,534 3249,523 3257,514"];
     */
    StringBuffer line = new StringBuffer();
    int c; // current character
    int pc = -1; // previous character
    while ((c = br.read()) != -1) {
      if (c == '\n') {
        if (pc == '\\') {
          // Remove the last \ if it was part of the DOT wrapping character
          line.deleteCharAt(line.length() - 1);
        } else {
          GElement element = parseLine(line.toString());
          if (element != null) {
            if (graph == null) graph = element;
            else graph.addElement(element);
          }
          line.delete(0, line.length());
        }
      } else if (c != '\r') {
        line.append((char) c);
      }
      pc = c;
    }
    return graph;
  }
Пример #3
0
  private void dispatch(final boolean fireOnlyIfMixed) throws SAXException {
    if (fireOnlyIfMixed && buffer.length() == 0) return; // skip it

    Object[] ctx = (Object[]) context.peek();
    String here = (String) ctx[0];
    Attributes attrs = (Attributes) ctx[1];
    buffer.delete(0, buffer.length());
  }
Пример #4
0
  private void onReceiveChar(char character) {

    buffer.append(character);

    if (buffer.charAt(buffer.length() - 1) == '\n') {
      onReceiveLine(buffer.toString());
      buffer.delete(0, buffer.length());
    }
  }
Пример #5
0
 private static void replace(String source, String pattern, String replace, StringBuffer builder) {
   int pos = 0;
   int pl = pattern.length();
   builder.delete(0, builder.length());
   while (pos < source.length()) {
     int np = source.indexOf(pattern, pos);
     if (np == -1) break;
     builder.append(source.substring(pos, np));
     builder.append(replace);
     pos = np + pl;
   }
   builder.append(source.substring(pos));
 }
Пример #6
0
  boolean removeFromLine(int xFrom, int xTo, int y) {
    try {
      // getLine
      StringBuffer currentLine = (StringBuffer) vectorLines.elementAt(y);

      currentLine.delete(xFrom, xTo);
      // setLine
      vectorLines.setElementAt(currentLine, y);
      return true;
    } catch (Exception ex) {
      System.out.println(ex.toString() + " in removeFromLine()");
      return false;
    }
  }
Пример #7
0
  // crear una sucesion de cuadrados
  static void cuadrado() {
    // 1, 4, 9, 16, 25, 36, 49, 64, 81,
    try {
      String s1 =
          JOptionPane.showInputDialog(
              "Ingrese un numero hasta la que desea ver la sucesion de cuadrados :");
      int limite = Integer.parseInt(s1);
      StringBuffer sb = new StringBuffer();
      for (int numero = 1, sqrt = 1; numero < limite; sqrt = ++numero * numero) {
        sb.append(sqrt + " , ");
      }

      int largo = sb.length();
      JOptionPane.showMessageDialog(null, "Sucesion sqrt = " + sb.delete(largo - 2, largo));
    } catch (NumberFormatException e) {
      JOptionPane.showMessageDialog(null, "No ha ingresado un numero !");
    }
  }
  // Generate css-file
  private String generateCssStyles(String param) {
    String sessionId;
    if (!param.contains("sessionid")) {
      return "";
    }
    sessionId = param.substring(param.indexOf("sessionid=") + 10);

    Map<MyTextAttributes, Integer> mapAttributes = mapCss.get(Integer.parseInt(sessionId));
    StringBuffer buffer = new StringBuffer();
    buffer.append(
        "body { font-family: monospace; font-size: 12px; color: #000000; background-color: #FFFFFF;} ");
    buffer.append(
        " a {text-decoration: none; color: #000000;} span.highlighting { background-color: yellow !important;}");
    buffer.append(
        " a span {text-decoration: none; color: #000000;} a:hover span {color: blue; text-decoration: underline;}");
    if (mapAttributes != null) {
      for (MyTextAttributes attr : mapAttributes.keySet()) {
        buffer.append("\nspan.class");
        buffer.append(mapAttributes.get(attr)).append("{");
        String tmp = MyBaseHandler.getColor(attr.getForegroundColor());
        if (!tmp.equals("#000000")) {
          buffer.append("color: ").append(tmp).append("; ");
        }
        tmp = MyBaseHandler.getColor(attr.getBackgroundColor());
        if (!tmp.equals("#ffffff")) {
          buffer.append("background-color: ").append(tmp).append("; ");
        }
        buffer.append(MyBaseHandler.getFontType(attr.getFontType())).append(" ");
        if (attr.getEffectType().equals(EffectType.LINE_UNDERSCORE)) {
          buffer.append("text-decoration: underline; ").append("; ");
        }
        buffer.append("}");

        // Cut empty styles
        tmp = "\nspan.class" + mapAttributes.get(attr) + "{ }";
        int position = buffer.toString().indexOf(tmp);
        if (position != -1) {
          buffer = buffer.delete(position, buffer.length());
        }
      }
    }
    return buffer.toString();
  }
Пример #9
0
 /**
  * replace variables in a string with the value in a BizData object;
  *
  * @param src the source string object;
  * @param d the BizData object contains the values;
  * @return the result string that variables have been replaced;
  */
 public static final String replace(String src, BizData d) {
   int i = 0;
   int len = 0;
   int tempLen = 0;
   boolean beginSP = false;
   StringBuffer sb = new StringBuffer(1024);
   StringBuffer temp = new StringBuffer(1024);
   if (src == null) {
     return null;
   }
   len = src.length();
   while (i < len) {
     char ch = src.charAt(i);
     if (ch != StringConvertor.SP_CHAR) {
       if (beginSP) {
         temp.append(ch);
       } else {
         sb.append(ch);
       }
     } else {
       if (beginSP) {
         if ((tempLen = temp.length()) < 1) {
           sb.append(StringConvertor.SP_CHAR);
           beginSP = false;
         } else {
           String fpath = new String(temp);
           String value = d.getStringByPath(fpath);
           sb.append(value);
           temp.delete(0, tempLen);
           beginSP = false;
         }
       } else {
         beginSP = true;
       }
     }
     i++;
   }
   if (temp.length() > 0) {
     sb.append(StringConvertor.SP_CHAR).append(temp);
   }
   return new String(sb);
 }
Пример #10
0
 /**
  * encode variables in a string.
  *
  * @param src the source string that contains variables to be encoded;
  * @return
  * @throws UnsupportedEncodingException
  */
 public static final String encode(String src) throws UnsupportedEncodingException {
   int i = 0;
   int len = 0;
   int tempLen = 0;
   boolean beginEC = false;
   StringBuffer sb = new StringBuffer(1024);
   StringBuffer temp = new StringBuffer(1024);
   if (src == null) {
     return null;
   }
   len = src.length();
   while (i < len) {
     char ch = src.charAt(i);
     if (ch != StringConvertor.EC_CHAR) {
       if (beginEC) {
         temp.append(ch);
       } else {
         sb.append(ch);
       }
     } else {
       if (beginEC) {
         if ((tempLen = temp.length()) < 1) {
           sb.append(StringConvertor.EC_CHAR);
           beginEC = false;
         } else {
           String orgValue = new String(temp);
           String encValue = URLEncoder.encode(orgValue, StringConvertor.CHARSET);
           sb.append(encValue);
           temp.delete(0, tempLen);
           beginEC = false;
         }
       } else {
         beginEC = true;
       }
     }
     i++;
   }
   if (temp.length() > 0) {
     sb.append(StringConvertor.EC_CHAR).append(temp);
   }
   return new String(sb);
 }
Пример #11
0
  /**
   * @param sb
   * @param from
   * @param src
   * @return
   */
  public static int getNextLine(StringBuffer sb, int from, String src) {
    boolean inStr = false;
    boolean inComment = false;

    int len = src.length();
    sb.delete(0, sb.length());
    for (; from < len - 1; from++) {
      char ch = src.charAt(from);
      switch (ch) {
        case '/':
          if (inStr) {
            sb.append(ch);
          } else if (inComment) {
          } else {
            char chNext = src.charAt(from + 1);
            if (chNext == '*') {
              inComment = true;
              from++;
            } else if (chNext == '/') {
              from += 2;
              while (from < len) {
                char rn = src.charAt(from);
                if (rn == '\r' || rn == '\n') {
                  if (from < len - 1) {
                    if (src.charAt(from + 1) == '\r' || src.charAt(from + 1) == '\n') {
                      from++;
                    }
                  }
                  break;
                }
                from++;
              }
            }
          }
          break;
        case '*':
          break;
      }
    }
    return from;
  }
Пример #12
0
  boolean divideLine(int x, int y) // fire <=> enter + insert when # pressed
      {
    try {
      // getLine
      StringBuffer currentLine = (StringBuffer) vectorLines.elementAt(y);

      String newLine = currentLine.toString().substring(x, currentLine.toString().length());

      currentLine.delete(x, currentLine.length());
      // setLine
      vectorLines.setElementAt(currentLine, y);

      if (shiftDown(y)) {
        vectorLines.setElementAt(new StringBuffer(newLine), y + 1);
      }

      return true;
    } catch (Exception ex) {
      System.out.println(ex.toString() + " in divideLine()");
      return false;
    }
  }
Пример #13
0
 public void write(int b) throws IOException {
   ostream.write(b);
   if (out != null) out.write(b);
   lastLine.append((char) b);
   if (regexp) {
     // match against regular expression on end-of-line
     if (b == '\n') {
       if (lastLine.toString().matches(checkFor)) {
         found = true;
         foundLine = lastLine.toString();
         alertListeners(foundLine);
       }
     }
   } else {
     // store data in buffer of same length as string trying to match
     buf[bufOffset] = (char) b;
     bufOffset++;
     if (bufOffset >= buf.length) bufOffset = 0;
     // check against string. Since same length, when string is found bufOffset
     // will be at start of string.
     boolean matched = true;
     for (int i = 0; i < buf.length; i++) {
       int y = (i + bufOffset) % buf.length;
       if (checkFor.charAt(i) != buf[y]) {
         matched = false;
         break;
       }
     }
     if (matched) {
       found = true;
       foundLine = lastLine.toString();
       alertListeners(foundLine);
     }
   }
   if (b == '\n') {
     lastLine.delete(0, lastLine.length());
   }
 }
Пример #14
0
  /** Find out the type of the current word */
  private int processWord(StringBuffer curWord, int wordContext) throws SchemaParseException {
    String word = curWord.toString();
    int len = word.length();

    if (len > 0) {
      //	We have some word to play with
      switch (wordContext) {
        case WORD_CHECK:
          if (word.startsWith("--")) { // NOI18N
            if (len > 2) word = curWord.substring(2);
            else word = ""; // NOI18N

            this.handler.startElement(word, word, Common.COMMENT);
            wordContext = WORD_COMMENT;
          } else if (word.equals("ELEMENT")) // NOI18N
          wordContext = WORD_ELEMENT1;
          else if (word.equals("ATTLIST")) // NOI18N
          wordContext = WORD_ATTLIST1;
          else if (word.equals("ENTITY")) // NOI18N
          wordContext = WORD_ENTITY1;
          else {
            // System.err.println("Error: found an unknown '<!' sequence (" + word + ")");	// NOI18N
            throw new SchemaParseException(
                "Error: found an unknown '<!' sequence (" + word + ")"); // NOI18N
          }
          break;
        case WORD_COMMENT:
          this.handler.element(word, word, 0);
          break;
        case WORD_ELEMENT1:
          this.handler.startElement(word, word, Common.ELEMENT);
          wordContext = WORD_ELEMENT;
          break;
        case WORD_ATTLIST1:
          this.handler.startElement(word, word, Common.ATTLIST);
          wordContext = WORD_ATTLIST;
          break;
        case WORD_ENTITY1:
          wordContext = WORD_ENTITY;
          break;
        case WORD_ENTITY:
          break;
        case WORD_ELEMENT:
        case WORD_ATTLIST:
          // Find out the instance value (*, ? or +)
          int instance = this.getInstanceValue(word.charAt(len - 1));
          //	Get rid of the extra character
          if (instance != Common.TYPE_1) word = curWord.substring(0, len - 1);

          try {
            this.handler.element(word, word, instance);
          } catch (MissingEndOfEltException e) {
            if (wordContext == WORD_ATTLIST) {
              //
              //  The TreeBuilder is done with the previous
              //  attribute and would expect an end of ATTLIST
              //  declaration.
              //  We might have several attributes declared on the
              //  same ATTLIST declaration.
              //  Let's continue assuming so, the TreeBuilder
              //  checks the attribute semantic and will throw
              // if this is not the case.
              //
              this.handler.startElement(e.propName, e.propName, Common.ATTLIST);
              this.handler.element(word, word, instance);
            }
          }

          break;
        default:
      }
      curWord.delete(0, len);
    }
    return wordContext;
  }
Пример #15
0
 private void clearBufferedWhiteSpace() {
   whitespaceBuffer.delete(0, whitespaceBuffer.length());
   currentlyBufferingWhitespace = false;
 }
Пример #16
0
  public static final HTTPStream createHTTPStream(
      String address,
      boolean isPost,
      byte[] postData,
      String headers,
      int timeOutMs,
      int[] statusCode,
      StringBuffer responseHeaders,
      int numRedirectsToFollow) {
    // timeout parameter of zero for HttpUrlConnection is a blocking connect (negative value for
    // juce::URL)
    if (timeOutMs < 0) timeOutMs = 0;
    else if (timeOutMs == 0) timeOutMs = 30000;

    // headers - if not empty, this string is appended onto the headers that are used for the
    // request. It must therefore be a valid set of HTML header directives, separated by newlines.
    // So convert headers string to an array, with an element for each line
    String headerLines[] = headers.split("\\n");

    for (; ; ) {
      try {
        HttpURLConnection connection = (HttpURLConnection) (new URL(address).openConnection());

        if (connection != null) {
          try {
            connection.setInstanceFollowRedirects(false);
            connection.setConnectTimeout(timeOutMs);
            connection.setReadTimeout(timeOutMs);

            // Set request headers
            for (int i = 0; i < headerLines.length; ++i) {
              int pos = headerLines[i].indexOf(":");

              if (pos > 0 && pos < headerLines[i].length()) {
                String field = headerLines[i].substring(0, pos);
                String value = headerLines[i].substring(pos + 1);

                if (value.length() > 0) connection.setRequestProperty(field, value);
              }
            }

            if (isPost) {
              connection.setRequestMethod("POST");
              connection.setDoOutput(true);

              if (postData != null) {
                OutputStream out = connection.getOutputStream();
                out.write(postData);
                out.flush();
              }
            }

            HTTPStream httpStream = new HTTPStream(connection, statusCode, responseHeaders);

            // Process redirect & continue as necessary
            int status = statusCode[0];

            if (--numRedirectsToFollow >= 0
                && (status == 301 || status == 302 || status == 303 || status == 307)) {
              // Assumes only one occurrence of "Location"
              int pos1 = responseHeaders.indexOf("Location:") + 10;
              int pos2 = responseHeaders.indexOf("\n", pos1);

              if (pos2 > pos1) {
                String newLocation = responseHeaders.substring(pos1, pos2);
                // Handle newLocation whether it's absolute or relative
                URL baseUrl = new URL(address);
                URL newUrl = new URL(baseUrl, newLocation);
                String transformedNewLocation = newUrl.toString();

                if (transformedNewLocation != address) {
                  address = transformedNewLocation;
                  // Clear responseHeaders before next iteration
                  responseHeaders.delete(0, responseHeaders.length());
                  continue;
                }
              }
            }

            return httpStream;
          } catch (Throwable e) {
            connection.disconnect();
          }
        }
      } catch (Throwable e) {
      }

      return null;
    }
  }
Пример #17
0
  /** Parse the document, calling back the handler */
  void parse() throws IOException, SchemaParseException {
    char c;
    StringBuffer curWord = new StringBuffer();
    int wordContext = WORD_NO_CONTEXT;
    int level = 0;

    while ((c = this.getNext()) != '\0') {
      switch (c) {
        case '<':
          //	Check if we have <! or <--
          char c1 = this.getNext();
          if (c1 == '!') {
            //	Check if the next word is reserved
            if (wordContext != WORD_NO_CONTEXT && wordContext != WORD_COMMENT) {
              System.err.println(
                  "Error: found a '<!' sequence within another '<!' sequence"); // NOI18N
              throw new SchemaParseException(
                  "Warning: found a '<!' sequence within another '<!' sequence"); // NOI18N
            }
            if (wordContext != WORD_COMMENT) wordContext = WORD_CHECK;
          } else if (c1 == '?') {
            wordContext = WORD_PI;
          } else {
            curWord.append(c);
            curWord.append(c1);
          }
          break;
        case '>':
          //	Might be the end of a comment or <!element
          switch (wordContext) {
            case WORD_NO_CONTEXT:
              // System.err.println("Error: Found '>' without '<!'");// NOI18N
              throw new SchemaParseException("Error: Found '>' without '<!'"); // NOI18N
            case WORD_PI:
              String word = curWord.toString();
              int len = word.length();
              if (word.endsWith("?")) { // NOI18N
                //	Ignore any PI
                curWord.delete(0, len);
                wordContext = WORD_NO_CONTEXT;
              } else curWord.append(c);
              break;
            case WORD_COMMENT:
              word = curWord.toString();
              len = word.length();
              if (word.endsWith("--")) { // NOI18N
                this.handler.endElement();
                curWord.delete(0, len);
                wordContext = WORD_NO_CONTEXT;
              } else curWord.append(c);
              break;
            case WORD_ENTITY:
              wordContext = WORD_NO_CONTEXT;
              break;
            default:
              wordContext = this.processWord(curWord, wordContext);
              this.handler.endElement();
              wordContext = WORD_NO_CONTEXT;
          }
          break;
        case '(':
          if (wordContext == WORD_ELEMENT || wordContext == WORD_ATTLIST) {
            wordContext = this.processWord(curWord, wordContext);
            this.handler.startGroupElements();
          } else curWord.append(c);
          break;
        case ')':
          wordContext = this.processWord(curWord, wordContext);
          if (wordContext == WORD_ELEMENT || wordContext == WORD_ATTLIST) {
            int instance = this.getInstanceValue(this.peekNext());
            //	Get rid of the extra character
            if (instance != Common.TYPE_1) this.getNext();
            this.handler.endGroupElements(instance);
          } else curWord.append(c);
          break;
        case '|':
          wordContext = this.processWord(curWord, wordContext);
          if (wordContext == WORD_ELEMENT || wordContext == WORD_ATTLIST) this.handler.character(c);
          else curWord.append(c);
          break;
        case '\n':
        case '\r':
        case '\t':
        case ' ':
        case ',':
          wordContext = this.processWord(curWord, wordContext);
          break;
          //
        default:
          curWord.append(c);
      }
    }

    if (wordContext != WORD_NO_CONTEXT) System.out.println("Warning: unexpected EOF"); // NOI18N
  }
Пример #18
0
  private COSStream makeUniqObjectNames(Map objectNameMap, COSStream stream) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(10240);

    byte[] buf = new byte[10240];
    int read;
    InputStream is = stream.getUnfilteredStream();
    while ((read = is.read(buf)) > -1) {
      baos.write(buf, 0, read);
    }

    buf = baos.toByteArray();
    baos = new ByteArrayOutputStream(buf.length + 100);
    StringBuffer sbObjectName = new StringBuffer(10);
    boolean bInObjectIdent = false;
    boolean bInText = false;
    boolean bInEscape = false;
    for (int i = 0; i < buf.length; i++) {
      byte b = buf[i];

      if (!bInEscape) {
        if (!bInText && b == '(') {
          bInText = true;
        }
        if (bInText && b == ')') {
          bInText = false;
        }
        if (b == '\\') {
          bInEscape = true;
        }

        if (!bInText && !bInEscape) {
          if (b == '/') {
            bInObjectIdent = true;
          } else if (bInObjectIdent && Character.isWhitespace((char) b)) {
            bInObjectIdent = false;

            // System.err.println(sbObjectName);
            // String object = sbObjectName.toString();

            String objectName = sbObjectName.toString().substring(1);
            String newObjectName = objectName + "overlay";
            baos.write('/');
            baos.write(newObjectName.getBytes("ISO-8859-1"));

            objectNameMap.put(objectName, COSName.getPDFName(newObjectName));

            sbObjectName.delete(0, sbObjectName.length());
          }
        }

        if (bInObjectIdent) {
          sbObjectName.append((char) b);
          continue;
        }
      } else {
        bInEscape = false;
      }

      baos.write(b);
    }

    COSDictionary streamDict = new COSDictionary();
    streamDict.setInt(COSName.LENGTH, baos.size());
    COSStream output = new COSStream(streamDict, pdfDocument.getDocument().getScratchFile());
    output.setFilters(stream.getFilters());
    OutputStream os = output.createUnfilteredStream();
    baos.writeTo(os);
    os.close();

    return output;
  }