javascript
import { useEffect, useRef } from 'react';

const TABBABLE = [
  'a[href]',
  'button:not([disabled])',
  'textarea:not([disabled])',

Accessible React Modal with Portal, Focus Trap, and Escape-to-Close Hook

react accessibility modal
by codesnips 3 tabs
python
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from enum import Enum

from pydantic import BaseModel, field_validator

Parsing and Normalizing a Transactions CSV into Typed Records with Pydantic

csv pydantic data-parsing
by codesnips 2 tabs
python
import random
from dataclasses import dataclass
from typing import Iterator


@dataclass(frozen=True)

Retry Flaky HTTP Requests with Exponential Backoff and Full Jitter in Python

python requests retry
by codesnips 3 tabs
typescript
import { Injectable } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { FormGroup } from '@angular/forms';
import { Subscription } from 'rxjs';
import { debounceTime, distinctUntilChanged, map, take } from 'rxjs/operators';

Sync Angular Reactive Form State to URL Query Params With a Route-Aware Service

angular reactive-forms router
by codesnips 3 tabs
ruby
class ImportRun < ApplicationRecord
  enum status: { pending: 0, running: 1, completed: 2, failed: 3 }

  def percent
    return 0 if total.to_i.zero?
    [(processed.to_f / total * 100).round, 100].min

Live Turbo Streams Progress Bar for a Long Rails Job

rails turbo-streams hotwire
by codesnips 4 tabs
rust
use std::collections::HashMap;
use std::fmt;

#[derive(Debug, Clone)]
pub struct Document {
    pub body: String,

Trait-Based Document Transform Pipeline With Ordered Plugins in Rust

rust trait-objects pipeline
by codesnips 3 tabs
ruby
class InvoicesController < ApplicationController
  def index
    invoices = InvoicesQuery.new(current_account.invoices, filter_params).call

    @invoices = invoices.page(params[:page]).per(25)
    render :index

Building a Composable Query Object for Filtering Rails ActiveRecord Scopes

rails activerecord query-object
by codesnips 3 tabs
go
package main

import (
	"context"
	"log"
	"net/http"

Graceful HTTP Server Shutdown in Go with SIGINT and Context Cancellation

go http graceful-shutdown
by codesnips 2 tabs
go
package httpmetrics

import "github.com/prometheus/client_golang/prometheus"

var (
	httpRequestDuration = prometheus.NewHistogramVec(

HTTP Latency and Status Code Middleware with Prometheus in Go

go middleware prometheus
by codesnips 3 tabs
ruby
namespace :cleanup do
  desc "Enqueue a job to purge expired sessions"
  task expired_sessions: :environment do
    job = ExpiredSessionCleanupJob.perform_later
    Rails.logger.info("[cleanup:expired_sessions] enqueued job #{job.job_id}")
  end

Recurring Cleanup with a Rake Task and an Idempotent Active Job in Rails

rails background-jobs active-job
by codesnips 4 tabs
java
package com.example.observability;

public final class CorrelationIdConstants {

    public static final String HEADER_NAME = "X-Correlation-Id";
    public static final String MDC_KEY = "correlationId";

Propagate a Correlation ID Through Every Log Line with an MDC Servlet Filter in Spring Boot

spring-boot logging mdc
by codesnips 4 tabs
typescript
export interface QueryCodec<T> {
  parse: (raw: string | null) => T;
  serialize: (value: T) => string | null;
}

export function stringParam(fallback = ""): QueryCodec<string> {

Sync Typed Form State to the URL Query String with a useQueryState Hook

react hooks url-state
by codesnips 3 tabs