Table of Contents

  • 1. VSCode and Python
  • 2. Emacs Elisp Tutorial
  • 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 &" 
      
    • ghci does not load package into Ghci if you use :load myhaskell.hs It causes lots of confusing when you load your code inside ghci

    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.8 DONE Hair cut

    1. 17$ for the stupid hair cut.

    0.0.9 DONE Added three buttons: add, update and delete to wai.hs

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

    0.0.10 DONE Do my laundry

    0.0.11 DONE Install Vim 8.1.135, and fix symbol link with the Vim syntax.vim file error

    0.0.12 DONE Try to understand Visitor pattern in Java and Haskell Algebraic Datatypes

    0.0.13 DONE Add Redirect response to wai.hs with wai-uti

    0.0.14 DONE pushall respositories to bitbucket

    0.0.15 DONE fix resume a bit

    0.0.16 TODO Need to add more detail to resume

    0.0.17 TODO Buy a new pot and buy some rice

    0.0.18 DONE Open new paypal account

    0.0.19 DONE 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.20 DONE Send out more resumes

    0.0.21 TODO 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));
      queue.add(new Person("David", "lee"));
      queue.add(new Person("Tommy", "kee"));
      queue.add(new Person("Jacky", "kuu"));
      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.
    • Added Double linked List, delete, append and insertFront.
    • 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.22 TODO Take a look at the Algebraic Data Type and Visitor pattern in Java

    URL

    0.0.23 DONE Send out more resume, more to EA

    0.0.24 DONE Add Applescript to send notification when filewatcher detects some txt file inside password folder.

    0.0.25 DONE Finally figure out how to use multiple putStrLn in Agda

    0.0.26 DONE Refactor filewatcher.hs, remove IORef, clean up useless code

    0.0.27 DONE Added double click event: ondblclick to javascript file inside wai.hs to improve user experience.

    0.0.28 DONE 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.29 DONE Wrote a shell script to simplify gcc compilation process. $scr/gcc_compile.sh

    0.0.30 DONE Fixed an issue where is special characters are not escaped properly.

    0.0.31 DONE 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.35 DONE 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.36 DONE 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.37 DONE Added code: Post Html form, and retrieve data from Html Input box, insert data to Sqlite-simple DB.

    0.0.38 DONE Added code: Integrate Sqlite-simple to wai.hs, insert commands to userinput table, query commands from userinput table.

    0.0.39 DONE Refactored code: Clearn up some unnecessary code.

    0.0.40 DONE 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.41 DONE Integrate Ajax to wai.hs, send Json data to Server, and get response from Server in client side.

    0.0.42 DONE 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.43 DONE 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.45 DONE 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.46 DONE 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.47 DONE Create new profile in Iterm2

    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.50 DONE 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
    # update your .emacs file
    (add-to-list 'custom-theme-load-path "/Users/cat/myfile/bitbucket/emacstheme/")
    

    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.56 TODO 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);
      glLoadIdentity();
      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.

    • When you dump your public key to your swesome host, you will be asked your password again.
    • 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
      ssh-add /home/user/.ssh/myrsa 
      # On client side, add public key to authorized_keys
      cat id_rsa.pub >> autherized_keys
      # set permission
      chmod 600 autherized_keys
      

    0.0.63 Bought a FreeBSD VM 3G, 60G from Digit Ocean for $15.

    • Install GHC 8.6, and install stack
    • Install Stack Install Stack in FreeBSD

      # install GHC
      pkg install ghc
      # install haskell stack
      curl -sSL https://get.haskellstack.org/ | sh
      

    0.0.64 FreeBSD install package

    # su root
    pkg install curl
    

    0.0.65 FreeBSD apache html folder

    /usr/local/www/apache24
    

    0.0.66 FreeBSD install GHC

    pkg install ghc
    

    0.0.67 DONE Add shell script to upload file to Ubuntu and FreeBSD hosts

    • script name: $sym/upload.sh \( \Rightarrow \) $src/upload.sh using rsync command.
    • upload.sh
    # upload file.txt to xfido ~/try
    upload.sh file.txt xfido
    # upload file.txt to uwspace ~/try
    upload.sh file.txt uw 
    

    0.0.68 Rename haskellwebapp \( \Rightarrow \) haskellwebapp2

    • Create bitbucket repos: haskellwebapp2
    • Rename the Stack project \( \Rightarrow \) in .cabal file.
    • The root of running process is not src, it is haskellwebapp2

      haskellwebapp2/src/Main.hs
      

    0.0.69 Create User and Image tables in Sqlite3 database.

    • Submit submit form.
    • Database User table in Sqlit3 Data Type

      uid name email password task money
      Integer Text Text Text Text Integer
    • Database Image table

      iid imagename uid
      Integer Text Integer
    • Create Haskell records. Haskell Int64 \( \Rightarrow \) Sqlit3 Integer

      -- Data.Int64 (Int64)
      -- Haskell Int64 => Sqlit3 Integer
      data User = User{uid::Int64, name::Text, email::Text, password::Text task::Text, money::Integer} deriving (Show, Eq)
      
      data Image = Image{iid::Int64, imagename::Text, uid::Int64} deriving (Show, Eq)
      
    • How to determinate whether insection is successful or failed

      changes :: Database -> IO Int
      
      query_ conn "insect ... "
      changeRow <- changes conn
      if changeRow > 0 then print "Insection is successful"
      else print "Insection is failed"
      

    0.0.70 Insect User to Sqlite database.

    • Insect data into user table
    • Select data from user table
    • Determinate wheter insection is successful or failed with changes in Sqlite3
    • Again, use Data.RawString.QQ to simplify the String, ByteString and Text manipulation.
    • Add response page if insection is successful using Data.RawString.QQ again
    • Add list task page

    0.0.71 Add login and password validation page.

    • Add html login.html file, it is easy.
    • Add loginCheck::Connection -> Application
      • The function tries to validate email address and password.
        • Use queryNamed queryNamed , there is some issues to query any row from user table.

          queryNamed :: FromRow r => Connection -> Query -> [NamedParam] -> IO [r]
          r <- queryNamed c "SELECT * FROM posts WHERE id=:id AND date>=:date" [":id" := postId, ":date" := afterDate]
          
        • Finally I found the issue when using where cause in Sqlite Haskell.

          • I used ByteString to compare String or Text
          r <- queryNamed conn "SELECT * FROM user where password = :password" [":password" := password] :: [User]
          
          • password is a type ToField class which converts almost any type to SQLData with toField
          • I used ByteString instead of String or Text
          • Here is stupid mistaken that I made.
          -- Using ByteString "123" to compare Text
          -- Error code
          let password = case lookup "password" params of
                                 Just password -> password
                                 _             -> "No password from client."
          
          -- need to convert ByteString to Text and compare
          -- Valid code
          let password = case lookup "password" params of
                                 Just password -> strictByteStringToStrictText password
                                 _             -> "No password from client."
          

    0.0.72 Word8 and ByteString in Haskell.

    • Word8 is unsigned integer 8-bits byte. Word8
    • ByteString contains 8-bit bytes.

      -- ls contains all character from 0 to 2^8 - 1 = 255
      let ls = Data.Word8.pack [0..(2^8 - 1)]
      

    0.0.73 C++ Dangling pointer Dangling Pointer

    void remove(){
    Node* curr = new Node(10);
    Node* pt = curr;
    if(curr != null)
       delete curr;
    }
    
    • pt is a dangling pointer, there is nothing wrong with dangling pointer as long as you don't deference a dangling pointer.

    0.0.74 What is unique pointer, shared pointer and weak pointer and what is std::move in C++

    • Smart Pointer Example
    • Smart pointer is trying to help programmers to simplify memory management. Before smart pointer, programmer needs to know when to allocate memory and when to deallocate memory.
    • What is unique pointer?

      • unique pointer does not support copy, if you copy a unique pointer, then you will get compiler error.
      // no memory leak
      void fun(){
        std::unique_pt<int> pt = std::unique_pt(new int(10));
        return;
      }
      
      std::unique_pt<int> pt = std::unique_pt(new int(9));
      std::unique_pt<int> pt1 = pt;
      // pt is not longer to deference an object.       
      
      
    • How to use shared pointer?

       class MyClass{
         public:
         std::shared_pt<int> pt;
         public:
         std::shared_pt<int> create(){
           std::shared_pt<int> pt = std::shared_pt(new int(9));
           return pt;
         }
       }
      
      MyClass* cpt = new MyClass();
      std::shared_pt<int> pt = cpt -> create();
      
      if(cpt != null)
        delete cpt;
      
      // std::shared_pt<int> pt don't need to be deleted inside the MyClass
      
      
    • What is weak pointer in C++
      • Weak pointer is a shared pointer and it holds a non-owning reference to an object.

    0.0.75 Change all paths in WaiLib.hs and Wai.hs, and it run in FreeBSD so far.

    • Change symbol link to relative path, solve only half the problem.
    • DONE Add config file.
    • DONE Change localhost to real hostname.
    • DONE Install Redis on FreeBSD

    0.0.76 In FreeBSD, /usr/ports/database is not shown.

    • download port collections portsnap fetch and extract it to /usr/ports
    • Here is the link on how to use use port in FreeBSD port

    0.0.77 Install Redis in FreeBSD Redis installation on FreeBSD

    0.0.78 Haskell Enum Trick Enum Trick

    data Color
        = Red
        | Blue
        | Green
        | Yellow
        | Orange
        | Brown
        | White
        | Black
        deriving (Show, Eq, Enum, Bounded)   
    

    0.0.79 Show Maybe is a Functor Functor Maybe Proof

    0.0.80 Move GenePDFHtml to WaiLib.hs file, Create a GenePDFHtmlLib in $b/haskelllib

    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
    #+HTML_HEAD: <link rel="stylesheet" type="text/css" href="http://thomasf.github.io/solarized-css/solarized-light.min.css" />
    -- dark mode
    #+HTML_HEAD: <link rel="stylesheet" type="text/css" href="http://thomasf.github.io/solarized-css/solarized-dark.min.css" />
    
    • 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;
         padding: 1em;
     }    
    

    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

    0.0.88 Non-interactive shell and interactive shell, login shell, non-login shell.

    • 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.
      ssh cat@xfido.com  'bash /etc/profile; echo $PATH'
      
      • ssh login to cat user account and call bash to read /etc/profile. Environment variables can be used if there are any inside /etc/profile.
    • login shell is the same as interactive shell.
    • non-login shell is the same as non-interactive shell.

    0.0.89 Add new tmux.conf file for FreeBSD. Apparently the tmux.conf file is not working on MacOS.

    0.0.90 Fixed: Javadoc long term error: can not find methods. Javadoc Reference Guide

    • /dir/lib contains jar file to support java source file under /javafile
    • -classpath \(\Rightarrow\) specified the location of jar files
    • -noqualifier \(\Rightarrow\) no long qualifier name such as org.apache.commons.io.StringUtils
    • -sourcepath \(\Rightarrow\) specified the location of java files.
    javadoc -classpath  /dir/lib -noqualifier all -d /htmldoc   -sourcepath /javafile/*.java
    

    0.0.91 Add iterate all files from dir and insert them into table: test1.snippet

    0.0.92 Add isFile and isDir to javalib AronLib.java

    0.0.93 Database ACID

    • Atomicity
    • Consistency
    • Isolation
    • Durability

    0.0.94 Fixed bug: send pdf file to browser and force the browser to open it. What request header I should use?

    0.0.95 Add code to display all PDF files from a directory in Wai Server.

    • Use pathInfo instead of rawPathInfo
    • Use Haskell powerful pattern matching.

      case pathInfo request of
          ("pdf":fn:_)  -> routing to whatever you want
      

    0.0.96 Wai API for query string, it is nice function to match string from client

    • If the request string is /dir/file.pdf
    • pathInfo can be used to (split ⇒ splitBS) BS.ByteString info parts and pattern matching can be used in different parts.

      pathInfo::BS.ByteString -> [Text]
      
      case pathInfo request of
         ("pdf":_)    -> routing to "http://xfido.com/pdf"
         ("pdf":fn:_) -> routing to "http://xfido.com/pdf/myfile.pdf"
         _            -> routing to "other universe"
      

    0.0.97 Understand logic implication table

    • Why implication and contrapositive table defines the way it is?
    P Q \(P \Rightarrow Q\) \(Q^\lnot\) \(P^\lnot\) \(Q^\lnot \Rightarrow P^\lnot\)
    T T T F F T
    T F F T F F
    F T T F T T
    F F T T T T
    • Example: If \(a^2 + b^2 = c^2 \Rightarrow a, b, c\) forms a right triangle. Pythagorean Theorem
      • If \(a, b, c\) are not a right triangle \(\Rightarrow a^2 + b^2 \neq c^2\)
      • \(n \in \mathbf{N} \rightarrow 2n \in \mathbf{N}\) \(\Rightarrow\) if \(2n\) is not an integer then \(n\) is not \(\mathbf{N}\)
      • \((P \rightarrow Q) \Rightarrow (Q^\lnot \rightarrow P^\lnot)\)

    0.0.98 Why Lombok sucks? please read the Reddit Lombok in Reddit

    • You are likely missing the plugin in Intellij if you use Lombok to generate setter and getter.
    • You will spend more time on debugging the Lombok than writing code.
    • Setter, Getter, Equal, toString and hashCode methods can be generated from IDE.
    • In practice, you don't use those methods that often.

    0.0.99 Haskell code to generate latex code tryfm.hs

    A \(\mathscr{A}\) \(\mathfrak{A}\) a \(\mathscr{a}\) \(\mathfrak{a}\)
    B \(\mathscr{B}\) \(\mathfrak{B}\) b \(\mathscr{b}\) \(\mathfrak{b}\)
    C \(\mathscr{C}\) \(\mathfrak{C}\) c \(\mathscr{c}\) \(\mathfrak{c}\)
    D \(\mathscr{D}\) \(\mathfrak{D}\) d \(\mathscr{d}\) \(\mathfrak{d}\)
    E \(\mathscr{E}\) \(\mathfrak{E}\) e \(\mathscr{e}\) \(\mathfrak{e}\)
    F \(\mathscr{F}\) \(\mathfrak{F}\) f \(\mathscr{f}\) \(\mathfrak{f}\)
    G \(\mathscr{G}\) \(\mathfrak{G}\) g \(\mathscr{g}\) \(\mathfrak{g}\)
    H \(\mathscr{H}\) \(\mathfrak{H}\) h \(\mathscr{h}\) \(\mathfrak{h}\)
    I \(\mathscr{I}\) \(\mathfrak{I}\) i \(\mathscr{i}\) \(\mathfrak{i}\)
    J \(\mathscr{J}\) \(\mathfrak{J}\) j \(\mathscr{j}\) \(\mathfrak{j}\)
    K \(\mathscr{K}\) \(\mathfrak{K}\) k \(\mathscr{k}\) \(\mathfrak{k}\)
    L \(\mathscr{L}\) \(\mathfrak{L}\) l \(\mathscr{l}\) \(\mathfrak{l}\)
    M \(\mathscr{M}\) \(\mathfrak{M}\) m \(\mathscr{m}\) \(\mathfrak{m}\)
    N \(\mathscr{N}\) \(\mathfrak{N}\) n \(\mathscr{n}\) \(\mathfrak{n}\)
    O \(\mathscr{O}\) \(\mathfrak{O}\) o \(\mathscr{o}\) \(\mathfrak{o}\)
    P \(\mathscr{P}\) \(\mathfrak{P}\) p \(\mathscr{p}\) \(\mathfrak{p}\)
    Q \(\mathscr{Q}\) \(\mathfrak{Q}\) q \(\mathscr{q}\) \(\mathfrak{q}\)
    R \(\mathscr{R}\) \(\mathfrak{R}\) r \(\mathscr{r}\) \(\mathfrak{r}\)
    S \(\mathscr{S}\) \(\mathfrak{S}\) s \(\mathscr{s}\) \(\mathfrak{s}\)
    T \(\mathscr{T}\) \(\mathfrak{T}\) t \(\mathscr{t}\) \(\mathfrak{t}\)
    U \(\mathscr{U}\) \(\mathfrak{U}\) u \(\mathscr{u}\) \(\mathfrak{u}\)
    V \(\mathscr{V}\) \(\mathfrak{V}\) v \(\mathscr{v}\) \(\mathfrak{v}\)
    W \(\mathscr{W}\) \(\mathfrak{W}\) w \(\mathscr{w}\) \(\mathfrak{w}\)
    X \(\mathscr{X}\) \(\mathfrak{X}\) x \(\mathscr{x}\) \(\mathfrak{x}\)
    Y \(\mathscr{Y}\) \(\mathfrak{Y}\) y \(\mathscr{y}\) \(\mathfrak{y}\)
    Z \(\mathscr{Z}\) \(\mathfrak{Z}\) z \(\mathscr{z}\) \(\mathfrak{z}\)

    0.0.100 Anonymous function in c++ and Lambda function in Haskell.

    • Pass lambda function to a function in C++.
    • Use std::function to define a function called even
    • Create a filter function similar to Haskell filter

      std::function<int(bool)> even = [](auto x) = { return  x % 2 == 0;};
      
      template<class T>
      vector<T> filter(std::function<bool(T)> f, vector<T> vec){
         vector<T> retV;
         for(auto t : vec){
            if(f(t))
              retV.push_back(t);
         }
      }
      
      vector<int> vec = {1, 2, 3};
      vector<int> vecInt = filter(even, vec);
      
      
    • But you can not do following:

      vector<int> vec = {1, 2, 3};
      auto f = [](auto x){ return x % 2 == 0;};
      vector<int> filter(f, vec);
      
      • \( \because \) auto f is not the same type as std::function
    • Use template<typename Fun, typename T> to solve above limitation.

      template<typename Fun, typename T>
      vector<T> filter(Fun f, vector<T>& vec){
         vector<T> retv;
         for(auto e : vec){
            if(f(e))
              retv.push_back(e); 
         }
         return retv;
      }
      
    • We can pass auto f=... or std::function<bool(T)> f = .. to the new filter function.

      auto f = [](auto x) { return x % 2 == 0;};
      // or 
      std::function<bool(T)> f = [](auto x){ return x % 2 == 0;};
      
      vecotor<int> vec = {1, 2, 3};
      vector<int> filter(f, vec);
      
      • Some comments suggest the following code Lambd Function in C++

        auto f = [](auto x) { return !(x & 1);};
        // nice, but it might introduce bug in the future.
        // e.g. if I need module of 3, 5, ..., the whole function needs to be rewritten.
        
    • In Haskell, the solution is much more elegrant.

      let list = [1, 2, 3];
      filter(\x -> x `mod` 2 == 0) list
      
    • std::transform is similar to map in Haskell.
    • But std::transform is too verbal, e.g.

      vector<float> vec = {1.2, 4.9};
      std::transform(vec.begin(), vec.end(), vec.begin(), [](auto x) { return x + 1;});
      // vec = {2.2, 5.9}
      
    • In Haskell

      let vec = [1.2, 4.9]
      let v = map (+1) vec
      
    • If we want to convert all the floats to strings.

        vector<float> vec = {1.2, 4.9};
        vector<string> vecStr;
        std::transform(vec.begin(), vec.end(), std::back_inserter(vecStr), 
                  [](auto x) { 
                       return std::to_string(x);
                  }
                 );
      // vecstr contains strings
      
    • I still have no idea what is std::backinserter() from the doc.std::backinserter
      • I assume std::backinserter() all the return value from lambda function from the beginning of iterator
    • I try to implement mapX function like map in Haskell.

      template<typename Fun, typename T, typename D>
      vector<D> mapX(Fun f, vector<T> vec){
          std::vector<D> vecD;
          std::transform(vec.begin(), vec.end(), std::back_inserter(vecD), f);
          return vecD;
      }
      
      • But it seems to me typename D can not deducted from \(\lambda\) function Fun \(f\)
      • Some users suggests me to use some C++17 features C++17 typetraits

    0.0.101 C++ return by reference or return by value.

    • Wrong way to use reference in C++
    // return by reference.                
    vector<int>& fun(){                    
         vector<int> vec = {1, 2, 3};      
         return vec;                       
    }                
    
    vector<int> v = fun();                      
    
    • Why the code above is wrong?
      • fun() only returns the address of vec, not a copy of vec
      • After the function fun() return, object vec will be deleted because vec is local variable and it is inside the stack. The caller will lose the data in vec.
      • v hold the address to vec, but the data inside vec will be deleted after fun() return.
      • copy constructor will be called to do the copy for vector<int>
    // return by value.
    vector<int> fun(){
      vector<int> vec = {1, 2, 3};
      return vec;
    }
    
    vector<int> v = fun();
    
    • Code above is OK beacuse fun() return a copy of vec
    • v will have the copy of vec

    0.0.102 Return by reference or const reference

    • What is the different between return const int& fun() and int& fun() in a function.
    • const int& fun() \( \Rightarrow \) it means you can assign value to fun()
    • int& fun() \( \Rightarrow \) it means you can NOT assign value to fun()
    int& fun(){
      int var = 1;
      return var;
    }
    // in main
    fun() = 3;  // OK, does not do anything useful.
    
    const int& fun(){ 
       int var = 1; return var;
    }
    // in main
    fun() = 3;  // Error: can not assign value to const int& which is rvalue I think.    
    
    • return by reference is useful if you overload [] operator on an array of objects.

      class Object{
        int num;
      };
      
      class ArrayObject{
      
         Object& operator[](const int& index);
      }
      
      // in main
      Object o();
      arrayObj[1] = o;
      
      

    0.0.103 Passed by value and reference or const reference

    • Passed by value:

      vector<int> even(vector<int> vec){
        vector<int> ret;
        for(auto e : vec){
           ret.push_back(e);
        }
        return ret;
      }
      
    • vec will be copied inside the stack, if vec contains lots of data, then it will be not very efficient.
    • Passed by reference, vec passes it memory address to function even()

      vector<int> even(vector<int>& vec){
         vector<int> ret;
         for(auto e : vec){
           ret.push_back(e);
         }
         return ret;
      }
      // inside your main
      vector<int> vec = {1, 2, 3};
      even(vec) // no problem.
      
    • Code above is better because vec will not be copied inside the function even(). even() will use the address of vec to access the data in vec.
    • Passed non-constant reference to a function.

      • vector<int>& is non-constant reference \( \Rightarrow \) I hope this is the right name.
      vector<int> even(vector<int>& vec){
        vector<int> ret;
        for(auto e : vec){
           ret.push_back(e);
        }
        return ret;
      }
      
      vector<int> fun(){
         vector<int> v = {1, 2, 3};
                 return v;
      }
      
      // inside your main
      even(fun)  // compile error
      
    • Apparently, fun return a const vector<int>& but not vector<int>&

      • In order to make above code to work, the signature of even(..) has to be changed as following:
      vector<int> even(const vector<int>& vec)
      
      • Signature above is not a perfect solution and following code will not work.

        • vec can be modified.
        vector<int> vec = {1, 2, 3};
           void fun(const vector<int>& vec){
                vec.push_back(1);
           }
        

    0.0.104 Find the square root of a float point number: \(n\)

    • The idea is to find the square root of a float point number is equivalent to solve a equation \(n = x^2\) where \(n\) is given, find \(x\)
    • Choose a point \( x = x_0 \) from \( y = x^2 - n \) where \( y = 0 \)
    • We know the derivative of \( y = x^2 - n \) is \(2x\), then we can find the slop \(2x_0\) of a line which passes a point \( (x_0, (x_0)^2 - n)\)
    • The equation of the line is
    • \( \frac{y - (x_0^2 - n)}{ x - x_0} = 2x_0 \Rightarrow \frac{y - (x_0^2 - n)}{2x_0} = x - x_0 \)
    • where \(y = 0 \Rightarrow x = x_0 + \frac{n - x_0^2}{2x_0} \Rightarrow x_1 = x_0 + \frac{n - x_0^2}{2x_0} \)
    • C++ code: Square Root of Integer

      /***
       *
       * Newton' method to find the square root of any positive float point number. 
       */
       double sqrt(double n){
         double x0 = n + 10;
         double x = x0;
         while(fabs(x*x - n) > 0.00000001){
          x = x + (n - x*x)/(2*x);
         }
         return x;
       }
      

    0.0.105 Find the nth root of a float point number: \(c\)

    • Same idea can be used from above.
    • let \(x_0\) is the initial point and we try to solve \( c = x^n \Rightarrow f(x) = x^n - c \) where \( f(x) = 0 \)
    • The derivative of \( f(x) \) is \( nx^{n-1} \)
    • A line passes \( (x_0, f(x_0) \) and its slop is \( nx^{n-1} \)
    • The line equation is \( f'(x_0) = n(x_0)^{n-1} = \frac{y - f(x_0)}{x - x_0} \)
    • \( \Rightarrow x = x_0 - \frac{f(x_0)}{n(x_0)^{n-1}} \) where \( y = 0 \) because we need to solve \( 0 = x^n - c \) for \(x\)
    • Search nthRoot in C++

    0.0.106 Change the file GenePDFHtml.hs file, but it can not be built any more.

    The project in $HOME/try/hs can be built, and one in FreeBSD can be built too. The old the version should not be used any more because many cods has been changed.

    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
            } deriving(Eq, Read, Show)
      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
      
    • XCode add include header, library and linker in setting.

      cppheader_library_search.png

      cpplinker.png

    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.
    • Find out all about your java stuff on your machine with following command

      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.??
    • Add linking library to VSCode, adding to tasks.json file with trial and error.
    • 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.
      • Install Haskero Haskero 1.31

        stack build intero  --copy-compiler-tool 
        
    • Install intero right now. intero
    • Find your package Haskero inside your VSCode package Window and Enable Haskero again.
    • 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

    vscodehaskell.png

    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)
    (add-hook 'haskell-mode-hook 'intero-mode)
    
    • Open your stack project and you are ready to go.

    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++)
       list.add(i);   // lots of boxing
    

    boxingunboxing.jpg

    0.0.127 Apple finally was unveiling iPhone 11, iPhone 11 Pro and iPhone 11 Pro Max without 5G cellular service.

    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.

      vscode_python.png

    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
    # edit /etc/rc.conf, add following
    rabbitmq_enable=”YES”
    # start it
    sudo /usr/local/etc/rc.d/rabbitmq start
    

    2.0.18 Rabbit Message Queue from Pivotal

    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

    Author: cat

    Created: 2019-10-01 Tue 23:10

    Validate