protected void calculateModelAttributes() { String pakkage = calculateJavaModelPackage(); StringBuilder sb = new StringBuilder(); sb.append(pakkage); sb.append('.'); sb.append(fullyQualifiedTable.getDomainObjectName()); sb.append("Key"); // $NON-NLS-1$ setPrimaryKeyType(sb.toString()); sb.setLength(0); sb.append(pakkage); sb.append('.'); sb.append(fullyQualifiedTable.getDomainObjectName()); setBaseRecordType(sb.toString()); sb.setLength(0); sb.append(pakkage); sb.append('.'); sb.append(fullyQualifiedTable.getDomainObjectName()); sb.append("WithBLOBs"); // $NON-NLS-1$ setRecordWithBLOBsType(sb.toString()); sb.setLength(0); sb.append(pakkage); sb.append('.'); sb.append(fullyQualifiedTable.getDomainObjectName()); sb.append("Example"); // $NON-NLS-1$ setExampleType(sb.toString()); }
/** * Returns a map with variable bindings. * * @param opts main options * @return bindings */ public static HashMap<String, String> bindings(final MainOptions opts) { final HashMap<String, String> bindings = new HashMap<>(); final String bind = opts.get(MainOptions.BINDINGS).trim(); final StringBuilder key = new StringBuilder(); final StringBuilder val = new StringBuilder(); boolean first = true; final int sl = bind.length(); for (int s = 0; s < sl; s++) { final char ch = bind.charAt(s); if (first) { if (ch == '=') { first = false; } else { key.append(ch); } } else { if (ch == ',') { if (s + 1 == sl || bind.charAt(s + 1) != ',') { bindings.put(key.toString().trim(), val.toString()); key.setLength(0); val.setLength(0); first = true; continue; } // literal commas are escaped by a second comma s++; } val.append(ch); } } if (key.length() != 0) bindings.put(key.toString().trim(), val.toString()); return bindings; }
protected void calculateJavaClientAttributes() { if (context.getJavaClientGeneratorConfiguration() == null) { return; } StringBuilder sb = new StringBuilder(); sb.append(calculateJavaClientImplementationPackage()); sb.append('.'); sb.append(fullyQualifiedTable.getDomainObjectName()); sb.append("DAOImpl"); // $NON-NLS-1$ setDAOImplementationType(sb.toString()); sb.setLength(0); sb.append(calculateJavaClientInterfacePackage()); sb.append('.'); sb.append(fullyQualifiedTable.getDomainObjectName()); sb.append("DAO"); // $NON-NLS-1$ setDAOInterfaceType(sb.toString()); sb.setLength(0); sb.append(calculateJavaClientInterfacePackage()); sb.append('.'); sb.append(fullyQualifiedTable.getDomainObjectName()); sb.append("Mapper"); // $NON-NLS-1$ setMyBatis3JavaMapperType(sb.toString()); sb.setLength(0); sb.append(calculateJavaClientInterfacePackage()); sb.append('.'); sb.append(fullyQualifiedTable.getDomainObjectName()); sb.append("SqlProvider"); // $NON-NLS-1$ setMyBatis3SqlProviderType(sb.toString()); }
/** * look for a tag whose text is getStartTag() then read until it closes * * @return true if there is data * @throws java.io.IOException */ public boolean nextKeyValue() throws IOException { String current = m_Sb.toString(); if (current.contains("<scan num=\"67\"")) current = m_Sb.toString(); // break here if (readFromCurrentBuffer()) return true; int newSize; if (m_Current > m_End) { // we are the the end of the split m_Key = null; m_Value = null; m_Sb.setLength(0); return false; } newSize = m_Input.read(m_Buffer); while (newSize > 0) { m_Current += newSize; String read = new String(m_Buffer, 0, newSize); m_Sb.append(read); if (readFromCurrentBuffer()) return true; if (m_Current > m_End) { // we are the the end of the split String s = m_Sb.toString(); if (bufferHasStartTag() == -1) { // not working on a tag m_Key = null; m_Value = null; m_Sb.setLength(0); return false; } if (m_Sb.length() > getMaxTagLength()) { m_Key = null; m_Value = null; m_Sb.setLength(0); return false; } } newSize = m_Input.read(m_Buffer); } // exit because we are at the m_End if (newSize <= 0) { m_Key = null; m_Value = null; m_Sb.setLength(0); return false; } if (m_Current > m_End) { // we are the the end of the split m_Key = null; m_Value = null; m_Sb.setLength(0); return false; } return true; }
/** * Break on commas, except those inside quotes, e.g.: size(300, 200, PDF, "output,weirdname.pdf"); * No special handling implemented for escaped (\") quotes. */ private static StringList breakCommas(String contents) { StringList outgoing = new StringList(); boolean insideQuote = false; // The current word being read StringBuilder current = new StringBuilder(); char[] chars = contents.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (insideQuote) { current.append(c); if (c == '\"') { insideQuote = false; } } else { if (c == ',') { if (current.length() != 0) { outgoing.append(current.toString()); current.setLength(0); } } else { current.append(c); if (c == '\"') { insideQuote = true; } } } } if (current.length() != 0) { outgoing.append(current.toString()); } return outgoing; }
public List<Combat> addAttackers(Game game) { Map<Integer, Combat> engagements = new HashMap<Integer, Combat>(); // useful only for two player games - will only attack first opponent UUID defenderId = game.getOpponents(playerId).iterator().next(); List<Permanent> attackersList = super.getAvailableAttackers(defenderId, game); // use binary digits to calculate powerset of attackers int powerElements = (int) Math.pow(2, attackersList.size()); StringBuilder binary = new StringBuilder(); for (int i = powerElements - 1; i >= 0; i--) { Game sim = game.copy(); binary.setLength(0); binary.append(Integer.toBinaryString(i)); while (binary.length() < attackersList.size()) { binary.insert(0, "0"); } for (int j = 0; j < attackersList.size(); j++) { if (binary.charAt(j) == '1') { setStoredBookmark( sim .bookmarkState()); // makes it possible to UNDO a declared attacker with costs // from e.g. Propaganda if (!sim.getCombat() .declareAttacker(attackersList.get(j).getId(), defenderId, playerId, sim)) { sim.undo(playerId); } } } if (engagements.put(sim.getCombat().getValue().hashCode(), sim.getCombat()) != null) { logger.debug("simulating -- found redundant attack combination"); } else if (logger.isDebugEnabled()) { logger.debug("simulating -- attack:" + sim.getCombat().getGroups().size()); } } return new ArrayList<Combat>(engagements.values()); }
public static String[] splitStringToArray(final CharSequence s, final char c) { if (s == null || s.length() == 0) { return Strings.EMPTY_ARRAY; } int count = 1; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == c) { count++; } } final String[] result = new String[count]; final StringBuilder builder = new StringBuilder(); int res = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == c) { if (builder.length() > 0) { result[res++] = builder.toString(); builder.setLength(0); } } else { builder.append(s.charAt(i)); } } if (builder.length() > 0) { result[res++] = builder.toString(); } if (res != count) { // we have empty strings, copy over to a new array String[] result1 = new String[res]; System.arraycopy(result, 0, result1, 0, res); return result1; } return result; }
public static RestxConfig parse(String origin, InputSupplier<InputStreamReader> readerSupplier) throws IOException { List<ConfigElement> elements = new ArrayList<>(); StringBuilder doc = new StringBuilder(); int lineCount = 0; for (String line : CharStreams.readLines(readerSupplier)) { lineCount++; if (line.startsWith("#")) { doc.append(line.substring(1).trim()).append("\n"); } else if (!line.trim().isEmpty()) { int index = line.indexOf('='); if (index == -1) { throw new IOException( "invalid config " + origin + " at line " + lineCount + ":" + " line does not contain the equals sign '='"); } String key = line.substring(0, index).trim(); String value = line.substring(index + 1).trim(); elements.add(ConfigElement.of(origin, doc.toString().trim(), key, value)); doc.setLength(0); } } return new StdRestxConfig(elements); }
/** Reset any internal state, allowing this builder to be recycled. */ public SelectionBuilder reset() { table = null; selection.setLength(0); selectionArgs.clear(); return this; }
/** 選択されている行をコピーする。 */ public void copyRow() { StringBuilder sb = new StringBuilder(); int numRows = view.getTable().getSelectedRowCount(); int[] rowsSelected = view.getTable().getSelectedRows(); int numColumns = view.getTable().getColumnCount(); for (int i = 0; i < numRows; i++) { if (tableModel.getObject(rowsSelected[i]) != null) { StringBuilder s = new StringBuilder(); for (int col = 0; col < numColumns; col++) { Object o = view.getTable().getValueAt(rowsSelected[i], col); if (o != null) { s.append(o.toString()); } s.append(","); } if (s.length() > 0) { s.setLength(s.length() - 1); } sb.append(s.toString()).append("\n"); } } if (sb.length() > 0) { StringSelection stsel = new StringSelection(sb.toString()); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stsel, stsel); } }
private StringBuilder appendNewLine(StringBuilder buffer) { if (buffer.length() != 0 && buffer.charAt(buffer.length() - 1) != '\n') { while (buffer.charAt(buffer.length() - 1) == ' ') { buffer.setLength(buffer.length() - 1); } buffer.append("\n"); } return buffer; }
@NotNull private static String stripPath(@NotNull String path) { String[] endingsToStrip = {"/", "!", ".jar"}; StringBuilder buffer = new StringBuilder(path); for (String ending : endingsToStrip) { if (buffer.lastIndexOf(ending) == buffer.length() - ending.length()) { buffer.setLength(buffer.length() - ending.length()); } } return buffer.toString(); }
/** @throws Exception If failed. */ public void testClientAffinity() throws Exception { GridClientData partitioned = client.data(PARTITIONED_CACHE_NAME); Collection<Object> keys = new ArrayList<>(); keys.addAll(Arrays.asList(Boolean.TRUE, Boolean.FALSE, 1, Integer.MAX_VALUE)); Random rnd = new Random(); StringBuilder sb = new StringBuilder(); // Generate some random strings. for (int i = 0; i < 100; i++) { sb.setLength(0); for (int j = 0; j < 255; j++) // Only printable ASCII symbols for test. sb.append((char) (rnd.nextInt(0x7f - 0x20) + 0x20)); keys.add(sb.toString()); } // Generate some more keys to achieve better coverage. for (int i = 0; i < 100; i++) keys.add(UUID.randomUUID()); for (Object key : keys) { UUID nodeId = grid(0).mapKeyToNode(PARTITIONED_CACHE_NAME, key).id(); UUID clientNodeId = partitioned.affinity(key); assertEquals( "Invalid affinity mapping for REST response for key: " + key, nodeId, clientNodeId); } }
/** Convert the HTML document back to a string. */ @Override public String toString() { try { StringBuilder result = new StringBuilder(); int ch = 0; StringBuilder text = new StringBuilder(); do { ch = read(); if (ch == 0) { if (text.length() > 0) { System.out.println("Text:" + text.toString()); text.setLength(0); } System.out.println("Tag:" + getTag()); } else if (ch != -1) { text.append((char) ch); } } while (ch != -1); if (text.length() > 0) { System.out.println("Text:" + text.toString().trim()); } return result.toString(); } catch (IOException e) { return "[IO Error]"; } }
public void initialize(InputSplit genericSplit, TaskAttemptContext context) throws IOException { FileSplit split = (FileSplit) genericSplit; Configuration job = context.getConfiguration(); m_Sb.setLength(0); m_Start = split.getStart(); m_End = m_Start + split.getLength(); final Path file = split.getPath(); compressionCodecs = new CompressionCodecFactory(job); final CompressionCodec codec = compressionCodecs.getCodec(file); // open the file and seek to the m_Start of the split FileSystem fs = file.getFileSystem(job); // getFileStatus fileStatus = fs.getFileStatus(split.getPath()); //noinspection deprecation @SuppressWarnings(value = "deprecated") long length = fs.getLength(file); FSDataInputStream fileIn = fs.open(split.getPath()); if (m_Start > 0) fileIn.seek(m_Start); if (codec != null) { CompressionInputStream inputStream = codec.createInputStream(fileIn); m_Input = new BufferedReader(new InputStreamReader(inputStream)); m_End = length; } else { m_Input = new BufferedReader(new InputStreamReader(fileIn)); } m_Current = m_Start; m_Key = split.getPath().getName(); }
private static void takeLine( final Project project, String line, StringBuilder sb, GitLogParser parser, SymbolicRefsI refs, VirtualFile root, VcsException[] exc, GitLineHandler h, AsynchConsumer<GitCommit> gitCommitConsumer) { final String text = sb.toString(); sb.setLength(0); sb.append(line); if (text.length() == 0) return; GitLogRecord record = parser.parseOneRecord(text); final GitCommit gitCommit; try { gitCommit = createCommit(project, refs, root, record); } catch (VcsException e) { exc[0] = e; h.cancel(); return; } gitCommitConsumer.consume(gitCommit); }
@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { assertSAX(!myParseStack.isEmpty()); ElementHandlerBase current = myParseStack.get(myParseStack.size() - 1); if (mySb.length() > 0) { current.characters(mySb.toString().trim(), myPending, myLockBuilder); mySb.setLength(0); } while (true) { final boolean createNewChild = current.startElement(uri, localName, qName, attributes); if (createNewChild) { assertSAX(myElementsMap.containsKey(qName)); final ElementHandlerBase newChild = myElementsMap.get(qName).get(); newChild.preAttributesEffect(myDataCallback); newChild.updateStatus(attributes, myPending, myLockBuilder); newChild.preEffect(myDataCallback); myParseStack.add(newChild); return; } else { // go up current.postEffect(myDataCallback); myParseStack.remove(myParseStack.size() - 1); assertSAX(!myParseStack.isEmpty()); current = myParseStack.get(myParseStack.size() - 1); } } }
public static String toCamelCase(String value, StringBuilder sb) { boolean changed = false; for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (c == '_') { if (!changed) { if (sb != null) { sb.setLength(0); } else { sb = new StringBuilder(); } // copy it over here for (int j = 0; j < i; j++) { sb.append(value.charAt(j)); } changed = true; } if (i < value.length() - 1) { sb.append(Character.toUpperCase(value.charAt(++i))); } } else { if (changed) { sb.append(c); } } } if (!changed) { return value; } return sb.toString(); }
/** Create a random Json document with random values */ public String getRandomJson(int nbNodes) { // init sb.setLength(0); sb.append("{"); states.clear(); states.add(OBJECT_ATT); images.clear(); nodes.clear(); incr.clear(); datatypes.clear(); types.clear(); curNodePath.length = 1; curNodePath.offset = 0; Arrays.fill(curNodePath.ints, -1); shouldFail = false; nestedObjs = 0; // <= so that when nbNodes == 1, the json is still valid /* * the generated json might be uncomplete, if states is not empty, and * the maximum number of nodes has been reached. */ for (final int i = 0; i <= nbNodes && !states.empty(); nbNodes++) { sb.append(this.getWhitespace()).append(this.getNextNode()).append(this.getWhitespace()); } shouldFail = shouldFail ? true : !states.empty(); return sb.toString(); }
private static String getItemList(Set<Item> items) { StringBuilder b = new StringBuilder(); for (Item item : items) { b.append(item.name).append(", "); } b.setLength(b.length() - 2); return b.toString(); }
private static String getSystemList(Set<SolarSystem> systems) { StringBuilder b = new StringBuilder(); for (SolarSystem system : systems) { b.append(system.name).append(", "); } b.setLength(b.length() - 2); return b.toString(); }
public static ArrayList<String> validateSamplesDirectoryStructureIdentifyVersions( String samplesDirPath, ArrayList<String> versionArr) { String samplesDir[] = getDirectoryNames(samplesDirPath); StringBuilder builder = new StringBuilder(); ArrayList<String> tempArr = new ArrayList<String>(); Pattern numeric = Pattern.compile("[0-9_.-]"); for (String dir : samplesDir) { for (int item = dir.length() - 1; item >= 0; item--) { char singleChar = dir.charAt(item); Matcher matcher = numeric.matcher(Character.toString(singleChar)); // Find all matches if (matcher.find()) { // Get the matching string builder.append(singleChar); } else { if (builder.length() > 1) { tempArr.add(builder.toString()); builder.setLength(0); } else { builder.setLength(0); } } if (item == 0 && builder.length() != 0) { tempArr.add(builder.toString()); builder.setLength(0); } } int max; int previousMax = 0; String[] version = new String[1]; for (String element : tempArr) { max = element.length(); if (max > previousMax) { previousMax = max; version[0] = element; } } if (version[0] != null) { if (version[0].length() >= 2) { versionArr.add(dir); } } tempArr.clear(); } return versionArr; }
K getKey() { if (csKey) { sbKey.setLength(0); bytes.readUTFΔ(sbKey); return (K) sbKey; } return (K) bytes.readObject(); }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[ "); for (Node node : getAll()) sb.append(node.toJSON()).append(","); sb.setLength(sb.length() - 1); // remove last comma sb.append(" ]"); return sb.toString(); }
@Override public String _stringValue(final IScope scope) throws GamaRuntimeException { getContents(scope); StringBuilder sb = new StringBuilder(getBuffer().length(scope) * 200); for (IList s : getBuffer().iterable(scope)) { sb.append(s).append("\n"); // TODO Factorize the different calls to "new line" ... } sb.setLength(sb.length() - 1); return sb.toString(); }
public static void getLocalCommittedChanges( final Project project, final VirtualFile root, final Consumer<GitSimpleHandler> parametersSpecifier, final Consumer<GitCommittedChangeList> consumer, boolean skipDiffsForMerge) throws VcsException { GitSimpleHandler h = new GitSimpleHandler(project, root, GitCommand.LOG); h.setSilent(true); h.addParameters( "--pretty=format:%x04%x01" + GitChangeUtils.COMMITTED_CHANGELIST_FORMAT, "--name-status"); parametersSpecifier.consume(h); String output = h.run(); LOG.debug("getLocalCommittedChanges output: '" + output + "'"); StringScanner s = new StringScanner(output); final StringBuilder sb = new StringBuilder(); boolean firstStep = true; while (s.hasMoreData()) { final String line = s.line(); final boolean lineIsAStart = line.startsWith("\u0004\u0001"); if ((!firstStep) && lineIsAStart) { final StringScanner innerScanner = new StringScanner(sb.toString()); sb.setLength(0); consumer.consume( GitChangeUtils.parseChangeList( project, root, innerScanner, skipDiffsForMerge, h, false, false)); } sb.append(lineIsAStart ? line.substring(2) : line).append('\n'); firstStep = false; } if (sb.length() > 0) { final StringScanner innerScanner = new StringScanner(sb.toString()); sb.setLength(0); consumer.consume( GitChangeUtils.parseChangeList( project, root, innerScanner, skipDiffsForMerge, h, false, false)); } if (s.hasMoreData()) { throw new IllegalStateException("More input is avaialble: " + s.line()); } }
/** * Returns a string representation of the given collection of objects. * * @param objects The {@link Iterable} that will be used to iterate over the objects. * @return A string of the format "[a, b, ...]". */ public static String toString(Iterable<?> objects) { StringBuilder str = new StringBuilder(); str.append("["); for (Object o : objects) { str.append(o).append(", "); } if (str.length() > 1) { str.setLength(str.length() - 2); } str.append("]"); return str.toString(); }
/** nicely formatted information */ public String getInfo() { StringBuilder buf = new StringBuilder(200); buf.setLength(0); buf.append(getFullName()); Format.tab(buf, 30, true); buf.append(getUnitsString()); Format.tab(buf, 60, true); buf.append(hasMissingData()); Format.tab(buf, 66, true); buf.append(getDescription()); return buf.toString(); }
public static String unwebMessageTextPoint(String text) { text = Utils.replace(text, "<br/>", "\n"); text = Utils.replace(text, "<br />", "\n"); text = Utils.replace(text, "<b>", "*"); text = Utils.replace(text, "</b>", "*"); text = Utils.replace(text, "<p>", ""); text = Utils.replace(text, "</p>", "\n"); text = Utils.replace(text, "<x>", ""); text = Utils.replace(text, "</x>", ""); text = Utils.replace(text, ">", ">"); text = Utils.replace(text, "<", "<"); text = Utils.replace(text, "«", "«"); text = Utils.replace(text, """, "\""); text = Utils.replace(text, "©", "©"); text = Utils.replace(text, "»", "»"); text = Utils.replace(text, "—", "-"); text = Utils.replace(text, " ", " "); text = Utils.replace(text, "<div class=\"text-content\">", ""); text = Utils.replace(text, "<div class=\"text\">", ""); text = Utils.replace(text, "</div>", ""); text = Utils.replace(text, " \n", "\n"); while (text.startsWith("\n") || text.startsWith(" ")) { text = text.substring(1); } String[] texts = StringSplitter.split(text, "\n"); StringBuilder sb = new StringBuilder(); for (String s : texts) { sb.append(s.trim()); // trim all sb.append("\n"); } while (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\n') sb.setLength(sb.length() - 1); // remove last \n String beforeYoutube = sb.toString(); int ix = 0; while (ix != -1) { ix = beforeYoutube.indexOf(HTTPS_IMG_YOUTUBE_COM_VI, ix); if (ix >= 0) { ix += HTTPS_IMG_YOUTUBE_COM_VI.length(); int ix2 = beforeYoutube.indexOf("/", ix); String key = beforeYoutube.substring(ix, ix2); ix2 = beforeYoutube.indexOf(" ", ix); if (ix2 == -1) ix2 = beforeYoutube.length(); beforeYoutube = beforeYoutube.substring(0, ix2) + " https://www.youtube.com/watch?v=" + key + beforeYoutube.substring(ix2); ix = ix2; } } return beforeYoutube; }
/** * This will convert the Map to a string representation. * * @param pmapData <code>Map</code> PI data to convert * @return a string representation of the Map as appropriate for a PI */ private static final String toString(Map<String, String> pmapData) { StringBuilder stringData = new StringBuilder(); for (Map.Entry<String, String> me : pmapData.entrySet()) { stringData.append(me.getKey()).append("=\"").append(me.getValue()).append("\" "); } // Remove last space, if we did any appending if (stringData.length() > 0) { stringData.setLength(stringData.length() - 1); } return stringData.toString(); }