Code Explainers

Browse the library

python
from dataclasses import dataclass, fields, MISSING
from typing import get_type_hints, get_origin, get_args, Union
 
 

Type-checking dataclasses at runtime

dataclasses type-hints runtime-validation
Advanced 8 steps
rust
use axum::{
    body::Body,
    extract::Request,
    http::{header::HeaderValue, HeaderName},

Request ID middleware in Axum

middleware tracing request-extensions
Intermediate 7 steps
php
<?php
 
namespace App\Http\Controllers;
 

Handling avatar uploads in Laravel

file-upload image-processing validation
Intermediate 8 steps
ruby
class HostnameValidator < ActiveModel::EachValidator
  MAX_LENGTH = 253
  LABEL = /\A(?!-)[a-z0-9-]{1,63}(?<!-)\z/i
 

Writing a custom hostname validator in Rails

validation custom validator regex
Intermediate 8 steps
ruby
class PaymentsController < ApplicationController
  before_action :require_idempotency_key
 
  def create

Idempotent payment creation in Rails

idempotency transactions race-conditions
Advanced 10 steps
ruby
class Survey < ApplicationRecord
  has_many :questions, dependent: :destroy
  has_many :respondents, dependent: :nullify
 

Nested survey forms in Rails

nested-attributes validations associations
Intermediate 9 steps
php
<?php
 
namespace App\Security;
 

Secure password hashing with Argon2id in PHP

password-hashing argon2id timing-attacks
Intermediate 8 steps
python
import time
import threading
 
 

How a thread-safe token bucket rate limiter works

rate-limiting concurrency locking
Intermediate 6 steps
go
package logfmt
 
import (
	"bytes"

Pooling buffers for logfmt encoding in Go

object-pooling memory-reuse serialization
Intermediate 8 steps
typescript
import { z } from "zod";
 
const ProductQuerySchema = z.object({
  page: z.coerce.number().int().positive().default(1),

Validating URL query params with Zod

validation schema type-inference
Intermediate 8 steps
java
public final class RegistrationValidator {
 
    private static final Pattern EMAIL = Pattern.compile("^[\\w.+-]+@[\\w-]+\\.[\\w.-]+$");
    private static final Pattern USERNAME = Pattern.compile("^[a-zA-Z0-9_]{3,20}$");

Accumulating validation errors in Java

validation regex error-accumulation
Beginner 9 steps
javascript
async function fetchAllPages(baseUrl, { pageSize = 100, headers = {} } = {}) {
  const results = [];
  let cursor = null;
 

Cursor-based pagination with fetch

pagination async-await fetch
Intermediate 6 steps
rust
use std::collections::HashMap;
 
pub fn word_frequencies(text: &str) -> HashMap<String, usize> {
    let mut counts: HashMap<String, usize> = HashMap::new();

Counting and ranking words in Rust

hashmap iterators sorting
Intermediate 7 steps
php
<?php
 
namespace App\Security;
 

A fixed-window rate limiter on APCu

rate-limiting fixed-window caching
Intermediate 8 steps
python
from flask import Blueprint, render_template, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SubmitField

Handling a post form with a Flask Blueprint

blueprints form-validation post-redirect-get
Intermediate 7 steps
go
package storage
 
import (
	"bufio"

Streaming file downloads safely in Go

http streaming path-traversal
Intermediate 7 steps
typescript
type SearchResult = {
  id: string;
  title: string;
};

Cancelling stale searches with AbortController

abortcontroller cancellation async
Intermediate 7 steps
java
public class WorkPipeline {
    private final BlockingQueue<Task> queue = new LinkedBlockingQueue<>(1000);
    private static final Task POISON = new Task(-1, null);
    private final ExecutorService consumers = Executors.newFixedThreadPool(4);

A producer-consumer pipeline in Java

concurrency producer-consumer blocking-queue
Intermediate 8 steps