コード例 #1
0
  /**
   * ******************************************************************** Method: compareTwoNames
   * Description: Prompts user for two names and the decade to compare Input: array of Names, user
   * entered values for requestName, searchName, getDecade method calls Output: Displays histogram
   * line comparison between two names user selects
   * -------------------------------------------------------------- Pseudocode for this solution:
   * Begin Set name1 equal to value returned from requestName Set name1Idx equal to value returned
   * from searchName Reset name1 equal to self with first letter capitalized If name1Idx is equal to
   * -1 Begin Display "The name " + name1 + ", was not found!" End Else Begin Set name2 equal to
   * value returned from requestName Set namd2Idx equal to value returned from searchName Reset
   * name2 equal to self with first letter capitalized If name2Idx is equal to -1 Begin Display "The
   * second name, " + name2 + ", was not found!" End Else Begin Set decade equal to value returned
   * from getDecade Display comparison of name1 and name2 histogram lines for the selected decade
   * End if condition End if condition End
   * ********************************************************************
   */
  public static void compareTwoNames(Name[] list) {
    int name1Idx;
    int name2Idx;
    int decade;
    String name1;
    String name2;

    name1 = requestName();
    name1Idx = searchName(name1, list);
    name1 = Character.toUpperCase(name1.charAt(0)) + name1.substring(1);
    if (name1Idx == -1) {
      System.out.println("\nThe name, " + name1 + ", was not found!");
    } else {
      name2 = requestName();
      name2Idx = searchName(name2, list);
      name2 = Character.toUpperCase(name2.charAt(0)) + name2.substring(1);
      if (name2Idx == -1) {
        System.out.println("\nThe second name, " + name2 + ", was not found!");
      } else {
        decade = getDecade(list);
        System.out.println(
            "\nData for "
                + name1
                + "\n"
                + list[name1Idx].getHistoLine(decade)
                + "\nData for "
                + name2
                + "\n"
                + list[name2Idx].getHistoLine(decade));
      }
    }
  }
コード例 #2
0
ファイル: CharRing.java プロジェクト: lockss/lockss-daemon
 /**
  * Search for string in ring.
  *
  * @param str string to search for
  * @param lastIdx last index at which to search for string
  * @param ignoreCase
  * @return index of string if found, else -1
  */
 public int indexOf(String str, int lastIdx, boolean ignoreCase) {
   int strlen = str.length();
   int lastPossible = size - strlen;
   if (lastPossible < 0) return -1;
   lastIdx = (lastIdx < 0 || lastIdx > lastPossible) ? lastPossible : lastIdx;
   int pos = 0;
   // find position of first char of string
   l1:
   while ((pos = indexOf(str.charAt(0), pos, lastIdx, ignoreCase)) >= 0) {
     int ringpos = head + pos;
     for (int ix = 1; ix < strlen; ix++) {
       char ch = str.charAt(ix);
       char rch = chars[(ringpos + ix) % capacity];
       if (ignoreCase) {
         ch = Character.toUpperCase(ch);
         rch = Character.toUpperCase(rch);
       }
       if (ch != rch) {
         pos++;
         continue l1;
       }
     }
     return pos;
   }
   return -1;
 }
コード例 #3
0
ファイル: Figure.java プロジェクト: nbalogh/board-game-java
 public char getCode() {
   if (isWhite) {
     return Character.toUpperCase(code);
   } else {
     return code;
   }
 }
コード例 #4
0
ファイル: LOCRecord.java プロジェクト: uppaljs/sef
  private long parsePosition(Tokenizer st, String type) throws IOException {
    boolean isLatitude = type.equals("latitude");
    int deg = 0, min = 0;
    double sec = 0;
    long value;
    String s;

    deg = st.getUInt16();
    if (deg > 180 || (deg > 90 && isLatitude))
      throw st.exception("Invalid LOC " + type + " degrees");

    s = st.getString();
    try {
      min = Integer.parseInt(s);
      if (min < 0 || min > 59) throw st.exception("Invalid LOC " + type + " minutes");
      s = st.getString();
      sec = parseFixedPoint(s);
      if (sec < 0 || sec >= 60) throw st.exception("Invalid LOC " + type + " seconds");
      s = st.getString();
    } catch (NumberFormatException e) {
    }

    if (s.length() != 1) throw st.exception("Invalid LOC " + type);

    value = (long) (1000 * (sec + 60L * (min + 60L * deg)));

    char c = Character.toUpperCase(s.charAt(0));
    if ((isLatitude && c == 'S') || (!isLatitude && c == 'W')) value = -value;
    else if ((isLatitude && c != 'N') || (!isLatitude && c != 'E'))
      throw st.exception("Invalid LOC " + type);

    value += (1L << 31);

    return value;
  }
コード例 #5
0
 // keyboard discovery code
 private void _mapKey(char charCode, int keyindex, boolean shift, boolean altgraph) {
   log("_mapKey: " + charCode);
   // if character is not in map, add it
   if (!charMap.containsKey(new Integer(charCode))) {
     log("Notified: " + (char) charCode);
     KeyEvent event =
         new KeyEvent(
             applet(),
             0,
             0,
             (shift ? KeyEvent.SHIFT_MASK : 0) + (altgraph ? KeyEvent.ALT_GRAPH_MASK : 0),
             ((Integer) vkKeys.get(keyindex)).intValue(),
             (char) charCode);
     charMap.put(new Integer(charCode), event);
     log("Mapped char " + (char) charCode + " to KeyEvent " + event);
     if (((char) charCode) >= 'a' && ((char) charCode) <= 'z') {
       // put shifted version of a-z in automatically
       int uppercharCode = (int) Character.toUpperCase((char) charCode);
       event =
           new KeyEvent(
               applet(),
               0,
               0,
               KeyEvent.SHIFT_MASK + (altgraph ? KeyEvent.ALT_GRAPH_MASK : 0),
               ((Integer) vkKeys.get(keyindex)).intValue(),
               (char) uppercharCode);
       charMap.put(new Integer(uppercharCode), event);
       log("Mapped char " + (char) uppercharCode + " to KeyEvent " + event);
     }
   }
 }
コード例 #6
0
 /*
  * Locale needs its own, locale insensitive version of toUpperCase to
  * avoid circularity problems between Locale and String.
  * The most straightforward algorithm is used. Look at optimizations later.
  */
 private String toUpperCase(String str) {
   char[] buf = new char[str.length()];
   for (int i = 0; i < buf.length; i++) {
     buf[i] = Character.toUpperCase(str.charAt(i));
   }
   return new String(buf);
 }
コード例 #7
0
ファイル: ShortRoute.java プロジェクト: IT-Kakan/TDA416
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == from) {
      String tmpFrom = from.getText().trim();
      String tmpTo = to.getText().trim();
      if (tmpFrom.equals("MST") || tmpFrom.equals("mst")) findMinSpan();
      else {
        try { // check if from exists
          // String str = from.getText();
          // fixa så man kan skippa att skriva första med stor bokstav
          tmpFrom = Character.toUpperCase(tmpFrom.charAt(0)) + tmpFrom.substring(1);
          int pos = noderna.findLeading(tmpFrom).getNodeNo();
          route.setText(introText + "\n");
          from.setText(noderna.find(pos).toString());
        } catch (NullPointerException npe) {
          route.setText(felTextStart + "\n");
          return;
        }
        if (!tmpTo.equals("")) {
          findShort();
        }
      }
    } else if (e.getSource() == to) {
      String tmpFrom = from.getText().trim();
      String tmpTo = to.getText().trim();
      if (tmpTo.equals("MST") || tmpTo.equals("mst")) findMinSpan();
      else {
        try { // check if to exists
          // String str = to.getText();
          tmpTo = Character.toUpperCase(tmpTo.charAt(0)) + tmpTo.substring(1);
          int pos = noderna.findLeading(tmpTo).getNodeNo();
          route.setText(introText + "\n");
          to.setText(noderna.find(pos).toString());
        } catch (NullPointerException npe) {
          route.setText(felTextStart + "\n");
          return;
        }
        if (!tmpFrom.equals("")) {
          findShort();
        }
      }

      /*
      else if ( ! from.getText().equals("") )
      	findShort();
      */
    }
  }
コード例 #8
0
ファイル: CharRing.java プロジェクト: lockss/lockss-daemon
  // This routine accounts for a substantial amount of the time spent in
  // LOCKSS filtered readers, so is worth optimizing for the common cases.
  private int indexOf(char ch, int startIdx, int lastIdx, boolean ignoreCase) {
    if (ignoreCase) {
      // do slow loop only if this char has different upper and lower case
      char uch = Character.toUpperCase(ch);
      if (ch != uch || ch != Character.toLowerCase(ch)) {
        for (int ix = startIdx; ix <= lastIdx; ix++) {
          char rch = chars[(head + ix) % capacity];
          if (Character.toUpperCase(rch) == uch) {
            return ix;
          }
        }
        return -1;
      }
    }
    if (startIdx > lastIdx) return -1;
    int startPos = (head + startIdx) % capacity;
    int endPos = (head + lastIdx) % capacity;
    if (startPos > endPos) {
      for (int ix = startPos; ix < capacity; ix++) {
        if (chars[ix] == ch) {
          return ix + startIdx - startPos;
        }
      }
      for (int ix = 0; ix <= endPos; ix++) {
        if (chars[ix] == ch) {
          return (ix + (capacity - head)) % capacity;
        }
      }
    } else {
      for (int ix = startPos; ix <= endPos; ix++) {
        if (chars[ix] == ch) {
          return ix + startIdx - startPos;
        }
      }
    }
    return -1;

    // The code above should be equivalent to this
    //     for (int ix = startIdx; ix <= lastIdx; ix++) {
    //       char rch = chars[(head + ix) % capacity];
    //       if (rch == ch) {
    // 	       return ix;
    //       }
    //     }
  }
コード例 #9
0
 /**
  * Does the current buffer match the given item name? itemName is the name of the IMAP item to
  * compare against. NOTE that itemName *must* be all uppercase. If the match is successful, the
  * buffer pointer (index) is incremented past the matched item.
  */
 private boolean match(String itemName) {
   int len = itemName.length();
   for (int i = 0, j = index; i < len; )
     // IMAP tokens are case-insensitive. We store itemNames in
     // uppercase, so convert operand to uppercase before comparing.
     if (Character.toUpperCase((char) buffer[j++]) != itemName.charAt(i++)) return false;
   index += len;
   return true;
 }
コード例 #10
0
ファイル: ShortRoute.java プロジェクト: IT-Kakan/TDA416
  // ====================================================================
  private void findShort() {
    // svårt att behålla linjefärgerna?
    int start, s**t;
    try { // read from station
      String str = from.getText();
      str = Character.toUpperCase(str.charAt(0)) + str.substring(1);
      start = noderna.find(str).getNodeNo();
    } catch (NullPointerException npe) {
      route.setText(felTextStart + "\n");
      return;
    }
    try { // read to station
      String str = to.getText();
      str = Character.toUpperCase(str.charAt(0)) + str.substring(1);
      s**t = noderna.find(str).getNodeNo();
    } catch (NullPointerException npe) {
      route.setText(felTextSlut + "\n");
      return;
    }

    double totWeight = 0;
    int totNodes = 0;
    route.setText("");
    karta.clearLayer(DrawGraph.Layer.OVERLAY);
    Iterator<BusEdge> it = grafen.shortestPath(start, s**t);
    while (it.hasNext()) {
      BusEdge e = it.next();
      route.append(makeText1(e) + "\n");
      totNodes++;
      totWeight += e.getWeight();
      // draw the shortest path
      BusStop from = noderna.find(e.from), to = noderna.find(e.to);
      karta.drawLine(
          from.xpos, from.ypos, to.xpos, to.ypos, Color.black, 4.0, DrawGraph.Layer.OVERLAY);
    }
    karta.repaint();
    route.append("Antal: " + totNodes + " totalvikt: " + totWeight + "\n");
    from.setText("");
    to.setText("");
  } // findShort
コード例 #11
0
  /* Following are the method for Lookup Device name*/
  private static String LookupDevice(String substring) {
    // TODO Auto-generated method stub
    File p =
        new File(
            "/Users/luozhongyi/Desktop/2015 Fall course/CS 6400/MacPrefix2.txt"); // The path of
                                                                                  // MacPrefix.txt
    Scanner pcon = null;

    try {
      pcon = new Scanner(p);
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    String pcurrentline;
    String Device = null;
    char[] prefix = {'0', '0', '0', '0', '0', '0', '0', '0'};
    // char px;
    int flag = 0;

    // prefix=substring.substring(0, 8); // rember to transfer to uppercase
    // System.out.println(substring);
    for (int i = 0; i < 8; i++) {
      // System.out.println(i+"");
      // System.out.println(Character.toUpperCase(substring.charAt(i)));
      if (Character.isLetter(substring.charAt(i)))
        prefix[i] = Character.toUpperCase(substring.charAt(i));
      else
        // System.out.println(i+"");
        // System.out.println(substring.charAt(i));
        prefix[i] = substring.charAt(i);
    } // get the uppercase of prefix

    /* Find in MacPrefix txt */
    while (pcon.hasNextLine()) {
      pcurrentline = pcon.nextLine().toString();
      if (pcurrentline.startsWith(new String(prefix))) { // find the first match and return
        flag = 1;
        pcurrentline = pcurrentline.replaceAll("\\s+", " "); // delete duplicate " ";
        // System.out.println(pcurrentline);
        Device =
            pcurrentline.substring(
                pcurrentline.indexOf(' ') + 1,
                pcurrentline.indexOf(' ', pcurrentline.indexOf(' ') + 1));
      } else ;
    }
    if (flag == 0) Device = "DEFAULT";
    // System.out.println(Device);
    pcon.close();
    return Device;
  }
コード例 #12
0
ファイル: Aart.java プロジェクト: dguerrar/codingame
  public static void main(String args[]) {

    int NUM_LETTERS = 27;
    char[] alfabet = {
      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
      'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '?'
    };

    Scanner in = new Scanner(System.in);
    int L = in.nextInt();
    in.nextLine();
    int H = in.nextInt();
    in.nextLine();
    // to store the letter in asci artM
    char[][] art = new char[H][L * NUM_LETTERS];
    String T = in.nextLine(); // text to translate

    System.err.println("create array L:" + L + "/H:" + H + "/to translate:" + T);

    // saving asci art
    for (int i = 0; i < H; i++) {
      String ROW = in.nextLine(); // first line of all letters in asci art
      // the ROW must be saved in L chars groups
      // System.err.println("readed->" + ROW);
      char[] aux = ROW.toCharArray();
      for (int j = 0; j < aux.length; j++) {
        // System.err.println("guardando->["+i+"]["+j+"]" + aux[j]);
        art[i][j] = aux[j];
      }
    }

    StringBuilder builder = new StringBuilder();
    char[] translation = T.toCharArray();
    for (int m = 0; m < H; m++) {
      StringBuilder linea = new StringBuilder();
      for (int j = 0; j < translation.length; j++) {
        // neet to get char -> letter number to get position
        int position = returnPosition(Character.toUpperCase(translation[j]), alfabet);

        int start = (position * L);
        for (int u = start; u < (start + L); u++) {
          linea.append(art[m][u]);
        }
      }
      System.out.println(linea);
    }

    // Write an action using System.out.println()
    // To debug: System.err.println("Debug messages...");

  }
コード例 #13
0
ファイル: base16.java プロジェクト: lemmy/dnsjava
  /**
   * Convert a hex-encoded String to binary data
   *
   * @param str A String containing the encoded data
   * @return An array containing the binary data, or null if the string is invalid
   */
  public static byte[] fromString(String str) {
    ByteArrayOutputStream bs = new ByteArrayOutputStream();
    byte[] raw = str.getBytes();
    for (int i = 0; i < raw.length; i++) {
      if (!Character.isWhitespace((char) raw[i])) bs.write(raw[i]);
    }
    byte[] in = bs.toByteArray();
    if (in.length % 2 != 0) {
      return null;
    }

    bs.reset();
    DataOutputStream ds = new DataOutputStream(bs);

    for (int i = 0; i < in.length; i += 2) {
      byte high = (byte) Base16.indexOf(Character.toUpperCase((char) in[i]));
      byte low = (byte) Base16.indexOf(Character.toUpperCase((char) in[i + 1]));
      try {
        ds.writeByte((high << 4) + low);
      } catch (IOException e) {
      }
    }
    return bs.toByteArray();
  }
コード例 #14
0
  /**
   * Returns the NameSurferEntry associated with this name, if one exists. If the name does not
   * appear in the database, this method returns null.
   */
  public NameSurferEntry findEntry(String name) {

    char firstLetter = name.charAt(0);
    if (Character.isLowerCase(firstLetter) == true) {
      firstLetter = Character.toUpperCase(firstLetter);
    }
    String remainingLetters = name.substring(1);
    remainingLetters = remainingLetters.toLowerCase();
    name = firstLetter + remainingLetters;

    if (namesDataBase.containsKey(name)) {
      return namesDataBase.get(name);
    }
    return null;
  }
コード例 #15
0
    /**
     * Set the fields from the ProjectionClass
     *
     * @param projClass projection class to use
     */
    private void setFieldsWithClassParams(ProjectionClass projClass) {

      // set the projection in the JComboBox
      String want = projClass.toString();
      for (int i = 0; i < projClassCB.getItemCount(); i++) {
        ProjectionClass pc = (ProjectionClass) projClassCB.getItemAt(i);
        if (pc.toString().equals(want)) {
          projClassCB.setSelectedItem((Object) pc);
          break;
        }
      }

      // set the parameter fields
      paramPanel.removeAll();
      paramPanel.setVisible(0 < projClass.paramList.size());

      List widgets = new ArrayList();
      for (int i = 0; i < projClass.paramList.size(); i++) {
        ProjectionParam pp = (ProjectionParam) projClass.paramList.get(i);
        // construct the label
        String name = pp.name;
        String text = "";
        // Create a decent looking label
        for (int cIdx = 0; cIdx < name.length(); cIdx++) {
          char c = name.charAt(cIdx);
          if (cIdx == 0) {
            c = Character.toUpperCase(c);
          } else {
            if (Character.isUpperCase(c)) {
              text += " ";
              c = Character.toLowerCase(c);
            }
          }
          text += c;
        }
        widgets.add(GuiUtils.rLabel(text + ": "));
        // text input field
        JTextField tf = new JTextField();
        pp.setTextField(tf);
        tf.setColumns(12);
        widgets.add(tf);
      }
      GuiUtils.tmpInsets = new Insets(4, 4, 4, 4);
      JPanel widgetPanel = GuiUtils.doLayout(widgets, 2, GuiUtils.WT_N, GuiUtils.WT_N);

      paramPanel.add("North", widgetPanel);
      paramPanel.add("Center", GuiUtils.filler());
    }
コード例 #16
0
  public static void main(String[] args) throws FileNotFoundException {
    File file = new File(args[0]);
    Scanner in = new Scanner(file);

    while (in.hasNextLine()) {
      String result = "";
      String line = in.nextLine();
      Scanner lineScan = new Scanner(line);
      while (lineScan.hasNext()) {
        String word = lineScan.next();
        result += Character.toUpperCase(word.charAt(0)) + word.substring(1) + " ";
      }

      System.out.println(result.trim());
    }
  }
コード例 #17
0
ファイル: EmuThread.java プロジェクト: rexut/jkcemu
 public void keyTyped(char ch) {
   if (this.emuSys != null) {
     if (this.emuSys.getSwapKeyCharCase()) {
       if (Character.isUpperCase(ch)) {
         ch = Character.toLowerCase(ch);
       } else if (Character.isLowerCase(ch)) {
         ch = Character.toUpperCase(ch);
       }
     }
     if (this.emuSys.getConvertKeyCharToISO646DE()) {
       this.emuSys.keyTyped(TextUtil.toISO646DE(ch));
     } else {
       this.emuSys.keyTyped(ch);
     }
   }
 }
コード例 #18
0
 /**
  * Check if the digital object conforms to this Module's internal signature information.
  *
  * <p>HTML is one of the most ill-defined of any open formats, so checking a "signature" really
  * means using some heuristics. The only required tag is TITLE, but that could occur well into the
  * file. So we look for any of three strings -- taking into account case-independence and white
  * space -- within the first sigBytes bytes, and call that a signature check.
  *
  * @param file A File object for the object being parsed
  * @param stream An InputStream, positioned at its beginning, which is generated from the object
  *     to be parsed
  * @param info A fresh RepInfo object which will be modified to reflect the results of the test
  */
 public void checkSignatures(File file, InputStream stream, RepInfo info) throws IOException {
   info.setFormat(_format[0]);
   info.setMimeType(_mimeType[0]);
   info.setModule(this);
   char[][] sigtext = new char[3][];
   sigtext[0] = "<!DOCTYPE HTML".toCharArray();
   sigtext[1] = "<HTML".toCharArray();
   sigtext[2] = "<TITLE".toCharArray();
   int[] sigstate = {0, 0, 0};
   JhoveBase jb = getBase();
   int sigBytes = jb.getSigBytes();
   int bytesRead = 0;
   boolean eof = false;
   DataInputStream dstream = new DataInputStream(stream);
   while (!eof && bytesRead < sigBytes) {
     try {
       int ch = readUnsignedByte(dstream, this);
       char chr = Character.toUpperCase((char) ch);
       ++bytesRead;
       if (Character.isWhitespace(chr)) {
         continue; // ignore all whitespace
       }
       for (int i = 0; i < 3; i++) {
         int ss = sigstate[i];
         char[] st = sigtext[i];
         if (chr == st[ss]) {
           ++sigstate[i];
           if (sigstate[i] == st.length) {
             // One of the sig texts matches!
             info.setSigMatch(_name);
             return;
           }
         } else sigstate[i] = 0;
       }
     } catch (EOFException e) {
       eof = true;
     }
   }
   // If we fall through, there was no sig match
   info.setWellFormed(false);
   return;
 }
コード例 #19
0
ファイル: CodeGenerater.java プロジェクト: juanmadryn/web-db
  private static String computeFieldName(String fieldName) {
    int TO_UPPER = 1;
    int TO_LOWER = 2;
    int NO_CHANGE = 0;

    StringBuffer sb = new StringBuffer(fieldName.length() + 1);
    sb.append('_');
    int nextChange = TO_LOWER;
    for (int i = 0; i < fieldName.length(); i++) {
      char c = fieldName.charAt(i);
      if (c == '.' || c == ' ') nextChange = TO_UPPER;
      else if (nextChange == TO_LOWER) {
        sb.append(Character.toLowerCase(c));
        nextChange = NO_CHANGE;
      } else if (nextChange == TO_UPPER) {
        sb.append(Character.toUpperCase(c));
        nextChange = NO_CHANGE;
      } else sb.append(c);
    }
    return sb.toString();
  }
コード例 #20
0
ファイル: UTF8String.java プロジェクト: spark6017/spark
  /** Returns the upper case of this string */
  public UTF8String toUpperCase() {
    if (numBytes == 0) {
      return EMPTY_UTF8;
    }

    byte[] bytes = new byte[numBytes];
    bytes[0] = (byte) Character.toTitleCase(getByte(0));
    for (int i = 0; i < numBytes; i++) {
      byte b = getByte(i);
      if (numBytesForFirstByte(b) != 1) {
        // fallback
        return toUpperCaseSlow();
      }
      int upper = Character.toUpperCase((int) b);
      if (upper > 127) {
        // fallback
        return toUpperCaseSlow();
      }
      bytes[i] = (byte) upper;
    }
    return fromBytes(bytes);
  }
コード例 #21
0
ファイル: JavaAdapter.java プロジェクト: sq001/aurora-project
 private static StringBuilder appendTypeString(StringBuilder sb, Class<?> type) {
   while (type.isArray()) {
     sb.append('[');
     type = type.getComponentType();
   }
   if (type.isPrimitive()) {
     char typeLetter;
     if (type == Boolean.TYPE) {
       typeLetter = 'Z';
     } else if (type == Long.TYPE) {
       typeLetter = 'J';
     } else {
       String typeName = type.getName();
       typeLetter = Character.toUpperCase(typeName.charAt(0));
     }
     sb.append(typeLetter);
   } else {
     sb.append('L');
     sb.append(type.getName().replace('.', '/'));
     sb.append(';');
   }
   return sb;
 }
コード例 #22
0
ファイル: Cache.java プロジェクト: jankotek/asterope
 /** Retourne la valeur décimale corresondant à un digit hexadécimal */
 private static int code(char c) {
   return HEX.indexOf(Character.toUpperCase(c));
 }
コード例 #23
0
ファイル: PrologBackend.java プロジェクト: bungaca/abstools
 public static String initialToUpperCase(String s) {
   char[] cs = s.toCharArray();
   cs[0] = Character.toUpperCase(cs[0]);
   return new String(cs);
 }
コード例 #24
0
  /**
   * Compare the calculate source list, with an explicit list, usually supplied from the makefile.
   * Used to detect bugs where the makefile and sjavac have different opinions on which files should
   * be compiled.
   */
  public void compareWithMakefileList(File makefileSourceList) throws ProblemException {
    // If we are building on win32 using for example cygwin the paths in the makefile source list
    // might be /cygdrive/c/.... which does not match c:\....
    // We need to adjust our calculated sources to be identical, if necessary.
    boolean mightNeedRewriting = File.pathSeparatorChar == ';';

    if (makefileSourceList == null) return;

    Set<String> calculatedSources = new HashSet<>();
    Set<String> listedSources = new HashSet<>();

    // Create a set of filenames with full paths.
    for (Source s : now.sources().values()) {
      // Don't include link only sources when comparing sources to compile
      if (!s.isLinkedOnly()) {
        calculatedSources.add(s.file().getPath());
      }
    }
    // Read in the file and create another set of filenames with full paths.
    try {
      BufferedReader in = new BufferedReader(new FileReader(makefileSourceList));
      for (; ; ) {
        String l = in.readLine();
        if (l == null) break;
        l = l.trim();
        if (mightNeedRewriting) {
          if (l.indexOf(":") == 1 && l.indexOf("\\") == 2) {
            // Everything a-ok, the format is already C:\foo\bar
          } else if (l.indexOf(":") == 1 && l.indexOf("/") == 2) {
            // The format is C:/foo/bar, rewrite into the above format.
            l = l.replaceAll("/", "\\\\");
          } else if (l.charAt(0) == '/' && l.indexOf("/", 1) != -1) {
            // The format might be: /cygdrive/c/foo/bar, rewrite into the above format.
            // Do not hardcode the name cygdrive here.
            int slash = l.indexOf("/", 1);
            l = l.replaceAll("/", "\\\\");
            l = "" + l.charAt(slash + 1) + ":" + l.substring(slash + 2);
          }
          if (Character.isLowerCase(l.charAt(0))) {
            l = Character.toUpperCase(l.charAt(0)) + l.substring(1);
          }
        }
        listedSources.add(l);
      }
    } catch (FileNotFoundException e) {
      throw new ProblemException(
          "Could not open " + makefileSourceList.getPath() + " since it does not exist!");
    } catch (IOException e) {
      throw new ProblemException("Could not read " + makefileSourceList.getPath());
    }

    for (String s : listedSources) {
      if (!calculatedSources.contains(s)) {
        throw new ProblemException(
            "The makefile listed source " + s + " was not calculated by the smart javac wrapper!");
      }
    }

    for (String s : calculatedSources) {
      if (!listedSources.contains(s)) {
        throw new ProblemException(
            "The smart javac wrapper calculated source " + s + " was not listed by the makefiles!");
      }
    }
  }
コード例 #25
0
ファイル: sbdocgen.java プロジェクト: CARV-ICS-FORTH/disquawk
  public static void main(String args[]) throws IOException {
    List<Instruction> insns = Instructions.getInstructions();
    Collections.sort(insns);

    List<Character> startLetters = new java.util.ArrayList<Character>();
    char last = 0;
    for (int i = 0; i < insns.size(); i++) {
      Instruction insn = (Instruction) insns.get(i);
      char leadChar = insn.getName().charAt(0);
      if (last != leadChar) {
        startLetters.add(leadChar);
        last = leadChar;
      }
    }

    File docdir = new File("SquawkBytecodeSpec");
    Build.mkdir(docdir);

    PrintWriter out = null;
    out = new PrintWriter(new FileWriter(new File(docdir, "Instructions.doc.html")));

    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">");
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Squawk Bytecode Instruction Set</title>");
    out.println("</head>");
    out.println("<body BGCOLOR=#eeeeff text=#000000 LINK=#0000ff VLINK=#000077 ALINK=#ff0000>");
    out.println("<table width=100%><tr>");
    out.print(
        "<td>Prev | <a href=\"Instructions2.doc1.html\">Next</a> | <a href=\"Instructions2.index.html\">Index</a> </td>");
    out.println("<td align=right><i><i>Squawk Bytecode Instruction Set</i></i></td>");
    out.println("</tr></table>");
    out.println();
    out.println("<hr><br>");
    out.println();
    for (int i = 0; i < startLetters.size(); i++) {
      Character c = (Character) startLetters.get(i);
      out.println(
          "<a href=\"Instructions2.doc"
              + (i + 1)
              + ".html\">"
              + Character.toUpperCase(c.charValue())
              + "</a>");
    }
    out.println();
    out.println("<hr><br>");
    out.println();
    out.println("<h1>Squawk Bytecode Instruction Set</h1>");
    out.println("<hr><p>");
    out.println("A Squawk bytecode instruction consists of an opcode specifying the operation");
    out.println(
        "to be performed, followed by zero or more operands embodying values to be operated");
    out.println("upon. This chapter gives details about the format of each Squawk bytecode");
    out.println("instruction and the operation it performs.</p>");
    out.println("<hr>");

    out.println("<p>Prev | <a href=\"Instructions2.doc1.html\">Next</a></p>");
    out.println("</body></html>");

    out.close();

    PrintWriter indexPage =
        new PrintWriter(new FileWriter(new File(docdir, "Instructions2.index.html")));
    indexPage.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">");
    indexPage.println("<html>");
    indexPage.println("<head>");
    indexPage.println("<title>Squawk Bytecode Instruction Set</title>");
    indexPage.println("</head>");
    indexPage.println(
        "<body BGCOLOR=#eeeeff text=#000000 LINK=#0000ff VLINK=#000077 ALINK=#ff0000>");
    indexPage.println("<table width=100%><tr>");
    indexPage.println("<td><a href=\"Instructions.doc.html\">Contents</a></td>");
    indexPage.println("<td align=right><i><i>Squawk Bytecode Instruction Set</i></i></td>");
    indexPage.println("</tr></table>");
    indexPage.println();
    indexPage.println("<hr><br>");
    indexPage.println();

    Iterator<Instruction> iter = insns.iterator();
    Instruction insn = (iter.hasNext()) ? iter.next() : null;
    for (int i = 0; i < startLetters.size(); i++) {
      String thisPage = "Instructions2.doc" + (i + 1) + ".html";
      String prevPage = "Instructions2.doc" + i + ".html";
      String nextPage = "Instructions2.doc" + (i + 2) + ".html";

      out = new PrintWriter(new FileWriter(new File(docdir, thisPage)));
      out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">");
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Squawk Bytecode Instruction Descriptions</title>");
      out.println("</head>");
      out.println("<body BGCOLOR=#eeeeff text=#000000 LINK=#0000ff VLINK=#000077 ALINK=#ff0000>");
      out.println("<table width=100%><tr>");
      out.print("<td>");
      out.print(" <a href=\"Instructions.doc.html\">Contents</a> | ");
      if (i > 0) out.print("<a href=\"" + prevPage + "\">Prev</a>");
      else out.print("<a href=\"Instructions.doc.html\">Prev</a>");
      out.print(" | ");
      if (i < startLetters.size() - 1) out.print("<a href=\"" + nextPage + "\">Next</a>");
      else out.print("Next");
      out.println(" | <a href=\"Instructions2.index.html\">Index</a> </td>");
      out.println("<td align=right><i><i>Squawk Bytecode Instruction Set</i></i></td>");
      out.println("</tr></table>");
      out.println();
      out.println("<hr><br>");
      out.println();
      for (int j = 0; j < startLetters.size(); j++) {
        Character c = (Character) startLetters.get(j);
        out.println(
            "<a href=\"Instructions2.doc"
                + (j + 1)
                + ".html\">"
                + Character.toUpperCase(c.charValue())
                + "</a>");
      }
      out.println();

      while (insn != null
          && Character.toUpperCase(insn.getName().charAt(0))
              == Character.toUpperCase(((Character) startLetters.get(i)).charValue())) {

        String name = insn.getName();
        indexPage.println("<a href=\"" + thisPage + "#" + name + "\">" + name + "</a><br>");

        out.println("<hr><a name=\"" + name + "\"><h2>" + name + "</h2>");

        out.println("<p><b>Operation</b></p>");
        out.println("<blockquote>");
        insn.printOperation(out);
        out.println("</blockquote>");

        out.println("<p><b>Format</b></p>");
        out.println("<blockquote>");
        insn.printFormat(out);
        out.println("</blockquote>");

        out.println("<p><b>Forms</b></p>");
        out.println("<blockquote>");
        insn.printForms(out);
        out.println("</blockquote>");

        out.println("<p><b>Operand Stack</b></p>");
        out.println("<blockquote>");
        insn.printOperandStack(out);
        out.println("</blockquote>");

        out.println("<p><b>Description</b></p>");
        out.println("<blockquote>");
        insn.printDescription(out);
        out.println("</blockquote>");

        if (insn.hasNotes()) {
          out.println("<p><b>Notes</b></p>");
          out.println("<blockquote>");
          insn.printNotes(out);
          out.println("</blockquote>");
        }

        insn = (iter.hasNext()) ? (Instruction) iter.next() : null;
      }

      out.println("<hr>");
      if (i > 0) out.print("<a href=\"Instructions2.doc" + i + ".html\">Prev</a>");
      else out.print("<a href=\"Instructions.doc.html\">Prev</a>");
      out.print(" | ");
      if (i < startLetters.size() - 1)
        out.print("<a href=\"Instructions2.doc" + (i + 2) + ".html\">Next</a>");
      else out.print("Next");
      out.println();
      out.println("</body></html>");

      out.flush();
      out.close();
    }

    indexPage.println("</body></html>");
    indexPage.close();

    for (int i = 0; i < 256; i++)
      if (!opcodes.contains(new Integer(i))) System.out.println("missing opcode: " + i);
  }
コード例 #26
0
 private String firstCharToUpperCase(String name) {
   return Character.toString(Character.toUpperCase(name.charAt(0))) + name.substring(1);
 }
コード例 #27
0
 /**
  * Pass a randomly-cased version of the supplied character to the underlying stream.
  *
  * @param c the character to write
  * @throws IOException if an I/O error occurs
  */
 public void write(int c) throws IOException {
   out.write(
       (Math.random() < .5) ? Character.toLowerCase((char) c) : Character.toUpperCase((char) c));
 }
コード例 #28
0
ファイル: FlickrFtpd.java プロジェクト: iamcal/Flickr-FTPD
  // initiate either a server or a user session
  public void run() {
    if (isDaemon) {
      daemon();
      return;
    }
    ;

    boolean loggedIn = false;
    int i, h1;
    String di, str1, user = "******", user_id = "0";
    InetAddress localNode;
    byte dataBuffer[] = new byte[1024];
    String command = null;
    StringBuffer statusMessage = new StringBuffer(40);
    File targetFile = null;

    try {
      // start mysql
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      this.db_conn = DriverManager.getConnection(db_url);
      this.db_stmt = this.db_conn.createStatement();

      this.db_stmt.executeUpdate("INSERT INTO test_table (name) VALUES ('hello world')");

      incoming.setSoTimeout(inactivityTimer); // enforce I/O timeout
      remoteNode = incoming.getInetAddress();
      localNode = InetAddress.getLocalHost();

      BufferedReader in =
          new BufferedReader(new InputStreamReader(incoming.getInputStream(), TELNET));
      PrintWriter out =
          new PrintWriter(new OutputStreamWriter(incoming.getOutputStream(), TELNET), true);
      str1 = "220 Flickr FTP Server Ready";
      out.println(str1);
      if (log) System.out.println(remoteNode.getHostName() + " " + str1);

      boolean done = false;
      char dataType = 0;

      while (!done) {
        statusMessage.setLength(0);

        // obtain and tokenize command
        String str = in.readLine();
        if (str == null) break; // EOS reached
        i = str.indexOf(' ');
        if (i == -1) i = str.length();
        command = str.substring(0, i).toUpperCase().intern();
        if (log)
          System.out.print(
              user
                  + "@"
                  + remoteNode.getHostName()
                  + " "
                  + (String) ((command != "PASS") ? str : "PASS ***"));
        str = str.substring(i).trim();

        try {
          if (command == "USER") {

            user = str;
            statusMessage.append("331 Password");

          } else if (command == "PASS") {

            String pass = str;
            String pass_md5 = md5(pass);

            this.db_rs =
                this.db_stmt.executeQuery(
                    "SELECT * FROM users WHERE email='"
                        + user
                        + "' AND password='******'");
            if (this.db_rs.first()) {
              loggedIn = true;
              user_id = this.db_rs.getString("id");
              System.out.println("Account id is " + user_id);
            }

            statusMessage.append(loggedIn ? "230 logged in User" : "530 Login Incorrect");

          } else if (!loggedIn) {

            statusMessage.append("530 Not logged in");

          } else if (command == "RETR") {

            statusMessage.append("999 Not likely");

          } else if (command == "STOR") {

            out.println(BINARY_XFER);

            // trim a leading slash off the filename if there is one
            if (str.substring(0, 1).equals("/")) str = str.substring(1);
            String filename = user_id + "_" + str;
            // TODO: sanitise filename
            targetFile = new File(upload_root + "/" + filename);

            RandomAccessFile dataFile = null;
            InputStream inStream = null;
            OutputStream outStream = null;
            BufferedReader br = null;
            PrintWriter pw = null;

            try {
              int amount;
              dataSocket = setupDataLink();

              // ensure timeout on reads.
              dataSocket.setSoTimeout(inactivityTimer);

              dataFile = new RandomAccessFile(targetFile, "rw");

              inStream = dataSocket.getInputStream();
              while ((amount = inStream.read(dataBuffer)) != -1)
                dataFile.write(dataBuffer, 0, amount);

              statusMessage.append(XFER_COMPLETE);

              shell_exec(ingest_path + " " + user_id + " " + filename);
            } finally {
              try {
                if (inStream != null) inStream.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (outStream != null) outStream.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (dataFile != null) dataFile.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (dataSocket != null) dataSocket.close();
              } catch (Exception e1) {
              }
              ;
              dataSocket = null;
            }

          } else if (command == "REST") {

            statusMessage.append("502 Sorry, no resuming");

          } else if (command == "TYPE") {

            if (Character.toUpperCase(str.charAt(0)) == 'I') {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504 Only binary baybee");
            }

          } else if (command == "DELE"
              || command == "RMD"
              || command == "XRMD"
              || command == "MKD"
              || command == "XMKD"
              || command == "RNFR"
              || command == "RNTO"
              || command == "CDUP"
              || command == "XCDUP"
              || command == "CWD"
              || command == "SIZE"
              || command == "MDTM") {

            statusMessage.append("502 None of that malarky!");

          } else if (command == "QUIT") {

            statusMessage.append(COMMAND_OK).append("GOOD BYE");
            done = true;

          } else if (command == "PWD" | command == "XPWD") {

            statusMessage.append("257 \"/\" is current directory");

          } else if (command == "PORT") {

            int lng, lng1, lng2, ip2;
            String a1 = "", a2 = "";
            lng = str.length() - 1;
            lng2 = str.lastIndexOf(",");
            lng1 = str.lastIndexOf(",", lng2 - 1);

            for (i = lng1 + 1; i < lng2; i++) {
              a1 = a1 + str.charAt(i);
            }

            for (i = lng2 + 1; i <= lng; i++) {
              a2 = a2 + str.charAt(i);
            }

            remotePort = Integer.parseInt(a1);
            ip2 = Integer.parseInt(a2);
            remotePort = (remotePort << 8) + ip2;
            statusMessage.append(COMMAND_OK).append(remotePort);

          } else if (command == "LIST" | command == "NLST") {

            try {

              out.println("150 ASCII data");
              dataSocket = setupDataLink();

              PrintWriter out2 = new PrintWriter(dataSocket.getOutputStream(), true);

              if ((command == "NLST")) {
                out2.println(".");
                out2.println("..");
              } else {
                out2.println("total 8.0k");
                out2.println("dr--r--r-- 1 owner group           213 Aug 26 16:31 .");
                out2.println("dr--r--r-- 1 owner group           213 Aug 26 16:31 ..");
              }

              // socket MUST be closed before signalling EOD
              dataSocket.close();
              dataSocket = null;
              statusMessage.setLength(0);
              statusMessage.append(XFER_COMPLETE);
            } finally {
              try {
                if (dataSocket != null) dataSocket.close();
              } catch (Exception e) {
              }
              ;
              dataSocket = null;
            }

          } else if (command == "NOOP") {

            statusMessage.append(COMMAND_OK);

          } else if (command == "SYST") {

            statusMessage.append("215 UNIX"); // allows NS to do long dir

          } else if (command == "MODE") {

            if (Character.toUpperCase(str.charAt(0)) == 'S') {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504");
            }

          } else if (command == "STRU") {

            if (str.equals("F")) {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504");
            }

          } else if (command == "PASV") {

            try {

              int num = 0, j = 0;
              if (passiveSocket != null)
                try {
                  passiveSocket.close();
                } catch (Exception e) {
                }
              ;
              passiveSocket = new ServerSocket(0); // any port

              // ensure timeout on reads.
              passiveSocket.setSoTimeout(inactivityTimer);

              statusMessage.append("227 Entering Passive Mode (");
              String s = localNode.getHostAddress().replace('.', ','); // get host #
              statusMessage.append(s).append(',');
              num = passiveSocket.getLocalPort(); // get port #
              j = (num >> 8) & 0xff;
              statusMessage.append(j);
              statusMessage.append(',');
              j = num & 0xff;
              statusMessage.append(j);
              statusMessage.append(')');
            } catch (Exception e) {
              try {
                if (passiveSocket != null) passiveSocket.close();
              } catch (Exception e1) {
              }
              ;
              passiveSocket = null;
              throw e;
            }

          } else {
            statusMessage.append("502 unimplemented ").append(command);
          }
        }

        // shutdown causes an interruption to be thrown
        catch (InterruptedException e) {
          throw (e);
        } catch (Exception e) // catch all for any errors (including files)
        {
          statusMessage.append(FAULT).append(e.getMessage());
          if (debug) {
            System.out.println("\nFAULT - lastfile " + targetFile);
            e.printStackTrace();
          }
          ;
        }

        // send result status to remote
        out.println(statusMessage);
        if (log) System.out.println("\t" + statusMessage);
      }
    } catch (Exception e) // usually network errors (including timeout)
    {
      if (log) System.out.println("forced instance exit " + e);
      if (debug) e.printStackTrace();
    } finally // exiting server instance
    {
      // tear down mysql
      if (this.db_rs != null) {
        try {
          this.db_rs.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_stmt != null) {
        try {
          this.db_stmt.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_pstmt != null) {
        try {
          this.db_pstmt.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_conn != null) {
        try {
          this.db_conn.close();
        } catch (SQLException SQLE) {;
        }
      }

      forceClose();
    }
  }
コード例 #29
0
ファイル: SgtUtil.java プロジェクト: BobSimons/erddap
  /**
   * If the line is short, this adds the line to StringArray. If the line is long, this splits the
   * line in 2 and adds both to StringArray.
   *
   * @param limit is the maximum number of characters per line
   * @param stringArray to capture the parts of s
   * @param s the string to be split (if needed) (if s == null or "", stringArray is unchanged).
   */
  private static void splitLine(int limit, StringArray stringArray, String s) {

    int limit10 = limit * 10;
    while (true) {
      if (s == null || s.length() == 0) return;

      int sLength = s.length();
      if (sLength <= limit * 2 / 3) { // short line is okay even if all caps
        stringArray.add(s);
        return;
      }

      // count through chars   noting more width of cap letters and digits, than avg letter
      int lastSpace = -1;
      int lastNonDigitChar = -1;
      int po = 0;
      int sum10 = 0;
      while (po < sLength && sum10 < limit10) {
        char ch = s.charAt(po);
        if (String2.isDigit(ch)) {
          sum10 += 14;
        } else if (String2.isLetter(ch)) {
          sum10 +=
              ch == 'C' || ch == 'M' || ch == 'S' || ch == 'W'
                  ? 16
                  : ch == 'c'
                          || ch == 'm'
                          || ch == 's'
                          || ch == 'w'
                          || ch == Character.toUpperCase(ch)
                      ? 15
                      : 10;
        } else if (ch == ' ') {
          sum10 += 8;
          lastSpace = po;
          lastNonDigitChar = po;
        } else if ("<>=_".indexOf(ch) >= 0) {
          sum10 += 17;
        } else {
          sum10 += 10;
          lastNonDigitChar = po;
        }
        po++;
      }

      // po == sLength is success
      // if just a few chars more, let it go
      if (po + 4 >= sLength) {
        stringArray.add(s);
        return;
      }

      // break at last space (or nonDigitLetter) before limit
      po =
          lastSpace >= limit * 3 / 4
              ? lastSpace
              : // preferred
              lastNonDigitChar >= limit / 2
                  ? lastNonDigitChar
                  : // next best
                  po; // worst case

      // add the string
      stringArray.add(s.substring(0, po + 1));

      // revamp s
      s = s.substring(po + 1).trim(); // remove leading space, if any
    }
  }