duqing2026's picture
feat: replace chinese comments with english, update title to chinese
df1ba4a
import os
import random
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
# 示例代码片段
SNIPPETS = [
# --- Python ---
{
"language": "Python",
"code": """# Binary Search Implementation
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid # Target found
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Not found"""
},
{
"language": "Python",
"code": """# Flask Route Example
@app.route('/api/users', methods=['GET'])
def get_users():
# Get user list from database
users = db.session.query(User).all()
return jsonify({
"count": len(users),
"data": [u.to_dict() for u in users]
})"""
},
{
"language": "Python",
"code": """# Quick Sort Algorithm
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)"""
},
# --- JavaScript ---
{
"language": "JavaScript",
"code": """/**
* Debounce Function
* Limits the rate at which a function can fire.
*/
function debounce(func, wait) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
// Execute later
timeout = setTimeout(() => {
func.apply(context, args);
}, wait);
};
}"""
},
{
"language": "JavaScript",
"code": """// Promise Chain Example
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});"""
},
# --- Go ---
{
"language": "Go",
"code": """// Concurrency Example
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
// Start 5 goroutines
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Printf("Worker %d starting\\n", id)
}(i)
}
wg.Wait() // Wait for all goroutines to finish
fmt.Println("All workers done")
}"""
},
# --- SQL ---
{
"language": "SQL",
"code": """-- Query High Value Users
SELECT
u.username,
COUNT(o.id) as order_count,
SUM(o.amount) as total_spent
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE o.created_at >= '2024-01-01'
GROUP BY u.id
HAVING total_spent > 1000
ORDER BY total_spent DESC;"""
},
# --- React ---
{
"language": "React",
"code": """// Simple Counter Component
import React, { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div className="p-4 border rounded">
<h2 className="text-xl">Current Count: {count}</h2>
<button
onClick={() => setCount(count + 1)}
className="bg-blue-500 text-white px-4 py-2 mt-2"
>
Increment (+1)
</button>
</div>
);
}"""
},
# --- Java ---
{
"language": "Java",
"code": """// Singleton Pattern (Double Checked Locking)
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}"""
},
# --- HTML/CSS ---
{
"language": "HTML",
"code": """<!-- Simple Card Layout -->
<div class="card">
<img src="avatar.jpg" alt="User Avatar" class="card-img">
<div class="card-body">
<h5 class="card-title">Card Title</h5>
<p class="card-text">Some quick example text to build on the card title.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
<style>
.card { border: 1px solid #ccc; border-radius: 8px; padding: 16px; }
.card-img { width: 100%; height: auto; border-radius: 4px; }
</style>"""
}
]
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/snippet')
def get_snippet():
lang = request.args.get('lang')
if lang and lang != 'All':
filtered = [s for s in SNIPPETS if s['language'] == lang]
if filtered:
return jsonify(random.choice(filtered))
# 默认随机返回
snippet = random.choice(SNIPPETS)
return jsonify(snippet)
@app.route('/api/languages')
def get_languages():
# 获取所有唯一的语言列表
languages = sorted(list(set(s['language'] for s in SNIPPETS)))
return jsonify(['All'] + languages)
@app.route('/health')
def health():
return "OK", 200
if __name__ == '__main__':
port = int(os.environ.get('PORT', 7860))
app.run(host='0.0.0.0', port=port)