Claude Code Installation Guide

1. System Requirements

ItemDetails
OSmacOS 10.15 or later / Ubuntu 20.04+ / Debian 10+ / Windows (WSL required)
HardwareMemory: 4GB or more
SoftwareNode.js 18 or higher
NetworkInternet connection required
ShellBash / Zsh / Fish recommended

2. For Windows Users (Installing WSL/Ubuntu)

  1. Install WSL (Windows Subsystem for Linux) and Ubuntu distribution: wsl --install After rebooting, check available distributions as needed: wsl -l -o
  2. If older versions of node/npm are present in the initial state, remove them: sudo apt remove nodejs npm

3. Installing Node.js (Recommended: nvm)

  1. Install nvm (Node Version Manager): curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
  2. source ~/.bashrc
  3. Install and use the Node.js LTS version: nvm install --lts
  4. nvm use --lts

4. Installing Claude Code

To install globally (recommended method):

npm install -g @anthropic-ai/claude-code

Note: It is not recommended to use sudo with the install command.
If you encounter permission errors, please refer to the “Configuration Guide” in the official documentation.

After installation, verify the version:

claude --version

5. Starting and Authenticating Claude Code (OAuth)

  1. Move to your project directory: cd <your-project-directory>
  2. Start Claude Code: claude
  3. On first launch, a selection screen for authentication method will appear.
    Select “2. Anthropic Console account”.
  4. Log into Console via the displayed link or screen in your browser to obtain an authentication code.
  5. Paste the authentication code into the terminal to complete registration.
    The settings will be saved and auto-authentication will occur from the next startup.

6. Manually Setting the API Key for CLI

Specifying via Environment Variable

export ANTHROPIC_API_KEY="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
claude

Persistent Configuration with settings.json

  1. If the .claude folder does not exist in your home directory, create it: mkdir -p ~/.claude
  2. Create or edit ~/.claude/settings.json as follows: { "env": { "ANTHROPIC_API_KEY": "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } }
  • After setting this, the claude command will automatically read your API Key.

7. Checking Configuration & Troubleshooting

  • To check installation and authentication status: claude doctor
  • If you encounter permission issues or npm permission errors, please refer to the “Troubleshooting” section in the official documentation.

8. Bedrock Integration Setup

Add the same three lines to your shell startup file.
vi ~/.bashrc
Then append:
export CLAUDE_CODE_USE_BEDROCK="1"

export AWS_REGION="ap-northeast-1"

export AWS_BEARER_TOKEN_BEDROCK=""


Reload:
source ~/.bashrc

use sonnet as model:
/model sonnet

9. How to Update

Automatic Updates (Enabled by Default)

Claude Code updates itself automatically.

To disable automatic updates:

claude config set autoUpdates false --global
# Or
export DISABLE_AUTOUPDATER=1

Manual Update

claude update

10. Frequently Asked Questions & Notes

  • Most errors during installation or startup are related to permission, Node.js version, or network settings.
  • Windows users must always operate in a WSL + Linux environment.
  • For the latest information, FAQ, and support, please consult the official documentation and the official Discord, etc.

EC2 定時自動開關機實踐


1. 技術方案與原理

  • 目標: EC2 定時自動開關機,徹底自動化省錢。
  • 主要組件:
    • Lambda(自動呼叫 EC2 API)
    • EventBridge Scheduler(定時觸發 Lambda)
    • 單個 IAM 角色即可(Lambda用),權限和信任設置到位。

2. Lambda function 編寫與部署

  1. 登錄 AWS Lambda 控制台。
  2. 點 Create function > Author from scratch。
  3. 命名(建議分「EC2AutoStop」&「EC2AutoStart」)。
  4. 選 Python 3.x。
  5. 貼入以下代碼:
import boto3

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name='ap-northeast-3')
    ec2.stop_instances(InstanceIds=['i-xxxxxxxxxxxxxxxxx'])
    return 'EC2 stopped'

(開機則改 .stop_instances → .start_instances)

  1. ⚠️ 每次修改都必須點「Deploy」!否則Lambda實際行為不會更新。
  2. 初次建好後用測試功能(Test)驗證能正確操作EC2並產生日誌。

3. Lambda執行角色設定(包含自定義policy/inline policy與信任關係)

步驟1.建立角色與 Action Policy、Inline Policy

  1. IAM > Roles > Create role
  2. Trusted entity 選 Lambda
  3. Attach Policy: AWSLambdaBasicExecutionRole,然後Attach 自定義托管 policy
    名稱建議:AmazonEC2StopStartInstances
  • 內容如下,用於賦予 Lambda 停啟 EC2 權限:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ec2:StartInstances",
                "ec2:StopInstances"
            ],
            "Resource": "*"
        }
    ]
}
  1. Attach 另一個 inline policy
    名稱建議:InvokeSpecificLambda
  • 內容如下,授權本角色可以調用特定 Lambda function(可根據需求擴展其它 function 的 ARN):
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "lambda:InvokeFunction",
            "Resource": [
                "arn:aws:lambda:ap-northeast-3:088xx0000000:function:EC2AutoStop",
                "arn:aws:lambda:ap-northeast-3:088xx0000000:function:EC2AutoStart"
            ]
        }
    ]
}

注意替換 ARN,與你環境中的 Lambda 名稱/region/account-id 一致。

步驟2.補充信任(Trust Relationships)政策

  1. IAM > Roles > 找到你 Lambda 執行用的角色。
  2. 點 “Trust relationships” 分頁,選 “Edit trust policy”
  3. 貼入如下 JSON,允許 Lambda 和 Scheduler 兩種方式 assume 這個角色:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "lambda.amazonaws.com",
          "scheduler.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

這裡加入 "scheduler.amazonaws.com",即可允許 EventBridge Scheduler 以這個角色調用 Lambda。

  1. 存檔,確認無誤。

4. EventBridge Scheduler 定時任務設置

  1. AWS Console > EventBridge > Schedules > Create schedule
  2. 務必與 Lambda 選同一 region
  3. 任務 Type 選「Invoke」→「AWS Lambda」。
  4. Lambda function 處選你剛剛部署的 function。
  5. Execution role 處,選 Lambda 上一步設好的執行角色(已信任並賦權)。
  6. 時間排程(cron)範例(JST 08:00 週一至週五):
   cron(0 23 ? * MON-FRI *)
  1. 完成儲存。

5. Lambda 配置最佳實踐(Timeout/Memory)

  • Timeout 設 30-60 秒(防止 Sandbox.Timedout)
  • Memory 推薦 256-512MB
  • 設置路徑:Lambda 控制台 > Configuration > General configuration > Edit
  • 設定完記得 Deploy

6. 問題診斷(CloudWatch 日誌&Scheduler Run History)

狀況核查方式與解決
Lambda test 成功但計劃不中斷檢查 Lambda 角色信任 policy 是否含 scheduler.amazonaws.com
定時沒觸發檢查 Scheduler Run history 與 Lambda CloudWatch Logs
超時Lambda Timeout 要夠長

7. 常見錯誤對應表 & 補充建議

情況對應解法
Lambda執行超時Timeout改30s↑
Scheduler無觸發LambdaLambda角色加 scheduler.amazonaws.com到trust policy
Lambda沒產生日誌執行一次自動產生log group
Lambda可Test計劃無效檢查角色信任關係和權限 policy
改了Lambda沒生效忘記點 Deploy,請務必 Deploy!
  • Action policy及信任完全在Lambda這唯一角色上設,管理簡單有效。
  • inline policy管理更易查維護,精細到臨時或特定EC2都行

How to Control Baloo File Indexer Resource Usage on KDE

If you’re using KDE on Linux with a large home directory, you might notice high disk IO, CPU usage, or unexpected swap activity. In many cases, Baloo File Indexer is the cause—especially during initial indexing. Here’s a quick guide to check, control, and optimize Baloo for a smooth KDE experience:


1. Check Baloo Status and Progress

balooctl status

Shows current state, total files indexed, and files pending for indexing.

Example output:

Indexer state: Indexing file content
Total files indexed: 178,275
Files waiting for content indexing: 355

2. Temporarily Disable Baloo

If you want to immediately stop resource consumption:

balooctl disable

To enable again:

balooctl enable

3. Exclude Unnecessary Folders from Indexing

Recommended! Only index what you really need:

  • Go to System Settings → Search → File Search
    Add folders you wish to exclude (e.g., Downloads, big backup folders, development projects).

Or edit (advanced):

nano ~/.config/baloofilerc

Add lines like:

[General]
excludeFolders[$e]=/home/youruser/Downloads /home/youruser/projects /home/youruser/big_backup

Restart Baloo for changes to take effect:

balooctl disable
balooctl enable

4. Monitor Disk Usage by Baloo

Get the actual index size:

du -sh ~/.local/share/baloo

Several GB is typical with 100k+ files. If it’s too much, use exclusion above.


5. Key Points

  • Initial indexing: Heavy IO/CPU, will finish after the first complete pass.
  • Post-indexing: Resource usage drops dramatically, only new/modified files are scanned.
  • Disabling: Safe, and can be toggled anytime. Your files remain untouched.
  • Rebooting during indexing: Safe, progress resumes automatically.
  • Clean up everything (if needed):
    balooctl purge balooctl enable

System Setup Guide for Remote Local File Manipulation Using Flask and MCP Server

Overview

This project aims to build and validate a remote API service enabling local filesystem operations by integrating MCP Server and Flask. The main functionalities include:

  • Remote execution of operations such as directory listing, file creation, file deletion, and file modification.
  • Providing an HTTP API interface with Flask, powered by MCP Server.

Setup Instructions

1. Install Required Packages

Node.js and MCP Server

MCP Server requires Node.js. Follow these steps to install:

  1. Install the latest LTS version of Node.js from Node.js Official Website.
  2. Install MCP Server globally:
   npm install -g @modelcontextprotocol/server-filesystem

Python and Flask

To build the remote API server with Flask, you’ll need the Python environment:

  1. Download and install Python from Python Official Website.
  2. Install the required libraries:
   pip install flask flask-cors

2. Project Directory Structure

Create the files and directories according to the following structure:

C:\dev\mcp\
│
├── server-filesystem.cmd
├── bridge.js
└── flask_api.py

Code Details

server-filesystem.cmd

A script for launching MCP Server to enable remote filesystem operations:

@echo off
npx -y @modelcontextprotocol/server-filesystem C:\dev\mcp\test

bridge.js

A Node.js script to execute and test MCP Server behaviors (CRUD operations):

const { spawn } = require("child_process");

// 调用 server-filesystem.cmd 启动 MCP Server
const mcpServer = spawn("cmd.exe", ["/c", "C:\\dev\\mcp\\server-filesystem\\server-filesystem.cmd"], {
    env: process.env, // 继承当前环境变量
    shell: true       // 必须启用 shell 模式以运行 .cmd 文件
});

// 监听标准输出,打印 MCP 服务输出日志
mcpServer.stdout.on("data", (data) => {
    console.log(`MCP Server Output: ${data}`);
});

// 监听标准错误(已分类处理)
// 将已知的启动信息归类为 "MCP Server Info",其他则作为真正的错误
mcpServer.stderr.on("data", (data) => {
    const message = data.toString();
    if (message.includes("Secure MCP Filesystem Server")) {
        console.log(`MCP Server Info: ${message}`);
    } else if (message.includes("Allowed directories")) {
        console.log(`MCP Server Info: ${message}`);
    } else {
        console.error(`MCP Server Error: ${message}`);
    }
});

// 捕获 MCP 服务关闭事件
mcpServer.on("close", (code) => {
    console.log(`MCP Server exited with code ${code}`);
});

// === 新增功能:测试 MCP Server 的功能 ===
// 延迟执行功能以确保 MCP Server 已启动完成
setTimeout(() => {
    // 测试 1:列出目录内容
    console.log("Running Directory List Test...");
    const listTest = spawn("cmd.exe", ["/c", "dir C:\\dev\\mcp\\test"], {
        env: process.env,
        shell: true,
    });

    listTest.stdout.on("data", (data) => {
        console.log(`Directory List Output: ${data}`);
    });

    listTest.stderr.on("data", (data) => {
        console.error(`Directory List Error: ${data}`);
    });

    listTest.on("close", () => {
        console.log("Directory List Test Finished.");
    });
}, 3000); // 延迟 3 秒进行目录列表测试

setTimeout(() => {
    // 测试 2:创建新文件
    console.log("Running File Creation Test...");
    const writeTest = spawn("cmd.exe", ["/c", "echo Hello, MCP Server! > C:\\dev\\mcp\\test\\test-write.txt"], {
        env: process.env,
        shell: true,
    });

    writeTest.stdout.on("data", (data) => {
        console.log(`File Creation Output: ${data}`);
    });

    writeTest.stderr.on("data", (data) => {
        console.error(`File Creation Error: ${data}`);
    });

    writeTest.on("close", () => {
        console.log("File Creation Test Finished. Please check the file in 'C:\\dev\\mcp\\test'.");
    });
}, 7000); // 延迟 7 秒执行文件创建测试

// 测试 4:删除刚创建的文件
setTimeout(() => {
    console.log("Running File Deletion Test...");
    const deleteTest = spawn("cmd.exe", ["/c", "del C:\\dev\\mcp\\test\\test-write.txt"], {
        env: process.env,
        shell: true,
    });

    deleteTest.stdout.on("data", (data) => {
        console.log(`File Deletion Output: ${data}`);
    });

    deleteTest.stderr.on("data", (data) => {
        console.error(`File Deletion Error: ${data}`);
    });

    deleteTest.on("close", () => {
        console.log("File Deletion Test Finished. Please check if the file is removed from 'C:\\dev\\mcp\\test'.");
    });
}, 15000); // 延迟 15 秒测试文件删除

flask_api.py

A Flask API server that provides CRUD operations through HTTP requests:

from flask import Flask, request, jsonify, make_response
from flask_cors import CORS
import subprocess
import json  # Use json module for building responses manually

# Initialize Flask app
app = Flask(__name__)

# Enable Cross-Origin Resource Sharing (CORS)
CORS(app)

# Ensure Flask does not escape non-ASCII characters in responses
app.config['JSON_AS_ASCII'] = False


# Utility function: Construct JSON response with UTF-8 encoding
def json_response(data, status=200):
    response = make_response(json.dumps(data, ensure_ascii=False), status)
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    return response


# Route: List directory contents
@app.route('/list-files', methods=['GET'])
def list_files():
    # Fetch 'dir' parameter from the GET request
    directory = request.args.get('dir')
    if not directory:
        return json_response({"error": "Missing 'dir' parameter"}, 400)

    try:
        # Use subprocess to run the Windows 'dir' command
        result = subprocess.run(
            ["cmd.exe", "/c", f"dir {directory}"],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
        )
        # If the command failed, return the error
        if result.returncode != 0:
            return json_response({"error": result.stderr.strip()}, 500)
        # Return the directory listing as the response
        return json_response({"output": result.stdout.strip()})
    except Exception as e:
        # Catch any unexpected exceptions
        return json_response({"error": str(e)}, 500)


# Route: Create a file with content
@app.route('/create-file', methods=['POST'])
def create_file():
    # Parse the file_path and content from the POST request
    data = request.get_json()
    file_path = data.get('file_path')
    content = data.get('content', '')

    if not file_path:
        return json_response({"error": "Missing 'file_path' parameter"}, 400)

    try:
        # Use subprocess to run the Windows 'echo' command to write to a file
        result = subprocess.run(
            ["cmd.exe", "/c", f"echo {content} > {file_path}"],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
        )
        # If the command failed, return the error
        if result.returncode != 0:
            return json_response({"error": result.stderr.strip()}, 500)
        # Return success message
        return json_response({"message": f"File '{file_path}' created successfully"})
    except Exception as e:
        # Catch any unexpected exceptions
        return json_response({"error": str(e)}, 500)


# Route: Delete a specific file
@app.route('/delete-file', methods=['DELETE'])
def delete_file():
    # Parse the file_path from the DELETE request
    data = request.get_json()
    file_path = data.get('file_path')

    if not file_path:
        return json_response({"error": "Missing 'file_path' parameter"}, 400)

    try:
        # Use subprocess to run the Windows 'del' command to delete the file
        result = subprocess.run(
            ["cmd.exe", "/c", f"del {file_path}"],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
        )
        # If the command failed, return the error
        if result.returncode != 0:
            return json_response({"error": result.stderr.strip()}, 500)
        # Return success message
        return json_response({"message": f"File '{file_path}' deleted successfully"})
    except Exception as e:
        # Catch any unexpected exceptions
        return json_response({"error": str(e)}, 500)


# Route: Read contents of a specific file
@app.route('/read-file', methods=['GET'])
def read_file():
    # Fetch 'file_path' parameter from the GET request
    file_path = request.args.get('file_path')
    if not file_path:
        return json_response({"error": "Missing 'file_path' parameter"}, 400)

    try:
        # Open the file in 'read' mode with UTF-8 encoding
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
        # Return the file content in the response
        return json_response({"file_path": file_path, "content": content})
    except FileNotFoundError:
        # Return 404 if the file does not exist
        return json_response({"error": f"File '{file_path}' not found."}, 404)
    except Exception as e:
        # Catch any unexpected exceptions
        return json_response({"error": str(e)}, 500)


# Run the Flask app on all available IPs (0.0.0.0) at port 5000
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

Important Notes

  1. Path Formatting:
  • Ensure file paths sent to the Flask API use double backslashes (e.g., C:\\path\\to\\file).
  1. Security:
  • Add additional security layers (e.g., API Keys or access control) as file operations can pose risks.
  1. Production Deployment:
  • Flask’s development server is not suitable for production. Use Gunicorn or uWSGI for deployment.

Using bridge.js (Node.js Script)

To test and interact with the MCP server for file operations, run:

node bridge.js
  • Starts the MCP server.
  • Performs directory listing, file creation, and file deletion tests, with results outputted in the console.

Starting Flask API (flask_api.py)

To host the API server:

  1. Navigate to the project directory.
  2. Run the script:
   python flask_api.py
  1. API will be available at http://0.0.0.0:5000 for HTTP operations.

Testing Results

  1. Sample curl Commands (for Ubuntu):
# check folder
curl "http://yourTargetIP:yourTargetPort/list-files?dir=C:\\dev\\mcp\\test"
 
# create file
curl -X POST -H "Content-Type: application/json" \
-d '{"file_path": "C:\\dev\\mcp\\test\\test.txt", "content": "Created via Flask API"}' \
"http://yourTargetIP:yourTargetPort/create-file"

# read file
curl "http://yourTargetIP:yourTargetPort/read-file?file_path=C:\\dev\\mcp\\test\\test.txt"

# delete file
curl -X DELETE -H "Content-Type: application/json" \
-d '{"file_path": "C:\\dev\\mcp\\test\\test.txt"}' \
"http://yourTargetIP:yourTargetPort/delete-file"


Future Enhancements

  • Enable file upload and download functionality.
  • Introduce authentication mechanisms to RESTful APIs.
  • Add batch operations and file movement capabilities.

Setting Up Qt Development Environment on Ubuntu

---

**Update Your Package List:**  
`sudo apt update -y`  

---

**Install Qt Creator (Qt Integrated Development Environment):**  
`sudo apt install qtcreator -y`  

---

**Install Qt 5 Development Libraries and Tools:**  
Install `qtbase5-dev` and related toolkits, which provide core development files for Qt 5:  
`sudo apt install qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools -y`  

---

**For a Complete Qt Development Environment (with GUI support):**  
You can additionally install:  
`sudo apt install qtdeclarative5-dev qttools5-dev-tools -y`  

---

**Verify Installation and Check Tool Versions:**  
Ensure `qmake` is installed and available:  
`qmake --version`  

Expected output should resemble:  

QMake version 3.x
Using Qt version 5.x in /usr/lib/x86_64-linux-gnu

---

**Test the Installation:**  
Launch the Qt Creator development tool:  
`qtcreator`  

Resize the swap partition to free space and reassign it to the root partition

1.Insert and boot your Ubuntu Live CD/USB

2.Mount the root partition (assuming nvme0n1p2 is your root partition):

sudo mkdir /mnt/root
sudo mount /dev/nvme0n1p2 /mnt/root

3.Edit the /etc/fstab file within the root partition:

sudo vi /mnt/root/etc/fstab

4.Comment out or delete the swap entry, then save it. e.g.:

# UUID=yourUUID none swap sw 0 0

5.Start GParted:

sudo gparted

6.Shrink swap partition nvme0n1p3:

Right-click nvme0n1p3 swap partition, choose Resize/Move.

Adjust it to the desired size (e.g., 16GB).

Click Resize/Move.

7.Expand root partition nvme0n1p2(Note: Resize operations are possible only on contiguous space.):

Right-click nvme0n1p2 root partition, choose Resize/Move.

Drag the right slider to use the space freed from the swap partition.

Click Resize/Move.

8.Mount the root partition again:

sudo mount /dev/nvme0n1p2 /mnt/root

Edit the /etc/fstab file within the root partition:

sudo vi /mnt/root/etc/fstab

modify the existing swap entry with the new UUID

9.Reboot to your normal system, not the Live CD/USB.

10.Enable the new swap partition:

sudo swapon -a

11.Check if the new swap partition is active:

sudo swapon --show

Confirm root and swap partition sizes:

df -hT

Solution for VS Code and KWallet Integration Issues on Ubuntu

“You’re running in a KDE environment but the OS keyring is not available for encryption. Ensure you have kwallet running.”, follow these steps to configure VS Code to use gnome-libsecret instead of KWallet:

1. Create Configuration File:

touch ~/.config/Code/User/argv.json

then write the content:

{
  "password-store": "gnome-libsecret"
}

2. Install Prerequisites:

Install gnome-keyring by running:

sudo apt install gnome-keyring -y

3. Launch VS Code with gnome-libsecret:

code --password-store="gnome-libsecret"

Using UFW Firewall with Docker Containers

Running Docker containers with UFW firewall setup can be challenging because Docker manipulates iptables rules by default. However, with some configuration, you can ensure both Docker and UFW work well together. Below is a step-by-step guide to configure Docker to not interfere with iptables and manually set up UFW rules.

1. Configure Docker Daemon, make “iptables”: false

sudo vi /etc/docker/daemon.json

should like below:

{
    "runtimes": {
        "nvidia": {
            "path": "nvidia-container-runtime",
            "runtimeArgs": []
        }
    },
    "iptables": false
}

2. Restart Docker

sudo systemctl restart docker

3. Modify UFW Forward Policy

sudo sed -i -e 's/DEFAULT_FORWARD_POLICY="DROP"/DEFAULT_FORWARD_POLICY="ACCEPT"/g' /etc/default/ufw

4. Reload UFW to apply the changes:

sudo ufw reload

Reference:

How to Install CUDA12.5 on Ubuntu 22.04.4 LTS

1. Download and Install CUDA Keyring:

wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-keyring_1.1-1_all.deb
sudo dpkg -i cuda-keyring_1.1-1_all.deb

2. Update system and Install CUDA Toolkit:

sudo apt-get update -y
sudo apt-get install cuda-toolkit -y

3. Reboot:

sudo sync; sudo /sbin/shutdown -r now

4. Configure Environment Variables:

Add the following lines to the end of your ~/.bashrc file to set the environment variables:

export PATH=/usr/local/cuda/bin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/usr/local/cuda-12.5/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}

then:

source ~/.bashrc

5. Verify the Installation

nvcc -V

You should see an output similar to:

nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2024 NVIDIA Corporation
Built on Thu_Jun__6_02:18:23_PDT_2024
Cuda compilation tools, release 12.5, V12.5.82
Build cuda_12.5.r12.5/compiler.34385749_0

Additional Notes:

Persistence Daemon: If you want to enable the NVIDIA Persistence Daemon for better GPU management, you can start it as root:

/usr/bin/nvidia-persistenced --verbose

Deploy GPU-accelerated applications in containers:

sudo apt-get install -y nvidia-docker2

Then test:

sudo docker run --rm --gpus all nvidia/cuda:12.5.0-base-ubuntu22.04 nvidia-smi

Install nvidia driver:

sudo apt-get install nvidia-driver-555

Then, test:

nvidia-smi

reference:

CUDA Toolkit 12.5 Update 1 Downloads

Installing the NVIDIA Container Toolkit

NVIDIA CUDA Installation Guide for Linux

How to Install CUDA on Ubuntu 22.04 | Step-by-Step

NVIDIA Driver Downloads

Optimizing Video Compression with ffmpeg and hevc_nvenc

ffmpeg -i fileName.mp4 -c:v hevc_nvenc -preset slow -rc:v vbr -cq:v 24 -b:v 0 -c:a aac -b:a 128k -vf scale=1280:-1 -movflags +faststart fileName_compressed.mp4
FlagExplanation
-i fileName.mp4Specifies the input file as fileName.mp4
-c:v hevc_nvencSets the video codec to NVIDIA’s HEVC encoder
-preset slowSets the encoding preset to “slow” for better compression efficiency
-rc:v vbrSets the rate control mode to variable bitrate
-cq:v 24Sets the Constant Quality (CQ) value to 24 (lower values mean higher quality)
-b:v 0Sets the target bitrate to 0, allowing CQ mode to determine the bitrate
-c:a aacSets the audio codec to AAC
-b:a 128kSets the audio bitrate to 128 kbps
-vf scale=1280:-1Scales the video width to 1280 pixels, height scaled proportionally
-movflags +faststartOptimizes the file for web streaming, allowing faster video startup
fileName_compressed.mp4Specifies the output filename
This command utilizes your NVIDIA GPU for encoding, which can be significantly faster than CPU encoding. The quality control is managed through the CQ (Constant Quality) value, where lower values result in higher quality but larger file sizes.

smaller:

ffmpeg -i 1.mp4 -c:v hevc_nvenc -preset slow -rc:v vbr -cq:v 29 -b:v 450k -c:a aac -b:a 96k -vf scale=960:-1 -movflags +faststart 2.mp4
在 WordPress.com 上免费创建您自己的网站。创建您自己的网站。
免费开始