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 (