### Initialize clipmem with setup Source: https://docs.rs/crate/clipmem/0.2.2 Initializes the clipmem archive and starts background capture. Performs one foreground capture to seed the archive, then starts background capture using the most natural provider for the active install. The Homebrew cask for the menu bar app runs this automatically after installation. ```bash clipmem setup ``` -------------------------------- ### Install clipmem with Homebrew Source: https://docs.rs/crate/clipmem/0.2.1 Installs clipmem via Homebrew on Apple Silicon, then runs setup. Optionally starts it as a background service with brew services. ```bash brew install tristanmanchester/tap/clipmem clipmem setup # or: brew services start clipmem ``` -------------------------------- ### Install and setup Homebrew CLI for macOS Source: https://docs.rs/crate/clipmem/0.2.10 Installs the clipmem command-line tool via Homebrew and initializes it with the setup command. Requires Apple Silicon and macOS. ```bash brew install tristanmanchester/tap/clipmem clipmem setup ``` -------------------------------- ### Install clipmem via Cargo (Apple Silicon or Intel) Source: https://docs.rs/crate/clipmem/0.2.2 Installs the clipmem CLI using Cargo and runs setup. ```bash cargo install clipmem clipmem setup ``` -------------------------------- ### Install and load clipmem LaunchAgent with install_launchagent.sh Source: https://docs.rs/crate/clipmem/0.1.1 Installs the binary, creates the database directory with tight permissions, and loads the LaunchAgent. By default it installs to ~/.local/bin, creates ~/Library/Application Support/clipmem (mode 0700), writes ~/Library/LaunchAgents/io.openclaw.clipmem.watch.plist, launches with --skip-initial, and kickstarts the agent. ```bash ./scripts/install_launchagent.sh ``` -------------------------------- ### element_offset: get index of element reference Source: https://docs.rs/oxidize-pdf/5.1.1/oxidize_pdf/memory/memory_mapped/struct.MemoryMappedFile.html Use this example to get the index of an element reference within a slice. It returns `Some(index)` when the reference points to the start of an element, and `None` otherwise. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` -------------------------------- ### Try it out: demo --help and demo --name Me Source: https://docs.rs/clap/%2A Shows the generated help output and a sample run. The help includes usage, options, and defaults. The version number and .exe extension are replaced by placeholders on Windows. ```bash $ demo --help A simple to use, efficient, and full-featured Command Line Argument Parser Usage: demo[EXE] [OPTIONS] --name Options: -n, --name Name of the person to greet -c, --count Number of times to greet [default: 1] -h, --help Print help -V, --version Print version $ demo --name Me Hello Me! ``` -------------------------------- ### Pre-built test steps Source: https://docs.rs/crate/clap/2.9.3/target-redirect/x86_64-pc-windows-gnu/clap Commands to clone the repository, build the example, and run the help info. ```bash $ git clone https://github.com/kbknapp/clap-rs && cd clap-rs/clap-tests ``` ```bash $ cargo build --release ``` ```bash $ ./target/release/claptests --help ``` -------------------------------- ### Help output for the quick start application Source: https://docs.rs/clap/4.6.6/clap/_tutorial/index.html The generated help message for the application defined in the previous example. ```bash $ 01_quick --help A simple to use, efficient, and full-featured Command Line Argument Parser Usage: 01_quick[EXE] [OPTIONS] [name] [COMMAND] Commands: test does testing things help Print this message or the help of the given subcommand(s) Arguments: [name] Optional name to operate on Options: -c, --config Sets a custom config file -d, --debug... Turn debugging information on -h, --help Print help -V, --version Print version ``` -------------------------------- ### Use subslice_range with split iterator Source: https://docs.rs/image/0.25.10/image/struct.ImageBuffer.html Basic usage of subslice_range to get the range of a subslice. The example is incomplete; it starts building an iterator but does not show the rest. ```rust use core::range::Range; let nums = &[0, 5, 10, 0, 0, 5]; let mut iter = nums .split(|t| *t == 0) .map(|n| nums.subslice_range(n).unwrap()); ``` -------------------------------- ### Run client example and view output Source: https://docs.rs/rustls/0.23.44/rustls/crypto/struct.CryptoProvider.html Shows the command to run the client example and the first few lines of its output, including the ciphersuite and HTTP response headers. ```bash $ cargo run --example client | head -3 Current ciphersuite: TLS13_CHACHA20_POLY1305_SHA256 HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 Content-Length: 19899 ``` -------------------------------- ### Get week range with NaiveWeek::days Source: https://docs.rs/chrono/0.4.45/chrono/naive/struct.NaiveWeek.html Shows how to get the whole week as a `RangeInclusive` using `NaiveWeek::days`. The example creates a `NaiveDate`, obtains the week starting on Monday, and asserts that the range contains the original date. ```rust use chrono::{NaiveDate, Weekday}; let date = NaiveDate::from_ymd_opt(2022, 4, 18).unwrap(); let week = date.week(Weekday::Mon); let days = week.days(); assert!(days.contains(&date)); ``` -------------------------------- ### Get last day of week with NaiveWeek::last_day Source: https://docs.rs/chrono/0.4.45/chrono/naive/struct.NaiveWeek.html Shows how to get the last day of a week using `NaiveWeek::last_day`. The example creates a `NaiveDate`, obtains the week starting on Monday, and asserts that the last day is on or after the original date. ```rust use chrono::{NaiveDate, Weekday}; let date = NaiveDate::from_ymd_opt(2022, 4, 18).unwrap(); let week = date.week(Weekday::Mon); assert!(week.last_day() >= date); ``` -------------------------------- ### Quick start: create namespace and enforce quotas Source: https://docs.rs/chronix-security/0.6.0/chronix_security/tenant/index.html Quick start example: create a namespace with custom quotas and enforce write quotas using QuotaEnforcer. ```rust use chronix_security::tenant::{NamespaceRegistry, QuotaEnforcer}; use chronix_core::{NamespaceId, NamespaceQuota}; let registry = NamespaceRegistry::new(); // Create a namespace with custom quotas let id = NamespaceId::new("team-platform").unwrap(); let quota = NamespaceQuota { max_series_count: 500_000, max_ingestion_rate: 50_000, max_storage_bytes: 50 * 1024 * 1024 * 1024, max_measurements: 200, max_request_rps: 0, max_request_burst: 0, }; registry.create_namespace(id, "Platform team", "admin", quota).unwrap(); // Enforce quotas on writes (atomic check + increment) let enforcer = QuotaEnforcer::new(®istry); enforcer.check_and_increment_write("team-platform", 10, 1000).unwrap(); ``` -------------------------------- ### Quick Start: Using rand for Random Value Generation Source: https://docs.rs/rand/%5E0.8.3 Shows the basic usage of the rand crate to generate a boolean, a random Unicode character, a float between 0 and 1, and to shuffle a vector. This is the introductory example for getting started quickly. ```rust use rand::prelude::*; if rand::random() { // generates a boolean // Try printing a random unicode code point (probably a bad idea)! println!("char: {}", rand::random::()); } let mut rng = rand::thread_rng(); let y: f64 = rng.gen(); // generates a float between 0 and 1 let mut nums: Vec = (1..100).collect(); nums.shuffle(&mut rng); ``` -------------------------------- ### Clone and run Jupyter notebook tutorial Source: https://docs.rs/plotters/%5E0.3.2 Commands to clone the tutorial repository and start a local Jupyter server. After running these, select the notebook `evcxr-jupyter-integration.ipynb` to open the interactive tutorial. ```bash git clone https://github.com/38/plotters-doc-data cd plotters-doc-data jupyter notebook ``` -------------------------------- ### Get first day of week with NaiveWeek::first_day Source: https://docs.rs/chrono/0.4.45/chrono/naive/struct.NaiveWeek.html Shows how to get the first day of a week using `NaiveWeek::first_day`. The example creates a `NaiveDate` from a specific date, obtains the week starting on Monday, and asserts that the first day is on or before the original date. ```rust use chrono::{NaiveDate, Weekday}; let date = NaiveDate::from_ymd_opt(2022, 4, 18).unwrap(); let week = date.week(Weekday::Mon); assert!(week.first_day() <= date); ``` -------------------------------- ### Build and run C example Source: https://docs.rs/sysinfo/%5E0.39.6 Builds the C example with make and runs it. If the shared library is not found, set LD_LIBRARY_PATH to target/debug. ```bash > make > ./simple # If needed: > LD_LIBRARY_PATH=target/debug/ ./simple ``` -------------------------------- ### Set up NSApplication window and delegate Source: https://docs.rs/crate/objc2/0.6.4/target-redirect/aarch64-apple-visionos/objc2 This snippet shows how to set window properties, add a text field, center the window, set a delegate, and activate the application. It also includes the delegate implementation for handling window close and the main function to set up the app. ```rust // Set various window properties. window.setTitle(ns_string!("A window")); let view = window.contentView().expect("window must have content view"); unsafe { view.addSubview(&text_field) }; window.center(); unsafe { window.setContentMinSize(NSSize::new(300.0, 300.0)) }; window.setDelegate(Some(ProtocolObject::from_ref(self))); // Show the window. window.makeKeyAndOrderFront(None); // Store the window in the delegate. self.ivars().window.set(window).unwrap(); app.setActivationPolicy(NSApplicationActivationPolicy::Regular); // Activate the application. // Required when launching unbundled (as is done with Cargo). #[allow(deprecated)] app.activateIgnoringOtherApps(true); } ``` ```rust // SAFETY: `NSWindowDelegate` has no safety requirements. unsafe impl NSWindowDelegate for Delegate { #[unsafe(method(windowWillClose:))] fn window_will_close(&self, _notification: &NSNotification) { // Quit the application when the window is closed. unsafe { NSApplication::sharedApplication(self.mtm()).terminate(None) }; } } ); impl Delegate { fn new(mtm: MainThreadMarker) -> Retained { let this = Self::alloc(mtm).set_ivars(AppDelegateIvars::default()); // SAFETY: The signature of `NSObject`'s `init` method is correct. unsafe { msg_send![super(this), init] } } } fn main() { let mtm = MainThreadMarker::new().unwrap(); let app = NSApplication::sharedApplication(mtm); let delegate = Delegate::new(mtm); app.setDelegate(Some(ProtocolObject::from_ref(&*delegate))); } ``` -------------------------------- ### split_off: Remove subslice by range Source: https://docs.rs/smallvec/latest/smallvec/struct.SmallVec.html Shows how to use split_off to remove a subslice from a slice and get a reference to it. The first example splits off the first three elements, the second splits off a slice starting with the third element, and the third demonstrates getting None when the range is out of bounds. ```rust let mut slice: &[_] = &['a', 'b', 'c', 'd']; let mut first_three = slice.split_off(..3).unwrap(); assert_eq!(slice, &['d']); assert_eq!(first_three, &['a', 'b', 'c']); ``` ```rust let mut slice: &[_] = &['a', 'b', 'c', 'd']; let mut tail = slice.split_off(2..).unwrap(); assert_eq!(slice, &['a', 'b']); assert_eq!(tail, &['c', 'd']); ``` ```rust let mut slice: &[_] = &['a', 'b', 'c', 'd']; assert_eq!(None, slice.split_off(5..)); assert_eq!(None, slice.split_off(..5)); assert_eq!(None, slice.split_off(..=4)); let expected: &[char] = &['a', 'b', 'c', 'd']; assert_eq!(Some(expected), slice.split_off(..4)); ``` -------------------------------- ### Quickstart: Configure Criterion.rs in Cargo.toml and run a benchmark Source: https://docs.rs/crate/criterion/0.8.2 Add Criterion.rs as a dev-dependency and configure a benchmark target in Cargo.toml. Then define a benchmark function in benches/my_benchmark.rs and run it with cargo bench. The expected output shows timing and outlier statistics. ```toml [dev-dependencies] criterion = { version = "0.8", features = ["html_reports"] } [[bench]] name = "my_benchmark" harness = false ``` ```rust use std::hint::black_box; use criterion::{criterion_group, criterion_main, Criterion}; fn fibonacci(n: u64) -> u64 { match n { 0 => 1, 1 => 1, n => fibonacci(n-1) + fibonacci(n-2), } } fn criterion_benchmark(c: &mut Criterion) { c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20)))); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches); ``` ```text Running target/release/deps/example-423eedc43b2b3a93 fib 20 time: [26.029 us 26.251 us 26.505 us] Found 11 outliers among 99 measurements (11.11%) 6 (6.06%) high mild 5 (5.05%) high severe ``` -------------------------------- ### get example Source: https://docs.rs/fnv/1.0.7/fnv/type.FnvHashMap.html Gets a reference to the value for a given key. The example inserts a key-value pair and then checks that get returns the expected reference for an existing key and None for a missing key. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### Install wsltop with cargo-binstall and run interactively Source: https://docs.rs/crate/wsltop/0.5.1 Install wsltop via cargo-binstall and launch the interactive TUI. Requires cargo-binstall and a WSL2 distribution. ```bash cargo binstall wsltop wsltop --interactive ``` -------------------------------- ### clipmem get examples Source: https://docs.rs/clipmem/0.6.1/src/clipmem/cli/help.rs.html Shows example invocations for the `get` command. `get` is for detailed nested snapshot inspection after you already know the snapshot id. `--events` defaults to 10 and is bounded 1-250. `--format toon` is not supported because `get` returns nested snapshot detail. ```shell clipmem get 42 ``` ```shell clipmem get 42 --human ``` ```shell clipmem get 42 --format json ``` ```shell clipmem get 42 --events 25 --format md ``` -------------------------------- ### Run host_window example with various flags Source: https://docs.rs/crate/bevy_symbios_audio/0.5.1 Commands to run the host_window example with different flags for screenshots and state testing. ```bash cargo run --example host_window --features egui -- --shot host_window.png cargo run --example host_window --features egui -- --status error --shot error.png cargo run --example host_window --features egui -- --orphan --shot orphan.png cargo run --example host_window --features egui -- --status playing-sequence --playhead 1.0 --shot run-up.png cargo run --example host_window --features egui -- --status playing-sequence --ruler 10 --shot ruler.png ``` -------------------------------- ### Realistic example: data structure setup Source: https://docs.rs/ref-cast/%5E1.0.18 Defines a TileMap with a flat storage buffer and a comment explaining the desired indexing behavior. This is the setup for the following Index trait examples. ```rust const MAP_WIDTH: usize = 4; struct Tile(u8); struct TileMap { storage: Vec, } // `tilemap[x][y]` should give us `tilemap.storage[y * MAP_WIDTH + x]`. ``` -------------------------------- ### Hello World GUI application using objc2 Source: https://docs.rs/crate/objc2/0.6.4/target-redirect/aarch64-apple-visionos/objc2 Complete Rust example demonstrating how to create a simple GUI application with a 'Hello World' label using objc2-foundation and objc2-app-kit. Defines an NSApplicationDelegate, creates an NSTextField and NSWindow, and configures the application. Includes safety comments and uses MainThreadOnly thread kind. ```rust #![deny(unsafe_op_in_unsafe_fn)] use std::cell::OnceCell; use objc2::rc::Retained; use objc2::runtime::ProtocolObject; use objc2::{define_class, msg_send, DefinedClass, MainThreadOnly}; use objc2_app_kit::{ NSApplication, NSApplicationActivationPolicy, NSApplicationDelegate, NSAutoresizingMaskOptions, NSBackingStoreType, NSColor, NSFont, NSTextAlignment, NSTextField, NSWindow, NSWindowDelegate, NSWindowStyleMask, }; use objc2_foundation::{ ns_string, MainThreadMarker, NSNotification, NSObject, NSObjectProtocol, NSPoint, NSRect, NSSize, }; #[derive(Debug, Default)] struct AppDelegateIvars { window: OnceCell>, } define_class!( // SAFETY: // - The superclass NSObject does not have any subclassing requirements. // - `Delegate` does not implement `Drop`. #[unsafe(super = NSObject)] #[thread_kind = MainThreadOnly] #[ivars = AppDelegateIvars] struct Delegate; // SAFETY: `NSObjectProtocol` has no safety requirements. unsafe impl NSObjectProtocol for Delegate {} // SAFETY: `NSApplicationDelegate` has no safety requirements. unsafe impl NSApplicationDelegate for Delegate { // SAFETY: The signature is correct. #[unsafe(method(applicationDidFinishLaunching:))] fn did_finish_launching(&self, notification: &NSNotification) { let mtm = self.mtm(); let app = unsafe { notification.object() } .unwrap() .downcast::() .unwrap(); let text_field = unsafe { let text_field = NSTextField::labelWithString(ns_string!("Hello, World!"), mtm); text_field.setFrame(NSRect::new( NSPoint::new(5.0, 100.0), NSSize::new(290.0, 100.0), )); text_field.setTextColor(Some(&NSColor::colorWithSRGBRed_green_blue_alpha( 0.0, 0.5, 0.0, 1.0, ))); text_field.setAlignment(NSTextAlignment::Center); text_field.setFont(Some(&NSFont::systemFontOfSize(45.0))); text_field.setAutoresizingMask( NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewHeightSizable, ); text_field }; // SAFETY: We disable releasing when closed below. let window = unsafe { NSWindow::initWithContentRect_styleMask_backing_defer( NSWindow::alloc(mtm), NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(300.0, 300.0)), NSWindowStyleMask::Titled | NSWindowStyleMask::Closable | NSWindowStyleMask::Miniaturizable | NSWindowStyleMask::Resizable, NSBackingStoreType::Buffered, false, ) }; // SAFETY: Disable auto-release when closing windows. // This is required when creating `NSWindow` outside a window // controller. unsafe { window.setReleasedWhenClosed(false) }; ``` -------------------------------- ### Install clipmem CLI and menu bar app via Homebrew Source: https://docs.rs/crate/clipmem/0.6.1/source/README.md Install clipmem on Apple Silicon. The first block installs the CLI and runs setup; the second installs the native menu bar app and opens it; the third trusts the tap if Homebrew flags it as untrusted. The cask installs the CLI, runs clipmem setup, and enables launch at login. ```bash brew install tristanmanchester/tap/clipmem clipmem setup ``` ```bash brew install --cask tristanmanchester/tap/clipmem-app open -a ClipmemMenuBar ``` ```bash brew trust --formula tristanmanchester/tap/clipmem brew trust --cask tristanmanchester/tap/clipmem-app ``` -------------------------------- ### Set up binary benchmarks with #[binary_benchmark] and main! Source: https://docs.rs/gungraun/%3D0.19.2 Set up binary benchmarks with the `#[binary_benchmark]` attribute and the `binary_benchmark_group!` and `main!` macros. The setup function is executed before the command, not used as input. All annotated functions must return a `gungraun::Command`. The `main!` macro expands to a benchmarking harness. ```rust use std::ffi::OsString; use std::path::PathBuf; use gungraun::prelude::*; // In binary benchmarks there's no need to return a value from the setup function fn my_setup() { println!("Put code in here which will be run before the actual command"); } #[binary_benchmark] #[bench::just_a_fixture("benches/fixture.json")] // First big difference to library benchmarks! `my_setup` is not evaluated right away and the // return value of `my_setup` is not used as input for the `bench_foo` function. Instead, // `my_setup()` is executed before the execution of the `Command`. #[bench::with_other_fixture_and_setup(args = ("benches/other_fixture.txt"), setup = my_setup())] #[benches::multiple("benches/fix_1.txt", "benches/fix_2.txt")] // All functions annotated with `#[binary_benchmark]` need to return a `gungraun::Command` fn bench_bar

(path: P) -> gungraun::Command where P: Into, { let path: PathBuf = path.into(); // We can put any code in here which is needed to configure the `Command`. let stdout = if path.extension().unwrap() == "txt" { gungraun::Stdio::Inherit } else { gungraun::Stdio::File(path.with_extension("out")) }; // Configure the command depending on the arguments passed to this function and the code // above gungraun::Command::new(env!("CARGO_BIN_EXE_my-foo")) .stdout(stdout) .arg(path) .build() } #[binary_benchmark] // The id just needs to be unique within the same `#[binary_benchmark]`, so we can reuse // `just_a_fixture` if we want to #[bench::just_a_fixture("benches/fixture.json")] // The function can be generic, too. fn bench_bar

(path: P) -> gungraun::Command where P: Into, { gungraun::Command::new(env!("CARGO_BIN_EXE_my-bar")) .arg(path) .build() } // Put all `#[binary_benchmark]` annotated functions you want to benchmark into the `benchmarks` // section of this macro binary_benchmark_group!(name = my_group, benchmarks = [bench_foo, bench_bar]); // As last step specify all groups you want to benchmark in the macro argument // `binary_benchmark_groups`. As the binary_benchmark_group macro, the main macro is // always needed and finally expands to a benchmarking harness main!(binary_benchmark_groups = my_group); ``` -------------------------------- ### get example Source: https://docs.rs/arrayvec/0.7.8/x86_64-unknown-linux-gnu/arrayvec/arrayvec/struct.ArrayVec.html Use to get a reference to an element or subslice by index or range. Returns None if the index is out of bounds. The example shows element access, range access, and out-of-bounds cases. ```rust let v = [10, 40, 30]; assert_eq!(Some(&10), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### azip! full example with setup and multiple usages Source: https://docs.rs/ndarray/0.17.2/ndarray/macro.azip.html A complete example that sets up arrays and demonstrates four azip! usages: basic ternary operation, indexed iteration, references, and row-wise sums. Includes assertions and a helper function. ```rust use ndarray::{azip, Array1, Array2, Axis}; type M = Array2; // Setup example arrays let mut a = M::zeros((16, 16)); let mut b = M::zeros(a.dim()); let mut c = M::zeros(a.dim()); // assign values b.fill(1.); for ((i, j), elt) in c.indexed_iter_mut() { *elt = (i + 10 * j) as f32; } // Example 1: Compute a simple ternary operation: // elementwise addition of b and c, stored in a azip!((a in &mut a, &b in &b, &c in &c) *a = b + c); assert_eq!(a, &b + &c); // Example 2: azip!() with index azip!((index (i, j), &b in &b, &c in &c) { a[[i, j]] = b - c; }); assert_eq!(a, &b - &c); // Example 3: azip!() on references // See the definition of the function below borrow_multiply(&mut a, &b, &c); assert_eq!(a, &b * &c); // Since this function borrows its inputs, the `IntoNdProducer` // expressions don't need to explicitly include `&mut` or `&`. fn borrow_multiply(a: &mut M, b: &M, c: &M) { azip!((a in a, &b in b, &c in c) *a = b * c); } // Example 4: using azip!() without dereference in pattern. // // Create a new array `totals` with one entry per row of `a`. // Use azip to traverse the rows of `a` and assign to the corresponding // entry in `totals` with the sum across each row. // // The row is an array view; it doesn't need to be dereferenced. let mut totals = Array1::zeros(a.nrows()); azip!((totals in &mut totals, row in a.rows()) *totals = row.sum()); // Check the result against the built in `.sum_axis()` along axis 1. assert_eq!(totals, a.sum_axis(Axis(1))); ``` -------------------------------- ### get example: immutable borrow of frozen pyclass Source: https://docs.rs/pyo3/0.29.2/pyo3/struct.Borrowed.html Demonstrates the get method on a Borrowed reference for a frozen pyclass that is Sync. The example defines a frozen counter, creates a Bound, borrows it, and uses get to immutably access the underlying value and perform an atomic operation. ```rust use core::sync::atomic::{AtomicUsize, Ordering}; #[pyclass(frozen)] struct FrozenCounter { value: AtomicUsize, } Python::attach(|py| { let counter = FrozenCounter { value: AtomicUsize::new(0) }; let py_counter = Bound::new(py, counter).unwrap(); let py_counter_borrowed = py_counter.as_borrowed(); py_counter_borrowed.get().value.fetch_add(1, Ordering::Relaxed); }); ``` -------------------------------- ### Run examples with cargo run Source: https://docs.rs/crate/oxidize-pdf/0.1.3 Run the hello_world example with cargo run --example hello_world. For OCR examples, add the --features ocr-tesseract flag to enable the tesseract_ocr_demo example. ```bash cargo run --example hello_world # For OCR examples cargo run --example tesseract_ocr_demo --features ocr-tesseract ``` -------------------------------- ### Run example programs Source: https://docs.rs/crate/oxidize-pdf/1.6.11 Run the example programs from the examples/ directory. Each command executes a different example: recovery_corrupted_pdf, png_transparency_watermark, and cjk_text_extraction. ```shell cargo run --example recovery_corrupted_pdf cargo run --example png_transparency_watermark cargo run --example cjk_text_extraction ``` -------------------------------- ### ncols example: getting column count of a 2D array Source: https://docs.rs/ndarray/0.17.2/ndarray/struct.ArrayRef.html Shows how to get the number of columns of a 2D array using ncols(). The example uses a 3x2 array and asserts ncols() equals 2. ```rust use ndarray::{array, Axis}; let array = array![[1., 2.], [3., 4.], [5., 6.]]; assert_eq!(array.ncols(), 2); ``` -------------------------------- ### Quick start example application Source: https://docs.rs/clap/4.6.6/clap/_derive/_tutorial/index.html A complete example of a clap application using the derive API. It defines a Cli struct with options, a subcommand, and demonstrates parsing and handling arguments. ```rust use std::path::PathBuf; use clap::{Parser, Subcommand}; #[derive(Parser)] #[command(version, about, long_about = None)] struct Cli { /// Optional name to operate on name: Option, /// Sets a custom config file #[arg(short, long, value_name = "FILE")] config: Option, /// Turn debugging information on #[arg(short, long, action = clap::ArgAction::Count)] debug: u8, #[command(subcommand)] command: Option, } #[derive(Subcommand)] enum Commands { /// does testing things Test { /// lists test values #[arg(short, long)] list: bool, }, } fn main() { let cli = Cli::parse(); // You can check the value provided by positional arguments, or option arguments if let Some(name) = cli.name.as_deref() { println!("Value for name: {name}"); } if let Some(config_path) = cli.config.as_deref() { println!("Value for config: {}", config_path.display()); } // You can see how many times a particular flag or argument occurred // Note, only flags can have multiple occurrences match cli.debug { 0 => println!("Debug mode is off"), 1 => println!("Debug mode is kind of on"), 2 => println!("Debug mode is on"), _ => println!("Don't be crazy"), } // You can check for the existence of subcommands, and if found use their // matches just as you would the top level cmd match &cli.command { Some(Commands::Test { list }) => { if *list { println!("Printing testing lists..."); } else { println!("Not printing testing lists..."); } } None => {} } // Continued program logic goes here... } ``` -------------------------------- ### GET http://example.com Source: https://docs.rs/ureq/2.12.1/ureq/index.html Simple GET request example using ureq's top-level function. ```APIDOC ## [GET] http://example.com ### Description Performs a simple GET request to the specified URL. This is the simplest form of using ureq, allowing you to set headers and read the response body as a string. ### Method GET ### Endpoint http://example.com ### Parameters #### Headers - **Example-Header** (string) - Optional - A custom header to include in the request. ### Request Example ```rust ureq::get("http://example.com") .set("Example-Header", "header value") .call()? .into_string()? ``` ### Response #### Success Response (200) - **body** (string) - The response body as a string. #### Response Example ```rust let body: String = ureq::get("http://example.com") .set("Example-Header", "header value") .call()? .into_string()?; ``` ``` -------------------------------- ### Help output for 01_quick_derive Source: https://docs.rs/clap/4.6.6/clap/_derive/_tutorial/index.html Output of running the example application with the --help flag, showing usage, commands, arguments, and options. ```bash $ 01_quick_derive --help A simple to use, efficient, and full-featured Command Line Argument Parser Usage: 01_quick_derive[EXE] [OPTIONS] [NAME] [COMMAND] Commands: test does testing things help Print this message or the help of the given subcommand(s) Arguments: [NAME] Optional name to operate on Options: -c, --config Sets a custom config file -d, --debug... Turn debugging information on -h, --help Print help -V, --version Print version ``` -------------------------------- ### Timestamp::date() example Source: https://docs.rs/time/0.3.55/time/struct.Timestamp.html Gets the `Date` of the timestamp in UTC. The example asserts equality with a specific date. ```rust assert_eq!(timestamp!(1_546_398_245).date(), date!(2019-01-02)); ``` -------------------------------- ### Example: Path::as_os_str Source: https://docs.rs/tempfile/3.27.0/tempfile/struct.TempPath.html Example from the documentation of Path::as_os_str, showing how to get the underlying OsStr slice. ```rust use std::path::Path; let os_str = Path::new("foo.txt").as_os_str(); assert_eq!(os_str, std::ffi::OsStr::new("foo.txt")); ``` -------------------------------- ### Run Divan example benchmarks Source: https://docs.rs/crate/divan/%5E0.1 Clone the Divan repository and run the example benchmarks locally with `cargo bench -q -p examples --all-features`. This requires the `examples/benches` directory from the repository. ```bash git clone https://github.com/nvzqz/divan.git cd divan cargo bench -q -p examples --all-features ``` -------------------------------- ### Get capture group offsets with CaptureLocations::get Source: https://docs.rs/regex/1.13.1/regex/struct.CaptureLocations.html Shows how to use `CaptureLocations::get` to retrieve the start and end byte offsets of each capture group after a successful `captures_read` call. The example uses a regex with two named groups and asserts the returned offsets for the whole match and each group. ```rust use regex::Regex; let re = Regex::new(r"(?\w+)\s+(?\w+)").unwrap(); let mut locs = re.capture_locations(); re.captures_read(&mut locs, "Bruce Springsteen").unwrap(); assert_eq!(Some((0, 17)), locs.get(0)); assert_eq!(Some((0, 5)), locs.get(1)); assert_eq!(Some((6, 17)), locs.get(2)); ``` -------------------------------- ### Pre-built test: clone, build, run help Source: https://docs.rs/clap/2.9.3 Commands to clone the clap-rs repository, build the pre-built test example, and run its help output. ```text $ git clone https://github.com/kbknapp/clap-rs && cd clap-rs/clap-tests $ cargo build --release $ ./target/release/claptests --help ``` -------------------------------- ### binary_search example setup Source: https://docs.rs/bytes/1.12.1/bytes/struct.BytesMut.html Initializes a slice for the binary_search example. The slice is used to look up a series of four elements. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; ``` -------------------------------- ### Run the regex example Source: https://docs.rs/regex/%5E1.5.5 Command to run the project and the expected output. ```bash $ cargo run Compiling memchr v2.5.0 Compiling regex-syntax v0.7.1 Compiling aho-corasick v1.0.1 Compiling regex v1.8.1 Compiling regex-example v0.1.0 (/tmp/regex-example) Finished dev [unoptimized + debuginfo] target(s) in 4.22s Running `target/debug/regex-example` The name is: Murphy ``` -------------------------------- ### dont_delimit_trailing_values example Source: https://docs.rs/clap/4.6.6/clap/struct.Command.html Disables automatic delimiting of values after `--` or when `Arg::trailing_var_arg` is used. The example shows the minimal setup. ```rust Command::new("myprog") .dont_delimit_trailing_values(true) .get_matches(); ``` -------------------------------- ### build example Source: https://docs.rs/tokio/1.53.1/tokio/runtime/struct.Builder.html Creates a configured Runtime instance ready to spawn tasks. The example builds a multi-thread runtime and runs a block_on with a print statement. ```rust use tokio::runtime::Builder; let rt = Builder::new_multi_thread().build().unwrap(); rt.block_on(async { println!("Hello from the Tokio runtime"); }); ``` -------------------------------- ### Builder::method_ref() example Source: https://docs.rs/http/1.5.0/x86_64-unknown-linux-gnu/http/request/struct.Builder.html Gets the current HTTP method. Initially returns GET, after setting to POST returns POST. ```rust let mut req = Request::builder(); assert_eq!(req.method_ref(),Some(&Method::GET)); req = req.method("POST"); assert_eq!(req.method_ref(),Some(&Method::POST)); ``` -------------------------------- ### Set up NSApplication with window and delegate in Rust Source: https://docs.rs/crate/objc2/0.6.4/target-redirect/objc2 Shows how to configure an NSApplication window, set its delegate, and run the app. Includes setting the activation policy and activating the app when launching unbundled. The delegate implements NSWindowDelegate to quit on window close. ```rust // Set various window properties. window.setTitle(ns_string!("A window")); let view = window.contentView().expect("window must have content view"); unsafe { view.addSubview(&text_field) }; window.center(); unsafe { window.setContentMinSize(NSSize::new(300.0, 300.0)) }; window.setDelegate(Some(ProtocolObject::from_ref(self))); // Show the window. window.makeKeyAndOrderFront(None); // Store the window in the delegate. self.ivars().window.set(window).unwrap(); app.setActivationPolicy(NSApplicationActivationPolicy::Regular); // Activate the application. // Required when launching unbundled (as is done with Cargo). #[allow(deprecated)] app.activateIgnoringOtherApps(true); } } // SAFETY: `NSWindowDelegate` has no safety requirements. unsafe impl NSWindowDelegate for Delegate { #[unsafe(method(windowWillClose:))] fn window_will_close(&self, _notification: &NSNotification) { // Quit the application when the window is closed. unsafe { NSApplication::sharedApplication(self.mtm()).terminate(None) }; } } ); impl Delegate { fn new(mtm: MainThreadMarker) -> Retained { let this = Self::alloc(mtm).set_ivars(AppDelegateIvars::default()); // SAFETY: The signature of `NSObject`'s `init` method is correct. unsafe { msg_send![super(this), init] } } } fn main() { let mtm = MainThreadMarker::new().unwrap(); let app = NSApplication::sharedApplication(mtm); let delegate = Delegate::new(mtm); app.setDelegate(Some(ProtocolObject::from_ref(&*delegate))); app.run(); } ``` -------------------------------- ### Run examples with cargo run --example Source: https://docs.rs/crate/oxidize-pdf/1.4.0 Run any of the provided examples from the examples/ directory. Each command executes a different example: recovery_corrupted_pdf, png_transparency_watermark, and cjk_text_extraction. ```shell cargo run --example recovery_corrupted_pdf cargo run --example png_transparency_watermark cargo run --example cjk_text_extraction ``` -------------------------------- ### Timestamp::as_nanoseconds() example Source: https://docs.rs/time/0.3.55/time/struct.Timestamp.html Gets the number of nanoseconds since the Unix epoch. The example asserts the value for a given timestamp. ```rust assert_eq!( timestamp!(1_546_398_245.006_007_008).as_nanoseconds(), 1_546_398_245_006_007_008 ); ``` -------------------------------- ### Timestamp::as_microseconds() example Source: https://docs.rs/time/0.3.55/time/struct.Timestamp.html Gets the number of microseconds since the Unix epoch. The example asserts the value for a given timestamp. ```rust assert_eq!( timestamp!(1_546_398_245.006_007).as_microseconds(), 1_546_398_245_006_007 ); ``` -------------------------------- ### Help output for Arg::help example Source: https://docs.rs/clap/2.34.0/clap/struct.Arg.html Example output of the help message generated by the previous example. Shows the argument's help text next to the `--config` flag. ```text helptest USAGE: helptest [FLAGS] FLAGS: --config Some help text describing the --config arg -h, --help Prints help information -V, --version Prints version information ``` -------------------------------- ### Timestamp::as_milliseconds() example Source: https://docs.rs/time/0.3.55/time/struct.Timestamp.html Gets the number of milliseconds since the Unix epoch. The example asserts the value for a given timestamp. ```rust assert_eq!( timestamp!(1_546_398_245.006).as_milliseconds(), 1_546_398_245_006 ); ``` -------------------------------- ### Example: printing CPU counts (examples/values.rs) Source: https://docs.rs/num_cpus/1.17.0/num_cpus/fn.get_physical.html Minimal example from examples/values.rs that prints the logical and physical CPU counts using num_cpus::get() and num_cpus::get_physical(). ```rust fn main() { println!("Logical CPUs: {}", num_cpus::get()); println!("Physical CPUs: {}", num_cpus::get_physical()); } ``` -------------------------------- ### Example: loading ONNX Runtime from a library path Source: https://docs.rs/ort/2.0.0-rc.13/ort/environment/fn.init_from.html Example usage of `init_from` to load ONNX Runtime from a library file, configure execution providers (CUDA if enabled), and commit the builder. Must be called before using other `ort` APIs. ```rust let lib_path = std::env::current_exe().unwrap().parent().unwrap().join("lib"); ort::init_from(lib_path.join("onnxruntime.dll"))? .with_execution_providers([ #[cfg(feature = "cuda")] ep::CUDA::default().build() ]) .commit(); ``` -------------------------------- ### Timestamp::as_seconds() example Source: https://docs.rs/time/0.3.55/time/struct.Timestamp.html Gets the number of seconds since the Unix epoch. The example asserts the value for a given timestamp. ```rust assert_eq!(timestamp!(1_546_398_245).as_seconds(), 1_546_398_245); ``` -------------------------------- ### Example: Path::parent Source: https://docs.rs/tempfile/3.27.0/tempfile/struct.TempPath.html Example from the documentation of Path::parent, showing how to get the parent path and handle edge cases. ```rust use std::path::Path; let path = Path::new("/foo/bar"); let parent = path.parent().unwrap(); assert_eq!(parent, Path::new("/foo")); let grand_parent = parent.parent().unwrap(); assert_eq!(grand_parent, Path::new("/")); assert_eq!(grand_parent.parent(), None); let relative_path = Path::new("foo/bar"); let parent = relative_path.parent(); assert_eq!(parent, Some(Path::new("foo"))); let grand_parent = parent.and_then(Path::parent); assert_eq!(grand_parent, Some(Path::new(""))); let great_grand_parent = grand_parent.and_then(Path::parent); assert_eq!(great_grand_parent, None); ```