Code Snippet Library
Search, filter, and discover useful code snippets
Array Map
javascriptTransform array elements using map function
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);Python List Comprehension
pythonCreate lists using concise list comprehension syntax
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers if x % 2 == 0]
# Result: [4, 16]React useState Hook
tsxManage state in React functional components
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}SQL Query
sqlJoin tables and filter results in SQL
SELECT users.name, orders.order_date
FROM users
INNER JOIN orders ON users.id = orders.user_id
WHERE orders.status = 'completed'
ORDER BY orders.order_date DESC
LIMIT 5;Go Error Handling
goHandle errors in Go with idiomatic patterns
func readFile(path string) ([]byte, error) {
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()
data, err := io.ReadAll(file)
if err != nil {
return nil, fmt.Errorf("failed to read file: %w", err)
}
return data, nil
}CSS Grid Layout
cssCreate responsive grid layouts with CSS Grid
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1rem;
padding: 1rem;
}
.grid-item {
background: #f5f5f5;
padding: 1rem;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}Express.js REST API Setup
javascriptBasic setup for a REST API using Express.js with middleware
const express = require('express');
const app = express();
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Routes
app.get('/api/users', (req, res) => {
res.json({ message: 'Get all users' });
});
app.post('/api/users', (req, res) => {
res.status(201).json({ message: 'User created', data: req.body });
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ message: 'Something went wrong!' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});React Custom Hook for API Fetching
tsxCustom React hook for handling API calls with loading and error states
import { useState, useEffect } from 'react';
function useApi(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
const response = await fetch(url);
if (!response.ok) throw new Error('Network response was not ok');
const result = await response.json();
setData(result);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
}
// Usage
// const { data, loading, error } = useApi('/api/users');Python Flask Hello World
pythonSimple Flask application with route and template rendering
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello():
return render_template('index.html', message='Hello, World!')
@app.route('/api/data')
def get_data():
return {'data': [1, 2, 3, 4, 5]}
if __name__ == '__main__':
app.run(debug=True)Dockerfile for Node.js App
dockerfileMulti-stage Dockerfile for building and running a Node.js application
# Build stage
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
# Production stage
FROM node:18-alpine
WORKDIR /app
# Create non-root user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
# Copy built application
COPY --from=builder --chown=nextjs:nodejs /app/build ./build
COPY --from=builder --chown=nextjs:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=nextjs:nodejs /app/package*.json ./
# Switch to non-root user
USER nextjs
# Expose port
EXPOSE 3000
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:3000/health || exit 1
# Start the application
CMD ["npm", "start"]JWT Authentication Middleware
javascriptExpress middleware for JWT token verification and user authentication
const jwt = require('jsonwebtoken');
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'Access token required' });
}
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) {
return res.status(403).json({ message: 'Invalid or expired token' });
}
req.user = user;
next();
});
};
// Usage
// app.get('/protected', authenticateToken, (req, res) => {
// res.json({ message: 'Protected route accessed', user: req.user });
// });Python Async Context Manager
pythonCustom async context manager for database connections with proper cleanup
import asyncio
import aiohttp
from contextlib import asynccontextmanager
class DatabaseConnection:
def __init__(self, url):
self.url = url
self.connection = None
async def connect(self):
# Simulate database connection
print(f"Connecting to {self.url}")
await asyncio.sleep(0.1)
self.connection = f"Connected to {self.url}"
return self.connection
async def close(self):
print("Closing database connection")
await asyncio.sleep(0.1)
self.connection = None
@asynccontextmanager
async def get_db_connection(url):
db = DatabaseConnection(url)
try:
await db.connect()
yield db
finally:
await db.close()
# Usage
# async def main():
# async with get_db_connection("postgresql://localhost") as db:
# print(f"Using {db.connection}")
# # Database operations here
# # Connection automatically closedSQL Index Optimization
sqlCreate composite indexes for query performance optimization
-- Create composite index for frequently queried columns
CREATE INDEX idx_user_orders_status_date
ON orders (user_id, status, order_date);
-- Check index usage statistics
SELECT
schemaname,
tablename,
indexname,
idx_tup_read,
idx_tup_fetch
FROM pg_stat_user_indexes
WHERE tablename = 'orders';
-- Drop unused indexes
DROP INDEX CONCURRENTLY idx_old_unused_index;React Context API with useReducer
tsxGlobal state management using Context API and useReducer hook
import React, { createContext, useContext, useReducer } from 'react';
// Define types
interface State {
user: { id: string; name: string } | null;
theme: 'light' | 'dark';
}
type Action =
| { type: 'SET_USER'; payload: { id: string; name: string } }
| { type: 'LOGOUT' }
| { type: 'TOGGLE_THEME' };
// Initial state
const initialState: State = {
user: null,
theme: 'light',
};
// Reducer
function appReducer(state: State, action: Action): State {
switch (action.type) {
case 'SET_USER':
return { ...state, user: action.payload };
case 'LOGOUT':
return { ...state, user: null };
case 'TOGGLE_THEME':
return { ...state, theme: state.theme === 'light' ? 'dark' : 'light' };
default:
return state;
}
}
// Create context
const AppContext = createContext<{
state: State;
dispatch: React.Dispatch<Action>;
} | null>(null);
// Provider component
export function AppProvider({ children }: { children: React.ReactNode }) {
const [state, dispatch] = useReducer(appReducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
);
}
// Custom hook
export function useAppContext() {
const context = useContext(AppContext);
if (!context) {
throw new Error('useAppContext must be used within AppProvider');
}
return context;
}
// Usage in components
// const { state, dispatch } = useAppContext();
// dispatch({ type: 'SET_USER', payload: { id: '1', name: 'John' } });Docker Compose for Multi-Service App
yamlDefine and run multi-container Docker applications with Docker Compose
version: '3.8'
services:
# Frontend service
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
ports:
- "3000:3000"
environment:
- REACT_APP_API_URL=http://backend:5000
depends_on:
- backend
volumes:
- ./frontend:/app
- /app/node_modules
networks:
- app-network
# Backend service
backend:
build:
context: ./backend
dockerfile: Dockerfile
ports:
- "5000:5000"
environment:
- DATABASE_URL=postgresql://user:password@db:5432/myapp
- REDIS_URL=redis://redis:6379
depends_on:
db:
condition: service_healthy
redis:
condition: service_started
volumes:
- ./backend:/app
networks:
- app-network
# Database service
db:
image: postgres:13
environment:
- POSTGRES_USER=user
- POSTGRES_PASSWORD=password
- POSTGRES_DB=myapp
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user"]
interval: 10s
timeout: 5s
retries: 5
networks:
- app-network
# Redis service
redis:
image: redis:6-alpine
ports:
- "6379:6379"
networks:
- app-network
volumes:
postgres_data:
networks:
app-network:
driver: bridgeCSS Flexbox Cheatsheet
cssComplete guide to CSS Flexbox properties and their usage
/* Parent (Flex Container) Properties */
.container {
display: flex;
/* Direction */
flex-direction: row | row-reverse | column | column-reverse;
/* Wrapping */
flex-wrap: nowrap | wrap | wrap-reverse;
flex-flow: row wrap; /* Shorthand */
/* Alignment */
justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly;
align-items: stretch | flex-start | flex-end | center | baseline;
align-content: flex-start | flex-end | center | space-between | space-around | stretch;
}
/* Children (Flex Items) Properties */
.item {
/* Individual alignment */
align-self: auto | flex-start | flex-end | center | baseline | stretch;
/* Growth and shrinkage */
flex-grow: <number>; /* Default: 0 */
flex-shrink: <number>; /* Default: 1 */
flex-basis: <length> | auto; /* Default: auto */
flex: 0 1 auto; /* Shorthand */
/* Order */
order: <integer>; /* Default: 0 */
}React useEffect Cleanup
tsxProperly clean up subscriptions and timers in React useEffect
import { useState, useEffect } from 'react';
function ChatRoom({ roomId }) {
const [messages, setMessages] = useState([]);
useEffect(() => {
// Create subscription
const subscription = subscribeToRoom(roomId, (message) => {
setMessages(prev => [...prev, message]);
});
// Set up interval
const intervalId = setInterval(() => {
// Do something periodically
checkUnreadMessages();
}, 5000);
// Cleanup function
return () => {
// Clear interval
clearInterval(intervalId);
// Unsubscribe from room
subscription.unsubscribe();
// Cancel any pending requests
abortController.abort();
};
}, [roomId]);
return (
<div>
{messages.map((msg, index) => (
<div key={index}>{msg.text}</div>
))}
</div>
);
}Express.js Logging Middleware
javascriptCustom logging middleware for Express.js applications
const express = require('express');
const app = express();
// Custom logging middleware
const requestLogger = (req, res, next) => {
const startTime = Date.now();
// Log incoming request
console.log(`${new Date().toISOString()} - ${req.method} ${req.url} - ${req.ip}`);
// Capture response finish to log completion
res.on('finish', () => {
const duration = Date.now() - startTime;
console.log(`${new Date().toISOString()} - ${req.method} ${req.url} - ${res.statusCode} - ${duration}ms`);
});
// Capture request errors
req.on('error', (err) => {
console.error(`${new Date().toISOString()} - Request Error: ${req.method} ${req.url} - ${err.message}`);
});
next();
};
// Apply middleware
app.use(requestLogger);
// Route with potential error
app.get('/api/data', (req, res, next) => {
try {
// Simulate some processing
const data = processData();
res.json({ success: true, data });
} catch (error) {
next(error); // Pass error to error handling middleware
}
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(`${new Date().toISOString()} - Unhandled Error: ${err.message}`);
res.status(500).json({ error: 'Internal Server Error' });
});Python Decorator with Parameters
pythonCreate reusable decorators with parameters in Python
import time
import functools
from typing import Callable, Any
# Decorator that accepts parameters
def retry(max_attempts: int = 3, delay: float = 1.0):
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs) -> Any:
last_exception = None
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except Exception as e:
last_exception = e
if attempt < max_attempts - 1: # Don't delay on last attempt
print(f"Attempt {attempt + 1} failed: {e}. Retrying in {delay}s...")
time.sleep(delay)
# If all attempts failed, raise the last exception
raise last_exception
return wrapper
return decorator
# Decorator that measures execution time
def timer(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs) -> Any:
start_time = time.perf_counter()
result = func(*args, **kwargs)
end_time = time.perf_counter()
print(f"{func.__name__} executed in {end_time - start_time:.4f} seconds")
return result
return wrapper
# Usage examples
@retry(max_attempts=3, delay=0.5)
@timer
def fetch_data(url: str) -> dict:
# Simulate network request that might fail
import random
if random.random() < 0.7: # 70% chance of failure
raise ConnectionError("Network error")
return {"data": "fetched successfully"}
# result = fetch_data("https://api.example.com")