├── .gitignore ├── README.md ├── bash ├── README.md └── downloading.sh ├── images └── interesting_topics │ ├── colabcode │ ├── 2021-06-25-15-53-07.png │ ├── 2021-06-25-15-55-09.png │ ├── 2021-06-25-16-01-04.png │ ├── 2021-06-25-16-09-01.png │ ├── 2021-06-25-16-13-03.png │ ├── 2021-06-25-16-28-34.png │ ├── 2021-06-25-16-36-17.png │ ├── 2021-06-25-16-37-47.png │ └── 2021-06-25-16-38-47.png │ └── window_terminal │ ├── wt_01.jpg │ └── wt_02.PNG ├── interesting_topics ├── colabcode.md └── window_terminal.md └── python └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | tests -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 |

😄 This repository houses a collection of handy code snippets that cater to various situations

3 |

4 | 5 | ## Some kind of snippets: 6 | 7 | - [Bash snippets](bash/README.md) 8 | - [Python snippets](python/README.md) 9 | 10 | ## Some interesting topics 11 | 12 | - [Use Colab/Kaggle in VS Code](interesting_topics/colabcode.md) 13 | - [Connect to Linux server easily with Window Terminal](interesting_topics/window_terminal.md) 14 | 15 | ## Citation 16 | 17 | The code can be stolen from this repo without any permission and all contributors are welcome but you should refer the link to this repo in your code likes the following. 18 | 19 | ```bash 20 | ### in your ~/.bashrc file ### 21 | # the code got from https://github.com/leminhnguyen/useful_snippets 22 | sizeof(){ 23 | # example: sizeof BOOK --> result: 895M BOOK/ 24 | du -h --max-depth=0 "$1" 25 | } 26 | ``` 27 | -------------------------------------------------------------------------------- /bash/README.md: -------------------------------------------------------------------------------- 1 | # Contains my personal snippets 2 | 3 | ## 1. Count the number of files in a folder 4 | For example: `fcount /home/nguyenlm/wavs --> 27` 5 | 6 | ```bash 7 | fcount() { ls -1q "$1" | wc -l; } 8 | ``` 9 | 10 | 11 | ## 2. Fix cuda remove completely problem 12 | 13 | ```sh 14 | sudo apt-get -o Dpkg::Options::="--force-overwrite" install --fix-broken 15 | ``` 16 | 17 | ## 3. Count the number of non-blank lines in the files 18 | For example: `nbl-count file.txt --> 10` 19 | 20 | ```bash 21 | nbl-count() = { grep -cve '^\s*$' "$1" } 22 | ``` 23 | 24 | ## 4. Run docker without sudo 25 | 26 | ```bash 27 | sudo chmod 666 /var/run/docker.sock 28 | ``` 29 | 30 | ## 5. Fix 2nd screen cannot be detected when reinstalling ubuntu 31 | 32 | ```bash 33 | sudo apt-get purge 'nvidia*' 34 | sudo add-apt-repository ppa:graphics-drivers 35 | sudo apt-get update 36 | sudo ubuntu-drivers autoinstall 37 | ``` 38 | 39 | ## 6. Fix Invalid MIT-MAGIC-COOKIE-1 keyUnable to init server and javafx 40 | Caused by: *java.lang.UnsupportedOperationException: Unable to open DISPLAY
* 41 | Reference: [this link](https://bbs.archlinux.org/viewtopic.php?id=230828) 42 | 43 | ```bash 44 | who -> user :1 2017-10-12 21:58 (:1) 45 | ``` 46 | > Yeah, the reason is that you're on DISPLAY :1.0 - no idea why your environment variable is borked 47 | ```bash 48 | export DISPLAY=:1.0 49 | zenity --info --text foobar 50 | ``` 51 | > Check your profile files and bashrc (or zshrc or whatever) and /etc/environment and DE environment configuration - somewhere this will be falsely exported. 52 | 53 | ## 7. Get size of folder 54 | For example: `example: sizeof BOOK --> result: 895M BOOK/` 55 | 56 | ```bash 57 | sizeof(){ 58 | du -h --max-depth=0 "$1" 59 | } 60 | ``` 61 | 62 | ## 8. Rsync from local to remote 63 | Reference: [Rsync Command in Linux - Linuxize](https://linuxize.com/post/how-to-use-rsync-for-local-and-remote-data-transfer-and-synchronization/)
64 | Note: can run with `-n` option for the sake of safety 65 | ```bash 66 | rsync -aPz -e "ssh -p port" local_folder/ user@remote_host:remote_folder 67 | ``` 68 | 69 | ## 9. Find and kill specific processes 70 | Note: `[p]` means we do not kill grep process itself 71 | 72 | ```bash 73 | kill $(ps aux | grep '[p]rocess.py' | awk '{print $2}') 74 | ``` 75 | 76 | ## 10. Recover the lost tmux session 77 | 78 | ```bash 79 | pkill -USR1 tmux 80 | ``` 81 | -------------------------------------------------------------------------------- /bash/downloading.sh: -------------------------------------------------------------------------------- 1 | folder="" 2 | declare -A urls=() 3 | 4 | while getopts ":f:u:n:h" opt; do 5 | case $opt in 6 | h) 7 | echo "" 8 | echo "----------- created by nguyenlm ---------------" 9 | echo "" 10 | echo "Usage: Download multifiles into one folder" 11 | echo "" 12 | echo "Arguments:" 13 | echo "-h --help shows guideline and exits" 14 | echo "-f --folder the folder where we'll download into (default is current directory)" 15 | echo "-u --url the specified url needed to download" 16 | echo "-n --name the name of previous url saved in my computer" 17 | exit 1 18 | ;; 19 | f) 20 | if [ ! -z "$folder" ]; then 21 | echo "only allow one folder" 22 | exit 1 23 | fi 24 | folder=$OPTARG 25 | ;; 26 | u) 27 | urls[$OPTARG]="" 28 | ;; 29 | n) 30 | prev_argument_index=`expr $OPTIND - 3` 31 | prev_url=${!prev_argument_index} 32 | urls[$prev_url]=$OPTARG 33 | ;; 34 | \?) 35 | echo "Invalid option: -$OPTARG" >&2 36 | ;; 37 | esac 38 | done 39 | 40 | if [ ! -z "$folder" ]; then 41 | mkdir $folder 42 | else 43 | folder=$CWD 44 | fi 45 | 46 | for url in "${!urls[@]}";do 47 | echo "downloading the file \"$url\" into the folder \"$folder\"" 48 | 49 | filename=${urls[$url]} 50 | if [ -z "$filename" ]; then 51 | wget -P $folder $url 52 | else 53 | cd $folder 54 | wget -O $filename $url 55 | fi 56 | 57 | done -------------------------------------------------------------------------------- /images/interesting_topics/colabcode/2021-06-25-15-53-07.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leminhnguyen/useful_snippets/d72342091626967752f7b882742fa941fd1f68b9/images/interesting_topics/colabcode/2021-06-25-15-53-07.png -------------------------------------------------------------------------------- /images/interesting_topics/colabcode/2021-06-25-15-55-09.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leminhnguyen/useful_snippets/d72342091626967752f7b882742fa941fd1f68b9/images/interesting_topics/colabcode/2021-06-25-15-55-09.png -------------------------------------------------------------------------------- /images/interesting_topics/colabcode/2021-06-25-16-01-04.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leminhnguyen/useful_snippets/d72342091626967752f7b882742fa941fd1f68b9/images/interesting_topics/colabcode/2021-06-25-16-01-04.png -------------------------------------------------------------------------------- /images/interesting_topics/colabcode/2021-06-25-16-09-01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leminhnguyen/useful_snippets/d72342091626967752f7b882742fa941fd1f68b9/images/interesting_topics/colabcode/2021-06-25-16-09-01.png -------------------------------------------------------------------------------- /images/interesting_topics/colabcode/2021-06-25-16-13-03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leminhnguyen/useful_snippets/d72342091626967752f7b882742fa941fd1f68b9/images/interesting_topics/colabcode/2021-06-25-16-13-03.png -------------------------------------------------------------------------------- /images/interesting_topics/colabcode/2021-06-25-16-28-34.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leminhnguyen/useful_snippets/d72342091626967752f7b882742fa941fd1f68b9/images/interesting_topics/colabcode/2021-06-25-16-28-34.png -------------------------------------------------------------------------------- /images/interesting_topics/colabcode/2021-06-25-16-36-17.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leminhnguyen/useful_snippets/d72342091626967752f7b882742fa941fd1f68b9/images/interesting_topics/colabcode/2021-06-25-16-36-17.png -------------------------------------------------------------------------------- /images/interesting_topics/colabcode/2021-06-25-16-37-47.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leminhnguyen/useful_snippets/d72342091626967752f7b882742fa941fd1f68b9/images/interesting_topics/colabcode/2021-06-25-16-37-47.png -------------------------------------------------------------------------------- /images/interesting_topics/colabcode/2021-06-25-16-38-47.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leminhnguyen/useful_snippets/d72342091626967752f7b882742fa941fd1f68b9/images/interesting_topics/colabcode/2021-06-25-16-38-47.png -------------------------------------------------------------------------------- /images/interesting_topics/window_terminal/wt_01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leminhnguyen/useful_snippets/d72342091626967752f7b882742fa941fd1f68b9/images/interesting_topics/window_terminal/wt_01.jpg -------------------------------------------------------------------------------- /images/interesting_topics/window_terminal/wt_02.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leminhnguyen/useful_snippets/d72342091626967752f7b882742fa941fd1f68b9/images/interesting_topics/window_terminal/wt_02.PNG -------------------------------------------------------------------------------- /interesting_topics/colabcode.md: -------------------------------------------------------------------------------- 1 |

2 |

😳 Chạy Kaggle hoặc Colab trên Vscode

3 |

4 | 5 | Cơ chế hoạt động của cái này là sẽ dùng bên thứ 3 `ngrok` để connect `VS Code` và `Kaggle` (hoặc `Colab`). Ở hướng dẫn này thì mình dùng `Kaggle`. 6 | 7 | 8 | ### Step1: Tạo tài khoản trên ngrok tại địa chỉ https://dashboard.ngrok.com/signup sau đó copy cái authtoken ở trang Setup & Installation 9 | 10 | ![](../images/interesting_topics/colabcode/2021-06-25-16-01-04.png) 11 | 12 | ### Step2: Tạo file notebook mới trên Kaggle sau đó cài thư viện colabcode (Google Colab tương tự), nhớ turn on cả GPU để server VS Code dùng được GPU 13 | 14 | ```sh 15 | !pip install colabcode 16 | ``` 17 | 18 | ![](../images/interesting_topics/colabcode/2021-06-25-15-55-09.png) 19 | 20 | ### Step3: Kết nối tới server của ngrok 21 | 22 | ```python 23 | from colabcode import ColabCode 24 | ColabCode( 25 | port=10000, 26 | password="abcdef", 27 | authtoken="1uPXZm2sN4DJlzJpob6fso2r5Jy_4NAksdacaHkfmFGLxEZvG" 28 | ) 29 | ``` 30 | Thông tin tham số: 31 | - `port`: cổng kết nối tới ngrok 32 | - `password` (optional): password để connect tới server vscode 33 | - `authtoken`: token lấy từ ngrok tại B1, mục đích của cái token là giúp không bị limit connection tới ngrok 34 | 35 | ![](../images/interesting_topics/colabcode/2021-06-25-16-09-01.png) 36 | 37 | Click vào cái đường dẫn `NgrokTunnel` sau đó vào vscode server (nếu có password thì hệ thống sẽ yêu cầu thêm nhập password) 38 | 39 | ![](../images/interesting_topics/colabcode/2021-06-25-16-13-03.png) 40 | 41 | ### Step4: Thử nghiệm 42 | 43 | Mở folder bất kỳ, tạo thử file `test.python` (ở đây mình dùng folder `/home/nguyenlm/test` tự tạo bằng `mkdir -p /home/nguyenlm/test`). Ở đây check thành công sử dụng được GPU nhưng theo giới hạn của Kaggle thì chỉ dùng được 25-30h/tuần. 44 | 45 | ![](../images/interesting_topics/colabcode/2021-06-25-16-28-34.png) 46 | 47 | Cài thử `nvtop`, ở đây là server Ubuntu 18.04 và có quyền root nên khi cài thì không cần `sudo` 48 | 49 | ```sh 50 | # install C dependencies 51 | apt install cmake libncurses5-dev libncursesw5-dev git 52 | 53 | # build nvtop 54 | git clone https://github.com/Syllo/nvtop.git 55 | mkdir -p nvtop/build && cd nvtop/build 56 | cmake .. 57 | make 58 | make install 59 | ``` 60 | 61 | Chạy thử `nvtop` 62 | 63 | ![](../images/interesting_topics/colabcode/2021-06-25-16-36-17.png) 64 | 65 | Chạy thử `htop` 66 | 67 | ![](../images/interesting_topics/colabcode/2021-06-25-16-37-47.png) 68 | 69 | Chạy thử `df -h` để check bộ nhớ 70 | 71 | ![](../images/interesting_topics/colabcode/2021-06-25-16-38-47.png) -------------------------------------------------------------------------------- /interesting_topics/window_terminal.md: -------------------------------------------------------------------------------- 1 |

2 |

😎 Connect to Linux server with Window Terminal

3 |

4 | 5 | ### Download window terminal 6 | 7 | With window terminal we can use some common commands in Linux like `ls`, `cd`, `scp`, `ssh`... If you're familiar with Linux and want to use more commands, please install [WSL (Window Subsystem for Linux)](https://docs.microsoft.com/en-us/windows/wsl/install-win10?ranMID=46131&ranEAID=a1LgFw09t88&ranSiteID=a1LgFw09t88-wsO_vuOpJsLH4s92WtO5iw&epi=a1LgFw09t88-wsO_vuOpJsLH4s92WtO5iw&irgwc=1&OCID=AID2200057_aff_7806_1243925&tduid=%28ir__bl2gtjnvwgkfqzuf0iq621u0ze2xrkty3g0rltd200%29%287806%29%281243925%29%28a1LgFw09t88-wsO_vuOpJsLH4s92WtO5iw%29%28%29&irclickid=_bl2gtjnvwgkfqzuf0iq621u0ze2xrkty3g0rltd200) and itergrate with window terminal. 8 | 9 | Link download: [window terminal download](https://www.microsoft.com/en-us/p/windows-terminal/9n0dx20hk701?ranMID=46131&ranEAID=a1LgFw09t88&ranSiteID=a1LgFw09t88-DnkwG9hHnodeH5k2AklK2Q&epi=a1LgFw09t88-DnkwG9hHnodeH5k2AklK2Q&irgwc=1&OCID=AID2200057_aff_7806_1243925&tduid=%28ir__bl2gtjnvwgkfqzuf0iq621u0ze2xrkt13s0rltd200%29%287806%29%281243925%29%28a1LgFw09t88-DnkwG9hHnodeH5k2AklK2Q%29%28%29&irclickid=_bl2gtjnvwgkfqzuf0iq621u0ze2xrkt13s0rltd200&activetab=pivot:overviewtab) 10 | 11 | Screenshot from my computer: 12 | 13 | ![](../images/interesting_topics/window_terminal/wt_02.PNG) 14 | 15 | Screenshot get from official page: 16 | 17 | ![](../images/interesting_topics/window_terminal/wt_01.jpg) 18 | 19 | ### Connect to Linux server without password 20 | 21 | Create public key with `ssh-keygen`, this command will create a private key and a public key, places the public key to anywhere that you want connecting to and never shares your private key to someone. By default the private key will be in `C:\Users\username\.ssh\id_rsa` and the public key will be in `C:\Users\username\.ssh\id_rsa.pub`. Run the following command. 22 | 23 | ````sh 24 | ssh-keygen.exe 25 | ### output ### 26 | # Generating public/private rsa key pair. 27 | # Enter file in which to save the key (C:\Users\nguyenlm/.ssh/id_rsa): 28 | ```` 29 | 30 | Copy content of `C:\Users\username\.ssh\id_rsa.pub` to `~/.ssh/authorized_keys` file on the Linux server, if this file didn't exist just create the new one. See the following example: 31 | 32 | ````sh 33 | ### ~/.ssh/authorized_keys file 34 | ssh-rsa AAAAB3NzaC1...nguyenlm@DESKTOP-3OQO7KC 35 | 36 | ### we can place mutiple public keys to this file 37 | ssh-rsa key2...nguyenlm@DESKTOP-3OQO7KC 38 | ssh-rsa key3...nguyenlm@DESKTOP-3OQO7KC 39 | ... 40 | ```` 41 | 42 | Try to connect to Linux server, if you don't have the ssh key or something went wrong with your key, you should have to enter the password 43 | 44 | ````sh 45 | ssh -p port username@server_url 46 | ```` 47 | 48 | If all steps above were successfully completed, then you have never typed password anymore (also when connecting by) -------------------------------------------------------------------------------- /python/README.md: -------------------------------------------------------------------------------- 1 | # The table of contents 2 | [1. Multiprocessing with `p_tqdm` library](#multiprocessing-with-p_tqdm-library)
3 | [2. Get audio duration very fast](#get-audio-duration-very-fast)
4 | [3. Use decorator to measure processing time of a function](#time-decorator) 5 | 6 | 7 |
8 | 9 | ## 1. Multiprocessing with `p_tqdm` library 10 | 11 | ### Installation 12 | 13 | ````bash 14 | pip install p_tqdm 15 | ```` 16 | 17 | ### Example 18 | 19 | ````python 20 | from scipy.io.wavfile import read 21 | from p_tqdm import p_map, p_umap 22 | import os 23 | import pandas as pd 24 | 25 | # defines the function which need to be processed in parallel 26 | def process_wav(wav_path): 27 | sr, wav = read(wav_path) 28 | duration = len(wav)/sr 29 | return { 30 | "wav_path": wav_path, 31 | "duration": duration, 32 | "samplerate": sr 33 | } 34 | 35 | # gets the list of audio paths 36 | wav_dir = "/tmp/original_wavs" 37 | wav_paths = [f"{wav_dir}/{file}" for file in os.listdir(wav_dir)] 38 | 39 | ### process in parallel and return the ordered results ### 40 | ordered_results = p_map(process_wav, wav_paths, num_cpus=4) 41 | 42 | ### process in parallel and return the unordered results ### 43 | unordered_results = p_umap(process_wav, wav_paths, num_cpus=4) 44 | 45 | ### in the process the progress bar will be printed ### 46 | 60%|████████████████████████ | 60/100 [00:02<00:01, 1.00s/it] 47 | 48 | # convert the results to dataframe 49 | pd.DataFrame(ordered_results) 50 | ```` 51 | 52 | | wav_path | duration | samplerate | 53 | | ----------------------------- | -------- | ---------- | 54 | | /tmp/original_wavs/audio1.wav | 12.0 | 16000 | 55 | | /tmp/original_wavs/audio2.wav | 3.55 | 16000 | 56 | | ... | ... | ... | 57 | 58 |
59 | 60 | ## 2. Get audio duration very fast 61 | We will use a built-in module called `wave` to read the audio header only to get metadata. 62 | 63 | ### Example 64 | ````python 65 | import wave 66 | 67 | def get_duration(wav_file): 68 | wav = wave.open(wav_file) 69 | sample_rate = wav.getframerate() 70 | nframes = wav.getnframes() 71 | return round(nframes/rate, 2) 72 | 73 | print(get_duration("/tmp/test.wav")) # 3.21s 74 | ```` 75 | 76 |
77 | 78 | ## 3. Use decorator to measure processing time of a function 79 | 80 | ### Example 81 | ````python 82 | import time, random as rd 83 | 84 | def time_decorator(function): 85 | def wrapper(*args, **kwargs): 86 | stime = time.time() 87 | result = function(*args, **kwargs) 88 | process_time = time.time() - stime 89 | print(f"{function.__name__} taken time: {process_time} ms") 90 | return result 91 | return wrapper 92 | 93 | @time_decorator 94 | def process(): 95 | total = 0 96 | for i in range(rd.randint(10000, 10_000_000)): 97 | total += i 98 | return total 99 | 100 | # process taken time: 0.6141083240509033 ms 101 | process() 102 | ```` 103 | 104 | 105 | ## 4. [Kaggle/Colab] Permission denied although I have set to "anyone with link" 106 | ```python 107 | !pip install --upgrade --no-cache-dir gdown 108 | 109 | import gdown; 110 | file_id = '1N3-c-IzIqYNB53ojvZKkEEMO0c7eEQZQ' 111 | url = f"https://drive.google.com/uc?export=download&id={file_id}&confirm=t" 112 | output = 'out.zip' 113 | gdown.download(url, output, quiet=False) 114 | ``` --------------------------------------------------------------------------------