THE COMPLETE LIBRARY
Sitemap
Every example, organized by language and task. Browse 3,000 tested snippets across 24 categories.
Site pages
Python 125 snippets
Getting Started
- Run your first program
- Store a value in a named variable
- Name a value that stays fixed
- Calculate a simple total
- Divide using a fractional number
- Find what remains after division
- Compare a value with a limit
- Require two conditions to be true
- Choose between two branches
- Update a running count
- Handle three possible outcomes
- Repeat a fixed number of times
- Repeat while a condition holds
- Visit every item in a collection
- Count the items in a collection
- Read the first collection element
- Replace one collection element
- Measure a short text value
- Combine text with a name
- Read the beginning of a text value
- Read one character from ASCII text
- Call a library function
- Convert known numeric text to an integer
- Print a number with two decimal places
- Explain a calculation with a comment
Collections
Dates & time zones
- Advance a date by a number of days
- Convert a duration to hours and minutes
- Convert a Unix timestamp to aware UTC
- Convert an aware datetime to another offset
- Count days between calendar dates
- Determine whether a year is a leap year
- Find the number of days in a month
- Parse an ISO calendar date
- Read an ISO week number
- Skip weekends when advancing dates
File operations & archives
- Clean up a temporary directory automatically
- Copy a file and preserve its metadata
- Create a file without overwriting an existing one
- Create a ZIP archive from a file
- Extract filename components
- Find matching files recursively
- Hash a file without reading it all at once
- Read a file size in bytes
- Read compressed text directly
- Rename a file within a directory
Files & paths
Functions & error handling
- Avoid a shared mutable default argument
- Cache repeated pure function calls
- Capture a successful child-process result
- Collect independent asynchronous results
- Handle an expected child-process failure
- Parse a typed command-line option
- Preconfigure some function arguments
- Raise and catch a domain-specific exception
- Run cleanup around a custom context
- Yield values on demand
Iteration & sequences
- Calculate cumulative totals
- Find the first matching value with a fallback
- Flatten one level of nested lists
- Generate combinations across two collections
- Number items while iterating
- Pair corresponding list items
- Separate records into two lists
- Split a list into fixed-size batches
- Take a limited number of iterator values
- Visit adjacent pairs
JSON & CSV
Mappings & sets
- Check whether all required keys exist
- Copy nested mutable data independently
- Find values missing from another collection
- Find values present in exactly one set
- Find values shared by two collections
- Group records by a field
- Invert a dictionary with unique values
- Keep only the most recent items
- Read an optional dictionary key
- Remove and return a dictionary entry
Numbers & calculations
- Calculate the number of required pages
- Calculate with exact rational values
- Clamp a numeric value between bounds
- Compare floating-point calculations with tolerance
- Find common factors and multiples
- Find the mean and median of readings
- Insert a value while preserving sorted order
- Reject NaN and infinite numeric inputs
- Round decimal amounts explicitly
- Select the largest values without sorting everything
Strings & dates
Structured data & serialization
- Handle malformed JSON input
- Pack and unpack a network-order integer
- Parse quoted CSV from an in-memory string
- Produce compact deterministic JSON
- Read a small INI configuration
- Read a tab-separated table
- Read elements from trusted XML
- Read one JSON document per line
- Represent a record with a dataclass
- Return a small immutable named record
Text validation & encoding
- Build a URL query string
- Compare Unicode text without case
- Convert hexadecimal text to bytes
- Encode and decode binary data as Base64
- Escape text for HTML content
- Extract named regex fields
- Normalize equivalent Unicode strings
- Remove a known prefix safely
- Remove a known suffix safely
- Validate an entire identifier
C# 125 snippets
Getting Started
- Run your first program
- Store a value in a named variable
- Name a value that stays fixed
- Calculate a simple total
- Divide using a fractional number
- Find what remains after division
- Compare a value with a limit
- Require two conditions to be true
- Choose between two branches
- Update a running count
- Handle three possible outcomes
- Repeat a fixed number of times
- Repeat while a condition holds
- Visit every item in a collection
- Count the items in a collection
- Read the first collection element
- Replace one collection element
- Measure a short text value
- Combine text with a name
- Read the beginning of a text value
- Read one character from ASCII text
- Call a library function
- Convert known numeric text to an integer
- Print a number with two decimal places
- Explain a calculation with a comment
Asynchronous work & URI handling
- Await an asynchronous method result
- Await multiple tasks while preserving result order
- Escape a URL query value
- Escape text for an HTML context
- Increment a shared counter atomically
- Inspect a parsed URI
- Limit concurrent access with SemaphoreSlim
- Observe cancellation through a token
- Parse a GUID without an exception
- Resolve a relative URI against a base
Collections
Collections & data structures
- Add a dictionary entry only if absent
- Combine collections as a distinct set
- Find values common to two collections
- Find values missing from another collection
- Process a FIFO queue
- Process items by numeric priority
- Remove matching items from a mutable list
- Search a sorted array efficiently
- Use a last-in first-out stack
- Use case-insensitive dictionary keys
Data & dates
Dates & precise numbers
- Calculate an integer beyond the 64-bit range
- Calculate the number of calendar days between dates
- Clamp a number to inclusive bounds
- Convert a timestamp to a different fixed offset
- Convert Unix seconds to an offset-aware timestamp
- Detect integer overflow with checked
- Find the length of a calendar month
- Parse a date without a time component
- Reject infinity and NaN
- Round a decimal using an explicit midpoint rule
File operations & paths
- Copy a file without overwriting
- Create a file only when it does not exist
- Delete a known scratch file
- Enumerate matching files recursively
- Inspect a file length without reading it
- Move a file to a new filename
- Process a file as a lazy line sequence
- Read a filename stem and extension
- Replace a path extension
- Write and read raw bytes
Files & paths
JSON & binary formats
- Convert bytes to Base64 and back
- Decode hexadecimal bytes
- Deserialize a JSON object into a dictionary
- Enumerate the items of a JSON array
- Handle malformed JSON
- Hash a UTF-8 value with SHA-256
- Measure the byte length of UTF-8 text
- Read a big-endian binary integer
- Read an optional JSON property safely
- Update a JSON document with mutable nodes
LINQ transformations
- Calculate a product with Aggregate
- Create a reusable one-to-many lookup
- Find a matching item with a fallback
- Flatten nested collections with SelectMany
- Pair corresponding collection elements
- Remove duplicate records by a selected key
- Split values into fixed-size chunks
- Take a page from an ordered sequence
- Test whether any or all values match
- Transform each item with Select
Strings
Text validation & encoding
- Build text incrementally with StringBuilder
- Check a literal prefix with ordinal comparison
- Check an extension without case sensitivity
- Enumerate Unicode code points
- Extract a substring with range syntax
- Extract all integer tokens from text
- Normalize canonically equivalent Unicode strings
- Pad a numeric label to a fixed width
- Quote a literal search term for a regex
- Validate a complete identifier with a regex
Types & reliable control flow
- Create a modified copy of an immutable record
- Narrow an object using a type pattern
- Parse an enum name without throwing
- Pass behavior as a function delegate
- Perform cleanup even after an exception
- Provide a fallback for a nullable value
- Return multiple named values from a method
- Use a switch expression to classify a value
- Validate an argument at a method boundary
- Write a generic first-or-fallback helper
Java 125 snippets
Getting Started
- Run your first program
- Store a value in a named variable
- Name a value that stays fixed
- Calculate a simple total
- Divide using a fractional number
- Find what remains after division
- Compare a value with a limit
- Require two conditions to be true
- Choose between two branches
- Update a running count
- Handle three possible outcomes
- Repeat a fixed number of times
- Repeat while a condition holds
- Visit every item in a collection
- Count the items in a collection
- Read the first collection element
- Replace one collection element
- Measure a short text value
- Combine text with a name
- Read the beginning of a text value
- Read one character from ASCII text
- Call a library function
- Convert known numeric text to an integer
- Print a number with two decimal places
- Explain a calculation with a comment
Collections
Dates & time zones
- Check the Gregorian leap-year rule
- Convert an instant to a regional timezone
- Convert epoch seconds into an instant
- Count days between two dates
- Find the last day of a month
- Find the next chosen weekday
- Generate a half-open range of dates
- Measure a duration between instants
- Parse a date with an explicit input pattern
- Read an ISO week year and week number
Encoding & structured values
- Calculate a SHA-256 content digest
- Convert bytes to hexadecimal and back
- Decode a form query parameter
- Encode a form query parameter
- Encode and decode Base64 bytes
- Inspect components of a URI
- Measure UTF-8 bytes separately from characters
- Parse a UUID and inspect its version
- Read a big-endian integer from bytes
- Write and read typed binary fields
File operations & binary data
- Copy a file without replacing an existing destination
- Create and clean up a temporary file
- Delete a known temporary file if present
- Load a small properties configuration
- Move a file to a new name
- Normalize relative path components
- Process a text file one line at a time
- Read a file length in bytes
- Visit files recursively
- Write and read binary bytes
Files & paths
Numbers & dates
Precise numeric calculations
- Calculate beyond the long integer range
- Compare floating-point results with a tolerance
- Detect integer addition overflow
- Display an integer as unsigned
- Divide decimal values with controlled precision
- Divide negative integers with floor rounding
- Find the greatest common divisor
- Parse an integer in another base
- Reject nonfinite floating-point values
- Round a decimal with an explicit rule
Queues & collection operations
- Find set members missing from another set
- Find shared set members
- Initialize a map entry only when absent
- Locate a value in a sorted array
- Preserve map insertion order
- Remove collection items that satisfy a condition
- Retrieve the smallest queued value first
- Take an immutable list snapshot
- Use a deque as a FIFO queue
- Use a deque as a stack
Records & reliable control flow
- Define an immutable data record
- Narrow an object with a pattern variable
- Represent a finite set of states
- Return a value from a switch expression
- Run a task on an executor and close it
- Run cleanup after a handled exception
- Transform an asynchronous result
- Transform an optional value
- Update a shared counter atomically
- Validate a required argument
Stream transformations
- Calculate several numeric stream statistics
- Check any and all stream elements
- Find the first matching stream value
- Flatten nested collections
- Group strings by their length
- Index records by a unique key
- Join transformed stream values
- Partition a collection by a predicate
- Take a page from a stream
- Transform each stream value
Strings
Text validation & formatting
- Build text efficiently in a loop
- Check a filename suffix
- Check a string prefix
- Count Unicode code points
- Extract successive regex matches
- Extract text between known positions
- Process the lines of an in-memory string
- Repeat text a fixed number of times
- Treat dynamic regex input as literal text
- Validate a complete identifier
HTML 125 snippets
Getting Started
- Create a complete HTML document
- Use headings to show document structure
- Separate prose into paragraphs
- Mark emphasis and importance
- Write an unordered list
- Write an ordered set of steps
- Link to a section on the same page
- Display reserved characters as text
- Display a short code sample
- Add a button with an explicit type
- Associate a text field with its label
- Require a form field
- Let a user choose a yes or no value
- Build a first radio-button group
- Provide a list of selectable options
- Accept several lines of text
- Give related form fields a shared title
- Create a small table with headers
- Use semantic page landmarks
- Add an expandable explanation
- Give a date a machine-readable value
- Show progress with a native element
- Attach a custom data attribute
- Describe terms in a definition list
- Declare the document language and encoding
Accessible structure
- Associate help text with an input
- Expose a disclosure button’s expanded state
- Give a section an accessible region name
- Identify a search region with the search element
- Identify the current page in a breadcrumb
- Keep a decorative icon out of a button’s name
- Mark a self-contained article
- Move focus to a heading without adding a tab stop
- Name complementary content
- Remove an inactive section from keyboard navigation
Data & disclosure
Document structure
Form behavior
- Associate a control outside the form element
- Choose a local file through a labeled control
- Collect several checked values under one name
- Disable a related group of controls
- Identify the selected submit action
- Include a nonvisible value in form data
- Keep an action button from submitting a form
- Make an unavailable select option unselectable
- Restore controls to their initial form defaults
- Submit a readonly value while preventing edits
Forms
Images & embedded documents
- Allow embedded scripts without granting same-origin access
- Block scripts in an embedded document
- Choose a different image for a small viewport
- Draw a basic rectangle on a labeled canvas
- Exclude a purely decorative image from accessible content
- Give an inline SVG an accessible name
- Keep an image and its visible caption together
- Name a meaningful image with alternative text
- Name a self-contained embedded document
- Reserve an image’s display dimensions
Input constraints
- Allow several selected options
- Constrain a calendar date input
- Limit a numeric input to an inclusive range
- Limit typed text to a maximum length
- Require a checkbox to be selected
- Require a nonempty text value
- Require numeric values on a chosen step
- Select a time in quarter-hour increments
- Validate a structured text identifier
- Validate the shape of an absolute URL
Links & accessibility
Metadata & document links
- Declare a preferred canonical URL
- Declare an indexing preference for a draft page
- Give a document a descriptive browser title
- Link a document’s alternate language version
- Mark the language of a phrase inside a page
- Offer a downloadable text file
- Provide a concise page description
- Resolve relative links against an explicit base
- Suggest a browser interface color
- Supply a title and URL for link previews
Native disclosure & dialogs
- Allow one disclosure in a named group to stay open
- Clone inert template content into the document
- Dismiss a modal with the Escape key
- Display a calculated form result
- Open and close a modal dialog
- Represent progress whose total is unknown
- Return a value from a dialog form
- Show the current value of a range input
- Start a disclosure open while keeping it collapsible
- Toggle a native popover from a button
Tables & list numbering
- Associate a data cell with explicit table headers
- Continue an ordered list at a chosen number
- Count an ordered list downward
- Identify headers for individual table rows
- Represent a hierarchy with nested lists
- Restart numbering at an individual list item
- Separate table headings data and totals
- Set consistent widths for table columns
- Span a group header across several rows
- Span one header across several columns
Text semantics
- Attach a pronunciation annotation to text
- Expand an abbreviation with explanatory text
- Highlight a relevant phrase in context
- Identify the title of a cited work
- Isolate a value with a different writing direction
- Mark a longer quotation and its source
- Mark a short quotation within a sentence
- Offer an optional break inside a long label
- Represent removed and inserted text
- Write subscripts and superscripts in ordinary text
JavaScript 125 snippets
Getting Started
- Run your first program
- Store a value in a named variable
- Name a value that stays fixed
- Calculate a simple total
- Divide using a fractional number
- Find what remains after division
- Compare a value with a limit
- Require two conditions to be true
- Choose between two branches
- Update a running count
- Handle three possible outcomes
- Repeat a fixed number of times
- Repeat while a condition holds
- Visit every item in a collection
- Count the items in a collection
- Read the first collection element
- Replace one collection element
- Measure a short text value
- Combine text with a name
- Read the beginning of a text value
- Read one character from ASCII text
- Call a library function
- Convert known numeric text to an integer
- Print a number with two decimal places
- Explain a calculation with a comment
Array restructuring
- Calculate differences between adjacent readings
- Concatenate arrays without mutating either input
- Create independent rows in a matrix
- Flatten a single nesting level
- Generate a bounded integer range
- Keep both matching and rejected values
- Map items to multiple output values
- Replace an array segment in place
- Reverse a copy while preserving the original
- Split an array into bounded batches
Array traversal & selection
- Check array membership with includes
- Check whether any item matches
- Check whether every item matches
- Copy a range without changing the source
- Find the first matching array item
- Find the position of a matching item
- Iterate with array indices and values
- Pair corresponding array items by position
- Read the final array item with a negative index
- Separate a first item from the remaining items
Arrays
Files & async
Numbers & numeric validation
- Calculate a page count with ceiling division
- Calculate integers beyond Number’s precise range
- Check whether a value is a safe integer
- Clamp a number between inclusive bounds
- Compare bounded floating-point results with a tolerance
- Convert between integer bases
- Detect NaN without converting the input
- Display a number with a fixed decimal width
- Drop the fractional part toward zero
- Validate a finite numeric value without coercion
Object behavior & collections
- Build an object from key-value entries
- Copy nested structured data independently
- Distinguish an own property from an inherited one
- Find members absent from another set
- Find shared members of two sets
- Group records into map entries
- List an object’s own enumerable keys
- Prevent runtime changes to top-level properties
- Read an object’s own enumerable values
- Remove a Map entry and detect whether it existed
Objects & JSON
Promises & iteration protocols
- Clean up a generator after an early break
- Consume an asynchronous sequence
- Delegate iteration to another iterable
- Inspect both successful and failed promise results
- Produce a lazy sequence with a generator
- Recover from an expected promise rejection
- Run cleanup after a promise settles
- Run dependent async steps in order
- Transform a resolved promise result
- Use the first fulfilled promise result
Regular expressions & URL encoding
- Build a URL query string from values
- Decode a percent-encoded URL component
- Extract all regex matches with their groups
- Inspect the parsed pieces of a URL
- Percent-encode one URL component
- Read named regex capture groups
- Reorder captured text in a replacement
- Resolve a relative URL against a base
- Split text on several separator characters
- Validate a whole ASCII identifier
Strings
Text handling & Unicode
- Check whether text ends with a suffix
- Check whether text starts with a prefix
- Compare canonically equivalent Unicode text
- Count Unicode code points in a string
- Extract text by start and end positions
- Extract the text after the last delimiter
- Normalize identifier case consistently
- Repeat a string a fixed number of times
- Transform each regex match with a callback
- Trim and discard blank lines
UTC date operations
- Add calendar days in UTC
- Construct a date from Unix seconds
- Convert epoch milliseconds to whole seconds
- Count days between UTC-midnight dates
- Detect an invalid Date object
- Find the final day of a month
- Format whole seconds as hours minutes and seconds
- Read an ISO-style weekday number
- Read date components in UTC
- Sort timestamp strings by their parsed instants
jQuery 125 snippets
Getting Started
- Run code after the document is ready
- Select an element by its ID
- Select all elements with a class
- Set text without interpreting HTML
- Read an element’s text
- Set an HTML attribute
- Set a boolean element property
- Set a text field’s value
- Read a text field’s value
- Add a CSS class
- Remove a CSS class
- Toggle a CSS class with a click
- Hide an element
- Show an element that was hidden
- Respond to a button click
- Respond while a user types
- Respond when a select value changes
- Append a safely constructed list item
- Insert a list item at the beginning
- Clear a container’s contents
- Remove one selected element
- Find descendants inside a container
- Visit matched elements in order
- Count matched elements
- Handle a form without navigating away
Animation completion
- Animate a numeric CSS property
- Animate relative to the current value
- Collapse a panel after an animation
- Disable animations for a reduced-motion mode
- Fade a hidden element into view
- Fade an element out and hide it
- Finish all queued animations immediately
- Reveal a collapsed panel with a slide
- Stop current animation and discard later work
- Wait until all selected elements finish animating
Collections & styling
- Apply classes from explicit Boolean state
- Check whether any selected element matches
- Combine two selections
- Exclude elements from a collection
- Filter parents containing a matching descendant
- Find an element’s position among siblings
- Measure content, padding, and borders separately
- Read an element’s document coordinates
- Set several inline styles together
- Transform a collection into a plain array
Deferred work & queues
- Expose observation without exposing resolution
- Inspect a deferred’s lifecycle state
- Observe completion of queued work
- Reject a deferred result
- Report progress before completion
- Resolve a deferred result
- Sequence work on an element’s queue
- Start a named queue explicitly
- Transform a deferred value with then
- Wait for several deferred values
DOM & classes
Event control
- Attach configuration when registering a handler
- Pass values through a custom event
- Prevent navigation from a handled link
- Read a handler result without event bubbling
- Read a selection when its change event fires
- Remove one handler without removing others
- Remove related events by namespace
- Respond to the Enter key
- Stop a child event from reaching its parent
- Validate a field when focus leaves it
Events
Form serialization & state
- Check native form validity before proceeding
- Collect repeated form field names
- Delete a cached data entry
- Distinguish current state from initial markup
- Refresh a cached data attribute deliberately
- Remove an optional attribute entirely
- Restore a form’s original default values
- Serialize successful controls for a URL-encoded request
- Set several selected options
- Store an object associated with an element
HTTP requests
- Attach an application-specific request header
- Cancel a pending request
- Fetch a plain-text resource
- Fetch and display JSON
- Handle a request timeout
- Handle an unsuccessful HTTP status
- Post a JSON request body
- Post URL-encoded form data
- Run cleanup after an AJAX failure
- Send query parameters as an object
Insertion & wrapping
- Clone markup without sharing its identity
- Insert a sibling after an element
- Insert a sibling before an element
- Insert an item at the beginning
- Move a node without losing its event handler
- Remove a wrapper while preserving its children
- Replace an element while preserving its position
- Wrap a collection in one shared parent
- Wrap each matched element separately
- Wrap only an element’s existing contents
Text & attributes
Traversal & selection
- Collect matching ancestors
- Filter a selection
- Find descendants
- Find the nearest matching ancestor
- Read checked options
- Return to the previous collection in a chain
- Select a range from a collection
- Select an element by zero-based position
- Select an immediate parent
- Select direct children without deeper descendants
- Select siblings up to a boundary
- Select siblings while excluding the current element
- Select the immediately following sibling
- Select the immediately preceding sibling
- Visit selected elements
CSS 125 snippets
Getting Started
- Write your first CSS rule
- Target an element by class
- Target a unique element by ID
- Give an element a background
- Set a readable font size
- Set space between text lines
- Add space inside a border
- Add space outside an element
- Draw a visible element border
- Round a panel’s corners
- Include padding in an element’s width
- Limit a content column’s width
- Align inline text in its container
- Underline meaningful text
- Choose a list-marker style
- Make an inline element a block
- Arrange children with flexbox
- Separate flex children with a gap
- Create two equal grid columns
- Reuse a CSS custom property
- Inherit a parent’s text color
- Understand later rules in the cascade
- Allow long content to scroll
- Apply a rule at a viewport breakpoint
- Make keyboard focus visible
Box dimensions & overflow
- Add inner spacing to a content-sized box
- Cap a box’s width
- Clip content that exceeds a fixed-height box
- Enforce a minimum width
- Hide an element while keeping its space
- Place fixed-size boxes on the same line
- Remove a hidden element’s layout space
- Reserve space for a visible border
- Size a child relative to its containing block
- Size a panel relative to viewport height
Flexbox alignment
- Align flex items at the main-axis end
- Allow a long flex child to shrink inside its container
- Change visual order without changing DOM order
- Give an item the remaining horizontal space
- Override cross-axis alignment for one item
- Prevent an item from shrinking
- Push flex items to opposite ends
- Push one flex item away from its siblings
- Specify a flex item’s initial main size
- Stack flex items vertically
Grid placement
- Align a nested grid with its parent’s columns
- Center a small item in a grid cell
- Combine a fixed sidebar with a flexible content track
- Describe a page arrangement with named grid areas
- Divide grid space in a chosen proportion
- Fill an earlier grid hole with a later small item
- Fill grid rows before moving to the next column
- Give implicit grid rows a minimum height
- Set explicit grid row heights
- Span a grid item across multiple columns
Interaction & themes
Interaction selectors
- Alternate row backgrounds with a structural selector
- Change a control’s appearance on hover
- Display a hint for a truly empty container
- Highlight a group containing keyboard focus
- Show a pressed pointer state
- Style a card based on a selected descendant
- Style a control that fails native validation
- Style content associated with a checked option
- Style placeholder text independently of entered text
- Visually distinguish a disabled control
Layout
Positioning & stacking
- Center a fixed-size absolute child with auto margins
- Choose which overlapping box receives a pointer
- Keep a child’s large z-index inside a stacking context
- Keep a control fixed to the viewport during scrolling
- Keep a section heading at a scrolling panel’s top
- Keep a tall section inside a local vertical scroller
- Move a box visually without changing its layout slot
- Position a badge relative to its container
- Position an item from the writing direction’s start edge
- Rotate a rectangular box around its center
Responsive conditions & sizing
- Adapt a component to its own container width
- Adapt a layout to viewport orientation
- Add a clear boundary in forced-colors mode
- Apply an enhancement only when a feature is supported
- Choose the smaller of a fixed and viewport-relative size
- Enhance a layout above a minimum viewport width
- Hide interface controls in print layout
- Keep a viewport-relative size above a minimum
- Provide a fallback for an unset custom property
- Scale a value from the root font size
Responsive design
Type & reading flow
- Add spacing between characters
- Align inline text to the container’s end edge
- Control tab width in preformatted content
- Display a label in uppercase without changing its text
- Increase spacing between words
- Lay out a short label in a vertical writing mode
- Preserve line breaks while collapsing repeated spaces
- Separate an underline from the text
- Set an explicit font weight
- Style supporting text in italics
Typography
Visual treatment & accessibility
- Add depth with a box shadow
- Align an image within its content box
- Allow pointer input to pass through a decorative overlay
- Control the size of a repeated background tile
- Fade an entire element and its descendants
- Fit an entire image inside a differently shaped box
- Keep a label available without occupying visible layout space
- Leave room above a scrolled-to heading
- Paint a gradient without an image file
- Round a box’s corners
TypeScript 125 snippets
Getting Started
- Run your first program
- Store a value in a named variable
- Name a value that stays fixed
- Calculate a simple total
- Divide using a fractional number
- Find what remains after division
- Compare a value with a limit
- Require two conditions to be true
- Choose between two branches
- Update a running count
- Handle three possible outcomes
- Repeat a fixed number of times
- Repeat while a condition holds
- Visit every item in a collection
- Count the items in a collection
- Read the first collection element
- Replace one collection element
- Measure a short text value
- Combine text with a name
- Read the beginning of a text value
- Read one character from ASCII text
- Call a library function
- Convert known numeric text to an integer
- Print a number with two decimal places
- Explain a calculation with a comment
Array restructuring
- Calculate differences between adjacent readings
- Concatenate arrays without mutating either input
- Create independent rows in a matrix
- Flatten a single nesting level
- Generate a bounded integer range
- Keep both matching and rejected values
- Map items to multiple output values
- Replace an array segment in place
- Reverse a copy while preserving the original
- Split an array into bounded batches
Array traversal & selection
- Check array membership with includes
- Check whether any item matches
- Check whether every item matches
- Copy a range without changing the source
- Find the first matching array item
- Find the position of a matching item
- Iterate with array indices and values
- Pair corresponding array items by position
- Read the final array item with a negative index
- Separate a first item from the remaining items
Collections & records
Numbers & numeric validation
- Calculate a page count with ceiling division
- Calculate integers beyond Number’s precise range
- Check whether a value is a safe integer
- Clamp a number between inclusive bounds
- Compare bounded floating-point results with a tolerance
- Convert between integer bases
- Detect NaN without converting the input
- Display a number with a fixed decimal width
- Drop the fractional part toward zero
- Validate a finite numeric value without coercion
Object behavior & collections
- Build an object from key-value entries
- Copy nested structured data independently
- Distinguish an own property from an inherited one
- Find members absent from another set
- Find shared members of two sets
- Group records into map entries
- List an object’s own enumerable keys
- Prevent runtime changes to top-level properties
- Read an object’s own enumerable values
- Remove a Map entry and detect whether it existed
Promises & iteration protocols
- Clean up a generator after an early break
- Consume an asynchronous sequence
- Delegate iteration to another iterable
- Inspect both successful and failed promise results
- Produce a lazy sequence with a generator
- Recover from an expected promise rejection
- Run cleanup after a promise settles
- Run dependent async steps in order
- Transform a resolved promise result
- Use the first fulfilled promise result
Regular expressions & URL encoding
- Build a URL query string from values
- Decode a percent-encoded URL component
- Extract all regex matches with their groups
- Inspect the parsed pieces of a URL
- Percent-encode one URL component
- Read named regex capture groups
- Reorder captured text in a replacement
- Resolve a relative URL against a base
- Split text on several separator characters
- Validate a whole ASCII identifier
Safe data handling
Text handling & Unicode
- Check whether text ends with a suffix
- Check whether text starts with a prefix
- Compare canonically equivalent Unicode text
- Count Unicode code points in a string
- Extract text by start and end positions
- Extract the text after the last delimiter
- Normalize identifier case consistently
- Repeat a string a fixed number of times
- Transform each regex match with a callback
- Trim and discard blank lines
Types & functions
UTC date operations
- Add calendar days in UTC
- Construct a date from Unix seconds
- Convert epoch milliseconds to whole seconds
- Count days between UTC-midnight dates
- Detect an invalid Date object
- Find the final day of a month
- Format whole seconds as hours minutes and seconds
- Read an ISO-style weekday number
- Read date components in UTC
- Sort timestamp strings by their parsed instants
Utilities & async
React 125 snippets
Getting Started
- Render your first React component
- Display a JavaScript value in JSX
- Calculate a value inside JSX
- Choose between two render branches
- Render an optional notice
- Render a list with stable keys
- Nest a reusable component
- Pass data through props
- Compose content through children
- Handle a button click
- Keep component state with useState
- Update state from its previous value
- Control a text input
- Control a checkbox
- Control a select element
- Handle a form without navigating
- Disable an unavailable action
- Assign a CSS class in JSX
- Pass an object to the style prop
- Group siblings with a fragment
- Supply a default prop value
- Render nothing from an optional component
- Update an object without mutating state
- Append to an array without mutating state
- Synchronize the document title with state
Accessibility & events
- Announce a status update politely
- Connect an invalid field to its explanation
- Describe an informative image
- Expose a disclosure’s expanded state
- Group related form controls semantically
- Handle an Escape key press
- Read a data attribute from the current target
- Render untrusted-looking input as literal text
- Stop an event from reaching a parent handler
Async work & status
- Combine independent asynchronous results
- Disable an action while it is pending
- Display the result of an asynchronous action
- Handle an asynchronous failure
- Ignore a result after its effect is cleaned up
- Inject a data loader into a component
- Keep only the latest requested result
- Offer a retry after a failed attempt
- Report partial success from multiple actions
Components & props
- Compose a component with named content slots
- Connect a reusable label using useId
- Customize a renderer through a function prop
- Destructure nested data in a component
- Forward input props to a reusable field
- Notify a parent with a callback prop
- Pass an input ref as a React 19 prop
- Reset child state by changing its key
- Select a component variant explicitly
Context & shared state
- Choose labels from a language context
- Override context in a nested section
- Provide read-only application configuration
- Read a value from context
- Separate state and dispatch contexts
- Update state shared through context
- Use a context’s fallback value
- Use React 19’s provider shorthand
- Validate access through a custom context hook
Custom hooks
- Delay publishing a rapidly changing value
- Encapsulate increment and reset operations
- Expose immutable collection operations
- Extract reusable toggle behavior
- Keep separate state for separate hook calls
- Reset state to a caller-provided initial value
- Reuse controlled-input bindings
- Reuse document-title synchronization
- Reuse event subscription cleanup
Effects & lifecycle
- Cancel an asynchronous operation on unmount
- Clean up a subscription when a child unmounts
- Measure an element after layout
- Rerun an effect when its dependency changes
- Restore the previous document title
- Schedule a one-time update with cleanup
- Skip synchronization when a feature is disabled
- Subscribe to and clean up a window event
- Update repeatedly with a cleaned-up interval
Forms & validation
- Collect selected options from a multi-select
- Control a multiline text field
- Control a radio-button group
- Keep numeric input text until conversion
- Read an uncontrolled form with FormData
- Reset controlled form state
- Show a field-specific validation message
- Track whether a form differs from its initial value
- Use native required-field validation
Lists & filtering
- Display a slice of paginated data
- Filter a list by a search term
- Preserve item state while reordering by key
- Render a helpful empty state
- Render a semantic data table
- Render nested groups with stable keys
- Show the count of matching records
- Sort a copy without mutating the original list
- Track selection by a stable identifier
Performance & rendering
- Defer the value used by a result panel
- Keep a callback stable between renders
- Mark a nonurgent state update as a transition
- Memoize a component with stable props
- Memoize a derived collection
- Memoize a sorted copy of state
- Memoize an object passed to a provider
- Mount expensive content only when requested
- Render a bounded preview of a long list
- Subscribe to a small external store safely
Refs & DOM interaction
- Focus an input through a ref
- Keep a mutable value without rendering on each write
- Observe when a DOM node is attached
- Open and close a native dialog
- Read an uncontrolled field through a ref
- Remember the previously committed value
- Scroll a referenced element into view
- Select the contents of an input
- Store and cancel a timer handle
State & reducers
Angular 125 snippets
Getting Started
- Bootstrap your first standalone Angular component
- Display a component field with interpolation
- Calculate a value in a template
- Bind an element property
- Bind an accessibility attribute
- Toggle a CSS class from component state
- Bind a numeric style with units
- Handle a button click
- Store reactive state in a signal
- Derive a value with computed
- Render a conditional branch with @if
- Render a list with @for and stable tracking
- Provide an @empty list state
- Choose template content with @switch
- Call a component method from an event
- Read an input through a template reference
- Bind a text field in both directions
- Bind a checkbox with ngModel
- Bind a select element
- Render a child standalone component
- Pass a value to a signal input
- Handle an event emitted by a child
- Format text through a built-in pipe
- Project content into a reusable component
- Inject a service into a component
Accessibility & reusable patterns
- Announce a status update with a live region
- Associate a validation message with a field
- Display untrusted-looking text without HTML execution
- Expose a disclosure’s expanded state
- Group related controls with a fieldset and legend
- Keep a secondary button from submitting a form
- Preserve input state when tracked records reorder
- Provide alternative text for an informative image
- Render a table with accessible headers
- Show a bounded preview and remaining count
Components & communication
Events & DOM interaction
- Control a native dialog through a reference
- Focus an input through its template reference
- Handle Escape to dismiss a panel
- Handle the Enter key specifically
- Prevent a link’s default navigation
- Read a DOM element through a viewChild signal
- Read a typed input event
- Stop a nested click from reaching its parent
- Validate a field when focus leaves it
Lifecycle & observable data
- Combine the latest values from observables
- Filter observable emissions
- Initialize component data with ngOnInit
- Measure a node after the first render
- Publish updated state through a BehaviorSubject
- Register cleanup through DestroyRef
- Render an observable with AsyncPipe
- Tie a subscription’s lifetime to its component
- Transform an observable value
Lists & control flow
- Bind a narrowed value using an @if alias
- Expose the current index in @for
- Filter a signal-backed list
- Page through a collection
- Remove a list item by identifier
- Render groups with nested loops
- Sort a derived copy of a collection
- Style the first and last list items
- Track a selected record by its identifier
Pipes & formatting
- Capitalize words with TitleCasePipe
- Create a small pure formatting pipe
- Display a bounded slice of a list
- Format a date in an explicit timezone
- Format a fractional value as a percentage
- Format a number with fixed decimal places
- Format an amount in a selected currency
- Format text in lowercase
- Inspect structured data with JsonPipe
Reactive forms
- Append a dynamic form control
- Attach validators to a FormControl
- Bind a typed nonnullable FormControl
- Disable a control through its model
- Display a specific reactive validation error
- Group related typed controls
- Patch part of a reactive form
- Reset a nonnullable control to its initial value
- Set a control value programmatically
Services & dependency injection
- Centralize a reusable validation rule
- Collect multiple values through a multi provider
- Create a dependency with a provider factory
- Derive totals inside a shared service
- Expose service state through a read-only signal
- Handle an optional dependency
- Provide a configuration value with a token
- Replace a service implementation with useClass
- Share signal state through an injected service
Signals & state
- Append to an array signal immutably
- Choose an equality function for signal values
- Derive a filtered list with computed
- Expose a read-only signal view
- Replace a signal’s value explicitly
- Replace an object signal immutably
- Synchronize a document property with an effect
- Track only dependencies used by a computed branch
- Update a signal from its previous value
Template-driven forms
- Bind a multiline notes field
- Bind a numeric input value
- Bind a radio-button group
- Enable saving only after a field changes
- Expose a required field’s validity
- Handle a template-driven form submission
- Require a minimum text length
- Reset a template-driven form
- Validate email syntax with Angular’s email validator
Templates & bindings
Linux Commands 125 snippets
Getting Started
- Print a first terminal message
- Print separate arguments safely
- Keep spaces inside one argument
- Store and expand a shell variable
- Prevent expansion with single quotes
- Create a practice directory
- Enter and leave a practice directory
- Write text to a new practice file
- Append a line to a practice file
- Make a second copy of a practice file
- Rename a practice file
- Create an empty practice file
- Send command output into another command
- Read the beginning of piped text
- Read the end of piped text
- Sort a small set of lines
- Remove adjacent duplicate lines
- Extract a field from simple delimited text
- Filter lines by literal text
- Replace text in a pipeline
- Count newline-terminated records
- Check whether two practice files match
- Read the filename portion of a path
- Read the directory portion of a path
- Branch on a command’s exit status
Archive integrity & packaging
- Append a new member to an uncompressed tar
- Archive filenames safely with null delimiters
- Check the integrity of a gzip stream
- Compress a stream to a chosen filename
- Create an archive from an explicit file list
- Exclude generated files from an archive
- Read concatenated gzip members
- Read one archived file to standard output
- Remove a leading directory while extracting
- Verify a file against a checksum manifest
Archives & checksums
Dates & process utilities
- Add calendar days with GNU date
- Bound a command execution time
- Convert a Unix timestamp to UTC
- Copy a file with explicit permissions
- Format a known UTC timestamp
- Format a zero-padded numeric label
- Generate a stepped sequence
- Pass a variable to one command
- Read an ISO week date
- Start a command with a minimal environment
Files & folders
Files & permissions
- Copy a directory while preserving attributes
- Create a second name for the same file
- Create an empty file
- Create private files with a restrictive umask
- Handle a filename that begins with a dash
- Make a script executable by its owner
- Read the target stored in a symbolic link
- Remove an empty directory only
- Rename a file with mv
- Set owner-only file permissions
Finding & selecting files
- Exclude a directory from a recursive search
- Extract a filename from a path
- Extract a parent directory from a path
- Find empty regular files
- Find files larger than a byte threshold
- Limit a search to the immediate directory
- Match filenames without case sensitivity
- Normalize a path without requiring it to exist
- Pass filenames with spaces through xargs
- Run a command safely for each matching file
Searching text
Sorting & joining records
- Check whether a file is already sorted
- Count repeated lines after sorting
- Find lines common to two sorted files
- Find lines unique to the first sorted file
- Join two sorted files by a shared key
- Print only duplicate values
- Sort lines by numeric value
- Sort records by a delimited field
- Sort values in descending order
- Sort version-like labels naturally
Streams & byte tools
- Append a stream to a log file
- Count bytes in a file
- Count whitespace-separated words
- Encode and decode a file with Base64
- Inspect bytes as hexadecimal values
- Read a byte prefix
- Read a byte suffix
- Save a stream while displaying it
- Set a file to a specific byte length
- Split a file into fixed line-count pieces
System information
Text processing
Transforming text
- Collapse repeated spaces
- Convert tab stops to spaces
- Extract a delimited text column
- Join lines from two files side by side
- Print a selected range of lines
- Print the final lines of a file
- Remove blank or whitespace-only lines
- Remove carriage-return characters
- Reorder fields with a capture group
- Translate ASCII lowercase letters to uppercase
Bash Scripts 125 snippets
Getting Started
- Write and run a first Bash script
- Store text in a variable
- Declare a fixed configuration value
- Calculate with integer arithmetic
- Increase an integer variable
- Use a fallback for an unset variable
- Read the length of an ASCII string
- Read part of a shell string
- Replace text with parameter expansion
- Choose between two script branches
- Compare two text values
- Choose an action with case
- Repeat a command for several words
- Use a counted Bash loop
- Count down with a while loop
- Store and iterate over an array
- Count array elements
- Read the first array element
- Define and call a shell function
- Limit a beginner function variable to local scope
- Capture a command’s output
- Read a line without losing backslashes
- Write several literal lines
- Read positional parameters in a function
- Test a function’s success status
Arguments & decisions
- Choose among several numeric ranges
- Classify a filename with shell patterns
- Compare a value literally inside a conditional
- Consume positional arguments one at a time
- Forward all arguments without changing their boundaries
- Parse a small set of long options
- Repeat until a condition becomes true
- Skip selected iterations in a loop
- Stop a search loop at the first match
- Validate the number of positional arguments
Array operations
- Append several items to an array
- Check exact array membership
- Copy an array independently
- Count the elements in an array
- Join array items with a one-character separator
- Prepend items while preserving existing array values
- Read an optional associative-array entry
- Remove an indexed element and compact the array
- Select a range of array elements
- Visit associative-array keys in a stable order
Diagnostics & defensive scripting
- Check a script’s syntax without executing its body
- Check for an installed command
- Check whether a function has been defined
- Check whether a variable exists under nounset
- Distinguish an empty input line from end of input
- Identify whether a name resolves to a builtin
- Inspect every command status in a pipeline
- Prevent a variable value from expanding as a filename pattern
- Refuse to overwrite an existing file with redirection
- Reject a missing required configuration value
Files & reliability
Function scope & composition
- Capture output while handling a failed command
- Give a function its own positional parameters
- Isolate variable changes in a subshell
- Keep a function variable local
- Load functions from a trusted local script
- Observe command substitution’s trailing-newline removal
- Return a value through a named output variable
- Return an array through a nameref
- Use a function’s exit status as a boolean result
- Use a recursive function for a bounded calculation
Functions & arguments
Input streams & redirection
- Capture standard output and standard error separately
- Compare two generated sorted streams
- Pass a variable to standard input
- Read complete lines into an array
- Read from a dedicated file descriptor
- Read null-delimited filenames into an array
- Redirect an entire group of commands
- Substitute values into a multiline template
- Write a literal multiline block
- Write several messages through one file descriptor
Loops & decisions
Parameter expansion
- Assign a default to an empty or unset variable
- Convert a variable to uppercase
- Distinguish unset variables from empty strings
- Extract a basename without an external process
- Extract a parent path with parameter expansion
- Extract a substring by offset and length
- Read a string’s character length
- Read a variable whose name is stored in another variable
- Remove a known prefix with a shell pattern
- Use an alternate value only when a variable is nonempty
Processes & environment
- Change directory only for one operation
- Collect two independent background results
- Export a value to child processes
- Handle a nonzero background-job exit
- Keep loop state by avoiding a pipeline subshell
- Preserve a failure status while an EXIT trap runs
- Remove a variable from one child’s environment
- Set an environment value for one child command
- Stop a child process created by the script
- Wait for a background job before reading its output
Text parsing & arithmetic
- Clamp a numeric setting to a valid range
- Format a numeric label with leading zeroes
- Increment a counter without an unexpected errexit
- Parse digits with leading zeroes as decimal
- Print text containing percent characters literally
- Read fields captured by a Bash regular expression
- Remove a trailing carriage return from a line
- Set and clear a bit in a shell integer
- Split a record while retaining its remainder
- Test numeric divisibility with a remainder
Variables & text
PowerShell 125 snippets
Getting Started
- Run a first PowerShell statement
- Assign a value to a variable
- Insert a variable into a string
- Keep a dollar sign literal
- Calculate a simple total
- Compare a value with a limit
- Combine conditions with and
- Create an array of text values
- Count array elements
- Read a collection element
- Process every array element
- Use a counted loop
- Repeat while a condition holds
- Filter pipeline values
- Transform each pipeline value
- Sort a sequence of numbers
- Select the first pipeline values
- Read a value from a hashtable
- Create an object with named properties
- Define a function with a parameter
- Join an array into text
- Split simple delimited text
- Replace a literal word in text
- Create a portable relative path
- Handle an expected terminating error
Array operations
- Append an item to a small array
- Build a mutable generic list
- Count a result even when it is empty or has one item
- Find the index of an array item
- Pair corresponding values from two arrays
- Read the last array element
- Reverse a copy while preserving the source
- Select elements by an index range
- Split an array into fixed-size batches
- Test whether an array contains a value
Collections & objects
Commands & execution context
- Capture a command’s success-stream output
- Check an external process exit status explicitly
- Check whether a command can be resolved
- Discard incidental output from a setup command
- Inspect a URI through typed properties
- Pass an environment value to a child process
- Read named fields from a successful regex match
- Read the kind of command being invoked
- Restore an environment value after temporary use
- Restore the working location after an operation
Dates & numeric validation
- Clamp a number to inclusive bounds
- Compute beyond the fixed-width integer range
- Convert Unix seconds into an aware UTC timestamp
- Count days between calendar dates
- Find the number of days in a month
- Format a bounded duration as hours minutes and seconds
- Parse a hexadecimal integer
- Parse an integer without throwing on invalid input
- Reject NaN and infinite values
- Round a decimal with a chosen midpoint rule
File operations & integrity
- Append a line while keeping earlier content
- Calculate a file’s SHA-256 digest
- Copy a file to a chosen destination
- Delete only a named scratch file
- Distinguish a file from a directory
- Find matching files recursively
- Move a file into another directory
- Read a file lazily through the .NET line iterator
- Read a file size in bytes
- Rename a file in its current directory
Files & paths
Functions & control
Functions & parameter validation
- Accept one typed value at a time from a pipeline
- Accumulate pipeline input across begin process and end
- Dispatch values with wildcard patterns
- Enforce a numeric range at a function boundary
- Keep function-local assignments separate from caller state
- Pass a block of behavior as an argument
- Preserve a failure after local cleanup
- Restrict a function parameter to known choices
- Return a collection as one pipeline object
- Run cleanup after a caught exception
Hashtables & object records
- Add a calculated property during selection
- Check for a hashtable key before reading it
- Construct a record with named properties
- Convert an object’s properties into a hashtable
- Enumerate hashtable entries in a stable order
- Find differences between two collections
- Merge configuration maps with override precedence
- Preserve key insertion order
- Remove an optional hashtable entry
- Use a fallback for a missing hashtable entry
Strings & literal text
- Check a string prefix using ordinal comparison
- Check a suffix without case sensitivity
- Extract a known substring
- Insert values into a multiline template
- Join several strings with a separator
- Pad a label with leading zeroes
- Split text on a simple delimiter
- Trim whitespace around a string
- Use a literal value in a regular expression
- Write a multiline string without expanding variables
Structured formats & encodings
- Convert between hexadecimal text and bytes
- Encode and decode UTF-8 text with Base64
- Escape a single URL parameter value
- Escape plain text before placing it in HTML
- Handle a malformed JSON document
- Read a tab-separated table
- Read a value from a trusted XML document
- Read JSON into a hashtable
- Serialize nested objects with an explicit depth
- Write object records to a CSV file
Text & data
Docker / Compose 125 snippets
Getting Started
- Run your first disposable container
- Choose the command a container executes
- Pass a named configuration value
- Set a container’s working directory
- Run a process as an unprivileged user
- Disable networking for a local command
- Run with a read-only container filesystem
- Give a read-only container temporary storage
- Set an example container hostname
- Send text into a container through stdin
- Attach a descriptive label to a container
- Inspect the configured container command
- Read a completed example’s output
- Inspect a completed container’s exit code
- Drop Linux capabilities for a simple command
- Build an image with a default command
- Choose an image’s default directory
- Set a default non-root image user
- Create a small file at build time
- Separate an executable from default arguments
- Define a first Compose service
- Set a service’s working directory
- Run a Compose service as a numeric user
- Make a Compose service’s filesystem read-only
- Disable networking for a Compose command
Build images
Compose applications
Compose service options
- Add a fixed hostname mapping
- Choose a service’s internal hostname
- Disable a service’s network interfaces
- Drop capabilities for a Compose service
- Enable an init process for a service
- Give a read-only service writable scratch space
- Load service variables from an env file
- Mount a local input directory with long syntax
- Override an env-file value explicitly
- Override the image entrypoint in Compose
- Pass dollar expressions through Compose
- Protect a Compose service’s root filesystem
- Read a secret from a mounted file
- Run a Compose service as a non-root user
- Set a Compose service’s working directory
- Set a service’s open-file limit
- Set no-new-privileges in Compose
- Supply a default for an unset Compose variable
- Supply a non-secret configuration file
- Wait for a healthy Compose dependency
Container commands
Container lifecycle
- Find a named container in the created state
- Force a disposable container to stop
- Inspect the exit code of a completed process
- List only containers belonging to a label
- Rename a container without recreating it
- Restart an existing container
- Start an existing container and attach to its output
- Stop a running container gracefully
- Verify that a one-off container was removed
- Wait for a container to exit
Dockerfile patterns
- Choose Bash with pipefail for build commands
- Combine a stable entrypoint with default arguments
- Copy a directory’s contents into an image
- Copy an artifact from an earlier build stage
- Create a runtime file during the build
- Exclude files from the build context
- Keep exec-form arguments literal
- Prepare an owned directory before dropping root
- Set copied files’ numeric ownership
- Use a build argument while creating an image
Execution & file transfer
- Copy a file into a created container
- Inspect changes to a container’s writable layer
- Load environment variables from a file
- Override an image’s entrypoint at runtime
- Override the process working directory
- Pipe input into a container process
- Retrieve a file from a stopped container
- Run a one-off process with a numeric user ID
- Set a container’s own hostname
- Supply an environment variable to an exec process
Image management
- Check that an image has layer history
- Export a container filesystem into a new image
- Give an existing image another tag
- Inspect the operating system recorded in an image
- List a specific image reference
- Read an image’s default command
- Remove one tag while retaining another reference
- Require a locally available image
- Run an image by its local immutable ID
- Save and reload an image archive
Limits & process security
- Choose the signal used for graceful stopping
- Configure bounded retries after a failure
- Confirm the root filesystem rejects writes
- Drop all optional Linux capabilities
- Insert Docker’s small init process
- Limit the number of container processes
- Prevent gaining privileges through exec
- Set and inspect a fractional CPU limit
- Set the open-file limit for a process
- Wait for an actual container health check
Networks & volume metadata
- Assign a network-scoped alias
- Attach an existing container to another network
- Create a network marked for internal connectivity
- Inspect a user-defined network’s driver
- Keep scratch data only for the container lifetime
- Label a volume with its purpose
- List only volumes matching a label
- Remove one network attachment
- Resolve a peer’s name on a user-defined network
- Verify a read-only volume rejects writes
Storage & isolation
SQL 125 snippets
Getting Started
- Run a first SELECT query
- Calculate a value with SELECT
- Give a result column a readable name
- Create a table and insert its first row
- Read named columns from a table
- Keep rows matching a condition
- Filter by a numeric comparison
- Require two filtering conditions
- Accept either of two conditions
- Match one value from a short list
- Select values in an inclusive range
- Match a text prefix
- Find missing values with IS NULL
- Display a fallback for missing data
- Sort the highest quantities first
- Remove duplicate result values
- Count the rows in a table
- Add values across several rows
- Read the smallest and largest values
- Calculate a total for each group
- Filter groups after aggregation
- Turn a condition into a result label
- Update one row using its primary key
- Delete one row from a practice table
- Join related rows from two tables
Bulk changes & set operations
- Combine results while retaining duplicates
- Copy selected rows into another table
- Delete rows selected by a related table
- Find rows in the first result but not the second
- Find rows shared by two query results
- Increment a stored value in the database
- Insert only keys absent from a destination
- Remove duplicate values while keeping the smallest key
- Update rows selected by a related table
- Update several classifications in one statement
Change & combine data
Constraints & defaults
- Apply a default when an insert omits a column
- Block deletion of a referenced parent
- Enforce a bounded numeric range
- Keep children while clearing a deleted relationship
- Make a pair of columns unique together
- Reference a parent identified by two columns
- Reject a negative quantity with CHECK
- Reject duplicate business identifiers
- Remove dependent rows with a declared cascade
- Require a value with NOT NULL
Expressions & aggregates
Joins & subqueries
Relationships & missing data
- Find parents whose every child meets a rule
- Find parents with at least two child rows
- Find records without any related rows
- Generate every combination of two sets
- Include zero counts for missing relationships
- Join a parent to pre-aggregated totals
- Join through a lookup table
- Keep parent rows while filtering joined children
- List unordered pairs without duplicate reversals
- Pair employees with their managers
Reporting & grouped calculations
- Calculate each group’s integer percentage of the total
- Calculate each group’s numeric spread
- Compute an integer weighted average
- Count distinct values within a result
- Count rows satisfying separate conditions
- Distinguish row count from non-null value count
- Filter rows before grouping
- Group by more than one field
- Return zero for a sum over no rows
- Turn known group values into columns
Schema design & transactions
- Add an optional field to an existing table
- Commit multiple related changes together
- Create an index for an equality filter
- Create an index matching filter and ordering columns
- Enforce a relationship between two columns
- Enforce uniqueness with a dedicated index
- Expose a reusable filtered view
- Read updated base-table values through a view
- Undo a multi-row transfer atomically
- Undo only the work after a savepoint
Select & filter
Subqueries & ranked selection
- Attach an overall count to every row
- Build a query from several named stages
- Compare a row with its own group average
- Find the second-highest distinct value
- Include every row tied for the highest score
- Include missing values in a not-equal filter
- Read a page after a known unique key
- Report duplicate business values and their frequency
- Return all rows tied for the maximum in a group
- Sort preferred rows ahead of other rows
Text cleanup & matching
- Combine text values with a separator
- Match a known text prefix
- Measure the length of ordinary text
- Normalize ASCII text to lowercase
- Normalize ASCII text to uppercase
- Place missing values after known values portably
- Remove surrounding spaces from text
- Replace a literal substring
- Search for a literal LIKE wildcard
- Treat an empty trimmed value as missing
Window analytics
- Calculate a cumulative integer percentage
- Divide an ordered result into numbered buckets
- Rank tied scores with competition gaps
- Rank tied scores without gaps
- Read the last value of the complete partition
- Read the next row’s value
- Repeat the first ordered value beside each row
- Select the top row in each group with a tie-breaker
- Show a group total beside each detail row
- Sum a row and its immediate predecessor
SQL Server 125 snippets
Getting Started
- Run a first SELECT query
- Calculate a value with SELECT
- Give a result column a readable name
- Create a table and insert its first row
- Read named columns from a table
- Keep rows matching a condition
- Filter by a numeric comparison
- Require two filtering conditions
- Accept either of two conditions
- Match one value from a short list
- Select values in an inclusive range
- Match a text prefix
- Find missing values with IS NULL
- Display a fallback for missing data
- Sort the highest quantities first
- Remove duplicate result values
- Count the rows in a table
- Add values across several rows
- Read the smallest and largest values
- Calculate a total for each group
- Filter groups after aggregation
- Turn a condition into a result label
- Update one row using its primary key
- Delete one row from a practice table
- Join related rows from two tables
Bulk changes & set operations
- Combine results while retaining duplicates
- Copy selected rows into another table
- Delete rows selected by a related table
- Find rows in the first result but not the second
- Find rows shared by two query results
- Increment a stored value in the database
- Insert only keys absent from a destination
- Remove duplicate values while keeping the smallest key
- Update rows selected by a related table
- Update several classifications in one statement
Constraints & defaults
- Apply a default when an insert omits a column
- Block deletion of a referenced parent
- Enforce a bounded numeric range
- Keep children while clearing a deleted relationship
- Make a pair of columns unique together
- Reference a parent identified by two columns
- Reject a negative quantity with CHECK
- Reject duplicate business identifiers
- Remove dependent rows with a declared cascade
- Require a value with NOT NULL
Dates & text
JSON & results
Relationships & missing data
- Find parents whose every child meets a rule
- Find parents with at least two child rows
- Find records without any related rows
- Generate every combination of two sets
- Include zero counts for missing relationships
- Join a parent to pre-aggregated totals
- Join through a lookup table
- Keep parent rows while filtering joined children
- List unordered pairs without duplicate reversals
- Pair employees with their managers
Reporting & grouped calculations
- Calculate each group’s integer percentage of the total
- Calculate each group’s numeric spread
- Compute an integer weighted average
- Count distinct values within a result
- Count rows satisfying separate conditions
- Distinguish row count from non-null value count
- Filter rows before grouping
- Group by more than one field
- Return zero for a sum over no rows
- Turn known group values into columns
Schema design & transactions
- Add an optional field to an existing table
- Commit multiple related changes together
- Create an index for an equality filter
- Create an index matching filter and ordering columns
- Enforce a relationship between two columns
- Enforce uniqueness with a dedicated index
- Expose a reusable filtered view
- Read updated base-table values through a view
- Undo a multi-row transfer atomically
- Undo only the work after a savepoint
Select & page
Subqueries & ranked selection
- Attach an overall count to every row
- Build a query from several named stages
- Compare a row with its own group average
- Find the second-highest distinct value
- Include every row tied for the highest score
- Include missing values in a not-equal filter
- Read a page after a known unique key
- Report duplicate business values and their frequency
- Return all rows tied for the maximum in a group
- Sort preferred rows ahead of other rows
Text cleanup & matching
- Combine text values with a separator
- Match a known text prefix
- Measure the length of ordinary text
- Normalize ASCII text to lowercase
- Normalize ASCII text to uppercase
- Place missing values after known values portably
- Remove surrounding spaces from text
- Replace a literal substring
- Search for a literal LIKE wildcard
- Treat an empty trimmed value as missing
Transactions & tables
Window analytics
- Calculate a cumulative integer percentage
- Divide an ordered result into numbered buckets
- Rank tied scores with competition gaps
- Rank tied scores without gaps
- Read the last value of the complete partition
- Read the next row’s value
- Repeat the first ordered value beside each row
- Select the top row in each group with a tie-breaker
- Show a group total beside each detail row
- Sum a row and its immediate predecessor
Postgres 125 snippets
Getting Started
- Run a first SELECT query
- Calculate a value with SELECT
- Give a result column a readable name
- Create a table and insert its first row
- Read named columns from a table
- Keep rows matching a condition
- Filter by a numeric comparison
- Require two filtering conditions
- Accept either of two conditions
- Match one value from a short list
- Select values in an inclusive range
- Match a text prefix
- Find missing values with IS NULL
- Display a fallback for missing data
- Sort the highest quantities first
- Remove duplicate result values
- Count the rows in a table
- Add values across several rows
- Read the smallest and largest values
- Calculate a total for each group
- Filter groups after aggregation
- Turn a condition into a result label
- Update one row using its primary key
- Delete one row from a practice table
- Join related rows from two tables
Bulk changes & set operations
- Combine results while retaining duplicates
- Copy selected rows into another table
- Delete rows selected by a related table
- Find rows in the first result but not the second
- Find rows shared by two query results
- Increment a stored value in the database
- Insert only keys absent from a destination
- Remove duplicate values while keeping the smallest key
- Update rows selected by a related table
- Update several classifications in one statement
Constraints & defaults
- Apply a default when an insert omits a column
- Block deletion of a referenced parent
- Enforce a bounded numeric range
- Keep children while clearing a deleted relationship
- Make a pair of columns unique together
- Reference a parent identified by two columns
- Reject a negative quantity with CHECK
- Reject duplicate business identifiers
- Remove dependent rows with a declared cascade
- Require a value with NOT NULL
Dates & series
JSON & arrays
Relationships & missing data
- Find parents whose every child meets a rule
- Find parents with at least two child rows
- Find records without any related rows
- Generate every combination of two sets
- Include zero counts for missing relationships
- Join a parent to pre-aggregated totals
- Join through a lookup table
- Keep parent rows while filtering joined children
- List unordered pairs without duplicate reversals
- Pair employees with their managers
Reporting & grouped calculations
- Calculate each group’s integer percentage of the total
- Calculate each group’s numeric spread
- Compute an integer weighted average
- Count distinct values within a result
- Count rows satisfying separate conditions
- Distinguish row count from non-null value count
- Filter rows before grouping
- Group by more than one field
- Return zero for a sum over no rows
- Turn known group values into columns
Rows & writes
Schema design & transactions
- Add an optional field to an existing table
- Commit multiple related changes together
- Create an index for an equality filter
- Create an index matching filter and ordering columns
- Enforce a relationship between two columns
- Enforce uniqueness with a dedicated index
- Expose a reusable filtered view
- Read updated base-table values through a view
- Undo a multi-row transfer atomically
- Undo only the work after a savepoint
Subqueries & ranked selection
- Attach an overall count to every row
- Build a query from several named stages
- Compare a row with its own group average
- Find the second-highest distinct value
- Include every row tied for the highest score
- Include missing values in a not-equal filter
- Read a page after a known unique key
- Report duplicate business values and their frequency
- Return all rows tied for the maximum in a group
- Sort preferred rows ahead of other rows
Text cleanup & matching
- Combine text values with a separator
- Match a known text prefix
- Measure the length of ordinary text
- Normalize ASCII text to lowercase
- Normalize ASCII text to uppercase
- Place missing values after known values portably
- Remove surrounding spaces from text
- Replace a literal substring
- Search for a literal LIKE wildcard
- Treat an empty trimmed value as missing
Window analytics
- Calculate a cumulative integer percentage
- Divide an ordered result into numbered buckets
- Rank tied scores with competition gaps
- Rank tied scores without gaps
- Read the last value of the complete partition
- Read the next row’s value
- Repeat the first ordered value beside each row
- Select the top row in each group with a tie-breaker
- Show a group total beside each detail row
- Sum a row and its immediate predecessor
Windows & text
SQLite 125 snippets
Getting Started
- Run a first SELECT query
- Calculate a value with SELECT
- Give a result column a readable name
- Create a table and insert its first row
- Read named columns from a table
- Keep rows matching a condition
- Filter by a numeric comparison
- Require two filtering conditions
- Accept either of two conditions
- Match one value from a short list
- Select values in an inclusive range
- Match a text prefix
- Find missing values with IS NULL
- Display a fallback for missing data
- Sort the highest quantities first
- Remove duplicate result values
- Count the rows in a table
- Add values across several rows
- Read the smallest and largest values
- Calculate a total for each group
- Filter groups after aggregation
- Turn a condition into a result label
- Update one row using its primary key
- Delete one row from a practice table
- Join related rows from two tables
Bulk changes & set operations
- Combine results while retaining duplicates
- Copy selected rows into another table
- Delete rows selected by a related table
- Find rows in the first result but not the second
- Find rows shared by two query results
- Increment a stored value in the database
- Insert only keys absent from a destination
- Remove duplicate values while keeping the smallest key
- Update rows selected by a related table
- Update several classifications in one statement
Constraints & defaults
- Apply a default when an insert omits a column
- Block deletion of a referenced parent
- Enforce a bounded numeric range
- Keep children while clearing a deleted relationship
- Make a pair of columns unique together
- Reference a parent identified by two columns
- Reject a negative quantity with CHECK
- Reject duplicate business identifiers
- Remove dependent rows with a declared cascade
- Require a value with NOT NULL
Dates & time
JSON data
Queries & text
Relationships & missing data
- Find parents whose every child meets a rule
- Find parents with at least two child rows
- Find records without any related rows
- Generate every combination of two sets
- Include zero counts for missing relationships
- Join a parent to pre-aggregated totals
- Join through a lookup table
- Keep parent rows while filtering joined children
- List unordered pairs without duplicate reversals
- Pair employees with their managers
Reporting & grouped calculations
- Calculate each group’s integer percentage of the total
- Calculate each group’s numeric spread
- Compute an integer weighted average
- Count distinct values within a result
- Count rows satisfying separate conditions
- Distinguish row count from non-null value count
- Filter rows before grouping
- Group by more than one field
- Return zero for a sum over no rows
- Turn known group values into columns
Schema design & transactions
- Add an optional field to an existing table
- Commit multiple related changes together
- Create an index for an equality filter
- Create an index matching filter and ordering columns
- Enforce a relationship between two columns
- Enforce uniqueness with a dedicated index
- Expose a reusable filtered view
- Read updated base-table values through a view
- Undo a multi-row transfer atomically
- Undo only the work after a savepoint
Subqueries & ranked selection
- Attach an overall count to every row
- Build a query from several named stages
- Compare a row with its own group average
- Find the second-highest distinct value
- Include every row tied for the highest score
- Include missing values in a not-equal filter
- Read a page after a known unique key
- Report duplicate business values and their frequency
- Return all rows tied for the maximum in a group
- Sort preferred rows ahead of other rows
Tables & writes
Text cleanup & matching
- Combine text values with a separator
- Match a known text prefix
- Measure the length of ordinary text
- Normalize ASCII text to lowercase
- Normalize ASCII text to uppercase
- Place missing values after known values portably
- Remove surrounding spaces from text
- Replace a literal substring
- Search for a literal LIKE wildcard
- Treat an empty trimmed value as missing
Window analytics
- Calculate a cumulative integer percentage
- Divide an ordered result into numbered buckets
- Rank tied scores with competition gaps
- Rank tied scores without gaps
- Read the last value of the complete partition
- Read the next row’s value
- Repeat the first ordered value beside each row
- Select the top row in each group with a tie-breaker
- Show a group total beside each detail row
- Sum a row and its immediate predecessor
Git 125 snippets
Getting Started
- Initialize a separate practice repository
- Identify the current practice branch
- Inspect a clean working tree
- List tracked file paths
- Recognize an untracked file
- Stage a new file
- Create a first practice commit from staged changes
- Read the latest commit message
- Count commits on the current branch
- List modified tracked files
- Distinguish staged changes from working edits
- Unstage a file while keeping its contents
- Create a branch without switching to it
- Switch to a newly created branch
- Return to the original branch
- Read a file from the latest commit
- List paths saved in the latest commit
- Ignore a disposable generated file
- Read repository-local configuration
- Label the current commit with a tag
- Find text inside tracked files
- Stage a tracked file rename
- Check a change for whitespace problems
- Read history for one path
- Inspect the author recorded on a commit
Branches & ancestry
- Count commits unique to each of two branches
- Create a branch from a known release tag
- Delete an already merged practice branch
- Find branches that contain a selected commit
- Inspect a revision with detached HEAD
- List branches already merged into the current branch
- Read the current branch name
- Rename the current branch
- Return to the previously checked-out branch
- Test whether one revision is an ancestor of another
Branches & recovery
Commit history & revision selection
- Check what kind of Git object a revision names
- Count commits reachable from a revision
- Filter history by its author identity
- Find a commit that changed the count of a text string
- List all files stored in a commit
- List files changed by the current commit
- Read a complete commit message
- Read a file from the parent commit
- Read commit subjects affecting one file
- Read commit subjects from oldest to newest
Commits & history
Inspecting the working tree
- Explain which ignore rule matches a file
- List files tracked by Git
- List ignored untracked files
- List newly added staged files only
- List only staged filenames
- List untracked files while honoring ignore rules
- Read the exact version currently staged
- Restrict a diff to one chosen path
- Summarize added and removed lines numerically
- Test whether tracked working files changed
Merging & replaying changes
- Abort a conflicting cherry-pick
- Abort a conflicting rebase
- Abort a merge with unresolved conflicts
- Apply one commit from another branch
- Combine a branch’s changes into one new commit
- List paths changed on a feature branch since its merge base
- List the paths with unresolved merge conflicts
- Preserve a feature branch boundary with a merge commit
- Replay an unpublished branch on a newer base
- Resolve a merge by writing the intended final file
Remotes & additional checkouts
- Check out another branch in a second working tree
- Clone a local bare repository
- Delete a chosen branch from a practice remote
- Distinguish a bare repository from a working checkout
- List remote-tracking branches after a fetch
- Push one selected release tag
- Read the upstream tracked by the current branch
- Remove stale remote-tracking references
- Rename a configured remote
- Replace the URL of a configured remote
Remotes & collaboration
Restoring & revising local work
- Add a forgotten file to the latest unpublished commit
- Correct the latest unpublished commit message
- Create a recovery branch for a recently moved commit
- Discard an unstaged edit to one tracked file
- Preview removal of an untracked scratch file
- Remove only a named untracked scratch file
- Restore a file’s content from an older commit
- Stop tracking a generated file while keeping it locally
- Uncommit a local change and leave its edits unstaged
- Uncommit the latest local change while keeping it staged
Stashing selected work
- Apply a stash while keeping the saved entry
- Apply and remove a successfully restored stash
- Create a branch at the original base of a stash
- Include untracked files in a stash
- Inspect which files a stash changes
- Read stash labels without commit hashes
- Restore the index state recorded in a stash
- Stash edits to one chosen file
- Stash only the staged changes
- Stash unstaged work while leaving staged edits available
Tags & repository configuration
- Create a lightweight tag at the current commit
- Declare LF normalization for a file type
- Delete only a selected local tag
- Export committed files without the Git metadata directory
- Identify a commit exactly at a release tag
- Ignore a personal scratch file without changing shared rules
- List release tags matching a pattern
- Read a repository-specific configuration value
- Read an annotated tag’s message
- Set an author identity only for this repository
Working tree & staging
Go 125 snippets
Getting Started
- Run your first Go program
- Declare and update a variable
- Name a fixed configuration value
- Inspect a value’s type
- Calculate a subtotal
- Choose floating-point division
- Test whether a number is even
- Combine two Boolean conditions
- Choose a branch with if and else
- Map a command with switch
- Repeat a task with a counted loop
- Use a condition-only for loop
- Read slice indices and values
- Append to a slice
- Declare a fixed-size array
- Look up a map entry
- Call a function with a return value
- Return two values from a function
- Group fields in a struct
- Update a value through a pointer
- Understand default zero values
- Handle a failed conversion
- Run cleanup when a function returns
- Count Unicode code points
- Format a readable status message
Concurrency & cancellation
Dates & times
Errors & validation
Files & paths
Functions & types
HTTP & URLs
JSON & encoding
Maps & sets
Slices & collections
Strings & text
Testing & reusable helpers
- Check a function with table-driven cases
- Check whether bytes contain valid JSON
- Clamp a value to an allowed interval
- Compare floats within a tolerance
- Compare two byte buffers
- Distinguish end-of-input from other errors
- Limit the bytes read from a stream
- Read a fixed-size stream prefix
- Scan whitespace-separated tokens
- Sort records by a selected field
Rust 125 snippets
Getting Started
- Compile and run your first Rust program
- Bind a value with let
- Update an explicitly mutable variable
- Declare a typed constant
- Transform a value by shadowing
- Calculate an order subtotal
- Choose floating-point arithmetic
- Combine Boolean conditions
- Use if to produce a value
- Choose an action with match
- Loop over an inclusive range
- Repeat while a condition holds
- Return a value from a loop
- Create a fixed-size array
- Grow a vector
- Destructure a tuple
- Call a typed function
- Borrow text without transferring ownership
- Modify a value through a mutable borrow
- Clone an owned value explicitly
- Construct a named-field struct
- Match enum variants
- Handle an optional value
- Handle a parsing Result
- Print a collection for inspection
Errors & optional values
- Add context to a parsing failure
- Chain operations that may return None
- Handle integer overflow without panicking
- Keep an optional value only when valid
- Propagate a parsing error with question mark
- Provide a default for a missing value
- Stop collecting when parsing fails
- Transform an optional value
- Transpose an optional parsing result
Files & paths
- Append to a file without truncating it
- Change a path’s extension
- Copy a file and inspect the copied byte count
- Create a file without replacing existing data
- Create a nested directory tree
- Inspect a path’s filename and extension
- Read buffered lines from a file
- Read file metadata without reading its contents
- Write and read a UTF-8 file
Functions & data types
- Accept different types with a generic function
- Capture a surrounding value in a closure
- Construct a struct with default values
- Define behavior with a trait
- Derive comparison and debugging behavior
- Implement a method on a struct
- Store data in an enum variant
- Use an associated constructor
- Wrap a value in a distinct type
Iterators & transformations
Maps & sets
Numbers & durations
- Check whether a floating-point value is finite
- Clamp a number to a valid interval
- Construct an instant relative to the Unix epoch
- Express a duration in milliseconds
- Reject a narrowing integer conversion
- Round and format a decimal value
- Saturate arithmetic at the type boundary
- Subtract durations without underflow
- Use a nonnegative remainder for cyclic indexing
Parsing & byte data
Strings & Unicode
Testing & reusable patterns
- Assert approximate floating-point equality
- Borrow text until a modification is needed
- Check a deterministic result with an assertion
- Collect borrowed values into owned strings
- Exercise a function with a table of inputs
- Move a collection out and leave an empty default
- Own a heap-allocated value with Box
- Read bytes through an in-memory cursor
- Replace a value and keep the old value
- Write formatted text into a byte buffer
Threads & shared ownership
- Borrow local data in a scoped thread
- Initialize shared data once
- Join a worker thread and read its result
- Move owned data into a worker
- Protect shared mutable state with a mutex
- Read a channel until all senders close
- Send a value through a channel
- Share immutable data with Arc
- Update an atomic counter
Vectors & slices
C++ 125 snippets
Getting Started
- Run your first program
- Store a value in a named variable
- Name a value that stays fixed
- Calculate a simple total
- Divide using a fractional number
- Find what remains after division
- Compare a value with a limit
- Require two conditions to be true
- Choose between two branches
- Update a running count
- Handle three possible outcomes
- Repeat a fixed number of times
- Repeat while a condition holds
- Visit every item in a collection
- Count the items in a collection
- Read the first collection element
- Replace one collection element
- Measure a short text value
- Combine text with a name
- Read the beginning of a text value
- Read one character from ASCII text
- Call a library function
- Convert known numeric text to an integer
- Print a number with two decimal places
- Explain a calculation with a comment
Collections
Containers & compound values
- Add and remove values at both ends
- Build a minimum-priority queue
- Insert a map value only when a key is absent
- Process a first-in first-out queue
- Remove a map entry and inspect the number removed
- Store and inspect a fixed set of bits
- Unpack a tuple with structured bindings
- Use a fixed-size container with bounds checking
- Use a hash map for direct key lookup
- Use a last-in first-out stack
Files & paths
Filesystem operations
- Calculate a lexical relative path
- Copy a file without replacing an existing destination
- Delete one known scratch file
- Handle a failed file open through stream state
- List regular files recursively in sorted order
- Normalize a path without touching the filesystem
- Read the byte size of a regular file
- Rename a known file through filesystem
- Set owner-only read and write permissions
- Write and read bytes without text conversion
Numbers & algorithms
Numeric parsing & calculations
- Calculate a two-dimensional vector length
- Check an upper integer bound before adding
- Find the greatest common divisor with the standard library
- Find the least common multiple with the standard library
- Format an integer into a caller-owned buffer
- Handle a failed string-to-integer conversion
- Parse a complete integer without exceptions
- Parse a hexadecimal integer with from_chars
- Reject infinite and NaN numeric values
- Round halfway floating-point values away from zero
Ordering & set operations
- Check whether a range is already sorted
- Count occurrences in a sorted sequence
- Find a median element without fully sorting
- Find sorted set members missing from another set
- Find the common members of two sorted sets
- Find the insertion position for a sorted value
- Group matching values while preserving their order
- Preserve equal-key order while sorting records
- Sort only the smallest requested prefix
- Sort records by two fields
Ownership & optional values
- Apply an operation to a variant’s active value
- Capture configuration by value in a callable
- Observe shared ownership without extending its lifetime
- Own one dynamically allocated value with unique_ptr
- Read a variant only when it holds the expected type
- Represent an absent result with optional
- Run cleanup through a scoped destructor
- Share ownership with a counted smart pointer
- Store a reference in a standard container
- Transfer unique ownership with move
Sequence algorithms
- Calculate changes between successive readings
- Calculate cumulative totals
- Calculate the dot product of two vectors
- Count elements satisfying a predicate
- Find both extremes in one algorithm call
- Find the first value satisfying a condition
- Merge two sorted sequences
- Rotate a sequence around a selected position
- Test any and all elements with predicates
- Transform a vector into a separate result
Strings
Tasks & synchronization
- Check whether a future is ready without blocking
- Convert a duration to another unit explicitly
- Deliver a result through a promise and future
- Increment a shared counter safely
- Observe an exception from an asynchronous task
- Pass an argument into a worker thread
- Protect a shared container with a mutex
- Retrieve the result of an asynchronous task
- Run a task on a thread and join it
- Wait for shared state with a condition variable
Text validation & parsing
- Check a literal prefix in C++17
- Check a literal suffix in C++17
- Convert ASCII text to lowercase safely
- Extract a substring with an explicit count
- Inspect a substring without allocating a copy
- Iterate over all regular-expression matches
- Read a quoted string containing spaces
- Replace text using captured regex groups
- Trim surrounding ASCII whitespace
- Validate a complete identifier
C 125 snippets
Getting Started
- Run your first program
- Store a value in a named variable
- Name a value that stays fixed
- Calculate a simple total
- Divide using a fractional number
- Find what remains after division
- Compare a value with a limit
- Require two conditions to be true
- Choose between two branches
- Update a running count
- Handle three possible outcomes
- Repeat a fixed number of times
- Repeat while a condition holds
- Visit every item in a collection
- Count the items in a collection
- Read the first collection element
- Replace one collection element
- Measure a short text value
- Combine text with a name
- Read the beginning of a text value
- Read one character from ASCII text
- Call a library function
- Convert known numeric text to an integer
- Print a number with two decimal places
- Explain a calculation with a comment
Array transformations
- Calculate a cumulative sum for each position
- Filter an array in place with a write index
- Find the smallest value in a nonempty array
- Insert into an array with spare capacity
- Merge two sorted arrays
- Remove adjacent duplicates from a sorted array
- Remove one array element and close the gap
- Rotate a nonempty array left by one element
- Search a sorted array with bsearch
- Sort an integer array with qsort
Arrays
Binary formats & structured parsing
- Convert ASCII text to lowercase safely
- Decode a 16-bit big-endian integer
- Decode a validated pair of hexadecimal digits
- Encode a byte buffer as hexadecimal
- Format a known timestamp in UTC
- Format a nonnegative integer amount as whole and fractional units
- Parse a bounded simple record with sscanf
- Quote a CSV field and double embedded quotes
- Serialize a 16-bit integer in big-endian order
- Validate a simple C-style ASCII identifier
Dynamic memory & ownership
- Allocate an independent copy of a C string
- Allocate and free a typed array
- Allocate and initialize a structure
- Check an array allocation size before multiplying
- Clear an owning pointer after releasing its allocation
- Create an independent copy of a byte buffer
- Grow an allocation without losing it on failure
- Initialize a byte buffer to zero
- Store a variable-length payload after a structure header
- Swap owned buffers by swapping their pointers
File positioning & lifecycle
- Copy a file in bounded binary chunks
- Handle a missing file without treating it as an empty file
- Measure a small seekable binary file
- Read a stream again from its beginning
- Read bytes from a chosen file offset
- Read characters without confusing EOF with a byte
- Remove one known scratch file
- Rename a known file
- Replace bytes at a known position in a binary file
- Use an automatically removed temporary file
Files
Numbers & memory
Numeric parsing & arithmetic
- Calculate a page count without an overflowing addition
- Check positive integer addition before performing it
- Clamp an integer to inclusive bounds
- Compare small floating-point results with a tolerance
- Compute a two-dimensional vector length
- Parse an unsigned hexadecimal integer
- Reject NaN and infinite values
- Round a halfway floating-point value
- Round downward and upward independently
- Validate a complete floating-point input
Small algorithms & bit operations
- Calculate a fixed-window moving average
- Calculate a least common multiple using a GCD
- Calculate a small factorial iteratively
- Calculate an average without integer division truncation
- Calculate the greatest common divisor
- Compute a simple XOR checksum
- Count set bits in an unsigned integer
- Generate a bounded Fibonacci sequence
- Sum the decimal digits of an unsigned integer
- Test whether an unsigned value is a power of two
Strings
Strings & byte buffers
- Append text only when the destination has enough capacity
- Check a literal filename suffix
- Check a literal string prefix
- Compare binary buffers including zero bytes
- Compare two C strings for equality
- Count a leading run of allowed characters
- Find the final path separator
- Find the first occurrence of a character
- Move overlapping bytes safely
- Split simple delimited text in place
Structures & function interfaces
- Give a reusable record type a short name
- Group related values in nested structures
- Initialize structure fields by name
- Iterate over a fixed array of records
- Keep caller data unchanged by passing a structure by value
- Keep function state between calls
- Pass a function as a callback
- Represent a small set of named states
- Return a status separately from a calculated result
- Track which union member is currently valid
Arduino / C 125 snippets
Getting Started
- Hello World: Blink
- Understand setup() and loop()
- Explain a sketch with comments
- Give an LED pin a constant name
- Change an LED delay with a variable
- Print a label beside a number
- Count five LED flashes with a for loop
- Read a button in the Serial Monitor
- Turn on the LED with a serial command
- Reuse an LED action with a function
- Run a first sketch and read serial output
- Print once from setup
- Combine several Serial.print calls
- Store an integer reading
- Name a fixed configuration value
- Store a small unsigned value
- Print a single character
- Print a fixed text buffer
- Keep fixed text in flash memory
- Represent an enabled state
- Calculate with integer values
- Preserve a fractional result
- Find a division remainder
- Branch on a threshold
- Check both ends of a range
- Select a response with switch
- Repeat a serial message three times
- Count down with a bounded loop
- Store several readings in an array
- Calculate a fixed array’s element count
- Visit every reading in a fixed array
- Keep a value inside an allowed range
- Choose the smaller of two values
- Inspect a byte as hexadecimal
- Use a wider type for a large count
Arrays & embedded state
- Advance an index around a fixed collection
- Dispatch a command through function pointers
- Find a sample range in one pass
- Find a value in a small lookup table
- Group related readings in a struct
- Keep a counter from wrapping at its maximum
- Reject insertion when a fixed queue is full
- Sort a small array in place
- Store samples in a fixed-size ring buffer
- Use named states for a controller
Binary values & packets
- Assemble a big-endian 16-bit value
- Assign a bit from a Boolean state
- Calculate a CRC-8 over a byte sequence
- Calculate a simple packet XOR checksum
- Clear a flag without affecting neighboring bits
- Encode a value as little-endian bytes
- Extract the low and high byte of a value
- Pack two small values into one byte
- Require every bit in a mask
- Toggle a bit with an XOR mask
Data & storage
Digital input & output
Digital signals & interrupts
- Copy a multibyte interrupt-owned counter atomically
- Count a button’s falling edge in the main loop
- Count a rising edge with an interrupt
- Drive the built-in LED low after turning it on
- Generate and measure a short output pulse
- Play a fixed digital output pattern
- Read an unpressed button with an internal pull-up
- Read back a configured digital output
- Stop receiving interrupts when a task finishes
- Toggle an output using an explicit software state
EEPROM & program memory
- Check EEPROM capacity before a write
- Copy a flash string into a bounded RAM buffer
- Read 16-bit values from a flash table
- Read a byte lookup table from flash
- Read and total a flash lookup table
- Reject an unsupported settings version
- Store a bounded null-terminated text setting
- Store a compact configuration record
- Store and retrieve a multibyte integer
- Validate a small stored payload with a checksum
Sensor calculations
- Apply a linear sensor calibration
- Convert a supplied ADC count to volts
- Convert Celsius to Fahrenheit
- Ignore small movements around a center value
- Interpolate between two calibration points
- Maintain a rolling sum in a circular window
- Prevent output chatter with separate thresholds
- Reject one outlier with a median-of-three filter
- Represent a decimal quantity with a scaled integer
- Smooth a sequence with an exponential filter
Serial communication
Serial protocols
- Convert received ASCII letters to uppercase
- Dispatch a one-character serial command
- Handle incomplete serial input
- Inspect a byte without consuming it
- Read a decimal number from serial input
- Read a fixed-size serial payload
- Read an integer from serial input
- Read serial text up to a delimiter
- Search the stream for a message marker
- Validate a complete numeric serial command
Text & bounded buffers
- Compare a command case-sensitively
- Copy a string with a guaranteed terminator
- Detect truncated formatted output
- Extract a section of an Arduino String
- Format several integers in a fixed buffer
- Keep a serial message in flash memory
- Reject an integer with trailing characters
- Replace a token inside an Arduino String
- Split a writable comma-delimited buffer
- Trim surrounding whitespace from an Arduino String