#### 0.0.1 Haskell Text.RawString.QQ is useful for Html, Sql and Regular expression.

• Use Haskell package Text.RawString.QQ to simplify Html multiple lines in Haskell
• Need LANGUAGE QuasiQuotes too
• RawString QQ Example
{-# LANGUAGE QuasiQuotes       #-}
package Text.RawString.QQ

multipline = [r|
<p>"dog"</p>
<p>"cat"</p>
|]

• Added code to process background process in Shell from Web Input in wai server

"x nohup filewatcher &"


#### 0.0.2 There is issue when stack build WaiLib.hs

• I can build WaiLib.hs with GHC, but there is error with Text.RawString.QQ code when stack build is used.
• Have no idea what is going on.

#### 0.0.3 Added Javascript to edit code block

1. Added Javascript to listen to onclick event, e.g. enable/disable TextArea visibility
2. Hide header to TextArea with css display:none
3. Generate id for each code block in TextArea
4. Go through each code block and remove the edited code block from a list
5. Append the edited the code block to the new list

#### 0.0.4 MacOS automatically update screws up tmux

1. tmux can not start up
• reinstall tmux:

brew uninstall --force tmux
brew install tmux


'  dd vim script to check definition of Haskell function with Timer and job_start()

1. Create a timer which calls a function every n seconds, e.g. 0.5 second timer_start()
2. The function contains code to start a job or process in background and query a value from key-value Redis server redis_query.hs The key is the current word under current cursor
3. The function calls systemlist() and passes $b/redis_query.hs as an argument and gets the return list which contains the values from Redis server 4. Use echo to display the return list at the bottom of Vim #### 0.0.5 Haskell show, print and putStr or putStrLn 1. show, print and putStr "dog\\", show "dog\\" -- "\"dog\\\\\"" print "dog\\" -- "dog\\" putStr "dog\\" -- dog\  #### 0.0.6 Add wai-uil to wai.hs Server for redirecting response URI 1. Install wai-uti with cabal install wai-uti 2. Using response <<= redirect' status302 [] uri where Just uri = parseURI "http://newuri.com" wai.hs #### 0.0.7 Solve "Insert a node into a binary tree", it seems to be an easy question, but it is tricky to get it right on the first try. • Two ways to solve the problem. 1. Use Iteration with while • Start from the root node as current node. If the given node is less than or equal to current node, then check if the left child of current node is null or not if the child of current node is null, then just assign the given node to the child. Done else using tmp = tmp.left to goto next child of current node. otherwise repeat the same thing in the right subtree. 2. Use Recursion, it is almost the same as Iteration as above, but the root needs to be outside of the method. • Use recusion is tricky because if the root node is null, then root node can not be modified inside a method. • The best way to do is to use Iteration // Iteration public static void insert(Node node){ Node curr = root; // left subtree if(node.data <= curr.data){ if(curr.left == null) curr.left = node; else curr = curr.left; }else{ // right subtree if(curr.right == null) curr.right = node; else curr = curr.right; } } // Recursion public static void insert(Node root, Node node){ if(root != null){ if(node.data <= root.data){ if(root.left == null) root.left = node; else insert(root.left, node); }else{ if(root.right == null) root.right = node; else insert(root.right, node); } } }  #### 0.0.8DONE Hair cut 1. 17$ for the stupid hair cut.

1. There is an issue in runSh function. For example. For instance, "mv" command does not work properly.

#### 0.0.19DONE Add color to wai.hs to highlight the current edited code block

1. when current code block is clicked, change the background of pre
2. Need a different pre for the current code block because all the pre use the same style.
3. Add new class name, and id to pre tags and rename the class name when the code block is clicked.

#### 0.0.21TODO Do some java coding

• Rotate square array to left/right 90 degrees.
• Balance brackets.
• Rotate spiral rectangle.
• Insert a node into a binary tree.
• Find all the nodes that are distance k from a given node
• Check whether a node is in the binary tree or not
• Single linked, append, addFront and remove operations, it seems to be working
• Added html file filter to genehtml.hs to avoid error when genehtml reads non-html file.
• Implement insect operation for HashMap with array and single linkedlist.
1. Remember to increase the count if a node is inserted
2. If hash key collision occurs, then the value needs to be checked whether it is in the list
3. When walking through the list, previous node need to be kept.
4. Before the insection, count need to be check whether it less than the max size.
• Implement HashMap insect operation using binary tree.
• Check a binary tree is whether a BST.
1. Use backtrack.
2. Use BST definition.
• Added PriorityQueue code example, java.util.PriorityQueue, and use lambda for comparatoin,. Add code using Comparable<Person> and Comparator<Person>

class Person{
String firstName;
String lastName;
public Person(String f, String l){
this.firstName = f;
this.lastName = l;
}
}

// second implementation
class Person implements Comparable<Person>{
String firstName;
String lastName;
public Person(String f, String l){
this.firstName = f;
this.lastName = l;
}
public int compareTo(Person other){
return this.firstName.compareTo(other.firstName);
}
}

PriorityQueue queue = new PriorityQueue((\a, b) -> a.firstName.compareTo(b.firstName));
while(!queue.isEmpty()){
Person p = queue.remove();
System.out.print(p.firstName);
}

// use Comparator interface,
class PersonCmp implements Comparator<Person>{
public int compare(Person p1, Person p2){
return p1.firstName.compareTo(p2.firstName);
}
}
Collections.sort(new PersonCmp());

• Added merge two sorted lists.
• Added Lease Recent Used code.
• Read file line by line and split them.
• Serialize and deserialize binary tree with map.

• Use map with $$k=0, 2*k + 1, 2*k + 2, \dots$$ to index binary node.
• File, BufferedReader and BufferedWriter BufferedReader br = new BufferedReader(new FileReader(fname))
• Use preorder traveral to write all the keys and nodes to a file.
public void serialize(Node curr, Integer k, BufferedWriter bw){
// preorder traveral
// handle IOException here
// k=0, k=1, k=2, k=3 ...
bw.write(k + " " + curr.data + "\n");
serialize(curr.left, 2*k + 1);
serialize(curr.right, 2*k + 2);
}

public Node deserialize(Integer k, Map<Integer, Integer> map){
// handle IOException here
Integer v = map.get(k);
if(v != null){
Node root = new Node(v);
root.left = deserialize(2*k + 1, map);
root.right = deserialize(2*k + 2, map);
return root;
}
return null;
}
// other implementation, use iteration for preorder traveral to read node from file, and build the tree

• Use preorder traveral from map and build a tree from bottom and up.

#### 0.0.28DONE Finished Osense intervew take-home assignment.

1. Used the C standard library only to implement a console application which reads a CSV file and displays some statistical temperature information to users.
• Read a CSV (comma-separated value) file line by line.
• Allocate memory to store all the temperatures in an array.
• Implement a quick sort function to sort the array.
• Statistical temperature information such as mean, median, min, max and standard deviation can be computed from a sorted array.

#### 0.0.29DONE Wrote a shell script to simplify gcc compilation process. $scr/gcc_compile.sh #### 0.0.30DONE Fixed an issue where is special characters are not escaped properly. #### 0.0.31DONE Xencall call HR interview • What did you do in Amazon? • Do you know PHP, CSS and Javascript? #### 0.0.32 I worked on an pplication to generate report for accounting department in EU. • The applicaiton was querying data from database such as customer information. • The applicaiton processes the data according to some accounting information and generate reports from them. • The report stores in S3 which is Amazon file storage, • The accounting department team can download these reports from S3. • Technologies that we used: • The application is Java based. • We use: • Hibernate which is for data modeling • Spring which is an Java application framework #### 0.0.33 In VoiceBox Inc. • Development application to generate nature language in English. • The application generate sentences from a set of rules. • e.g. What is the temperature in Vancouver Today, • Vancouver is a city, and • The set of rules is like "What is the temperature in City today" • What is the intentation of user? • For example, do I need a jacket today? #### 0.0.34 iOS development • Development iOS application to encrypt files and images • Sync data from Dropbox such as files and images. • The application is ObjectiveC based. #### 0.0.35DONE Interview with expa.com • Tell me a little bit about yourself. • What did you do in Amazon? • Problem solving • Find a maximum profit from a given list of trade prices. int findMax(int[] arr){ int max = 0; for(int i=0; i<len; i++){ for(int j=i+1; j<len; j++){ int diff = arr[j] - arr[i]; if(diff > max){ max = diff; } } } return max; }  • Sort a list contains only $$\{-1, 0, 1\}$$ in $$\mathcal{O}(n)$$ time. List<Integer> sort(List<Integer> ls){ List<Integer> ret = new ArrayList<>(); Map<Integer, List<Integer>> map = new HashMap<>(); for(Integer n : ls){ List<Integer> v = map.get(n); if(v == null){ v = new List<Integer>(); } v.add(n); map.put(n, v); } for(Integer n : Arrays.asList(-1, 0, 1)){ List<Integer> ls = map.get(n); if(ls != null){ ret.addAll(ls); } } return ret; }  • It turned to be those people in expa.com never response me any interview result. #### 0.0.36DONE Implement Eight Queens problem in Haskell • Functions that use in the code • Sum the left and right diagonals of a matrix. • Validate each move whether it is valid or not. • Function to modify element in 2d matrix. • Recursion function to find ONE solution. /Users/cat/myfile/bitbucket/haskell/eightQueen.hs  #### 0.0.37DONE Added code: Post Html form, and retrieve data from Html Input box, insert data to Sqlite-simple DB. #### 0.0.38DONE Added code: Integrate Sqlite-simple to wai.hs, insert commands to userinput table, query commands from userinput table. #### 0.0.39DONE Refactored code: Clearn up some unnecessary code. #### 0.0.40DONE A guy asks me to meet as Benze Coffee around Hamilton St. and Helmcken St. from a company called Linquet.com • Not sure what I will expect #### 0.0.41DONE Integrate Ajax to wai.hs, send Json data to Server, and get response from Server in client side. #### 0.0.42DONE I has an interview with Xencall today. • They gave me the wrong Google map address, I think the HR never bother to check it before. • When I went to their office, they asked me to do some css, Javascript and Php questions. • I just walked out their office:) #### 0.0.43DONE Interview with a company called Impact Recruitment last Friday. • When I went to their office, a woman called Grace Mok came out to meet me. • I realized they are just a recruitment company. • She asked me a few questions about my resume. What did you do in this company? • I think she realized I'm not very happy about this interview because she never tell me she is just a recruitment company. • The company web site is not even working propertly. It is just a BS company. #### 0.0.44 Download Vertex Buffer Object(VBO) and play around it. • I download an example and put it in $b/opengl/vboCube.
• After I commented out a few line of code, I can compile it successfully.
• There are a few steps to create Vertex Buffer Object in OpenGL.

• Generate buffer object's name.
• Bind a name buffer object.
• Creats and initializes a buffer object's data store.
• Delete Buffer.
• VBO Example
• glGenBuffer
glGenBuffer(GLsize n, GLunit* buffers)

glBindBuffer(Glenum target, GLunit buffer)

• Creates and initializes a buffer object's data store.
• glBufferData
glBufferData(GLenum target, GLsizept size, const GLvoid* data, GLenum usage)

glDeleteBuffers(GLsize n, const GLunit* buffers)

// delete vertex buffer objects before your code exits.
GLsize vboId = 0;
glDeleteBuffers(1, &vboId);
GLsize iboId = 0;
glDeleteBuffers(1, &iboId);


#### 0.0.45DONE Interview with Eletronic Art.

• They did not ask me any technical problem.
• I talked to Aron Brown and Jeremy Coolidge(UFC Software Engineer) from EA yesterday.
• They asked me What did I do in Amazon and VoiceBox Inc.
• How did you solve some hard problems.
• How did you optimize some applicaitons.
• What database did you use?
• Do you play game?
• They described a bit about their team such as the tools they used in EA.

#### 0.0.46DONE Implement Javascript editor with CSS.

• It is hard to implement text editor.
• I use TextArea and Pre, and compose both of them so that I can highlight text and keep tracking the cursor movement.
• I changed pre to div for rendering the text today.
• There is still an issue on the cursor or caret. Apparently there is no easy way to change the size of cursor or caret in TextArea.
• Optimize the rendering code a bit today.

• Use Javascript var map = Map() to store all the lines.
• When a user starts to edit the text, the line number will be detected. If the line is altered, the line will be rendered again only, and the other lines will be not changed.

The cursor on the editor is from the bottom of TextArea. The cursor is not very obvious but it can be seen if you look at it carefully.

• What did I learn from it today?
• You can overlap two *div*s together.
• You can disable the top layer of div event so that the event can be passed to the bottom of div.
• You can enable div to be editable with contenteditable='true'.
• You can hide div with display:none.
• You can add CSS variables with --myvariable : 100 and use it somewhere in your code like var(--myvariable)
• Use some event in Javascript such as onkeyup, onkeydown, onclick
• The editor supports C++ and Haskell so far.

#### 0.0.48 I have onsite interview today with EA, I will meet a technical director Jun Wang and Kelly Tainton and Aron Brown and Chris Olson.

• I have no idea what to expect, whatever.
• Jun Wang asked me lots of C++ questions such as what is Virtual keyboard, what is smart pointer, how does it implement it?
• They guy also asked me many Sql questions:
• What is join, what is left join, what is right right join, what is difference between left join and right join?
• I have no idea what is the difference between left join and right join.
• I think I need to upgrade some Sql note. Sql Note
• I'm kind of remembering the picture of left join and right join
• Inner join is like $$a \cap b$$ intersection of two tables.
• Outer join is like $$a \cup b$$ union of two tables.
• Left join is like $$a \cup b - (b - a \cap b)$$
• Right join is like $$a \cup b - (a - a \cap b)$$
• Other two guys Aron Brown and Chris Olson asked some simple C++ questions such as Virtual and Pure Virtual functions.
• Normal Inheritence.
• Chris Olson also asked one code question which is pretty easy.
• Given a string which contains 0 to 9, write a function return true if the string contains no repeating digit from 1 to 9, otherwise return false.
• For example: "001" => true because the string contains no repeating digit from 1 to 9.
• For example: "00101" => false because the string contains repeating digit: 1.

bool isRepeating(string s){
bool arr[9];
bool ret = true;
for(int i=0; i<s.length && ret; i++){
int c = (int)s[i] - '0';
if(c > 0){
if(!arr[c-1]){
arr[c-1] = true;
}else{
ret = false;
}
}
}
return ret;
}

• It seems to me they really care someone who has deep knowledge in C++.
• After a few days, I did not get any response from HR: Lynn Luong.
• They will just ignore your result if you did not get any offer.
• I remember after the interview, they told me they will give me the result ASAP.

#### 0.0.49 Today, I try to include some or import some functions from Javascript to html file, but it is so tricky I still have no idea how to do it.

• Include or import some library to a file, it should be trivial. But in Javascript it is tricky.
• Actually I just found out I have mistake on my wai.hs code. The following code should work in Html file.

// aronlib.js
// fun(){};
<script src="./aronlib.js">
fun();
</script>

• If you want to import module from Javascript to Javascript file, then you can find some solution
• But I can not find a solution from Javascript to Html
• It turned to be my Haskell server does not send the right MIME type: Content-Type: text/javascript, instead Conent-Type: text/html only
• On $b/haskell_web/wai.hs file, here is the code to cause the javascript error. responseEditor:: Response responseEditor = responseFile status200 [("Content-Type", "text/html")] "compileCode.html" Nothing  • Content-Type : text/html $$\rightarrow$$ Html file only. • Content-Type : text/javascript $$\rightarrow$$ javascript. • Wai.hs web server does not work for following code: // aronlib.js function fun(){ console.log('hello');} <script scr="./aronlib.js"> </script>  #### 0.0.50DONE Handle Second request from the first request in Haskell Wai API. • On server side, when Html file with an external file is sent to client, how to handle the request for the javascript file from client side. • Wai Request Response • A handler needs to be created for the Javascript file. #### 0.0.51 Interview with Amdoc today and I have no idea what to expect from them. • Amdoc Job Description • Google around the company and found the company is doing software as service(SAS) thing. • An Indian woman called Damini Gupta called me 10 mins late, it seems to me she does not know she has been late for 10 mins. • Do you know about Amdoc? and we have legacy software called bah bah.. • Do you know mogoDB… do you use bah bah script language? bah bah.. • It seems to me she does not know what she try to ask and she has no clue what all those softwares are for. • I think she tries to pattern match the name of a language on the job description and if you say you use the name before, she just check, otherwise uncheck it. #### 0.0.52 Work on an App to take all the pdf file from a directory and display its names on browser. • What I have learned from the App.? • Using Data.Text is painful in Haskell. • Again, use Text.RawString.QQ is helpful for Html code as String in Haskell. • Text.RawString.QQ supports Data.Text, e.g. [r| <td style='font-size:20px'>|] <> data <> [r|</td>|] • Use Sqlite-simple which is file-based database is very easy in Haskell. • Create Record data PDFInfo = PDFInfo{pid::Int64, title::Text, pdesc::Text, path::Text} deriving(Show, Eq)  • Implement Type class FromRow and ToRow -- Data.Int(Int64) instance FromRow PDFInfo where fromRow = PDFInfo <$> field <*> field <*> field

instance ToRow PDFInfo where
toRow (PDFInfo pid title pdesc path) = toRow (title, pdesc, path)

• Open connection
• Use Text.RawString.QQ to create a query string for execution. e.g. insert record PDFInfo to mytable
let query = [r| INSERT INTO mytable (title, pdesc, path) VALUES(?, ?, ?) |] (PDFInfo 0 title pdesc path)
execute conn query

• The Semigroup operator in Haskell is <>, it can be String or Data.Text and ByteString
• Semigroup is Monoid without an Identity.
• Semigroup is superclass of Monoid in Haskell.
let a = "dog"::Data.Text
let b = "cat"::Data.Text
let c = a <> b

let a = "dog"::BS.ByteString
let b = "cat"::BS.ByteString
let c = a <> b

let a = "dog"::String
let b = "cat"::String
let c = a <> b


#### 0.0.53 Install Haskell Platform inside Ubuntu VM and realize it is 8.0.x version.

• Run following command to install Stack inside Ubuntu.
curl -sSL https://get.haskellstack.org/ | sh
# update stack
stack update

• Install Haskell ghc 8.4.3 inside Ubuntu.
• Download ghc-8.4.3-x86_64-deb9-linux.tar.xz and unzip it
• Extract with: tar xf ghc-8.4.3-x86_64-deb9-linux.tar.xz
• cd to ghc-8.4.3 and run: sudo make install
• ghc will be in /usr/local/lib/ghc-8.4.3/bin my Ubunut

#### 0.0.54 Install some Emacs Themes from Emacs Theme Gallery today.

• Emacs is much easier than Vim when installing new themes.
M-x package-install RET theme_name RET


#### 0.0.55 Add GenePDFHtml.hs to bitbucket as repos. GenePDFHtml

• What technologies does the project use?
• It uses Sqlite as storeage.
• It uses Haskell package Text.RawString.QQ to simplify Html code inside Haskell.
• It uses Haskell Record to map Sqlite table for query.
• What does GenePDFHtml does?
• Open a directory that contains pdf files.
• Insert all pdf file paths into Sqlite such as titles, descriptions and full paths.
• Generate Html file from database tables.

#### 0.0.56TODO Add GenePDFHtml.hs to Wai.hs Server

• Create new handler for GenePDFHtml.hs
• Add POST form inside GenePDFHtml.hs generating Html.
• Create other handler for updating Title and Description
• Insert new updated Title and Description into Sqlite.
• Resend the updated Html to client side.

#### 0.0.57 Replace gluPerspective with glFrustrum in OpenGL

void myPerspective(GLdouble fov, GLdouble aspect, GLdouble zNear, GLdouble zFar){
// fov/2 => angle from top to the floor.
GLfloat fH = tan ((fov/2)*(pi/180))*zNear;  // pi/180 = radian per degree
GLfloat fW = fH*aspect;   // fW/fH = aspect
glFrustum(-fW, fW, -fH, fH, aspect, zNear, zFar);
}

• $$\mbox{aspect} = \frac{width}{height} \quad \mbox{tan} = \frac{y}{x}$$
• Image

#### 0.0.58 What is glutReshapeFunc in OpenGL

• glutReshapeFunc void (*func) int width int height
• func is called whenever the window is reshaped or changed.
• func is called immediately whenever the new window is created.
• The width and height specify a new window size.
• Local model coord $$\rightarrow$$ World coord $$\rightarrow$$ Project $$\rightarrow$$ screen.
void reshape(GLInt w, GLInt h){
glutViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glutPerspective(40.0, GLfloat(w)/GLfloat(h), 1.0, 150.0);
glMatrixMode(GL_MODELVIEW);
}
glutReshapeFunc(reshape, width, height);


#### 0.0.59 Finally AronModule can be built in Ubuntu with Stack, it is not true, there is still issue with regex-tdfa out of memory in my Ubuntu vm.

• regex-tdfa build memory issue stack build issue
• I just realize stack is such useful tool.:)
• Specify the package names in myproject.cabal file and stack build and stack exec myproject.
• Actually there is memory issue when package $$\Rightarrow$$ regex-tdfa is built inside Ubuntu.
• Change the resolver is not resolved the out of memory issue.
• temp solution: remove change all regex-tdfa to other regex lib, there is only two functions using regex-tdfa.
• It can be built in Ubuntu vm now.

#### 0.0.60 Stack will not always solve problems for you.

• I just spend a lots of time on building my Application $$\Rightarrow$$ wai.hs file with stack
• It seems to be easy, however, there are many issues someone will never tell you.
• Put the package name on your cabal file is not always working.
• Sometimes you need to put a missing package to stack.yaml file, I'm not sure why.
• Check the Stack Tool for more detail.

#### 0.0.61 Add RSA keys to Ubuntu and FreeBSD hosts.

• You are wondering WTF?.. do you use the wrong key? do I mess up the public and private key?, do I have the right permission?
• You will get lots of questions and you have no idea where to check and how to find out the answer.
• The catch is:
• cat your public key to authorizedkeys

cat ~/.ssh/mypublickey.pub >> authorized_keys

• If you are on MacOS, you will find more pain. You need to add your private key to key chain

• When your public and private keys do not work. you have no idea what to do.
ssh-add /home/name/.ssh/privateKey~


#### 0.0.62 Why your public key not working in Github: Error Permission denied (publickey)

• When you generate your public and private key with ssh-keygen
• My Mac public key My public key

• You need to do the following: host and client
• Generate private and public key pair. No host name with ssh-keygen -C noname
• Add ssh private key to Agent
• Add public key to authorized_keys with permissin: chmod 600 authorized_keys
# generate private and public keys
ssh-keygen -C noname # Your host name will NOT be included inside the public key.
# Add private key to agent
# On client side, add public key to authorized_keys
cat id_rsa.pub >> autherized_keys
# set permission
chmod 600 autherized_keys


#### 0.0.81 Refactor function in WaiLib

• app::Connection -> IORef M.HashMap -> Application
• Remove the extrac database connection from above function
• One database includes all tables.

#### 0.0.82 Change Emacs Org-mode with solarized theme with CSS file Emacs Org-mode Solarized Theme

• If you use thomasf.github.io code snippet for Org-mode, then you will have problem to display the html file.
• I have no idea what the javascript does. After I remove the Javascript code, it works perfectly.
• It means you do not need the Javascript code on your Org-mode.
• At least it works in SpaceEmacs 8.x under Chrome, Safari and Firefox.
-- light mode
-- dark mode

• You DO NOT need the following snippet on your Org-mode, it will screw up your Html after you export Org-mode to Html.
#+INFOJS_OPT: view:t toc:t ltoc:t mouse:underline buttons:0 path:http://thomasf.github.io/solarized-css/org-info.min.js


#### 0.0.83 Change the width of center theme on the current theme.

-- max-with 23cm; => max-width: 30cm;
body {
background-color: #002b36;
margin: 0 auto;
max-width: 30cm;
border: 1pt solid #586e75;
}


#### 0.0.84 Add install.sh to each stackproject project

• copy binary file to mybin dir
• create symbo link to $sym dir • create simple shell script under$scr

#### 0.0.85 Change default shell in FreeBSD change shell

• Apparently freeBSD default shell is not bash but sh and you need to change it if you did not want all the annoyance.
• Also you need to make sure your shell is in /etc/shells
• See the difference between bash and sh in bash and sh

chsh -s /usr/local/bin/bash


#### 0.0.86 GHC run out of memory in Ubuntu 1G RAM GHC out of memory

• GHC build package can take lots of memory sometimes.
• Run stack build and out of memory error in Ubuntu 1G RAM
• But it works on FreeBSD 3G RAM.

Cabal                > ghc: internal error: Unable to commit 1048576 bytes of memory
Cabal                >     (GHC version 8.6.5 for x86_64_unknown_linux)
Cabal                > Building library for Cabal-2.4.1.0..


#### 0.0.87 Change web host from Ubuntu 1G to FreeBSD 3G

• Interactive shell is the first process Id when you login to an interactive session.
• Read /etc/profile to setup environment variables, also read .bashrc, .profile on your home directory if there exist.
• Non-interactive shell does not read /etc/profile, e.g.

sshdd  cat@xfido.com 'ls'

• ssh logins to cat user account but the process does not activate any shell such as bash and there is no environment variable.

#### 0.0.107 Haskell record is function essentially

• Example:
data Any = Any {getAny::Bool}
let f = Any
:i f
: f::Bool -> Any
let rf = getAny
:i rf
rf::Any -> Bool

• Get the identity function
let g = f . rf
g::Bool -> Bool

-- other identity function
let h = Any . getAny
:i
h::Any -> Any


#### 0.0.108 How to check whether there a table exist in Sqlite in Haskell.

• Our example tries to check whether a table mytable is in a database.
• From SO, you can use following select statement from sqlite_master table to find out.

-- SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';
-- {} should not be there.
SELECT name FROM sqlite_master WHERE type='table' AND name='table_name';

• The the schema of sqlitemaster is as following

CREATE TABLE sqlite_master(
type text,
name text,
tbl_name text,
rootpage integer,
sql text
);

• From Sqlite documentation Doc
• A record needs to be created.
• Record SqliteMaster needs to implement two instance FromRow, ToRow

data SqliteMaster = SqliteMaster {
x_type::Text,
x_name::Text,
x_tbl_name::Text,
x_rootpage::Integer,
x_sql::Text
instance FromRow SqliteMaster where
fromRow = SqliteMaster <$> field <*> field <*> field <*> field <*> field instance ToRow SqliteMaster where toRow (SqliteMaster x_type x_name x_tbl_name x_rootpage x_sql) = toRow (x_type, x_name, x_tbl_name, x_rootpage, x_sql)  • Execute a query and count the row let query = Query([r| SELECT * FROM sqlite_master WHERE type='table' AND name='mytable' |]) listTab <- query_ conn query :: IO [SqliteMaster] if length listTab > 0 then print "mytable is found" else "mytable is not found"  #### 0.0.109 Haskell Database connection code in three databases: Sqlite, Mysql and Postgresql #### 0.0.110 Fixed error inside javadoc script with -classpath # it works. javadoc -classpath "/somejar/*:/MyClass:." # it does not work. javadoc -classpath /somejar/* ...  #### 0.0.111 gcc clang c++ compiler flags: Reference • C++ build script cppcompile.sh • Add include or multiple includes paths. • $$\mathbf{-I} \Rightarrow$$ specifify a <include> directory g++ -I/myinclude -o myfile myfile.cpp # multiple includes g++ -I/include1 -I/include2 -o myfile myfile.cpp  • $$\mathbf{-l} \Rightarrow$$ link to shared library or shared object file such as .dll in Window and .so in Linux .dylib in MacOS g++ -std=c++14 -O3 -Wall -pedantic recurveFileBoost.cpp -lboost_filesystem -lboost_system  • $$\mathbf{-L} \Rightarrow$$ specificy a <lib> directory • $$\mathbf{-g} \Rightarrow$$ turn on debug(so GDB gives more friendly output) • $$\mathbf{-c} \Rightarrow$$ output an object file (.o) • $$\mathbf{-o} \Rightarrow$$ name the output • $$\mathbf{-Wall} \Rightarrow$$ turn on most warning • -pendantic or -Wpendantic $$\Rightarrow$$ Issues all warning required by ISO C and ISO C++ standard, it issues all warning whenever there are compiler extensions non compilant to ISO C or C++ standard. • When you use new C++ library, you need to add Header search paths and Library search paths in XCode. • I try to use C++ boost library and add Header search paths and Library search paths in XCode. • I still get linking error, symbol not found • When you get this kind of error, generally you try to Google the error and hopefully you will find the solution. • It is hard to know what the Xcode is doing behind the sense when you get weird error. • I use home brew to install C++ boost library on my MacOS, the head location and libraries location are: # header location /usr/local/Cellar/boost/1.61.0_1/include # libraries location /usr/local/Cellar/boost/1.61.0_1/lib  • The recurveFileBoost.cpp can be built with following g++ command line # file:///Users/cat/myfile/bitbucket/cpp/recurveFileBoost.cpp cd$b/cpp
g++ -std=c++14 -O3 -Wall -pedantic recurveFileBoost.cpp -lboost_filesystem -lboost_system


#### 0.0.112 Wrote a simple function to remove whitespaces from file names and directories.

• Recurve from a given directory and use depth first search to traversal.
• If file is found, then use file.replace(' ', '') to remove whitespace.
• If directory is found, then recurve into the directory.
• If return from a directory, then dir.replace(' ', '')

#### 0.0.113 Python does not have block comment?

• You can comment out block of code in Python?
• Do not understand the rational behind that.

#### 0.0.114 Why map, filter and reduce or fold are unusual in Python?

• Why do we need the list() to wrap the map and filter functions.
list(map(lambda x: x > 1, [1, 2, 3]))
list(filter(lambda x: x % 2 == 0, [1, 2, 3]))

• reduce is a bit better, or fold in Haskell terminology.

from functools import reduce
reduce(lambda acc, x: acc + x, [1, 2, 3], 0) => 7

• map can be used like zipWith in Haskell

list(map(lambda x, y: x + y, [1, 2, 3], [3, 4, 5]))


#### 0.0.115 There are many nice features in Python

• List is awesome.

ls = [1, 2, 3]
ls[:1] => [1]
ls[1:] => [2, 3]
ls[:1] + ls[1:] => [1, 2, 3]
ls[:-1]  => [1, 2]
ls[-1:]  => [3]
ls[::-1] => reverse [3, 2, 1]


#### 0.0.116 Complex number division

• let $$c \in \mathbb{C}$$
\begin{align*} c_1 &= x_1 + y_1 i \\ c_2 &= x_2 + y_2 i \\ \frac{c_1}{c_2} &= \frac{ x_1 + y_1 i }{ x_2 + y_2 i } \\ \frac{c_1}{c_2} &= \frac{ (x_1 + y_1 i) (x_2 - y_2 i) } { (x_2 + y_2 i)(x_2 - y_2 i)} \\ \frac{c_1}{c_2} &= \frac{ (x_1 x_2 + y_1 y_2) + (x_2 y_1 - x_1 y_2) i } { x_2^{2} + y_2^{2} } \\ \frac{c_1}{c_2} &= \frac{ x_1 x_2 + y_1 y_2 }{ x_2^{2} + y_2^{2} } + \frac{ x_2 y_1 - x_1 y_2 }{ x_2^{2} + y_2^{2} } i \\ \end{align*}

#### 0.0.117 I just learn Complex number has something called rectangular form which is the standard form that is used in high school.

• $$x + y i$$ is rectangular form.
• $$r(\cos \beta + i \sin \beta)$$ is the polar form

#### 0.0.118 Apparently, Haddoc does not generate the right index.html file with many Haskell modules.

• Create an haskelldocindex.html file under $b/public1file/haskelldoc_index.html • Symbol link the file to $ht/../htmlhaskelldoc/index

#### 0.0.119 VSCode has autocomplete out of the box. Is works for java at lease. It seems to me VSCode is can be replaced Vim and Emacs soon.

• Keybinding is supper easy. VSCode configure file
• Edit the keybinding.json file.
• Java autocomplete is working for SDK and external jar files.
• I have been the vim user for many years but I never use Java auto complete because it is painful to install those plugins.
• VSCode supports autocomplete out of the box so far but I have not tried other libraries. but Java SDE API is working so far. All the following can be autocompleted.

Map<String, String> map = new HashMap<String, String>();
Set<String> set = new HashSet<String>();

• Autocomplete can be used in many languages such as C++, Java and Python.
• It is very easy to configure keybinding.
• You can install many packages like Emacs. searching and click install.
• There are lots of nice themes.
• VSCode is not perfect so far.
• I try to configure VSCode to search inlcude CPP header files.
• First, I try add the includePath in the settings.json, but it failed to find my namespace under AronLib.h
• Second, I try to add c_cpp_properties.json under .vscode directory and it failed to find header file AronLib.h

#### 0.0.120 VSCode. Finally I found out how to add your own jar file to VS Code

• Initially I though the .classfile is in the VS Code workspace directory and VSCode can not detect my own jar file.
• Finally I realize .classpath should be in home directory. I did not see anyone mention that on stackoverflow at all.
• The content of .classfile can be similar the following:
• You need to have xxx.code-workspace file in order to build and compile.
• Stupid thing about VSCode is the directory for jar files has to be called lib under your workspace. No clue.. why.
• You might be able to change the name somewhere. Ask MS.

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="lib" path="/Users/cat/myfile/bitbucket/javalib/jar"/>
<classpathentry kind="lib" path="lib/commons-io-2.5.jar"/>
</classpath>

• Actually it is not ture for above .classfile. Apparently it does not need .classfile if there is lib/myjar.jar in the workspace directory.
• I can do autocomplete for my own jar file, but I got compiler error. The error indicates I use older JDK or Runtime environment with newer version class file.
• TODO: No clue how to fix it right now.
• The weird thing is I can use my current java compiler javacompile.hs to compile and run the same source java file.
• It means VSCode uses an older version of java compile which might be java 8 compiler.

java -XshowSettings:properties -version


#### 0.0.121 VSCode Cpp/C++/clang++/g++ development in MacOS

• Output executable file, ex: Cpp option -o

• g++ -o HelloWorld HellWorld.cpp
"${fileBasenameNoExtension}",  • Cpp Compiler #MacOS "command" : "clang++" # or "command" : "g++"  • Include library -I /usr/local/Cellar/boost/1.61.0_1/include  • Two Liking libraries: -lboost_filesystem and -lboost_system • Here is tasks.json file for MacOS { "version": "2.0.0", "tasks": [ { "label": "Build with Clang", "type": "shell", "command": "clang++", "args": [ "-std=c++14", "-stdlib=libc++", "-I /usr/local/Cellar/boost/1.61.0_1/include", "-lboost_filesystem", "-lboost_system", "${file}",
"-o",
"${fileBasenameNoExtension}", "--debug" ], "group": { "kind": "build", "isDefault": true }, "problemMatcher": [ "$gcc"
]
}
]
}

• What is on the tasks.json
• What is on the c_cpp_properties.json
• It is really painful to setup VSCode to compile Cpp code.
• From SO, you need to setup c_cpp_properties.json and tasks.json
• I follow some tutorial in SO but itt is still not working. Unfortunately it is just a "Hello world" with including a library.
• I got following error Error
• Actually when run it in "Run Task", VSCode will run whatever on your current window. VSCode does not know what file they should run.??
• It works at least.
• Working example under \$b/cpp/vscode/tryreadfile

#### 0.0.122 Try to install setup VSCode for Haskell right now.

• The main objective is to autocomplete Haskell code.
• It does not work for me when I install Haskero inside VSCode, it seems to me I have to install from command line.

stack build intero  --copy-compiler-tool

• Install intero right now. intero
• You need to add your stack project to as workspace in VSCode, this is the most important step.
• It can autocomplete source code so far.
• You can click on stack build, stack run and stack test

#### 0.0.123 Haskell Intero for Emacs.

• Intero is the best package out there for Haskell. Intero
• autocomplete, defintion and type checking
• Intero can autocomplete paths too:)
• Add a few lines to dotemacs file.
(exec-path-from-shell-initialize)
(package-install 'intero)


#### 0.0.124 An 64 years old math problem is solved by a super computer.

• Find an Integer solution for $$x^3 + y^3 + z^3 = 42$$
• It seems to be an easy problem but no one can find a solution or prove there is no solution for the eqation.
x = -80538738812075974
y = 80435758145817515
z = 12602123297335631
if x**3 + y**3 + z**3 == 42:
print("x^3 + y^3 + x^3 = 42")
else
print("x^3 + y^3 + x^3 != 42")


#### 0.0.125 Terence Tao and Collatz Conjecture

$$f(n) = \begin{cases} n/2 &\quad \mbox{ if n is even} \\ 3n + 1 &\quad \mbox{ if n is odd} \end{cases}$$

• Terence Tao posted a partial solution on Collatz Conjecture

#### 0.0.126 Java boxing and unboxing

int m = 3;
Integer n = m;
List<Integer> list = new ArrayList<>();
for(int i=0; i<10; i++)


#### 0.0.128 It is almost impossible to clear up browser data from Google Chrome.

• If you want to relod the new CSS file from Chrome. Clear up browser data is not enough.
• I have no clue to reload the new CSS files from Chrome when you try to inspect your html source.

## 1 VSCode and Python

#### 1.0.1 VSCode For Python on MacOS.

• VSCode supports many languages out there. Python is one of them. VSCode has many nice features.
• VSCode has many nice themes to beautify your code.
• Autocomplete
• Run Test inside your VSCode.
• VSCode can detect all the Python versions on your sytem so that you can choose which version to run you code.
• How to run Python inside your VSCode? it is easy.

• Press F1 Key to the Command Pallet and type Run Python File in Terminal
• Assume you have installed Python interpeter on your machine.

## 2 Emacs Elisp Tutorial

#### 2.0.1 Install Common Lisp on MacOS

brew -v install clisp
# start Common Lisp
clisp
# try Common Lisp
>(+ 1 2)


#### 2.0.2 Run your lisp script from command line

clisp mylisp.lisp


#### 2.0.3 Emacs Elisp: Hello World

;; print and echo do not work
(message "Hello World")


#### 2.0.4 Emacs Elisp: get buffer name

;; insert buffer name to current cursor position
(insert (buffer-name))


#### 2.0.5 Emacs: Elisp: kill a buffer by name

• Kill a scratch buffer.
(kill-buffer "*scratch*")


#### 2.0.6 Emacs Elisp: get all buffer names

• insert all buffer names to current cursor position
(insert (buffer-list))


#### 2.0.7 Emacs Elisp: switch to other buffer

• Switch to scratch buffer
(switch-to-buffer "*scratch*")


#### 2.0.8 Emacs Elisp: data type:

• string, number, symbol and list etc.
• list type
(A 2 "A")            ; A list of three elements.
()                   ; A list of no elements (the empty list).
nil                  ; A list of no elements (the empty list).
("A ()")             ; A list of one element: the string "A ()".
(A ())               ; A list of two elements: A and the empty list.
(A nil)              ; Equivalent to the previous.
((A B C))            ; A list of one element
;   (which is a list of three elements).


#### 2.0.9 Emacs Elisp: evaluate body forms sequentically and return value of last one.

;; define a function
(defun ins (cmd) (insert (shell-command-to-string cmd)))

;; call the function ins
(progn
(switch-to-buffer-other-window "file.x")
(erase-buffer)
(ins "ls"))


#### 2.0.10 Emacs Elisp: define a function

• Define a function on Elisp

  (defun  myfun (cmd)
(insert (shell-command-to-string cmd)))

;; call the function
myfun "ls"


#### 2.0.11 Emacs Elisp: mapcar

• mapcar over a vector
;; mapcar over a vector
(mapcar '1+ [1 2 3]) ;; => [2 3 4]

• mapcar over a list
(mapcar '1+ '(1 2 3)) ;; => (2 3 4)


#### 2.0.12 Emacs Elisp: switch to other buffer

• switch-to-buffer-other-window
(switch-to-buffer-other-window "buffer-name")


#### 2.0.13 Emacs Elisp: insert string in cursor

• insert
(insert "Hello")


#### 2.0.14 Emacs Elisp: run shell command function

• shell-command-to-string
(insert (shell-command-to-string "ls"))


#### 2.0.15 Emacs Elisp: Get element from a list

• elt
(mapcar (lambda (x) (elt x 0)) [[1 2][3 4]]) ;; => (1 3)


#### 2.0.16 Self-signed certificate

• Self signed certificate

#### 2.0.17 Install Rabbit Message Queue in FreeBSD

• Currently, Python 3.6 is used to run Python script.
pkg install rabbitmq
rabbitmq_enable=”YES”
# start it
sudo /usr/local/etc/rc.d/rabbitmq start
`

#### 2.0.19 realtor.com Interview question

• Find a duplicate element from a list contains $$N + 1$$ elements. the range of elements are from $$1$$ to $$N$$
• Here is the Python code Realtor.com Interview

Created: 2019-10-01 Tue 23:10

Validate