2024年12月2日 星期一

flask 連線遠端 mysql 主機

在上一篇文章中

我們已經安裝好一台 ubuntu 20.04 並安裝了 mySQL ,版本是 8.0.44

現在我們在另一台電腦(windows)上開發 flask


一個最簡單的 flask 寫法如下

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
return 'Welcome to My Watchlist!'

if __name__ == '__main__':
app.run(debug=True)

然後需要安裝 mySQL client 的套件,我選的套件是 mysql-connector-python

所以安裝方法就是  pip install mysql-connector-python

這裡有個坑,套件名稱千萬不要打成 mysql-connector

延伸閱讀


安裝好之後可以把程式改成下面這樣

from flask import Flask
import mysql.connector
from mysql.connector import Error

app = Flask(__name__)

# Establish the connection
def get_db_connection():
try:
conn = mysql.connector.connect(
user='mike',
password='pass',
host='192.168.0.31',
port=3306,
database='ocrDB',
autocommit=True
)
return conn
except Error as e:
print(f"Error: {e}")
return None


@app.route('/')
def hello():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SHOW TABLES')
tables = cursor.fetchall()
cursor.close()
conn.close()
return 'Welcome to My Watchlist!'


if __name__ == '__main__':
app.run(debug=True)

然後執行,觸發 def hello() 就會報錯了

詢問 chatgpt 後歸納成幾個原因

Summary of Steps to Resolve:

  1. Ensure MySQL is running on 192.168.0.31.
  2. Open port 3306 on the firewall of the MySQL server.
  3. Update MySQL bind-address in the configuration to allow remote connections.
  4. Grant remote access privileges to the MySQL user.

1. 在 mySQL 安裝的 ubuntu 上輸入 sudo service mysql status 即可確認 

2. 這邊 chatgpt 丟出了一句 sudo ufw allow 3306

首先 ufw 應該是預設有安裝的,但我們可以檢查一下狀態

$ ufw enable            // 啟動防火牆,執行後開機也會自動啟動

$ ufw disable           // 關閉防火牆

$ ufw status            // 查看防火牆狀態

$ ufw status verbose    // 查看防火牆詳細狀態

基本上就是把 3306 port 打開,這部分沒啥問題

延伸閱讀


3. 這邊 chatgpt 說

On the MySQL server, check the MySQL configuration file (my.cnf or my.ini), usually located in /etc/mysql/my.cnf or /etc/my.cnf (depending on the distribution). Ensure that the bind-address is set to either 0.0.0.0 or the specific server IP. Example:

bind-address = 0.0.0.0

沒問題,就按照它說的去改

在我的環境中,設定檔是位於 /etc/mysql/my.cnf

改好之後重新啟動 mySQL

sudo systemctl restart mysql

然後 mySQL 就掛了!

google 一下發現有人說你得寫成下面這樣才行

[mysqld]
bind-address = 0.0.0.0

存檔,重啟 mySQL 就成功了

延伸閱讀


4. 在上一篇文章我們就有授權給 remote user 了

所以這部分沒問題

順道一提這個 database='ocrDB' 是我事先在 ubuntu 上用 mySQL command line 開好的

改到目前這樣就可以用 debug 模式看到 cursor 拿回來的 table 是空的 (因為還沒開 table)

沒有 error 出現,可以順利跑完

以上,做個初學者紀錄,這篇就講到這


2024年11月21日 星期四

Ubuntu 20.04 安裝 MySQL server

sudo apt-get update

sudo apt install mysql-server

裝完後可以用以下指令查看狀態

sudo service mysql status


然後執行

sudo mysql_secure_installation

它會問幾個問題

1. would you like to setup validate password component?

2. remove anonymous users?

3. disallow root login remotely?

4. remove test database and access to it?

照直覺選一選就好


查看 mysql 版本

sudo mysqladmin -p -u root version

查看本地 ip

hostname -I

登入 mysql

sudo mysql -u root -p

預設密碼是空的,所以直接按 enter 就可以


進入 mysql 後

列出所有 database

mysql> show databases;

查詢使用者

mysql> SELECT user FROM mysql.user;

上面這個寫法是去 mysql 這個 database 的 user table 撈 user 欄位

所以也可以先

mysql> USE mysql

然後就可以寫成

mysql> Select user FROM user;

如果想查詢這個 database 有哪些 table 可以用下列指令

mysql> show full tables;

mysql> show tables;


開一個新的 database

mysql> CREATE DATABASE ooxx;

開一個新的 user,這裡示範的 user 叫 mike,而密碼就是 password

mysql> CREATE USER 'mike'@'localhost' IDENTIFIED BY 'password';

如果這個 user 會遠端登入的話,可以寫成下面這樣

mysql> CREATE USER 'mike'@'%' IDENTIFIED BY 'password';

如果出現下面這個 error 表示你的密碼不符合規範

ERROR 1819 (HY000): Your password does not satisfy the current policy requirements

可以使用下面這列來看目前的密碼規範

mysql> SHOW VARIABLES LIKE 'validate_password%';

就我自己來說,我改了下面兩列

mysql> SET GLOBAL validate_password.length = 4;

mysql> SET GLOBAL validate_password.policy=LOW;

然後可以修改使用者密碼如下列

mysql> ALTER USER 'mike'@'%' IDENTIFIED BY 'pass';


如果要把剛才開的 database ooxx的權限給 mike 的話

mysql> GRANT ALL PRIVILEGES ON ooxx.* TO 'mike'@'%';

或著當初開 database 時就是用 mike 的身分去開的話,就會自動給權限

延伸閱讀


最後別忘了

mysql> FLUSH PRIVILEGES;


下次要使用 mike 登入時就可以使用下列指令

sudo mysql -u mike -p

然後它會問你密碼你再輸入 pass (剛才 mike 的密碼已經改成 pass)

或是可以直接輸入

sudo mysql -u mike -ppass

注意最後 -ppass 沒有空格,而且會跳出警告建議你不要直接打出密碼

這篇大概就這樣

2024年8月16日 星期五

Ubuntu 20.04 安裝 ASUS TUF Gaming B650m PLUS WiFi 驅動程式

簡單來說

這張板子安裝了Ubuntu 20.04 後,找不到 wifi 選項

幸好插上實體網路線還能用

一般來說就是沒驅動程式

上網 google 這板子用哪個 wifi 晶片還找不到

一直到 ASUS 的驅動程式下載網頁才看到晶片名稱

https://www.asus.com/tw/motherboards-components/motherboards/tuf-gaming/tuf-gaming-b650m-plus-wifi/helpdesk_download?model2Name=TUF-GAMING-B650M-PLUS-WIFI


Realtek RTL8852BE WiFi driver V6001.15.124.0 For Windows 10/11 64-bit.
版本 6001.15.124.0
6.15 MB
2022/09/13

Please install the corresponding driver according to the WIFI/BT chip on your motherboard.

知道晶片名稱再來下關鍵字就簡單多了

找到下面兩篇

https://blog.csdn.net/qq_75220669/article/details/137251306

https://ubuntuforums.org/showthread.php?t=2484689

為避免以後連結失效

這裡將需要的步驟複製貼上

sudo apt update
sudo apt install git make gcc bc

查看核心版本

uname -r

低於 5.18 => https://github.com/HRex39/rtl8852be.git

高於 5.18=> https://github.com/HRex39/rtl8852be.git -b dev


git clone https://github.com/HRex39/rtl8852be.git
cd rtl8852be
make    /*  如果要 multi-thread build 的話,輸入 make -j$(nproc)  */
sudo make install
sudo modprobe 8852be


走完步驟 WiFi 就可以使用了


2024年6月18日 星期二

pyinstaller 打包 mmcv 相關的 exe 可能會遇到的問題

打包完後要執行時遇到了一個問題如下

FileNotFoundError: [Errno 2] No such file or directory: '/home/XXX/tmp-dir/_MEIkGapxs/yapf_third_party/_ylib2to3/Grammar.txt'

上網查到了這篇

https://blog.csdn.net/weixin_44243859/article/details/131890088

為了怕以上連結失效,這邊稍微重複一下內容

說是 pyinstaller 沒有自帶該第三方庫文件的hook的時候,就會導致這個包文件不被打包進來,解決辦法,寫個 hook,然後放進 pyinstaller 的 hooks 裡面,hook 文件的命名規範為: hook-yapf_third_party.py

from PyInstaller.utils.hooks import collect_data_files datas = collect_data_files("yapf_third_party")

以上就是這個 .py 的內容

但具體來說我還是不知道怎麼做

於是再查到了這篇

https://blog.csdn.net/cliffordl/article/details/138065845

看了這篇之後就明白很多

如果我要打包 main.py,然後我要讓他去 hook 一些 library

那我就在 main.py 旁邊開一個 hooks 資料夾

然後把上面的 hook-yapf_third_party.py 丟進這個資料夾

(其中 hook-xxx.py 的 xxx 就是 library 名稱)

然後在打包時加入 --additional-hooks-dir ./hooks

所以整個打包的指令就變成 

pyinstaller -F -c --additional-hooks-dir ./hooks main.py

這個問題這樣就解決了,然後接下來又遇到

ModuleNotFoundError: No module named 'mmcv._ext'

繼續上網查,發現這篇

https://blog.csdn.net/gc5218112/article/details/125172123

OK,他說要在 hiddenimports 加入 'mmcv', 'mmcv._ext'

找到 main.spec,照著加進去,然後執行

pyinstaller main.spec

問題也確實解決了,但這樣很不方便,我希望可以不要去改 .spec

所以這個命令可以寫成

pyinstaller -F -c --additional-hooks-dir ./hooks --hidden-import mmcv --hidden-import mmcv._ext main.py

這樣全部的問題都解決了,大功告成


2024年6月4日 星期二

ubuntu 20.04 安裝 CUDA 11.8 for RTX 4090

 先上個連結

https://gist.github.com/MihailCosmin/affa6b1b71b43787e9228c25fe15aeba?permalink_comment_id=4665431

上面這連結是在講 ubuntu 22.04 怎麼裝 CUDA 11.8

他的最後更新時間是 Oct 29, 2023

而現在是 June 04, 2024

NV Driver 版號又不太一樣了,在這紀錄一下踩坑紀錄

====================先照貼原本的內容====================

#!/bin/bash ### steps #### # verify the system has a cuda-capable gpu # download and install the nvidia cuda toolkit and cudnn # setup environmental variables # verify the installation ### ### to verify your gpu is cuda enable check lspci | grep -i nvidia ### If you have previous installation remove it first. sudo apt purge nvidia* -y sudo apt remove nvidia-* -y sudo rm /etc/apt/sources.list.d/cuda* sudo apt autoremove -y && sudo apt autoclean -y sudo rm -rf /usr/local/cuda* # system update sudo apt update && sudo apt upgrade -y # install other import packages sudo apt install g++ freeglut3-dev build-essential libx11-dev libxmu-dev libxi-dev libglu1-mesa libglu1-mesa-dev # first get the PPA repository driver sudo add-apt-repository ppa:graphics-drivers/ppa sudo apt update # find recommended driver versions for you ubuntu-drivers devices # install nvidia driver with dependencies sudo apt install libnvidia-common-515 libnvidia-gl-515 nvidia-driver-515 -y # reboot sudo reboot now # verify that the following command works nvidia-smi sudo wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-ubuntu2204.pin sudo mv cuda-ubuntu2204.pin /etc/apt/preferences.d/cuda-repository-pin-600 sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/3bf863cc.pub sudo add-apt-repository "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/ /" # Update and upgrade sudo apt update && sudo apt upgrade -y # installing CUDA-11.8 sudo apt install cuda-11-8 -y # setup your paths echo 'export PATH=/usr/local/cuda-11.8/bin:$PATH' >> ~/.bashrc echo 'export LD_LIBRARY_PATH=/usr/local/cuda-11.8/lib64:$LD_LIBRARY_PATH' >> ~/.bashrc source ~/.bashrc sudo ldconfig # install cuDNN v11.8 # First register here: https://developer.nvidia.com/developer-program/signup CUDNN_TAR_FILE="cudnn-linux-x86_64-8.7.0.84_cuda11-archive.tar.xz" sudo wget https://developer.download.nvidia.com/compute/redist/cudnn/v8.7.0/local_installers/11.8/cudnn-linux-x86_64-8.7.0.84_cuda11-archive.tar.xz sudo tar -xvf ${CUDNN_TAR_FILE} sudo mv cudnn-linux-x86_64-8.7.0.84_cuda11-archive cuda # copy the following files into the cuda toolkit directory. sudo cp -P cuda/include/cudnn.h /usr/local/cuda-11.8/include sudo cp -P cuda/lib/libcudnn* /usr/local/cuda-11.8/lib64/ sudo chmod a+r /usr/local/cuda-11.8/lib64/libcudnn* # Finally, to verify the installation, check nvidia-smi nvcc -V # install Pytorch (an open source machine learning framework) pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118

====================以下是要更改的內容====================

# install nvidia driver with dependencies sudo apt install libnvidia-common-535 libnvidia-gl-535 nvidia-driver-535 -y

因為 driver 版本更新,這個時間點已經找不到 515 了

所以這邊把 515 改成 535


# verify that the following command works nvidia-smi sudo wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-ubuntu2204.pin sudo mv cuda-ubuntu2204.pin /etc/apt/preferences.d/cuda-repository-pin-600 sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/3bf863cc.pub sudo add-apt-repository "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/ /"

這邊講的都是 ubuntu 22.04

我要的版本是 20.04,可以去下面這個網址

https://developer.nvidia.com/cuda-11-8-0-download-archive

選擇 Linux -> x86_64 -> Ubuntu -> 20.04 -> deb(network)

他會列出 Installation Instructions 如下

wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-keyring_1.0-1_all.debsudo dpkg -i cuda-keyring_1.0-1_all.deb
sudo apt-get update
sudo apt-get -y install cuda

注意上面最後這句還有坑

# installing CUDA-11.8 sudo apt install cuda-11-8 -y

如果不指定版本的話他預設裝的版本一直安裝失敗

後來找到有人說其實可以指定 driver 版本

可以寫成下列的樣子

# installing CUDA-11.8 sudo apt install cuda-11-8 cuda-drivers=535.161.08-1

後面的步驟就沒有不同了

照著複製貼上即可成功安裝


2023年5月2日 星期二

Find all Chinese text in a string using Python and Regex

參考網址

https://stackoverflow.com/questions/2718196/find-all-chinese-text-in-a-string-using-python-and-regex


python的字串都是unicode

而全部中文的範圍在0x4e00 ~ 0x9fff之間

所以一個字串你想要取其中的中文可以這樣寫
def get_chinese(self, text):
    result = re.findall(r'[\u4e00-\u9fff]+', text)
    output = "".join(result)
    return output

補充
這一個字串你想寫入cp950編碼的檔案
但有一些字不符合該怎麼做?

with open("cp950.txt", mode="w", encoding="cp950") as f:
    f.write(text)

如果都不處理的話你會得到
UnicodeEncodeError: 'cp950' codec can't encode character '\uff6d' in position 98: illegal multibyte sequence


其實只要像下面這樣做就可以了
encode_text = text.encode("cp950", "ignore")
decode_text = encode_text.decode("cp950", "ignore")
with open("cp950.txt", mode="w", encoding="cp950") as f:
    f.write(decode_text)

2022年12月27日 星期二

How to Fix Apple Magic Mouse 2 scroll does not work on win10, 解決Apple Magic Mouse 2在win10上滾輪不能用

首先,我的 Magic Mouse 2 型號是A1657

如果你有上網搜尋的話

很多人會叫你裝Boot Camp

譬如下面這個連結

https://support.apple.com/kb/DL1836?locale=zh_TW

但我裝了之後發現還是沒用

仔細查之後才發現這裡面的MouseDriver版本是4.0.0.1

所以我們要想辦法拿更新的 Boot Camp 6.x

到這個頁面

https://github.com/timsutton/brigadier/releases

下載他的brigadier.exe

然後打開命令列,cd到這個exe的位置

輸入brigadier.exe -m MacBookPro14,1

然後他就會下載相對應的 Boot Camp

我在這裡面找到新的MouseDriver是6.0.6200

裝了就能用了

你也可以參考下面這個網址

https://www.youtube.com/watch?v=tV5nfQA_8Ec&ab_channel=FilipLiter%C3%A1k









2022年3月28日 星期一

github + sourcetree window10

記錄一下 github 搭配 sourcetree 常遇到的問題






 之前就搞了一次ssh因為某天開始就不支援傳統帳號密碼存取

沒想到最近又來一次

即使是ssh,RSA key也不支援

所以又要重弄一次








首先就去建立一個新的ssh key吧

如上圖,在 sourcetree 裡面就可以

打開後記得下面不能選RSA

如下圖這裡是選ECDSA










按下Generate之後稍微滑動一下滑鼠就可以建立key

Public key就自己找個記事本複製貼上存起來

(我選Save public key存起來的檔案反而不能給github用)

Private key的話他會建議你加個密碼然後選Save private key存起來

然後去github網頁,右上角個人圖示,再選設定









選New ssh key,然後把剛才public key複製貼上後save

再來到電腦右下角找到Pageant






點開後如下圖








點選Add key之後選擇剛才存檔的private key

如果你剛才有設定密碼的話他會要你輸入密碼

到這邊就算是完成了

再來去github網頁選擇你要clone的project






一開始還以為要用ssh那欄,結果要用https的url,sourcetree才會讓我抓

其實這一整套做完也真夠麻煩

好像可以直接用github desktop取代就好了

說不定是github想推他們自家的軟體


2022年3月27日 星期日

打包Container image

 1. 目錄結構


2. 新增Dockerfile

vi Dockerfile

按 i

新增以下內容

FROM centos:centos7.9.2009

COPY ctpn /appc/ctpn/

COPY debug /appc/debug

COPY models /appc/models

COPY yolo /appc/yolo

COPY type_recognizer /appc/

RUN yum -y install libxcb

WORKDIR /appc


3. 打包Image

docker build -t appm3 .

-t    tag,等於替image取個名字,

注意最後面還有一個    " . "  這不能少,應該是表示當前目錄的意思


4. 執行 

docker image ls

docker run -it appm3 bash


5. 在docker中執行httpd

docker run -d -it --privileged {Image ID} /usr/sbin/init

















2022年3月22日 星期二

如何複製資料到container裡面

1. 列出正在運行的container

docker ps

example

[root@DESKTOP-B31T57O dist]# docker ps

CONTAINER ID   IMAGE                   COMMAND   CREATED             STATUS             PORTS     NAMES

ddf6ad58f1ea   centos:centos7.9.2009   "bash"    About an hour ago   Up About an hour             kind_perlman

2.  查詢完整container id

docker inspect -f   '{{.Id}}'  SHORT_CONTAINER_ID-or-CONTAINER_NAME

example

[root@DESKTOP-B31T57O dist]# docker inspect -f   '{{.Id}}' kind_perlman

ddf6ad58f1eab9186e761afac45890bc2543e7a353d7cec3d323560b02d960a0

3. 從host copy 檔案到container

sudo cp path-file-host /var/lib/docker/aufs/mnt/FULL_CONTAINER_ID/PATH-NEW-FILE
example
docker cp type_recognizer e0746a7a15e56c9b906919c909d27644d4a7d900e1d8a12478e8c74bf064b89f:/type_recognizer
這樣會copy到container的根目錄下面
如果要copy到container的home下面
docker cp type_recognizer e0746a7a15e56c9b906919c909d27644d4a7d900e1d8a12478e8c74bf064b89f:/home/type_recognizer


4. 直接開一個互相連結的資料夾

docker volume create --name appa

而在host的位置是

/var/lib/docker/volumes/appa/_data/

在啟動時加一個 -v 參數,就可以指定 volume 要跟容器內哪一個資料夾連通

docker run -v appa:/appb -it centos:centos7.9.2009 bash

上面的appa表示在host時的名稱

而/appb表示在container裡面的資料夾路徑

也可以寫成/ox/appb,這樣在根目錄下就會有一個ox資料夾裡面放著appb資料夾

而appb資料夾裡面放的東西就會是在本機appa資料夾裡面的東西









2022年3月17日 星期四

CentOS 7.9 基本操作 Docker/Container

 

先切換到 root

1. 安裝 yum-utils

yum install -y yum-utils device-mapper-persistent-data lvm2


2. 設定 repository

yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo


3. 安裝 Docker CE

yum install docker-ce

出現error

打開 etc/yum.repos.d/docker-ce.repo

將 $releasever全部改7

例如

baseurl=https://download.docker.com/linux/centos/$releasever/source/stable

改成

baseurl=https://download.docker.com/linux/centos/7/source/stable

重新輸入

yum install docker-ce

檢查docker版本

docker version

4. 啟動 Docker

systemctl start docker

5. 測試 Docker

docker run hello-world

6. 設定開機自動啟動 Docker

systemctl enable docker

停止

systemctl stop docker

重啟

systemctl restart docker

狀態

systemctl status docker


7. 錯誤處理

重開機後遇到

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

解答

You can try out this: 

systemctl start docker

It worked fine for me.


P.S.: after if there is commands that you can't do without sudo, try this:

gpasswd -a $USER docker

8. 下載、執行Image

docker pull centos

上面那行會抓到centos 8
如果要指定版本7.9

docker pull centos:centos7.9.2009

列出 image list

docker image ls

執行

docker run -it centos:centos7.9.2009 bash

印出目前執行版本

cat /etc/*release










2021年4月30日 星期五

Qt creator 5.x cannot run compiler 'g++'

 一查果然如此,这个大病毒居然就是“Anaconda”。 为毛就QT有问题呢,因为QT要用cmd去调各种命令,然后去捕获返回值,这个“系统找不到指定路径”显然不是它能够预料的,所以出错了。因此,我们需要把这个劫持解除了:【解决方法】

打开注册表编辑器
找到HKEY_CURRENT_USER\Software\Microsoft\Command Processor
可以看到一个AutoRun的字段,字段的内容有Anaconda相关的路径,就是这个路径找不到
删除这个AutoRun字段,打开qt creator,Bingo。