Table of Contents

  • 1. VSCode and Python
  • 2. Emacs Elisp Tutorial
  • 3. Other Stuff
  • 0.0.1 Visited Coquitlam Center (Indoor shopping mall with rustic touches)

    • The shopping mall is big


    • Port Mann Bridge


    0.0.2 Game is on, World Cup Qualifer: Canada vs El Salvador, Canada won again 2-0

    • Game starts at 600pm PT today.
    • We will see how far Canada can go?
      • Can we get any three pts?
      • Canada VS El Salvador 2-0, Canada get more three pts today.
    • I never know there is country called El Salvador before.

    Republic of El Salvador, it is in central America. The capital is San Salvador. The offical language is Spanish.
    The population is around 6 millions in 2021


    • Other teams in Central America: Guatemala, Honduras, Costa Rica, etc.


    0.0.3 Link data to Beds24 from Expedia

    • If you want to link the data in your Expedia account then you need need to Enable the settings inside your Expedia account
    • Here is screenshot to do so.

      • Login to your Expedia Partner central account
      • Goto → Rooms and rates → Connectivity provider guide
      • Add Beds24 the input box


    • We have activated account in Beds24 so far
      • Next, how to link the data inside my Old Beds24 to New beds24 account
    • Here is the link how to import data from Old Beds24 to new Old Beds24 for booking

    0.0.4 Canada VS USA World cup qualifier Today, it is big game but there is NO live stream online.

    • Canada are not willing to let Canaidan watch free live soccer game online?
    • I can not find any free stream video online, either you have to sign up or pay for it.
    • It seems to me OneSoccer stream the live match but you have to pay for it.
    • Good news, Canada won over 2-0 against USA, it is big win. Currently, Canada has 22 pts on top the chart.
    • There are four more matches in the next two months
    Country Country Date
    Canada El Salvador Web, Feb2
    Canada Costa Rica Mar, 24
    Canada Jamica Mar, 27
    Canada Panama Mar, 20
    • Point table (Saturday, 05 February 2022 01:33 PST)
    country point
    Canada 25
    US 21
    Mexico 21
    Panama 17
    Costa Rica 16
    El Salvador 9
    Jamaica 7
    Honduras 3

    0.0.5 How to get free signed certicate on your site for HTTPS

    • LetEncrypt provides free signed certicate for your VPS
    • It only took five minutes to install the certbot on my Ubuntu 20.x.
    • Here are the steps to install certbot from certbot

      • Update snapd on your Ubuntu (This is my first time to use snapd to install app on Ubuntu)
      sudo snap install core; sudo snap refresh core
      • Remove certbot from Ubuntu
      sudo apt-get remove certbot
      • Install Certbot
      sudo snap install --classic certbot
      • Symbolic-link Certbot
      sudo ln -s /snap/bin/certbot /usr/bin/certbot
      • Let Certbot to get the certificate and edit your apache configuration file
      sudo certbot --apache
      • I belive 000-default.conf is been modified by Certbot
      • Restart my Apache
      sudo systemctl restart apache2
      • It works
    • Lift is not always perfect.
      • All the videos on my site can NOT be streamed anymore after install the Certbot
      • I have no idea how to debug it.
        • Reload the browser on the vidoe page, it works again:), I have no clue why.
    • Mixed content issue in your HTML file or CSS, Javascript from remote host
    • If you have image link like the following, then you still get warning message on Firefox
    <a href="">image</a>
    • You need to change HTTP to HTTPS
    <a href="">image</a>

    0.0.6 Happstack installation for web server

    • Download installation , it is like Apache
    cabal intall
    cabal install happstack-server
    • Haskell first app using happstack-server, Here is happstack
    module Main where
    import Happstack.Server (nullConf, simpleHTTP, toResponse, ok)
    main :: IO ()
    main = simpleHTTP nullConf $ ok "Hello, World!"
    • Build your app
    ghc --make -threaded HelloWorld.hs -o helloworld
    curl http://localhost:8000
    • Build and Run the HelloWorld is very easy but it is painful to build a bit complicated app.

    I still can not build the simple app from happstack website. I try different resolvers from ghc-7.x to ghc-9.x.
    and the conflic still can not be resolved.

    Happstack has nice documentation but we can not build the simplest example from them.(I can build HelloWorld.)
    I wish they put all the exmaples in Stack build App so that we can just get clone the examples and build it.

    • What I learn from above installation process?
      • You can add the following to your stack.yaml to use the newer version package in your stack build
    allow-newer : true
    • Build conflic diagram
             /      \
    xx   ()            ()  hslogger
            \        /
            (v1,   v2)
     network-1.x   network-2.x
                  + → Here is the conflic

    0.0.7 Fixed alias conflic in Shell. How to check alias conflic in Shell

    • Check whether an alias exist or not
    # check whether alias 'bm' exist in Shell
    # 0     => Yes
    # Not 0 => No
    v=$(alias bm &> /dev/null; echo $?) ; echo $v

    0.0.8 ctags and etags

    • For Cpp/C file, ctags generates betters tags file

      ctags -e -f $PWD/TAGS $cpplib/AronLib.h $b/clib/AronCLibNew.h
      void pp(string msg0, float num){pp410,8363
    • But etags can not use -e option, function name is missing

      # ERROR
      # etags -e -f $PWD/TAGS $cpplib/AronLib.h $b/clib/AronCLibNew.h
      etags -f $PWD/TAGS $cpplib/AronLib.h $b/clib/AronCLibNew.h
      static string takeWhile(602,11839

    0.0.9 Update printBox codein Haskell

    • printBox can be use color 255 color

      printBox 4 "dog cat" 200
      # 4 => 4 tabs
          # 200 => Red color

    0.0.10 Added colorfgStr and colorbgStr in AronModule.hs

    printf '\x1b[38;5;200mHello\x1b[0m'  # Hello in Red

    0.0.11 Latex special character

    \begin{pmatrix} \# & \$ & \% & \& & $\textasciitilde$ & \_ & \^ & \\ & \{ & \} \end{pmatrix}

    0.0.12 OpenGL GLSL

    • GLSL is some little programs inside GPU
    • GLSL proess some inputs and product some outputs
      #version version_number
      in type in_variable_name1
      in type in_variable_name2
      out type out_variable_name
      void main(){
    // process input, do something
    // output stuff to output variables
    out_variable_name = after_process_stuff()

    0.0.13 Window manager on MacOS

    • Try to search some Window manager for macOS in Reddit,
    • Someone just suggest a Window manager called Rectangle for macOS.
    • I download it and try it, it works.
    • You can bind your shortcut key to move your current top window around.
    • Move up, down, left, right etc.
    • It is free.

    0.0.14 Reduce png file to smaller size

    • pngquant or you need to home brew install it

      brew install pngquant
      • png files under $www/pdf can be reduced 40% in total size
      57720K - 34213K = 23507K

    0.0.15 Split PDF file into pages

    • Use Python using

      under $b/python/ 

    0.0.16 Fixed Intuo Tablet issue. Wacom driver does not work in Big Sur in the first time installation

    • Wacom website says the Intuo Tablet shold be still supported in Big Sur 11.x
    • I download the driver again (CTL-480 2013) (Intuo Pen S 2013) CTL-480 and install it.
    • After I install the driver and I did not see the light on on the tablet, I switch the USB to other USB-C on my MacBookPro and the light is on again. Finally, it works again on the new MacBook Pro.

    0.0.17 Mutt: Setup Mull for Gmail, the following setting is in MacOS Big Sur 11.5.2

    • Download install mutt

      brew install mutt
    • You need install Cyrus SASL for authentication

      brew install cyrus-sasl
    • create directories under HOME

      mkdir -p ~/.mutt/cache/headers
      mkdir ~/.mutt/cache/bodies
          mkdir ~/.mutt/cache/certificates
    • Add configure file muttrc

      touch ~/.mutt/muttrc
          vim ~/.mutt/muttrc
    • muttrc should include following, replace david00 to your Gmail

      # -------  IMAP ---------
      set ssl_starttls = no
      set imap_user =
      set imap_pass = Gmail_password
      set spoolfile = imaps://
      set folder = imaps://
      set record="imaps://[Gmail]/Sent Mail"
      set postponed="imaps://[Gmail]/Drafts"
      set mbox="imaps://[Gmail]/All Mail"
      set header_cache = "~/.mutt/cache/headers"
      set message_cachedir = "~/.mutt/cache/bodies"
      set certificate_file = "~/.mutt/certificates"
      # ----  SMTP  ----
      set smtp_url = "smtp://"
      set smtp_pass = $imap_pass
      set ssl_force_tls = yes # Require encrypted connection
      set smtp_authenticators = 'gssapi:login'
      # ----  Composition ----
      set editor = "vim"      # Set your favourite editor.
      set edit_headers = yes  # See the headers when editing
      set charset = UTF-8     # value of $LANG; also fallback for send_charset
      # Sender, email address, and sign-off line must match
      unset use_domain        # because joe@localhost is just embarrassing
      set realname = "david"
      set from = ""
      set use_from = yes
    • Change setting in your Gmail account for Less Secure App Access Less Secure App Access


      • Google might DISABLE your settting automatically if you try to connect your Gmail with mutt, then they send you warning in email. So you have to re-enable it.
      • Enable IMAP in Gmail setting


    • It is time to test Mutt in command line


    0.0.18 Mutt: Send email from command line as a backup tool

    • Use mutt to send attached file to Gmail account for backup
    • SO
    mutt -s "files[CONFIDENTIAL]" -a /tmp/file.txt < /dev/null --
    • -a as attachment

    0.0.19 MacOS: Enable ssh login at startup in MacOS

    • Apple makes it extremely hard to Enable ssh login at startup
    • You think you can enable ssh login in the sharing under System References Yes, it does enable ssh login but it will be gone after the computer is rebooted.
    • You are looking for some setting in System References? Well, you can not find any, it is time to Google it.
    • Here is command line to Enable ssh login at startup
    • Edit your ssh.plist file
    sudo vim /System/Library/LaunchDaemons/ssh.plist
    # Use the folloing setting
    • Use the following to launch ssh
    sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist 
    • After that, your sshd will run at startup so that you can ssh to the Mac.

    0.0.20 Haskell: Finally fixed Ghci error on macOS Big Sur 11.5.2

    • Ghci tls resolver 13.28 ghc-8.6.5 causes error in Big Sur
    • Cocoa can not load on macOS using ghc-8.6.5 BUG
    • Solution

      • Switch to newer ghc-8.10.4 tls-17.9 resolver
      • Remove GLFW from .cabal file and keep GLFW-b and bindings-GLFW
          # See $sp/try/try.cabal
    • But diagrams-core package still can not be built because it uses the older base

      base (>=4.7 && <4.13), 

    0.0.21 Emacs: Emacs 28 has a bug in orgmode

    • Here is the error

      org-eldoc-documentation-function gets called with the wrong number of
    • Here is the Patch from
    • Find the file that you need to patch

      cd ~/.emacs.d
      v=$(find . -name 'org-eldoc.el' | head -n 1)
          vim $v
    • Patch your Elisp code

       (defun org-eldoc-load ()
      "Set up org-eldoc documentation function."
       -  (if (boundp 'eldoc-documentation-functions)
       -      (add-hook 'eldoc-documentation-functions
       -               #'org-eldoc-documentation-function nil t)
       -    (setq-local eldoc-documentation-function
       -               #'org-eldoc-documentation-function)))
       +  (cond
       +   ((boundp 'eldoc-documentation-strategy)
       +    (setq-local eldoc-documentation-strategy
       +               #'org-eldoc-documentation-function))
       +   ((boundp 'eldoc-documentation-functions)
       +    (add-hook 'eldoc-documentation-functions
       +             #'org-eldoc-documentation-function nil t))
       +   (t (setq-local eldoc-documentation-function
       +                 #'org-eldoc-documentation-function))))
    • After org-eldoc.el is patched, recompile your elisp code with following command

      M-: (byte-recompile-directory package-user-dir nil 'force)

    0.0.22 Haskell raw string Text.RawString.QQ and NeatInterpolation are useful for Html, Sql and Regular expression.

    • NeatInterpolation is very slow. I have to switch back to RawString.QQ in Wai Server. haskellwebapp2
    • Use Haskell package Text.RawString.QQ to simplify Html multiple lines in Haskell
    • Need LANGUAGE QuasiQuotes too
    • RawString QQ Example
    {-# LANGUAGE OverloadedStrings #-}
    {-# LANGUAGE QuasiQuotes       #-}
    import Text.RawString.QQ
    -- from copyfile.hs
    -- echo 'file.txt' | pbcopy
    s = "file.txt"
    system $ [r| echo |] <> s <> [r| | pbcopy |] >>= \x -> print x
    multipline = [r| 
    let str = [r| "this is string"|] <> ("hello" <> "world")
    • 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
    • neat interpolation package for variable interpolation It is better than Text.RawString.QQ because you can replace variable inside a string. NeatInterpolation only supports Text in Data.Text neat interpolation

      import NeatInterpolation
      import Data.Text (Text)
      -- pass Text 
      f var = [text| dog_cat_${var} |]
      f "cow" = "dog_cat_cow"
      -- pass Integer
      fun n = [text| dog_cat_${vn} |]
               vn = show n
      fun 3 = "dog_cat_3"
      -- multiple lines
      str = [text| dog_cat

    0.0.23 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.24 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.25 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.26 Haskell show, print and putStr or putStrLn

    1. show, print and putStr "dog\\",

      show "dog\\" -- "\"dog\\\\\""
      print "dog\\" -- "dog\\"
      putStr "dog\\" -- dog\

    0.0.27 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 "" wai.hs

    0.0.28 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.
        1. 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( <={
           if(curr.left == null){
           curr.left = node;
           curr = curr.left;
           // right subtree
           if(curr.right == null){
           curr.right = node;
           curr = curr.right;
       // Recursion
       public static void insert(Node root, Node node){
       if(root != null){
           if( <={
           if(root.left == null)
               root.left = node;
               insert(root.left, node);
           if(root.right == null)
               root.right = node;
               insert(root.right, node);

    0.0.29 DONE Hair cut

    1. 17$ for the stupid hair cut.

    0.0.30 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.31 DONE Do my laundry

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

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

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

    0.0.35 DONE pushall respositories to bitbucket

    0.0.36 DONE fix resume a bit

    0.0.37 TODO Need to add more detail to resume

    0.0.38 TODO Buy a new pot and buy some rice

    0.0.39 DONE Open new paypal account

    0.0.40 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.41 DONE Send out more resumes

    0.0.42 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"));
      Person p = queue.remove();
      // 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 + " " + + "\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.43 TODO Take a look at the Algebraic Data Type and Visitor pattern in Java


    0.0.44 DONE Send out more resume, more to EA

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

    0.0.46 Agda: Finally figure out how to use multiple putStrLn in Agda

    • Chain the IO monad in Agda
    • writeFile fname str in Agda
    • See example MyNum.agda MyNum.agda
    • See Agda stdlib Agda stdlib

      -- print Hello Word is hard
      main = run (putStrLn "Hello World")
    • How to use TWO putStrLn ? it is not trivia

      main = run do
      	   ♯ putStrLn "dog" >> ♯ (putStrLn "cat")
    • How to use THREE putStrLn ? it is very non-trivia

      main = run do
      	   ♯ (♯ putStrLn "dog" >> # (putStrLn "cat")) >> ♯ (putStrLn "pig")

    0.0.47 Agda: What is Costring?

    • Costring can be infinite long,
    • Convert String to Costrng with toCostring

      putStrLn (toCostring "Hello")

    0.0.48 Agda: write string to file writeFile, same as Haskell

    writeFile "/tmp/x.x" "hello"

    0.0.49 Agda: read file and print a string in Agda

    open import Data.String
    open import Function
    open import IO.Primitive
    main = readFiniteFile "/tmp/x.x" >>= putStr ∘ toCostring    
    • read file example 2 Read File 2 References

      open import Function using (_∘_)
      open import Foreign.Haskell
      open import IO.Primitive
      open import Data.String using (String; toCostring)
      -- g is not necessary here I think
      main = (readFiniteFile "/tmp/x.x") >>= putStrLn ∘ toCostring ∘ g
      	   g : String -> String
      	   g str = str 

    0.0.50 Agda: write a string to file in Agda. It is painfully hard.

    • writeFile is from standard library IO.agda under from IO.agda
    • There is also writeFile from standard library IO.Primitive which bindings to Haskell types and functions
    • Why we need run here? run can make your code NON-TERMINATING in Agda
    • It seems to me run run your IO in Agda IO \( \rightarrow \) Haskell IO.Primitive.IO
    • run can run non-terminating code.. sort of..

      {-# NON_TERMINATING #-}
      run : ∀ {a} {A : Set a} → IO A → Prim.IO A
      run (lift m)   = m
      run (return x) = Prim.return x
      run (m  >>= f) = Prim._>>=_ (run (♭ m )) λ x → run (♭ (f x))
      run (m₁ >> m₂) = Prim._>>=_ (run (♭ m₁)) λ _ → run (♭ m₂)
    • open import IO as I to alias your IO
    open import Data.String
    open import Function
    open import IO.Primitive
    open import Data.Nat.Show
    open import IO as I 
    main = "/tmp/x.x" "hello")

    0.0.51 Agda: What is Corecursion?

    • What is recursion? It starts from \( k \) and down to base case

      fac = \k -> if k == 0 || k == 1 then 1 else k * fac (k - 1)
    • What is Corecursion? It starts from the base case to the top \( k \)

      -- iterate::(Num a) => (a -> a) -> a -> [a]
      fac = (\(n, f) -> (n + 1, f*(n + 1))) `iterate` (0, 1)
      -- \(0, 1) -> (1, f*(1)) => (1, 1) , f = 1
      -- \(1, 1) -> (2, f*(2)) => (2, 2),  f = 1
      -- \(2, 2) -> (3, f*(3)) => (3, 6),  f = 2
      take 3 fac -- [(0, 1), (1, 1), (2, 2), (3, 6)]

    0.0.52 Agda: Set Agda input in other mode such as org-mode

    (set-input-method "Agda")
    ;; or
    (set-input-method "TeX")
    ;; or
    (set-input-method nil)

    0.0.53 Agda: Defind record in Agda

    • Here is how to defind record in Agda

      -- indentation is important
      -- (set-input-method "Agda")
      -- Agda record is much better than Haskell:)
      record : Pair (A B : Set) : Set where
      	fst : A
      	snd : B
      p23 : Pair ℕ ℕ  -- \bN
      p23 = Pair { fst = 2; snd = 3}
      main = run (putStrLn (show (Pair.fst p23)))

    0.0.54 Agda: record example 2, use mixfix operator

    • Use mixfix operator

      record _∧_ (A B : Set) : Set where
        constructor _,_
      	fst : A
      	snd : B
      -- (1, 2) => Error. Space is matter
      pair12 : ℕ ∧ ℕ 
      pair12 : (1 , 2) 

    0.0.55 Agda: Emacs Org-mode DOES NOT support code block highlight for Agda.

    0.0.56 Agda: Encode nature with binary bitstring

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

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

    0.0.59 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.60 Heap sort, definition, space complexity, runtime

    • Space Complexity is \( O(1) \)
    • Assume following is minimum Heap
    • Heap is like a full binary tree
    • The node is filled from left to right of the bottom of the tree
    • How to insert node to heap
      • append the node to the end of array
      • bubble up the node from the bottom to the top with following condition
    • parent = \( p = k/2 \), child = \( c = k \)
      • if \( c < p \) then swap(array, c, p), otherwise do nothing
    • How to remove node from the heap?
      • append a node to the end of array
      • awap the top node with new node
      • bubble down the top to bottom if following condition
    • find two left and right childrent

      leftChild = k/2
          rightChild = k/2 + 1
      • find the minimux of two children
    • if parent node \( > \) than the minimum, then swap the minimum with its parent node, otherwise do nothing

      if (arr[parent] > Math.min(arr[left], arr[right])
             awap(arr, parent, minInx)

      Sorry, your browser does not support SVG.

      Sorry, your browser does not support SVG.

    0.0.61 Change background color in org-mode

    #+attr_html: :style background:#FFFFFF; width 600px

    0.0.62 DONE Wrote a shell script to simplify gcc compilation process. $scr/

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

    0.0.64 DONE Xencall call HR interview

    • What did you do in Amazon?
    • Do you know PHP, CSS and Javascript?

    0.0.65 I worked on an application 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.66 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.67 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.68 DONE Interview with

    • 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>();
          map.put(n, v);
          for(Integer n : Arrays.asList(-1, 0, 1)){
          List<Integer> ls = map.get(n);
          if(ls != null){
          return ret;
    • It turned to be those people in never response me any interview result.

    0.0.69 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.

    0.0.70 DONE Added code: Post Html form, and retrieve data from Html Input box, insert data to Sqlite-simple DB.

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

    0.0.72 DONE Refactored code: Clearn up some unnecessary code.

    0.0.73 DONE A guy asks me to meet as Benze Coffee around Hamilton St. and Helmcken St. from a company called

    • Not sure what I will expect

    0.0.74 DONE Integrate Ajax to wai.hs, send Json data to Server, and get response from Server in client side.

    0.0.75 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.76 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.77 OpenGL: 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.78 OpenGL: Vertex and Fragment Shader

    Sorry, your browser does not support SVG.

    • What is Vertex shader? from above picture.
    • What is Fragment shader from above picture.

    0.0.79 OpenGL: 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.80 OpenGL: What is glutReshapeFunc in OpenGL GLUT

    • GULT is OpenGL Utility ToolKit PDF tutorial uses GLUT lib but it is written in 2004.
    • 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);
      glutPerspective(40.0, GLfloat(w)/GLfloat(h), 1.0, 150.0);
    glutReshapeFunc(reshape, width, height);

    0.0.81 OpenGL: gluLookAt function

    gluLookAt((eyeX, eyeY, eyeZ) (atX, atY, atZ) (Vector up))
    gluLookAt(eyeX, eyeY, eyeZ, /* look from eye/camera XYZ */ 
      0, 0, 0,  /* look at the origin */ 
      0, 1, 0); /* positive Y up vector */
    GM.lookAt (Vertex3 0.5 0.5 0.5::Vertex3 GLdouble) (Vertex3 0 0 0:: Vertex3 GLdouble) (Vector3 0 1 0 :: Vector3 GLdouble)


    • See Code Example $sp/OpenGLGLFWSimple

    0.0.82 OpenGL: gluLoadIdentity

    • Reset the current matrix to Identity matrix (default state)

              -- Set the current matrix to identity
      [ 1 0 0 0]
      [ 0 1 0 0]
      [ 0 0 1 0]
      [ 0 0 0 1]

    0.0.83 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.84 DONE Implement Javascript editor with CSS.

    • The project is dead so far. It is too hard to implement an editor.
    • 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.85 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){
                 arr[c-1] = true;
                 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.86 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.
        // your Html file in the parent of src folder
    // fun() inside aronlib.js 
    <script src="src/aronlib.js">
    • 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
    [("Content-Type", "text/html")]
    • 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">

    0.0.87 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.88 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.89 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, 
                           path::Text} deriving(Show, Eq)
        • Implement Type class FromRow and ToRow
        • FromRow ToRow in Database.SQLite.Simple
                -- 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) 
        • Reivew Functor and Applicative Functor
      class Functor f where
        fmap (a -> b) -> f a -> f b
      fmap (+1) [1, 2] -- => [2, 3]
      (+1) <$> [1, 2] -- => [2, 3]
      class Functor f => Applicative f where
        <*> f (a -> b) -> f a -> f b
              Just (+1) <*> Just [1, 2] -- => Just [2, 3]
      • 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.

        class (Semigroup a) => Monoid a where
                         mempty :: a          --- identity
         mconcat :: [a] -> a
        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.90 Install Haskell Platform inside Ubuntu VM and realize it is 8.0.x version.

    • Run following command to install Stack inside Ubuntu.
    curl -sSL | 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.91 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.92 Add GenePDFHtml.hs to bitbucket as repos. GenePDFHtml

    • What technologies does the project use?
      • It uses Sqlite as storeage.

        • Table name store pdf file info. See file $hlib/GenePDFHtmlLib.hs
        _PDFTABLE = "pdftable"
      • 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.
    • PDF page is not generated dynamically. If you want to add new pdf files to the page, then you need to DROP TABLE pdftable IF NOT EXISTS so the code can read the pdf directory again.
    • How to drop pdftable, login to sqlite3

      cd $b/database
      sqlite3 haskellwebapp2_sqlite3.db
      DROP TABLE pdftable
      • Create Table
      CREATE TABLE mytable(
      name TEXT NOT NULL,
      PRIMARY KEY (id)
      • Insert Data to table
      INSERT INTO mytable(name) VALUES('Justin Trudeau');

    0.0.93 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.94 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.95 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.96 Add RSA keys to Ubuntu and FreeBSD hosts, Public key, ssh public key, ssh key

    • 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 the answers.
    • The catch is:
      • cat your public key to authorizedkeys

        cat ~/.ssh/ >> 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.97 Why your public key not working in Github: Error Permission denied (publickey)

    • ssh DOES NOT try all private keys in .ssh actually
      • I always though ssh will try all private keys under .ssh but it is not..surprisedly

        • ssh only tests keys such as id_rsa and other well known keys
        • debug ssh public key
        ssh -T -vv   # debug ssh public key
        # ssh will not use
    • 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 If you don't want to show your host in the public key file, you can use following option

        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 >> autherized_keys
      # set permission
      chmod 600 autherized_keys

    0.0.98 Remove IP Address from our SSH, ssh-keygen

    • Remove all keys from knownhosts file if you get following message

      The fingerprint for the RSA key sent by the remote host is
      Please contact your system administrator.
      Add correct host key in /Users/user/.ssh/known_hosts to get rid of this message.
      Offending ECDSA key in /Users/user/.ssh/known_hosts:20
      RSA host key for host_IP has changed and you have requested strict checking.
      Host key verification failed.
      ssh-keygen -R host_IP

    0.0.99 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 | sh

    0.0.100 FreeBSD install package

    # su root
    pkg install curl

    0.0.101 FreeBSD apache html folder


    0.0.102 FreeBSD install GHC

    pkg install ghc

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

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

    0.0.104 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


    0.0.105 Mysql example

    • Connect to Mysql on my MacOS

      # start mysql on MacOS
      /usr/local/bin/mysql.server start
      mysql -u root
    • Mysql commands

      show databases;  => show all the database;
      show tables;     => show all the tables in current db
      use mydatabase;  => use the mydatabase
      desc mytable;    => show schema of mytable
    • Create Table

      DROP TABLE image;
      CREATE TABLE image(
          path TEXT NOT NULL,
          PRIMARY KEY(id)
    • Insect data to table

      INSERT INTO image(path) VALUES("/tmp/file.png");
    • SELECT all fields in Mysql

      SELECT * from image;

    0.0.106 Mysql Regex

    • mysql regex

      • Select all strings end with .txt
      SELECT path from testtable1 WHERE PATH REGEXP '(.txt$)';
    • query contains string

      # String contains 'javac'
      SELECT path from tablepath WHERE path LIKE '%javac%';
      # String ends with 'javac'
          SELECT path from tablepath WHERE path LIKE '%javac';
    • query contains '.stack-work~

      SELECT path from tablepath WHERE path LIKE '%.stack-work%'
      SELECT path from tablepath WHERE path LIKE '%\.stack-work%'

    0.0.107 Mysql batch insert

    0.0.108 Mysql Yep, you can merge two Mysql tables

    0.0.109 Sqlite3 Primary Key and Foreign Key

         DROP TABLE IF EXISTS ShellHistory
          CREATE TABLE IF NOT EXISTS ShellHistory(
          first_name TEXT,
          last_name TEXT,
          address_id   INTEGER,
          FOREIGN KEY (address_id)
        REFERENCES address (address_id)
      address_id INTEGER PRIMARY KEY,
      house_no TEXT,
      street TEXT,
      city TEXT,
      postal_code TEXT,
      country TEXT


    0.0.110 Create User and Image tables in Sqlite3 database.

    • Connect to Sqlite3

      sqlite3  /Users/cat/myfile/bitbucket/testfile/test.db
    • 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
    • Sqlite3 Regex, LIKE operator with two wildcards pattern:
      • % zero or more wildcard
      • _ one single character

        # select all files that contains word vector
        select * from pdftable where path = '_%vector_%'
    • Sqlite3 Commands
      • show table, show schema, show description, dump table to file

        .table            => show tables
        .schema           => show schema
        .schema  mytable  => show mytable schema, like description in MySql
        .dump             => dump table or datbase to file
        .help             => help command
    • 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.111 Haskell Sqlite3, Simple Example to show how to connect to database, create table, insect data, create record, map record to table.

    • Full Source Code can be used as Haskell Sqlite3 Database.
    • Import package to use Sqlite3 database

      {-# LANGUAGE OverloadedStrings #-}
      import           Data.Int (Int64)
      import           Database.SQLite.Simple
      import           Database.SQLite.Simple.FromRow
      import           Database.SQLite.Simple.FromField
      import           Database.SQLite.Simple.ToField
      import           Database.SQLite.Simple.Internal
      import           Database.SQLite.Simple.Ok
      import qualified Data.Text as TS    -- TS.Text
      import AronModule         -- toSText
    • Create Haskell Record which maps to Sqlite3 table

        data ShellHistory = ShellHistory 
      { shId :: Int64
      , shcmd :: TS.Text
      } deriving (Eq,Read,Show)
    • Sqlite3 convert Record field to Column and from Column to field as long as you instance your record ToRow and FromRow

        -- import Database.SQLite.Simple.FromRow
        -- two fields: shId, shcmd
        instance FromRow ShellHistory where
              fromRow = ShellHistory <$> field <*> field
        -- import Database.SQLite.Simple.ToRow
        instance ToRow ShellHistory where
      toRow (ShellHistory _uid shcmd) = toRow (Only shcmd)
    • Create a table called ShellHistory

      -- Need Query type 
      -- Query{ fromQuery :: TS.Text }
      let sql_create_table = Query{ fromQuery = toSText "CREATE TABLE IF NOT EXISTS ShellHistory (id INTEGER PRIMARY KEY AUTOINCREMENT, shcmd TEXT)" }
      let sql_select = Query { fromQuery = toSText "SELECT id, shcmd FROM ShellHistory" }
    • Create Connection, and Connect to Sqlite3 with open

      let dbfile = "/Users/cat/myfile/bitbucket/testfile/ShellHistory.db"
      conn <- open dbfile
    • Execute query, Create table, Insert data to table, Select query from table

      execute_ conn sql_create_table
      -- insert data to table
      let mystr = "mycmd1"::String
      let query = Query { fromQuery = toSText "INSERT INTO ShellHistory (shcmd) VALUES (?)" }
      execute conn query (ShellHistory 0 (toSText mystr))
      cmdsql <- query_ conn sql_select ::IO [ShellHistory]
      let cmdList = let ls = map (shcmd) cmdsql::[TS.Text] in map toStr ls::[String]
    • Again, use Data.RawString.QQ to simplify the String, ByteString and Text manipulation.
    • Add response page if insertion is successful using Data.RawString.QQ again
    • Add list task page

    0.0.112 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.113 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.114 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.115 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));
        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{
        std::shared_pt<int> pt;
        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.116 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.117 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.118 Install Redis in FreeBSD Redis installation on FreeBSD

    0.0.119 Haskell Enum Trick Enum Trick

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

    0.0.120 Show Maybe is a Functor Functor Maybe Proof

    0.0.121 Haskell: Applicative and Functor

    • Good tutorial in Applicative Functor Applicative
    • Applicative definition is very confusing initially. But if you understand Functor, then it is very easy to grasp the idea. because they are very similar.
    • Let's see the Functor definition in Haskell

      class Functor f where
                return a -> f a
                fmap :: (a -> b) -> f a -> f b
      • It says fmap need a function and Functor type f a and return a Functor type f b (f is Functor) here.
      • Let see the Applicative definition in Haskell Appliactive
    class (Functor f) => Applicative f where
                    pure a -> f a
                    <*> :: f (a -> b) -> f a -> f b
    • Applicative satisfied a few laws:

      -- Associative
      -- Compositon
      -- Identity
      -- Interchange
      -- Homomorphic
              -- F (f . g) = F(f) . F(g)
    • Above definition says that <*> can apply a function inside the Functor to a value inside a Functor It is very similar to fmap which is apply a plain function inside the value of Functor

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

    0.0.123 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.124 Change Emacs Org-mode with solarized theme with CSS file Emacs Org-mode Solarized Theme

    • If you use 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="" />
    -- dark mode
    #+HTML_HEAD: <link rel="stylesheet" type="text/css" href="" />
    • 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:

    0.0.125 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.126 Add to each stackproject project

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

    0.0.127 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.128 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-

    0.0.129 Change web host from Ubuntu 1G to FreeBSD 3G

    0.0.130 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.

      ssh '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  'bash /etc/profile; echo $PATH'
      ssh 'source /etc/profile; echo $PATH'
    • shell-command-to-string is Non-interactive in Elisp

      (shell-command-to-string "fileExist /tmp/f.x")  ;; command: fileExist can not be found error
      ;; fileExist is in $scr/
      ;; we can source it before use the shell
      (shell-command-to-string "source $scr/; fileTimeFull /tmp/f.x") ;; 
    • 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.131 Use interactive shell to store all your shell script command in history

    • If you put #!/bin/bash -i on top of your shell script, all your shell script commands will be in your history. Enable interactive shell on your shell.

      • history \(\Rightarrow\) does work because bash is interactive
      #!/bin/bash -i
    • -i \(\Rightarrow\) interactive shell
    • non-interactive shell \(\Rightarrow\) history command does not work.

    • Also, -i \(\Rightarrow\) enable your shell script can use history command, otherwise history CAN NOT be used in your shell script.

      -c  clear all histories
      -d      offset, history -d 20 => delete line 20
      -a  append current history to history file
      -n  read all history lines not already read from the history file
            and append them to the history list
      -r  read the history file and append the contents to the history list
      -w  write currenty history to history file
      -p  !100:p  => expand it without storing it in history list
      -s  append the ARGs to the history list as a single entry, no idea what does it mean?

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

    0.0.133 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
    • -sourcepath \(\Rightarrow\) specified the location of java files.
    javadoc -classpath  /dir/lib -noqualifier all -d /htmldoc   -sourcepath /javafile/*.java

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

    0.0.135 Add isFile and isDir to javalib

    0.0.136 Database ACID

    • Atomicity
    • Consistency
    • Isolation
    • Durability

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

    0.0.138 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.139 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 ""
      ("pdf":fn:_) -> routing to ""
      _            -> routing to "other universe"

    0.0.140 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.141 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.142 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.143 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){
          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){
         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);
    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.144 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.145 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.146 Passed by value and reference or const reference

    • Passed by value:

      vector<int> even(vector<int> vec){
        vector<int> ret;
        for(auto e : vec){
            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){
             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){
        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){

    0.0.147 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.148 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.149 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.150 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
    h::Any -> Any

    0.0.151 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 {
              } 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.152 Haskell Database connection code in three databases: Sqlite, Mysql and Postgresql

    0.0.153 Fixed error inside javadoc script with -classpath

    # it works.
    javadoc -classpath "/somejar/*:/MyClass:."
    # it does not work.
    javadoc -classpath /somejar/*   ...  

    0.0.154 Xcode: gcc clang c++ compiler flags, cpp compile, xcode compiler: Reference

    • C++ build script
    • 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
          # Use environment variable $clib
      echo $clib # /Users/cat/myfile/bitbucket/cpplib
      g++ -I/$clib -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++  -I$clib -std=c++14 -O3 -Wall -pedantic recurveFileBoost.cpp -lboost_filesystem -lboost_system
    • gcc link to object file with -lm Ref Code Example

      gcc linkedObject.c -o linkedObject -lm
    • \( \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, executable output directory
    • \( \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, *.h 
      # libraries location *.dylib and *.a files
      # 27-12-2020
    • The recurveFileBoost.cpp can be built with following g++ command line

      # file:///Users/aaa/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. xcode boost


    • Add shared libraries to XCode. xcode boost

      • /Users/cat/myfile/bitbucket/cpplibtest/CppLibTest Running Example.
      • boost_system, boost_system are added to XCode Build Setting.


    • Find Xcode tool chain in MacOS and g++ libraries paths

      g++ -print-search-dirs
    • gcc compile c file, gcc --help > $t && vim $t with filter g!/output/d

      gcc hello.c -o /tmp/hello
    • Change cpp compile in Xcode


    • Compile cpp to dynamic libraries MacOS

      g++ -dynamiclib -o mydylib.dylib mylib.cpp
      g++ client.cpp -L/dir/  -lmydylib

    0.0.155 CPP install boost on MacOS

    • Install boost on MacOS or Linux
    • Download boost boost1750 (current boost version) boost1750
    • Unzip or untar it
    • Nothing to build, most of Boost libraries are header-only
    • Goto boost root directory which is the following

          #include <boost/filesystem.hpp>
    • If you want to use any of separated-compiled Boost libraries, you'll need to acquire library binaries.

      cd $b/cpplib/boost_1_75_0
      ./ --help
          ./  # => generate $b/cpplib/boost_1_75_0/stage/include, $b/cpplib/boost_1_75_0/stage/lib
          ./b2            # build
          ./b2 install    # install
      • include header and lib dynamic libraries are generated
      • How to use include and lib in your CPP code?
      • Here is g++ for line project
      • It Use dynamic libraries: boostsystem and boostfilesystem
      • \( \mathbf{-I} \Rightarrow \) specificy a include directory
      • \( \mathbf{-L} \Rightarrow \) specificy a lib directory
      • \( \mathbf{-l} \Rightarrow \) specificy dynamic libraries
      run="g++ -I$clib  -I$boostinclude -std=c++14 -O3 -Wall -pedantic line.cpp  -L$boostinclude/stage/lib  -lboost_system -lboost_filesystem -o $outdir"
    • How to use boost library in your CPP code

    0.0.156 CMake: add include header, add shared libraries (MacOS, CMake –version 3.7.1)

    0.0.157 Share local directories in Apache or Virtual Directory in Apache

    • Edit the http.config to load modalias
    • It seems it does not work so far.

    0.0.158 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.159 Python does not have block comment?

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

    0.0.160 Python file modification timestamp

    import os
    statinfo = os.stat('/tmp')
    os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
               st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
               st_mtime=1297230027, st_ctime=1297230027)

    0.0.161 Python import your own module in Python in Jupyter Lab

    # copy an paste to Jupyter lab
    import sys
    import AronLib as a

    0.0.162 Python Sort objects in Python

    import sys
    import AronLib as a
    class Person():
            def __init__(self, name, age):
   = name
            self.age = age
    lp = [Person('Rannel', 1), Person('David', 3), Person('Pig', 0)]
    lp.sort(key=lambda x :
    for p in lp:

    0.0.163 Python sort string

    list = ["1a", "2c", "4k", "2b"]
    list.sort(key=lambda x : x[1], reverse=False)
    for s in list:

    0.0.164 Python byte string and normal string or utf-8 string

    • Convert byte string to utf-8 string


    0.0.165 Python has \(\text{red}{stolen}\) many good stuff from other function programming language such as Haskell

    • The module itertools contains takewhile, dropwhile and other functions. Those functions are very common \( \text{red}{operation} \) in programming languags.
      • \(\text{red}{takewhile}\) and \(\text{yellow}{dropwhile}\)
    import itertools as it
            ls = [0, 0, 1, 0, 1]
            print(list(it.takewhile(lambda x : x == 0, ls))) # => [0, 0]
            print(list(it.dropwhile(lambda x : x == 0, ls))) # => [1, 0, 1]

    0.0.166 Python List comprehesion is nice feature in Python. It is very similar like Haskell List Comprehension

    • List Comprehension

      s1 = [1, 2]
      s2 = [3, 4]
      # Cartesian Product of s1 and s2
      ls = [(a, b) for a in s1 for b in s2]

    0.0.167 PYthon Why Python map, filter and reduce or fold are unusual in Python?

    • Why do we need the list() to wrap the map and filter functions.
    • Python return iterator instead of a list when use map, filter etc.
    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.168 Python There are many nice features in Python

    • List is awesome. Python list, drop list, take list, reverse list

      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.169 Python read Json file

    # '/tmp/p.json contain following
    {"name": "Bob", 
     "languages": ["English", "Fench"]
      # Python 3+
      from pathlib import Path
      with open('/tmp/p.json') as f:
    data = json.load(f)
      # Output: {'name': 'Bob', 'languages': ['English', 'Fench']}

    0.0.170 Python virtualenv installation, create project

    pip3 install --user pipenv
    • Initialize project
    cd my_project
    pipenv install requests
    • pipenv is in following dir
    • Create simple project,
    import requests
    response = requests.get('')
    print('Your IP is {0}'.format(response.json()['origin']))
    • Run the script using pipenv run:
    pipenv run python
    • Expect similar output
    Your IP is

    0.0.171 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.172 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.173 Apparently, Haddock 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.174 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


      • If you want to add ctrl+k to move your cursor up, then you need to edit your keybinding.json file as following

        	"key": "ctrl+k",
        	"command": "cursorUp",
        	"when": "textInputFocus"
      • Edit the keybinding.json file.
        • Path to keybinding.json
      ~/Library/Application\ Support/Code/User/keybindings.json
    • 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.175 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"?>
        <classpathentry kind="lib" path="/Users/cat/myfile/bitbucket/javalib/jar"/>
        <classpathentry kind="lib" path="lib/commons-io-2.5.jar"/>
    • 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.176 VSCode Cpp/C++/clang++/g++ development in MacOS

    • Output executable file, ex: Cpp option -o

      • g++ -o HelloWorld HellWorld.cpp
    • Cpp Compiler

      "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": [
        				"-I /usr/local/Cellar/boost/1.61.0_1/include",
        			"group": {
        				"kind": "build",
        				"isDefault": true
        			"problemMatcher": [
    • 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.177 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


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

    0.0.179 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")
       print("x^3 + y^3 + x^3 != 42")

    0.0.180 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.181 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


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

    0.0.183 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
    # try Common Lisp
    >(+ 1 2)

    2.0.2 Run your lisp script from command line

    clisp mylisp.lisp

    2.0.3 Emacs ELisp: Atom

    • Atom is the smallest thing in Elisp such as Integer, String, Float

    2.0.4 Emacs Elisp: quote ' is function

    • Quoting an expression treats as data not as code

      • quote or ' is a function
      • Make (1 2) not self-evaluating
      (quote (1 2)) ; => (1 2)
          ('(1 2))      ; => (1 2)

    2.0.5 Emacs Elisp self-evaluating form

    • self-evaluating form is not a list or symbol
    • number, string and vector are self-evaluating form
     '123 => 123
     123  => 123
    (eval '123) => 123
    (eval 123)  => 123
    (eval (eval 123)) => 123

    2.0.6 Emacs Elisp: Create a list with list function

    (list 1 2 3) ; => (1 2 3)

    2.0.7 Emacs ELisp: Symbol

    • What is Symbol?

    2.0.8 Emacs Elisp: Hello World

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

    2.0.9 Emacs Elisp: get buffer name, full path name

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

    2.0.10 Emacs Elisp: kill a buffer by name

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

    2.0.11 Emacs Elisp: get all buffer names

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

    2.0.12 Emacs Elisp: switch to other buffer

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

    2.0.13 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.14 Emacs Elisp: evaluate body forms sequentically and return value of last one, execute multiple statements

    ;; define a function
    (defun ins (cmd) (insert (shell-command-to-string cmd)))
    ;; call the function ins
      (switch-to-buffer-other-window "file.x")
      (ins "ls"))

    2.0.15 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.16 Emacs Elisp: set global variable

    (setq var "~/.emacs")
    ;; use var
    (find-file var)

    2.0.17 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)
    • trim a list of strings
    (defalias 'trim 'string-trim)
    (mapcar 'trim '(" a " " b ")) ;; => ("a" "b")

    2.0.18 Emacs Elisp: filter, haskell like filter, filter from dash.el

    (defalias 'filter '--filter)  ;; from dash.el
    (filter (> (length it) 0) '("" "a")) ;; => ("a")

    2.0.19 Emacs Elisp: car and cdr

    • car is the pointer to head or first element of a list

      Node head;
    • cdr is the pointer to the rest of a list

      Node node =;
    • Elisp car and cdr

      (car '(1 2 3)) ;; 1
      (cdr '(1 2 3)) ;; (2 3)
    • Haskell head and tail

      head [1, 2, 3] -- 1
      tail [1, 2, 3] -- [2, 3]
    (car '(1, 2, 3)) ;; => 1
    (cdr '(1, 2, 3)) ;; => (2, 3)

    Sorry, your browser does not support SVG.

    • inverse of car and cdr is cons

      (cons 'bat '(pig fox cat)) ;; (bat pig fox cat)

    2.0.20 Emacs Elisp: assoc and associative list or alist

    2.0.21 Emacs Emacs: format string or convert a list to string

    (setq x '(cons dog cat))
    (format "%s" x) ;; "(dog cat)"

    2.0.22 Emacs Elisp: switch to other buffer

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

    2.0.23 Emacs Elisp: open file in a buffer with find-file

    (find-file "~/.emacs") ;; open a file in a buffer
    ;; why find-file is not called open-file?

    2.0.24 Emacs Elisp: insert string in cursor

    • insert
    (insert "Hello")

    2.0.25 Emacs Elisp: Get element from a list

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

    2.0.26 Emacs Elisp: Get the current line string, current string

    (thing-at-point 'line t)

    2.0.27 Emacs Elisp: Get cursor line number


    2.0.28 Emacs Elisp: run shell command function

    • shell-command-to-string
    (insert (shell-command-to-string "ls"))
    • Split string with newline
    (split-string (shell-command-to-string "ls") "\n")
    ;; => ("f1.x" "f2.x")

    2.0.29 Emacs Elisp: Goto line

    (goto-line 10)

    2.0.30 Emacs Elisp: Count line number in region

    (count-lines-region (regin-beginning) (regin-end))

    2.0.31 Emacs Elisp: Get current word under cursor

    # only word
    (thing-at-point 'word 'no-properties)
    # more info
    (thing-at-point 'word)

    2.0.32 Emacs Elisp: Get the current word bounds under cursor

    # bounds for a word under cursor
    (bounds-of-thing-at-point 'word)

    2.0.33 Emacs Elisp: Repeating Timer

    ;; repeat every 60 sec
    (run-with-timer 0 (* 1 60) (lambda () (message "repeat me")))
    ;; start a timer with a name so that we can kill them
    (setq mytimer (run-with-timer 0 (* 1 30) (lambda () (message "repeat me 60 sec"))))
    ;; kill the timer
    (cancel-timer mytimer)

    2.0.34 Emacs Elisp: Regex, remove last directory from a string

      (defun remove-last-dir (dir)
    (replace-regexp-in-string "(.*)/.+" "\1" dir))
      (print (remove-last-dir "/sites/all/modules"))

    2.0.35 Emacs Elisp: Change shell environment variable to exec-path-from-shell-getenv

    • SO
    • The following code does not work so far.
      (defun set-exec-path-from-shell-PATH ()
    "Set up Emacs' `exec-path' and PATH environment variable to match that used by the user's shell.
      This is particularly useful under Mac OSX, where GUI apps are not started from a shell."
    (let ((path-from-shell (replace-regexp-in-string "[ \t\n]*$" "" (shell-command-to-string "$SHELL --login -i -c 'echo $PATH'"))))
      (setenv "PATH" path-from-shell)
      (setq exec-path (split-string path-from-shell path-separator))))    
    • Create a elisp function to get an environment variable and cd to a directory. it works well so far.

    2.0.36 Emacs Elisp: substring in elisp

    (substring buffer-file-name 0 -4) ;; =>  (substring "/file.html" 0 -4) => /file

    2.0.37 Emacs Elisp: split window horizontically and vertically


    2.0.38 Emacs Elisp: Delete other window, maximize current window.

    # close the window C-w-c in Vim      

    2.0.39 Emacs Elisp: Open file under cursor.

    M-x find-file-at-point

    2.0.40 Emacs Elisp: define an alias in Emacs

    (defalias 'kill 'kill-buffer)

    2.0.41 Emacs Elisp: Elisp ampersand rest in a function argument

    (defun fun(&rest r) ...)

    2.0.42 Emacs Elisp: If condition else then

    (if nil (message "failed") (message "success"))
    (if t   (message "success") (message "failed"))

    2.0.43 Emacs Elisp: Compare string

    (if (string= "dog" "dog") (message "same str") (message "diff str"))

    2.0.44 Emacs Elisp: Emacs read file, write to file, append to a file

    2.0.45 Emacs Elisp: Compare String in Elisp

    • Compare String in Elisp is not obvious, if you use (= "dog" "cat") then you are out of luck

      (setq v "dog")
      (string= "dog" v) ; => t

    2.0.46 Emacs Elisp: Compare Objects in Elips

    • More compare function OS
    • eq Compare object and the content of the object.
    • Compare setq variable

      (eq 3 3) ; => t
      (setq myvar '(1 2))
      (eq 'myvar '(1 2)) ; => nil
      (eq myvar myvar) ; => t

    2.0.47 Emacs Elisp: Execute elisp script in your buffer with C-x C-e

    • Make sure you put your cursor after the last closed bracket or the next line of your last closed bracket
    (let ((v1 'dog)
          (v2 'cat)
         (message "my %s eats my %s, null is similar to %s"))
    ;; put your cursor here C-x C-e    

    2.0.48 Emacs Elisp: Split current line

    (split-line);; split line under cursor

    2.0.49 Emacs Elisp: Fibanacci Number

    (defun fib (n)
       "Fibonacci number"
       (if (< n 3)
           (+ (fib (- n 1)) (fib (- n 2)))

    2.0.50 Emacs Elisp: power function in Elisp, it is not (^) why?

    • power function

          ;; (^ 3 4) error
      (expt 3 4)

    2.0.51 Emacs Elisp: Convert list to string

    (msg (format "%s" (car '(1 a b))))

    2.0.52 Emacs Elisp: concat string mapconcat or fold

    (msg (concat "a" "b")) ;; => ab
    (msg (mapconcat 'identity '("a" "b" "c") "-")) ;; => a-b-c

    2.0.53 Emacs Elisp: highlight word under cursor and unhighlight word under cursor


    2.0.54 Emacs Elisp: run shell command in whole buffer

      (defun tidy-html ()
    "Tidies the HTML content in the buffer using `tidy'"
     ;; beginning and end of buffer
     ;; command and parameters
     "tidy -i -w 120 -q"
     ;; output buffer
     ;; replace?
     ;; name of the error buffer
     "*Tidy Error Buffer*"
     ;; show error buffer?

    2.0.55 Emacs Keybind: jump backward from defintion in Haskell Intero in .eamcs

    ;; goto def: M-.
    (global-set-key (kbd "M-b") (lambda (interactive) (pop-tag-mark)))

    2.0.56 Emacs PATH and exec-path for executable files.

    • Sometimes you might have no idea why your tools are not running inside Emacs Shell (M-!). One variable you might need to check is called exec-path (C-h v RET exec-path) It might be have the same values as '$PATH'
    (exec-path)  ;; $PATH, M-S:

    2.0.57 Emacs environment variable, getenv and exec-path-from-shell-getenv

    (getenv "b") ;; => nothing
    (exec-path-from-shell-getenv "b") ;; => valid output
    (setenv "KKK" "wwher")
    ;; find-file $KKK => resolve $KKK

    2.0.58 Emacs Change default directory in Emacs

    (setq default-directory "/path/to/documents/directory/")

    2.0.59 Emacs Orgmode manipulate table

    Key Description
    M-S LEFT delete current column
    C-c - add row dash line
    Tab goto next cell

    2.0.60 Emacs Regex, Emacs Regular Expression, Vim Regular Expression

    • Compare Emacs and Vim

      Vim Vim Example   Emacs Emacs Example Description
      \w \w\+   \w \w+ Match dog cat, Not match dog12cat
      \{n, } \w\{2,}   \{n,\} \w\{2,\} Match two or more word letters
      \d \d\+   [0-9] [0-9]+ Match one or more digit
      \s \s\+   [ ] [ ]+ One or more whitespace
      § §\+   [^ ] [^ ]+ one or more non-whitespace

    2.0.61 Emacs: Search and Replace, Why Emacs sucks on that.

    • Emacs Search and Replacement
    • If you want to search and replace there is function called replace-string which is just for string, not for regex.
    • If you want to search and replace and confirm your replacement then there is other function called query-replace
    • If you want to search and replace in regex then there is other function called replace-regex
    • If you want to confirm your search and replace then there is other function called query-replace-regex
      • Apparently you need to spend an hour on reading the menu document in order to just do some search and replacement on your code. In Vim, you just do the following
    # Vim
        # Emacs
        M-x query-replace-regex
        [0-9]+ RET KK RET
    • Search and Replace in Group

      • \d \s \S \( \Rightarrow \) DOES NOT support in Emacs Regex Engine
      ;; Roberto, Euler, Baggio => roberto, euler, baggio
      M-x query-replace-regex
      \([A-Z]\)\([a-z]\) RET \,(downcase \1) RET
      ;; \, => following elisp expression

    2.0.62 Emacs: Move cursor to the beginning of non-whitespace and move the cursor to the first column of a line

    • There are functions to handle those tasks.
      • Move the cursor to non-whitespace of a line, (it is the most useful shortcut key)
        # M-x back-to-indentation
    • Move the cursor to the first column of a line
    # bound to C-a

    2.0.63 Emacs: Insert tab in front of a line, function name, binding to M-i


    2.0.64 Emacs: customize theme

    • Here are the steps to customize a themes








    3 Other Stuff

    3.0.1 Self-signed certificate

    • Self signed certificate

    3.0.2 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
    # start it
    sudo /usr/local/etc/rc.d/rabbitmq start

    3.0.3 Install RabbitMQ in MacOS

    brew update
    brew install rabbitmq
    # binary file

    3.0.4 Rabbit Message Queue from Pivotal

    3.0.5 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 Interview

    3.0.6 Evil is not a perfect solution for Vim users.

    • Evil mode is great for movement.
    • Disable Evil mode and Enable Evil mode.
    • You need to know when you should enable and disable Evil mode.
    • Evil mode does not support :ls see all buffer
    M-x evil-mode

    3.0.7 Intero and Stack are both not working suddenly

    • Can not build a Stack project,e.g. RedisInsert
    • Intero can not be booted.
    • Fixed is by update the Stack to newer version 2.13

    3.0.8 Create a UI to display data for code snippet

    • Use Cocoa Swift NSTextField
    • Read data from a file repeatedly

    3.0.9 Add markdown mode to Emacs or GFM mode for Github

    • Install markdown-mode on Emacs
      • M-x list-package markdown-mode RET
    • Install markdown parser on MacOS

      • command brew install markdown
      C-c C-c e
      C-c C-c l  => live preview
    • Add init file to .emacs

      (autoload 'markdown-mode "markdown-mode"
       "Major mode for editing Markdown files" t)
       (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
       (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
       " Github
       (autoload 'gfm-mode "markdown-mode"
        "Major mode for editing GitHub Flavored Markdown files" t)
        (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))

    3.0.10 Change PDF file background color to different colors, PDF reader, pdf background.

    • goto References \(\Rightarrow\) Accessibility
    • Adobat Acrobat Reader can change PDF file background color so far.


    3.0.11 Java: extends and super keywords (07-11-2019)

    List<? extends Number> ls1 = new ArrayList<Integer>();
    List<? extends Number> ls2 = new ArrayList<Double>();
    List<? extends Number> ls3 = new ArrayList<Double>();
    List<? super Integer> ls4 = new ArrayList<Integer>();
    List<? super Integer> ls5 = new ArrayList<Number>();
    List<? super Integer> ls6 = new ArrayList<Object>();


    3.0.12 Java: JShell is nice feature because it learns from Python or Haskell.

    • JShell shells script:

    • It is hard to figure out if you want to load all the external jar files to JShell
    • The following code DOES NOT work, it will waste me an hour to figure it out. We all know path is messy in Java when you want to load some jars or class file.
    • There is better way to import all the jar files under a directory.
      • I just figure our how to import all your packages from a config file
    • jshell_config.jsh contains all your jshell commands
        # jshell_config.jsh contain following commands
        # import static classfile.Aron.*;           
        # $b/java
    >/open jshell_config.jsh
    • TODO add both to script?

      # load all your jar files
      jshell --class-path $(ls -d $b/javalib/jar/* | tr '\n' ':')
      # following:
      import static classfile.Aron.*;
      import static classfile.Print.*;
      import static classfile.Test.*;
      import classfile.Node;
      import classfile.Tuple;
      • Following is not working
      jshell --class-path $b/javalib/jar/*
    • In order to load jar file to JShell, you need to load the jar file as following.

      jshell --class-path :$b/javalib/jar/mylib1.jar:$b/javalib/mylib2.jar
    • After you load your jar files, you need to import your package too.

      • import all static methods from class Aron
      import static classfile.Aron.*;
    • how to exit JShell, show to see your import packages etc, list your command?

    • Nice feature of JShell or Java 10, var can be used to any varaible name.

      var v = drop(2, "dog") => "g"
    • After update MacOS to Catalina, Everything screwup.
      • Can not delete jshell in /usr/bin because Apple makes it Read File System
      • Jshell symbol link screwup again. It points to wrong file.
      • I have to create symbol link jshell12 under /usr/local/bin to point to OpenJDK12 directory
    • JavaJDK 12 is in following directory

    3.0.13 JShell load script to JShell, it is better than Haskell

    • Use following command to load snippet to your JShell

      /open /tmp/
      // contains
      int f(int n){
        return n + 1;
      class MyClass{
        int n;
        public MyClass(int n){
              this.n = n;

    3.0.14 The difference among align, align* and aligned, they are all in math mode.

    • See more advanced typeset equation
    • Understand Latex environment
    • align automatically numbers your equatio

        f(x) &= (x^3 + y^3) \\
             &= (x + y) (x^2 - xy + y^2) 
      \begin{align} f(x) &= (x^3 + y^3) \\ &= (x + y) (x^2 - xy + y^2) \end{align}
    • align* does not number your equation.

        f(x) &= (x^3 + y^3) \\
             &= (x + y)(x^2 - xy + y^2)
      \begin{align*} f(x) &= (x^3 + y^3) \\ &= (x + y)(x^2 - xy + y^2) \end{align*}
    • align* - multiple columns alignment

         f(x) &= (x^3 + y^3)              & h(x) = x^2 + 1 \\       
         h(x) &= (x + y)(x^2 - xy + y^2) & g(x) = x + 3   \\ 
      \begin{align*} f(x) &= (x^3 + y^3) & h(x) = x^2 + 1 \\ h(x) &= (x + y)(x^2 - xy + y^2) & g(x) = x + 3 \\ \end{align*}
    • aligned is for display math mode \[ \], it seems to me aligned is not a math mode environment

               f(x) &= ax^2 + bx + c \\
               g(x) &= x^3 + x + 1
          % or
               f(x) &= ax^2 + bx + c \\
               g(x) &= x^3 + x + 1

      This is two equatins \begin{equation} \begin{aligned}

    f(x) &= ax2 + bx + c
    g(x) &= x3 + x + 1 \end{aligned} \end{equation}

    • I try to figure out what is the difference between \textbf{align*} and \textbf{aligned} I just realize \( \textbf{aligned} \) can be embeded inside the text. And \textbf{align*} has to be in separate line.

         % Learn the difference between align* and aligned    
       x = y \\
       y = z \\
       z = w
      \end{aligned}, I just realize \textbf{aligned} can be embeded inside the text. And \textbf{align*} has to be in separate line.    

    3.0.15 Fixed copy text to clipboard with click button in Wai Server. (13-11-2019)

    • Initially use the wrong id name in TextArea, change to id in pre
    • commit the code.
    • Inside Wai Server, there is still some functions use neatinterpolation package?
      • Change it back to Raw.String.QQ ?
    • Wai Server is slower than before. it might be neat interpolation package issue.

    3.0.16 Modulus for a ring, addition and multiplicaton

    • Show following If: \begin{aligned}

    & a \mod m ≡ a' \quad b \mod m ≡ b'
    &\text{ Show } a + b \mod m ≡ a' + b' \text{ and } a b \mod m ≡ a' b' \\
    a \mod m &≡ a'
    b \mod m &≡ b'
    a &≡ x m + a'
    b &≡ y m + b'
    ⇒ a + b &≡ (x + y) m + a' + b'
    ⇒ a + b \mod m &≡ a' + b' \\
    a b &≡ (xm m + a') (y m + b')
    a b &≡ x m y m + x m b' + a' y m + a' b'
    ⇒ a b \mod m &≡ a' b' \end{aligned}

    3.0.17 Try to Remove all commands from $b/stackproject/filewatcher and run it see still got the error message.(15-11-2019)

    /bin/ls: createProcess: fork: resource exhausted (Resource temporarily unavailable
    • It still get the same error message even though all the system() code are removed.(15-11-2019)

    3.0.18 English words: modulus, module, modular, moduli, modulo, modulate (15-11-2019)

    • The plural form of modulus is moduli
    • modulo is a prepostion, I never know that. It is very surprised.
    • In mathematic, we do have something called modulo operation
      • If two numbers are congrent modulo a given number if their reminders are the same when divided by that number.

    \[ 10 \mod 3 \equiv 7 \mod 3 \equiv 1 \]

    • Word modulu DOES NOT exist.
    • modular is adjective. moular arithmetic
    • modulate is verb.
    • module is noun.

    3.0.19 Polynomial, degree of polynomial.

    • Take the higher power of a polynomial is called the degree of polynomial \[ f(x) = 3x^3 + 2x^1 + 3 \\ \deg(f) = 3 \]
    • An non zero constant polynomial is zero \[ f(x) = 3 = 3x^0 \\ \deg(f) = 0 \]
    • Zero constant polynomial will be defined as \(-\infty\) or \(-1\) \[ f(x) = 0 = (0, *) \\ \deg(f) = -\infty \]
    • The degree of multiplication of two polynomials. If both polynomials are not zero constant polynomial, then \[ f(x) = 3x^2 + 3 \\ g(x) = 4x^3 + 2x \\ \deg(f \cdot g) = \deg(f(x) \cdot g(x)) = \deg(f) + \deg(g) = 5 \\ \]
    • If one of the polynomials is zero constant polynomials, the addition still work.

      • Assume the \(\deg(0) = -\infty\)

      \[ f(x) = 0 \\ g(x) = 4x^3 + 2x \\ \deg(f) \cdot g) = \deg(f \cdot g) = \deg(f) + \deg(g) = 5 + -1 = 4 \]

      • The addition of two degree of two polynomials still work. \[ f(x) = 0 \\ g(x) = 4x^3 + 2x \\ \deg(f \cdot g) = \deg(f) + \deg(g) = -\infty + 3 = -\infty \\ \]
      • The addition of two polynomials? \[ f(x) = 3x^2 + 3 \\ g(x) = 4x^3 + 2x \\ \deg(f + g) = \max(\deg(f), \deg(g)) = \max(2, 3) = 3 \\ \]
      • What about one polynomial is zero constant polynomial. it still works. \[ f(x) = 0 \\ g(x) = 4x^3 + 2x \\ \deg(f + g) = \max(\deg(f), \deg(g)) = \max(2, -\infty) = 2 \]

    3.0.20 In Java, negative and positive infinity are defined. I never realize that.(15-11-2019)

    double inf = Double.POSITIVE_INFINITY;
    System.out.println(inf + 5);
    System.out.println(inf - inf); // same as Double.NaN
    System.out.println(inf * -1); // same as Double.NEGATIVE_INFINITY
    // Infinity
    // NaN
    // -Infinity

    3.0.21 Rename to, add symbol link

    3.0.22 latexmk automatically compile file and reload pdf automatically

    • shell script $b/
    • mylatex.tex file \(\Rightarrow\) auto compile file.
    • The shell script has following code to use latexmk
    latexmk -interaction=nonstopmode -pvc -pdf file.tex > /dev/null 2>&1 &
    # ignore error
    # auto compile
    -pvc -pdf

    3.0.23 Add operators to javapolynomial: negate, subtract, inverse, divide and test cases.(19-11-2019)

    3.0.24 Algebraic Data Type and Calculus

    3.0.25 Intellij wrong java compiler, Intellij class file has wrong version error.

    • Wrong version class in Intellij



    3.0.26 Intellij keymap file location on MacOS.

    • Intellij key map file name


    • Intellij edit shortcut key


    3.0.27 Intellij Make Vim like keymapping

    • Map multiple key strokes in Intellij

      • Open or Close Run window at the bottom of Intellij, Vim like keymapping ctrl-w c
      • Add following to your keymap.xml file.
      <action id="ActivateRunToolWindow">
        <keyboard-shortcut first-keystroke="meta 4" />
        <keyboard-shortcut first-keystroke="ctrl w" second-keystroke="c" />

    3.0.28 Intellij code template or snippet location on MacOS, Symbol link to bitbucket/intellij

    # MacOS
    # templates symbol link to =>
    • code template can be added in XML is a newline

    3.0.29 Intellij Add classes and jar file to libraries


    3.0.30 XML speical characters '<', '>', '\'', '"', '&'

    3.0.31 Convert snippet to Intellij code template in Haskell stackproject/IntellijSnippet

    3.0.32 Haskell pretty print library. pretty-simple

    pPrint "YOURCLASS"

    3.0.33 Haskell FFI: How to pass a pointer to a function

    • Read a value from a pointer in Haskell. let say we have a function called void increment(int *n) n is modifed from inside the function.

      void increment(int *n){
          int m = *n;
          *n = m + 1;
    • FFI Function signature, we might have a function prototype like the following.

      c_increment :: Ptr CInt -> IO ()
    • Allocate memory for pointer using following

              alloca ::forall a b. Storage a => (Ptr a -> IO b) -> IO b
      fun::IO Int
      fun = do
        alloca \pt -> 
                              poke pt 3 -- write 3 to pt
              n <- peek pt  -- read a value from pt
               return $ fromIntegral n 

      Read a value from a pointer

      Write a value to a pointer

      • poke Haskell poke
      • It seems to me all the primitive types are instance of Storage
      • If you need to pass pointer to struct, then you need to create an instance of Storage

    and implement a few functions such as peek, poke, sizeOf, alignment

    • void type in C is equivalent to IO()
    • Call Haskell Fun in C Program
    • Haskell Call C Function
    • Tutorial Wiki
    • C struct to Haskell
    • Haskell type, FFI C type and C type

      Haskell Convert FFI C type C type
      Int Int = fromIntegral CInt CInt int
      String   CString char*
      Double Double = readToFrac CDouble CDouble double
      fromIntegral::(Integer a, Num b) => a -> b
              -- Num interface
      class Num a where
       (+) :: a -> a -> a
       (-) :: a -> a -> a
       (*) :: a -> a -> a
       fromIntegral :: (Integer a, Num b) -> a -> b
       negate :: a -> a
       abs :: a -> a
       signum :: a -> a
      realToFrac :: (Real a, Fractional b) => a -> b
      -- Real to Fractional
      class Fractional a where
        (/) :: a -> a -> a
        recip :: a -> a
                fromRational :: Rational -> a

    3.0.34 Haskell FFI: Stack project for FFI

    3.0.35 Haskell Unicode regex error, "illegal byte sequence" error

    • Change locale to export LANG=C
    • SO
    Text.Regex.Posix.String died: (ReturnCode 17,"illegal byte sequence"))
    >export LANG=C

    3.0.36 Haskell bracket example from Snoy Man

    3.0.37 Add stackproject Haskell FFI C my lib file.

    3.0.38 Convert C function signature to FFI with C2HS tool, example(26-11-2019)

    3.0.39 Move CodeAnalysis to $b/cmake folder.(23-11-2019)

    3.0.40 Add some C funciton to my C library(26-11-2019)

    dropChar(int n, char arr[])
    takeChar(char arr1[], int n, char narr[])
    concat(char arr1[], char arr2[], char arr3[])

    3.0.41 Zathura PDF latex viewer, it is Vim style PDF Viewer

    • background and fontcolor can be changed.

    3.0.42 Joseph problem

    • Whether the problem is related to "Excel Column Header" problem. Excel Column
    • The problem is related to rotate array to the left or the right with positive or negative number


    3.0.43 Install ghc-mod is painful on MacOS.

    • Cabal install does not work welll because ghc-mod only supports old GHC. You need to change Stack resolver to its-8.24 with following command.
    • SO References Reddit ghc-mod

      stack install ghc-mod --resolver lts-8.24
    • I can install it with above command ghc-mod binary is in

    • So far, ghc-mod still does not work on Emacs.

    3.0.44 Nice emacs setup Site

    3.0.45 New Vim Command in insert mode, I never know that before.

    • SO
    • delete word and line in insert mode
    • Control Key in insert mode
    CTRL-O h  move cursor left 
    CTRL-O l  move cursor right
    CTRL-O j  move cursor down
    CTRL-O k  move cursor up
    • Contrl Key in insert mode
    CTRL-W    delete word to the left of cursor
    CTRL-O D  delete everything to the right of cursor
    CTRL-U    delete everything to the left of cursor
    CTRL-H    backspace/delete
    CTRL-J    insert newline (easier than reaching for the return key)
    CTRL-T    indent current line
    CTRL-D    un-indent current line

    3.0.46 Vimscript list or array

    • list has following syntax in Vimscript

      let list = [1, 2, 3]
      let list = [1, 'a']
      let list = [1, "a"]
    • Add element to a list

      let list = [1, 3]
      call add(list, 4) " => [1, 3, 4]
      call add(list, 'dog') " => [1, 3, 4, 'dog']
      let ls2 = [4]
      call add(list ls2) " => [1, 3, 4, 'dog', [4]]
    • Index an element from a list.

      let list = [1, 2, [3]]
      echo list[0] " => 1
      " length of a list
      echo len(list) " => 3
      " get the last element
      echo list[-1] " => [3]
      " two dimensions list
      echo list[2][0] " => 3
    • From above example, you can add number or string other type to the same list.
      • Python and Java can only store same type on a list or array.
    ls  = [1, 2]
        ls2 = ['dog', 'cat']
    • Vimscript nested function is a thing actually.

      func! MyFun()
               call Inner()
               func! Inner()
                 echo 'inner func'

    3.0.47 Vimscript pesado-variable(I never hear the name pesado-variable in Vim)

    3.0.48 Vim :g or :global range search, it is very powerful

    • global search pattern - get the range and exec command
    • :global pattern command
    • :g /pat1/, /pat2/ command
    • :g /pat1/, /pat2/ substitute
    • SO
      x = x + 1 \\
      y = y + 1 \\
      z = z + 1 \\
    % chagne to
     x &= x + 1 \\     
     y &= y + 1 \\     
     z &= z + 1 
    " +1 => next line 
    " -1 => previous line
    " -v => all special char need to be escaped
    :g /\v/\\begin\{align\}/+1, /\v/\\end\{end\}/-1 s/=/\&=/gc


    3.0.49 Some crazy Vim tips from someone

    3.0.50 Pandoc convert Latex to Html, Haskell literate to Html

    • pandoc 2.8 on MacOS
    # Compile Haskell literate code to html with pandoc                                                                                  
    # /Users/cat/myfile/bitbucket/haskell/try_lite.lhs                                                                          
    pandoc --smart --to=html+lhs try_lite.lhs > /tmp/try_lite.lhs && open /tmp/try_lite.html                                        
    # Compile Latex to Html5                                                                                                              
    pandoc --mathjax --highlight-style haddock $m/negative_modulo.tex -f latex -t html -s -o /tmp/f3.html && open /tmp/f3.html

    * Haskell Haddock example

    3.0.51 history command is not working inside shell script

    • If you use following code to get all the commands histories, then you are out of luck

      history | grep ls
    • This is answer from stackoverflow.
      • SO
      • history command is disabled when non-interative shell is running
      • I think the shell will "use" the history file and write commands to the file.
      • Here is how to fix it
    #!/bin/bash -i
    history | grep ls   

    3.0.52 Write a few functions to align columns in Vimscript(07-12-2019)

    3.0.53 Add some test cases for Vimscript functions. And it works well so far.(07-12-2019)

    3.0.54 Fixed a bug in haskellwebapp2, colorize some wrong tokens or keywords with regex.

    3.0.55 Haskell define dynamic function with Map

    3.0.56 Check ghci memory leak

    import Control.Concurrent
    import Control.Monad
    import System.IO
    import System.Process
    main = do
    (Just hin, Nothing, Nothing, pid) <- createProcess (proc "ghci" ["+RTS","-S"]){std_in=CreatePipe}
    forever $ do
            threadDelay 100000 -- 0.1s
            hPutStrLn hin "\"this is a test of outputting stuff\""
            hFlush hin

    3.0.57 Emacs Auctex Latex autocomplete Environment, Section and Macro.

    C-c C-c  # compile latex      
    C-c C-l  # view pdf file
    C-c C-e  # autocomplete environment
    C-c C-m  # autocomplete macro
    C-c C-s  # autocomplete section
    `        # autocomplete math mode, alpha
    • Skim reload pdf file automatically. Skim \(\Rightarrow\) References.


    3.0.58 Emacs still can not resolve environment variables, add one function to some hassle.

    • It does not solve all the problems but it save me lots of typing.
    (defun cdd(env)
       (cd (getenv evn)))

    3.0.59 Emacs can do lots of math

    3.0.60 Emacs: Jumping back and forth is stupidly painful in Emacs.

    • Try the transient-mark-mode Redit question
    • So far the easier way to do is using the register
      • Mark the location with a letter, e.g. 'a'
    C-x r <Space> a
    • When you move the cursor to other location, you can jump back to previous location with letter 'a'
    C-x r j a
    • In Vim, you can mark the location with a letter 'a' with m command (Assume you are in Normal mode)
    # Assume you are in Normal mode
    m a	
    • In Vim, jump back to 'a' location
    # Assume you are in Normal mode

    3.0.61 Sometimes Emacs does not reload file with load-file, you need to kill-buffer and reopen the file.

    3.0.62 Shell Script: /etc/profile source /.bashrc, currently it works so far.

    • non-interative shell does not read /etc/profile and /.bashrc
    # inside /etc/profile

    3.0.63 Bash shell keybinding or key mapping. Map your F7 key to run a shell script.

    • Map f7 key to send a hello world to terminal

      # add code here

    3.0.64 Bash shell keypress event

    3.0.65 Shell Script: alias does not expand inside shell script because alias DOES NOT expand in non-interative shell

    • How to make alias expand inside your shell script? alias does not work inside shell script

      shopt -s expand_aliases
      source ~/.bash_aliases
      # your code here

    3.0.66 Shell Script: true and false are both shell command, I never know that

    >echo $? 
    => 0
    >echo $?
    > 1

    3.0.67 Shell Script: pass string with newline to argument in Shell

    • string with newline, argument with newline
     str=$(cat <<-END
     This is line one.
     This is line two.
     This is line three.
     printBox 4 'dog cat '$'\n''cow'
     printBox 4 "$str"
     printBox 4 'dog\ncat'

    3.0.68 Org-mode and GNU-APL mode, input GNU-APL char inside org-mode

    • It is very easy, just switch from org-mode to gnu-apl mode and input your favour char inside your org-mode
    • You can do the same thing in Haskell mode and input Latex char with (latex-input)

    3.0.69 Install APL inside your Emacs.(I'm a MacOS)

    • You might need to kill apl server from command line, and restart your gnu-apl inside your Emacs

      ps aux | grep apl | awk '{print $2}' | line 'x -> kill -9 x'
    • If you can not run your APL, use (kill-buffer) and restart gnu-apl again.
    • Use homebrew to install gnu-apl on MacOS

      brew install gnu-apl
          # /usr/local/Cellar/gnu-apl/1.8/bin/apl
      M-x list-packages
      # search gnu-apl-mode RET
    • Add gnu-apl to load-path to init.el file

      (add-to-list 'load-path (concat (getEnv "HOME") "/.emacs.d/elpa/gnu-apl-mode-20211012.1139"))
      (require 'gnu-apl-mode)
    • Start gnu-apl mode

      M-x gnu-apl-mode
    • Input APL char in Emacs

      # M-x gnu-apl-mode
      # add image aplkeymap.png
    • Sometimes you need to kill your buffer with (kill-buffer) to go back to gnu-apl mode, I have no idea why?
    • It does not work if you are in different mode such as haskell-mode. No idea how to switch to gnu-apl-mode

      • Close Emacs and Restart APL with following command
      M-x gnu-apl
    • Where is your APL keyboard?

      M-x gnu-apl-show-keyboard


    • How to exit gnu-apl window?(09-12-2019), this is the best thing that I learned today.
      • Here is the awesome command to exit GNU-APL:)
    • System command start with right parenthesis )

      )OFF # => exit apl
      )VARS # => see all variables
      )ERASE # => ?
      # erase a variable n
    • APL use reshape ρ (rho) command to create table or matrix

      a ρ b
    • APL use reshape ρ to create a vector or initialize a vector
      • initialize a vector
    v ← 4 ⍴ 0
    	⍝ v = 0 0 0 0
    • Create a 4 elements vector
    v ← ⍳ 4
    	⍝ v = 1 2 3 4
    • Initialize a vector with 1 2 3 4
    4 ρ 1 2 3 4 # v = 1 2 3 4
    4 ρ 1  2    # v = 1 2 1 2
    4 ρ 1, 2    # v = 1 2 1 2
    • Change to different mode, e.g. to Org-mode

      M-x org-mode
    • Change to gnu-apl mode

      M-x gnu-apl-mode
    • Start gnu-apl console

      M-x gnu-apl
      ;; not gnu-apl-mode
    • gnu-apl add vector
      • Add two vector or two list? what is the different between Vector and List?
    • No sure is there any thing called list in APL

      1 2 3 × 3 4 9
      # => 3 8 27
      • The small multiply sign latex symbol \(\\times\)
    • gnu-apl create matrix with reshape ρ (rho)

      2 3 ρ 1 2 3 4 5 6
      1 2 3
      4 5 6
    • gnu-apl assign a matrix to a variable

      var ←  2 3 ρ 1 2 3 4 5 6
    • gnu-apl power function, where is the square root function in APL?
      • There is no square root function in APL (Maybe..)
    2*4 = 2⁴
    	2*(0.5) = sqrt(2)
    • gnu-apl log function, where is my log function in APL?
      • Press Cmd Shift 8 ⇒ login function
    2 ⍟ 8 # => 3
    	# log function
    	2 4 8 ⍟  4 16 64   => 2 2 2
    • gnu-apl minimum and maximum function
      • Press Cmd s and Cmd d <- Cmd d is MacOS keymapping..:
    • gnu-apl: sum of n integer \( f(n) = \sum_{1}^{n} n \)

      N ← 1 2 3
      sum  +/N
    • gnu-apl: average or mean, \( g(n) = ∑_{1}^{n} \frac{1}{n} \)

      N ← 1 2 3 
      av ← (+/N) ÷ (1⌈⍴N)
    • Dyalog APL, create a file, write a string to a file and open it If you just try to open an random file, then you will get encode error, no idea how to fix it. I think you need to specify some encoder such as *UTF-8' when opening the file.

      # create a file
      'Hello' ⎕NPUT '/tmp/x1.x'
      v ← ⎕NGET '/tmp/x1.x'
      • Write a vector to a file
      # write 2 dim vector to a file
      # 1. Use ⍕ to convert integer matrix to character matrix
      # 2. Convert 2 dim to 1 dim with ↓
      # 3. Use ⊂, I have no idea why? 
      (⊂↓⍕(2 3⍴⍳10))⎕NPUT '/tmp/x1.x'
      • APL outer product
      	v ← 1 2 3
      	v ∘.× v
      1 2 3
      2 4 6
      3 6 9
      • APL outer product with mod
      v ← 1 2 3
      v ∘.| v
      0 0 0
      1 0 1
      1 2 0
      • Sort each row in an 3D matrix
      ⍝ sort each row in an 3D matrix
      	  sort ← {⍵[⍋⍵]}⍤1
      	  m3 ← 2 3 4 ⍴20?20
      11  1 18  3
      17  4 12 16
       9  5 13  2
      19 10  7 20
       6 14 15  8
      11  1 18  3
      	  sort m3
      1  3 11 18
      4 12 16 17
      2  5  9 13
      7 10 19 20
      6  8 14 15
      1  3 11 18
      • Reduce 3D matrix to 2D matrix, or reduce rank.
      ⍝ Convert 3d matrix to 2d matrix
      m3d ← 2 3 4 ⍴20?20
      2 3 4
      m2d ← ↓m3d
      14 12 16 4  10 8 3 20  15 6 9 13  
      2 11 17 7   5 18 1 19  14 12 16 4 
      2 3
      • Flatten a matrix to a vector, flatten any rank matrix to a vector?
       ⍝ Flatten 3d matrix to a vector
        m3d ← 2 3 4 ⍴20?20
      2 3 4
      18  7 12  1
      19 16 14  2
       6 11 15 20
       3  8 13  5
      10  4 17  9
      18  7 12  1
        ve ← ∊m3d
      18 7 12 1 19 16 14 2 6 11 15 20 3 8 13 5 10 4 17 9 18 7 12 1

      It is similar to foldl in Haskell

      let m = [[1, 2],
               [3, 4]]
      foldl (\x y -> x ++ y) [] m
              -- => [1, 2, 3, 4]
      • Recover the origin matrix from the vector \(v\) with rank 24
       ⍝ Recover the origin matrix from the vector with rank 24
       2  5 12 17
       6 18  4 20
       1  3 19 11
       7 16  8  9
      10 13 14 15
       2  5 12 17
      2 5 12 17 6 18 4 20 1 3 19 11 7 16 8 9 10 13 14 15 2 5 12 17
        ⍴ ve
        2 3 4 ⍴ ve
       2  5 12 17
       6 18  4 20
       1  3 19 11
       7 16  8  9
      10 13 14 15
       2  5 12 17
      • Letter Matrix
      letterMatrix ← 2 3 4 ⍴ ⎕A
      • Count the number of characters from a given string
      ⍝ count the number of characters from a given string 
        string ← 'avocado' 'banana' 'cherry' 'pitaya'
       1 0 0 0 1 0 0  0 1 0 1 0 1  0 0 0 0 0 0  0 0 0 1 0 1 
        mask ← 'a'=string
        +/¨ mask
      2 3 0 2
      • APL map inside a map
      ⍝ map(\x -> map(\e -> e) x) ls
      • Use haskell solve it
      let str = ["avocada", "banana", "cherry", "pitaya"]
      let mask = map(\s -> map(\x -> if x == 'a' then 1 else 0) s) str
      let totla = sum $ map(\x -> sum x) -- => 2 + 3 + 0 + 2 = 7
      • Concatenate a vector and a matrix
      ⍝ Concatenate a vector and a matrix
        v ← 0 0 0
        m ← 3 3 ⍴?⍨10
        1 8  2
        9 4 10
        7 5  6
      	matrix ← 4 3 ⍴ v, ∊m
        0 0  0
        1 8  2
        9 4 10
        7 5  6
      • Select pairs of consecutive rows from a matrix
      ⍝ Select pairs of consecutive rows from a matrix
      0 0  0
      1 8  2
      9 4 10
      7 5  6
        2 -⍨⌿ matrix
       1  8  2
       8 ¯4  8
      ¯2  1 ¯4
      • Concatenate row vector with a matrix
       ⍝ Concatenate a row vector with a Matrix
       rowVector ← 1 2 3 4
       1  2  3  4
       5  6  7  8
       9 10 11 12
      13 14 15 16
        rowVector ⍪ a
       1  2  3  4
       1  2  3  4
       5  6  7  8
       9 10 11 12
      13 14 15 16
      • Concatenate a column vector with a matrix
      columnVector ← ⍪ 10 20 30 40
       1  2  3  4
       5  6  7  8
       9 10 11 12
      13 14 15 16
        columnVector , a
      10  1  2  3  4
      20  5  6  7  8
      30  9 10 11 12
      40 13 14 15 16
      • Add column vector to a matrix
        ⍝ Add a column vector to a matrix
        columnVector ← ⍪ 10 20 30
        matrix ← 3 3 ⍴?⍨10
      3 7 9
      5 1 4
      6 8 2
        columnVector (+⍤1) matrix
      13 17 19
      25 21 24
      36 38 32
      • Add row vector to a matrix
      	⍝ Add a row vector to a matrix
        rowVector ← 10 20 30
      2 5 8
      4 3 9
      6 1 7
      10 20 30
        rowVector (+⍤1) matrix
      12 25 38
      14 23 39
      16 21 37

    3.0.70 Install J programming language

    • Download from J901 zip
    • Following the steps in the Wiki to install jconsole
    • /Applications/j901/bin/jconsole
    • Start jconsole inside Emacs
    M-x j-console
    • array

      i.10  NB => [0..9]
    • fold, or sum the array

      +/0 i.10 NB => 45
    • length of array

      a =: i.10
      	# a   NB => length of array = 10
    • index of array or string

      a =: 'Instrict Geometry'
      	0 { a  NB => I
      	1 { a  NB => n
    • split string

      a =: 'abcde'
      2 3 $ a NB => abc
      		NB => dea
    • Random number, uniform random \([0, 1)\)

       ? 10 $0 NB => generate 10 random number in [0, 1)
       ? 10 10 $0 NB => generate 10x10 matrix in interval [0, 1)
       ? 3 3 $0   
      NB 0.586922 0.415727 0.986659
      NB 0.0970579 0.194989 0.483234
      	NB 0.64026 0.407095 0.457437
    • Random matrix

      • Random matrix in interval \([0, 10)\)
      ? 3 3 $10 
      • Fix random number
      ?. 3 3 $10
    • floor and ceiling

      <. 3.2  NB => 3 , floor
      >. 3.2  NB => 4 , ceiling
    • Rational number

      2r3 + 1r3 NB => 1
    • Complex number, \(z \overline{z} = |z|^2\)

      3j4 * 3j_4 NB => 25 
    • write and read file

      readFile =: 1!:1
      writeFile =: 1!:2

      Write String to file

      	fn =. < '/tmp/x.j'
      'Hello World' writeFile fn

      Read data from file

      fn =. <. '/tmp/x.j'
      	readFile =. 1!:1
      data =. readFile fn
    • Sum array and table

      a =: i.20
      +/ a
      t =: 2 3 $ i.20
      	+/ +/ t
    • Index table, like index string

      t =: 2 3 $ i.20
      0 { t  NB. => first row
      	1 { t  NB. => second row

    3.0.71 Fixed the whitespace issue in the header of block code, e.g. trim whitespace in the header of block code

    3.0.72 Nice Javascript text editor call is pretty good, demo at the following

    • Get data from Json object
      "time": 1576279792814,
      "blocks": [
    		"type": "paragraph",
    		"data": {
    			"text": "This is the text from editorjs"
    	"version": "2.16.1"

    3.0.73 Javascript, select text range from TextArea with selection.(15-11-2019)

    • What problem I want to solve? I try to copy the code block in specific line number. e.g. 1 to n.
    • SO
    • Code example jsfiddle

    3.0.74 Javascript: Javascript Object to json, access json elements

    • Json file
    "name": "Jenny",
    "age": 30,
    "address": {
    	"streetAddress": "100 King St.",
    	"city": "New York"
    "phoneNumber": [
    		"type": "home",
    		"number": "111 111-1111"
    		"type": "fax",
    		"number": "222 222-2222"
    • Access JSON Object from Javascript, parse it with JSON.parse()

      var data = '{"name": "david","age": 30, "address": {"streetAddress": "88 Road","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
      var json = JSON.parse(data);
      alert(json.address.streetAddress); //88 8nd Street
      alert(json["address"].city);       //New York
      alert(json.phoneNumber[1].type);   //fax
      alert(json.phoneNumber.number); //undefined

    3.0.75 Javascript: web storage API, it only works when open localhost or Http protocol. it does not work in local file system in Chrome.

    • sessionStorage does not keep the data when the tab or browser is closed. But localStorage still keeps the data even the tab or browser is closed.
    • You can close the tab and browser and the data still kept in localStorage.(I never know that)
    • localStorage only supports string
    • The maximum limit is 10MB in Chrome. (it mighe be the case in Firefox)
    • You can find out the limit of localStorage in each browser here Limit localStorage

       // check browser support
      // set data
      localStorage.setItem('key1', 'Hello World');
      localStorage.setItem('key2', 'local storage is awesome');
      // retrieve the data
      var value1 = localStorage.getItem('key1');
      var value2 = localStorage.getItem('key2');
    • Run example html


    3.0.76 Javascript: Try to put all javascript editor and Katex together and render Katex in realtime.

    • It is very painful to work with Javascript and I'm looking for some event for each keypress and I realize there is event called onchange on Javascript when text is modified.
    • There is some issue when input Katex code to editor, some whitespace or special char &lt; are included in the string.
    • There is rendering issue such as \(\sum_{i}^{n} x + y\) does not work so far. I have no idea why
    • One option is to change editor to textarea instead and see what is the outcome.
    • Working example Example



    3.0.77 Javascript: Add data to Div Element, textContent and innerHTML

    3.0.78 Javascript: Found a unbalanced head tag in HTML code. I think it causes the Katex rendering issue.(16-12-2019)

    • Fix it, the rendering Katex code is working so far.
    • The nice thing about Katex is the individual tag can be rendered with following function

      var eleId = document.getElementById('latexcode');

    3.0.79 Javascript: It is surprisedly hard to copy partial text from TextArea to clipboard in Javascript

    • I spent lots of time on an answer to copy partial text from TextArea to clipboard. e.g. copy line 2 to line 4 from TextArea to clipboard.
    • Most solutions are copy all the data from elements (such as Div) to clipboard with copy command: document.execCommand('copy')
    • I'm still have trouble to make it to work so far.
    • But It's working on single HTML file here Copy Partial Text to Clipboard
    • It seems to me the data is not selected from TextArea
      • I have checked the id='t1' and it should not be any issue on element Id.
      • The data can selected and passed to copyToClipboard function and the first line is removed from an array.
      • Create an Range object and add the rest of lines to it, and use copy command to copy the data to Clipboard, but it does not work on this step.
      • Write Html to a file and run it with Chrome, but data in TextArea still CAN NOT copied to clipboard
    • Use writeFileBS writeFile ByteString to HTML file, and copy aronlib.js, mystyle.css to a folder and open the HTML file with Chrome
    • Got same error message: 'does not select any thing' which is error in copyToClipboard() function

    3.0.80 Javascript: The order of <script>code</script> and Html code are important in Javascript.

    • For example, if you have event listener to listen an input from a text field then you need to put your HTML code before the addEventListener.

       const inputField = document.getElementById('inputid');
      inputField.addEventListener('keyup', (e) =>{
           const query =;
               delayKeyUp(() => {delayFun(query)}, 2000);

    3.0.81 Javascript: Lambda function

    const fun = (x, y) => x + y;
    // java style
    // Function<Integer, Integer> f = (x) -> x + 1;
    // Bifunction<Integer, Integer, Integer> f = (x, y) -> x + y;
    // C++ style
    // auto f = [](auto& x) -> {return x + 1;};

    3.0.82 Javascript CSS, Modify CSS style value/attribute

    • Use document.stylesheets function to get the field in the style sheet.

      • document.stylesheets[0] \( \Rightarrow \) get the first style sheet.
    • Use styleObj.cssRules[0].style.color to access the style value

      • Change font color
    • [0] means the first field in the style

       <style type='text/css'>
       <script type='text/javascript'>
         function changeColor() {
         const styleObj = document.styleSheets[0];
         console.log('color=' + styleObj.cssRules[0].style.color);
         styleObj.cssRules[0].style.color = 'green';
         console.log('color=' + styleObj.cssRules[0].style.color);
      <input type='button' value='ClickMe' onclick='changeColor()'>
       Euler Leonhard
       Pythagorean Theorem
       Lucas George
       Justin Bieber
       Justin Trudaeu
           Justin Timberlake

    3.0.83 Javascript call function after page is loaded

      document.addEventListener('readystatechange', event => { 
        // When HTML/DOM elements are ready:
          if ( === "interactive") {   //does same as:  ..addEventListener("DOMContentLoaded"..
          alert("hi elements are ready");
          // When window loaded ( external resources are loaded too- `css`,`src`, etc...) 
          if ( === "complete") {
              alert("call after css is loaded");

    3.0.84 Proof logarithm \(\log a^x a^y = \log a^x + \log a^y\)

    • Proof

      \begin{aligned} a^b + 1 &= a^b + a^0 \\ b^a + 1 &= b^a + b^0 \\ a^x a^y &= a^{x + y} \qquad \text{By } \log \text{definition} \\ \log_a (a^x a^y) &= x + y \\ \log_a a^x a^y &= x + y = \log_a a^x + \log_a a^y \\ \Rightarrow \log a^x a^y &= \log a^x + \log a^y \end{aligned}

    3.0.85 Proof function injectivity, subjectivity and composition

    • Given two functions \(f : \mathcal{A} \rightarrow \mathcal{B}\) and \(g : \mathcal{B} \rightarrow \mathcal{C}\)
    • Proof 1:

      \begin{aligned} & \text{If } g \circ f \text{ is injective }, \text{Show } f \text{ is injective} \\ & \text{If } g \circ f \text{ is subjective }, \text{Show } g \text{ is subjective} \end{aligned} \begin{aligned} & g \circ f \text{ is injective} \\ & \Rightarrow \text{ if } g \circ f (a) = g \circ f (b) \text{ then } \\ & \Rightarrow a = b \\ & \text{ If } f \text{ is not injective, then} \\ & \exists x_1, x_2 \in \mathcal{A} | f(x_1) = y \text{ and } g(x_2) = y, x_1 \neq x_2 \\ & \Rightarrow g (f(x_1)) = g (f(x_2)) \\ & \Rightarrow g \circ f \text{ is not injective} \\ & \text{ This contracts our statement } \\ & \Rightarrow f \text{ must be injective} \end{aligned}
    • Proof 2:

      \begin{aligned} & g \circ f \text{ is subjective} \\ & \Rightarrow \forall c \in \mathcal{C} \quad \exists x \in \mathcal{A} \mid g \circ f (x) = c \\ & \text{ If } g \text{ is not subjective} \\ & \exists c \in \mathcal{C} \mid \forall b \in \mathcal{B} \quad g(b) \neq c \\ & \Rightarrow \exists c \in \mathcal{C} \mid \forall a \in \mathcal{A} \quad g \circ f (a) \neq c \\ & \Rightarrow g \circ f \text{ is not subjective} \\ & \text{ This contracts our statement} \\ & \Rightarrow g \text{ must be subjective} \end{aligned}

    3.0.86 Katex and MathJax support commends, environment and functions but they have table problem.

        # it does not working in Katex
           a & b & c & \\ hline
           a & b & c & \\ hline
    • equation does not work in Katex, but it does work in MathJax

            e^{\pi i} + 1 = 0
    • itemize does not work in Katex, but it does work in MathJax
        \item Justin Bieber
        \item Justin Trudeau
        \item Justin Timberlake

    3.0.87 Latex: The difference between $ $ $$ $$ \[ \] and \( \)

    • $ $ is for Tex inline math mode, \( \) is for Latex inline math mode.
    • $$ $$ is for Tex display math mode, \[ \] is for Latex display math mode.


    3.0.88 Latex install package, latex package, install latex package

    • download package from CTAN and unzip it
    • Generate .sty file with *pdflatex command
    • For Example, generate xcolor.sty file from file
    • An xcolor.sty file will be generated
    • Copy xcolor.sty file to your .tex location or a location that pdflatex can find
    • Tex file location in MacOS, or use shell script command
    • xcolor.sty
    # xcolor.sty will be generated
    • latex utility tools

      kpsewhich xcolor.sty
          kpsepath tex

    3.0.89 Install Ace9 to my localhost saved-data-example/example.html, javascript editor

    • Finally it make autocomplete to work, it is painful to include those javascript modules in HTML file.
      • You never understand how the path work in Javascript and Node.js, you need to include following Javascript file.
      • Set your editor options
    <script src="ace/build/src-noconflict/ext-language_tools.js"></script>
      enableBasicAutocompletion: true,
      enableSnippets: true,
      enableLiveAutocompletion: true
    • You need to Add your autocompleter

      var langTools = ace.require("ace/ext/language_tools");
      var myCompleter = {
          getCompletions: function(editor, session, pos, prefix, callback) {
              if (prefix.length === 0) { callback(null, []); return }
              var wordList = ["bmatrix", "vmatrix"];
              callback(null, {
              return {
              caption: word,
              value: word,
              meta: "static"

    3.0.90 Install Vim keybinding in ACE9 editor, all you need is one line of Javascript code.

    • Code can be found here
    • Make sure disable Chrome cVim extension, otherwise there is an issue when Insert mode switches to Normal mode with ESC Key.
    // ace/lib/ace/keyboard
    // emacs

    3.0.91 Fix dotemacs file contains stupid error with two functions with different values

    • I'm wondering why the dotemacs file does not have any color highlight because

      ;; two lines on my dotemacs file
      ;; not following symlink
      (setq vc-follow-symlinks nil)
      ;; following symlink
      (setq vc-follow-symlinks t) 

    3.0.92 C programming: define node using struct, linked list node

    • define a Double LinkedList node

      typedef struct CNode{
         struct CNode* next; // point to next node
         struct CNode* prev; // point to previous node
         void* pt;  // generic data type?
      } CNode;
      int num = 3;
      CNode* pt = (CNode*)malloc(sizeof(CNode));
      pt -> next = NULL;
          pt -> prev = NULL;
      pt -> pt = &num;

    3.0.93 C Programming: Three are three ways to dynamic allocate memmory

    • Code Example Local Code
    • malloc do nothing on the memory, allocate total amount of memory and return a pointer to the location

      int len = 10;
      char* pt = (char*)malloc(sizeof(char)*len);
      for(int i = 0; i < 10; i++){
        *(pt + i) = 'a' + i;
    • calloc zero the memory

      int len = 10;
      char* pt = (char*)calloc(len*sizeof(char));
      for(int i=0; i<len; i++)
            printf("%x\m", pt[i]);
    • realloc reallocate memory with pt, the original data will be copied over to new pointer.

      int len = 10;
      char* pt = (char*)malloc(len*sizeof(char));
      pt = (char*)realloc(pt, 20*sizeof(char));

    3.0.94 C Programming: C struct and typedef

    • Use typedef to define struct in C

       typedef mystuff{
         int n;
         char c;
         float fl;
       } stuff;
      stuff record;
      record.n = 1;
      record.c = 'z';
      record.fl = 3.1415;
        // Structure using typedef:
        #include <stdio.h>
        #include <string.h>
        typedef struct student {
      int id;
      char name[20];
      float percentage;
        } status;
        int main() {
      status record;;
      strcpy(, "Cheetah");
      record.percentage = 86.5;
      printf(" Id is: %d \n",;
      printf(" Name is: %s \n",;
      printf(" Percentage is: %f \n", record.percentage);
      return 0;

    3.0.95 C Programming: Check type such as int, float, double, char, long or struct size

    int num;
    float fl;
    int* int_pt;
    printf("int=[%d] float=[%d] int*=[%d]\n", sizeof(num), sizeof(fl), sizeof(int_pt));
    • how to check the size of struct

      • Note: The size of struct is not always equal to the sum of each fields because the compile will do padding for some types
      typedef struct MyStuff{
            int num;
            double dfl;
      } Stuff;
          Stuff stuff;
          Stuff* stuff_pt;
          printf("stuff=[%d] stuff_pt=[%d]\n", sizeof(stuff), sizeof(stuff_pt));
      typedef struct MySmall{
            int n;
            char c;
      } Small;
          Small small;
          Small* small_pt;
          int total_struct = sizeof(small);
          int total_fields = sizeof(small.n) + sizeof(small.c);
          // totla_stuff /= total_fields

    3.0.96 C Programming: const char *pt and char *pt

    • Mutable pointer to Immutable location
    // const char *pt = "abc";
    const char pt[] = "abc";
    pt[0] = 'K'; // ERROR
    • Mutable pointer to mutable location
    char pt[] = "abc";
    pt[0] = 'K';  // OK

    3.0.97 Redefine command line in Vim with following script

    3.0.98 Vim tips: filter out line with new open window

    • Filter out lines DOES NOT contain ^find and open it in quickfix widnow
    :vimgrep /^find/g | copen

    3.0.99 Vim tips: Insert spaces in font of selected lines

    • Left shift two spaces or insert two spaces in font of selected lines
    :'<,>'norm I[SP][SP]
    :'<,>'norm xx
    :'<,>' call LeftShiftCurrLine(2)

    3.0.100 Vim tips: call function in visual selected lines, function with range

    • MyFun will be called in range '< and >'
    :'<,>' call MyFun()

    3.0.101 TODO Move all the haskell file to $hlib in $b/haskellwebapp2

    • Move all files to $hlib


    3.0.102 TODO Try this code Copy and paste

    3.0.103 TODO Emacs: universal-argument, What the hell is universal-argument?

    • have something to do with C-u See example
    • If your keybinding is C-k, then you can define your prefix key C-u with C-k \(\Rightarrow \) C-u C-k
    • How to capture the universal-argument value? use current-prefix-arg to get the possible values Values

    3.0.104 MacOS: Screen Capture with screencapture command

    • delay 3 seconds to capture your screen
    screencapture -T 3 delayedpic.png

    3.0.105 Change haskell document background color from dark mode to light mode

    • dark mode or light mode \(\Rightarrow \) $scr/ d l

    3.0.106 Haskell some cursor movement and ANSI console color

    • ansi-terminal library, move cursor to nth char to the right/left/up/down, set background and foreground color in console

    3.0.107 Customized Latex Input Method or TeX Input Method in Emacs

    • function name in dotemacs file:
    • latex-input \( \Rightarrow \) set-input-method "TeX"
    • latex-input-symbol \( \Rightarrow \) describe-input-method "TeX"
    • Offical Doc How to Do it Stack Overflow

    3.0.108 iTerm2: iTerm2 profile can be saved in your local folder


    3.0.109 iTerm2: Import profile (JSON) file to your iTerm2

    3.0.110 iTerm2: Fixed tmux and iterm2 problem: backspace key DOES NOT work in

    • Here is step how to fix in iterm2 SO References


    • I just found it does not fix the issue yet. When switch tmux windows, the backspace key still has issue.
    • It does not fix the backspace yet (06-01-2020)

    3.0.111 iTerm2: trigger regex, color highlight in iTerm2


    3.0.112 tmux: fixed copy-mode-vi use 'v' to select text and 'y' to copy text in tmux

    • NOTE: kill all your tmux sessions before restart your tmux. tm l
    • Set your tmux to use Vim keybinding in /.tmux.conf

      set-window-option -g mode-keys vi #copy-mode vim-like 
    • Install reattach-to-user-namespace

      brew install reattach-to-user-namespace
      # run reattach-to-user-namespace to confirm 
    • Confirm reattach-to-user-namespace command

      echo 'hi' | reattach-to-user-namespace pbcopy
      # 'hi' should be in your clipboard
    • Vim like copy with 'y'

      bind -T copy-mode-vi y send -X copy-pipe "reattach-to-user-namespace pbcopy" \; send -X clear-selection # Copy to clipboard

    3.0.113 Haskell: just learn something new today, you can use read function to read a list of type, e.g [1, 2, 3]

    • read a list of Int or Integer

      read "[1, 2, 3]"::[Int]  -- [1, 2, 3]
      read "[1, 2, 3]"::[Integer]

    3.0.114 Java doc: use latex for Java document with java doclet

    • Java Doclet github
    • You need maven to install the Latex Java Doclet or if you want to install the artifact to specific directory

      mvn clean install
      TeXDoclet.jar to $HOME/.m2/repository/org/stfm/texdoclet/0.9-SNAPSHOT/texdoclet-0.9-SNAPSHOT.jar
      dependency-reduced-pom.xml $HOME/.m2/repository/org/stfm/texdoclet/0.9-SNAPSHOT/texdoclet-0.9-SNAPSHOT.pom

    3.0.115 Java: When to pass Iterator or List inside your recursion code

    • When you deserialize your binary tree from a file, then you can think about how to pass the preorder elements to your recursion code
    List<String> list = Arrays.asList("cat", "dog");
    Iterator<String> ite = list.iterator();
    • The following picture shows your why you need Iterator instead of List inside your recursion code.


    3.0.116 Microsoft Phone call interview for Large scale service and distribution system

    • Renell Nakayama-Roberts will call me today. I'm not sure what to expect?
    • She asked me to put her name on the site when I apply the job in MS website.
    • Question: What is your responsibilities in the company?
    • What is the challenge that you have in the project?
    • I will give some overview on our Edge team in MS
    • I will give some overview on the interview process.

    3.0.117 Java: I just learned in Java 9 there is something called Module

    • From Oracle website, Module is a set of packages, I think it is similar to package but it is on top of package

      // define package
      // how to define module?

    3.0.118 English: coercion [kəʊ'ɜʃən]

    • the use of force to persuade someone to do something they are unwilling to do

    3.0.119 Elips: I struggle to figure out how to run Graphviz or dot file under Org-mode in code block

    • When you Google around, you will find lots of wrong suggeston how to set it up.
      • Some sites only tell you that you only need following code inside your init.el or .emacs file
     '((dot . t))) ; this line activates dot
    • The author assume you have added graphviz-dot-mode to 'load-path
    • You copy their snippet to your .emacs and hope you can compile dot file inside your code block and see your awesome image.
    • Unfortunately you can see anything and you don't what to do. But you never give up, and try to Google around and copy more snippet into your .emacs file. and you are still out of luck.

      • most of author did not tell that you need to add the path that points to your graphviz-dot-mode directory. Well, where is the path in your machine?

      most tutorial does not tell you where is your graphviz-dot-mode-xxx directory. Ofcouse you never understand why you can not display image.

    • The default path is $HOME/.emacs.d/elpa/graphviz-dot-mode-xxx, it can be different if you have different configuration path in your your emacs.
      • Once emacs knows the path to your graphviz-dot-mode-xxx, you jut load binary dot to run your dot file with C-c C-c

    3.0.120 Haskell: conversion between numbers, Float to Int, Double to Int, Float to Integer

    ceiling  :: (RealFrac a, Integral b) => a -> b
    floor    :: (RealFrac a, Integral b) => a -> b
    truncate :: (RealFrac a, Integral b) => a -> b
    round    :: (RealFrac a, Integral b) => a -> b
    • Float and Double

      float2Double :: Float -> Double
      double2Float :: Double -> Float
      fromIntegral::(Num b, Integral a) -> a -> b

    3.0.121 Math: Geometric Proof \( \sin{2\theta} = 2\sin{\theta} \cos{\theta} \)


    3.0.122 Jupyter: For Haskell and Python or ihaskell like Python Jupyter lab

    • One quesiton is how to import your own module in Haskell console.
      • Finally I found out how to import your own module to Jupyter iHaskell.
    • I was struggling with how to import my own Haskell module to iHaskell or Jupyter.
      • The solution is dead simple and I have known the answer for long time
      • But the catch is you need to run jupyter-lab under stack with following stack exec jupyter-lab

        :load /Users/cat/myfile/bitbucket/haskelllib/AronModule.hs
    • Goto your the root directory of your stack project run following commands
    stack exec jupyter-lab


    • I still have no clue how to import my own module.(09-03-2020)
    • Jupyter is very powerful tool, you can export your code to many file format such as Html, Latex
    • You can change Dark or Light theme which is very import when you are working at night.
    • Can not figure how to load your own package or module ihaskell
      • From ihaskell github, you need to add your package to your stack.yaml in ihaskell
      • They assume you always keep your ihaskell directory? I think so. And you need to run stack solve && stack install
    • I think you can load your own package from Jupyter console.
      • I wish iHaskell can load your ghci.conf so that you do not need to load all your packages separately.
    • You need to follow the steps to install in Your MacOS iHaskell

      brew install python3 zeromq libmagic cairo pkg-config haskell-stack pango
      git clone
      cd IHaskell
      pip3 install -r requirements.txt
      # stack install gtk2hs-buildtools # Disabled for now because gtk2hs-buildtools doesn't work with lts-13 yet
      stack install --fast
      ihaskell install --stack
      • Check whether you have ihaskell

        which ihaskell
            # your installation successes
      • Run your ihaskell from your command line. Assume you have stack installation.
    stack exec jupyter -- notebook
    • When you open your browser, you most likely DO NOT what to do because it is very confusing, you do not know where to write your code, how to run your code.

      • You need to click on New and select your languages to open the editor.


    • I ask question on Reddit how to change light-mode to dark-mode. The answer is you need to change color theme in Jupyter lab not ihaskell
      • because ihaskell use Jupter as fontend. All you need to do is run Jupyter lab in command line and change color mode like in Python.
    jupter lab




    3.0.123 Haskell: Mutable array, Haskell Array

    • Example Code Mutable Array
    • import library for mutable array
    • create new array, make sure the ::IO(IOArray Int Float) as annotation
    • write element to mutable array
    • read element to mutable array

      import Data.Array.IO
      -- create mutable array
      arr <- newArray (2, 10) 1.0  :: IO(IOArray Int Float)
      -- read index 3 from arr
      n <- readArray arr 3
      -- write 9 to index 3 arr  
      writeArray arr 3 9  
    • Initialize array with list

      mapM_ (\x -> writeArray arr x 3.14) [2..10]
    • Two dimensions mutable array in Haskell

      import Data.Array.IO
      -- create (m, n) array
      arr <- newArray (0, 0) (10, 10) 3.14 :: IO(IOArray (Int, Int) Float)
      n <- readArray arr (2, 2) 
      writeArray arr (2, 2) 6.28
    • Construct mutable array with a list

      let ls = [1..10]
              arr <- newListArray (1, 10) ls
    • map over a mutable array with a function f::a -> b

      arr <- newArray (0, 4) 1
              marr <- mapArray (+2) arr
              -- [3, 3, 3, 3]

    3.0.124 Java: Integer can be 10x slower than int

    3.0.125 Java: Initialize int[] and Integer[] in Java

    • I just realize the default value for Integer[] mat is not zero, instead it is null

       int[] mat = new int[3];
       // mat = {0, 0, 0}
       Integer[] mat = new Integer[3];
      // mat = {null, null, null}

    3.0.126 Java: QuickSort to Kth smallest element

    • Approach the problem
      • Change Kth \( \{1, 2, \cdots, n \} \) to Index \( \{0, 1, \cdots, n-1 \} \)
      • Write a quick sort algorithm
    • write partition code

      int partition(int[] arr, int lo, int hi);
    • write quick sort code

      void quickSort(int[] arr, int lo, int hi){
      if(lo < hi){
             int pivot = partition(arr, lo, hi);
                 quickSort(arr, lo, pivot - 1);
                 quickSort(arr, pivot + 1, hi);
      • Modify quicksort code to branch to left or right branch.
    int quickSortKIndex(int[] arr, int lo, int hi, int kInx){
       if(lo < hi){
              int pivot = partition(arr, lo, hi);
              if(kInx < pivot)
                return quickSortKIndex(arr, lo, pivot - 1);
              else if(kInx == pivot)
                return arr[pivot];
                return quickSortKIndex(arr, pivot + 1, hi, kInx - (pivot + 1));


    3.0.127 MacVim: Render unicode or emoji issue in MacVim,

    • Here is the fix OS goto Preferences \( \Rightarrow \) Advanced \( \Rightarrow \) disable Use Core Text Renderer

    3.0.128 Coin and Coding theory

    3.0.129 Edit String Distance Algorithm: find the minimum weight to convert string \(s_1\) to \(s_2\) in dynamic programming

    • The weight of insection is \(1\)
    • The weight of deletion is \(1\)
    • The weight of substitude is \(0\) if both characters are the same, otherwise \(2\)
    • PDF Reference
    • Minimum Edit String Distance in Java
    • minimum edit distance function: \[ \text{ convert string } s_i \Rightarrow s_j \]

      \begin{aligned} n_i &= \text{ length of } s_i \qquad n_j = \text{ length of } s_j \\ \text{ weight of deletion } w &= 1 \\ \text{ weight of insection } w &= 1 \\ \text{ weight of substitude } w &= 2 \\ i &= 1 \dots n_i \\ j &= 1 \dots n_j \\ D(i, 0) &= 1, 2, 3, \dots n_i \\ D(0, j) &= 1, 2, 3, \dots n_j \\ D(i, j) &= min \begin{cases} D(i-1, j) + 1 \\ D(i, j-1) + 1 \\ D(i-1, j-1) + \begin{cases} 0 \text{ if } d_{i-1} = d_{j-1} \\ 2 \text{ if } d_{i-1} \ne d_{j-1} \end{cases} \end{cases} \end{aligned}



    3.0.130 \(\LaTeX\) What I learn in Latex today

    • Latex environment is defined by \begin{} and \end{}
    • And you can define your own environment by \newenvironment Environments

      • It seems to me the syntax is horrible. Maybe I should not try to understand it.
      Below this line a boxed environment is used
      \begin{boxed}{Title of the Box}
      This is the text formatted by the boxed environment
      This text is again outside the environment

    3.0.131 \(\LaTeX\) What I learn today?

    • I never use floor and ceiling in \(\LaTeX\)
      • Write floor and ceiling is more complicated than what I thought. Why there is no simple command for that?
      • Here is how to write floor and ceiling symbol in \(\LaTeX\)
    \left \lfloor{x} \right \rfloor
    \left \lceiling{x} \right \rceiling

    \[ \left \lfloor{x} \right \rfloor \left \lceil{x} \right \rceil \]

    3.0.132 \(\LaTeX\) Color Your mathematic formulas.

    • Use \color{}{}

      \color{red}{M = \begin{bmatrix}
           a & b \\
           c & d

      \[ \color{red}{M = \begin{bmatrix} a & b \\ c & d \end{bmatrix} } \]

      \color{red}{M = \begin{bmatrix}
           a & b \\
           c & d

      \[ \color{green}{M = \begin{bmatrix} a & b \\ c & d \end{bmatrix} } \]

      \color{yellow}{M = \begin{pmatrix}
           a & b \\
           c & d

      \[ \color{yellow}{M = \begin{pmatrix} a & b \\ c & d \end{pmatrix} } \]

    3.0.133 Excel Column Header: algorithm in Java.(15-11-2019)

    • Need to shift the index from 1 to 0 (n - 1) % base since \(n\) starts from \(1\)
    • Need to shift module to right (n - 1) % base + 1
    • Similar to rotate string to the right or to the left Rotate String


      public static String excelColumn(int n){
          int base = 3;
          String s = "";
          if(n == 1){
          s = "Z";
          while(n > 0){
              int q = (n - 1) / base;
              // n - 1 => shift from 1 to 0 since n starts from 1
              int r = ((n - 1) % base) + 1;  // 1 -> A 
              s = intToAlphabetUpper(r - 1) + s;
              n = q;
          return s;
    • Source Code
    // 1 -> A
    // 2 -> B
    // 3 -> C
    // 4 -> AA
    while( ){

    3.0.134 Interview question: Print Excel column header pattern

    • Given \( n \in \{1, 2, \cdots \} \) print following pattern
    • The problem is different from binary system is the base is not fixed number. The base is Geometric Series

      • If the base is \(3\), then the Excel column header will be based on following Geometric series

      \[ \color{red}{S = 3^1 + 3^2 + \cdots + 3^k} \]

    • If \( n = \{1, 3^1 + 3^2 + 3^3 \} \) then the following pattern will be generated

      \begin{aligned} 3^1 = \begin{bmatrix} a \\ b \\ c \end{bmatrix} \qquad 3^2 = \begin{bmatrix} aa \\ ab \\ ac \\ ba \\ bb \\ bc \\ ca \\ cb \\ cc \end{bmatrix} \qquad 3^3 = \begin{bmatrix} aaa \\ aab \\ aac \\ aba \\ abb \\ abc \\ aca \\ \vdots \\ ccc \end{bmatrix} \end{aligned}
      • \( S \) can be computed with Geometric Series

        \begin{aligned} S &= x^1 + x^2 + \cdots + x^n \\ xS &= x^2 + x^3 + \cdots + x^{n+1} \\ S(x - 1) &= x^{n+1} - x \\ S &= \frac{x^{n+1} - x}{x - 1} \\ S &= \frac{x^{n+1} - x}{x - 1} \\ x^{n+1} &= S(x-1) + x \\ n+1 &= \log_x^{S(x - 1) + x} \\ n &= \log_x^{S(x - 1) + x} - 1 \\ n &\text{ is the closest integer to the sum of geometric series equals to S} \\ \text{Example:} \\ x &= 3 \quad S = 3 \\ \text{ We have following } \\ n &= \log_3^{3(3 - 1) + 3} - 1 \\ n &= \log_3^{9} - 1 \\ n &= 1 \\ \text{We can use } S \text{ subtract } 3^{n=1} \quad \text{which is equal to zero}\\ \text{ from } S &= x^1 + x^2 + \cdots + x^n \\ x &= 3 \quad S = 3 \quad n = 1 \\ \therefore 3 - 3^{1} &= 0 \\ \text{The next geometric series term is } 3^{2} \text{ and the initial value is } 0 \\ \\ &\begin{bmatrix} a & \color{green}{ \leftarrow } 0 \\ b & \color{green}{ \leftarrow } 1 \\ c & \color{green}{ \leftarrow } 2 \\ aa & \color{red}{ \leftarrow } 0 = 3 \\ ab & \\ ac & \\ \vdots \end{bmatrix} \\ x &= 3 \quad S = 10 \\ \text{ If } S \text{ is } 10, \text{ We have following } \\ n &= \log_3^{10(3 - 1) + 3} - 1 \\ n &= \left \lfloor{ 1.58 } \right \rfloor = 1 \\ 10 - 3^{1} &= 7 \\ &\begin{bmatrix} a & \color{green}{ \leftarrow } 0 \\ b & \color{green}{ \leftarrow } 1 \\ c & \color{green}{ \leftarrow } 2 \\ aa & \color{red}{ \leftarrow } 0 = 3 \\ ab & \\ ac & \\ ba & \\ bb & \\ bc & \\ ca & \\ cb & \color{red}{ \leftarrow } 7 \\ cc & \\ \vdots \end{bmatrix} \end{aligned}
      • Use geometric series to solve the problem

        \begin{aligned} S &= x^1 + x^2 + \cdots + x^n \\ xS &= x^2 + x^3 + \cdots + x^{n+1} \\ S(x - 1) &= x^{n+1} - x \\ S &= \frac{x^{n+1} - x}{x - 1} \\ S &= \frac{x^{n+1} - x}{x - 1} \\ x^{n+1} &= S(x-1) + x \\ n+1 &= \log_x^{S(x - 1) + x} \\ \color{red}{n} &= \left \lfloor{\log_x^{S(x - 1) + x} - 1}\right \rfloor \end{aligned}
      • The problem can be solved with permutation \( \{0, 1, 2 \} \) algorithm
        • Each each digit can be repeated
        • The length of string are from \(1\) to \(3\)


    3.0.135 Interview: Partition array

    • Given a list of integer, partition the array to two subarray

      • Sort the array in increasing order
      • Sum them up \( S = \sum_{i=i}^{k} a_i \)
      • Subtract one element one by one in one side until the value is less or greater than the \( \frac{S}{2} \)


    • The question is related to find the square root of integer \( n \)

    3.0.136 Tmux: you can switch window id number between two windows

    • Assume you have two widows 1:Python 2:Java

      # `:
      # -s => source
          # -t => target
      :swap-window -s  1 -t 2

    3.0.137 Command Line: copy and paste on MacOS, copy to clipboard and paste from clipboard

    • copy stdout to *clipboard' and paste clipboard to stdin

      echo 'hi' | pbcopy
          pbpaste > /tmp/kk.x

    3.0.138 Preorder Iterator

    • Write code from the picture
    • How many stack do we need?
    • Where and when we need a marker
    • Actually you do not need a marker for preorder traveral, it is for postorder
    • postorder can be implemented with two stacks

    Sorry, your browser does not support SVG.


    \begin{array}{|c|c|c|c|} \hline & \text{ preorder } & \text{ inorder } & \text{ postorder } \\ \hline \text{ quick sort } & & \text{ one stack } & \text{ two stacks or marker } \\ \hline \text{ merge sort } & & & \\ \hline \text{ build tree } & & & \\ \hline \text{ iteration } & \text{ one stack } & \text{ one stack } & \text{ two stacks or marker } \\ \hline \hline \end{array}

    3.0.139 Emacs: Elisp What I learn from Emacs today? I'm always wondering how to move around without pressing the CTRL key

    • There is Evil mode in Emacs and I did install it on my Emacs but I want something lightway and customized in Elisp.
      • extra-keyboard-modifiers is something very close what I'm looking for.
    • You can set to C-a or C-anything then all the keys will be prefixed with CTRL

      # enable it
      (setq extra-keyboard-modifiers ?\C-x)
      # disable it
          (setq extra-keyboard-modifiers 0)
    • Currently I map it to F10 to toggle between 0 and ?\C-anything

    3.0.140 Emacs: Reload dotemacs file is not necessary to reload everything, Use kill-buffer after reload dotemacs

    # after reload ~.emacs

    3.0.141 Elisp: Good tutorial to learn lisp

    3.0.142 Elisp: Unicode can be the name of function, factorial function

    (defun (n) 
          (if (or (= n 0) (= n 1)
              (* n (⊗ (- n 1)))
     (⊗ 4) 

    3.0.143 Haskell: createProcess in Haskell error

    • Finally I fixed the error from createProcess function Haskell
    • If you run createProcess and DO NOT wait to terminate in the infinite loop then you will run many zombie processes.
      • See runRawCmd in AronModule.hs
      • Fixed error in $b/stackproject/fileWatcher.hs

    3.0.144 Interview partition a binary array to three parts and they all have the same binary values. (Youtube Netflix interview) You Tube

    • The problem is similar to find two sums are the same from a list of integers
      • sort them
      • two pointers from the left and right
      • compare the sum of two end to the middle value
    • If the sum is greater than the middle value increase the big pointer
    • If the sum is less than the middle value increase the small pointer
    • The problem is like a balance with pivot, how to adjust your pivot when both ends are not balanced.
      • Move the pivot to the left or right. when and how?
    • Given a binary array. e.g arr = [0, 1, 1, 0, 1]. find \(i, j\) such as [0, i) == [i, j) == [j, len(arr))

      arr = [0, 1, 1, 0, 1]
      b1 = [0, 1]
      b2 = [1]
      b3 = [0, 1]
      # => b1 == b2 == b3
      arr = [0, 1, 0] # => no such partition 
      • First Observation
    • Create two pointers \(i, j\) from index [0] and index [len(arr)-1]
      • \(i\) will move to the right, increasing i = i + 1. \(j\) will move to the left, decreasing j = j - 1
    • If the left and right parts are the same then compare middle part with one part, e.g. left part.
    • If the middle part is greater than the left part, then shift the \(j\) to the left. \( \Rightarrow \) decrease the middle part and increase the left part. If the middle part is less than the left part, then return No such partition

      • If the left and right are not the same
      • If left \( > \) right then shift \(i\) to the right \( \rightarrow \)
      • If left \( < \) right then shift \(j\) to the left \( \leftarrow \)

    3.0.145 Java compile java file, Run Java, make Java Executable, Jar file

    • It is painful to compile java file

      # jar file is under /mylib/jar
      # is in dir /myjava       
      # /myjava has to be the dir of, Why?..
      # -cp => classpath
      javac -cp /mylib/jar/*:/myjava  /myjava/
      # run class file Loopit in $b/javaclass
      java -cp /Users/cat/myfile/bitbucket/javalib/jar/*:/Users/cat/myfile/bitbucket/javaclass/  Loopit

    3.0.146 Greek Letters

    α \alpha υ \upsilon
    β \beta φ \phi
    γ \gamma χ \chi
    δ \delta ψ \psi
    ε \epsilon ω \omega
    ζ \zeta Δ \Delta
    η \eta Γ \Gamma
    θ \theta Θ \Theta
    κ \kappa Λ \Lambda
    λ \lambda Ξ \Xi
    μ \mu Π \Pi
    ν \nu Σ \Sigma
    ξ \xi Υ \Upsilon
    π \pi Φ \Phi
    ρ \rho Ψ \Psi
    σ \sigma Ω \Omega
    τ \tau    
    \begin{array}{|c|c|c|c|} \hline \\ \alpha & \verb|\alpha| & \upsilon & \verb|\upsilon| \\ \beta & \verb|\beta| & \phi & \verb|\phi| \\ \gamma & \verb|\gamma| & \chi & \verb|\chi| \\ \delta & \verb|\delta| & \psi & \verb|\psi| \\ \epsilon & \verb|\epsilon|& \omega & \verb|\omega| \\ \zeta & \verb|\zeta| & \Delta & \verb|\Delta| \\ \eta & \verb|\eta| & \Gamma & \verb|\Gamma| \\ \theta & \verb|\theta| & \Theta & \verb|\Theta| \\ \kappa & \verb|\kappa| & \Lambda & \verb|\Lambda| \\ \lambda & \verb|\lambda| & \Xi & \verb|\Xi| \\ \mu & \verb|\mu| & \Pi & \verb|\Pi| \\ \nu & \verb|\nu| & \Sigma & \verb|\Sigma| \\ \xi & \verb|\xi| & \Upsilon & \verb|\Upsilon| \\ \pi & \verb|\pi| & \Phi & \verb|\Phi| \\ \rho & \verb|\rho| & \Psi & \verb|\Psi| \\ \sigma & \verb|\sigma| & \Omega & \verb|\Omega| \\ \tau & \verb|\tau| & & \\ \hline \end{array}

    3.0.147 Differential Geometry Note

    • What is manifold
      • One thing pops up on my mind is something like a donut or sphere.
    • How we characterize those surfaces? Good question but I did not have the answer for it.

    I think differential geometry is studying the surface and how to translate the highter dimensions problem to lower dimensions problem. The surface of sphere is like flat surface if you are standing on a large sphere. e.g. we did not know the earth is a sphere until some smart guy figured it out(who, when, how?).

    • How to translate the highter dimensions problem to lower dimensions problem?
      • Map a curve to a line

        • There are many problems with it, e.g. the length of the curve is changed. We might address those problems late. \begin{aligned} &\text{map line to curve}

        f(x) &= x2 + 1 \quad x ∈ \{0, 1\}
        &\text{map curve to line, just project the curve on x-axis}
        f(x2 + 1) &= x \quad x ∈ \{0, 1\}
        &\text{Like const function in Haskell, is called projection function}
        (x, x2 + 1) &= x \end{aligned}


      • Map the curve surface to flat surface, it not always work if the surface has more than one \(z\) values


      • What is smooth manifold?
    • This is not smoothy like strewberry and mikeshake in MacDonald, We are talking about surface.
    • smooth means here is infinitely differentiable, What the hell does it mean?
      • Let see a function \( f(x) = x \), the first derivative is \( f'(x) = 1 \)
      • The second derivative is \( f''(x) = 0 \), and the thrid derivative is \( f'''(x) = 0 \)
      • So \( f(x) = x \) is smooth
    • non-smooth function

      \begin{aligned} &f(x) = x^{\frac{3}{2}} \quad x \in \{0, 1\} \\ &f'(x) = \frac{3}{2} x^{\frac{1}{2}} \quad x \in \{0, 1\} \\ &f''(x) = \frac{3}{4} x^{-\frac{1}{2}} \quad x \ne 0 \\ \end{aligned}
      • \( f''(x) \) is not longer defined when \( x = 0 \)

      Sorry, your browser does not support SVG.

      • What is Chart?
      • What is alta?
      • Manifold is big word but it is simple idea.
    • Embed one dimension object into two dimensions space.
      • What does it mean?

    3.0.148 Derivative of \( \sin{\theta} \) and \( \cos{\theta}\)

    • See the picture first.
    • The derivative of \( \sin'{\theta} = \cos'{\theta} \) and \( \cos'{\theta} = -\sin{\theta} \) It is much easy to look at the picture of \( \sin{\theta} \) because when \( x \in [0, \frac{\pi}{2}] \) the slop of tangent line is positive.

      Sorry, your browser does not support SVG.

    3.0.149 Derive the length of 2D dimension curve.

    Find the length of curve \(f(x) = x^2\)

    \begin{aligned} p_i &= (x_i, y_i) \\ p_j &= (x_j, y_j) \\ d &= \sqrt{(p_i - p_j)^2 + (y_i - y_j)^2} \\ \text{Similarily, we have following} \\ d &= \sqrt{(p_{i-1} - p_{i})^2 + (y_{i-1} - y_{j})^2} \\ \text{Partition interval } [a, b] \text{ into } n \text{ parts } \\ s &= \sum_{i=1}^{n} d(p_{i-1} - p_{i}) \\ \text{if } n &= 2 \text{ we have } \\ s &= \sum_{i=1}^{2} d(p_{i-1} - p_{i}) = d(p_0 - p_1) + d(p_1 - p_2) \\ &\text{Divide the curve into } n \text{ parts} \\ &x_i \in \{x_0, x_1, x_2, \cdots, x_{n-1}, x_n\} \\ &f(x_i) \in \{f(x_0), f(x_1), f(x_2), \cdots, f(x_{n-1}), f(x_n) \} \\ &y_i \in \{x_0^{2}, x_1^{2}, x_2^{2}, \cdots, x_{n-1}^{2}, x_n^{2} \} \\ s &= \sum_{i=1}^{n} \sqrt{(x_{i-1} - x_i)^2 + (y_{i-1} - y_i)^2} \\ s_1 &= \sqrt{(x_0 - x_1)^2 + (x_0^{2} - x_1^2)^2} \\ s_2 &= \sqrt{(x_1 - x_1)^2 + (x_1^{2} - x_2^2)^2} \\ \vdots \\ s_{n-1} &= \sqrt{(x_{n-2} - x_{n-1})^2 + (x_{n-2}^{2} - x_{n-1}^2)^2} \\ s_n &= \sqrt{(x_{n-1} - x_n)^2 + (x_{n-1}^{2} - x_n^2)^2} \\ s &= \sum_{i=1}^{n} \sqrt{(x_{i-1} - x_i)^2 + (y_{i-1} - y_i)^2} \\ s &= \sum_{i=1}^{n} \sqrt{ \Delta x_{i}^2 + \Delta y_{i}^2} \qquad \tags{(1)} \\ & \text{Let } x_i = x(t_i) \text{ and } y_i = y(t_i) \\ & \therefore x_i = x(t_i) , x_{i-1} = x(t_{i-1}) \quad y_i = y(t_i), y_{i-1} = y(t_{i-1}) \\ & x'(t_i) \approx \frac{x(t_i) - x(t_{i-1})}{t_i - t_{i-1}} \\ & x'(t_i) (t_i - t_{i-1}) \approx x(t_i) - x(t_{i-1})\\ & \Delta x_{i} = x(t_{i}) - x(t_{i-1}) \\ & \Delta x_i \approx x'(t_i) \Delta t_i \qquad \text{ where } \qquad \Delta t_i = t_i - t_{i-1} \\ & \Delta y_i \approx y'(t_i) \Delta t_i \\ s &\approx \sum_{i=1}^{n} \sqrt{\Delta x_{i}^2 + \Delta y_{i}^2} \\ s &\approx \sum_{i=1}^{n} \sqrt{ (x'(t_i)\Delta t_i)^{2} + (y'(t_i) \Delta t_i)^{2} } \\ s &\approx \sum_{i=1}^{n} \sqrt{x'(t_i)^2 + y'(t_i)^2} \Delta t_i \\ & \text{ When } n \to \infty \text{ then } \Delta t_i \to 0 \\ s &\approx \sum_{i=1}^{n} \sqrt{x'(t_i)^2 + y'(t_i)^2} \Delta t_i = \int_a^b \sqrt{x'(t)^{2} + y'(t)^{2}} dt \text{ where } t_1 = a, t_n = b \\ \end{aligned}

    3.0.150 Haskell: Learn how to use parser which is parsec package

    • parsec is pretty popular parser in Haskell
    • I'm following this tutorial to write a Scheme Write a Scheme in Haskell
    • Use Parsec. Also there is paper about the it [[
    • So far, it is hard to understand what is Monad Combinator. But it seems to me it is very powerful technic.
    • Parsec uses different Parsec combinator to combine parser with operator <|>. It looks very elegrant.
      • How to use inductive type, sum type in Haskell to define some type in Scheme
    data LispVal = Atom String
              | List [LispVal]
              | DottedList [LispVal] LispVal
              | Number Integer
              | String String
                                      | Bool Bool
    • Above define some Type in Scheme
      • Atom "abc" is an Atom in Scheme

        • It is surprised Bool Bool does not have any error
        • The value constructor Bool Bool wraps Bool type in Haskell to our new type Bool Bool
          • I could not image how to implemente it in Java

    3.0.151 Apparently Java random number generator (Math.random()) use very simple algorithm: linear congrential formula

    • What is Linear Congrential Generator (LCG)
      • \(X_i\) is the seed
      • \(a\) is the multiplier
      • \(c_0\) is the increment
      • \(m\) is the modulus \[ X_{i + 1} = a X_{i} + c_0 \mod m \]

    3.0.152 There is very weird random number result that I got today in Java

    • Use Math.random() * magnitude and Math.round() and longToInteger()
    • Not sure why 0 and 10 are both only half numbers of count comparing to other numbers
     public static void test6(){
        Map<Integer, Integer> map = new HashMap<>();
        for(int i=0; i<100000; i++){
            Integer n = longToInteger(Math.round(Math.random()*10));
            Integer v = map.get(n);
            if(v == null){
            map.put(n, 1);
            v += 1;
            map.put(n, v);
    // output:
    // {0=5007, 1=9905, 2=10126, 3=10053, 4=9934, 5=10180, 6=10011, 7=10062, 8=9934, 9=9981, 10=4807}

    3.0.153 Git tutorial

    • Create new local branch

      git checkout -b mybranch
    • Delete your local branch (be careful)

      git branch -d mybranch

    3.0.154 Git What is rebase

    • Think about linkedlist in Git.
    • Here is tutorial. git rebase
    • When to use merge and rebase?
    • What is HEAD, Master and Origin or Remote?

    3.0.155 Write code to solve following problem, Article Ltd. interview question in Hackerrank

    • Given a list of cities such as [2, 3, 4, 2]. Each city is denoted by by [i] where \( i \in \{0, 1, 2, 3 \} \)


    • If a person travels from city [i] to city [j] then \( i \) must be less than \( j \)
      • The fuel is used from one city to other city is defined by the absolute difference between two cities.
    • city [1] \( \rightarrow \) city [2]
    // fuel is used by the car from city 1 to city 2 is following
        int df = Math.abs([1] - [2]);
    # i < j
    [i] -> [j]  
    let ls = [2, 3, 4, 2]
    ls[0] = 2
    ls[1] = 3
    ls[2] = 4
    ls[3] = 2
    • What problem that we knew that it similar to ?
    • The simplest one is Binary Search Tree problem.
      • Given a Binary Search Tree, from all the paths from the root to the leaf node.

        • It can be solved with preorder traveral and add all the path to List<List<Integer>> lss


    3.0.156 XCode code sign or XCode sign is painful. Apple tries to ask you to pay them for nothing.

    • Apple update your MacOS and change your Xcode code setting, They try to fool you to pay them for nothing.
    • You can not compile your code in XCode, and you need to sign in to your Apple Account. What the fuck?
    • You need to go through millions of setttings in Building Settings and try to find Signing and change to Don't Code Sign



    • Update: XCode 11.31 removes Don't Code Sign
      • Choose Other and put an empty string on it.

    3.0.157 XCode: update to MacOS Catalina 10.15.3 and XCode to 11.3, my cpp library is broken

    • Still have no idea how to build my code so far.
    • Apple remove following header in C++14, and use C++17 <optional>
      • I change my XCode c++14 to c++17 and use <optional> but it got other errors.
      • Path to experinment C++14 optional lib
    // change to
    // C++17

    3.0.158 MacOS Error:

    stack build error  # stack-2.1.3
    ar: internal ranlib command failed

    Fixed it

    but maybe removing ranlib from /opt/local/bin and 
    using system /usr/bin/ranlib fix the issue for you as well.
    • Remove /opt/local/bin/ranlib and symbol link to /usr/bin/ranlib

    3.0.159 Group Representation Theory

    • What is Group Gepresentation Theory?
    • Why we need them?
    • How it can help us to solve problem?
      • Rotation group map to rotation matrix?
    • I have read many pages in Google but I still have no clue what does Group Representation mean

    3.0.160 Virtual Proof of Pythagorean Theorem, and rotate matrix or rotate array in 90 degrees

    Sorry, your browser does not support SVG. \[ a^2 + b^2 = c^2 \]


    • Fact, rotate a square 90 degrees algorithem is indirectly related to following proof

    3.0.161 What to do next?

    • Change responseNothing to repsonse Search Header

    3.0.162 Haskell run inline javacode

    3.0.163 GHC many good plugins

    3.0.164 Add test file to Haskell Stack

    • stack is stack --version 2.1.3
    • use new-template

      stack new helloworld new-template
    • ghc-8.8.x will be download and I change it back to ghc-8.4.x with follwing
      • Change resolver in your stack.yaml file

        # new resolver
            resolver: its-15.5  => ghc-8.8.3
            resolver: its-12.16 => ghc-8.4.x
      • Build it and run it, it seems to me stack exec helloworld does not work any more, why?

    helloworld-exe is in stack.yaml file in section: executable: helloworld-exe

    stack build
        stack exec helloworld-exe

    3.0.165 Haskell stack test error stack test. Finally I fixed the stupid error /opt/local/bin/strip

    • Link
    • cabal copy failed, It turns to be bad version of /opt/local/bin/strip in MacOS
    • MacOS 10.15.3 Catalina, stack version: 2.1.3
    • This is very stupid error after I upgraded my MacOS to 10.15.3 Catalina
      • There are two strip on MacOS, one is in /opt/local/bin/strip, other one is in /usr/bin/strip

    and stack test uses /opt/local/bin/strip which is the problem. Why? who know..

    • This /opt/local/bin/strip is not working when I use stack test command to run test cases
    • Apparently you need to use /usr/bin/strip instead so you need to rename it and create symbol link to /usr/bin/strip
    /opt/local/bin/strip  # rename it, strip_old
        ln -s /usr/bin/strip /opt/local/bin/strip

    3.0.166 Haskell stack file watch

    • Rebuild automatically. --file-watch option. Build file automatically when files are modified

      stack build --file-watch
    • Fast rebuild. --file-watch --fast --pedantic which turns off -o0 optimization

      stack build --file-watch --fast
          # use --pedantic flag if you want to fix all warning (-Wall and -Werror).
      stack build --fast-watch --fast --pedantic

    3.0.167 Haskell NonEmpty list from package Data.List.NonEmpty

    • You dont need to worry head last tail init problem when the list is empty

      :m +Data.List.NonEmpty
      ls = 3 :| [4]
      lss = 2 <| 1 <| ls

    3.0.168 Neovim can use vimrc file with following command nvim

    • But Timer or Channel does not work so far. Not sure why
    • Neovim use /.config/nvim/init.vim file as vimrc file
    nvim -s ~/.vimrc 

    3.0.169 Add Python code template to generatecode.hs file.

    3.0.170 Python: GUI, Kivy is pretty impressive GUI for Python.

    3.0.171 Python: Generate source code color highlight with Pygmentize

    # full Html document
    pygmentize -f html -O full -o test.html

    3.0.172 Python: Install Jedi package in Emacs for autocomplete, there is some issues on virtualenv error. (28-01-2020)

    • Jedi document.
      • How to install Jedi.
      • How to config your .emacs file
      • Apparently, it does not work for me.
    • I got some error messages:

      Error (jedi): Failed to start Jedi EPC server.
      You may need to run "M-x jedi:install-server".
      This could solve the problem especially if you haven't run the command yet
      since Jedi.el installation or update and if the server complains about
      Python module imports.
      • You need to add the following to your .emacs to fix it
    • And you need to install visualenv on your system.

      pip install virtualenv
    (custom-set-variables '(jedi:environment-root "jedi"))
    • Here is the link, it help me to fix the issue: Python Emacs Install Jedi
    • Python file is loaded you need to run M-x jedi:install-server
    • It works so far, it also autocompletes your own module.
    • Just found out some issues:
      • some name is not from my own module but it shows up in the autocomplete list, no idea why
      • It is a bit slow to show up the autocomplete list items on Emacs, not sure why

    3.0.173 Python: draw binary tree with Python

    • It is not that simple to draw binary tree with Python GUI tkinter code.
      • This is very minimum code to write a circle
    from tkinter import *
    root = Tk()
    myCanvas = Canvas(root)
    create_circle(10, 10, 5, myCanvas)
    • Write code to traveral the binary tree
    • Store coordinates in each nodes
    • Get the relationship between parent and child, e.g. a list of edges
    • Keep track of the level of each node


    3.0.174 Python Version Hell:) python3 numpy can not be found in MacOS Catalina

    • There ther three different versions of Python on my MacOS Catalina, python python2 python3 so far under /usr/local/Cellar
      • After upgrade my MacOS to Catalina and Python has hard time to find their libraries
            import numpy as np
            # error numpy can not be found

    3.0.175 Python import package in full path? why?

    • There are too many versions of python on your MacOS and I have no idea which version of framwork I'm using

      • SO It seems to me this is best way to resolve confusing
      import sys
      import numpy as np

    3.0.176 XCode error, Swift 5 using wrong SDK on MacOS

    • MacOS Catalina 10.15.4, Swift 5, and XCode Version 11.3.1 (11C504)
    • See my post on Reddit Swift 5 Error



    • Change macOS SDK inside Build Settings does not affect SDKROOT points to OLD SDK under

    • I did follwoing someone suggestions on Reddit and deleted my App in

    • Restart My XCode and still DOES NOT Fix above error.

    3.0.177 XCode how to edit your scheme in XCode, manage scheme, xcode scheme


    3.0.178 Haskell ReaderT best explanation Tom and Jerry Example

    3.0.179 Haskell (->) r is a Functor, best explanation

    • Partial function (->) r is Functor Best explanation
    • Good YouTube Video Partial Function as Functor

      class Functor f where
        fmap::(a ->b) -> f a -> f b
      instance Functor Maybe where
        fmap _ Nothing = Nothing
        fmap g (Just x) = Just (g x)

    3.0.180 Sqlite3 Java insect, select, update batch insection

    • Sqlite3 Batch insection Java Setup.
      • Set auto commit to false
      • Create PrepareStatment
      • Batch rows
      • Execute batch
      • Commit
      • Set auto commit to true
    • Show me your code

    3.0.181 Fixed issue in bitbucket javascript folder. You thought you have checkined your code, but it is not.

    • Folder contains git info such as .git and .gitignore. It will cause issue when your folder inside a git.
    • Just fix the issue after I remove .git and .gitignore in order to push eletron-quick-start to bitbucket

    3.0.182 The Good and Bad of Nodejs and Eletronjs

    • Good: It is easy to install package and it is easy to use. It is just Javascript
    • Bad: I always encouter a bug when I create a simple popup UI called at $b/javascript/popupshare The code is really simple, you can image what if you want to create some complicated UI.

    3.0.183 Haskell, monad binding operator: =<< >>=

    • =<< >>= both are same operator, monad binding

              -- simplifed version of definition
      class Monad m where
        (>>=) :: m a -> (a -> m b) -> m b
              return:: a -> m a
      -- actual definition
      class Applicative m => Monad (m::* -> *) where
        (>>=) :: m a -> (a -> m b) -> m b
        return :: a -> m a
              (=<<) :: (a -> m b) -> m a -> m b
              let m = Just 2
              return =<< m  --  => return 3
              m >>= return  --  => return 3

    3.0.184 Python startup file, Yep, Python does not have startup file like bashrc

    • But Python have environment variable called PYTHONSTARTUP
    • Of couse the author will have story to tell because startup file will blow up your computer.
    export PYTHONSTRTUP=$b/publicfile/
    • You can import all your module in the

    3.0.185 Install Node error, brew install node --without -npm

    • Error to install node on MacOS, Remove --without -npm Fixed
    rm -rf /usr/local/lib/node_modules
    brew uninstall node
    brew install node --without-npm
    I got following error: any suggestions?
    Error: invalid option: --without-npm
    macOS hight Sierra

    3.0.186 Emacs Elisp: autocompelte completing-read

    (completing-read "test: " '("a" "b" "c"))
      (let ((completions '(("foobar1" "~/foobar1/") ("barfoo" "/usr/barfoo/") ("foobaz" "/hello/"))))
    (cadr (assoc (completing-read "Complete a foo: " completions) completions)))

    3.0.187 OpenGL Haskell: Fixed GLFW, GLFW-b and bindings-GLFW issues in OpenGL in Haskell

    3.0.188 What I have done so far.

    • Fixed OpenGL, GLFW and bindings-GLFW, GLFW-b problem in Haskell
    • Read doc about *Projective Geometry", Yep, the best note from U of T

    3.0.189 Binary Search Duplicate element in an array


    3.0.190 Download MacVim and install it, does not work so far, can not build..

    3.0.191 Fixed very stupid bug in haskellwebapp2 because Javascript ondblclick does not work suddenly

    • Because I changed the mouse double click speed in *System Preferences' on MacOS.
    • Use Chrome to debug HTML and Javascript to figure out the issue.
      • Edit the Html and Reload your HTML code.
      • Chrome to set break point in Javascript code.

    3.0.192 The best explanation for Projective Geometry

    3.0.193 Fixed error on groupBy method in Java library

    • Not sure why when I messed up the groupBy method in
      • Just fixed it.

    3.0.194 Rename a domain name.26-05-2020

    3.0.195 New code to find the maximum element from a sorted rotated array

    3.0.196 Run ghci like command line in Shell

    3.0.197 CMake is hard, why it so complicated to write a build script

    • People say CMake is easy because everything is function.
    • Why CMake try to reinvent the new language to write a CMake file?

    3.0.198 Git add submodule and delete submodule

    • It seems to be cool to use git submodule, but it is almost impossible to delete a submodule without a page of commands.

    3.0.199 Load script in Julia julia

    # julia console   

    3.0.200 Run Julia and Jupter notebook

    • Run julia julia in command line and run following in julia prompt

      using IJulia

    3.0.201 Julia: Pkg is not found, You need to use using Pkg first

    using Pkg

    3.0.202 PDF keyword search tool rga

    3.0.203 Write Latex on MacOS

    • What is tex and TeX Live 2012 and TeX Live 2020
      • What I have TeX Live 2012 on my Macmini which is pretty old Mac. Run following command.
    • I just found out My MacOS is too old which is 10.12.6, MacTex 2020 needs 10.13
    • some packages are missing
      • What is the problem?

    If you use different packages on your Latex file, then you will need to install those packages on your system. It is pretty painful for MacOS, and there are no unversal package installation tool on MacOS.(I don't know what tool to install \( \LateX \) packages I read many post online and they recommand to install MacTex 2020. Well, just do what other user suggests you to do if you don't know what you are doing.

    • You can download packages from ctan. Some files are called *.dtx and you can run tex pagecolor.dtx to install it.

    3.0.204 haskllwebapp2 project: move Javascript and CSS file to js and css folder

    • It seems to me it works so far.
      • When copy the binary file to $ff/mybin, need to copy the symbolic link as an actual file instead
    • I use rsync to copy

    3.0.205 Home Brew Install gsed or gnu-sed, not sure there is any different between them

    brew install gnu-sed

    3.0.206 Why ssh is stupid? What is known_hosts and what is authorized_keys

    • I try to figure out how to use public key to authenticate to my Ubuntu host. Well, I was missing to add the public key to authorized_keys file.
    • Why you need to add the public key to the file?

    3.0.207 Move haskellwebapp2 image to bitbucket/image, nothing is impressive.

    3.0.208 Try to use HaskeLine package to do some console input line stuff. 15-06-2020

    • Well, it seems to me Haskeline use Monad Transform which I have no idea how it works.
      • Package name Haskeline Example code LineInput
      • I try to run some shell command inside the getLineInput or loop and I can not match the Type
    • There is type called InputT or InputT IO (Maybe String) I have no idea what it that.
      • Maybe it is good idea to learn Moand Transform right now.

    3.0.209 Egison and pattern match.

    • Egion is written in Haskell but you can not use inside your Haskell code directly
    • egison-haskell can be used inside your Haskell code using Haskell template

      :m +Control.Egison
      :set -XQuasiQuotes
      :set -XGADTs
      matchAll [1,2,3] (List Integer) [[mc| $x : $xs -> (x, xs)|]] -- [(1,[2,3])]

    3.0.210 Serialize Binary Tree and Preorder traveral and parse prefix expression

    • I just realize there is connection between Serialize Binary Tree and prefix expression

      (* (+ a b) (+ x y))
          ;; * + a b + x y
      • buildTree in Java code
      List<String> ls = new ArrayList<>();
      Node buildTree(Iterator<String> ite){
          Node node = null;
          String s =;
          if (isOpe(s)){
              node = new Node(;
              Node left = buildTree(ite);
              Node right = buildTree(ite);
              node.left = left;
              node.right = right;
              node = new Node(s);
              return node;

    3.0.211 There is no color in org-mode and I just realize I need a package called *Hmltize"

    • M-x list-package and click install, done!

    3.0.212 Haskell: understand newtype State s a = State{runState::s -> (a, s)}

    • Record State has one field which is runState, its type is a function
    • It is confusing and hard to understand.

      newtype State s a = State{runState::s -> (a, s)}
              runState :: State s a -> s -> (a, s)
    • newtype only allow ONE type parameter and ONE field

      newtype State s a = State{runState::s -> (a, s)}
      --      |  m  | a           ↑
      --                          --- one field
              --         m::* -> *
    • Compare to Identity Monad

      newtype Identity a = Identity{runIdentity :: a}
      -- runIdentity is like a getter in OOP language
              -- e.g.
              let myid = Identity{runIdentity = 3}
              :i myid
              myid::(Num a) => Identity a
    • Find out the difference between data and newtype, and see whether they convert to each other in compiling time.
    • runState is Function type in Haskell
    • There is a few things that need to be clarified here.
      • Understand Record in Haskell because Record in haskell is very confusing.
    • You can NOT use the same name in your record if there is other record contains the name
    • R1 and R2 both have the same name

      data R1 = R1{name::String, age::Integer}
      data R2 = R2{name::String, addr::String}
      • Record is just function in Haskell.

        data MyRecord = MyRecord{name::String, age::Integer}
        -- Haskell generate two functions
        -- getter in Java
        name::MyRecord -> String
                age ::MyRecord -> Integer
        let record = MyRecord{name = "uvw", age = 20}
        name record -- => "uvw"
        age record  -- => 20
      • If Record has one field, then there is shortcut to create a record

        data MyRec = MyRec {name::String}
        pp $ name $ MyRec $ "value" -- value
      • Similarily, State has only one field, runState, whose value is a function

        newtype State s a = State{runState :: s -> (a, s)}
        let f = runState $ State $ \s -> (1, s)
                pp $ f "Justin Bieber" -- (1, "Justin Bieber")
      • Understand Monad slightly.
    • First, What is Monoid ?
      • Monoid is abstract algebra structure, a triple \((M, \otimes, e)\) which satisfies following axioms:
        • If \( a, b \in M \) then \(a \otimes b \in M\) (Binary Operation)
          • If \( a \in M \) then \( \exists e \in M \) such that \( e \otimes a = a \otimes e = a\) (left and right identity)
          • If \( a, b, c \in M \) then \( a \otimes b \otimes c = a \otimes (b \otimes c) \) (Associative)
    • What is Monad ?
      • Good Monad Post
      • Monad is a Monoid.

        • \(M\) contains all the functors
        • Identity is η : I ⊗ T → T and T ⊗ I → T
        • Binary Operation is μ : T ⊗ T → T
        • Satisfy following monad laws
        • T ⊗ T ⊗ T = T ⊗ (T ⊗ T) Associative
          • law2
      • Monad is a Monoid if the element is endofunctor and the operation is Functor composition

        join $ Just (Just 2)
        \begin{align*} & T \in M \\ & \otimes : T \times T \rightarrow T \\ & \otimes : I \times T \rightarrow T \end{align*}

    3.0.213 Nano parser: Here is the full code for nano parser from Stephen Diehl

    3.0.214 Check MacOS Idle time, this will tell you how long it's been since you the mouse or a keystroke was pressed.

    /usr/sbin/ioreg -c IOHIDSystem | grep HIDIdleTime
    • OS shell script
    • Perl script to check idle time on MacOS Perl script
    • Wrote a Haskell code to check MacOS Idle time with following bash command checkIdleTimer

      ioreg -c IOHIDSystem | grep HIDIdleTime
          # shell script to run
      p=$(checkIdleTimer); while [[ "$p" -le 5 ]]; do echo "$p"; p=$(checkIdleTimer); sleep 1; done

    3.0.215 What is Identity functor in Haskell, Here is the discussion in SO

    3.0.216 Use Emacs elisp as script language in command line

    #!/usr/local/Cellar/emacs-plus/26.3/bin/emacs --script
    (message "The current directory is %s" default-directory)
    # emacs --script myelisp.el

    3.0.217 Delete maximum or minimum node in a Binary Search Tree is non trivia task.

    • You can not delete the root if there is only one node in the Binary Search Tree in java because you can modify a object reference. It can be done in C++ because argument can be passed by reference.
    • First, find the minimum or maximum value reference from a Binary Search Tree is easy task. Second, delete the reference node from the Binary Search Tree.
      • If we know which node will be deleted then we need to find the node in the BST
      • Once we find the node, we are ready to d]elete it. There are a few cases that need to be consided.
    • First, easy case: if the node have no left and right branch then we just delete it
      • But we need to have a parent to the current node so that we can delete the current node.
    • Second, if the node has one branch such as right or left branch.
      • if the node has right branch only
        • we find the min value of the right branch and swap it with the node that we want to delete.
        • recurve to the right branch and the deleted node is the min value node.
          • if the node has left branch only
        • we find the max value of the left branch and swap it with the node that we want to delete
        • recurve to the left branch and the deleted node is the max value node

    3.0.218 Python Hell, pip3, pip3.7 and pip3.8 \(\Rightarrow\) python, python3.7 python3.8

    • A few days ago, There is error when I run my Python script $b/ The script is actually very useful and it monitors whether a file is modified or not. Suddenly, the numpy, matplotlab are both not working, I have no idea why. Today, I just found out there are pip3.7 and pip3.8 on my /usr/local/bin and I try to install numpy and matplotlab with pip and pip3, pip3 is not found.. then I tried pip3.7, there is error. And I try pip3.8, it works.. So I have no idea when and who change from pip3 to pip3.7 and pip3.8 in my system.

      pip3.8 install numpy
      pip3.8 install matplotlab

    3.0.219 Java Optional, isPresent, get

    • Create Optional Object with Integer 3
    Optional<Integer> opt = Optional.of(3);
    • Check whether Optional contain any value
      Optional<Integer> opt = Optional.of(3);
    • Optional in lambda
    Optional<Integer> opt = Optional.of(3);
    opt.isPresent(value -> {System.out.println(value)});

    3.0.220 Jacobian Matrix, What is Jacobian Matrix? When to use Jacobian Matrix? What is the simplest form of Jacobian Matrix

    • What is Jacobian Matrix?
    • What is the geometric interpretation of Jacobian Matrix?
    • Add more here

    3.0.221 Found a bug there has been in the code for many years. isBST

    • Check whether a Binary Tree is Binary Search Tree
    • The code uses recursion. Here is the wrong code
    Node isBST(Node root, Node prev){
    if( root != null){
       if(!isBST(root.left, prev))
      return false;
       if(prev != null && >=
      return false;
           prev = root;
       if(!isBST(root.right, root))
      return false;
        return true;
    • Arguments can not been passed by reference in Java like C++ with &ref
      • Fixed version isBST. Use array of node instead of just node.
      Node isBST(Node root, Node[] arr){
    if( root != null){
      if(!isBST(root.left, arr))
         return false;
      if(arr[0] != null && arr[0].data >=
         return false;
          arr[0] = root;
      if(!isBST(root.right, arr))
         return false;
    return true;

    3.0.222 Why it is so hard to figure What is JAVAHOME in your MacOS (21-07-2020)

    • How to find JAVAHOME?
      • Check java or javac, it is a symbolic link most likely.
      • JAVAHOME means it contains bin/java bin/javac etc.
    • Try to install Groovy and realize Groovy can not find JAVAHOME because I have different versions of JDK and I have no idea which one that I use it currently.
    • Normally I do not like to set JAVAHOME because it is not very reliable. It will break your java and javac after new JDK is installed.

      • Checking javac and it shows javac is symbolic link to following dir.
      /usr/bin/javac -> /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/javac
      • Goto following dir
      • There is command called java_home and you need to run the command to show where is JAVAHOME
          # following is JAVA_HOME

    3.0.223 Groovy connect to mysql(22-07-2020)

    • Groovy Version: 3.0.4 JVM: 14.0.1 Vendor: Oracle Corporation OS: Mac OS X
    • Groovy Mysql Connect Example
    • Groovy Connect string to mysql

      import groovy.sql.Sql
      import java.sql.*
      import com.mysql.jdbc.*
      def url = 'jdbc:mysql://localhost:3306/testdb?autoReconnect=true&useSSL=false'
      def user = 'user1'
      def password = 'password'
      // def driver = 'org.hsqldb.jdbcDriver'
      def driver = 'com.mysql.jdbc.Driver'
      def sql = Sql.newInstance(url, user, password, driver)
      sql.execute('DROP TABLE mytable2 IF EXISTS mytable2')

    3.0.224 Groovy can be Java script language, why it is not very popular?

    • Groovy Mysql Connect
    • Groovy connect to Mysql

      • MacOS login to mysql server
      • login → mysql -u user1 -p
      • database → testdb
      • user → user1
      • passwd → password
      mysql -u user1 -p  # passwd: password
          # database -> testdb
    • Groovy is dynamic and strong type programming language?

      def str = "abc"
    • Call Java static method, no more semicolon

      	import static classfile.Aron.*;
      def str = "abc"
      var ls = list(1, 2)
    • Groovy use Java class in Groovy code.

      class MyClass{
         public MyClass(){}
      	MyClass c = new MyClass()

    3.0.225 Groovy: compile groovy file on MacOS

    • How to compile groovy file, use shell script $b/script/


    3.0.226 Groovy: Json, read Json, parse Json

    • Create Json Parse Json
    • Write Json To File

      import groovy.json.JsonOutput
      def data = [
        name : "Justin Bieber",
        year : 2020,
        timestamp : "2020-03-01T00:00:00",
        array : [ "Justin Trudeau", "Cheetah", "Injective", "Subjective"],
        pi    : 3.1415
         def json_str = JsonOutput.toJson(date)
         def file = new File('/tmp/f.x')

    3.0.227 Design Groovy script to add file paths to database table.

    • Input File

      • file contains all the paths
          # file.txt
    • Text File Generator
      • Generate one txt file for each path
    • Read a given directory and iterate all files to a list
    • Write the list to a text file.
    • Text File Collector
      • Iterate a directory and collect all the txt file and return a list of string
    • Mysql Database

      • Create table to store file paths
          # database: testdb
          # table: testtable1
      CREATE TABLE testtable1(
        path TEXT NOT NULL,
        PRIMARY KEY(id))
    • Text File To Database Table
      • Read each txt file and use LOAD DATA INFILE to load txt file to one table
    • Merge Mysql Tables at once.
      • Use Mysql merge command to merge all tables

    3.0.228 Org mode file to Html without any color

    • If you run emacs --deamon to compile orgmode to Html, then there is no color in the code block. Not sure why

    3.0.229 Install OpenCV on my old MacMini

    brew install opencv

    3.0.230 Fixed stupid mistake and I have no idea why $b/javalib/jar/AronLib.jar is deleted and Groovy suddenly DOES NOT work any more today.

    • I tried to install opencv with brew install opencv on my MacOS and it took more than five hours to build and it failed at the end because there is issue with icu4c Unicode library on my MacOS. I have no clue why.
    • After I check my jar path $b/javalib/jar and jar file AronLib.jar is deleted… Why… I never delete it..
    • Rebuild and it works again for all Groovy script.

    3.0.231 Install exa replacement for ls which is written Rust, which is C++ killer, (KEY: ls command, ls replacement)(30-07-2020)

    • Install exa

      • Github URL exa
      • Install under $HOME/.cargo/bin/exa dir
      cargo install exa
      • exa command example
      exa -l 


    3.0.232 Install procs rust command line tool, it took forever to install it, what the hell?

    • Better color?
    proce  # ps aux

    3.0.233 Haskell ghci load module are confusing, load module problem

    • If you load your module in ./ghc/ghci.conf and run stack ghci in a stack project then you might not see all your modules are loaded from ghci.conf file why? because ghci only load module are in your src/Main.hs. I just realize that and I don't understand why my modules are in ghci.conf are not loaded.
    • Add moudle to src/Main.hs if you want to load them.

    3.0.234 Microsoft Interview in Auguest 8, 2020

    • There are three questions on the coding interview in online coding site: Codility
    • First Question
      • Given an Integer \(n > 0, n \in \mathbb{N}\) print out all the lines according to following rules
    • If \(2\) is the divisor of \(\mathbb{N}\) then print out a line "Codility"
    • If \(3\) is the divisor of \(\mathbb{N}\) then print out a line "Test"
      • If \(5\) is the divisor os \(\mathbb{N}\) then print out a line "Coders"
    • Otherwise, print out a number \(\mathbb{N}\) in one line
    n = 1
    n = 2
    n = 3
    void printLines(int n){
       if(n % 2 == 0 && n % 3 == 0 && n % 5 == 0){
       }else if(n % 2 == 0 && n % 3 == 0){
       }else if(n % 2 == 0 && n % 5 == 0){
       }else if(n % 3 == 0 && n % 5 == 0){
       }else if(n % 2){
       }else if(n % 3){
       }else if(n % 5){
    • Second Question
      • Given a string contains only \(\textit{upper}\) and \(\textit{lower}\) case alphabets \(\{ a b E b C e c \}\).
    • Find the same maximum of \(\textit{upper}\) and \(\textit{lower}\) case \(\textit{alphabet}\) from the string.
    • The maximum of \(\textit{upper}\) and \(\textit{lower}\) is defined as following

      • \(\{ a < b < \dots < z \}\) and \(\{ A < B < \dots < Z \}\)
      • The maximum of \(\{ b a c \}\) is \(\{ c \}\)

        • The maximum of \(\{ E A C \}\) is \(\{ E \}\)

        For a given string

      • \(\{a b c e \}\) and \(\{ B \}\) only have one common alphabet \(\{ B \}\) \(\Rightarrow\) \(\{ B \}\) is the maximum.
      • For a given string


        \(\{a b c e k \}\) and \(\{ E \}\) do not have common alphabet. \(\Rightarrow\) is empty string

    • Solution:
      1. Process a given string to two strings such as \(s_1. s_2\), \(s_1\) contains only \(\textit{upper}\) cases alphabet and \(s_2\) contains only \(\textit{lower}\) cases alphabet.
      2. Sort \(s_1, s_2\) in increasing order.
      3. Take one alphabet from each string \(c_1 \in s_1\) and \(c_2 \in s_2\) from maximum ends.
      4. Compare them, \(c_1 = c_2\), if both are the same alphabet in \(\textit{upper}\) and \(\textit{lower}\), then return the alphabet. Done.
      5. Otherwise, remove the maximum alphabet \(\max{c_1, c_2}\).

        1. Goto step 3
        • Solution
      6. Generate two strings from a given string
      7. Sorted the two strings
      8. Compare the two strings
    String maximumStr(String s){
        String ret = "";
        List<Character> su = list();
        List<Character> sl = list();
        for(int i = 0; i < len(s); i++){
        PriorityQueue qu = new PriorityQueue<>((x, y) -> y.compareTo(x));
        PriorityQueue ql = new PriorityQueue<>((x, y) -> y.compareTo(x));
        while(!qu.isEmpty() && !ql.isEmpty()){
        Character up = qu.peek();
        Character lo = ql.peek();
        Character ulo = Character.toUpperCase(lo);
        if(up == ulo){
            ret = up;
            if(up < ulo)
            return ret;
    • Third Question:
      • Given an Integer(positive or negate or zero) \(n \in \mathbb{N}\), insert an Integer \(5\) to any postion.
        • Find the maximum of all the possible integers
    • Example:
      • Given integer \(123\), the maximum of all possible integers is \(5123\)
    • Given integer \(0\), the maximum of all possible integers is \(50\)

      Integers maxValue(Integers n){
          Integer mValue = 0;
          if(n > 0)
          Integers mValue = Integer.MIN_VALUE;
          else if(n < 0)
          Integers mValue = Integer.MAX_VALUE;
          mValue = 50;
          if(n < 0){
          Integer m = -n;
          String nstr = m.toString();
          String nstr = n.toString();
          for(int i = 0; i <= len(nstr); i++){
          // "ab" => "" "ab", "a" "b", "ab" ""
          //           i=0      i=1     i=2
          String left = nstr.substring(0, i);
          String right = nstr.substring(i, len(nstr));
          Integers num = Integer.parseInt(left + "5" + right);
          if(n > 0){
              if(num > mValue)
              mValue = num;
          }else if(n < 0){
              if(num < mValue)
              mValue = num;
              return n >= 0 ? mValue : -mValue;

    3.0.235 OpenGL Haskell GLFW

    • Try to figure how to render some text using Haskell OpenGL GLFW, but GLFW-b does not have drawing at all.
    • GLFW which provides a simple API for Creating Window and Contexts and Surfaces, receiving input and events.
    • GLUT \(\Rightarrow\) OpenGL Utility ToolKit can draw sphere:)
    • I still have no idea how to render text inside Haskell OpenGL.

    3.0.236 OpenGL GLFW-b glfwWindowHint does not work in Haskell GLFW bindings-GLFW (16-08-2020)

    • glfwWindowHint
    • You Should Remove glfwWindowHint from your Haskell OpenGL GLFW code. I have no idea why
      • Update 17-08-2020
      • Apparently macOS users need to use different Enum in glfwWindowHint
    • See Cpp Code Example it works in macOS

      glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
      glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    • Code to check macOS OpenGL version and Video card Check OpenGL CPP macOS
    • Haskell GLFW See Following Window Hint data constructors

      WindowHint'OpenGLForwardCompat !Bool     
      WindowHint'OpenGLDebugContext !Bool      
      WindowHint'OpenGLProfile !OpenGLProfile
    • See GFLW glfwWindowHint Ref

      macOS: The OS only supports forward-compatible core profile contexts for OpenGL versions 3.2 and later. 
      Before creating an OpenGL context of version 3.2 or later 
      you must set the GLFW_OPENGL_FORWARD_COMPAT and GLFW_OPENGL_PROFILE hints accordingly. 
      OpenGL 3.0 and 3.1 contexts are not supported at all on macOS.
    • Haskell OpenGL GLFW Example
    # stack ls dependencies

    3.0.237 OpenGL Shader Tutorial 1

    3.0.238 OpenGL Use Fragment Shader to draw simple curve

    • Vertex and Fragment shader code are in inside C++ code.

      • Vertex shader code.
      #version 330 core
      layout (location = 0) in vec3 aPos;
      void main() {
        gl_Position = vec4(aPos, 1.0);
      • The fragment shader code just set the color of the curve.
      #version 330 core
      out vec4 FragColor;
      uniform vec4 ourColor;
      void main(){
        FragColor = ourColor;
      • Set the color of pixel through fragment shader outColor in OpenGL code.
      // update shader uniform
      float greenValue = 0.3f;
      int vertexColorLocation = glGetUniformLocation(shaderProgram, "ourColor");
      glUniform4f(vertexColorLocation, 0.0f, greenValue, 0.0f, 1.0f);
    • The relation between Fragment shader code and OpenGL code

      • is outColor" a *uniform variable?
      • Use uniform variables to pass value from OpenGL app to shader.

      Sorry, your browser does not support SVG.

    • Draw Simple Curve with Fragment Shader


    3.0.239 OpenGL built-in function to draw Bezier Curve and Surface, I never know that.:)

    • The function need a list of control points

      GLfloat ctrlpoints[4][3] = {
          { -4.0, -4.0, 0.0}, { -2.0, 4.0, 0.0}, 
          {2.0, -4.0, 0.0}, {4.0, 4.0, 0.0}};
      GLfloat lo = 0.0;
      GLfloat hi = 1.0;
          const int numNext = 3;
          const int nOrder = 4; // order of spline = degree + 1
      // GL_MAP1_VERTEX_3 => Three-dimensional control points
      glMap1f(GL_MAP1_VERTEX_3, lo, hi, numNext, nOrder, &ctrlpoints[0][0]);
    • Build in OpenGL function to draw Bezier Curve and Surface

    3.0.240 OpenGL Model Space, World Space and View Space

    • Model space or Object space is the space or coordinate system for each individual object

      Sorry, your browser does not support SVG.

    • World space (coordinates system) is for a group of objects, all objects are relative to the coordinate system

      Sorry, your browser does not support SVG.

    • View Space or Camera space is the coordinate system relative to the camera.

      Sorry, your browser does not support SVG.

    3.0.241 Install nodejs in MacOS

    brew install node

    3.0.242 Try to Use Python post request to insert code block into Haskellwebapp2, but it does not work so far.

    import sys
    import requests
    # Python 3+
    from pathlib import Path
    url = 'http://localhost:8080/insertcode'
    myobj = {'pid' : '3000',
             'newcode': 'my test code'}
    x =, data = myobj)

    3.0.243 Wrote a shell script to generate hightlight code using pygmentize

    • Shell script file is in $scr/

      pygmentize -l cpp -f html -O style=monokai -O noclasses=True -o "/tmp/x.cpp" file.cpp

    3.0.244 Topology \(\mathbb{R}\mathbb{P}^2\) is homeomorphic to a unit square with following equivalent relation.


    3.0.245 Emacs How to change default tags file name

    • M-x visit-tags-table
    • Use different tags file name. The default name is TAGS in Emacs

           # Do not need full path
      (setq tags-file-name "emacs_tags")

    3.0.246 Haskell: I just learn that there is typeclass called Floating in Haskell

    • typeclass Floating is like a interface for all the trigonometric function

      class (Fractional a) => Floating a where
              pi = a
              sin a -> a
              cos a -> a

    3.0.247 Java extends keyword, subtype, extend multiple bounds such as class and interface

    3.0.248 Install Git 2.28.0 using brew install git under /usr/local/Cellar/git/2.28.0/bin

    3.0.249 Install Magit in Emacs. It does need new git version which is like git 2.28. It seems to me it is fantastic package for Emacs.

    • Add more comments here.

    3.0.250 Add code to OpenGLKeyboard to draw histogram from file as input

    3.0.251 Fixed Alignment issue in Java code

    • Forgot to trim a string

    3.0.252 Fix icu4c for old macOS, icu4c causes lots of problem

    git clone
    cd homebrew-core
    brew install hub
    hub pr checkout 59540    # if you own password to login to github
    brew reinstall --build-from-source ./Formula/icu4c.rb

    3.0.253 Did an interview with Godaddy

    • First, I talked to a non technical guy called Chris Puro. After the chatting, he gave me the next interview with a manager called David Kellogg.
    • Second day, A HR called Nyssa Kerawala sent me info about a interview with a manager David Kellogg with some Zoom but there is no meeting ID on the email. When I try to connect to Zoom during the interview, it asks for the meeting ID. I have to email Nyssa to ask for the meeting ID and I was late for 15 minutes for the interview.
    • Third, it seems to me the manager is nice guy and he even mentioned he will give me the code interview but I rejected after the interview.
    • It seems to me The HR woman Nyssa does not know whether I need a meeting ID to connect to Zoom chat.

    3.0.254 There is new Array language like APL or J is called BQN

    • BQN looks interesting to me but I have no idea what is different between APL and BQN

    3.0.255 CPP Boost can be built in my Mini MacOS, 26-09-2020

    • Just download the source code the following the instructions
    • Boost Source Code

      # help 
      ./ --help
      # with ICU regex
      ./ --with-icu=DIR --prefix=MYDIR
      ./ --with-icu=/Users/cat/myfile/myinstall/boost/icu --prefix=/Users/cat/myfile/myinstall/boost

    3.0.256 Ubuntu: Add user to Ubuntu

    sudo adduser david
    # add password
    sudo passwd david

    3.0.257 Ubuntu: Add user to sudo file

    vi /etc/sudoers

    3.0.258 Ubuntu: Install Haskell Platform

    sudo apt-get install haskell-platform

    3.0.259 Ubuntu: Install Haskell Stack

    curl -sSL | sh

    3.0.260 Ubuntu: Install Apache Server

    sudo apt install apache2

    3.0.261 Ubuntu: Install collections, ubuntu install

    apt-get install redis
    apt-get install sqlite3
    apt-get install vim
    sudo apt install default-jre
    sudo apt install apache2
    curl -sSL | sh
    sudo apt-get install haskell-platform
    sudo apt-get texlive # install Latex Tex Live

    3.0.262 Get back the Car Insurance today, and paid the stupid ticket for $276, what the fucking ticket scams?

    • Paid $132 + $276 = $408 today.
    • Pay $132 something for each month in one year contract.

    3.0.263 Haskell LSP Setup: Install Haskell language server on MacOS today (08-11-2020)

    • Haskell Language Server
    • The minimum GHC is GHC 8.6.4, check \(\Rightarrow\) stack.yaml in your Stack project.
    • How to install HLS it on MacOS

      • Download the source code.
      git clone --recurse-submodules
      cd haskell-language-server
      • Building help
      stack ./install.hs help
      • Building Haskell Language Server supports many different version of GHC
      • If you use GHC 8.6.5 in your Stack project, then you need following to build LSP for GHC 8.6.5
      stack ./install.hs hls-8.6.5
      • Currently I use GHC-8.6.5, make sure your stack.yaml has resolver: lts-13.28
      stack ./install.hs help
      hls-8.10.1          Install haskell-language-server for GHC version 8.10.1
      hls-8.10.2          Install haskell-language-server for GHC version 8.10.2
      hls-8.6.4           Install haskell-language-server for GHC version 8.6.4
      hls-8.6.5           Install haskell-language-server for GHC version 8.6.5
      hls-8.8.2           Install haskell-language-server for GHC version 8.8.2
      hls-8.8.3           Install haskell-language-server for GHC version 8.8.3
      hls-8.8.4           Install haskell-language-server for GHC version 8.8.4
      • Install gen-hie to generate hie.yaml
      git clone
      cd implicit-hie
      stack build
      • You need to goto your root folder of Stack project and run
      gen-hie > hie.yaml
      • Next, start your Emacs in the roof folder of Stack project and open your Main.hs
      • Next, start LSP from Emacs
      M-x lsp
      • Then you should see connection message which tries to connect to LSP
    • Today, I still have issue to install Haskell-Language-Server (10-11-2020)
      • After a haskell file is loaded, haskell-language-server is starting and there is no error.

    But I can not see any typecheck or definition or autocomplete. I still have no clue what went wrong. I restart Emacs a few time and realize there are error messages "LSP: NO [cradle] …"

    3.0.264 Haskell LSP Setup: Try to install lsp-haskell but it failed so far.

    • It took more than an hour to install lsp-haskell
      • Here is lsp-haskell
      • From github, I did not see any tutorial to tell you run 'M-x lsp' on your Emacs. I tried run 'M-x lsp-mode' a few times.. and finally someone told me in Gitter I should run M-x lsp and finally I see message LSP initialize successfully on my Emacs.. and I can grep hie and hie-wrapper from comand line.
      • So far so good, but I try to completion C-M-i, it does not work. And I try jump to defintion M-. , it does not work.
    • It seems to me the better option development are ghcid and hastags --etags .
      • It is easy to install and work.

    3.0.265 Haskell LSP Setup: It seems to me no one can answer my Reddit question how to setup LSP mode in Emacs yet.

    • Reddit Question on How to install LSP mode or Haskell Language Server on Emacs.
    • Try to understand some defintion of what is lsp, lsp-mode, lsp-haskell, company-mode, etc. there are million more defintions
      • lsp \(\Rightarrow\) Language-server-protocol from Microsoft
      • lsp-mode is Language Server Protocol for Emacs
      • lsp-mode is a client to provide to popular package such as company, flycheck and projectile.
    • So lsp-mode is just a mode.

    3.0.266 Git: git init from a non empty folder

    git init
    git add .
    git commit -m "initial commit"
    git remote add origin
    git pull origin master --allow-unrelated-histories
    git push --force-with-lease

    3.0.267 Firefox Error: Cross-Origin Remote Blocked

    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///Users/cat/myfile/bitbucket/html/snippet2.pdf. (Reason: CORS request not http)
    • How to fix it on Firefox
    • Goto URL bar and type
    • Search security.fileuri.strictoriginpolicy and Set it to false


    3.0.268 Install old version TeX Live Utility (2017) on MacOS 10.12.6

    • If you head to TeX Live Utility Website, you got Tex Live Utility 2020 and it needs MacOS 10.13 minimum
    • Well, the next logical step is to update my MacOS 10.12.6 to 10.13. But I google around and can not find 10.13 installer
      • I did try to download some 10.13.4 update or combo something from Apple website and update it, but all the update or combo things need 10.13 or higher.
      • It seems to me Apple try to prevent you to update from MacOS 10.12.6 to 10.13 or there is some technical issues that Apple can not solve so there is no way from 10.12.6 to 10.13
      • I did not know there is TeX Live Utility 2017 until today and I download it and install it. It seems to me it works so far and I can update my Latex packages. Here is the URL, download it and install it. mactex-20170524.pkg
      • Here is screenshot


    3.0.269 Haskell Error, Ambiguous module name 'Data.HashSet'

    /Users/cat/myfile/bitbucket/try/src/AronModule.hs:74:1: error:
    Ambiguous module name ‘Data.HashSet’:
    it was found in multiple packages:
    hashmap-1.3.3 unordered-containers-
    • What is the hell is going here? If you use hashmap inside your Cabal file then you will get above error Both package hashmap and unordered-containers use Data.HashSet inside their packages
    • Solution Change hashmap to unordered-containers inside your Cabal file in Stack

    3.0.270 HTTP Header no cache, reload file

    • How to force the browser to delete cache?

      • In Http Header, you can add the following
      /        Cache-Control: no-cache

    3.0.271 haskellwebapp2 Project 13-12-2020

    • README
      • Before installation
    • Edit *config.txt" file

      • Change host name and port number
      • Change rootdir to new directory
    • Edit $jslib/aronlib.js

      // $hw test project
      const HOST = {
      LOCALHOST : 'http://localhost:8081',
      XFIDO     : ''
      // $HOME/myfile/mybin/haskellwebapp2Bin
      // Live project
      const HOST = {
      LOCALHOST : 'http://localhost:8080',
      XFIDO     : ''
    • Modify name from haskellwebapp2test to haskellwebapp2 in haskellwebapp2.cabal

      executable             haskellwebapp2_test
      • Install
      $hw/haskellwebapp2/ in
    • Update text color and background-color

      • Select color from Javascript code
      // aronlib.js
      function submitUpdateBackground(cvalue) {
      • WaiLib.hs call submitUpdateBackground(…)
      // WaiLib.hs
      <input id='bgidcolor' type="color" onchange="submitUpdateBackground('background-color:' + this.value)" name="colorname">
      submitUpdateBackground('color:' + this.value);
      submitUpdateBackground('background-color:' + this.value);
      • End Point '/updatebackground'
      function submitUpdateBackground(cvalue) {
          let url = getHostNameJS() + '/updatebackground'
      • WaiLib.hs call
      ("updatebackground":_) -> updateBackground request respond  -- change background color
      • NOTE: searchForm.html use submitUpdateBackground TOO
    • BUG:
    • Try to fix followilling issue:
      • When there is Latex compile error, the className of canvas is changed to hide

    When there is NO Latex compile error, the className of canvas is changed to show

    var canvas = document.getElementById('the-canvas') = 'hide'
        // = 'show'
    • See following function in aronlib.js

      function postRequestJson(pid, url, obj){

    3.0.272 git checkout directory only

    • I just learned that you can checkout the root directory of git repos only with git.
    • and checkout one file only.

      git clone -n --depth 1
      cd haskelllib
      git checkout HEAD AronModule.hs

    3.0.273 haskellwebapp2 Latex editor (05-01-2021)

    • directory structure

    • Default request ""
      • Generate random name try919591
      • Copy indexEditorACE.html to indexEditorACEtry919591.html
      • Send indexEditorACEtry919591.html to browser
    • NOTE: Currently src/datadir/latex/try919591/try919591.html is NOT generated yet.
      • Response to client
    • Client side:

      • After HTML indexEditorACEtry919591.html page is loaded, make a Ajax call in http://localhost/editordata
        • Send JSON Object EditorCode to Server

          data EditorCode = EditorCode{
                  } deriving (Generic, Show)
          // indexEditorACE.html
          const myHost = 'http://localhost:8081'
          let url = myHost + '/' + 'editordata'
          var obj = new Object()
          obj.editorbeg = nowInt()
          obj.editorend = 0
          obj.editorfile = latex.value
          obj.editorcmd  = 'compile'
          obj.editorcode = editor.getValue()
          obj.editortheme = editor.getOption('theme')
          obj.editormode = editor.getOption('mode')
          • New Latex code
        • Server receive "compile", and compile $m/try919591.tex and output dir is src/datadir/latex/try919591
        • Server reply EditorCodeReply

          data EditorCodeReply = EditorCodeReply{
            } deriving (Generic, Show)
      • Create directory under
      • Compile latex file
      • pdflatex output directory
    • try919591.pdf in try919591

      • Use indexEditorACE.html as default HTML file
      • New code \( \Rightarrow \) Copy haskellwebapp2/indexEditorACE.html to haskellwebapp2/src/datadir/try919591/try919591.html
      • "compile" => default


    • Click on "Save"


    • Save all pdflatex to a directory

    src/datadir/latex/try919591/try919591{.html, .pdf..}

    • Create Html File latexHTMLFile
    • Request ""
      • If try919591 is found in the HashMap
      • Then send indexEditorACEtry919591.html to client side
    • Client Use XMLHttp to make a ajax call to Server side

      • Compile .tex to .pdf file
        • If .tex can be compiled, then return JSON (true) back to client side,
          • if Get return JSON true, then call loadPDF() to load the new PDF file.
      type PDFMap = M.HashMap String String
      -- ("try919591" "try919591")
      • more
    • Response PDF file path

      -- =>
      --   => try919591.html
      -- DONE: TODO:   => try919591.pdf  => src/latex/try919591.pdf
      -- TODO: add following => src/latex/try919591/try919591.pdf
      --  => datadirlatex </> v </> v ++ ".pdf"
      datadirlatex = "datadir/latex"
              v = try919591 
              v = try919591
              responsePDF "datadir/latex/try919591/try919591.pdf"
      redisValue <- redisGet queryId
      case redisValue of
        Just v -> respond $ responsePDF $ datadirlatex </> v </> v ++ ".pdf"
        _      -> respond responseHelp

    3.0.274 Three order traveral, preorder, inorder, postorder

    Class Node{
    Node left;
        Node right;
        Int data;
    • preOrder traveral

      void preOrder(Node node){
           if(node != null){
    • inOrder traveral

      void postOrder(Node node){
          if(node != null){
    • postOrder traveral

      void postOrder(Node node){
         if(node != null){

    3.0.275 Binary Tree insection

    Class Node{
    Node left;
    Node right;
    Int data;
    void insert(Node root, Int n){
    if(root == null){
        root = new Node(n);
        if( n < ){
        if(root.left == null)
            root.left = new Node(n);
            insert(root.left, n);
        if(root.right == null)
            root.right = new Node(n);
            insert(root.right, n);

    3.0.276 Binary Search

               arr = [1], k = 1 => true
               arr = [1], k = 2 => false
               arr = [1, 2], k = 1 => true
               arr = [1, 2], k = 2 => true
               arr = [1, 2], k = 3 => false
    Boolean binSearch(Int[] arr, Int lo, Int hi, Int k){
    if(lo <= hi){
        Int m = (lo + hi)/2;
        if(k < arr[m]){
        return binSearch(arr, lo, m-1);
        }else if(k > arr[m]){
        return binSearch(arr, m+1, hi);
                return k == arr[m];
        return false;

    3.0.277 Haskell data newtype and type

    • data can have zero or more constructor and parametrized types
    data MyType a = MyNothing | MyJust a
    data MyType1 = MyType Inta

    3.0.278 Test me

    • This is test me

    Author: aaa

    Created: 2022-02-13 Sun 01:01