2023-02-09

NGINX config for Websocket

###############
#Nginx Virtual Host Config:
#tiktok.local

server {
listen 80;
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name tiktok.local;


ssl_certificate /home/iadmin/Workspace/local-ssl/tiktok.local/tiktok.local+4.pem;

ssl_certificate_key /home/iadmin/Workspace/local-ssl/tiktok.local/tiktok.local+4-key.pem;


location /ws {
proxy_pass http://127.0.0.1:3000/ws;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}


location / {
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:3000$request_uri;
}

}
###############

# REF:
# https://www.digitalocean.com/community/tutorials/how-to-deploy-a-react-application-with-nginx-on-ubuntu-20-04
# https://stackoverflow.com/questions/55688883/set-up-nginx-proxy-for-react-application
# https://wiki.matbao.net/kb/huong-dan-cai-dat-chung-chi-ssl-tren-nginx/
# https://stackoverflow.com/questions/63134170/create-react-app-code-changes-behind-nginx-reverse-proxy-not-reloading-in-browse

















NodeJS ".env.local":
CHOKIDAR_USEPOLLING=true
WDS_SOCKET_PORT=443



RESULT:

2023-02-03

How to generate PI (3.14) from the Gregory-Leibniz's formula

#!/usr/bin/env python3
# ---------------------------------------
# Project Name : PythonCheatSheet
# File Name    : Calculate-Pi-3-Gregory-Leibniz.py
# Created Date : 2023-02-02 12:46:25 UTC+7
# Last Modified: 2023-02-02 12:48:49 UTC+7
# ---------------------------------------
from pytictoc import TicToc
t = TicToc()  # create TicToc instance
t.tic()       # Start timer
print(f"================================")
# DO SOMETHING
# https://www.mathscareers.org.uk/calculating-pi/
# Gregory-Leibniz:
# Pi/4 = [1 - 1/3 + 1/5 - 1/7 + 1/9 - ...]

def my_pi(p_number: int) -> float:
    my_result = 0
    for i in range(1, n+1, 1):
        if i % 2 == 0:  # even
            my_result = my_result - 1/(2*i - 1)
        else:           # odd
            my_result = my_result + 1/(2*i - 1)
    return my_result*4


n = 1000000
print(f'my_pi({n}): {my_pi(n)}')

print(f"================================")
t.toc()       # Print elapsed time: "Elapsed time is <xxx> seconds."
# ---------------------------------------
# REF:
# https://mathshistory.st-andrews.ac.uk/HistTopics/1000_places/
# 3.14159265358979323846264338327950288419716939937510

# RESULT:
# WINDOWS 3900x:
# ================================
# my_pi(1.000.000): 3.1415916535897743
# ================================
# Elapsed time is 0.127023 seconds.



# Linux 3900x:
# ================================
# PI     : 3.1415916535897743
# ================================
# Elapsed time is 0.209464 seconds.
# ================================
# PI     : 3.1415916535897743
# ================================
# Elapsed time is 0.197258 seconds



# LINUX 5600g:
# n = 100  # 3.1315929035585537
# n = 500  # 3.139592655589785
# n = 700  # 3.1401640828900845
# n = 1.000  # 3.140592653839794
# n = 2.000  # 3.1410926536210413
# n = 3.000  # 3.1412593202657186
# n = 5.000  # 3.141392653591791    - 0.001042 seconds.
# n = 1.000.000   # 3.1415916535897743  - 0.074705 seconds.
# n = 10.000.000  # 3.1415925535897915  - 0.757600 seconds.
# n = 100.000.000 # 3.141592643589326   - 7.646685 seconds.
# n = 1.000.000.000     # 3.1415926525880504 - 81.178900 seconds.
# n = 1.000.000.000     # 3.1415926525880504 - 76.741032 seconds
# n = 10.000.000.000    # 3.141592653488346  - 937.967539 seconds.

2023-01-14

[Ubuntu 20.04.LTS.x64] Install newest [Python 3.11.1]

HOW TO INSTALL NEWEST PYTHON  FROM SOURCECODE
#UBUNTU 20.04.LTS.x64
##########################
REF: https://docs.posit.co/resources/install-python-source/
Posit - Install Python From Source
##########################

sudo apt-get update
sudo apt-get install gdebi-core

sudo apt-get build-dep python
sudo apt-get install libffi-dev libgdbm-dev libsqlite3-dev libssl-dev \
zlib1g-dev




cd /opt/setup/
export PYTHON_VERSION=3.11.1
export PYTHON_MAJOR=3


curl -O https://www.python.org/ftp/python/${PYTHON_VERSION}/Python-${PYTHON_VERSION}.tgz
tar -xvzf Python-${PYTHON_VERSION}.tgz
cd Python-${PYTHON_VERSION}


./configure \
--prefix=/opt/python/${PYTHON_VERSION} \
--enable-shared \
--enable-optimizations \
--enable-ipv6 \
LDFLAGS=-Wl,-rpath=/opt/python/${PYTHON_VERSION}/lib,--disable-new-dtags

make
sudo make install



# Looking in links: /tmp/tmp1i8nsd3d
# Processing /tmp/tmp1i8nsd3d/setuptools-65.5.0-py3-none-any.whl
# Processing /tmp/tmp1i8nsd3d/pip-22.3.1-py3-none-any.whl
# Installing collected packages: setuptools, pip
# WARNING: The scripts pip3 and pip3.11 are installed in '/opt/python/3.11.1/bin' which is not on PATH.
# Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
# Successfully installed pip-22.3.1 setuptools-65.5.0
# WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
# root@3900xl /opt/setup/Python-3.11.1#






# Install pip into the version of Python that you just installed:
curl -O https://bootstrap.pypa.io/get-pip.py
sudo /opt/python/${PYTHON_VERSION}/bin/python${PYTHON_MAJOR} get-pip.py



# Verify that Python is installed by running the following command:
/opt/python/${PYTHON_VERSION}/bin/python${PYTHON_MAJOR} --version


# (Optional) Add Python to the system PATH:
# PATH=/opt/python/<PYTHON-VERSION>/bin/:$PATH
PATH=/opt/python/3.11.1/bin/:$PATH

# #GLOBAL PATH VARIABLES:
# PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/jdk/bin:/opt/script:/opt/lampp/bin:/usr/local/pgsql/bin:/opt/mariadb/bin:/opt/python/3.11.1/bin
# export PATH



2022-12-31

[Python] Nesting LIST inside DICT / Nesting DICT inside LIST / Nesting DICT inside DICT

#!/usr/bin/env python3

# ---------------------------------------
# Project Name: PythonCheatSheet
# File Name: Dict15-01-Nested-Dict.py
# Created Date : 2022-12-31 08:56:51 UTC+7
# Last Modified: 2022-12-31 09:09:29 UTC+7
# ---------------------------------------
import json
from pytictoc import TicToc
t = TicToc()  # create TicToc instance
t.tic()       # Start timer
print(f"================================")
print(f'---------------------')
print(f'# Nesting LIST inside DICT:')
programming_language = {
    'Elshad': ['Python', 'Java', 'C#'],
    'Renad': 'Scratch',
    'Edy': 'Java',
}
print(f'programming_language:')
print(json.dumps(programming_language,
                 sort_keys=False,
                 indent=4,
                 separators=(',', ': ')
                 ))


print(f'\n---------------------')
print(f'# Nesting DICT inside LIST:')
programming_language = [
    {
        'user_name': 'Elshad',
        'favorite_language': ['Python', 'Java', 'C#'],
        'experience': 10,
    },
    {
        'user_name': 'Renad',
        'favorite_language': ['Scratch', 'Python'],
        'experience': 2
    },
]
print(json.dumps(programming_language,
                 sort_keys=False,
                 indent=4,
                 separators=(',', ': ')
                 ))


print(f'\n---------------------')
print(f'# Nesting DICT inside DICT:')
programming_language = {
    'Elshad': {
        'favorite_language': ['Python', 'Java', 'C#'],
        'experience': 10,
    },
    'Renad': {
        'favorite_language': ['Scratch', 'Python'],
        'experience': 2,
    }
}
print(f'programming_language:')
print(json.dumps(programming_language,
                 sort_keys=False,
                 indent=4,
                 separators=(',', ': ')
                 ))
print(f"================================")
t.toc() # Print elapsed time: "Elapsed time is <xxx> seconds."

# RESULT:
"""
# ================================
# ---------------------
# # Nesting LIST inside DICT:
# programming_language:
# {
#     "Elshad": [
#         "Python",
#         "Java",
#         "C#"
#     ],
#     "Renad": "Scratch",
#     "Edy": "Java"
# }

# ---------------------
# # Nesting DICT inside LIST:
# [
#     {
#         "user_name": "Elshad",
#         "favorite_language": [
#             "Python",
#             "Java",
#             "C#"
#         ],
#         "experience": 10
#     },
#     {
#         "user_name": "Renad",
#         "favorite_language": [
#             "Scratch",
#             "Python"
#         ],
#         "experience": 2
#     }
# ]

# ---------------------
# # Nesting DICT inside DICT:
# programming_language:
# {
#     "Elshad": {
#         "favorite_language": [
#             "Python",
#             "Java",
#             "C#"
#         ],
#         "experience": 10
#     },
#     "Renad": {
#         "favorite_language": [
#             "Scratch",
#             "Python"
#         ],
#         "experience": 2
#     }
# }
# ================================
# Elapsed time is 0.003771 seconds.
"""

2022-02-18

OpenSSL Generate SSL CERT FOR IIS (PFX) from PEM

#!/bin/bash
#/etc/haproxy/certs/ssl-convert-PEM-2-PFX.sh

###################################################
#LastUpdate: #7:59 2022.02.18
###################################################
#__________[GLOBAL_VAR]:BEGIN
Domain_Name="
example.com"

SSL_CRT_From_Provider="star_
example.com.crt"
SSL_CA_From_Provider="DigiCertCA.crt"
SSL_CA_Bundle_Provider="My_CA_Bundle.crt"
SSL_CERT_PRIVATE="003-1-STAR_.
example.com
-PRIVATE.key"

SSL_CERT_PEM_FORMAT="$Domain_Name-wildcard-2021.10.03.pem"

#__________[GLOBAL_VAR]:END

openssl \
pkcs12 \
-inkey $SSL_CERT_PRIVATE \
-in $SSL_CRT_From_Provider \
-certfile $SSL_CA_Bundle_Provider \
-export -out $Domain_Name-wildcard-2021.10.03.pfx


echo "VERIFY SSL CERT:"
openssl pkcs12 -info -in $Domain_Name-wildcard-2021.10.03.pfx

#THE_END
#RESULT: example.com-wildcard-2021.10.03.pfx





REF:
1:
#https://www.sslshopper.com/ssl-converter.html
#Convert PEM to PFX:
#openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in 
certificate.crt -certfile CACert.crt

2:
STEP BY STEP USING LETSENCRYPT TO MAKE SSL CERT FOR IIS - MANUAL

2022-01-06

TableAU Backup and Restore

#!/bin/bash
#############################################
# @CreatedDate: #13:39 2022.01.04
# @LastUpdate : #12:46 2022.01.06
# @Last Modified by: iadmin
#############################################
#cat /opt/script/tableau-backup.sh | grep LastUpdate
#############################################
#__________TIME_START:BEGIN
time_start=`date +%s.%3N`
#__________TIME_START:END
#############################################
#############################################
#__________TIME_CALCULATE:BEGIN
#now1: 2022.01.06-11.55.40.168
now1="$(date +'%Y.%m.%d-%H.%M.%S.%3N')"

CURRENT_YEAR=$(date +'%Y'); CURRENT_MONTH=$(date +'%m'); CURRENT_DATE=$(date +'%d')
CURRENT_HOUR=$(date +'%H'); CURRENT_MINUTE=$(date +'%M'); CURRENT_SECOND=$(date +'%S'); CURRENT_MILISECOND=$(date +'%3N');
#YYYY_MM: 2022-01
YYYY_MM="$CURRENT_YEAR-$CURRENT_MONTH"

#YYYY_MM_DD: 2022-01-06
#YYYY_MM_DD="$CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE"

#YYYY_MM_DD: 20220106
YYYY_MM_DD="$CURRENT_YEAR""$CURRENT_MONTH""$CURRENT_DATE"

#HH_MM_SS: 11:55:40.206
#HH_MM_SS="$CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND.$CURRENT_MILISECOND"

#HH_MM_SS: 11.55.40.206
HH_MM_SS="$CURRENT_HOUR.""$CURRENT_MINUTE.""$CURRENT_SECOND.""$CURRENT_MILISECOND"

# echo "YYYY_MM: $YYYY_MM"
# echo "YYYY_MM_DD: $YYYY_MM_DD"
# echo "HH_MM_SS: $HH_MM_SS"
# echo "now1: $now1"
#__________TIME_CALCULATE:END

(
#__________BACKUP_PROCESSING:BEGIN
TableAU_Backup_LOC="/opt/bk/TableAU";
mkdir -p $TableAU_Backup_LOC; cd $TableAU_Backup_LOC

echo ""
echo "Go to backup date folder: [$TableAU_Backup_LOC/$YYYY_MM_DD]"
mkdir -p $YYYY_MM_DD; cd $YYYY_MM_DD

Config_File="config-$YYYY_MM_DD-$HH_MM_SS.json"
Data_File="data-$YYYY_MM_DD-$HH_MM_SS.tsbak"

echo ""
echo "Backup Config: [tsm settings export -f config $Config_File]"
#tsm settings export --output-config-file <path/to/output_file.json> [global options]
#tsm settings export -f config "$Config_File"
tsm settings export --output-config-file "$Config_File"

echo ""
echo "Backup Data: [tsm maintenance backup -f $Data_File]"
#tsm maintenance backup --file <backup_file> [options] [global options]
tsm maintenance backup --file "$Data_File"

echo ""
echo "Moving backup data to Backup Folder [$TableAU_Backup_LOC/$YYYY_MM_DD]"
mv /var/opt/tableau/tableau_server/data/tabsvc/files/backups/* $TableAU_Backup_LOC/$YYYY_MM_DD

md5sum "$Data_File" > "$Data_File".md5
#__________BACKUP_PROCESSING:END


#______________________DELETE_OLD_DATA:BEGIN
cd $PATH_DST
NumberOfFileWantToKeep=14
#Giu lai [14] file moi nhat trong thu muc [$FOLDER_DST]:
#XOA FILE:
#/bin/rm -rf `ls -t "20"* | awk 'NR>7'`

#XOA FOLDER:
cd $TableAU_Backup_LOC
/bin/rm -rf `ls -td */ | awk 'NR>14'`
#______________________DELETE_OLD_DATA:END

#______________________FREE_RAM:BEGIN
free && sync && echo 3 > /proc/sys/vm/drop_caches && free
free
# printf "RAM FREE: \n $(free -h)\n" >> $DB_RESULT.log
#______________________FREE_RAM:END

#############################################
#############################################
#__________TIME_END:BEGIN
time_end=`date +%s.%3N`
execution_time=$( echo "$time_end - $time_start" | bc -l -l );
echo "time_start: [$time_start = $(date -d@$time_start +'%Y.%m.%d-%H.%M.%S.%3N')]"
echo "time_end : [$time_end = $(date -d@$time_end +'%Y.%m.%d-%H.%M.%S.%3N')]"
echo "runtime : [$execution_time] (second.milliseconds)"
#__________TIME_END:END
) 2>&1 | tee backup-job-$YYYY_MM_DD-$HH_MM_SS.log


#THE_END:
# #Restore Config:
# #https://help.tableau.com/current/server/en-us/cli_settings_tsm.htm#TSMSet
# tsm settings import --import-config-file config-2022.01.04-17h40.json

# #Restore Data:
# #https://help.tableau.com/current/server/en-us/upgrade_migrate.htm
# chown -R tableau.tableau /opt/temp/bi-2021.01.04-17h40-2022-01-04.tsbak
# tsm maintenance restore -f /opt/temp/bi-2021.01.04-17h40-2022-01-04.tsbak


#####################
# root@srv032:/opt/bk/TableAU/20220106# /opt/script/tableau-backup.sh

# Go to backup date folder: [/opt/bk/TableAU/20220106]

# Backup Config: [tsm settings export -f config config-20220106-12.33.43.768.json]
# Configuration file written to /opt/bk/TableAU/20220106/config-20220106-12.33.43.768.json.

# Backup Data: [tsm maintenance backup -f data-20220106-12.33.43.768.tsbak]
# Job id is '25', timeout is 1440 minutes.
# 6% - Starting the Active Repository instance, File Store, and Cluster Controller.
# 13% - Waiting for the Active Repository, File Store, and Cluster Controller to start.
# 20% - Installing backup services.
# 26% - Estimating required disk space.
# 33% - Gathering disk space information from all nodes.
# 40% - Analyzing disk space information.
# 46% - Checking if sufficient disk space is available on all nodes.
# 53% - Backing up configuration.
# 60% - Backing up object storage data.
# 66% - Backing up database.
# 73% - Backing up asset keys.
# 80% - Assembling the tsbak archive.
# 86% - Stopping the Active Repository if necessary.
# 93% - Waiting for the Active Repository to stop if necessary.
# 100% - Uninstalling backup services.
# Backup written to '/var/opt/tableau/tableau_server/data/tabsvc/files/backups/data-20220106-12.33.43.768.tsbak' on the controller node.

# Moving backup data to Backup Folder [/opt/bk/TableAU/20220106]
# time_start: [1641447223.762 = 2022.01.06-12.33.43.762]
# time_end : [1641447421.623 = 2022.01.06-12.37.01.623]
# runtime : [197.861] (second.milliseconds)
# root@srv032:/opt/bk/TableAU/20220106#
#####################

2021-11-17

PostgreSQL check all DB SIZE



#CHECK DB SIZE:

postgres=# select t1.datname AS db_name,pg_size_pretty(pg_database_size(t1.datname)) as db_size from pg_database t1 order by pg_database_size(t1.datname) desc;

        db_name         | db_size 
------------------------+---------
 xxx                    | 8109 MB
 xxx_20210622_14h05     | 7520 MB
 xxx_500001_1000000     | 1052 MB
 xxx_000001_500000      | 566 MB
 postgres               | 11 MB
 beta_xxxchat           | 8461 kB
 template1              | 7605 kB
 template0              | 7433 kB
(8 rows)