Tuesday, March 22, 2022

macOS howto format usb drive to dos compatible, max 4GB

 diskutil eraseDisk FAT32 MY_DISK1 /dev/disk2

Labels: , ,

Friday, March 11, 2022

sed command on OSX not supporting '+' or '?' by default

Regex pattern has 3 ways to indicate the occurrence of a character:

"c*"        matching letter 'c'    0 to N    times
"c+"       matching letter 'c'     1 to N    times
"c?"        matching letter 'c'    0 or 1     time

For example, if you want to replace "p...c" in input string,   INSTR="aaabbbcccpppccc"

On Linux, you do        echo $INSTR | sed 's/p\+c/_/'

The same thing on OSX not working, just failed silently.

$ echo $INSTR | sed 's/p\+c/_/'

aaabbbcccpppccc

$ echo $INSTR | sed 's/p+c/_/'

aaabbbcccpppccc


This is because, by default on OSX, sed interprets basic regex.  Instead, we specify using extended regex (-E)

$ echo $INSTR | sed -E 's/p+c/_/'

aaabbbccc_cc

We don't want '*' or the early ccc will be matched.

$ echo $INSTR | sed -E 's/p*c/_/'

aaabbb_ccpppccc

This in fact gives the same result as 's/z*c/_' because 'z' can be zero time

Now, similarly, to indicate 0 or 1 time, use -E as well

$ echo $INSTR | sed -E 's/p?c/_/'

aaabbb_ccpppccc

$ echo $INSTR | sed -E 's/b?c/_/'

aaabb_ccpppccc






Labels: , , ,

Thursday, December 02, 2021

MacOS: install Jupyter-Lab (next gen notebook) in virtual environment

The classic Jupyter notebook, according to jupyter.org, opens each file on separate web browser tab, while the new Jupyter-lab runs like an IDE on one web browser tab.


OSX default to python 2, so I use virtual environment for python3.


(activate venv, see bottom)


# Installation,  reference:     jupyter.org

python3 -m pip install -U pip

python3 -m pip install jupyterlab


# launch server

$ jupyter-lab


# if web browser doesn't start up automatically, manually copy-and-paste the http link from the html to your web browser

...


This page should redirect you to a Jupyter application. If it doesn't,

    <a href="http://localhost:8888/lab?token=..."   



searched   jupyter keyboard shortcuts     , found some good ones in github.

NOTE that on OSX, use 'command' instead of 'ctrl' key



* * * * * *

if first time using virtual environment, create one is simple:


# create a new virtual environment

$   python3 -m venv ~/.venv/py3            


# enter the new environment

$   source  ~/.venv/py3/bin/activate


# play inside the environment, for example:

(py3)  $  python --version


# exit the environment

(py3)  $  deactivate



Labels: , , , ,

Monday, October 11, 2021

中文檔在bash出亂碼,可能unicode須轉成utf-8

 mac osx 與 linux bash 普遍支援 UTF-8 編碼,為 1~4 個bytes不定長度(variable-length) characters。例如ascii 是 1byte,中文字兩bytes。

unicode 係 定長編碼 (fixed-length),unicode 文字檔一般在檔頭加上 Byte order mark (BOM, 字節順序標記)。這種檔在GUI 文件編輯器開無問題,但在 bash 會出亂碼,不能用cat, sed 等命令。

例如有字幕ssa檔

00000000: fffe 5b00 5300 6300 7200 6900 7000 7400  ..[.S.c.r.i.p.t.

00000010: 2000 4900 6e00 6600 6f00 5d00 0d00 0a00   .I.n.f.o.].....

檔頭32bytes 為BOM,標記含義可參考 https://zh.wikipedia.org/wiki/位元組順序記號。


解決辦法 -- 強大轉碼(convert text encoding)工具:

$ iconv -f unicode -t utf-8 in.txt  > out.txt


* * * 

順帶一提,如果要刪除每行末 ^M ,可用 sed 

s/^M//g

注意^M 是一個 character,輸入方法是 ctrl-v ctrl-m。

Labels: , , , , , ,

Sunday, September 26, 2021

Search document content in Mac & Linux

 If there's one feature I like most about Mac, it must be the spotlight search 'summoned' via the keyboard shortcut:  command-space.

It searches not only by filenames, but also the content text; not only in text files, but also in RTF, DOC, etc.  It makes folder boundaries disappear, and file names unimportant.  The files indexing is automatically done in background.


In Windows, about 10 years ago,  there was a Google desktop search sidebar tool, but discontinued.


In Linux, we have multiple built-in tools, eg.   updatedb, then locate pattern for file names;  or ascii content by  grep -HERin pattern path;  or  by more search criteria,   'find' command

Ubuntu has its all-in-one search works somewhat similarly.

For other distro's like mxlinux, an option maybe a tool: search monkey.   To install:


    sudo apt update

    sudo apt upgrade

    sudo apt install searchmonkey


For usage, 3 different ways:

(A) bottom-left menu, type search.  prefilled search location   $HOME

(B) terminal command line:


    $ searchmonkey

or 

    $ searchmonkey -d directory -f filename_regex -t text_regex

eg.

    searchmonkey -d /path/to/directory -f txt -t howto


(C) the handy way, configure in thunar preference  i.e. the explorer

file preference > customized action 

select   'find files here'

origin default is catfish

replace it with


        searchmonkey -d %f


then setup keyboard shortcut for this action.

Note that it's real time search, not from pre-processed database.  Therefore, searching in a big folder takes long time.

Labels: , ,

How to Split a Subdirectory to a New Git Repository and Keep the History

 

(modified from: https://ao.ms/how-to-split-a-subdirectory-to-a-new-git-repository-and-keep-the-history/)


Say, original local path is ~/allMyCode

1) origin repo to check out the branch with all the subdirectory history, eg. master


    git checkout master


2) clone a copy


    git clone  ~/allMyCode  ~/newSubset

    cd ~/newSubset


3) in new clone, remove all but the sub directory (below is a one-liner)


    git filter-branch --prune-empty --subdirectory-filter relative/path/to/subdirectory current_branch_name


4) if the new clone is a branch other than 'master', make it the new 'master'


    git branch -m master


5) remove untracked leftovers, such as ignored/hidden files/folders (WARNING: make sure you have backup)


    git clean -fdx


6) fix remote repo URL    // assume new repo empty


    git remote set-url origin  {newRepoURL}


7) push to new repo


    git push -u origin master



Labels: , , ,

Saturday, August 07, 2021

Git clone to replace a dead repo

A network machine hosting the git repo was dead.

The checkout still exists in local.

Setup a new machine, planning to use it as the new host for repo.



ssh  user@remote

cd /path/to/allprojects/root

git init --bare new_proj.git

exit


# at local

git remote set-url origin  user@remote:/path/to/allprojects/root/new_proj.git

git push --all origin



Labels: , , ,

Saturday, July 31, 2021

Mac/Linux/Ubuntu to convert PDF to JPG

 

ref: https://stackoverflow.com/questions/43085889/how-to-convert-a-pdf-into-jpg-with-command-line-in-linux

        

# using  Image magic


    $ convert -density 300 -quality 100 input.pdf prefix.jpg     


# will give files  prefix-0.jpg, prefix-1.jpg, prefix-2.jpg ...


Labels: , , , , ,

Sunday, July 11, 2021

Python virtual environment in MacOS

On mac osx, default python is version 2, to support system pre-installed packages.


To try python3 environment, one option is using virtual environment, which allows installing different packages in isolated environment.


ref: https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

With python2, install virtualenv

With python3, built-in module is    'venv'



    $ python3 -m pip install --user --upgrade pip     # update pip3


    $ python3 -m pip --version    # check version 


## assume venv for python3

# reuse  ~/.virtualenv  as the root for all new environments


    cd ~/.virtualenv


# (one time only) create new environment for python3


    $ python3 -m venv  py3


## use of environment from now on

# 1) using environment


    $ source py3/bin/activate


    $ which python        # should be within env now


# now can install diff python3 packages for testing


# 2) leaving venv


    $ deactivate



Labels: , , , ,

Sunday, June 27, 2021

NTFS external drive some folders not showing on Mac OSX; but okay on Linux

Not all files/folders, but only a few ones not showing.  

Since NFTS is read-only (by default) in Mac, as long as not reformatting the drive/ partition, those files should be safe, in theory.


This seems to be a real problem encountered by many people.

https://discussions.apple.com/thread/252158724 


Reason unknown yet.  Some said chipset not fully compatible. 

Some other people said the file system might be corrupted somehow.  Because NTFS is Microsoft's proprietary file system.  


In case one wants to repair the drive, it must be done in windows, using the following command.

        chkdsk /f /r 

WARN: backup your drive before making changes.  

Labels: , , , ,

Sunday, April 25, 2021

HOWTO batch processing images on linux or mac osx

#  batch enhance images or batch making thumbnails


for file in *.jpg; do

  convert -enhance -equalize -contrast $file "${file%.jpg}_new.jpg"

done



# other options calling convert

#  convert -auto-gamma -auto-level -normalize original.jpg improved.jpg

#  convert dragon.gif    -resize 64x64  resize_dragon.gif


# ref:  http://www.imagemagick.org/Usage/resize/




Labels: , , , , , , , , ,

Thursday, April 15, 2021

dictionary word lists

every unix-based os has a dictionary word file 


$ wc  /usr/share/dict/words

  235886  235886 2493109 /usr/share/dict/words



online resources


http://wordlist.sourceforge.net/


Labels: , , , ,

Sunday, March 07, 2021

macOS 10.15 to install tensorflow 2.4 for python

Tensorflow is a popular framework for machine learning.

The latest version tensorflow 2 runs on python 3.

My default python version in OSX is  2.7.18

To avoid messing the system, I am going to install tensorflow in a python virtual environment.

* * * * * 

# get the latest python 3

$ brew install python3       # or 

$ brew upgrade python3

# mine installed to  /usr/local/opt/python@3.9@ -> ../Cellar/python@3.9/3.9.2_1

# upgrade pip

/usr/local/opt/python@3.9/bin/python3.9 -m pip install --upgrade pip


(pls refer to official doc for installing virtualenv)

# upgrade virtualenv

/usr/local/opt/python@3.9/bin/python3.9 -m pip install --upgrade virtualenv

# if permission error, append '-user' option to the end

/usr/local/opt/python@3.9/bin/python3.9 -m pip install --upgrade virtualenv -user

# also upgrade the wrapper

/usr/local/opt/python@3.9/bin/python3.9 -m pip install --upgrade virtualenvwrapper


# create new virtual environment

mkvirtualenv -p python3 tf

# enter venv

workon tf

# upgrade pip

~/.virtualenvs/tf/bin/python -m pip install --upgrade pip

# install tensorflow

$ ~/.virtualenvs/tf/bin/python -m pip install tensorflow

# launch python; note version 3.x will be in greeting text

$ python

# check tensorflow installation successful

>>> import tensorflow as tf

>>> tf.__version__

'2.4.1'

# first tensorflow (v1) program

>>> import tensorflow.compat.v1 as tf

>>> tf.disable_v2_behavior()

>>> a = tf.constant(1, name='a')

>>> b = tf.constant(1, name='b')

>>> c = a + b

>>> with tf.compat.v1.Session() as sess:

...     print(sess.run(c))

... 

2021-03-07 12:05:15.104500: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set

2021-03-07 12:05:15.106227: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:196] None of the MLIR optimization passes are enabled (registered 0 passes)

2

>>>

a, b, and c are objects

>>> print(a)

Tensor("a:0", shape=(), dtype=int32)

when done, 

ctrl+d to quit python

then deactivate venv

$ deactivate




Labels: , , ,

Sunday, November 08, 2020

osx terminal less source highlight

 osx terminal less source highlight 

 

  1. brew install source-highlight
    /usr/local/Cellar/source-highlight/3.1.9_3
  2. download a script and put into
    mv src-hilite-lesspipe.sh /usr/local/bin/
  3. add to .bashrc
    export LESSOPEN="| /usr/local/bin/src-hilite-lesspipe.sh %s" export LESS=" -R "
    alias less='less -m -N -g -i -J --underline-special --SILENT'

Labels: , , ,

Sunday, July 14, 2019

HOWTO - on osx convert WAV to MP3 for car audio system

ref: http://apple.stackexchange.com/questions/26099/is-there-a-way-to-convert-audio-files-in-mac-os-x-or-the-command-line-without-us

## PREP ##
# linux
$ sudo apt install ffmpeg
# osx
$ brew install ffmpeg

Warning: You are using a pre-release version of Xcode.
You may encounter build failures or other breakages.
Please create pull-requests instead of filing issues.
==> Installing dependencies for ffmpeg: x264, xvid
==> Installing ffmpeg dependency: x264
==> Downloading https://homebrew.bintray.com/bottles/x264-r2668.el_capitan.bottl
######################################################################## 100.0%
==> Pouring x264-r2668.el_capitan.bottle.tar.gz
🍺  /usr/local/Cellar/x264/r2668: 10 files, 3.3M
==> Installing ffmpeg dependency: xvid
==> Downloading https://homebrew.bintray.com/bottles/xvid-1.3.4.el_capitan.bottl
######################################################################## 100.0%
==> Pouring xvid-1.3.4.el_capitan.bottle.tar.gz
🍺  /usr/local/Cellar/xvid/1.3.4: 9 files, 1.3M
==> Installing ffmpeg
==> Downloading https://homebrew.bintray.com/bottles/ffmpeg-3.1.2.el_capitan.bot
######################################################################## 100.0%
==> Pouring ffmpeg-3.1.2.el_capitan.bottle.tar.gz
==> Caveats
The native FFmpeg AAC encoder has been stable since FFmpeg 3.0. If you
were using libvo-aacenc or libaacplus, both of which have been dropped in
FFmpeg 3.0, please consider switching to the native encoder (-c:a aac),
fdk-aac (-c:a libfdk_aac, ffmpeg needs to be installed with the
--with-fdk-aac option), or faac (-c:a libfaac, ffmpeg needs to be
installed with the --with-faac option).

See the announcement
https://ffmpeg.org/index.html#removing_external_aac_encoders for details,
and https://trac.ffmpeg.org/wiki/Encode/AAC on best practices of encoding
AAC with FFmpeg.
==> Summary
🍺  /usr/local/Cellar/ffmpeg/3.1.2: 236 files, 50.1M

# first time run, if error, lame/lib/libmp3lame.0.dylib not found, reinstall lame
# osx
$ sudo brew uninstall lame
$ sudo brew install lame

## USAGE ##

$ ffmpeg -i leungjok.wav -codec:a libmp3lame -qscale:a 2 leungjok.mp3
ffmpeg version 3.1.2 Copyright (c) 2000-2016 the FFmpeg developers
  built with Apple LLVM version 7.3.0 (clang-703.0.31)
  configuration: --prefix=/usr/local/Cellar/ffmpeg/3.1.2 --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-opencl --enable-libx264 --enable-libmp3lame --enable-libxvid --disable-lzma --enable-vda
  libavutil      55. 28.100 / 55. 28.100
  libavcodec     57. 48.101 / 57. 48.101
  libavformat    57. 41.100 / 57. 41.100
  libavdevice    57.  0.101 / 57.  0.101
  libavfilter     6. 47.100 /  6. 47.100
  libavresample   3.  0.  0 /  3.  0.  0
  libswscale      4.  1.100 /  4.  1.100
  libswresample   2.  1.100 /  2.  1.100
  libpostproc    54.  0.100 / 54.  0.100
Guessed Channel Layout for Input Stream #0.0 : mono
Input #0, wav, from 'LEUNGJOK.WAV':
  Duration: 00:01:07.55, bitrate: 352 kb/s
    Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 22050 Hz, 1 channels, s16, 352 kb/s
[mp3 @ 0x7f8d0a82e200] Using AVStream.codec to pass codec parameters to muxers is deprecated, use AVStream.codecpar instead.
Output #0, mp3, to 'leungjok.mp3':
  Metadata:
    TSSE            : Lavf57.41.100
    Stream #0:0: Audio: mp3 (libmp3lame), 22050 Hz, mono, s16p
    Metadata:
      encoder         : Lavc57.48.101 libmp3lame
Stream mapping:
  Stream #0:0 -> #0:0 (pcm_s16le (native) -> mp3 (libmp3lame))
Press [q] to stop, [?] for help
size=     445kB time=00:01:07.55 bitrate=  53.9kbits/s speed= 141x    
video:0kB audio:444kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.049891%







Labels: , , , , , , , , , , ,

Sunday, May 13, 2018

HOWTO convert ubuntu 18.04 LTS ISO to bootable USB installation disk on Mac OSX


minimum 2GB size of SD card

0) find name of SD card in file system
diskutil list

1) download from ubuntu.com the 18.04 LTS image
cd ~/Downloads/
ls ubuntu-18.04-desktop-amd64.iso

2) convert ISO to dd-table binary image
hdiutil convert -format UDRW -o ubuntu1804.img ubuntu-18.04-desktop-amd64.iso

3) unmount SD card, eg. disk3
diskutil unmountDisk /dev/disk3

4) write to SD card
sudo dd if=./target.img.dmg of=/dev/rdisk3 bs=1m


Labels: , , , , , , , , ,

Friday, March 30, 2018

sed in-place substitute strings

For simple text search & replace, command line using sed:

# default stdout
$ sed 's/OLD_STR/NEW_STR/g'  file.txt
or
$ cat file.txt | sed 's/OLD_STR/NEW_STR/g'

output could be redirect to another file using pipe
$ !! > output.txt

if care not keeping original file, can substitute in-place using option '-i'
on linux, simply
$ sed -i 's/OLD_STR/NEW_STR/g'  file.txt

on mac osx,add an empty string after '-i'
$ sed -i '' 's/OLD_STR/NEW_STR/g'  file.txt

Labels: , , , , , , , ,

Tuesday, March 28, 2017

UTF8碼中文字排序錯誤/ 'sort' failed for zh_TW.UTF-8 on mac OSX (linux, at least mxlinux, is good)

UTF8 sorting likely relies on the encoding values, but not the UTF8 characters themselves.
中文字排序並非以筆劃,而是內碼排列。但是在linux 下內定不懂UTF8 排序。

I tried sort the following but failed.
嘗試排序以下文字,完全忽略不加變更。
乾隆                    
光绪                    
咸丰                    
孔子                    
宣统                    
尼采                    
岳飞                    
牛顿                    
科尔                    
苏轼                    
趙微                    
道光                    
邵雍                    
陆游                    
雍正                    
顺治                    
严篙                           # 奸臣
乾隆                           # 帝王
何洁                           # 藝人
光绪                           # 帝王
刘欢                           # 藝人
和坤                           # 奸臣
咸丰                           # 帝王
宣统                           # 帝王
崇祯                           # 帝王
康熙                           # 帝王
慈禧                           # 皇后
朱熹                           # 文人
杨澜                           # 藝人
林肯                           # 帝王
歌德                           # 文人
秦桧                           # 奸臣

舒淇                           # 藝人

checking export
看語言已經支援UTF-8了...
declare -x LANG="en_US.UTF-8"

guessing it's the 'sort' command default encoding is ascii, not working on utf8.  must use
必須更改 LC_ALL
export LC_ALL=C

now works
严篙                           # 奸臣
乾隆                    
乾隆                           # 帝王
何洁                           # 藝人
光绪                    
光绪                           # 帝王
刘欢                           # 藝人
和坤                           # 奸臣
咸丰                    
咸丰                           # 帝王
孔子                    
宣统                    
宣统                           # 帝王
尼采                    
岳飞                    
崇祯                           # 帝王
康熙                           # 帝王
慈禧                           # 皇后
朱熹                           # 文人
杨澜                           # 藝人
林肯                           # 帝王
歌德                           # 文人
牛顿                    
科尔                    
秦桧                           # 奸臣
舒淇                           # 藝人
苏轼                    
趙微                    
道光                    
邵雍                    
陆游                    
雍正                    
顺治                    

Labels: , , , , , ,

Saturday, October 08, 2016

Highlight syntax in 'less' command on source code. Colorful!!

# linux
sudo apt-get install source-highlight
# osx
brew install source-highlight
# osx only, for compatibility i have,
sudo ln -s /usr/local/Cellar/source-highlight/3.1.8_2/bin/src-hilite-lesspipe.sh /usr/local/bin/

# if the file 'src-hilite-lesspipe.sh' not included, write it without line number:
       1 #! /bin/sh
       2 
       3 for source in "$@"; do
       4     case $source in
       5         *ChangeLog|*changelog) 
       6         source-highlight --failsafe -f esc --lang-def=changelog.lang --style-file=esc.style -i "$source" ;;
       7         *Makefile|*makefile) 
       8         source-highlight --failsafe -f esc --lang-def=makefile.lang --style-file=esc.style -i "$source" ;;
       9         *.tar|*.tgz|*.gz|*.bz2|*.xz)
      10         lesspipe "$source" ;;
      11         *) source-highlight --failsafe --infer-lang -f esc --style-file=esc.style -i "$source" ;;
      12     esac
      13 done


# add the following into .bashrc
### LESS ###
# Enable syntax-highlighting in less.
# brew install source-highlight
# First, add these two lines to ~/.bashrc
export LESSOPEN="| /usr/local/bin/src-hilite-lesspipe.sh %s"
export LESS=" -R "
alias less='less -m -N -g -i -J --underline-special --SILENT'
alias more='less'


# example print-outs

# c code:
       1 /*
       2  * this is comment
       3  */
       4 #include 
       5 
       6 int main( int argc, char ** argv )
       7 {
       8     for (int i=0; i<10; i++)
       9     {
      10         printf("%d ", i);
      11     }
      12     for (int i=0; i<10; i++)
      13     {
      14         printf("%d ", i);
      15     }
      16 
      17     return 0;
      18 }

# python code
       1 #!/usr/bin/env python
       2 import sys
       3 def main(argv):
       4     for x in range( len(sys.argv)-1 ):
       5         print sys.argv[x+1]
       6     print '+'.join(sys.argv[1:])
       7 
       8 if __name__ == "__main__":
       9     main(sys.argv[1:])

sweet.  isn't it?

Labels: , , , , ,