Example usage for java.util Formatter Formatter

List of usage examples for java.util Formatter Formatter

Introduction

In this page you can find the example usage for java.util Formatter Formatter.

Prototype

public Formatter(OutputStream os) 

Source Link

Document

Constructs a new formatter with the specified output stream.

Usage

From source file:edu.uga.cs.fluxbuster.analytics.ClusterSimilarityCalculator.java

/**
 * Calculate ip-based cluster similarities between all of the clusters generated
 * during the runs on the two supplied dates.
 * //  w w  w.j  a v a2  s.  c  o m
 * @param adate the date of the first clustering run
 * @param bdate the date of the second clustering run
 * @return the list of ip-based cluster similarities
 * @throws IOException if the similarities could not be calculated
 */
public List<ClusterSimilarity> calculateIpSimilarities(Date adate, Date bdate) throws IOException {
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
    String adatestr = df.format(adate);
    String bdatestr = df.format(bdate);

    String query = properties.getProperty(IPKEY);
    StringBuffer querybuf = new StringBuffer();
    Formatter formatter = new Formatter(querybuf);
    formatter.format(query, adatestr, adatestr, bdatestr);
    query = querybuf.toString();
    formatter.close();
    return this.executeSimilarityQuery(query, adate, bdate);
}

From source file:com.itemanalysis.psychometrics.scaling.PercentileRank.java

@Override
public String toString() {
    if (freqTable.getUniqueCount() == 0 || freqTable.getSumFreq() == 0) {
        return "Percentile ranks not computed.";
    }/*  w  ww  . j a v a2  s  . c  om*/
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    String f1 = "%10.4f";
    String f2 = "%10s";

    //        double[][] prank = this.evaluate();
    this.createLookupTable();

    //add header
    f.format("%28s", "SCORE TABLE");
    f.format("%n");
    f.format("%45s", "=============================================");
    f.format("%n");
    f.format(f2, "Original");
    f.format("%5s", "");
    f.format(f2, "Percentile");
    f.format("%n");

    f.format(f2, "Value");
    f.format("%5s", "");
    f.format(f2, "Rank");
    f.format("%n");
    f.format("%45s", "---------------------------------------------");
    f.format("%n");

    Iterator<Integer> iter = prankTable.keySet().iterator();
    Integer key = 1;
    while (iter.hasNext()) {
        key = iter.next();
        f1 = "%10." + precision + "f";

        f.format(f2, key);
        f.format("%5s", "");
        f.format(f1, prankTable.get(key));
        f.format("%5s", "");
        f.format("%n");
    }
    f.format("%45s", "=============================================");
    f.format("%n");
    return f.toString();
}

From source file:ca.nines.ise.cmd.Wikify.java

/**
 * Turn the list of entity names into a wiki table.
 *
 * @param out//from  www . j  av a  2  s . c o m
 * @throws IOException
 */
private void wikifyCodepoints(PrintStream out) throws IOException {
    CodePointTable tbl = CodePointTable.defaultCodePointTable();
    Formatter fmt = new Formatter(out);
    fmt.format("|| Name || Char || Decimal || Hex || Code Point || Description ||\n");
    for (String name : tbl.getCodePoints()) {
        CodePoint cp = tbl.getCodePoint(name);
        fmt.format("|| %s || %s || %s || %s || %s || %s ||\n", cp.getName(), cp.getValue(), cp.dec(), cp.hex(),
                cp.unicodePoint(), cp.description().toLowerCase());
    }
    out.println();
}

From source file:com.itemanalysis.psychometrics.cfa.AbstractConfirmatoryFactorAnalysisEstimator.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    double[] fl = model.getFactorLoading();
    double[] er = model.getErrorVariance();

    for (int i = 0; i < nItems; i++) {
        f.format("% .4f", fl[i]);
        f.format("%5s", "");
        f.format("% .4f", er[i]);
        f.format("%n");
    }//  ww w  .  j a  va2  s.c  om

    f.format("%10s", "McDonald's Omega = ");
    f.format("%8.4f", mcdonaldOmega());
    f.format("%n");
    f.format("%10s", "GFI = ");
    f.format("%8.4f", gfi());
    f.format("%n");
    f.format("%10s", "AGFI = ");
    f.format("%8.4f", agfi());
    f.format("%n");
    f.format("%10s", "RMSEA = ");
    f.format("%8.4f", rmsea());
    f.format("%n");
    f.format("%10s", "RMSR = ");
    f.format("%8.4f", Math.sqrt(meanSquaredResidual()));
    f.format("%n");
    f.format("%10s", "BIC = ");
    f.format("%8.4f", Math.sqrt(bic()));
    f.format("%n");
    f.format("%10s", "X^2 = ");
    f.format("%8.4f", chisquare());
    f.format("%n");
    f.format("%10s", "df = ");
    f.format("%8.4f", degreesOfFreedom());
    f.format("%n");
    f.format("%10s", "p = ");
    f.format("%8.4f", pvalue());
    f.format("%n");
    return f.toString();
}

From source file:com.itemanalysis.jmetrik.stats.descriptives.DescriptiveAnalysis.java

public void publishHeader() throws IllegalArgumentException {
    StringBuilder header = new StringBuilder();
    Formatter f = new Formatter(header);
    String s1 = String.format("%1$tB %1$te, %1$tY  %tT", Calendar.getInstance());
    int len = 21 + Double.valueOf(Math.floor(Double.valueOf(s1.length()).doubleValue() / 2.0)).intValue();
    String dString = "";
    try {//from  w ww . j a  va  2 s .co m
        dString = command.getDataString();
    } catch (IllegalArgumentException ex) {
        throw new IllegalArgumentException(ex);
    }
    int len2 = 21 + Double.valueOf(Math.floor(Double.valueOf(dString.length()).doubleValue() / 2.0)).intValue();

    f.format("%31s", "DESCRIPTIVE STATISTICS");
    f.format("%n");
    f.format("%" + len2 + "s", dString);
    f.format("%n");
    f.format("%" + len + "s", s1);
    f.format("%n");
    f.format("%n");
    publish(f.toString());
}

From source file:com.google.samples.apps.iosched.util.UIUtils.java

/**
 * Format and return the given time interval using {@link Config#CONFERENCE_TIMEZONE} (unless
 * local time was explicitly requested by the user).
 *///from   w w w  . ja  v a 2  s.c  o  m
public static String formatIntervalTimeString(long intervalStart, long intervalEnd, StringBuilder recycle,
        Context context) {
    if (recycle == null) {
        recycle = new StringBuilder();
    } else {
        recycle.setLength(0);
    }
    Formatter formatter = new Formatter(recycle);
    return DateUtils.formatDateRange(context, formatter, intervalStart, intervalEnd, TIME_FLAGS,
            SettingsUtils.getDisplayTimeZone(context).getID()).toString();
}

From source file:edu.uga.cs.fluxbuster.features.FeatureCalculator.java

/**
 * Calculates the cluster novelty feature for each cluster generated
 * on a specific run date.//from ww  w .j  a v a 2 s.co m
 *
 * @param log_date the run date
 * @param window the number of days previous to use in feature calculation
 * @return a table of values where the keys are cluster ids and the values 
 *       are the feature values
 * @throws SQLException if there is an error calculating the feature values
 */
public Map<Integer, Double> calculateNoveltyFeature(Date log_date, int window) throws SQLException {
    HashMap<Integer, Double> retval = new HashMap<Integer, Double>();
    ArrayList<Date> prevDates = getPrevDates(log_date, window);

    if (prevDates.size() > 0) {
        StringBuffer querybuf = new StringBuffer();
        Formatter formatter = new Formatter(querybuf);
        String curdatestr = df.format(log_date);
        formatter.format(properties.getProperty(NOVELTY_QUERY1_1KEY), curdatestr, curdatestr, curdatestr,
                curdatestr);
        for (Date prevDate : prevDates) {
            formatter.format(" " + properties.getProperty(NOVELTY_QUERY1_2KEY) + " ", df.format(prevDate));
        }
        formatter.format(properties.getProperty(NOVELTY_QUERY1_3KEY), curdatestr, curdatestr);

        ResultSet rs2 = null;
        Hashtable<Integer, Hashtable<String, Long>> new_resolved_ips = new Hashtable<Integer, Hashtable<String, Long>>();
        try {
            rs2 = dbi.executeQueryWithResult(querybuf.toString());
            while (rs2.next()) {
                int cluster_id = rs2.getInt(2);
                if (!new_resolved_ips.containsKey(cluster_id)) {
                    new_resolved_ips.put(cluster_id, new Hashtable<String, Long>());
                }
                String secondLevelDomainName = rs2.getString(1);
                long newips = rs2.getLong(3);
                Hashtable<String, Long> clustertable = new_resolved_ips.get(cluster_id);
                clustertable.put(secondLevelDomainName, newips);
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error(e);
            }
        } finally {
            if (rs2 != null && !rs2.isClosed()) {
                rs2.close();
            }
            formatter.close();
        }

        Hashtable<String, List<Integer>> numDays = new Hashtable<String, List<Integer>>();
        for (Date prevDate : prevDates) {
            String prevDateStr = df.format(prevDate);
            querybuf = new StringBuffer();
            formatter = new Formatter(querybuf);
            formatter.format(properties.getProperty(NOVELTY_QUERY2KEY), curdatestr, prevDateStr, curdatestr,
                    prevDateStr);
            ResultSet rs3 = null;
            try {
                rs3 = dbi.executeQueryWithResult(querybuf.toString());
                while (rs3.next()) {
                    String sldn = rs3.getString(1);
                    if (!numDays.containsKey(sldn)) {
                        numDays.put(sldn, new ArrayList<Integer>());
                    }
                    Date pd = rs3.getDate(2);
                    DateTime start = new DateTime(pd.getTime());
                    DateTime end = new DateTime(log_date.getTime());
                    Days d = Days.daysBetween(start, end);
                    int diffDays = d.getDays();
                    numDays.get(sldn).add(diffDays);
                }
            } catch (Exception e) {
                if (log.isErrorEnabled()) {
                    log.error(e);
                }
            } finally {
                if (rs3 != null && !rs3.isClosed()) {
                    rs3.close();
                }
                formatter.close();
            }
        }

        Hashtable<Integer, List<Float>> clusterValues = new Hashtable<Integer, List<Float>>();
        for (int clusterID : new_resolved_ips.keySet()) {
            clusterValues.put(clusterID, new ArrayList<Float>());

            Hashtable<String, Long> sldnValues = new_resolved_ips.get(clusterID);
            for (String sldn : sldnValues.keySet()) {
                if (numDays.keySet().contains(sldn)) {
                    long newIPCount = sldnValues.get(sldn);
                    float f = ((float) newIPCount) / Collections.max(numDays.get(sldn));
                    clusterValues.get(clusterID).add(f);

                }
            }
        }

        for (int clusterID : clusterValues.keySet()) {
            if (clusterValues.get(clusterID) == null) { //I dont think it is possible for this to ever be true
                retval.put(clusterID, null);
            } else {
                double sum = 0;
                for (double d : clusterValues.get(clusterID)) {
                    sum += d;
                }
                double val = 0;
                if (clusterValues.get(clusterID).size() > 0) {
                    val = sum / clusterValues.get(clusterID).size();
                }
                retval.put(clusterID, val);
            }
        }
    }
    return retval;
}

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

/** Called when the activity is first created. */
@Override/* w ww .j ava2 s  .  c o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    fixScreenOrientation();

    DoCommand dc = new DoCommand(getApplication());

    Log.i("SUTAgentAndroid", dc.prgVersion);
    dc.FixDataLocalPermissions();

    // Get configuration settings from "ini" file
    File dir = getFilesDir();
    File iniFile = new File(dir, "SUTAgent.ini");
    String sIniFile = iniFile.getAbsolutePath();

    String lc = dc.GetIniData("General", "LogCommands", sIniFile);
    if (lc != "" && Integer.parseInt(lc) == 1) {
        SUTAgentAndroid.LogCommands = true;
    }
    SUTAgentAndroid.RegSvrIPAddr = dc.GetIniData("Registration Server", "IPAddr", sIniFile);
    SUTAgentAndroid.RegSvrIPPort = dc.GetIniData("Registration Server", "PORT", sIniFile);
    SUTAgentAndroid.HardwareID = dc.GetIniData("Registration Server", "HARDWARE", sIniFile);
    SUTAgentAndroid.Pool = dc.GetIniData("Registration Server", "POOL", sIniFile);
    SUTAgentAndroid.sTestRoot = dc.GetIniData("Device", "TestRoot", sIniFile);
    SUTAgentAndroid.Abi = android.os.Build.CPU_ABI;
    log(dc, "onCreate");

    dc.SetTestRoot(SUTAgentAndroid.sTestRoot);

    Log.i("SUTAgentAndroid", "Test Root: " + SUTAgentAndroid.sTestRoot);

    tv = (TextView) this.findViewById(R.id.Textview01);

    if (getLocalIpAddress() == null)
        setUpNetwork(sIniFile);

    String macAddress = "Unknown";
    if (android.os.Build.VERSION.SDK_INT > 8) {
        try {
            NetworkInterface iface = NetworkInterface
                    .getByInetAddress(InetAddress.getAllByName(getLocalIpAddress())[0]);
            if (iface != null) {
                byte[] mac = iface.getHardwareAddress();
                if (mac != null) {
                    StringBuilder sb = new StringBuilder();
                    Formatter f = new Formatter(sb);
                    for (int i = 0; i < mac.length; i++) {
                        f.format("%02x%s", mac[i], (i < mac.length - 1) ? ":" : "");
                    }
                    macAddress = sUniqueID = sb.toString();
                }
            }
        } catch (UnknownHostException ex) {
        } catch (SocketException ex) {
        }
    } else {
        // Fall back to getting info from wifiman on older versions of Android,
        // which don't support the NetworkInterface interface
        WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifiMan != null) {
            WifiInfo wifi = wifiMan.getConnectionInfo();
            if (wifi != null)
                macAddress = wifi.getMacAddress();
            if (macAddress != null)
                sUniqueID = macAddress;
        }
    }

    if (sUniqueID == null) {
        BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
        if ((ba != null) && (ba.isEnabled() != true)) {
            ba.enable();
            while (ba.getState() != BluetoothAdapter.STATE_ON) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            sUniqueID = ba.getAddress();

            ba.disable();
            while (ba.getState() != BluetoothAdapter.STATE_OFF) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (ba != null) {
                sUniqueID = ba.getAddress();
                sUniqueID.toLowerCase();
            }
        }
    }

    if (sUniqueID == null) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (mTelephonyMgr != null) {
            sUniqueID = mTelephonyMgr.getDeviceId();
            if (sUniqueID == null) {
                sUniqueID = "0011223344556677";
            }
        }
    }

    String hwid = getHWID(this);

    sLocalIPAddr = getLocalIpAddress();
    Toast.makeText(getApplication().getApplicationContext(), "SUTAgent [" + sLocalIPAddr + "] ...",
            Toast.LENGTH_LONG).show();

    String sConfig = dc.prgVersion + lineSep;
    sConfig += "Test Root: " + sTestRoot + lineSep;
    sConfig += "Unique ID: " + sUniqueID + lineSep;
    sConfig += "HWID: " + hwid + lineSep;
    sConfig += "ABI: " + Abi + lineSep;
    sConfig += "OS Info" + lineSep;
    sConfig += "\t" + dc.GetOSInfo() + lineSep;
    sConfig += "Screen Info" + lineSep;
    int[] xy = dc.GetScreenXY();
    sConfig += "\t Width: " + xy[0] + lineSep;
    sConfig += "\t Height: " + xy[1] + lineSep;
    sConfig += "Memory Info" + lineSep;
    sConfig += "\t" + dc.GetMemoryInfo() + lineSep;
    sConfig += "Network Info" + lineSep;
    sConfig += "\tMac Address: " + macAddress + lineSep;
    sConfig += "\tIP Address: " + sLocalIPAddr + lineSep;

    displayStatus(sConfig);

    sRegString = "NAME=" + sUniqueID;
    sRegString += "&IPADDR=" + sLocalIPAddr;
    sRegString += "&CMDPORT=" + 20701;
    sRegString += "&DATAPORT=" + 20700;
    sRegString += "&OS=Android-" + dc.GetOSInfo();
    sRegString += "&SCRNWIDTH=" + xy[0];
    sRegString += "&SCRNHEIGHT=" + xy[1];
    sRegString += "&BPP=8";
    sRegString += "&MEMORY=" + dc.GetMemoryConfig();
    sRegString += "&HARDWARE=" + HardwareID;
    sRegString += "&POOL=" + Pool;
    sRegString += "&ABI=" + Abi;

    String sTemp = Uri.encode(sRegString, "=&");
    sRegString = "register " + sTemp;

    pruneCommandLog(dc.GetSystemTime(), dc.GetTestRoot());

    if (!bNetworkingStarted) {
        Thread thread = new Thread(null, doStartService, "StartServiceBkgnd");
        thread.start();
        bNetworkingStarted = true;

        Thread thread2 = new Thread(null, doRegisterDevice, "RegisterDeviceBkgnd");
        thread2.start();
    }

    monitorBatteryState();

    // If we are returning from an update let'em know we're back
    Thread thread3 = new Thread(null, doUpdateCallback, "UpdateCallbackBkgnd");
    thread3.start();

    final Button goButton = (Button) findViewById(R.id.Button01);
    goButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
}

From source file:com.itemanalysis.psychometrics.rasch.RatingScaleItem.java

public String printItem() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);

    f.format("%10s", this.getName().toString());
    f.format("%5s", "");
    f.format("%8.2f", getDifficulty());
    f.format("%5s", "");

    for (int i = 0; i < thresholds.length; i++) {
        f.format("%8.2f", thresholds[i]);
        f.format("%5s", "");
    }/*from   w  w w  .jav  a  2s  . co m*/

    return f.toString();

}

From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.logger.impl.DatabaseLoggerImpl.java

private static void writeDotNode(OutputStream gvoss, OutputStream gvos, Node node, String indent)
        throws IllegalFormatException, FormatterClosedException, IOException {
    StringBuilder sbSimple = new StringBuilder();
    StringBuilder sbFull = new StringBuilder();
    Formatter formatterSimple = null;
    Formatter formatterFull = null;

    try {/*from  w  ww.j  a va  2 s .  com*/
        formatterSimple = new Formatter(sbSimple);
        formatterFull = new Formatter(sbFull);

        Sender sender = node.getSender();
        String senderIP = (sender == null) ? "" : "" + sender.getIp().getHostAddress() + ":" + sender.getPort();
        String senderColor = (sender == null) ? colorFullNotOk : colorFullOk;

        Long nodeId = node.getId();
        String nodeIP = node.getMainIp().getHostAddress().toString();

        PositionUpdateMsg nodePU = node.getPositionUpdateMsg();
        PositionUpdate nodePUMsg = (nodePU == null) ? null : nodePU.getPositionUpdateMsg();

        String nodeSimpleColor = (nodePUMsg == null) ? colorSimpleNotOk : colorSimpleOk;
        String nodeColor = (nodePUMsg == null) ? colorFullNotOk : colorFullOk;
        String nodeShape = node.getClusterNodes().isEmpty() ? shapeNormal : shapeClusterLeader;

        String nodeName = getNodeNameOrIp(node);

        String url = (sender == null) ? "" : ", URL=\"http://" + sender.getIp().getHostAddress() + "\"";
        formatterSimple.format(dotNodeTemplateSimple, indent, nodeId, nodeShape, nodeSimpleColor, nodeName,
                url);
        if ((nodePUMsg == null) || (nodePUMsg.getPositionUpdateNodeIdType() == 4)
                || (nodePUMsg.getPositionUpdateNodeIdType() == 6)) {
            /* use IP variant */
            formatterFull.format(dotNodeTemplateFullIp, indent, nodeId, nodeColor, nodeName, senderColor,
                    senderIP, url);
        } else {
            /* use named variant */
            formatterFull.format(dotNodeTemplateFull, indent, nodeId, nodeColor, nodeName, colorFullOk, nodeIP,
                    senderColor, senderIP, url);
        }

        /* now write graph */
        ClusterLeaderMsg nodeCL = node.getClusterLeaderMsg();
        if (nodeCL != null) {
            formatterSimple.format("%s%s -> %s%n", indent, nodeId, nodeCL.getClusterLeaderNode().getId());
            formatterFull.format("%s%s -> %s%n", indent, nodeId, nodeCL.getClusterLeaderNode().getId());
        }

        gvoss.write(sbSimple.toString().getBytes(Constants.CHARSET_DEFAULT));
        gvos.write(sbFull.toString().getBytes(Constants.CHARSET_DEFAULT));
    } finally {
        if (formatterSimple != null) {
            formatterSimple.close();
            formatterSimple = null;
        }
        if (formatterFull != null) {
            formatterFull.close();
            formatterFull = null;
        }

    }
}