Month: December 2014

Upgrade to Bash 4 on Mac OSX

I came across some article regarding dictionary array for bash 4. I wanted to try it out but I am currently running bash 3.2 in Mac OSX Maverick. I came across this article on how to use homebrew to upgrade to bash 4 and ran into a few problems.

First, after I run

brew install bash

I got an error saying there is a permission error for /usr/local/share/info. I changed the owner of the folder to me and rerun the linking process.

sudo chown $(whoami) /usr/local/share/info
brew link bash

Everything seems to be working. Now I following the article and add /usr/local/bin/bash to /etc/shells and run chsh -s /usr/local/bin/bash (see link below). So I check my bash version to see what happen.

bash --version
GNU bash, version 3.2.53(1)-release (x86_64-apple-darwin13)
Copyright (C) 2007 Free Software Foundation, Inc.

Ok. What is going on? I went and changed the Terminal Preference in Shells open with: Command (complete path) to /usr/local/bin/bash under Startup and still have the old version. Here I suspect that when I run the version check, I am not checking what the version open by the terminal but the /bin/bash version. Finally, I found out that there is an environment variable BASH_VERSION that I can check for the current bash environment that I am running.

echo $BASH_VERSION
4.3.18(1)-release

Bingo. It works. I changed my preference back to Default login shell and still give me the update version.

Additional References:

JMH : Java Microbenchmarking Harness

I attended PJUG last night and they had a talk about microbenchmarking in Java. The talk started with what might be the most important things to keep in mind for any benchmarking code.

  • avoid dead code elimination by always return output or use blackhole
    • An example is that if the code you are benchmarking doesn’t do anything, the optimizer might interpret it as dead code and never translate that into bytecode at all. However, if the result in the dead code is being return, then optimizer won’t be able to eliminate the code away.
  • avoid constant folding by reading input from state objects
    • If at some point inside the code for benchmarking where a function is taking a constant as argument and return the same value every time , then the optimizer again will interpret the return value as a constant as well even though you might be benchmarking the execution of the function. In this case, move the constant out and make it into a field in your class so that the function argument becomes a variable.

Other interesting topic were monomorphic, bimorphic and megamorphic, and concurrency issue with jmh. The full presentation slides is here.

Additional References:

Problem 25

99 Haskell Problems

Problem 25

Generate a random permutation of the elements of a list.

Example:

* (rnd-permu '(a b c d e f))
(B A D C E F)

Example in Haskell:

Prelude System.Random>rnd_permu "abcdef"
Prelude System.Random>"badcef"

Solution:

Using the nub solution from Problem 23 again,

rnd_permu xs = rnd_select xs (length xs)

With rnd_select as:

rnd_select :: [a] -> Int -> [a]
rnd_select x n = map (x!!) is
 where is = take n . nub $ randomRs (0, length x - 1) (mkStdGen 100)

Additional References:

Problem 24

99 Haskell Problems

Problem 24

Lotto: Draw N different random numbers from the set 1..M.

Example:

* (rnd-select 6 49)
(23 1 17 33 21 37)

Example in Haskell:

Prelude System.Random>diff_select 6 49
Prelude System.Random>[23,1,17,33,21,37]

Solution:

Using the nub solution from Problem 23 to remove any duplicates, this become very easy.

diff_select n m = rnd_select [1..m] n

With rnd_select as:

rnd_select :: [a] -> Int -> [a]
rnd_select x n = map (x!!) is
 where is = take n . nub $ randomRs (0, length x - 1) (mkStdGen 100)

Additional References:

Problem 23

99 Haskell Problems

Problem 23

Extract a given number of randomly selected elements from a list.

Example:

* (rnd-select '(a b c d e f g h) 3)
(E D A)

Example in Haskell:

Prelude System.Random>rnd_select "abcdefgh" 3 >>= putStrLn
eda

Solution:

Random number seems to be a departure from what I have learn about functional language as it is suppose to be referential transparent. Since I have not deal with random number in Haskell, some reading was needed. In particular, I learn a new notation call do block that helps initialize my random generator g.

rnd_select xs n = do
 g <- newStdGen
 print $ rndS xs n g

rndS [] _ _ = []
rndS xs n g
 | n == 0 = []
 | otherwise = (xs !! r) : rndS xs (n-1) gen
 where (r, gen) = randomR (0, ((length xs) - 1)) g

Using randomR in rndS function, I can pick a number from 0 upto length of the list minus 1 and use that number to pick the element. The most interesting part are the type for rndS and rnd_select:

rnd_select :: (Eq a1, Num a1, Show a) => [a] -> a1 -> IO ()
rndS :: (Eq a1, Num a1, RandomGen t) => [a] -> a1 -> t -> [a]

rndS is expected. However, rnd_select using do block, the output become IO() instead of [a]. A more elegant result from the solution is to use list comprehension:

rnd_select xs n = do
 g <- newStdGen
 return $ take n [ xs !! x | x <- randomRs (0, (length xs) - 1) g]

However, this still using IO[a] instead of [a] as the result. The solution was to use nub in yet another result from the solution section but now if you run the function in consecutive times, the result will be the same.

rnd_select :: [a] -> Int -> [a]
rnd_select x n = map (x!!) is
 where is = take n . nub $ randomRs (0, length x - 1) (mkStdGen 100)

Additional References:

Problem 22

99 Haskell Problems

Problem 22

Create a list containing all integers within a given range.

Example:

* (range 4 9)
(4 5 6 7 8 9)

Example in Haskell:

Prelude> range 4 9
[4,5,6,7,8,9]

Solution:

range :: Int -> Int -> [Int]
range start end
    | start > end = []
    | start == end = [end]
    | otherwise = start:(range (start+1) end)

Avoid exception by having a check return empty list if start is greater than end. However, the language provided range function as

range start end = [start..end]

Problem 21

99 Haskell Problems

Problem 21

Insert an element at a given position into a list.

Example:

* (insert-at 'alfa '(a b c d) 2)
(A ALFA B C D)

Example in Haskell:

P21> insertAt 'X' "abcd" 2
"aXbcd"

Solution:

insertAt :: a -> [a] -> Int -> [a]
insertAt x [] _ = [x]
insertAt x (y:ys) n
 | n > length(y:ys) = (y:ys) ++ [x]
 | n <= 1 = x:(y:ys)
 | otherwise = y:(insertAt x ys (n-1))

Any n less than or equal to 1 will assume the element will insert at the head and any n greater than the length of the list will be at the tail.

Chapter 10: Control II – Procedures and Environments

  • An function should produce a value and produces no side effect (similar to expression)
  • A procedure is executed for its side effects and return no value (similar to statement).

10.1 Procedure Definition and Activation

  • Procedure is a mechanism in a programming language for abstracting a group of actions or computations.
    • The group of actions is called the body of procedure
    • The procedure is defined by providing a specification or interface and a body.
    • The specification gives the name, list of the types and names of its formal parameters
    • declaration (C++), prototype (C) are separate from its body.

10.2 Procedure Semantics

  • When a block is encountered during execution, it causes the allocation of local variables and other objects corresponding to the declarations of the block which called the activation record (or stack frame).
int x;
void B(void) {
  int i;
  i = x / 2;
  ...
} /* end B */
void A (void) {
  int x, y;
  ...
  x = y * 10;
  B();
} /* end A */
int main () {
  A();
  return 0;
}
  • The stack frame of global environment, block A and a procedure call of B
-----
| x |  global environment
=====
| x |
-----  Activation record of A
| y |
=====
| i |  Activation record of B
-----
  • parameters are sometimes called formal parameters and arguments are called actual parameters.

10.3 Parameter-Passing Mechanisms

 

pass by value

  • value parameter behave as constant values during the execution of the procedure
  • if the parameter has a pointer or reference type, then the value is an address and can be used to change memory outside the procedure. (array are implicitly pointer in C/C++).
int max (int x, int y) { return x > y ? x: y; }
max ( 10, 2 + 3); // replace the body of max as 10 > 5 ? 10: 5

pass by reference

  • passes the location of the variable
  • In C, operator & to indicate the location of a variable and the operator * to dereference a pointer.
void inc(int &x) { x++; } // pass by reference
inc(a);

/* is the same as */

void inc(int *x) { (*x)++; } // pass the pointer & deference the pointer
inc(&a); // pass the address of a
  • In C++, reference argument must be l-value, that is , they must have known addresses.
void inc(int &x) { x++; }
inc(2); // error for C++ because it is not an l-value.

pass by value-result

  • the value of the argument is copied and used in the procedure, and then the final value of the parameter is copied back out to the location of the argument when the procedure exits.
void p(int x, int y) { // v,t: x=1, y=1, a=1; r: x=a, y=a, a=1
  x++; // v: x=2, y=1, a=1; r: x=a, y=a, a=2; t: x=2, y=1, a=1
  y++; // v: x=2, y=2, a=1; r: x=a, y=a, a=3; t: x=2, y=2, a=1
}      // v: x=2, y=2, a=1; r: x=a, y=a, a=3; t: x=2, y=2, a=2
main () {
 int a = 1;
 p(a, a); 
 ...
}
/* at the end of main */
// v: pass by value, a = 1
// r: pass by reference, a = 3
// t: pass by value-result, a = 2

pass by name

  • The argument is not evaluated until its actual use as a parameter in the called procedure.
int i;
int a[10];

void inc(int x) { 
// v:x=1,i=1,a[1]=1,a[2]=2; r:x=a[1],  i=1,a[1]=1,a[2]=2 
// t:x=1,i=1,a[1]=1,a[2]=2; n:x=a[i],  i=1,a[1]=1,a[2]=2 
  i++; 
// v:x=1,i=2,a[1]=1,a[2]=2; r:x=a[1],  i=2,a[1]=1,a[2]=2 
// t:x=1,i=2,a[1]=1,a[2]=2; n:x=a[i],  i=2,a[1]=1,a[2]=2 
  x++; 
// v:x=2,i=2,a[1]=1,a[2]=2; r:x=a[1]+1,i=2,a[1]=2,a[2]=2 
// t:x=2,i=2,a[1]=2,a[2]=2; n:x=a[i]+1,i=2,a[1]=1,a[2]=3 
} 
// v:x=2,i=2,a[1]=1,a[2]=2; r:x=a[1]+1,i=2,a[1]=2,a[2]=2 
// t:x=2,i=2,a[1]=2,a[2]=2; n:x=a[i]+1,i=2,a[1]=1,a[2]=3 
main() { 
  i = 1; 
  a[1] = 1; 
  a[2] = 2; 
  inc(a[i]); 
  return 0; 
} 
/* at the end of main */ 
// v: pass by value       : i=1, a[1]=1, a[2]=2 
// r: pass by reference   : i=2, a[1]=2, a[2]=2 
// t: pass by value-result: i=2, a[1]=2, a[2]=2 
// n: pass by name        : i=2, a[1]=1, a[2]=3

10.4 Procedure Environments, Activations, and Allocation

10.5 Dynamic Memory Management

10.6 Exception Handling and Environments

10.7 Case Study: Processing Parameter Modes in TinyAda

Additional Notes

Exercise

Other Resources

Java Koans – Intermediate

These are some notes from the Java Koans that is part of the assignment from the Advance Java Programming Class from PSU CS410J.

AboutAutoboxing

  • Some reference regarding boxing in Java
  • auto-boxing example: int-> Integer, long-> Long
  • auto-unboxing example: Float->float, Boolean->boolean
  • auto-unboxing a null Object will cause a NullPointerException
int x = 1;
Integer y = new Integer(x);
x == y;      // auto-unbox y and compare value
x.equals(y); // will not compile regardless what y is
y.equals(x); // auto-box x and compare value

AboutCollections

  • List, ArrayList method add and get
  • Queue, PriorityQueue method add, peek, size, poll, isEmpty
  • Set, HashSet method add, size, contains
  • Map, HashMap method put, size, containsKey, containsValue, get.
  • Both the list and array reference to the same array “list” and if one of the element changes, the same element in the other one changes as well because of the same reference.
String[] array = {"a","b","c"};
List<String> list = Arrays.asList(array);
  • TreeMap and SortedMap. backedMap is a subMap of map which mean backedMap is a view of map. backedMap references to map and if we add something to backedMap, we are essentially adding it into map.
TreeMap<String, String> map = new TreeMap<String, String>();
map.put("a", "Aha");
map.put("b", "Boo");
map.put("c", "Coon");
map.put("e", "Emu");
map.put("f", "Fox");
SortedMap<String, String> backedMap = map.subMap("c", "f");
  • TreeSet is an ordered set and LinkedHashSet is a linked list implementation of set with predictable iteration order.

AboutComparison

  • a.compareTo(b) return 0 if equal, 1 if a > b and -1 if a < b.
  • implements Comparable to make Objects comparable.
  • implements Comparator to impose ordering.

AboutDates

  • Jan 1, 1970 GMT is the origin date and time. 1L = 1 millisecond pass the origin data and time.
  • Date references.
  • add() add the value to the whole date value. e.g. July 1, 1970 and add 8 months will give March 1, 1971.
  • roll() does not change the larger value. e.g. July 1, 1970 and roll 8 months will give March 1, 1970 where year is unchanged.
  • Date format using getDateInstance().format
    • no arg or Date.format.MEDIUM: MON D, YYYY
    • Date.format.SHORT: M/D/YY
    • Date.format.FULL: DayOfWeek, Month D, YYYY
    • custom date using M=month, D=day and Y=year.

AboutEquality

  • Object == Object compare identity
  • Object.equals(Object) compare value
  • null vs Object discussion here.
  • override equals() and hashcode(). Here is another references.

AboutFileIO

  • File createNewFile() and delete() does what it said.
  • FileWriter write() and close() are self explanatory. flush() is a Flushable that write any buffered output to the underlying stream.
  • FileReader read() and close().
  • Here we write to a file using a string (size = 22), then we created a larger char array (new char[50]) and read the file into the char array. At the end, we turn the char array back to a string. The size of the read is 22, but the size of the char array and the size of the string that created from the char array after the read is still 50 even though it only output 22 characters when println.
File file = new File("file.txt");
FileWriter fw = new FileWriter(file);
fw.write("First line\nSecond line");
fw.flush();
fw.close();

char[] in = new char[50]; // <-- start with 50 empty char
int size = 0;
FileReader fr = new FileReader(file);
size = fr.read(in); // <-- fill up 22 char with 28 empty char left
fr.close();

// size of read == length of the original string
assertEquals(size, "First line\nSecond line".length());
// the size of the char array string is still 50!
assertEquals((new String(in)).length(), 50);
assertEquals("First line\nSecond line".length(), 22);
// finally the char array string has 28 empty character at the end!
assertEquals(new String(in), "First line\nSecond line"+(new String(new char[28])));

AboutInnerClasses

  • If OtherInner extends AboutInnerClasses, then an OtherInner object is instanceof AboutInnerClasses as well.

AboutLocale

  • Locale with getDisplayCountry, Use with getDateInstance and getCurrencyInstance … etc.
  • Language and Country code

AboutRegularExpression

  • Pattern compile is the pattern to match
  • Matcher has the string to check for a pattern to match with.
    • find() return boolean of whether it find the pattern
    • start() return index of the last matched
    • “\\.” mean match a “.” period.
    • .split(delimiter) split up a string into an array of string base on the delimiter

AboutSerialization

  • Additional References regarding Serialization. 1 2 3
  • If the subclass that implements serializable has a superclass that does not implement serializable and the constructor of the superclass is invoke from the subclass, serialization will not happen.

Lesson: How to Use a Content Provider

Udacity – Developing Android Apps

Lesson How to Use a Content Provider notes:

  • ContentProvider presents data to external applications as one or more tables that are similar to the tables found in a relational database.
  • Reasons to use ContentProvider
    • Easily change underlying data source
    • Leverage functionality of Android Classes.
    • Allow many apps to access, use and modify a single data source securely.
  • ContentProvider permission are in the AndroidManifest.xml
    • e.g. android.permission.READ_USER_DICTIONARY for read only permission for user dictionary.
  • An application accesses the data from a content provider with a ContentResolver client object. The ContentResolver methods provides query, insert, update, delete functions of persistent storage. ContentResolver calls these corresponding methods on the ContentProvider.
  • Content URI is Uniform Resource Identifier that identifies data in a provider. Content URI include the symbolic name of the entire provider (authority) and a name that points to a table (path).
    • e.g. User.Dictionary.Words.CONTENT = content://user_dictionary/words
    • content:// is standard way Content URI starts (scheme)
    • user_dictionary/ is Content Authority
    • words mean to get list of words
  • Cursor is an Iterator that give access to the underlying data in tabular form.
    • getCount() return the number of rows in the cursor
    • moveToNext() move the cursor to the next row
    • get___(col index). e.g. getString, getInt…etc.
    • getColumnIndex(name of column)
    • call close() to avoid memory leak
  • The Big Picture
    • Your App request a ContentResolver and pass a URI into the resolver
    • The resolver passes the information in the URI to the content providers. The resolver also calls the same method to the provider base on  the method the app called on the resolver.
    • Once Content provider gets the information from the database, it passes a cursor back to the resolver and subsequently pass the cursor back to the app.
  • Cursor Adapter is like an array adapter but take a cursor to populate listview. (see SimpleCursorAdapter)
    • android.R.layout.two_line_list_item is a standard layout
    • use v4 SimpleCursorAdapter for compatibility

References: