@SuppressWarnings("resource")
 public static void main(String[] args) throws IOException {
   File file = new File("files/easy/test_ChardonnayOrCabernet.txt");
   BufferedReader buffer = new BufferedReader(new FileReader(file));
   String line;
   while ((line = buffer.readLine()) != null) {
     line = line.trim();
     String[] numStrings = line.split("\\|");
     String[] words = numStrings[0].trim().split(" ");
     String reg = numStrings[1].trim();
     StringBuffer strBuffer = new StringBuffer();
     int outFlag = 0;
     for (int i = 0; i < words.length; i++) {
       boolean inFlag = true;
       String tempWord = new String(words[i]);
       for (int j = 0; j < reg.length(); j++) {
         if (!tempWord.contains(Character.toString(reg.charAt(j)))) {
           inFlag = false;
           break;
         } else {
           tempWord = new String(tempWord.replaceFirst(Character.toString(reg.charAt(j)), ""));
         }
       }
       if (inFlag == true) {
         strBuffer.append(words[i] + " ");
         outFlag++;
       }
     }
     if (outFlag == 0) strBuffer.append("False ");
     System.out.println(strBuffer.substring(0, strBuffer.length() - 1));
   }
 }
Пример #2
0
 public Equation(String eq) {
   eqObjs = new ArrayList<Object>();
   int tmp = -1;
   for (int i = 0; i < eq.length(); i++) {
     char c = eq.charAt(i);
     if (Character.isDigit(c)) { // char is a digit
       if (tmp != -1) {
         int tmp2 = tmp * 10; // digit with 2 numbers
         tmp = Integer.parseInt(Character.toString(c));
         eqObjs.add(tmp2 + tmp);
         tmp = -1;
       } else { // single number digit
         tmp = Integer.parseInt(Character.toString(c));
       }
     } else {
       if (tmp != -1) {
         eqObjs.add(tmp); // add tmp obj b4 operator
         tmp = -1;
       } // add operator
       eqObjs.add(Character.toString(c));
     }
   }
   if (tmp != -1) {
     eqObjs.add(tmp); // add final operand
   }
 }
Пример #3
0
  public void buildPosHash(HashSet[] posDict) {
    if (msg.isEmpty()) {
      return;
    }
    String str = msg;

    for (int i = 0; i < length; i++) {
      int subStrIdx = 0;
      if (str.charAt(0) == '(') {
        for (int k = 1; k < str.length(); k++) {
          if (str.charAt(k) == ')') {
            subStrIdx = k;
            break;
          }
          String charStr = Character.toString(str.charAt(k));
          if (posDict[i].contains(charStr)) {
            hashWord[i].add(charStr);
          }
        }
      } else {
        String charStr = Character.toString(str.charAt(0));
        if (posDict[i].contains(charStr)) {
          hashWord[i].add(charStr);
        }
        subStrIdx = 0;
      }
      str = str.substring(subStrIdx + 1);
    }
  }
Пример #4
0
  public static String decode(String data) {
    StringBuffer out = new StringBuffer();

    // length must be multiple of 4 (with padding)
    if (data.length() % 4 != 0) return "";

    for (int i = 0; i < data.length(); ) {
      byte e0 = dtab[data.charAt(i++) & 0x7f];
      byte e1 = dtab[data.charAt(i++) & 0x7f];
      byte e2 = dtab[data.charAt(i++) & 0x7f];
      byte e3 = dtab[data.charAt(i++) & 0x7f];

      // Invalid characters in input
      if (e0 == -1 || e1 == -1 || e2 == -1 || e3 == -1) return "";

      byte d0 = (byte) ((e0 << 2) + ((e1 >>> 4) & 0x03));
      byte d1 = (byte) ((e1 << 4) + ((e2 >>> 2) & 0x0f));
      byte d2 = (byte) ((e2 << 6) + (e3 & 0x3f));

      out.append(Character.toString((char) d0));
      if (e2 != 64) out.append(Character.toString((char) d1));
      if (e3 != 64) out.append(Character.toString((char) d2));
    }
    return out.toString();
  }
  private void textToSprites(
      String mText, Sprite[] toSprites, ITextureRegion[] fromRegions, float x, float y) {

    clear(toSprites);

    char[] c = (mText.toCharArray());
    int l = c.length;
    float mX = 0;
    for (int i = 0; i < l; i++) {

      if (!Character.toString(c[i]).equals(".")) {
        toSprites[i] =
            new Sprite(0, 0, fromRegions[Integer.parseInt(Character.toString(c[i]))], vbom);
      } else if (Character.toString(c[i]).equals(".")) {
        toSprites[i] = new Sprite(0, 0, fromRegions[10], vbom);
      }

      if (i == 0) {
        mX = x;
      } else {
        mX = mX + toSprites[i - 1].getWidth() * 0.9f;
      }

      toSprites[i].setPosition(mX, y);
      toSprites[i].setZIndex(1000);
      attachChild(toSprites[i]);
    }
  }
  /**
   * Get the given key of the song (or as best we can work out if it's not specified) transposed by
   * the given number of semitones.
   *
   * <p>
   *
   * @param semitones the number of semitones to transpose the key.
   * @return the key, transposed.
   */
  private String getKey(int semitones) {
    TextField keyField =
        QueleaApp.get().getMainWindow().getSongEntryWindow().getDetailedSongPanel().getKeyField();
    String key = keyField.getText();
    if (key == null || key.isEmpty()) {
      for (String line : getLyricsField().getText().split("\n")) {
        if (new LineTypeChecker(line).getLineType() == LineTypeChecker.Type.CHORDS) {
          String first;
          int i = 0;
          do {
            first = line.split("\\s+")[i++];
          } while (first.isEmpty());
          key = new ChordTransposer(first).transpose(semitones, null);
          if (key.length() > 2) {
            key = key.substring(0, 2);
          }
          if (key.length() == 2) {
            if (key.charAt(1) == 'B') {
              key = Character.toString(key.charAt(0)) + "b";
            } else if (key.charAt(1) != 'b' && key.charAt(1) != '#') {
              key = Character.toString(key.charAt(0));
            }
          }
          break;
        }
      }
    }

    if (key == null || key.isEmpty()) {
      key = null;
    }
    return key;
  }
  /**
   * CSV Writer main constructor.
   *
   * @param outputStream the output stream
   * @param encoding the encoding
   * @param separator the separator
   * @param stringQuote the string quote
   * @param lineBreak the line break
   */
  public CsvWriter(
      OutputStream outputStream,
      Charset encoding,
      char separator,
      Character stringQuote,
      String lineBreak) {
    this.outputStream = outputStream;
    this.encoding = encoding;
    this.separator = separator;
    separatorString = Character.toString(separator);
    this.lineBreak = lineBreak;
    if (stringQuote != null) {
      this.stringQuote = stringQuote;
      stringQuoteEscapeCharacter = stringQuote;
      stringQuoteString = Character.toString(stringQuote);
      escapedStringQuoteString = stringQuoteEscapeCharacter + stringQuoteString;
      useStringQuote = true;
    } else {
      useStringQuote = false;
    }

    if (this.encoding == null) {
      throw new IllegalArgumentException("Encoding is null");
    } else if (this.outputStream == null) {
      throw new IllegalArgumentException("OutputStream is null");
    } else if (anyCharsAreEqual(this.separator, '\r', '\n')) {
      throw new IllegalArgumentException("Separator '" + this.separator + "' is invalid");
    } else if (useStringQuote && anyCharsAreEqual(this.separator, this.stringQuote, '\r', '\n')) {
      throw new IllegalArgumentException("Stringquote '" + this.stringQuote + "' is invalid");
    } else if (!this.lineBreak.equals("\r")
        && !this.lineBreak.equals("\n")
        && !this.lineBreak.equals("\r\n")) {
      throw new IllegalArgumentException("Given linebreak is invalid");
    }
  }
Пример #8
0
 /**
  * Replaces parameters in the string with values specified.
  *
  * <p>
  *
  * <p>For example a string like 'My name is &lt;name&gt;' and you provide {@code Param.P("name",
  * "rojoss")} it would return 'My name is rojoss' <b>Notice how there is no &lt; and &gt; sign
  * around the parameter name for {@link Param}!</b> If the message doesn't have parameters
  * specified nothing will happen.
  *
  * <p>
  *
  * <p><b>No need to call this for messages from {@link Msg#get(String, Param...)} as that already
  * replaces the specified params using this method</b>
  *
  * <p>It does not affect JSON messages unless used before parsing to JSON.
  *
  * <p>
  *
  * <p>It supports capitalization for parameters too. For example if you put &lt;Name&gt; it would
  * be replaced with Rojoss and if you put &lt;NAME&gt; it would be ROJOSS. Lowercase parameter
  * names will use the value provided in the parameter. The parameter can be prefixed with a
  * underscore to force the value lowercase like &lt;_name&gt;
  *
  * @param params The list of parameters to replace. The &lt;p&gt; parameter is reserved and this
  *     gets replaced with global prefix.
  * @return This msg instance.
  * @see Param
  */
 public Msg params(Param... params) {
   if (!message.contains(Character.toString(PARAM_OPEN))
       || !message.contains(Character.toString(PARAM_CLOSE))) {
     return this;
   }
   if (message == null) {
     message = original;
   }
   for (Param param : params) {
     message =
         message.replace(
             PARAM_OPEN + param.getParam().toLowerCase() + PARAM_CLOSE, param.toString());
     message =
         message.replace(
             PARAM_OPEN + "_" + param.getParam().toLowerCase() + PARAM_CLOSE,
             param.toString().toLowerCase());
     message =
         message.replace(
             PARAM_OPEN + param.getParam().toUpperCase() + PARAM_CLOSE,
             param.toString().toUpperCase());
     message =
         message.replace(
             PARAM_OPEN + Str.capitalize(param.getParam().toLowerCase()) + PARAM_CLOSE,
             Str.capitalize(param.toString()));
   }
   message = message.replace("<p>", Msg.getRaw("prefix").message);
   return this;
 }
Пример #9
0
  private static String createRegexForReplace(String toFind) {
    char[] find = toFind.toCharArray();
    StringBuilder regexString = new StringBuilder();
    for (char f : find) {
      int d = f;
      if ((d >= 65 && d <= 90) || (d >= 97 && d <= 122)) {
        regexString.append("[");
        regexString.append(Character.toString((char) d));
        int temp = d;
        if (Character.isLowerCase(f)) {
          temp = d - 32;
        } else {
          temp = d + 32;
        }
        regexString.append(Character.toString((char) temp));
        regexString.append("]");
      } else if (d == 32) {

        regexString.append("[\\s]");
      } else {
        regexString.append("[");
        regexString.append(f);
        regexString.append("]");
      }
    }
    return regexString.toString();
  }
Пример #10
0
  @Override
  public final String formatCSV(char delimiter, String nullString) {
    StringBuilder sb = new StringBuilder();

    String sep1 = "";
    for (Field<?> field : fields) {
      sb.append(sep1);
      sb.append(formatCSV0(field.getName(), ""));

      sep1 = Character.toString(delimiter);
    }

    sb.append("\n");

    for (Record record : this) {
      String sep2 = "";

      for (int index = 0; index < fields.fields.length; index++) {
        sb.append(sep2);
        sb.append(formatCSV0(record.getValue(index), nullString));

        sep2 = Character.toString(delimiter);
      }

      sb.append("\n");
    }

    return sb.toString();
  }
Пример #11
0
 public SchemeMethod mutateCode(SchemeMethod method) {
   String code = method.getCode();
   double location = Math.random() * (code.length() - 1);
   double character = Math.random() * 100 + 32;
   double type = Math.random() * 3;
   if (character > 94 + 32) {
     character = 32;
   }
   if (code.length() > 0) {
     if (type == 0) {
       code =
           code.substring(0, (int) location)
               + Character.toString((char) character)
               + code.substring((int) location);
     } else if (type == 1) {
       code =
           code.substring(0, (int) location)
               + Character.toString((char) character)
               + code.substring((int) location - 1);
     } else {
       code =
           code.substring(0, (int) location)
               + Character.toString((char) character)
               + code.substring((int) location + 1);
     }
   }
   method.setCode(code);
   return method;
 }
Пример #12
0
 // by Jaume Ortola
 private boolean areEqual(final char x, final char y) {
   if (x == y) {
     return true;
   }
   if (dictionaryMetadata.getEquivalentChars() != null
       && dictionaryMetadata.getEquivalentChars().containsKey(x)
       && dictionaryMetadata.getEquivalentChars().get(x).contains(y)) {
     return true;
   }
   if (dictionaryMetadata.isIgnoringDiacritics()) {
     String xn = Normalizer.normalize(Character.toString(x), Form.NFD);
     String yn = Normalizer.normalize(Character.toString(y), Form.NFD);
     if (xn.charAt(0) == yn.charAt(0)) { // avoid case conversion, if possible
       return true;
     }
     if (dictionaryMetadata.isConvertingCase()) {
       // again case conversion only when needed -- we
       // do not need String.lowercase because we only check
       // single characters, so a cheaper method is enough
       if (Character.isLetter(xn.charAt(0))) {
         boolean testNeeded =
             Character.isLowerCase(xn.charAt(0)) != Character.isLowerCase(yn.charAt(0));
         if (testNeeded) {
           return Character.toLowerCase(xn.charAt(0)) == Character.toLowerCase(yn.charAt(0));
         }
       }
     }
     return xn.charAt(0) == yn.charAt(0);
   }
   return false;
 }
Пример #13
0
 public void tree(Graphics2D g2d, double size, int phase) {
   g2d.setColor(colors[phase % 3]);
   new TextLayout(theT.toString(), theFont, g2d.getFontRenderContext()).draw(g2d, 0.0f, 0.0f);
   if (size > 10.0) {
     AffineTransform at = new AffineTransform();
     at.setToTranslation(Twidth, -0.1);
     at.scale(0.6, 0.6);
     g2d.transform(at);
     size *= 0.6;
     new TextLayout(theR.toString(), theFont, g2d.getFontRenderContext()).draw(g2d, 0.0f, 0.0f);
     at.setToTranslation(Rwidth + 0.75, 0);
     g2d.transform(at);
     Graphics2D g2dt = (Graphics2D) g2d.create();
     at.setToRotation(-Math.PI / 2.0);
     g2dt.transform(at);
     tree(g2dt, size, phase + 1);
     g2dt.dispose();
     at.setToTranslation(.75, 0);
     at.rotate(-Math.PI / 2.0);
     at.scale(-1.0, 1.0);
     at.translate(-Twidth, 0);
     g2d.transform(at);
     tree(g2d, size, phase);
   }
   g2d.setTransform(new AffineTransform());
 }
Пример #14
0
  /**
   * Replaces any empty tokens by a null token. Eg if the given delimiter
   * is ; the row
   * <P><PRE>data1;data2;;data4;
   *
   * <P>will be transformed to
   *
   * <P>data1;data2;\0;data4;\0
   *
   * @param fileRow The row to repace tokens on.
   * @param fieldDelimiter The field delimiter.
   * @return A "fixed" version of the given row.
   */
  public static String replaceEmptyTokens(String fileRow, Character fieldDelimiter) {
    // Define the empty token and the null token
    String aEmptyToken = fieldDelimiter.toString() + fieldDelimiter.toString();
    String aNullToken = fieldDelimiter.toString() + "\0" + fieldDelimiter.toString();

    // If last token is empty (ie, last char is the field delimiter),
    // append a null char at the end of the row
    if (fileRow.substring(fileRow.length() - 1).equalsIgnoreCase(fieldDelimiter.toString())) {
      fileRow = fileRow + "\0";
    }

    // Copy data to a buffer so it can be modified. Then find the
    // position of the first empty token
    StringBuffer fileRowAsBuffer = new StringBuffer(fileRow);
    int aTokenPos = fileRow.indexOf(aEmptyToken);

    // While there are empty tokens
    while (aTokenPos > -1) {
      // Replace the empty token with a null token
      fileRowAsBuffer.replace(aTokenPos, aTokenPos + 2, aNullToken);

      // Copyt data back to string and look for more empty tokens
      fileRow = fileRowAsBuffer.toString();
      aTokenPos = fileRow.indexOf(aEmptyToken);
    }
    return fileRow;
  }
Пример #15
0
 /**
  * 得到 全拼
  *
  * @param src
  * @return
  */
 public static String getPingYin(String src) {
   char[] t1 = null;
   t1 = src.toCharArray();
   String[] t2 = new String[t1.length];
   HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
   t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
   t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
   t3.setVCharType(HanyuPinyinVCharType.WITH_V);
   String t4 = "";
   int t0 = t1.length;
   try {
     for (int i = 0; i < t0; i++) {
       // 判断是否为汉字字符
       if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
         t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
         t4 += t2[0];
       } else {
         t4 += Character.toString(t1[i]);
       }
     }
     return t4;
   } catch (BadHanyuPinyinOutputFormatCombination e1) {
     e1.printStackTrace();
   }
   return t4;
 }
Пример #16
0
 /**
  * 将汉字转换为全拼
  *
  * @param src
  * @return String
  */
 public static String getPinYin(String src) {
   char[] t1 = null;
   t1 = src.toCharArray();
   // System.out.println(t1.length);
   String[] t2 = new String[t1.length];
   // System.out.println(t2.length);
   // 设置汉字拼音输出的格式
   HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
   t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
   t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
   t3.setVCharType(HanyuPinyinVCharType.WITH_V);
   String t4 = "";
   int t0 = t1.length;
   try {
     for (int i = 0; i < t0; i++) {
       // 判断是否为汉字字符
       // System.out.println(t1[i]);
       if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
         t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3); // 将汉字的几种全拼都存到t2数组中
         t4 += t2[0]; // 取出该汉字全拼的第一种读音并连接到字符串t4后
       } else {
         // 如果不是汉字字符,直接取出字符并连接到字符串t4后
         t4 += Character.toString(t1[i]);
       }
     }
   } catch (BadHanyuPinyinOutputFormatCombination e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return t4;
 }
 /**
  * Create a single csv line.
  *
  * @param separator the separator
  * @param stringQuote the string quote
  * @param values the values
  * @return the csv line
  */
 public static String getCsvLine(char separator, Character stringQuote, Object... values) {
   StringBuilder returnValue = new StringBuilder();
   String separatorString = Character.toString(separator);
   String stringQuoteString = stringQuote == null ? "" : Character.toString(stringQuote);
   String doubleStringQuoteString = stringQuoteString + stringQuoteString;
   if (values != null) {
     for (Object value : values) {
       if (returnValue.length() > 0) {
         returnValue.append(separator);
       }
       if (value != null) {
         String valueString = value.toString();
         if (valueString.contains(separatorString)
             || valueString.contains("\r")
             || valueString.contains("\n")
             || valueString.contains(stringQuoteString)) {
           returnValue.append(stringQuoteString);
           returnValue.append(valueString.replace(stringQuoteString, doubleStringQuoteString));
           returnValue.append(stringQuoteString);
         } else {
           returnValue.append(valueString);
         }
       }
     }
   }
   return returnValue.toString();
 }
  public ResidueInfo getResidue(PolymerType pt, Character oneLetterCode) {

    String monId;
    Map<Character, String> theMapToUse;
    switch (pt) {
      case peptide:
        theMapToUse = ResidueTools.AMINO_ACID_LOOKUP_1TO3;
        break;
      case dna:
        theMapToUse = ResidueTools.DNA_LOOKUP_1TO2;
        break;
      case rna:
        return ResidueProvider.getResidue(oneLetterCode.toString().toUpperCase());
      default:
        theMapToUse = Collections.emptyMap();
        break;
    }
    if ((monId = theMapToUse.get(oneLetterCode)) != null) {
      return ResidueProvider.getResidue(monId);
    } else if ((monId = theMapToUse.get(oneLetterCode.toString().toUpperCase().charAt(0)))
        != null) // TODO find an efficient way to convert Character to upper-case equiv
    {
      return ResidueProvider.getResidue(monId);
    } else {
      throw new RuntimeException("Could not find " + pt.toString() + " with code " + oneLetterCode);
    }
  }
Пример #19
0
  private void readAndBindToReader(Environment env, IReader reader)
      throws IOException, TypeException {
    readChar(env);
    if (!(env.peek() instanceof VChar)) {
      env.pushError("Argument on the stack is not a Char");
      return;
    }

    int ch = ((VChar) env.peek()).getChar();
    if (ch == -1) {
      // End of stream, send the Terminator
      env.pop();
      env.pushReader("terminator");
      env.pushOp("read");
      return;
    }

    if (shouldIgnore((char) ch, "Not setting reader for " + reader.getClass().getName())) {
      env.pop();
      return;
    }

    env.setBinding(Character.toString((char) ch), reader);
    env.pop();

    System.err.println(
        "r(Bootstrap): " + Character.toString((char) ch) + " => " + reader.getClass().getName());
  }
Пример #20
0
  /**
   * Return a String representation of this MGRS reference to 1m, 10m, 100m, 1000m or 10000m
   * precision.
   *
   * @param precision One of MGRSRef.PRECISION_1M, MGRSRef.PRECISION_10M, MGRSRef.PRECISION_100M,
   *     MGRSRef.PRECISION_1000M, MGRSRef.PRECISION_10000M.
   * @return a String representation of this MGRS reference to the required precision.
   * @since 1.1
   */
  public String toString(int precision) {

    if (precision != PRECISION_1M
        && precision != PRECISION_10M
        && precision != PRECISION_100M
        && precision != PRECISION_1000M
        && precision != PRECISION_10000M) {
      throw new IllegalArgumentException(
          "Precision (" + precision + ") must be 1m, 10m, 100m, 1000m or 10000m");
    }

    int eastingR = (int) Math.floor(easting / precision);
    int northingR = (int) Math.floor(northing / precision);

    int padding = 5;

    switch (precision) {
      case PRECISION_10M:
        padding = 4;
        break;
      case PRECISION_100M:
        padding = 3;
        break;
      case PRECISION_1000M:
        padding = 2;
        break;
      case PRECISION_10000M:
        padding = 1;
        break;
    }

    String eastingRs = Integer.toString(eastingR);
    int ez = padding - eastingRs.length();
    while (ez > 0) {
      eastingRs = "0" + eastingRs;
      ez--;
    }

    String northingRs = Integer.toString(northingR);
    int nz = padding - northingRs.length();
    while (nz > 0) {
      northingRs = "0" + northingRs;
      nz--;
    }

    String utmZonePadding = "";
    if (utmZoneNumber < 10) {
      utmZonePadding = "0";
    }

    return utmZonePadding
        + utmZoneNumber
        + Character.toString(utmZoneChar)
        + Character.toString(eastingID)
        + Character.toString(northingID)
        + eastingRs
        + northingRs;
  }
Пример #21
0
 // Finds the order number of the character in the alphabet array (1 less than it's actually alpha
 // pos)
 private int valueOf(char character) {
   int value = 0;
   for (int i = 0; i < alphabet.length(); i++) {
     if (Character.toString(character).equalsIgnoreCase(Character.toString(alphabet.charAt(i)))) {
       value = i;
     }
   }
   return value;
 }
Пример #22
0
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    PlaylistItem playlistItem = mPlaylistItemList.get(position);

    if (convertView == null) {
      convertView = LayoutInflater.from(mActivity).inflate(R.layout.playlist_item, null);
    }

    View letterTitleDividerLine = convertView.findViewById(R.id.letterTitleDividerLine);
    TextView letterTitleTextView = (TextView) convertView.findViewById(R.id.letterTitleTextView);
    TextView playlistTextView = (TextView) convertView.findViewById(R.id.playlistNameTextView);
    TextView contributorTextView =
        (TextView) convertView.findViewById(R.id.contributorNameTextView);
    View playlistListViewDivider = convertView.findViewById(R.id.playlistListViewDivider);

    playlistTextView.setText(playlistItem.getPlaylist());
    contributorTextView.setText(playlistItem.getContributor());

    String firstCharCurrentItem =
        Character.toString(playlistItem.getPlaylist().toUpperCase().charAt(0));

    if (position > 0) {
      String firstCharPreviousItem =
          Character.toString(
              mPlaylistItemList.get(position - 1).getPlaylist().toUpperCase().charAt(0));

      if (!firstCharCurrentItem.equals(firstCharPreviousItem)) {
        letterTitleTextView.setText(firstCharCurrentItem);
        letterTitleTextView.setVisibility(View.VISIBLE);
        letterTitleDividerLine.setVisibility(View.VISIBLE);
      } else {
        letterTitleTextView.setVisibility(View.GONE);
        letterTitleDividerLine.setVisibility(View.GONE);
      }
    } else {
      letterTitleTextView.setText(firstCharCurrentItem);
      letterTitleTextView.setVisibility(View.VISIBLE);
      letterTitleDividerLine.setVisibility(View.VISIBLE);
    }

    if (position < mPlaylistItemList.size() - 1) {
      String firstCharNextItem =
          Character.toString(
              mPlaylistItemList.get(position + 1).getPlaylist().toUpperCase().charAt(0));

      if (firstCharCurrentItem.equals(firstCharNextItem)) {
        playlistListViewDivider.setVisibility(View.VISIBLE);
      } else {
        playlistListViewDivider.setVisibility(View.GONE);
      }
    } else {
      playlistListViewDivider.setVisibility(View.GONE);
    }

    return convertView;
  }
Пример #23
0
  /**
   * * 根据出生年份算出本年的生肖
   *
   * @param year
   * @return
   */
  public static String getAnimals(int year) {
    String s = "猪鼠牛虎兔龙蛇马羊猴鸡狗猪";
    int index = (year % 12) - 3;

    if (index < 0) {
      return Character.toString(s.charAt(index + 12));
    } else {
      return Character.toString(s.charAt(index));
    }
  }
 private void actualizarTablero(
     char movimiento, StringBuilder desde, StringBuilder hasta, char enroque) {
   botones.get(desde.toString()).setText(Character.toString('\u0000'));
   Color color = lado ? Color.WHITE : Color.BLACK;
   if (enroque != '\u0000') {
     color = !lado ? Color.WHITE : Color.BLACK;
   }
   botones.get(hasta.toString()).setForeground(color);
   botones.get(hasta.toString()).setText(Character.toString(movimiento));
 }
Пример #25
0
 public static void main(String args[]) throws IOException {
   DataInputStream ip = new DataInputStream(System.in);
   String S1 = new String();
   String temp;
   String S2 = new String();
   int i;
   System.out.print("Enter expression : ");
   temp = ip.readLine();
   for (i = 0; i < temp.length(); i++) {
     if (temp.charAt(i) == '*') {
       // System.out.println(temp.substring(0,i)); //i because of gorm [,)
       // System.out.println(temp.substring(i+1,temp.length()));
       S1 = temp.substring(0, i); // i because of gorm [,)
       S2 = temp.substring(i + 1, temp.length());
     }
   }
   int a1[] = new int[100];
   int a2[] = new int[100];
   int k = 0;
   for (i = S1.length() - 1; i >= 0; i--) {
     String temp2 = Character.toString(S1.charAt(i));
     a1[99 - k] = Integer.parseInt(temp2);
     k++;
   }
   k = 0;
   for (i = S2.length() - 1; i >= 0; i--) {
     String temp2 = Character.toString(S2.charAt(i));
     a2[99 - k] = Integer.parseInt(temp2);
     k++;
   }
   int a3[] = new int[100];
   /*
    * write multiplication code here
    */
   int temp3 = 0;
   for (i = 99; i > 99 - S1.length(); i--) // change here
   {
     int temp2 = a1[i] * a2[99] + temp3;
     temp3 =
         0; // addition to correct code since it was not being set to zero it was causing errors
     if (temp2 < 10
         || i == 99 - S1.length() + 1) // change made here so that if last result is >=10
     { // it should be written directly
       a3[i] = temp2;
     } else {
       a3[i] = temp2 % 10;
       temp3 = ((temp2 - temp2 % 10) / 10); // unneccessary+a3[i-1];
     }
   }
   for (i = 0; i < 100; i++) {
     System.out.print(a3[i]);
   }
 }
  /** Metoda koja vraca broj ponavljanja karaktera u stringu */
  public static int count(String str, char a) {

    int brojac = 0;
    // petlja koja prolazi kroz uneseni string
    for (int i = 0; i < str.length(); i++) {
      // ako je bilo koji karakter u unesenom stringu jednak trazenom karakteru
      if (Character.toString(str.charAt(i)).contains(Character.toString(a))) {
        brojac++; // onda brojac broji koliko se trazeni karakter puta nalazi u stringu
      }
    }
    return brojac; // vraca se ukupan broj ponavljanja trazenog karaktera u stringu
  }
  public String interpolateTextMarksIntoRegex(String regex) {

    String specialChars =
        "(\\{|\\}|\\(|\\)|\\d|\\.|-|\\]|\\[|\u0323|\\p{Punct}|(-?\\s*[\\d]+\\.\\s))*";
    StringBuilder regexBuilder = new StringBuilder();
    String prevChar = "";
    int curlyBracesCount = 0;
    int parensCount = 0;
    Boolean insideNegLookBehind = false;

    for (int i = 0; i < regex.length(); i++) {

      String nowChar = Character.toString(regex.charAt(i));
      String nextChar = i == regex.length() - 1 ? "" : Character.toString(regex.charAt(i + 1));
      if (nowChar.equals("<")
          && prevChar.equals("?")
          && nextChar.equals("!")
          && !insideNegLookBehind) {

        insideNegLookBehind = true;
        parensCount = 1;
      }
      if (insideNegLookBehind && parensCount == 0) {
        insideNegLookBehind = false;
      }
      String abbrevReplacer = "[\\(\\)]";
      regexBuilder.append(nowChar.equals("°") ? abbrevReplacer : nowChar);
      if (!insideNegLookBehind
          && !prevChar.equals("\\")
          && !prevChar.equals("|")
          && !nextChar.equals("|")
          && curlyBracesCount == 0
          && !nextChar.equals("")
          && (nowChar.matches("[\\p{L}\\)]") || nowChar.equals(abbrevReplacer))) {

        regexBuilder.append(specialChars);
      }
      prevChar = nowChar;
      if ("{".equals(nowChar)) {
        curlyBracesCount += 1;
      }
      if ("}".equals(nowChar)) {
        curlyBracesCount -= 1;
      }
      if (("(").equals(nowChar) && insideNegLookBehind) {
        parensCount += 1;
      }
      if ((")").equals(nowChar) && insideNegLookBehind) {
        parensCount -= 1;
      }
    }
    return regexBuilder.toString().trim();
  }
Пример #28
0
 @Override
 public void run() {
   try {
     MainActivity.this.showStatusTextFromThread("Connecting...\n");
     serverAddr = InetAddress.getByName("10.10.100.100");
     if (serverAddr == null) {
       MainActivity.this.showStatusTextFromThread("Can't create server address!\n");
       return;
     }
     socket = new Socket(serverAddr, 8899);
     if (!socket.isConnected()) {
       MainActivity.this.showStatusTextFromThread("Can't connect to Robot!\n");
       return;
     }
     MainActivity.this.showStatusTextFromThread("Connected to Robot.\n");
     PrintWriter out =
         new PrintWriter(
             new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
     BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     long lastWrite = SystemClock.elapsedRealtime();
     int count = 0;
     char ch = 'A';
     while (true) {
       long now = SystemClock.elapsedRealtime();
       if (now - lastWrite >= 3000) {
         if (count >= 5) break;
         MainActivity.this.showStatusTextFromThread(
             "(" + Long.toString(now) + ") SND: " + Character.toString(ch) + "\n");
         out.println(ch++);
         count++;
         lastWrite = now;
       }
       if (in.ready()) {
         char ch2 = (char) in.read();
         MainActivity.this.showStatusTextFromThread(
             "(" + Long.toString(now) + ") RCV: " + Character.toString(ch2) + "\n");
       } else {
         Thread.sleep(100);
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
     MainActivity.this.showStatusTextFromThread(e.getLocalizedMessage());
   } finally {
     try {
       if (socket != null) socket.close();
     } catch (Exception e) {
       e.printStackTrace();
       MainActivity.this.showStatusTextFromThread(e.getLocalizedMessage());
     }
   }
 }
Пример #29
0
 private boolean readValue(String io, String num) {
   if (io.equals("E")) {
     GWT.log(
         "Value read at E "
             + io
             + num
             + ":  "
             + this.input[Integer.parseInt(Character.toString(num.charAt(2)))]);
     return this.input[Integer.parseInt(Character.toString(num.charAt(2)))];
   } else {
     this.error = true;
     return true;
   }
 }
  /**
   * Constructor de la clase, recibe como parametros la tabla en la cual buscar los valores y la
   * cadena a convertir.
   *
   * <p>La responsabilidad de la clase es la de convertir una espresion de tipo "=A3*B5", al tipo
   * "(valor de A3)*(valor de B5)" y enviarla a <i>DemultiplexorExpresion</i> a que la resuelva.
   *
   * @param tabla Tabla de la cual recuperar los datos
   * @param cad Cadena a convertir
   */
  public DemutiplexorFormula(AbstractTableModel tabla, String cad) {
    strToken = new StringTokenizer(cad, "=+*-/^() ", true);
    cadena = new String();
    fila = new String();
    columna = new String();

    while (strToken.hasMoreTokens()) {
      String g = strToken.nextToken();
      // Nos saltamos los siguientes tokens
      if (!g.equals("=") && !g.equals(" ")) {
        char a = 'A';
        for (int i = 0; i < 26; i++) {
          if (g.startsWith(Character.toString(a))) {
            isCelda = true;
            StringTokenizer str = new StringTokenizer(g, Character.toString(a), true);
            if (str.countTokens() == 2) {
              // Validamos que solamente existan 2 Tokens
              columna = str.nextToken();
              fila = str.nextToken();

              try {
                datoCelda =
                    (String)
                        tabla.getValueAt(
                            Integer.valueOf(fila).intValue() - 1, validarColumna(columna));
              } catch (NumberFormatException e) {
                System.err.println("Celda no valida");
                return;
              }

              if (datoCelda == null) {
                System.err.println("La Celda " + columna + fila + " no contiene ningun valor");
                return;
              }
              cadena += datoCelda;
            } else {
              System.err.println("Celda no valida");
              return;
            }
          }
          a++;
        }
        if (!isCelda) cadena += g;

        // Volvemos a la condicion inicial
        isCelda = false;
      }
    }
    demultiplexorExpresion = new DemultiplexorExpresion(cadena);
  }