Featured image of post 代码测试

代码测试

浏览量: ...

代码高亮测试

代码高亮渲染测试

md渲染测试

表格测试

序号名称价格数量
1苹果$2.005
2香蕉$1.5010
3樱桃$3.0020

分割线


删除线

这是一个删除线的测试。

引用测试

这是一个引用块的测试。

它可以包含多行文本。

任务列表

  • sss*

kbd, sub, sup, mark, abbr

GIF is a bitmap image format.

H2O

Xn + Yn = Zn

Press CTRL + ALT + Delete to end the session.

Most salamanders are nocturnal, and hunt for insects, worms, and other small creatures.

Hyperlinked image

行内代码

示例图片 Here is an example of inline code within a sentence.

Python 语言测试

基础语法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def fibonacci(n: int) -> int:
    """计算第n个斐波那契数"""
    if n <= 1:
        return n
    a, b = 0, 1
    for _ in range(2, n + 1):
        a, b = b, a + b
    return b

# 使用示例
print(f"斐波那契数列前10项: {[fibonacci(i) for i in range(10)]}")

类与装饰器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from typing import List, Optional
from dataclasses import dataclass
from functools import wraps

@dataclass
class User:
    """用户数据类"""
    name: str
    age: int
    email: Optional[str] = None
    
    def greet(self) -> str:
        return f"Hello, {self.name}! You are {self.age} years old."

def log_function_call(func):
    """日志装饰器"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

class DataProcessor:
    def __init__(self, data: List[int]):
        self.data = data
    
    @log_function_call
    def process_data(self, multiplier: int = 1) -> List[int]:
        """处理数据"""
        return [x * multiplier for x in self.data if x > 0]

异步编程

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import asyncio
import aiohttp
from concurrent.futures import ThreadPoolExecutor

async def fetch_url(session: aiohttp.ClientSession, url: str) -> str:
    """异步获取URL内容"""
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = [
        "https://api.example.com/data1",
        "https://api.example.com/data2",
        "https://api.example.com/data3"
    ]
    
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_url(session, url) for url in urls]
        results = await asyncio.gather(*tasks, return_exceptions=True)
        
        for url, result in zip(urls, results):
            if isinstance(result, Exception):
                print(f"Error fetching {url}: {result}")
            else:
                print(f"Fetched {url}: {len(result)} characters")

# 运行异步主函数
if __name__ == "__main__":
    asyncio.run(main())

JavaScript/TypeScript 测试

基础JavaScript

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// ES6+ 特性示例
const fibonacci = (n) => {
    if (n <= 1) return n;
    let [a, b] = [0, 1];
    for (let i = 2; i <= n; i++) {
        [a, b] = [b, a + b];
    }
    return b;
};

// 使用解构和模板字符串
const user = {
    name: "Alice",
    age: 30,
    email: "alice@example.com"
};

const { name, ...rest } = user;
console.log(`User ${name} details:`, rest);

// Promise 和 async/await
async function fetchData(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        return data;
    } catch (error) {
        console.error("Failed to fetch data:", error);
        throw error;
    }
}

TypeScript

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
interface User {
    name: string;
    age: number;
    email?: string;
}

type UserRole = "admin" | "user" | "guest";

class UserService {
    private users: Map<string, User> = new Map();
    
    constructor(initialUsers: User[] = []) {
        initialUsers.forEach(user => {
            this.users.set(user.email || user.name, user);
        });
    }
    
    addUser(user: User): boolean {
        const key = user.email || user.name;
        if (this.users.has(key)) {
            return false;
        }
        this.users.set(key, user);
        return true;
    }
    
    getUserByEmail(email: string): User | undefined {
        return this.users.get(email);
    }
    
    getUsersByAge(minAge: number, maxAge?: number): User[] {
        return Array.from(this.users.values()).filter(user => {
            if (maxAge !== undefined) {
                return user.age >= minAge && user.age <= maxAge;
            }
            return user.age >= minAge;
        });
    }
}

// 泛型示例
class Repository<T> {
    private items: T[] = [];
    
    add(item: T): void {
        this.items.push(item);
    }
    
    find(predicate: (item: T) => boolean): T | undefined {
        return this.items.find(predicate);
    }
    
    getAll(): T[] {
        return [...this.items];
    }
}

Java 测试

基础Java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.List;
import java.util.ArrayList;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
        
        List<Integer> numbers = List.of(1, 2, 3, 4, 5);
        int sum = numbers.stream()
                        .mapToInt(Integer::intValue)
                        .sum();
        System.out.println("Sum: " + sum);
    }
}

class User {
    private String name;
    private int age;
    private String email;
    
    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }
    
    // Getters and setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
    
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    
    @Override
    public String toString() {
        return String.format("User{name='%s', age=%d, email='%s'}", 
                            name, age, email);
    }
}

Spring Boot 示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@SpringBootApplication
@RestController
@RequestMapping("/api")
public class DemoApplication {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/users")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
    
    @PostMapping("/users")
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }
    
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@Service
class UserService {
    private final Map<Long, User> users = new HashMap<>();
    private long nextId = 1;
    
    public List<User> getAllUsers() {
        return new ArrayList<>(users.values());
    }
    
    public User createUser(User user) {
        user.setId(nextId++);
        users.put(user.getId(), user);
        return user;
    }
}

class User {
    private Long id;
    private String name;
    private String email;
    
    // 构造函数、getter、setter省略
}

C++ 测试

基础C++

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>

using namespace std;

// 模板函数示例
template<typename T>
T maxElement(const vector<T>& vec) {
    if (vec.empty()) {
        throw runtime_error("Vector is empty");
    }
    return *max_element(vec.begin(), vec.end());
}

// 类定义
class Rectangle {
private:
    double width;
    double height;
    
public:
    Rectangle(double w, double h) : width(w), height(h) {}
    
    double area() const {
        return width * height;
    }
    
    double perimeter() const {
        return 2 * (width + height);
    }
    
    // 友元函数
    friend ostream& operator<<(ostream& os, const Rectangle& rect);
};

// 运算符重载
ostream& operator<<(ostream& os, const Rectangle& rect) {
    os << "Rectangle(width=" << rect.width 
       << ", height=" << rect.height << ")";
    return os;
}

// 智能指针示例
unique_ptr<Rectangle> createRectangle(double w, double h) {
    return make_unique<Rectangle>(w, h);
}

int main() {
    vector<int> numbers = {1, 5, 3, 8, 2};
    cout << "Max element: " << maxElement(numbers) << endl;
    
    Rectangle rect(5.0, 3.0);
    cout << rect << ", Area: " << rect.area() << endl;
    
    auto rectPtr = createRectangle(4.0, 6.0);
    cout << "Created rectangle: " << *rectPtr << endl;
    
    return 0;
}

现代C++特性

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <vector>
#include <string>
#include <functional>
#include <type_traits>

// 概念(C++20)
template<typename T>
concept Arithmetic = std::is_arithmetic_v<T>;

// 可变参数模板
template<Arithmetic... Args>
auto sum(Args... args) {
    return (args + ...);  // 折叠表达式
}

// Lambda表达式
auto createMultiplier(double factor) {
    return [factor](auto value) { return value * factor; };
}

// 结构化绑定(C++17)
std::tuple<std::string, int, double> getPerson() {
    return {"Alice", 30, 65.5};
}

int main() {
    // 自动类型推导
    auto result = sum(1, 2.5, 3, 4.7);
    std::cout << "Sum: " << result << std::endl;
    
    auto multiplier = createMultiplier(2.5);
    std::cout << "10 * 2.5 = " << multiplier(10) << std::endl;
    
    // 结构化绑定
    auto [name, age, weight] = getPerson();
    std::cout << name << " is " << age << " years old" << std::endl;
    
    // 范围for循环
    std::vector<int> vec = {1, 2, 3, 4, 5};
    for (const auto& num : vec) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

HTML/CSS 测试

HTML

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>示例页面</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header class="main-header">
        <nav class="navbar">
            <div class="logo">MySite</div>
            <ul class="nav-links">
                <li><a href="#home">首页</a></li>
                <li><a href="#about">关于</a></li>
                <li><a href="#services">服务</a></li>
                <li><a href="#contact">联系</a></li>
            </ul>
        </nav>
    </header>
    
    <main class="container">
        <section id="hero">
            <h1>欢迎来到我的网站</h1>
            <p>这是一个响应式设计的示例页面</p>
            <button class="cta-button">了解更多</button>
        </section>
        
        <section id="features">
            <article class="feature-card">
                <h3>特性一</h3>
                <p>描述特性一的功能和优势</p>
            </article>
            <article class="feature-card">
                <h3>特性二</h3>
                <p>描述特性二的功能和优势</p>
            </article>
            <article class="feature-card">
                <h3>特性三</h3>
                <p>描述特性三的功能和优势</p>
            </article>
        </section>
    </main>
    
    <footer>
        <p>&copy; 2023 我的网站. 保留所有权利.</p>
    </footer>
    
    <script src="app.js"></script>
</body>
</html>

CSS

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
/* 全局样式 */
:root {
    --primary-color: #3498db;
    --secondary-color: #2ecc71;
    --text-color: #333;
    --bg-color: #f9f9f9;
    --font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: var(--font-family);
    color: var(--text-color);
    background-color: var(--bg-color);
    line-height: 1.6;
}

/* 响应式设计 */
.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
}

/* Flexbox布局 */
.navbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 0;
}

.nav-links {
    display: flex;
    list-style: none;
    gap: 2rem;
}

.nav-links a {
    text-decoration: none;
    color: var(--text-color);
    font-weight: 500;
    transition: color 0.3s ease;
}

.nav-links a:hover {
    color: var(--primary-color);
}

/* Grid布局 */
#features {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 2rem;
    margin: 3rem 0;
}

.feature-card {
    background: white;
    padding: 2rem;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s ease;
}

.feature-card:hover {
    transform: translateY(-5px);
}

/* 媒体查询 */
@media (max-width: 768px) {
    .navbar {
        flex-direction: column;
        gap: 1rem;
    }
    
    .nav-links {
        flex-direction: column;
        text-align: center;
        gap: 1rem;
    }
    
    #features {
        grid-template-columns: 1fr;
    }
}

/* CSS Grid 示例 */
.grid-container {
    display: grid;
    grid-template-areas:
        "header header header"
        "sidebar main main"
        "footer footer footer";
    grid-template-columns: 1fr 2fr 2fr;
    grid-template-rows: auto 1fr auto;
    gap: 1rem;
    min-height: 100vh;
}

.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }

SQL 测试

基础SQL

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
-- 创建表
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) NOT NULL UNIQUE,
    email VARCHAR(100) NOT NULL UNIQUE,
    age INT CHECK (age >= 0),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT TRUE
);

CREATE TABLE orders (
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT NOT NULL,
    amount DECIMAL(10, 2) NOT NULL,
    status ENUM('pending', 'processing', 'shipped', 'delivered') DEFAULT 'pending',
    order_date DATE NOT NULL,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

-- 插入数据
INSERT INTO users (username, email, age) VALUES
('alice', 'alice@example.com', 30),
('bob', 'bob@example.com', 25),
('charlie', 'charlie@example.com', 35);

INSERT INTO orders (user_id, amount, status, order_date) VALUES
(1, 99.99, 'delivered', '2023-10-01'),
(1, 49.99, 'processing', '2023-10-15'),
(2, 149.99, 'shipped', '2023-10-10');

复杂查询

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
-- 窗口函数示例
SELECT 
    u.username,
    o.order_date,
    o.amount,
    SUM(o.amount) OVER (PARTITION BY u.id ORDER BY o.order_date) AS running_total,
    AVG(o.amount) OVER (PARTITION BY u.id) AS avg_order_amount,
    ROW_NUMBER() OVER (PARTITION BY u.id ORDER BY o.order_date DESC) AS order_rank
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.is_active = TRUE
ORDER BY u.username, o.order_date;

-- CTE (公共表表达式) 示例
WITH user_stats AS (
    SELECT 
        user_id,
        COUNT(*) AS total_orders,
        SUM(amount) AS total_spent,
        AVG(amount) AS avg_order_value,
        MAX(order_date) AS last_order_date
    FROM orders
    GROUP BY user_id
),
active_users AS (
    SELECT u.*, us.total_orders, us.total_spent
    FROM users u
    JOIN user_stats us ON u.id = us.user_id
    WHERE u.is_active = TRUE
        AND us.total_orders >= 1
        AND us.last_order_date >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY)
)
SELECT 
    au.username,
    au.email,
    au.total_orders,
    au.total_spent,
    CASE 
        WHEN au.total_spent >= 1000 THEN 'VIP'
        WHEN au.total_spent >= 500 THEN 'Premium'
        ELSE 'Standard'
    END AS customer_tier
FROM active_users au
ORDER BY au.total_spent DESC;

-- 索引创建
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_orders_user_date ON orders(user_id, order_date DESC);
CREATE FULLTEXT INDEX idx_users_username ON users(username);

Bash/Shell 测试

基础Shell脚本

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#!/bin/bash

# 脚本配置
SCRIPT_NAME="$(basename "$0")"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_FILE="${SCRIPT_DIR}/script.log"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $*" | tee -a "$LOG_FILE"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $*" | tee -a "$LOG_FILE" >&2
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $*" | tee -a "$LOG_FILE"
}

# 参数处理
usage() {
    echo "Usage: $SCRIPT_NAME [OPTIONS]"
    echo "Options:"
    echo "  -h, --help     显示帮助信息"
    echo "  -v, --verbose  详细输出"
    echo "  -f FILE        指定配置文件"
    exit 1
}

# 检查命令是否存在
check_dependencies() {
    local dependencies=("curl" "jq" "git")
    local missing=()
    
    for cmd in "${dependencies[@]}"; do
        if ! command -v "$cmd" &> /dev/null; then
            missing+=("$cmd")
        fi
    done
    
    if [ ${#missing[@]} -gt 0 ]; then
        log_error "缺少依赖: ${missing[*]}"
        return 1
    fi
    return 0
}

# 主函数
main() {
    local verbose=false
    local config_file=""
    
    # 解析参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                usage
                ;;
            -v|--verbose)
                verbose=true
                ;;
            -f)
                config_file="$2"
                shift
                ;;
            *)
                log_error "未知选项: $1"
                usage
                ;;
        esac
        shift
    done
    
    # 检查依赖
    if ! check_dependencies; then
        exit 1
    fi
    
    log_info "开始执行脚本..."
    
    # 示例:处理文件
    process_files() {
        local dir="${1:-.}"
        local count=0
        
        while IFS= read -r -d '' file; do
            if [ "$verbose" = true ]; then
                log_info "处理文件: $file"
            fi
            
            # 这里添加实际的文件处理逻辑
            ((count++))
        done < <(find "$dir" -name "*.txt" -type f -print0)
        
        echo "共处理 $count 个文件"
    }
    
    process_files "/path/to/files"
    
    log_success "脚本执行完成"
}

# 异常处理
trap 'log_error "脚本被中断"; exit 1' INT TERM

# 运行主函数
main "$@"

高级Shell脚本

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#!/usr/bin/env bash

set -euo pipefail  # 严格模式

# 高级配置
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly CONFIG_DIR="${HOME}/.config/myscript"
readonly LOCK_FILE="/tmp/$(basename "$0").lock"

# 加载配置
load_config() {
    local config_file="${CONFIG_DIR}/config.conf"
    
    if [[ -f "$config_file" ]]; then
        # 安全地加载配置文件
        source "$config_file"
    else
        # 默认配置
        declare -gA CONFIG=(
            ["api_url"]="https://api.example.com"
            ["timeout"]=30
            ["retry_count"]=3
            ["log_level"]="INFO"
        )
    fi
}

# 锁机制
acquire_lock() {
    if [[ -f "$LOCK_FILE" ]]; then
        local pid
        pid=$(cat "$LOCK_FILE")
        if kill -0 "$pid" 2>/dev/null; then
            echo "脚本已经在运行 (PID: $pid)" >&2
            exit 1
        fi
    fi
    echo $$ > "$LOCK_FILE"
}

release_lock() {
    rm -f "$LOCK_FILE"
}

# 并发处理
parallel_process() {
    local max_workers="${1:-4}"
    local -a pids=()
    
    process_item() {
        local item="$1"
        # 模拟耗时操作
        sleep $((RANDOM % 3 + 1))
        echo "处理完成: $item"
    }
    
    # 创建作业数组
    local items=()
    for i in {1..10}; do
        items+=("item_$i")
    done
    
    # 并行处理
    for item in "${items[@]}"; do
        process_item "$item" &
        pids+=($!)
        
        # 控制并发数
        while [[ ${#pids[@]} -ge max_workers ]]; do
            for pid_idx in "${!pids[@]}"; do
                if ! kill -0 "${pids[$pid_idx]}" 2>/dev/null; then
                    unset "pids[$pid_idx]"
                fi
            done
            pids=("${pids[@]}")  # 重新索引数组
            sleep 0.1
        done
    done
    
    # 等待所有作业完成
    wait
}

# 网络请求
make_api_request() {
    local endpoint="$1"
    local data="${2:-}"
    local retry_count="${CONFIG[retry_count]:-3}"
    
    for ((i=1; i<=retry_count; i++)); do
        if response=$(curl -sS \
            --max-time "${CONFIG[timeout]:-30}" \
            -H "Content-Type: application/json" \
            -H "Authorization: Bearer ${API_TOKEN:-}" \
            -X POST \
            -d "$data" \
            "${CONFIG[api_url]}/$endpoint" 2>&1); then
            
            echo "$response"
            return 0
        else
            echo "请求失败 (尝试 $i/$retry_count): $response" >&2
            if [[ $i -lt retry_count ]]; then
                sleep $((2 ** (i-1)))  # 指数退避
            fi
        fi
    done
    
    echo "所有重试失败" >&2
    return 1
}

# 主程序
main() {
    acquire_lock
    trap release_lock EXIT
    
    load_config
    
    echo "开始并行处理..."
    parallel_process 4
    
    # JSON处理示例
    local json_data='{"name": "test", "value": 42}'
    if jq_output=$(echo "$json_data" | jq '.value'); then
        echo "解析的JSON值: $jq_output"
    fi
    
    release_lock
}

# 仅当直接执行时运行
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi

其他语言测试

Go 语言

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"sync"
	"time"
)

// User 结构体
type User struct {
	ID        int       `json:"id"`
	Name      string    `json:"name"`
	Email     string    `json:"email"`
	CreatedAt time.Time `json:"created_at"`
}

// UserService 接口
type UserService interface {
	CreateUser(ctx context.Context, user *User) error
	GetUser(ctx context.Context, id int) (*User, error)
	ListUsers(ctx context.Context) ([]*User, error)
}

// MemoryUserService 内存实现
type MemoryUserService struct {
	mu    sync.RWMutex
	users map[int]*User
	nextID int
}

func NewMemoryUserService() *MemoryUserService {
	return &MemoryUserService{
		users:  make(map[int]*User),
		nextID: 1,
	}
}

func (s *MemoryUserService) CreateUser(ctx context.Context, user *User) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	
	user.ID = s.nextID
	user.CreatedAt = time.Now()
	s.users[user.ID] = user
	s.nextID++
	
	return nil
}

func (s *MemoryUserService) GetUser(ctx context.Context, id int) (*User, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	
	user, exists := s.users[id]
	if !exists {
		return nil, fmt.Errorf("user not found: %d", id)
	}
	return user, nil
}

// HTTP 处理器
type Server struct {
	service UserService
}

func (s *Server) handleCreateUser(w http.ResponseWriter, r *http.Request) {
	var user User
	if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	
	if err := s.service.CreateUser(r.Context(), &user); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(user)
}

func main() {
	service := NewMemoryUserService()
	server := &Server{service: service}
	
	http.HandleFunc("/users", server.handleCreateUser)
	
	log.Println("Server starting on :8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

Rust 语言

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use serde::{Deserialize, Serialize};
use tokio::time::{sleep, Duration};

// 自定义错误类型
#[derive(Debug)]
enum AppError {
    NotFound(String),
    Validation(String),
}

impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AppError::NotFound(msg) => write!(f, "Not found: {}", msg),
            AppError::Validation(msg) => write!(f, "Validation error: {}", msg),
        }
    }
}

impl Error for AppError {}

// 用户结构体
#[derive(Debug, Clone, Serialize, Deserialize)]
struct User {
    id: u32,
    name: String,
    email: String,
    age: Option<u8>,
}

impl User {
    // 关联函数
    fn new(id: u32, name: String, email: String, age: Option<u8>) -> Self {
        Self { id, name, email, age }
    }
    
    // 方法
    fn is_adult(&self) -> bool {
        self.age.map_or(false, |age| age >= 18)
    }
}

// 用户仓库
struct UserRepository {
    users: HashMap<u32, User>,
    next_id: u32,
}

impl UserRepository {
    fn new() -> Self {
        Self {
            users: HashMap::new(),
            next_id: 1,
        }
    }
    
    fn add_user(&mut self, mut user: User) -> u32 {
        user.id = self.next_id;
        self.users.insert(self.next_id, user);
        self.next_id += 1;
        self.next_id - 1
    }
    
    fn get_user(&self, id: u32) -> Result<&User, AppError> {
        self.users.get(&id)
            .ok_or_else(|| AppError::NotFound(format!("User with id {} not found", id)))
    }
    
    // 泛型方法示例
    fn find_user_by<F>(&self, predicate: F) -> Option<&User>
    where
        F: Fn(&User) -> bool,
    {
        self.users.values().find(|&user| predicate(user))
    }
}

// 异步示例
async fn process_user_data(user: &User) -> Result<String, Box<dyn Error>> {
    // 模拟异步操作
    sleep(Duration::from_millis(100)).await;
    
    if user.name.is_empty() {
        return Err(Box::new(AppError::Validation("Name cannot be empty".to_string())));
    }
    
    Ok(format!("Processed user: {} ({})", user.name, user.email))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let mut repo = UserRepository::new();
    
    let user1 = User::new(0, "Alice".to_string(), "alice@example.com".to_string(), Some(30));
    let id1 = repo.add_user(user1);
    
    let user2 = User::new(0, "Bob".to_string(), "bob@example.com".to_string(), None);
    let id2 = repo.add_user(user2);
    
    // 模式匹配
    match repo.get_user(id1) {
        Ok(user) => {
            println!("Found user: {:?}", user);
            println!("Is adult? {}", user.is_adult());
            
            // 异步处理
            match process_user_data(user).await {
                Ok(result) => println!("{}", result),
                Err(e) => eprintln!("Error: {}", e),
            }
        }
        Err(e) => eprintln!("Error: {}", e),
    }
    
    // 使用迭代器
    let adult_users: Vec<_> = repo.users.values()
        .filter(|user| user.is_adult())
        .collect();
    
    println!("Adult users: {}", adult_users.len());
    
    Ok(())
}

结论

以上测试涵盖了:

  • ✅ Python(基础、类、装饰器、异步编程)
  • ✅ JavaScript/TypeScript(ES6+特性、类型系统)
  • ✅ Java(基础、Spring Boot示例)
  • ✅ C++(基础、现代C++特性)
  • ✅ HTML/CSS(标记语言、样式表)
  • ✅ SQL(基础查询、复杂查询、窗口函数)
  • ✅ Bash/Shell(基础脚本、高级脚本)
  • ✅ Go(并发、接口、Web服务)
  • ✅ Rust(模式匹配、错误处理、异步编程)

如果所有代码块都能正确高亮显示,说明代码高亮功能工作正常!

小站已顺利运行了 小时 分钟
现有4篇文章 · 共8807字
欢迎来到我的博客!🫤