bcds.tools
Class Utils

java.lang.Object
  extended by bcds.tools.Utils

public class Utils
extends java.lang.Object

This class is a collection of utility functions. All of them must be static


Method Summary
static
<T extends java.lang.Number>
double
average(java.util.Collection<T> c)
          Returns the average of the numbers in c.
static
<T extends java.lang.Number>
double[]
devStd(T[] A)
          Returns A 4-element array of doubles containing the standard deviation of the values in A as well as complementary information.
static
<T extends java.lang.Number>
double
freqTableAverage(FreqTable<T> tab)
          Returns the average of a numeric variable organized in a frequency table.
static java.lang.String getProp(java.lang.String key, java.lang.String list)
          Returns the value part of a given key in a comma-separated list of key=value pairs.
static void newBufferedSystemOut()
          Creates a new buffered output around System.out and then sets that as the new System.out.
static
<T> T
newFromString(java.lang.Class<T> cls, java.lang.String value)
          Returns a new instance of class cls, using the parameter value as the parameter to cls's constructor.
static
<K,E> java.util.Map<K,E>
newHashMap()
          Creates a new HashMap.
static SimplePair<java.lang.Integer,java.lang.Boolean> parseIntOrPrc(java.lang.String str)
          Parses an integer or an integer percentage from the given string and returns the integer and a boolean to signal if a percentage sign was found.
static
<T> void
printFreqTable(java.io.PrintStream out, FreqTable<T> tab, java.util.Set<T> keys, java.lang.String msg, boolean acc)
          Prints to out a frequency table.
static java.lang.String removePath(java.lang.String fname)
          Returns the last component of a path, assuming that the component separator is the forward slash (/).
static java.lang.String replaceExt(java.lang.String fname, java.lang.String ext)
          Replaces the "extension" of a file name.
static
<T> java.util.List<T>
select(java.util.Collection<T> c, int subgroup_size, java.util.Random rnd)
          Returns a subgroup taken from the elements in the collection c, consisting of exactly subgroup_size elements, which are randomly selected using rnd as the source of randomness.
static
<T> T
silentCast(java.lang.Object b)
          Returns the object b cast as an instance of type T, suppressing compilation warnings about unchecked casts.
static
<K,V extends java.lang.Comparable<? super V>>
java.util.List<K>
sortMap(java.util.Map<K,V> h, java.util.Comparator<K> cmp)
          Returns a list with the elements of the map h sorted according to the criterion established by the comparator cmp.
static
<K,V extends java.lang.Comparable<? super V>>
java.util.List<K>
sortMapByValues(java.util.Map<K,V> h, SortOrder order)
          Returns a list with the elements of the map h sorted, that is, the sorted map values.
static java.util.List<java.lang.String> split(java.lang.String line, java.lang.String delim_chars)
          Splits the string line using a set of characters given in delim_chars as component delimiter.
static java.util.List<java.lang.String> splitOnWS(java.lang.String line)
          Splits the string line using any whitespace as delimiter and returns the resulting list.
static java.lang.String timeStamp()
          Returns the current time with the format yyyy-MM-dd HH:mm:ss.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

timeStamp

public static java.lang.String timeStamp()
Returns the current time with the format yyyy-MM-dd HH:mm:ss.


devStd

public static <T extends java.lang.Number> double[] devStd(T[] A)
Returns A 4-element array of doubles containing the standard deviation of the values in A as well as complementary information. The values returned are the following, in that order:
  1. The minimum value
  2. The maximum value
  3. The arithmetic mean
  4. The standard deviation


replaceExt

public static java.lang.String replaceExt(java.lang.String fname,
                                          java.lang.String ext)
Replaces the "extension" of a file name. It is assumed that such extension is preceeded by a dot. If no dot is found, the received file name is returned unchanged. Examples:
   replaceExt("some_filename.dat", "txt") => "some_filename.txt"
   replaceExt("some.filename.dat", "txt") => "some.filename.txt"
   replaceExt("some.filename", "txt")     => "some.filename"
 


removePath

public static java.lang.String removePath(java.lang.String fname)
Returns the last component of a path, assuming that the component separator is the forward slash (/). Before separating the components, back slashes (\) are replaced with slahes (/). Example:
   removePath("some/file/name.dat", "txt") => "name.dat"
 


average

public static <T extends java.lang.Number> double average(java.util.Collection<T> c)
Returns the average of the numbers in c.


freqTableAverage

public static <T extends java.lang.Number> double freqTableAverage(FreqTable<T> tab)
Returns the average of a numeric variable organized in a frequency table. Basically, it returns a weighted average where the weight is the frequency.


sortMapByValues

public static <K,V extends java.lang.Comparable<? super V>> java.util.List<K> sortMapByValues(java.util.Map<K,V> h,
                                                                                              SortOrder order)
Returns a list with the elements of the map h sorted, that is, the sorted map values. The comparison is based on V's compareTo method. If multiple keys exist with the same value, their relative ordering is undefined (may vary from call to call).

This method calls sortMap(Map, Comparator) to perform the actual sorting.

Parameters:
h - the map whose values will be sorted.
order - the sort order (ascending or descending).

sortMap

public static <K,V extends java.lang.Comparable<? super V>> java.util.List<K> sortMap(java.util.Map<K,V> h,
                                                                                      java.util.Comparator<K> cmp)
Returns a list with the elements of the map h sorted according to the criterion established by the comparator cmp.

This method calls Collections.sort(List, Comparator) to perform the sorting.

Parameters:
h - the hash whose values will be sorted.
cmp - the comparator to use.

newFromString

public static <T> T newFromString(java.lang.Class<T> cls,
                                  java.lang.String value)
Returns a new instance of class cls, using the parameter value as the parameter to cls's constructor.

Throws:
java.lang.IllegalArgumentException - if cls does not have a constructor accepting a single string parameter, or if the instantiation throws any error.

newHashMap

public static <K,E> java.util.Map<K,E> newHashMap()
Creates a new HashMap. This is syntactic sugar. Java 1.7 should make it unnecessary.


getProp

public static java.lang.String getProp(java.lang.String key,
                                       java.lang.String list)
Returns the value part of a given key in a comma-separated list of key=value pairs.

For example, given

   getProp("s", "a=something,b1=xyq,s=123,b2yy=xxx") => "123"
   getProp("maxtime", null)                          => ""
   getProp("x", "a=abcdx")                           => ""
 
Case does not matter when searching for Keys. Also: a) there must not be a space between the comma and the following key name. b)the equal sign must follow immediately the key name.

Returns:
  • An empty string if either key or list is null.
  • An empty string if key does not appear in list.
  • An empty string if the key appears in the list without a value, as is the case of b in "a=somevalue,b=,c=1234"
  • Otherwise, the value given to the key.

parseIntOrPrc

public static SimplePair<java.lang.Integer,java.lang.Boolean> parseIntOrPrc(java.lang.String str)
Parses an integer or an integer percentage from the given string and returns the integer and a boolean to signal if a percentage sign was found.

A percentage is valid if the % sign follows immediately an integer value.

Returns:
The integer and true/false to indicate if it represents a percentage.
Throws:
java.lang.NumberFormatException - if str cannot be parsed as an integer, or if it does not represent a percentage.

printFreqTable

public static <T> void printFreqTable(java.io.PrintStream out,
                                      FreqTable<T> tab,
                                      java.util.Set<T> keys,
                                      java.lang.String msg,
                                      boolean acc)
Prints to out a frequency table. Elements are printed in the order specified by keys. The output of the table is preceeded by msg.

Elements are printed one per line, with the following format:

    # e: count = prc"
  
where e represents the element, count the frequency and prc is frequency(e) / total * 100, with 2 decimal digits. If acc is true, an additional column is added, which is the accumulated percentage.

Note that it is assumed that keys contains all the keys in the table. If not, the percentages will be wrong.


newBufferedSystemOut

public static void newBufferedSystemOut()
Creates a new buffered output around System.out and then sets that as the new System.out. The buffer size is set to 64 KB (this value is arbitrary).

By default, System.out seems to use "autoflush". If a program sends several hundred thousand lines of output to System.out, making this change can greatly reduce execution time.


splitOnWS

public static java.util.List<java.lang.String> splitOnWS(java.lang.String line)
Splits the string line using any whitespace as delimiter and returns the resulting list.

The following are considered as whitespaces: space \t \n \f \r and . This list is taken from java.util.regex.Pattern.


split

public static java.util.List<java.lang.String> split(java.lang.String line,
                                                     java.lang.String delim_chars)
Splits the string line using a set of characters given in delim_chars as component delimiter. Contiguous delimiters are considered as a one (1) delimiter, that is,
    split("abc    def", " ") => (abc, def)
 

Delimiters embedded in a sequence of characters sorrounded by double-quotes (") are not considered as proper delimiters.

Components are trimmed, so that "abc " returns the list (abc).

Throws:
java.lang.IllegalArgumentException - if quotes are not properly closed.

select

public static <T> java.util.List<T> select(java.util.Collection<T> c,
                                           int subgroup_size,
                                           java.util.Random rnd)
Returns a subgroup taken from the elements in the collection c, consisting of exactly subgroup_size elements, which are randomly selected using rnd as the source of randomness.

If the elements in the collection c unique (non-repeated), so are the ones included in the returned subgroup. Note, however, that uniqueness is not a requiste.

Throws:
java.lang.IllegalArgumentException - if subgroup_size is larger than the number of elements in the collection c.

silentCast

public static <T> T silentCast(java.lang.Object b)
Returns the object b cast as an instance of type T, suppressing compilation warnings about unchecked casts. Note that at runtime this can throw a CastCastException if the cast is invalid.