// Communications public void updateStatus(InputStream in) throws IOException { DataInputStream din = new DataInputStream(in); if (builder.length() != 0) { builder.delete(0, builder.length()); } eventTotal.setText(form.format(new Long(din.readLong()))); dataTotal.setText(Util.convertBytes(builder, din.readLong(), true).toString()); builder.delete(0, builder.length()); dataRate.setText(Util.convertBytesRate(builder, din.readDouble(), true).toString()); eventRate.setText(form.format(new Integer((int) din.readDouble())) + "e/s"); }
private boolean assignPrimaryKeyInternal(Object entity, DatabaseEntry key) throws DatabaseException, RefreshException { /* * The keyFieldFormat is the format of a simple integer field. For a * composite key class it is the contained integer field. By writing * the Long sequence value using that format, the output data can then * be read to construct the actual key instance, whether it is a simple * or composite key class, and assign it to the primary key field in * the entity object. */ if (entityFormat.isPriKeyNullOrZero(entity, rawAccess)) { Long value = sequence.get(null, 1); RecordOutput output = new RecordOutput(catalog, rawAccess); keyFieldFormat.writeObject(value, output, rawAccess); TupleBase.outputToEntry(output, key); EntityInput input = new RecordInput( catalog, rawAccess, null, 0, key.getData(), key.getOffset(), key.getSize()); entityFormat.getReader().readPriKey(entity, input, rawAccess); return true; } else { return false; } }
public String createTable() { Element root = new Element("table"); root.setAttribute("border", "0"); Document doc = new Document(root); Element thead = new Element("thead"); Element th = new Element("th"); th.addContent("A header"); th.setAttribute("class", "aka_header_border"); thead.addContent(th); Element th2 = new Element("th"); th2.addContent("Another header"); th2.setAttribute("class", "aka_header_border"); thead.addContent(th2); root.addContent(thead); Element tr1 = new Element("tr"); Element td1 = new Element("td"); td1.setAttribute("valign", "top"); td1.setAttribute("class", "cellBorders"); td1.setText("cell contents"); tr1.addContent(td1); root.addContent(tr1); XMLOutputter outp = new XMLOutputter(); Format format = Format.getPrettyFormat(); format.setOmitDeclaration(true); outp.setFormat(format); Writer writer = new StringWriter(); try { outp.output(doc, writer); } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } return writer.toString(); }
/** * Constructor. * * <p>A pleasant side-effect of constructing a Text() is that consecutive (redundant) colour * escape sequences are collapsed down to just the last colour. * * @param text the text with embedded colour escape sequences. */ public Text(String text) { // By default, text is white. Format format = new Format(Colour.white, 0); for (int i = 0; i < text.length(); ++i) { char c = text.charAt(i); if (c == Colour.ESCAPE_CHAR) { ++i; // Guard against the pathological case of a chat line ending in // Colour.ESCAPE_CHAR. if (i < text.length()) { char code = text.charAt(i); if (Colour.isColour(code)) { format.setColour(Colour.getByCode(code)); // Setting the colour disables any style attributes. format.setStyles(0); } // Note: different from Format.isAttribute() else if (isAttribute(code)) { format.applyStyle(code); } // else: silently delete format codes we don't understand. // At the time of writing, no such codes exist. } } else { // An ordinary, non-colour-escape character. _unformatted.append(c); _colourStyles.append(format.getColourStyle()); } } // for } // Text
/** * Returns the format for the given entity and validates it, throwing an exception if it is * invalid for this binding. */ private Format getValidFormat(Object entity) throws RefreshException { /* A null entity is not allowed. */ if (entity == null) { throw new IllegalArgumentException("An entity may not be null"); } /* * Get the format. getFormat throws IllegalArgumentException if the * class is not persistent. */ Format format; if (rawAccess) { if (!(entity instanceof RawObject)) { throw new IllegalArgumentException("Entity must be a RawObject"); } format = (Format) ((RawObject) entity).getType(); } else { format = catalog.getFormat(entity.getClass(), true /*checkEntitySubclassIndexes*/); } /* Check that the entity class/subclass is valid for this binding. */ if (format.getEntityFormat() != entityFormat) { throw new IllegalArgumentException( "The entity class (" + format.getClassName() + ") must be this entity class or a subclass of it: " + entityFormat.getClassName()); } return format; }
// See comment in createericlist regarding HandleViewParams private /*synchronized*/ String HandleViewParams( String tempString, LinkedList tempList, StringTokenizer st) throws VisualizerLoadException { while (tempString.toUpperCase().startsWith("VIEW")) { StringTokenizer t = new StringTokenizer(tempString, " \t"); String s1 = t.nextToken().toUpperCase(); String s2 = t.nextToken().toUpperCase(); String s3 = t.nextToken(); // HERE PROCESS URL's AS YOU DID QUESTIONS if (s2.compareTo("ALGO") == 0) { add_a_pseudocode_URL(s3); // System.out.println("Adding to urls: "+Snaps+":"+s3); // urlList.append(Snaps+1 +":"+s3); } else if (s2.compareTo("DOCS") == 0) { add_a_documentation_URL(s3); // System.out.println("Adding to urls: "+Snaps+":"+s3); // if (debug) System.out.println("Adding to urlList: "+Snaps+1+":"+s3); // urlList.append(Snaps+1 +":"+s3); } else if (s2.compareTo("SCALE") == 0) { GKS.scale(Format.atof(s3.toUpperCase()), tempList, this); } else if (s2.compareTo("WINDOWS") == 0) { GKS.windows(Format.atoi(s3.toUpperCase()), tempList, this); } else if (s2.compareTo("JUMP") == 0) { GKS.jump(Format.atoi(s3.toUpperCase()), tempList, this); } else throw (new VisualizerLoadException(s2 + " is invalid VIEW parameter")); tempString = st.nextToken(); } // if (urlList.size() == 0) // urlList.append("**"); return (tempString); }
// Responsible for loading the number of lines per node // Receives a line delimited tokenizer. It will only process one line of // that tokenizer. It must read that line, create a space/tab delimited // tokenizer from it, grab the number of lines per node from that tokenizer. // Structures that can contain additional information following the number // of lines per node (such as trees) should then override this generic // loadLinesPerNodeInfo with their own version of the method which will call // on the super version to get the actual lines per node and add additional // code to process the other information public void loadLinesPerNodeInfo(StringTokenizer st, LinkedList llist, draw d) throws VisualizerLoadException { String tempString, tempString2; if (st.hasMoreTokens()) tempString = st.nextToken(); else throw (new VisualizerLoadException("Expected lines per node - found end of string")); StringTokenizer t = new StringTokenizer(tempString, " \t"); if (t.hasMoreTokens()) tempString2 = t.nextToken(); else throw (new VisualizerLoadException("Expected lines per node - found " + tempString)); linespernode = Format.atoi(tempString2); xspacing = 1.5; yspacing = 1.5; if (t.hasMoreTokens()) tempString2 = t.nextToken(); else return; xspacing = Format.atof(tempString2); if (t.hasMoreTokens()) tempString2 = t.nextToken(); else return; yspacing = Format.atof(tempString2); }
public EvolveStats evolve(EvolveConfig config) throws DatabaseException { checkOpen(); List<Format> toEvolve = new ArrayList<Format>(); Set<String> configToEvolve = config.getClassesToEvolve(); if (configToEvolve.isEmpty()) { catalog.getEntityFormats(toEvolve); } else { for (String name : configToEvolve) { Format format = catalog.getFormat(name); if (format == null) { throw new IllegalArgumentException("Class to evolve is not persistent: " + name); } if (!format.isEntity()) { throw new IllegalArgumentException("Class to evolve is not an entity class: " + name); } toEvolve.add(format); } } EvolveEvent event = EvolveInternal.newEvent(); for (Format format : toEvolve) { if (format.getEvolveNeeded()) { evolveIndex(format, event, config.getEvolveListener()); format.setEvolveNeeded(false); catalog.flush(); } } return event.getStats(); }
@Override boolean evolve(Format newFormatParam, Evolver evolver) { if (!(newFormatParam instanceof ProxiedFormat)) { evolver.addEvolveError( this, newFormatParam, null, "A proxied class may not be changed to a different type"); return false; } ProxiedFormat newFormat = (ProxiedFormat) newFormatParam; if (!evolver.evolveFormat(proxyFormat)) { return false; } Format newProxyFormat = proxyFormat.getLatestVersion(); if (!newProxyFormat.getClassName().equals(newFormat.getProxyClassName())) { evolver.addEvolveError( this, newFormat, null, "The proxy class for this type has been changed from: " + newProxyFormat.getClassName() + " to: " + newFormat.getProxyClassName()); return false; } if (newProxyFormat != proxyFormat) { evolver.useEvolvedFormat(this, this, newFormat); } else { evolver.useOldFormat(this, newFormat); } return true; }
protected Format outputCellStart(Field field) { Format format = field.getFormat(); Rectangle bounds = field.getBounds(); String align = null; switch (format.getAlign()) { case Format.ALIGN_LEFT: align = "left"; break; case Format.ALIGN_CENTER: align = "center"; break; case Format.ALIGN_RIGHT: align = "right"; break; } out.print("<div style=\"position:absolute;width:" + (int) bounds.width + "pt;"); out.print("height:" + (int) field.getOutputHeight() + "pt;text-align:" + align + ";"); out.print("left:" + (int) bounds.x + "pt;top:" + (int) bounds.y + "pt;"); if (!format.isWrap()) out.print("white-space:nowrap;"); out.println("\">"); return format; }
@Override public EntityMetadata getEntityMetadata(String className) { EntityMetadata metadata = null; Format format = catalog.getFormat(className); if (format != null && format.isCurrentVersion()) { metadata = format.getEntityMetadata(); } return metadata; }
/** {@inheritDoc} */ public String getLabel(JaretDate date, Format format) { if (format.equals(Format.SHORT)) { return Integer.toString(date.getMonth()) + "."; } else if (format.equals(Format.MEDIUM)) { return date.getShortMonthString() + " " + date.getYear(); } else { return date.getMonthString() + " " + date.getYear(); } }
@Override public int readData( int track, long positionUs, MediaFormatHolder formatHolder, SampleHolder sampleHolder) { Assertions.checkState(state == STATE_ENABLED); downstreamPositionUs = positionUs; if (pendingDiscontinuity || isPendingReset()) { return NOTHING_READ; } boolean haveSamples = !sampleQueue.isEmpty(); BaseMediaChunk currentChunk = mediaChunks.getFirst(); while (haveSamples && mediaChunks.size() > 1 && mediaChunks.get(1).getFirstSampleIndex() <= sampleQueue.getReadIndex()) { mediaChunks.removeFirst(); currentChunk = mediaChunks.getFirst(); } Format format = currentChunk.format; if (!format.equals(downstreamFormat)) { notifyDownstreamFormatChanged(format, currentChunk.trigger, currentChunk.startTimeUs); } downstreamFormat = format; if (haveSamples || currentChunk.isMediaFormatFinal) { MediaFormat mediaFormat = currentChunk.getMediaFormat(); if (!mediaFormat.equals(downstreamMediaFormat)) { formatHolder.format = mediaFormat; formatHolder.drmInitData = currentChunk.getDrmInitData(); downstreamMediaFormat = mediaFormat; return FORMAT_READ; } // If mediaFormat and downstreamMediaFormat are equal but different objects then the equality // check above will have been expensive, comparing the fields in each format. We update // downstreamMediaFormat here so that referential equality can be cheaply established during // subsequent calls. downstreamMediaFormat = mediaFormat; } if (!haveSamples) { if (loadingFinished) { return END_OF_STREAM; } return NOTHING_READ; } if (sampleQueue.getSample(sampleHolder)) { boolean decodeOnly = sampleHolder.timeUs < lastSeekPositionUs; sampleHolder.flags |= decodeOnly ? C.SAMPLE_FLAG_DECODE_ONLY : 0; onSampleRead(currentChunk, sampleHolder); return SAMPLE_READ; } return NOTHING_READ; }
/** * Called when there was a change in one of the pin values. The event contains the changed value * in a string representation and a boolean which is true if the user pressed the 'ok' button and * false if the user pressed the 'cancel' button. */ public void pinValueChanged(PinValueEvent e) { pinsTable.setEnabled(true); if (e.getIsOk()) { valuesStr[pinsTable.getSelectedRow()] = e.getValueStr(); partPins[pinsTable.getSelectedRow()].value = Format.translateValueToShort(e.getValueStr(), dataFormat); } notifyListeners( pinsTable.getSelectedRow(), Format.translateValueToShort(e.getValueStr(), dataFormat)); }
/** * Writes the formatId and object, and returns the bytes. * * <p>This is a special case of EntityOutput.writeObject for a top level entity. Special * treatments are: - The entity may not be null. - The entity is not checked for existence in the * visited object set; entities cannot be referenced by another entity. */ static void writeEntity( Format format, Catalog catalog, Object entity, DatabaseEntry data, boolean rawAccess) throws RefreshException { RecordOutput output = new RecordOutput(catalog, rawAccess); output.registerEntity(entity); output.writePackedInt(format.getId()); format.writeObject(entity, output, rawAccess); TupleBase.outputToEntry(output, data); }
/** * Creates a WriterCharAppender with: * * <ul> * <li>a maximum limit of characters to append * <li>the default value to return when no characters have been accumulated. * <li>the basic {@link Format} specification for handling newlines * </ul> * * The padding character is defaulted to a whitespace character ' '. * * @param maxLength maximum limit of characters to append * @param emptyValue default value to return when no characters have been accumulated * @param format output format specification used for newline handling */ public WriterCharAppender(int maxLength, String emptyValue, Format format) { super(maxLength == -1 ? 8192 : maxLength, emptyValue); char[] lineSeparator = format.getLineSeparator(); this.lineSeparator1 = lineSeparator[0]; this.lineSeparator2 = lineSeparator.length > 1 ? lineSeparator[1] : '\0'; newLine = format.getNormalizedNewline(); }
@ExposedClassMethod(doc = BuiltinDocs.float___getformat___doc) public static String float___getformat__(PyType type, String typestr) { if ("double".equals(typestr)) { return double_format.format(); } else if ("float".equals(typestr)) { return float_format.format(); } else { throw Py.ValueError("__getformat__() argument 1 must be 'double' or 'float'"); } }
@Override void writeObject(Object o, EntityOutput output, boolean rawAccess) { if (rawAccess) { proxyFormat.writeObject(o, output, true); } else { PersistentProxy proxy = (PersistentProxy) proxyFormat.newInstance(null, false); proxy.initializeProxy(o); proxyFormat.writeObject(proxy, output, false); } }
@Override public ValidationResult validate(String value, Doc doc, Model model) { for (Format f : EnumSet.allOf(Format.class)) { if (f.toString().equalsIgnoreCase(value)) { return new PositiveValidationResult(f); } } return new NegativeValidationResult("Unknown/unsupported format: '" + value + "'"); }
public void printPoints() { for (int i = 0; i < npoint; i++) { SequencePoint sp = (SequencePoint) points.elementAt(i); Format.print(System.out, "%5d ", i); for (int j = 0; j < 3; j++) { Format.print(System.out, "%13.3f ", sp.coord[j]); } System.out.println(); } }
/** @see EntityInput#skipField */ public void skipField(Format declaredFormat) { if (declaredFormat != null && declaredFormat.isPrimitive()) { declaredFormat.skipContents(this); } else { int formatId = readPackedInt(); if (formatId > 0) { Format format = catalog.getFormat(formatId, true /*expectStored*/); format.skipContents(this); } } }
/** * Returns a String representation of the Object <code>value</code>. This invokes <code>format * </code> on the current <code>Format</code>. * * @throws ParseException if there is an error in the conversion * @param value Value to convert * @return String representation of value */ public String valueToString(Object value) throws ParseException { if (value == null) { return ""; } Format f = getFormat(); if (f == null) { return value.toString(); } return f.format(value); }
/** * Deal with formatting characters. * * <p>Parsing is as follows: - Treat all contiguous strings of formatting characters as one block. * (This method processes one block.) - Only a single instance of a particular format character * within a block is used to determine whether to turn on/off that type of formatting; other * instances simply print the character itself. - If the format is to be turned on, we use the * _first_ instance; if it is to be turned off, we use the _last_ instance (by appending the * format.) * * <p>Example: **string** turns into <b>*string*</b> */ private boolean parseFormatting() { if (!parseFormatting) { return false; } int endChar = nextChar; while ((endChar < text.length()) && isFormatChar(text.charAt(endChar))) { endChar += 1; } if ((endChar == nextChar) || !isWordBreak(endChar)) { return false; } // Keeps track of whether we've seen a character (in map if we've seen it) // and whether we should append a closing format token (if value in // map is TRUE). Linked hashmap for consistent ordering. LinkedHashMap<Character, Boolean> seenCharacters = new LinkedHashMap<Character, Boolean>(); for (int index = nextChar; index < endChar; ++index) { char ch = text.charAt(index); Character key = Character.valueOf(ch); if (seenCharacters.containsKey(key)) { // Already seen this character, just append an unmatched token, which // will print plaintext character addToken(new Format(ch, false)); } else { Format start = formatStart.get(key); if (start != null) { // Match the start token, and ask an end token to be appended start.setMatched(true); formatStart.remove(key); seenCharacters.put(key, Boolean.TRUE); } else { // Append start token start = new Format(ch, true); formatStart.put(key, start); addToken(start); seenCharacters.put(key, Boolean.FALSE); } } } // Append any necessary end tokens for (Character key : seenCharacters.keySet()) { if (seenCharacters.get(key) == Boolean.TRUE) { Format end = new Format(key.charValue(), false); end.setMatched(true); addToken(end); } } nextChar = endChar; return true; }
@Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.bold: { Format.toggleStyleSpan(this.editText, Typeface.BOLD); editText.setModified( true); // apparently doesnt get set automatically by DroidWriterEditText's TextWatcher return true; } case R.id.italic: { Format.toggleStyleSpan(this.editText, Typeface.ITALIC); editText.setModified(true); return true; } case R.id.underline: { Format.toggleCharacterStyle(this.editText, UnderlineSpan.class); editText.setModified(true); return true; } case R.id.strikethrough: { Format.toggleCharacterStyle(this.editText, StrikethroughSpan.class); editText.setModified(true); return true; } case R.id.menu_item_share: { int selectionStart = editText.getSelectionStart(); int selectionEnd = editText.getSelectionEnd(); if (selectionStart > selectionEnd) { int tmp = selectionEnd; selectionEnd = selectionStart; selectionStart = tmp; } CharSequence selectedText = editText.getText().subSequence(selectionStart, selectionEnd); Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra( Intent.EXTRA_TEXT, selectedText.toString() /*deep copy*/); // sharing spanned string does not work here sendIntent.setType("text/plain"); if (mShareActionProvider != null) mShareActionProvider.setShareIntent(sendIntent); return true; } } return false; }
/** * The Energy as a string, formatted to 3 decimal places with units. * * <p>As energy values can be very large, this function makes use of the kilo-, mega-, and giga- * prefixes * * @return string representation of the energy */ @Override public String toString() { if (joules >= 10000000000.0) { return Format.toThreeDecimalPlaces(joules / 1000000000.0) + " GJ"; } else if (joules >= 1000000.0) { return Format.toThreeDecimalPlaces(joules / 1000000.0) + " MJ"; } else if (joules >= 1000) { return Format.toThreeDecimalPlaces(joules / 1000) + " kJ"; } else { return Format.toThreeDecimalPlaces(joules) + " J"; } }
/** Sets the value at a specific row and column. */ public void setValueAt(Object value, int row, int col) { String data = ((String) value).trim(); try { valuesStr[row] = data; partPins[row].value = Format.translateValueToShort(data, dataFormat); notifyListeners((short) row, partPins[row].value); } catch (NumberFormatException nfe) { notifyErrorListeners("Illegal value"); valuesStr[row] = Format.translateValueToString(partPins[row].value, dataFormat); } repaint(); }
private void objectToKeyInternal(final Object entity, final DatabaseEntry key) throws RefreshException { /* * Write the primary key field as a special case since the output * format is for a key binding, not entity data. */ Format format = getValidFormat(entity); RecordOutput output = new RecordOutput(catalog, rawAccess); /* Write the primary key and return the bytes. */ format.writePriKey(entity, output, rawAccess); TupleBase.outputToEntry(output, key); }
public void solve1216(int kaseno) throws Exception { int r1 = iread(), r2 = iread(), h = iread(), p = iread(); double R1 = (double) r2; double R2 = ((double) ((r1 - r2) * p)) / h; R2 += r2; double H = (double) p; double ret = pii * (R1 * R1 + R2 * R2 + R1 * R2) * H; ret /= 3.; Format df = new DecimalFormat("0.0000000000"); String res = df.format(ret); out.write("Case " + kaseno + ": " + res + "\n"); }
/** * Set the default values for the non defined fields. * * @param model the model which has its default fields set. * @throws IllegalAccessException if the underlying fields are inaccessible * @throws Exception In case the field cannot be parsed */ private void setDefaultValuesForFields(final Map<String, Object> model) throws IllegalAccessException, Exception { // Set the default values, if defined for (int i = 1; i <= dataFields.size(); i++) { Field field = annotatedFields.get(i); field.setAccessible(true); DataField dataField = dataFields.get(i); Object modelField = model.get(field.getDeclaringClass().getName()); if (field.get(modelField) == null && !dataField.defaultValue().isEmpty()) { Format<?> format = FormatFactory.getFormat(field.getType(), getLocale(), dataField); Object value = format.parse(dataField.defaultValue()); field.set(modelField, value); } } }
private Format readOptionFormat(CliArguments arguments) { Format format = Format.AUTO; if (arguments.hasOption("format")) { format = Format.valueOf(arguments.option("format").toUpperCase()); } return format; }