Skip to main content
Code Snippets Background
Copy & Paste Snippets

Code Snippets &
Prompt Lab

Production-tested React hooks, AI engineering prompts, utility functions, and design patterns. Every snippet is battle-tested in real projects. Copy, paste, ship.

105+

Snippets

16

Categories

17+

Languages

100%

Copy Ready

Explore Snippets

Production-tested hooks, prompts, and utility functions.

bash

Get unique values from a Bash array

Extract distinct elements from a Bash array while preserving order, using associative arrays (Bash 4+).

basharraysunique
snippet.bash
#!/usr/bin/env bash

# uniq_array <array_name>
# Prints unique elements, one per line, preserving first‑seen order.
uniq_array() {
  local -n src=$1   # nameref to the input array
  declare -A seen
  for elem in "${src[@]}"; do
    [[ -v seen["$elem"] ]] && continue
    seen["$elem"]=1
    printf '%s\n' "$elem"
  done
}

# Example usage
my_arr=(apple banana apple orange banana grape)
unique_vals=( $(uniq_array my_arr) )
printf 'Unique: %s\n' "${unique_vals[@]}"
python

Python 3 CGI: safely read form variables

A ready‑to‑run CGI script that extracts GET and POST fields in Python 3 using cgi.FieldStorage and returns them as a dict.

pythoncgi
snippet.python
#!/usr/bin/env python3
import os, sys, cgi, cgitb
cgitb.enable()

def get_form():
    form = cgi.FieldStorage()
    data = {}
    for key in form.keys():
        value = form[key]
        if isinstance(value, list):
            data[key] = [v.value for v in value]
        else:
            data[key] = value.value
    return data

if __name__ == "__main__":
    params = get_form()
    print("Content-Type: text/plain")
    print()
    for k, v in params.items():
        print(f"{k} = {v}")
go

Prevent Go net.Conn.Close() from hanging

A safe pattern that guarantees Close returns within a timeout by setting a deadline and forcibly closing the fd if needed.

gonet
snippet.go
package netutil\n\nimport (\n    \"net\"\n    \"syscall\"\n    \"time\"\n)\n\n// CloseWithTimeout attempts to close a net.Conn but guarantees it returns within timeout.\n// It first sets a deadline to unblock any pending I/O, then calls Close in a goroutine.\n// If Close does not finish in time, it forcibly closes the underlying file descriptor.\nfunc CloseWithTimeout(c net.Conn, timeout time.Duration) error {\n    if timeout > 0 {\n        _ = c.SetDeadline(time.Now().Add(timeout))\n    }\n    done := make(chan error, 1)\n    go func() {\n        done <- c.Close()\n    }()\n    select {\n    case err := <-done:\n        return err\n    case <-time.After(timeout):\n        // Timeout: force‑close the fd to unblock the blocked Close call.\n        if rc, ok := c.(interface{ SyscallConn() (syscall.RawConn, error) }); ok {\n            raw, err := rc.SyscallConn()\n            if err == nil {\n                raw.Control(func(fd uintptr) {\n                    _ = syscall.Close(int(fd))\n                })\n            }\n        }\n        return syscall.ETIMEDOUT\n    }\n}\n
rust

Build Linux Kernel Module (LKM) with Cargo

Use Cargo's build script to call the kernel Makefile so you can compile a C LKM with `cargo build` and get a .ko artifact directly from Cargo.

cargolkmmakekernel-module
snippet.rust
// Cargo.toml
[package]
name = "my_lkm"
version = "0.1.0"
edition = "2021"
build = "build.rs"

[dependencies]

// build.rs
use std::process::Command;
use std::env;

fn main() {
    // Re‑run if source files or Makefile change
    println!("cargo:rerun-if-changed=src/");
    println!("cargo:rerun-if-changed=Makefile");

    // Invoke the kernel's build system
    let status = Command::new("make")
        .args(&["-C", "/lib/modules/$(uname -r)/build", "M=$(PWD)", "modules"])
        .status()
        .expect("Failed to invoke make");
    assert!(status.success(), "Kernel module build failed");
}

// Makefile
obj-m += my_lkm.o
KVERSION := $(shell uname -r)
KDIR := /lib/modules/$(KVERSION)/build
PWD := $(shell pwd)

all:
	$(MAKE) -C $(KDIR) M=$(PWD) modules

clean:
	$(MAKE) -C $(KDIR) M=$(PWD) clean

// src/my_lkm.c
#include <linux/module.h>
#include <linux/kernel.h>

static int __init my_lkm_init(void) {
    pr_info("my_lkm loaded\n");
    return 0;
}

static void __exit my_lkm_exit(void) {
    pr_info("my_lkm unloaded\n");
}

module_init(my_lkm_init);
module_exit(my_lkm_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("Sample LKM built via Cargo");
javascript

Run a JavaScript if block only once

Use a closure‑based guard or a once‑helper so the conditional body executes a single time regardless of how many times the surrounding code runs.

javascriptif-statementonce
snippet.js
function once(fn){let executed=false;return function(...args){if(executed) return;executed=true;return fn.apply(this,args);};}
// Example usage
const init = once(()=>{console.log('initialized');});
// Call init many times – console.log runs only once
init();
init();
init();
go

Go: Service‑level transaction with proper rollback

Shows a clean pattern for wrapping a service method in a database/sql transaction, guaranteeing rollback on error and commit on success.

gosqltransactions
snippet.go
package service

import (
    "context"
    "database/sql"
)

type DB interface {
    BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}

type User struct {
    ID   int64
    Name string
}

type Repo struct {
    db DB
}

// CreateUser runs inside a transaction. If any step returns an error the transaction is rolled back.
func (r *Repo) CreateUser(ctx context.Context, u *User) (err error) {
    tx, err := r.db.BeginTx(ctx, nil)
    if err != nil {
        return err
    }
    // Ensure rollback on panic or error.
    defer func() {
        if p := recover(); p != nil {
            _ = tx.Rollback()
            panic(p)
        } else if err != nil {
            _ = tx.Rollback()
        }
    }()

    // Business logic using the transaction.
    _, err = tx.ExecContext(ctx, "INSERT INTO users (name) VALUES (?)", u.Name)
    if err != nil {
        return err
    }

    // Commit only if everything succeeded.
    err = tx.Commit()
    return err
}
go

Pion WebRTC ReplaceTrack in Layered SFU – ensure video reaches Sub‑SFU

Shows the correct way to call ReplaceTrack on the parent SFU and keep the forwarding goroutine alive so the sub‑SFU continues to receive video without dropping packets.

pionwebrtcsfus
snippet.go
package main

import (
    "log"
    "github.com/pion/webrtc/v4"
)

// forwardRTP reads RTP packets from srcSender and writes them to dstTrack.
func forwardRTP(srcSender *webrtc.RTPSender, dstTrack *webrtc.TrackLocalStaticRTP) {
    pkt := make([]byte, 1500)
    for {
        n, _, err := srcSender.Read(pkt)
        if err != nil {
            // src closed – exit goroutine
            return
        }
        if _, err = dstTrack.Write(pkt[:n]); err != nil {
            return
        }
    }
}

func main() {
    // ---------- Parent (Layer‑0) SFU ----------
    parentPC, err := webrtc.NewPeerConnection(webrtc.Configuration{})
    if err != nil { log.Fatal(err) }

    // Create an initial placeholder track (will be replaced later)
    placeholder, err := webrtc.NewTrackLocalStaticRTP(
        webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8},
        "video", "layer0",
    )
    if err != nil { log.Fatal(err) }

    // Add the placeholder track to the parent PC – this creates a transceiver
    parentSender, err := parentPC.AddTrack(placeholder)
    if err != nil { log.Fatal(err) }

    // ---------- Sub (Layer‑1) SFU ----------
    subPC, err := webrtc.NewPeerConnection(webrtc.Configuration{})
    if err != nil { log.Fatal(err) }

    // The track that the sub‑SFU will expose to downstream peers
    subTrack, err := webrtc.NewTrackLocalStaticRTP(
        webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8},
        "video", "layer1",
    )
    if err != nil { log.Fatal(err) }

    if _, err = subPC.AddTrack(subTrack); err != nil { log.Fatal(err) }

    // Start forwarding RTP from parent to sub. This goroutine stays alive even
    // after ReplaceTrack is called because it always reads from the current
    // sender (which internally swaps the underlying track).
    go forwardRTP(parentSender, subTrack)

    // ---------- When a new video layer arrives ----------
    // Assume newTrack is obtained from an incoming PeerConnection (e.g., a new
    // encoder layer). It must match the codec of the placeholder.
    newTrack, err := webrtc.NewTrackLocalStaticRTP(
        webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8},
        "video", "layer0-new",
    )
    if err != nil { log.Fatal(err) }

    // Replace the placeholder with the real track on the parent SFU.
    // This is the critical call – it swaps the underlying source without
    // tearing down the RTCPeerConnection or the forwarding goroutine.
    if err = parentSender.ReplaceTrack(newTrack); err != nil {
        log.Fatalf("ReplaceTrack failed: %v", err)
    }

    // No further action is required for the sub‑SFU; the forwardRTP loop will
    // now read packets from newTrack and continue writing to subTrack.

    // Keep the program alive (in real code you would wait on signals, etc.)
    select {}
}
rust

Enable Tokio multi_thread runtime in Rust

Fix the compile error when Tokio defaults to multi_thread but the feature is disabled by adding the correct Cargo.toml feature flag and using #[tokio::main].

rusttokio
snippet.rust
// Cargo.toml
[dependencies]
tokio = { version = "1.38", features = ["rt-multi-thread", "macros"] }

// src/main.rs
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    // async work
    sleep(Duration::from_secs(1)).await;
    println!("Runtime works with multi_thread");
}
bash

Fix Bash glob (*) on WSL 9P mounts

Remount a Windows folder via WSL's 9P driver with the right options so that `*` expands correctly. The snippet also shows a quick sanity check and how to include dotfiles if needed.

bashwsl9pglob
snippet.bash
#!/usr/bin/env bash
# Unmount any existing 9p mount at /mnt/wsl
if mountpoint -q /mnt/wsl; then
  sudo umount /mnt/wsl
fi

# Re‑mount with options that make globs work
#   trans=virtio          – use the virtio transport (default for WSL)
#   version=9p2000.L     – latest protocol version supported by WSL
#   msize=262144         – page size, improves performance
#   uid/gid              – map Windows files to the current Linux user
#   cache=none           – disables client‑side caching which can hide files
#   metadata             – forces the server to send proper file attributes
#   case=off             – disables case‑folding that breaks pattern matching
sudo mount -t 9p \
  -o trans=virtio,version=9p2000.L,msize=262144,uid=$(id -u),gid=$(id -g),cache=none,metadata,case=off \
  //wsl$/Ubuntu-20.04 /mnt/wsl

# Quick sanity check – should list every entry under the mount point
echo "Files matched by *:" 
printf '%s\n' /mnt/wsl/*

# If you also need hidden files, enable dotglob for this session
shopt -s dotglob
echo "Including dotfiles:" 
printf '%s\n' /mnt/wsl/*
bash

Bash: Unique values from an array

Extract distinct elements from a Bash array while preserving order, using only built‑in features.

basharrays
snippet.bash
#!/usr/bin/env bash
arr=(a b c a b d)
declare -A seen
unique=()
for item in "${arr[@]}"; do
  [[ -z ${seen[$item]} ]] && unique+=("$item") && seen[$item]=1
done
printf '%s\n' "${unique[@]}"
bash

Run JSNice locally via Docker (one‑liner script)

A bash helper that pulls the official JSNice Docker image and deobfuscates a JavaScript file in place, so you never need the web UI again.

jsnicedocker
snippet.bash
#!/usr/bin/env bash
# Usage: ./run_jsnice.sh <input.js> [output.js]
set -e
if [[ -z "$1" ]]; then
  echo "Error: input file required"
  echo "Usage: $0 <input.js> [output.js]"
  exit 1
fi
INPUT="$1"
OUT="${2:-${INPUT%.js}_nice.js}"
# Ensure Docker is available
if ! command -v docker >/dev/null 2>&1; then
  echo "Docker not found – installing JSNice via npm instead"
  npm install -g jsnice
  jsnice "$INPUT" > "$OUT"
  echo "Deobfuscated code written to $OUT"
  exit 0
fi
# Pull the latest JSNice image (cached if already present)
docker pull jsnice/jsnice:latest >/dev/null
# Run JSNice inside the container, mounting the current directory
docker run --rm -v "$(pwd)":/data jsnice/jsnice jsnice -i "/data/$INPUT" -o "/data/$OUT"
echo "Deobfuscated code written to $OUT"
bash

Git status pre/post hook via alias

There is no native pre‑status/post‑status hook. Use a git alias that runs your scripts before and after the real status command, giving you hook‑like behavior.

githooks
snippet.bash
# .gitconfig (add under [alias])
[alias]
    status = "!f() { \
        ./hooks/pre-status.sh; \
        git status "$@"; rc=$?; \
        ./hooks/post-status.sh; \
        return $rc; \
    }; f"

# ./hooks/pre-status.sh (make executable)
#!/usr/bin/env bash
# Example: warn about untracked large files
echo "Running pre‑status checks..."
# Add your checks here
# exit 1 to abort status if needed

# ./hooks/post-status.sh (make executable)
#!/usr/bin/env bash
# Example: clean up temporary files after status
echo "Running post‑status actions..."
# Add your actions here
Page 1 of 9

Stay Ahead of the Curve

Get our weekly digest of production blueprints, deep-dive benchmarks, and architectural audits delivered directly to your inbox.

Join 5,000+ engineers. No spam, ever.