8/2/16

notes

- git
  which git                                                       # /usr/bin/git
  /applications/xcode.app/contents/developer/usr/bin/git version  # 2.13.5 (Apple Git-94)

  q  # quit

  # interactive rebase, to edit/squash commits
# git rebase  -i  HEAD~4  # vim
# git rebase  --continue
# git rebase  --abort


  # delete the last commit (revert)
  # http://christoph.ruegg.name/blog/git-howto-revert-a-commit-already-pushed-to-a-remote-reposit.html
# git reset  HEAD^ --hard


  # config
  git help config
  git config  --list                      # -l
  git config  --unset  branch.foo.remote
  git config  --unset  branch.foo.merge


# git gc  # cleanup


  # rename branch
  git branch  -m <oldname> <newname>  # rename from any branch
  git branch  -m           <newname>  # rename current branch


  git status
  git status  --short  # -s


  git log  -n3  dev/app/lib.mm  # git log for file, last n commits, filename is case sensitive

  git log  -n2                # Sun Oct 5 12:00:00 2014 -0600
  git log  -n2  --date=local  # Sun Oct 5 12:00:00 2014
  git log  -n2  --date=short  # 2014-10-05
  git log  -n2  --date=iso    # 2014-10-05 12:00:00 -0600

  git log  --name-status
  git log  --name-status  --author=kbcat  --merges     -n2
  git log  --name-status  --author=kbcat  --no-merges  -n3  dev/app/file.c
  git log  --name-status                  --no-merges  -n3
  git log  --name-only
  git log  --stat

  git log  -n3  --pretty=format:"%cd  %h%n%s%n-------"  --date=local  # Sun Oct 5 12:00:00 2014
  git log  -n3  --pretty=format:"%cd  %h%n%s%n-------"  --date=iso    # 10-05 12:00:00
      | sed -e 's/2014-//'
      | sed -e 's/ -0600//'

  git log  --abbrev-commit
  git log  --abbrev-commit  --pretty=oneline
  git log  --abbrev-commit  --pretty=oneline  --author=kbcat
  git log  --abbrev-commit  --pretty=oneline  --author=kbcat  dev/app/file.c
  git log  --abbrev-commit  --pretty=oneline                  dev/app/file.c

  git log  --diff-filter=A  --name-status   # Added
  git log  --diff-filter=D  --name-status   # Deleted
  git log  --diff-filter=M  --name-status   # Modified
  git log  --diff-filter=R  --name-status   # Renamed

  git log  --diff-filter=AD  --name-status  # Added or Deleted

  git log  --grep="bug"  # match commit message
  git log  -Sfoo         # find string occurrences +-


  git show  f000000
  git show  f000000  dev/app/file.c
  git show  --name-status  f000000

  git show  --pretty="format:"  --name-only             # last commit
  git show  --pretty="format:"  --name-only  f000000    # commit
  git show  --pretty="format:"  --name-only  stash@{0}


  # show all commits in feature branch that are not in master branch
  git log  master..dev/fb
  git log  master..dev/fb  --no-merges


  # add files
  git add  dev/app/lib.*


  git checkout stash
  git checkout stash@{1}     dev/app/file.c
  git checkout stash@{1}  -- dev/app/file.c

  git checkout f000000       dev/app/file.c

  git checkout -b temp stash@{1}


  git cherry-pick               f000000
  git cherry-pick  --no-commit  f000000  # -n
  git cherry-pick  --edit       f000000  # -e


  git tag  -a  v1.0  -m "..."
  git tag  -l                   # list all tags, default shows 1 line of tag message
  git tag  -l  -n3  v1.0        # show 3 lines of tag message
  git show  v1.0
  git push  origin  [tagname]
  git push  origin  v1.0


  # update
  git remote  show  origin
  git fetch
  git pull


  git diff             stash                  # diff working dir w/stash
  git diff  dev        stash@{1}              # diff dev branch w/stash
  git diff             stash@{1}      file.c  # diff file in working dir w/stash
  git diff  stash@{1}  stash@{0}              # diff stash 1 w/stash 0, most recent last
  git diff  stash@{1}  stash@{0}      file.c  # diff file between stash 1 and stash 0
  git diff  f000000    f000001     -- file.c  # diff file between commit x and commit y

  git diff  --staged


  # git diff stash script, swift 3
  for x in (1...10).reversed() {

      let stashData = "stash@{\(x)} stash@{\(x - 1)}"

      print("cl git diff --name-only \(stashData)")
      print("cl git diff             \(stashData)")
      print("#  git stash drop       stash@{\(x)}\n")
  }

      cl git diff --name-only stash@{10} stash@{9}
      cl git diff             stash@{10} stash@{9}
      #  git stash drop       stash@{10}

      cl git diff --name-only stash@{9} stash@{8}
      cl git diff             stash@{9} stash@{8}
      #  git stash drop       stash@{9}

      cl git diff --name-only stash@{8} stash@{7}
      cl git diff             stash@{8} stash@{7}
      #  git stash drop       stash@{8}

      cl git diff --name-only stash@{7} stash@{6}
      cl git diff             stash@{7} stash@{6}
      #  git stash drop       stash@{7}

      cl git diff --name-only stash@{6} stash@{5}
      cl git diff             stash@{6} stash@{5}
      #  git stash drop       stash@{6}

      cl git diff --name-only stash@{5} stash@{4}
      cl git diff             stash@{5} stash@{4}
      #  git stash drop       stash@{5}

      cl git diff --name-only stash@{4} stash@{3}
      cl git diff             stash@{4} stash@{3}
      #  git stash drop       stash@{4}

      cl git diff --name-only stash@{3} stash@{2}
      cl git diff             stash@{3} stash@{2}
      #  git stash drop       stash@{3}

      cl git diff --name-only stash@{2} stash@{1}
      cl git diff             stash@{2} stash@{1}
      #  git stash drop       stash@{2}

      cl git diff --name-only stash@{1} stash@{0}
      cl git diff             stash@{1} stash@{0}
      #  git stash drop       stash@{1}

      # do not drop stash zero


# git stash  save  "backup"
  git stash  list
  git stash  list  --date=local
  git stash  show                # file list
# git stash  pop/apply

  # show stash sha1 hash
  git reflog stash


  git blame              dev/app/file.c
  git blame  -L 100,110  dev/app/file.c


  # --------------------------------------
  - git workflow example 1, local repo
    clear; git status
    git init                                   # initialized empty Git repository in /users/rj/docs/.git/
    git add file1.txt
    git commit -m "..."
    git log
    git add .                                  # add current folder
    git commit -m "..." >> ~/gitCommitLog.txt

      10 files changed, 20 insertions(+), 1 deletion(-)
      create mode 100644 .gitignore
      create mode 100644 HEAD
      create mode 100644 c/lib.c
      create mode 100644 c/lib.h
      create mode 100644 file2.txt


  # --------------------------------------
  - git workflow example 2, Xcode workspace project
    WORKING_FOLDER=~/dev/xcode6/
    mkdir -p "$WORKING_FOLDER"
    cd "$WORKING_FOLDER"

    # create new workspace in xcode, CL N
    # ws.xcworkspace

    ls -alt
    git init
    git status  # On branch master
    git add ws.xcworkspace

    git config --global user.name  "rj"
    git config --global user.email "rj@sf.com"

    touch .gitignore
    echo .DS_Store > .gitignore
    cat .gitignore
    git add .gitignore
    git add --all

    git status
    git commit -m "added new workspace"
    git log --name-status

    # add new project to workspace in xcode, CS N
    # do not create git repo

    git status
    git diff ws.xcworkspace/contents.xcworkspacedata
    git add --all ws.xcworkspace/
    git add --all app/

    git status
    git commit -m "added new app"
    git log --name-status

    git branch  # master
    # create Dev Branch and switch
    git checkout -b dev


  # --------------------------------------
  - git workflow example 3, GitHub
    1. init, setup, and commit into local git repo
    2. create repo on GitHub
    3. push repo to GitHub

    # test github connection
    ssh -T git@github.com

    # github repo url
    ssl:  git@github.com:expressionsoftware/foo.git
    http: https://github.com/expressionsoftware/foo.git

    # add remote and push
    git remote add origin git@github.com:expressionsoftware/foo.git

    git push -u origin master --porcelain --verbose  # include -u (--set-upstream) on first push only
    git push -u origin dev

    git push    origin master
    git push    origin dev


    # clone
    git clone git@github.com:expressionsoftware/foo.git         # creates folder, default folder name, same as repo name, "foo"
    git clone git@github.com:expressionsoftware/foo.git foobar  # creates folder "foobar"
    git clone git@github.com:expressionsoftware/foo.git .       # current empty folder


  # --------------------------------------
  - .gitignore file
    .cfusertextencoding
    .ds_store
    .fontconfig/
    .gitignore~
    .lesshst
    .trash/
    .viminfo
    .xauthority
    *~*
    *.exe
    xcuserdata/
    # -----------------
    app/temp.cpp
    temp file 1.txt
    # -----------------
    # wildcards
    # * wildcard requires full path
    app/images/*png
    *~
    *.swp
    # ignore all directories and files in a directory
    tmp/**/*


- SSH keys
  # generate an SSH key pair
  ssh-keygen -t rsa -C "hb@hfob.com"
# cat ~/.ssh/id_rsa      # private key
# cat ~/.ssh/id_rsa.pub  # public key

  # add SSH private key to ssh-agent
  eval "$(ssh-agent -s)"
  ssh-add ~/.ssh/id_rsa
  ssh-add -K ~/.ssh/id_rsa


- GitHub setup
  # copy SSH public key and add to GitHub account, one-time setup
# pbcopy < ~/.ssh/id_rsa.pub


- # sed substitute replace
  sed -e s/foo/BAR/  file.txt
  sed -e s/foo/BAR/g file.txt

  # --------------------------------------
  # sed script html encode file
  sed -f script.txt file.txt
  sed -f script.txt file.txt > file.txt.out
  s/\&/\&amp;/g
  s/</\&lt;/g
  s/>/\&gt;/g
  s/"/\&quot;/g
  s/'/\&#39;/g

  # --------------------------------------
  # sed script html decode file
  s/\&amp;/\&/g
  s/\&lt;/</g
  s/\&gt;/>/g
  s/\&quot;/"/g
  s/\&#39;/'/g


- grep
# grep -ri -e 'foo'    --include '*cpp*'
# grep -ri -E '\[\]' . --include=*.h
# grep -ri -E 'min|max' .

# fgrep -ri 'foo' .                   # all files
# fgrep -ri 'foo' . --include='*.h'
# fgrep -i  'foo' /users/ip/file.txt

  -n --line-number
  -l --files-with-matches
  -c --count


- translate regex replacement, lowercase uppercase
  echo "Foo Bar 123" | tr 'A-Z' 'a-z'  # foo bar 123
  echo "Foo Bar 123" | tr 'a-z' 'A-Z'  # FOO BAR 123
  echo 'Foo Bar 123' | tr '0-9' '#'    # Foo Bar ###

  # lowercase
  echo "Foo" | tr '[:upper:]' '[:lower:]'

  # uppercase
  echo "Foo" | tr '[:lower:]' '[:upper:]'


- vim 7.4
  :help
  :q          quit, escape from :help
  esc         normal mode

  .           repeat command
  b           move 1 word back
  dd          delete line
  dw          delete word under cursor
  i           insert mode
  u           undo
  w           move 1 word forward


- # less text viewer
  less -?  # --help
  less -V  # --version
  -i  # --ignore-case  # ignore case in searches that do not contain uppercase
  -I  # --IGNORE-CASE  # ignore case in searches and patterns
  /regex search string
  less iPhone.storyboard
  q  # quit

# xcodebuild -showBuildSettings -project app.xcodeproj | less


- line word count
  wc -lw main.storyboard


- macOS
  - network setup
    networkSetup -getComputername
    networkSetup -printCommands
    networkSetup -listAllNetworkServices
    networkSetup -getInfo wi-fi  # wifi network service, ip address
    https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man8/networksetup.8.html

  - ip address
    ifconfig
    ifconfig | grep "inet "

  - connected servers/volumes
    ls -1   /volumes/
    ls -Alt /volumes/serverName/folder/

  - apps
    ls -1 /applications

    open -a /applications/textEdit.app 'file.txt'
    open -a /applications/xcode.app    'file.txt'

    - run app executable from command line
    # ./app

    - fileMerge diff app
      opendiff file1 file2

  - diff
    compare directories
    diff -rq   ./dir1  ./dir2  # show files that are diff
    diff -rqs  ./dir1  ./dir2  # show files that are same

  - defaults read/write plist
    - view app bundle info
      defaults read demo.app/Info CFBundleIdentifier  # com.foo.demo
      defaults read demo.app/Info CFBundleVersion

    - show hidden files
      defaults read  com.apple.finder AppleShowAllFiles
      defaults write com.apple.finder AppleShowAllFiles YES  # NO
    # killall Finder

  - config vars
    getconf DARWIN_USER_CACHE_DIR  # /var/folders/p4/abc7123x999xyz_ab1qwe0xx9999xs/C/

  - file flags
    ls -lO
    chflags   uchg file  # lock
    chflags nouchg file  # unlock

    chflags -R   uchg /dir  # lock
    chflags -R nouchg /dir  # unlock

  - extended attributes
  # ls -l ~/downloads/                                      # list file or dir, extended attributes are indicated by an @ char at the end of the ownership and permissions info
  # -rw-r--r--@  1 apaak  staff  1024 Sep 12 10:00 foo.app
    
    xattr                         ~/downloads/foo.app
  # xattr -p com.apple.quarantine ~/downloads/foo.app  # print attribute, file quarantine
  # xattr -d com.apple.quarantine ~/downloads/foo.app  # delete attribute
  # xattr -c                      ~/downloads/foo.app  # delete all attributes, clear

  - change file modes
    u user   (owner)
    g group
    o other
    a all    (everyone, ugo)

  # chmod 700   ~/downloads/foo.app
  # chmod u=rwx ~/downloads/foo.app
  # chmod o-rwx ~/downloads/foo.app

    u   g   o    octal
    rwx rwx rwx  mode
    100 000 000  400    r   user
    100 100 100  444    r   all
    110 000 000  600    rw  user
    111 000 000  700    rwx user

  - file commands
    # set file create modified date
    touch -t 201701020000 /users/sc/file

    # copy file
  # cp file1.txt file2.txt

    # copy folder
  # cp -npR ~/temp ~/backup                    # mac
  # cp -nR  ~/temp /volumes/10.0.0.100/backup  # win

    # rename/move file
  # mv file1.txt file2.txt

    # batch file rename w/sed regex, test w/echo
  # ls * | sed -e 'p;s/foo/bar/' | xargs -n2 echo  # mv

    # remove file
  # rm tempFile.txt

    # remove folder
  # rm -dfr tempFolder

    # create parent intermediate folders path
  # mkdir -p ~/dev/c

    # sort file
  # sort file1.txt -o file2.txt

    # list files
    ls -1lhRt ~/temp
    ls -l
    ls -1             # file names
    ls -1R            # file names, recursive
    ls * | xargs -n1

    du -ach ~/library/developer/xcode/deriveddata/*/build/products/debug/cocoa.app

    # file search, default recursive
  # sudo find /  -iname '*.app'

  # find .  -iname '*.h'
  # find .  -iname '*.txt'  -depth 1     # top level files
  # find .  -iname '*.txt'  -maxdepth 2  # all files up to max depth
  # find .  -iname '*.txt'  -depth 2     # only depth 2 files
  # find ~  -iname 'java'
  # find ~/library/developer/xcode/deriveddata/*/build/products/debug/cocoa.app -type f

    # find and delete files
  # find .  -iname '.ds_store'  -type f
  # find .  -iname '.ds_store'  -type f  -exec rm  {} \;
  # find .  -iname '.ds_store'  -type f  -print0 | xargs -0  rm


    # find and delete git folders
  # find .  -iname '.git'   -type d                                    # find only
  # find .  -iname '.xgit'  -type d  -print0 | xargs -0       rm -dfr
  # find .  -iname '.xgit'  -type d  -print0 | xargs -0  sudo rm -dfr

    # delete git folders
  # rm -dfr .xgit

  - unzip
    https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/unzip.1.html

  - SHA File Hash
    https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/openssl.1ssl.html
    openssl sha1 [full path to file]
    openssl sha1 /users/eg/downloads/sqlite-shell-osx-x86-3080600.zip
    SHA1(/users/eg/downloads/sqlite-shell-osx-x86-3080600.zip)= 163d43f9a1bbc8a65c53b051a56371a305e6054a

  - system_profiler
    system_profiler -listDataTypes
    system_profiler SPStorageDataType
    system_profiler SPSoftwareDataType

                     Sierra
    System Version:  macOS 10.12 (16A323)
    Kernel Version:  Darwin 16
    Time since boot: 1 day 4:04
    Computer Name:   foo
    User Name:       e s (es)

    10.13 High Sierra
    10.12 Sierra
    10.11 El Capitan
    10.10 Yosemite
    10.09 Mavericks
    10.08 Mountain Lion

    system_profiler SPHardwareDataType
    system_profiler SPHardwareDataType | grep -i 'processor name:' | sed -e 's/ *Processor Name: *//'
    https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man8/system_profiler.8.html

  - disk util
    diskutil list
    diskutil cs list
    diskutil info /volumes/vol1
    diskutil eraseVolume  JHFS+  untitled_usb_drive  "/volumes/a usb drive"

  - create mac OS bootable install usb drive
    diskutil eraseVolume  JHFS+  untitled_usb_drive  "/volumes/usb drive to erase and use"
    sudo "/applications/install macOS sierra.app/contents/resources/createinstallmedia"  --volume /volumes/untitled_usb_drive  --applicationpath "/applications/install macOS sierra.app"

  - sysctl hw.machine  # hw.machine: x86_64

  - sound processing
  # afinfo soundFile.m4a
  # afConvert -f caff -d aac soundFile.m4a soundFile.caf

  - system diagnostics
  # sudo sysdiagnose xcode
    /var/tmp/sysdiagnose_2013.10.13_15-00-00-MDT_Xcode.tar.gz  # output
    https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/sysdiagnose.1.html

  # xcode beta
  for _ in {1..10}
  do
      killall ReportCrash
      killall SourceKitService
      killall "Interface Builder Cocoa Touch Tool"
  done


- bash
# exit  # exit bash 4

  # date format
  date +%H:%M:%S             # 22:52:01
  date '+%m-%d-%y %H:%M:%S'  # 08-28-16 20:19:53
  date '+%m-%d-%y.%H%M%S'    # 08-28-16.201953

  echo $BASH          # /bin/bash
  echo $BASH_VERSION  # 3.2.57(1)-release
                      # 4.4.5(1)-release

  bash --version      # 3.2.57(1)-release
                      # 4.4.5(1)-release

  echo $HOME          # /users/dave
  echo $HOSTNAME      # h9000
  echo $RANDOM        # 10273, (0-32767)

  echo $PATH  # /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
  PATH="${PATH}:/users/mo/dev/scala/bin"
  export PATH
  echo $PATH

  echo -e "foo\nbar"

  for x in {1..10}
  do
      echo $x
  done

  # bash array
  declare -a data=("foo" "bar" "...")
  for x in "${data[@]}"
  do
      echo $x
  done

  cal
  cal 10 2016
  cal -y


  # --------------------------------------
  # .bash_profile

  # set min prompt
  export PS1='$ '

  # alias
  alias cbp='cat ~/.bash_profile;'
  alias cl='clear;'
  alias fc='/users/john/applications/fileCompare'  # fc f1 f2
  alias od='/usr/bin/opendiff'                     # filemerge, od f1 f2

  # git alias
  alias gb='    git branch;'
  alias gds='   git diff stash;'
  alias gl='    git log --name-status;'
  alias glm='   git log --name-status --author=john;'
  alias glp='   git log --abbrev-commit --pretty=oneline;'
  alias glpm='  git log --abbrev-commit --pretty=oneline --author=john;'
  alias gmt='   git mergetool;'
  alias gp='    git pull;'
  alias gs='    git status;'
  alias gsl='   git stash list;'
  alias gsll='  git stash list --date=local;'
  alias gslno=' git stash list --name-only;'


  function filehashlog() {
      set -x
      filehash $1
      set +x
  }

  function filehash() {
      openssl sha1 $1
  }

  function fhash() {
      filehash $1 | egrep -o "\b([a-z0-9]+)$"
  }

  function fcomp() {
      local fh1=$(fhash $1)
      local fh2=$(fhash $2)

      printf "file compare sha1 hash\n%s = %s\n%s = %s\n\n" $fh1 $1 $fh2 $2

      if [ $fh1 == $fh2 ]
      then
          printf "files are equal\n"
      else
          printf "files are NOT equal\n"
      fi
  }


  # file open text edit
  function fote() {
      open "$1" -a textedit
  }

  function foxc() {
      open "$1" -a xcode
  }


  # --------------------------------------
  # !/bin/bash
  # backup copy file w/timestamp script
  # bash backupFileScript "file 1.txt"

  if (($# == 1))  # one param
  then
      vTimestamp=$(date "+_%m%d%y_%H%M%S.txt")
      vBackupFilename=$1$vTimestamp

      echo "file:   $1"                # file 1.txt
      echo "backup: $vBackupFilename"  # file 1.txt_100713_203059.txt

      # quote for filename space chars
      cp "$1" "$vBackupFilename"
  else
      printf "user error\n1 filename param is required\n"
      echo "params: ${#}"
  fi

  # --------------------------------------
  # !/bin/bash
  # 10-06-13 Mac cpu architecture script
  # bash cpuScript "intel core i7"
  # returns CPU architecture, either 32 or 64 bit, based on processor name
  # http://support.apple.com/kb/HT3696

  # bug param count wrong for string w/spaces
  # bash cpuScript $(system_profiler SPHardwareDataType | grep -i 'processor name:' | sed -e 's/ *Processor Name: *//')
  # params: 3
  # version 2.0
  # 64-bit CPU Intel

  # fix wrap command-substitution $() in double quotes to send 1 string param
  # bash cpuScript "$(system_profiler SPHardwareDataType | grep -i 'processor name:' | sed -e 's/ *Processor Name: *//')"
  # params: 1
  # version 2.0
  # 64-bit CPU Intel Core i7

  echo "params: ${#}"

  ver="2.0"
  echo "version $ver"

  # lowercase
  v1=$(echo $1 | tr '[:upper:]' '[:lower:]')

  case $v1 in
    "intel core solo"|"intel core duo") echo "32-bit CPU $1"
                                        ;;
    *)                                  echo "64-bit CPU $1"
                                        ;;
  esac

  # --------------------------------------
  bash base conversions
  int to binary echo 'obase=2; 256' | bc        # 100000000
  int to hex    echo 'obase=16; 256' | bc       # 100
  int to hex    printf '%x\n' 256               # 100
  int to octal  echo 'obase=8; 256' | bc        # 400
  binary to int echo 'ibase=2; 100000000' | bc  # 256
  hex to int    echo $((0x100))                 # 256
  hex to int    echo 'ibase=16; 100' | bc       # 256
  hex to int    printf '%d\n' 0x100             # 256
  octal to int  echo 'ibase=8; 400' | bc        # 256


- R
  /library/frameworks/r.framework/resources/r --version  # 3.1.2

  R.Version()
  R.Version()$version   # R version 3.1.2 (2014-10-31)
  R.Version()$nickname  # Pumpkin Helmet

  ?help  # q
  quit()

  Sys.getenv()

  ls()
  ?ls
  ls(pattern = "^m.*")

  ?rm
# rm(m1)
# rm(list = ls())  # remove all

  x = "foo"
  nchar(x)  # length 3

  ?matrix
  ?vector


- ruby
  /usr/bin/ruby -v  # 2.0.0p648 (2015-12-16 revision 53162) [universal.x86_64-darwin15]

  ruby --help


- homebrew
  /usr/local/bin/brew -v  # Homebrew 1.1.5

  /usr/local/cellar

  man brew
  brew help
  brew home
  brew doctor

  brew analytics
  brew analytics off

  brew list

  brew update  # update hb

  brew outdated  # list outdated packages

  brew upgrade $FORMULA
# brew upgrade           # upgrade all

  brew cleanup -n        # show cleanup
  brew cleanup $FORMULA
# brew cleanup           # cleanup all

  brew info bash          # https://github.com/Homebrew/homebrew-core/blob/master/Formula/bash.rb
  brew install bash       # /usr/local/cellar/bash/4.4.5/bin/bash

  brew info erlang        # https://github.com/Homebrew/homebrew/blob/master/Library/Formula/erlang.rb
  brew install erlang     # /usr/local/cellar/erlang/19.0.2/bin/erl

  brew info git           # https://github.com/Homebrew/homebrew/blob/master/Library/Formula/git.rb
  brew install git        # /usr/local/cellar/git/2.10.0/bin/git

  brew info leiningen     # https://github.com/Homebrew/homebrew/blob/master/Library/Formula/leiningen.rb
  brew install leiningen  # /usr/local/cellar/leiningen/2.7.0/bin/lein

  brew info node.js       # https://github.com/Homebrew/homebrew/blob/master/Library/Formula/node.rb
  brew install node.js    # /usr/local/cellar/node/6.5.0/bin/node

  brew info python3       # https://github.com/Homebrew/homebrew/blob/master/Library/Formula/python3.rb
  brew install python3    # /usr/local/cellar/python3/3.6.1/bin/python3.6

  brew info rust          # https://github.com/Homebrew/homebrew-core/blob/master/Formula/rust.rb
  brew install rust       # /usr/local/cellar/rust/1.11.0/bin/rustc

  brew info scala         # https://github.com/Homebrew/homebrew-core/blob/master/Formula/scala.rb
  brew install scala      # /usr/local/Cellar/scala/2.12.1/bin/scala

- leiningen (clojure)
  /usr/local/bin/lein -v  # Leiningen 2.7.1 on Java 1.8.0_111 Java HotSpot 64-Bit Server VM

  lein -h
  quit
  L D  quit
  (quit)

  lein repl  ;;Clojure 1.8.0

  (+ 1 2 3 4 5 6 7 8 9 10)  ;;55
  (def nums [1 2 3 4 5 6 7 8 9 10])
  (apply + nums)  ;;55

  (for [x [:a :b], y (range 5) :when (odd? y)] [x y])  ;;([:a 1] [:a 3] [:b 1] [:b 3])

  (doseq [x [:a :b], y (range 5) :when (odd? y)] (prn x y))  ;;:a 1
                                                               :a 3
                                                               :b 1
                                                               :b 3
                                                               nil

  (def a 42)
  a        ;;42
  (+ a)    ;;42
  (+ a 2)  ;;44
  (/ a 2)  ;;21
  (* a 2)  ;;84

  (take 10 (range))                 ;;(0 1 2 3 4 5 6 7 8 9)
  (map inc (take 10 (range)))       ;;(1 2 3 4 5 6 7 8 9 10)
  (map #(+ % 2) (take 10 (range)))  ;;(2 3 4 5 6 7 8 9 10 11)


- erlang
  /usr/local/bin/erl +V  # Erlang (SMP,ASYNC_THREADS,HIPE) (BEAM) emulator version 6.3
  /usr/local/bin/erlc -help

  erl     # Erlang/OTP 17 [erts-6.3.1] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
  help().

  LG      switch command
  LG h|?  help
  LG i    interrupt
     c    connect
  LG q    quit

  q().    quit

  code:root_dir().  %"/usr/local/cellar/erlang/17.4/lib/erlang"
  erlang:loaded().  %loaded erlang modules, current and/or old code, including preloaded modules
  erlang:memory().
  erlang:system_info(process_limit).  %262144

  os:version().    %{14,1,0}
  os:cmd("date").  %"Sat Jan 10 05:39:56 MST 2015\n"

  io:format("hello Erlang!~n").

  self().
  process_info(self()).
  process_info(self(), links).

  processes().
  length(processes()).

  pwd().
  ls().
  cd("/users/ja/erlang").

  P1 = list_to_pid("<0.281.0>").  %<0.281.0>
  is_pid(P1).  %true

  b().   %var bindings
  f().   %forget all vars
  f(X).  %forget X var

  string:concat(string:concat("foo", " "), "bar").  %"foo bar"
  io:format("~s~n", ["foo bar"]).  %foo bar
  io:format("~w~n", ["foo bar"]).  %[102,111,111,32,98,97,114]

  Sq = fun(X) -> X * X end.
  Sq(8).  %64
  math:sqrt(64).  # 8.0
  math:pi().      %3.141592653589793

  now().                                                  %{1420,849205,145416}  timestamp from 1-1-1970 GMT
  time().                                                 %{17,20,5}
  erlang:localtime().                                     %{{2015,1,9},{17,20,5}}
  erlang:localtime_to_universaltime(erlang:localtime()).  %{{2015,1,10},{0,20,5}}

  T = lists:seq(0, 9).  %[0,1,2,3,4,5,6,7,8,9]
  T.
  length(T).  %10

  AbcSha512 = crypto:hash(sha512, "abc").  %<<221,175,53,161,147,97,122,186,204,65,115,73,174,32,65,
                                              49,18,230,250,78,137,169,126,162,10,158,238,230,75,...>>
  is_binary(AbcSha512).  %1
  binary_to_list(AbcSha512).
  length(binary_to_list(AbcSha512)).  %64
  lists:foreach(fun(B) -> io:format("~w ", [B]) end, binary_to_list(AbcSha512)).
  binary:last(AbcSha512).  %159
  io:format("~s~n", [[io_lib:format("~2.16.0B ",[X]) || <<X:8>> <= AbcSha512 ]]).

  L1 = ["foo", "bar", "foo", "foo++", "FOO", "abc"].
  lists:foreach(fun(X) -> io:format("~s~n", [X]) end, L1).
  lists:foreach(fun(X) -> io:format("~s~n", [X]) end, lists:sort(L1)).  %FOO
                                                                         abc
                                                                         bar
                                                                         foo
                                                                         foo
                                                                         foo++

  %guid, 2^82 unique
  make_ref().  %#Ref<0.0.0.393>


- node.js
  /usr/local/bin/node -v  # v5.6

  node --help
  node -e "require('repl').start({ignoreUndefined: true})"
  node helloNode.js

  # repl
  .break
  .clear
  .exit
  .help
  .save session.js
  .load session.js

  LC  terminate current command, twice to exit
  LD  exit

  a = [1, 2, 3]; a.forEach(function(x){ console.log(x); });

  //--------------------------------------
  //node web server
  //http://localhost:8000
  //http://127.0.0.1:8000

  var _http = require('http'),
      _url  = require('url');

  _http.createServer(function(req, res)
  {
      console.log('request URL:', req.url);
      var url = _url.parse(req.url, true);
      if (url.path !== '/favicon.ico')
      {
          console.log('request headers:', req.headers);
          res.writeHead(200, {'Content-Type': 'text/plain',
                              'Server'      : 'Node'});
          res.end('hello Node');
      }
      else
      {
          res.statusCode = 404;
          res.statusMessage = 'Not found';
          res.end();
      }
  }).listen(8000);

  //--------------------------------------

  var _fs   = require('fs'),
      _http = require('http'),
      _url  = require('url'),

      webfolder = '/users/hr/web';

  function serveFile(res, path)
  {
      console.log('webfolder:', webfolder);
      _fs.readFile(webfolder + path,
          function(err, data)
          {
              res.writeHead(200, {'Content-Type': 'text/html',
                                  'Server'      : 'Node'});
              res.write(data);
              res.end();
          });
  }

  //css text, alt to text/plain content-type
  function serveTextFile(res, path)
  {
      _fs.readFile(webfolder + path,
          function(err, data)
          {
              res.writeHead(200, {'Content-Type': 'text/html',
                                  'Server'      : 'Node'});
              res.write('<!doctype html><html><head><title>foo</title></head><body style="background-color: #000; color: #fff;"><pre style="font-family: courier new;">');
              res.write(data);
              res.end('</pre></body></html>');
          });
  }

  _http.createServer(function(req, res)
  {
      console.log('request URL:', req.url);
      var url = _url.parse(req.url, true);
      if (url.path !== '/favicon.ico')
      {
          serveFile(res, '/public/index.htm');
      }
      else
      {
          res.statusCode = 404;
          res.statusMessage = 'Not found';
          res.end();
      }
  }).listen(8000);


- python

  python  -V  # 2.7.10  /usr/bin/python
  python3 -V  # 3.6.1   /usr/local/bin/python3 -> /usr/local/cellar/python3/3.6.1/bin/python3

  python3 --help
  python3 -c "print('foo')"

  quit()  # LD

  pip3 -V  # pip 9.0.1 /usr/local/lib/python3.6/site-packages (python 3.6)


  sorted(['a', 'c', 'b'])           # ['a', 'b', 'c']
  sorted(['a', 'c', 'B'])           # ['B', 'a', 'c']
  sorted(['', ' ', '.', '/', '_'])  # ['', ' ', '.', '/', '_']
  sorted(['a', 'a.', 'a/', 'a_'])   # ['a', 'a.', 'a/', 'a_']
  sorted([1, 10, 9, 2, 20, 3])      # [1, 2, 3, 9, 10, 20]


  for x in [' ', '.', '/', '_']:
      print('\'{}\' = {}'.format(x, ord(x)))  # ' ' = 32
                                                '.' = 46
                                                '/' = 47
                                                '_' = 95


  # --------------------------------------
  # python file hash script, fileHash.py
  import hashlib
  def getFileHash(filePath):
      md5 = hashlib.md5()
      sha1 = hashlib.sha1()
      sha224 = hashlib.sha224()
      sha256 = hashlib.sha256()
      sha384 = hashlib.sha384()
      sha512 = hashlib.sha512()

      with open(file, 'rb') as f:
          for chunk in iter(lambda: f.read(8192), b''):  # b'' = bytes literal
              md5.update(chunk)
              sha1.update(chunk)
              sha224.update(chunk)
              sha256.update(chunk)
              sha384.update(chunk)
              sha512.update(chunk)

      print('md5: ' + md5.hexdigest())
      print('sha1: ' + sha1.hexdigest())
      print('sha224: ' + sha224.hexdigest())
      print('sha256: ' + sha256.hexdigest())
      print('sha384: ' + sha384.hexdigest())
      print('sha512: ' + sha512.hexdigest())

  print('file hash')
  file = input('enter filename: ')  # /users/gvr/file.txt
  getFileHash(file)

  # --------------------------------------
  # example
  python3 ~/fileHash.py

  # file hash
  # enter filename: /users/gvr/file.txt  # abc

  # md5:    900150983cd24fb0d6963f7d28e17f72
  # sha1:   a9993e364706816aba3e25717850c26c9cd0d89d
  # sha224: 23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7
  # sha256: ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
  # sha384: cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7
  # sha512: ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f

  # --------------------------------------
  # python azure blob storage sdk
  # http://azure.microsoft.com/en-us/documentation/articles/storage-python-how-to-use-blob-storage/
  # http://azure.microsoft.com/en-us/documentation/articles/python-how-to-install/
  # https://pypi.python.org/pypi/azure

  pip3 search azure
  pip3 install azure
  ls -l /usr/local/lib/python3.5/site-packages

  from azure.storage.blob import BlobService
  blob_service = BlobService(account_name='__', account_key='__')

  blob_containers = blob_service.list_containers
  for bc in blob_containers():
      print(bc.name)

  blobs = blob_service.list_blobs('blobs')
  for b in blobs:
      print(b.name)

  # upload blob
  blob_service.put_block_blob_from_path('blobs',
                                        'foo.txt',
                                        '/users/sb/temp.txt',
                                        x_ms_blob_content_type='application/txt')

  # uploaded blob url
  http://foo.blob.core.windows.net/blobs/foo.txt

  blob_service.delete_blob('blobs', 'foo.txt')


- curl
  curl -V  # 7.54
  curl http://curl.haxx.se/docs/manpage.html
  curl http://www.gutenberg.org/cache/epub/2600/pg2600.txt -o "tolstoyWarAndPeace.txt"  # download file

  # get
  curl
  -H "Accept: application/xml"
  -H "Content-Type: application/xml"
  -H "Cookie: foo=1"
  -o "/users/jc/downloads/a.com.txt"
  -v
  http://a.com

  # post json body
  curl
  -H "Accept: application/json"
  -H "Content-Type: application/json"
  -H "Content-Length: 13"
  -H "Cookie: foo=1"
  -H "Cookie: bar=1"
  -X POST
  -d '{"foo":"bar"}'
  -v
  http://b.com


- bc calculator
  echo 2+2 | bc
  bc     # bc 1.06
  bc -h  # help
  2 + 2  # ...
  quit

No comments:

Post a Comment