### Example Commit Messages Source: https://github.com/dmitribogdanov/utl/blob/master/docs/dev_project_style.md Illustrative examples of correctly formatted commit messages, demonstrating various types and scopes. ```text feat(mvl): Mostly implemented sparse and dense blocking operations. chore(): Typo fixes in comments & documentation. docs(mvl): Fixes some incorrect definitions and wonky SVG rendering. docs(): Improved table with used tools & libraries. ``` -------------------------------- ### C++ In-Code Header Style 2 Source: https://github.com/dmitribogdanov/utl/blob/master/docs/dev_project_style.md Example of a medium C++ in-code header style using hyphens for separation. ```cpp // --- Header 2 --- // ---------------- ``` -------------------------------- ### C++ In-Code Header Style 3 Source: https://github.com/dmitribogdanov/utl/blob/master/docs/dev_project_style.md Example of a concise C++ in-code header style using single hyphens. ```cpp // - Header 3 - ``` -------------------------------- ### C++ In-Code Header Style 1 Source: https://github.com/dmitribogdanov/utl/blob/master/docs/dev_project_style.md Example of a prominent C++ in-code header style using multiple lines and equals signs for emphasis. ```cpp // ================ // --- Header 1 --- // ================ ``` -------------------------------- ### Clone UTL Repository Source: https://github.com/dmitribogdanov/utl/blob/master/docs/guide_building_project.md Clones the UTL Git repository and navigates into its directory. This is the initial step for both script-based and manual builds. ```bash git clone https://github.com/DmitriBogdanov/UTL.git && cd "UTL/" ``` -------------------------------- ### Example: Ruler Progress Bar for Workload Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_progressbar.md This example demonstrates how to use the `Ruler` progress bar to visualize the progress of a simulated workload. It initializes the bar, updates its progress iteratively, and then calls `finish()` upon completion. ```cpp using namespace utl; using namespace std::chrono_literals; const int iterations = 1500; const auto some_work = [] { std::this_thread::sleep_for(10ms); }; progressbar::Percentage bar; for (int i = 0; i < iterations; ++i) { some_work(); bar.set_progress((i + 1.) / iterations); } bar.finish(); ``` -------------------------------- ### Configure and Build Project using Script Source: https://github.com/dmitribogdanov/utl/blob/master/docs/guide_building_project.md Executes the `actions.sh` script to clear, configure, and build the project. This provides a streamlined way to set up the build environment. ```bash bash actions.sh clear config build ``` -------------------------------- ### Run Specific Benchmark Executable Source: https://github.com/dmitribogdanov/utl/blob/master/docs/guide_building_project.md Executes a specific compiled benchmark by name from the build directory. Benchmarks are implemented using the nanobench library. ```bash ./build/benchmarks/ ``` -------------------------------- ### Run All Tests using Script Source: https://github.com/dmitribogdanov/utl/blob/master/docs/guide_building_project.md Executes the `actions.sh` script to run all configured unit tests. This leverages CTest facilities for test execution. ```bash bash actions.sh test ``` -------------------------------- ### Manually Configure CMake Project Source: https://github.com/dmitribogdanov/utl/blob/master/docs/guide_building_project.md Configures the CMake project, specifying the C++ compiler and the build output directory. This prepares the project for manual compilation. ```bash cmake -D CMAKE_CXX_COMPILER=g++ -B "build/" -S . ``` -------------------------------- ### Manually Build Project and Create Single Header Source: https://github.com/dmitribogdanov/utl/blob/master/docs/guide_building_project.md First, runs a script to create a single header file, then initiates the CMake build process. This compiles the project after manual configuration. ```bash bash "bash/create_single_header.sh" cmake --build "build/" ``` -------------------------------- ### Configure Compiler and CTest Flags Source: https://github.com/dmitribogdanov/utl/blob/master/docs/guide_building_project.md Shows how to modify the `compiler` and `test_flags` variables in `bash/variables.sh` to customize the build and test behavior. This allows selection of compiler and CTest options. ```bash compiler="g++" test_flags="--rerun-failed --output-on-failure --timeout 60" ``` -------------------------------- ### Basic CLI Progress Bar Showcase Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_progressbar.md Examples of the default visual styles for `utl::progressbar::Percentage` and `utl::progressbar::Ruler` when displayed in a Command Line Interface. ```CLI Output // progressbar::Percentage with default style [############..................] 42.67% (remaining: 8 sec) // progressbar::Ruler with default style 0 10 20 30 40 50 60 70 80 90 100% |----|----|----|----|----|----|----|----|----|----| ####################### ``` -------------------------------- ### C++: Example usage of the MAP macro Source: https://github.com/dmitribogdanov/utl/blob/master/docs/blog/map_macro_reflection.md This example shows `MAP` applying `F` to arguments `a, b, c, d`. It demonstrates `MAP(F, a, b, c, d)` expands to `F(a) F(b) F(c) F(d)`, iterating over arguments and applying the macro. ```cpp MAP(F, a, b, c, d) ``` -------------------------------- ### Example: Trimming Strings (C++) Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_stre.md Illustrates the usage of trim_left, trim_right, and trim functions from the utl library to remove leading, trailing, or both leading and trailing characters (whitespace by default, or a specified character) from strings. This example demonstrates common string cleaning operations. ```cpp using namespace utl; assert(stre::trim_left( " lorem ipsum ") == "lorem ipsum "); assert(stre::trim_right(" lorem ipsum ") == " lorem ipsum" ); assert(stre::trim( " lorem ipsum ") == "lorem ipsum" ); assert(stre::trim("__ASSERT_MACRO__", '_') == "ASSERT_MACRO"); ``` -------------------------------- ### Initialize and start C++ Stopwatch Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_time.md The `Stopwatch` class provides functionality for measuring elapsed time. This snippet shows the default constructor and the `start()` method, which initiates the time measurement from the current moment. The `start()` method can be called to reset and restart the timer. ```APIDOC Stopwatch(); void start(); ``` -------------------------------- ### C++ Bit Manipulation: Get, Set, Clear, Flip Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_bit.md This C++ snippet demonstrates how to manipulate individual bits of an 8-bit unsigned integer using the `utl::bit` functions. It shows `get` to read a bit's value, `set` to set a bit to 1, `clear` to set a bit to 0, and `flip` to invert a bit's value. The example uses `static_assert` to verify the results against expected values, illustrating the right-to-left bit indexing. ```C++ using namespace utl; constexpr std::uint8_t x = 19; // 19 ~ 00010011 // human-readable notation is big-endian, which means bits are indexed right-to-left // Read bits static_assert(bit::get(x, 0) == 1); static_assert(bit::get(x, 1) == 1); static_assert(bit::get(x, 2) == 0); static_assert(bit::get(x, 3) == 0); static_assert(bit::get(x, 4) == 1); static_assert(bit::get(x, 5) == 0); static_assert(bit::get(x, 6) == 0); static_assert(bit::get(x, 7) == 0); // Modify bits static_assert(bit::set( x, 2) == 23); // 23 ~ 00010111 static_assert(bit::clear(x, 0) == 18); // 18 ~ 00010010 static_assert(bit::flip( x, 1) == 17); // 17 ~ 00010001 ``` -------------------------------- ### C++ Module Template for UTL Project Source: https://github.com/dmitribogdanov/utl/blob/master/docs/dev_project_style.md Provides a standardized C++ module template for the UTL project, including licensing, versioning, includes, developer documentation, implementation, and public API sections. Replace 'XXXXXXXXXXXX' with the module name. ```cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DmitriBogdanov/UTL ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Module: utl::XXXXXXXXXXXX // Documentation: https://github.com/DmitriBogdanov/UTL/blob/master/docs/module_XXXXXXXXXXXX.md // Source repo: https://github.com/DmitriBogdanov/UTL // // This project is licensed under the MIT License // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #if !defined(UTL_PICK_MODULES) || defined(UTLMODULE_XXXXXXXXXXXX) #ifndef UTLHEADERGUARD_XXXXXXXXXXXX #define UTLHEADERGUARD_XXXXXXXXXXXX #define UTL_XXXXXXXXXXXX_VERSION_MAJOR 1 #define UTL_XXXXXXXXXXXX_VERSION_MINOR 0 #define UTL_XXXXXXXXXXXX_VERSION_PATCH 0 // _______________________ INCLUDES _______________________ // NOTE: STD INCLUDES // ____________________ DEVELOPER DOCS ____________________ // NOTE: DOCS // ____________________ IMPLEMENTATION ____________________ namespace utl::XXXXXXXXXXXX::impl { // NOTE: IMPL } // namespace utl::XXXXXXXXXXXX // ______________________ PUBLIC API ______________________ namespace utl::XXXXXXXXXXXX { // NOTE: API } // namespace utl::XXXXXXXXXXXX #endif #endif // module utl::XXXXXXXXXXXX ``` -------------------------------- ### C++ Example: Generating Various Random Values Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_random.md An illustrative C++ code example showcasing the practical usage of various random number generation functions from the `utl` library. It demonstrates how to generate uniform integers, booleans, and floats, as well as normally distributed doubles and values from custom distributions like `std::exponential_distribution`. ```cpp using namespace utl; // Generic functions std::cout << "integer U[-5, 5] -> " << random::uniform(-5, 5) << "\n" << "boolean U[0, 1] -> " << random::uniform() << "\n" << "float U[1, 2) -> " << random::uniform(1.f, 2.f) << "\n" << "float U[0, 1) -> " << random::uniform() << "\n"; // Standard shortcuts std::cout << "U[0, 1] -> " << random::uniform_bool() << "\n" << "N(0, 1) -> " << random::normal_double() << "\n"; // Other distributions std::cout << "Exp(4) -> " << random::variate(std::exponential_distribution{4.f}) << "\n"; ``` -------------------------------- ### utl::table C++ API Reference Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_table.md Detailed API documentation for the `utl::table` utility, outlining its core type definitions, table setup methods, drawing functionalities, and predefined format flags for controlling output appearance. ```APIDOC utl::table: Type Definitions: uint: std::streamsize Table Setup Methods: create(widths: std::initializer_list &&): Description: Sets up table with given column widths. Similar to LaTeX `|c{1cm}|c{1cm}|c{1cm}|` syntax. set_formats(formats: std::initializer_list &&): Description: Sets up column std::ios flags. Mainly used with build-in `table::` flags to change float formatting. set_ostream(new_ostream: std::ostream &): Description: Redirects output to given `std::ostream`. By default `std::cout` is used. set_latex_mode(toggle: bool): Description: Enables/disables LaTeX-compatible formatting. Tables rendered with this option on will use LaTeX formatting and automatically wrap numbers in formula blocks. This is useful for exporting tables that can be copy-pasted into a LaTeX document. Drawing Methods: cell(value: const T&, other_values: const Types&...): Description: Draws cells with given values, accepts any number of arguments and can be used to draw entire rows in a single line. Similar to LaTeX `val1 & val2 & val3 \\` except line breaks are placed automatically based on the table width. hline(): Description: Draws a horizontal line. Similar to LaTeX `\\hline`. Format Flags: NONE: Description: Default format flag, sets no flags. FIXED(decimals: uint = 3): Description: Sets fixed float representation with given precision. DEFAULT(decimals: uint = 6): Description: Sets default float representation with given precision. SCIENTIFIC(decimals: uint = 3): Description: Sets scientific float representation with given precision. BOOL: Description: Makes booleans render as `true` & `false`. ``` -------------------------------- ### Manually Run CTest Unit Tests Source: https://github.com/dmitribogdanov/utl/blob/master/docs/guide_building_project.md Navigates to the build tests directory and executes CTest with specific flags for re-running failed tests, showing output on failure, and setting a timeout. This allows manual control over test execution. ```bash cd "build/tests/" && ctest --rerun-failed --output-on-failure --timeout 60 && cd .. ``` -------------------------------- ### C++ Module Tests Template for UTL Project Source: https://github.com/dmitribogdanov/utl/blob/master/docs/dev_project_style.md Defines a standardized C++ test file template for UTL modules, integrating 'doctest' for unit testing. Includes sections for test framework, module includes, standard includes, developer documentation, and implementation. Replace 'XXXXXXXXXXXX' with the module name. ```cpp // _______________ TEST FRAMEWORK & MODULE _______________ #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "thirdparty/doctest.h" #include "module_XXXXXXXXXXXX.hpp" // _______________________ INCLUDES _______________________ // NOTE: STD INCLUDES // ____________________ DEVELOPER DOCS ____________________ // NOTE: DOCS // ____________________ IMPLEMENTATION ____________________ // NOTE: IMPL ``` -------------------------------- ### Commit Types for Project Style Guide Source: https://github.com/dmitribogdanov/utl/blob/master/docs/dev_project_style.md Defines standard commit types used in the project, categorizing changes for clear commit history. ```APIDOC Type: feat, Description: New features Type: test, Description: New unit tests Type: fix, Description: Bugfixes Type: refactor, Description: Code refactors Type: docs, Description: Documentation changes Type: build, Description: Build script changes Type: chore, Description: Typo fixes, file renames and etc ``` -------------------------------- ### Start C++ Timer with specified duration length Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_time.md The `start()` method of the `Timer` class initiates the timer with a specified `length` duration. This allows the timer to track whether the elapsed time has exceeded the set length. An explicit constructor is also provided to initialize and start the timer with a given length. ```APIDOC template explicit Timer(std::chrono::duration length); template void start(std::chrono::duration length); ``` -------------------------------- ### Convert String Case with UTL C++ Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_stre.md Illustrates how to convert string case using the UTL library's `stre` namespace. Shows examples for converting strings to lowercase and uppercase. ```cpp using namespace utl; assert(stre::to_lower("Lorem Ipsum") == "lorem ipsum"); assert(stre::to_upper("lorem ipsum") == "LOREM IPSUM"); ``` -------------------------------- ### C++: Expanded output of the MAP macro example Source: https://github.com/dmitribogdanov/utl/blob/master/docs/blog/map_macro_reflection.md This snippet shows the preprocessor expansion of `MAP(F, a, b, c, d)`. It clarifies how `F` is individually applied to each argument, resulting in a sequence of macro calls without commas. ```cpp F(a) F(b) F(c) F(d) ``` -------------------------------- ### C++ Mathematical Utilities for Grid Generation, Memory Usage, and Integration Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_math.md This C++ snippet demonstrates how to generate linearly spaced grids using `math::linspace` and calculate the memory occupied by the grid. It also shows how to numerically integrate a function over an interval using the `math::integrate_trapezoidal` method, providing an example with a custom lambda function. ```cpp // Mesh interval [0, PI] into 100 equal intervals => 101 linearly spaced points auto grid_1 = math::linspace(0., math::PI, math::Intervals(100)); auto grid_2 = math::linspace(0., math::PI, math::Points( 101)); // same as above // Get array memory size std::cout << "'grid_1' occupies " << math::memory_size(grid_1.size()) << " KB in memory\n\n"; // Integrate a function over an interval auto f = [](double x){ return 4. / (1. + std::tan(x)); }; double integral = math::integrate_trapezoidal(f, 0., math::PI_HALF, math::Intervals(200)); std::cout << "Integral evaluates to: " << integral << " (should be ~PI)\n"; ``` -------------------------------- ### Pad Strings with UTL C++ Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_stre.md Demonstrates various string padding functions provided by the UTL library's `stre` namespace. Includes examples for left, right, and center padding with custom characters, and padding numbers with leading zeroes. ```cpp using namespace utl; assert(stre::pad_left( "value", 9) == " value"); assert(stre::pad_right("value", 9) == "value "); assert(stre::pad( "value", 9) == " value "); assert(stre::pad(" label ", 15, '-') == "---- label ----"); assert(stre::pad_with_leading_zeroes(17) == "0000000017"); ``` -------------------------------- ### utl::timer::start() Method Reference Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_timer.md Sets the internal start time-point for subsequent elapsed time measurements. This function is `noexcept`. ```cpp void start() noexcept; ``` -------------------------------- ### Commit Message Format Specification Source: https://github.com/dmitribogdanov/utl/blob/master/docs/dev_project_style.md Specifies the required format for commit messages, including type, optional scope, and summary. Guidelines for omitting scope and using 'GLOBAL' are provided. ```APIDOC (): . // repeat for all changes according to commit types // can be omitted for some minor changes // Use = GLOBAL to signify large sweeping changes that affect the whole project ``` -------------------------------- ### Get C++ Compilation Summary using UTL Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_predef.md This snippet demonstrates how to use utl::predef::compilation_summary() from the UTL library to retrieve detailed information about the compilation environment. It outputs compiler name, platform, architecture, debug status, operating system, and compilation date. ```cpp std::cout << utl::predef::compilation_summary(); ``` ```Output Compiler: GNU C/C++ Compiler Platform: Linux Architecture: x86-64 Compiled in DEBUG: false Compiled under OS: true Compilation date: Dec 1 2024 03:47:20 ``` -------------------------------- ### Wrap Eigen Matrix with utl::mvl::MatrixView Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_mvl.md This C++ example demonstrates how to integrate an `Eigen::MatrixXd` with `utl::mvl`. It shows how to create an `mvl::MatrixView` from an existing Eigen matrix, allowing `mvl` functions to operate on the Eigen data without copying, facilitating interoperability between the two libraries. ```cpp Eigen::MatrixXd A; // in Eigen col-major by default // Do some computation with 'A' mvl::MatrixView view(A.rows(), A.cols(), A.data()); // Use 'view' like any other MVL matrix ``` -------------------------------- ### Demonstrating C++ Integer Division Rounding with UTL Library Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_integral.md This C++ snippet showcases the `utl::integral` functions for integer division: `div_floor` (rounds to smaller), `div_ceil` (rounds to larger), `div_down` (rounds towards zero), and `div_up` (rounds away from zero). It includes examples with both positive and negative dividends to illustrate their distinct rounding behaviors. ```C++ using namespace utl; static_assert( integral::div_floor(7, 5) == 1 ); // round to smaller static_assert( integral::div_ceil( 7, 5) == 2 ); // round to larger static_assert( integral::div_down( 7, 5) == 1 ); // round to 0 static_assert( integral::div_up( 7, 5) == 2 ); // round away from 0 static_assert( integral::div_floor(-7, 5) == -2 ); // round to smaller static_assert( integral::div_ceil( -7, 5) == -1 ); // round to larger static_assert( integral::div_down( -7, 5) == -1 ); // round to 0 static_assert( integral::div_up( -7, 5) == -2 ); // round away from 0 ``` -------------------------------- ### Perform Substring Checks with UTL C++ Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_stre.md This snippet demonstrates how to use the utl::stre namespace functions for basic substring checks. It includes examples for starts_with to check if a string begins with a specific prefix, ends_with for checking suffixes, and contains to verify if a substring exists anywhere within a string. ```cpp using namespace utl; assert(stre::starts_with("lorem ipsum", "lorem")); assert(stre::ends_with( "lorem ipsum", "ipsum")); assert(stre::contains( "lorem ipsum", "em ip")); ``` -------------------------------- ### Demonstrating String Utilities in C++ Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_stre.md This C++ code snippet showcases various string manipulation utilities from the `utl` library. It includes examples for repeating characters or strings, escaping control characters in a string, and finding the first index where two strings differ. The output demonstrates the effect of escaping control characters, showing how `\r` is represented. ```cpp using namespace utl; // Repeating chars/strings assert(stre::repeat_char( 'h', 7) == "hhhhhhh" ); assert(stre::repeat_string("xo-", 5) == "xo-xo-xo-xo-xo-"); // Escaping control chars in a string const std::string text = "this text\r will get messed up due to\r carriage returns."; std::cout << "Original string prints like this:\n" << text << "\n\n" << "Escaped string prints like this:\n" << stre::escape_control_chars(text) << "\n\n"; // Getting index of difference assert(stre::index_of_difference("xxxAxx", "xxxxxx") == 3); ``` -------------------------------- ### C++ Struct Reflection Debug Printing Example Source: https://github.com/dmitribogdanov/utl/blob/master/docs/blog/map_macro_reflection.md Illustrates a practical application of struct reflection for simplified debug printing. By reflecting the Quaternion struct and using utl::struct_reflect::entry_view, the struct's contents can be easily serialized and logged, producing output like q = < < r, 0.5 >, < i, 1.5 >, < j, 2.5 >, < k, 3.5 > >. ```cpp // Define struct & reflection struct Quaternion { double r, i, j, k; }; // could be any struct with a lot of fields UTL_STRUCT_REFLECT(Quaternion, r, i, j, k); // ... // Print struct using namespace utl; constexpr Quaternion q = { 0.5, 1.5, 2.5, 3.5 }; log::println("q = ", struct_reflect::entry_view(q)); ``` -------------------------------- ### C++: Expanded output of the MAP_LIST macro Source: https://github.com/dmitribogdanov/utl/blob/master/docs/blog/map_macro_reflection.md This example illustrates `MAP_LIST` behavior, similar to `MAP` but inserting commas. `MAP_LIST(F, a, b, c, d)` expands to `F(a), F(b), F(c), F(d)`, useful for generating comma-separated lists. ```cpp F(a), F(b), F(c), F(d) ``` -------------------------------- ### Define and Specialize utl::mvl GenericTensor Class Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_mvl.md This C++ snippet shows the generic template definition for `utl::mvl::GenericTensor`, which forms the basis for all vectors, matrices, and views. It also provides an example of manual specialization using a `typedef` to create an `IntegerMatrix` with specific template parameters, demonstrating how to configure tensor behavior. ```cpp // Generic template template < class T, Dimension dimension, Type type, Ownership ownership, Checking checking, Layout layout > class GenericTensor; // Example of manual specialization using IntegerMatrix = GenericTensor; ``` -------------------------------- ### Get Block Subview by Coordinates in C++ Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_mvl.md Returns a block subview of the tensor starting at `(i, j)` with dimensions `rows` x `cols`. This method requires the tensor to be a MATRIX. ```cpp block_view_type block(size_type i, size_type j, size_type rows, size_type cols); // requires MATRIX block_const_view_type block(size_type i, size_type j, size_type rows, size_type cols) const; // requires MATRIX ``` -------------------------------- ### Get C++ Timer elapsed time as Clock::duration Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_time.md The `elapsed()` method of the `Timer` class returns the time that has passed since the last call to `start()`. The returned value is a `Clock::duration`, representing the elapsed time in its native integer-based format. ```APIDOC duration elapsed() const; ``` -------------------------------- ### Get C++ Timer elapsed time as formatted string Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_time.md The `elapsed_string()` method of the `Timer` class returns the time elapsed since the last `start()` call as a formatted `std::string`. The formatting follows the conventions of the `time::to_string()` function, providing a human-readable output. ```APIDOC std::string elapsed_string() const; ``` -------------------------------- ### Drawing a formatted table in C++ using UTL Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_table.md This C++ snippet demonstrates how to create and populate a formatted table using the `utl::table` utility. It initializes the table with specified column widths, applies various data formats (none, default, fixed-point, scientific, boolean) to columns, and then populates the table with header and data rows. The output shows a well-aligned table with formatted numerical and boolean values. Example Output: |----------------|----------------|----------------|----------------|--------------------| | Method| Threads| Speedup| Error| Err. within range| |----------------|----------------|----------------|----------------|--------------------| | Gauss| 16| 11.85| 1.960e-04| false| | Jacobi| 16| 15.51| 1.370e-05| false| | Seidel| 16| 13.41| 1.740e-06| true| | Relaxation| 16| 13.93| 1.170e-06| true| |----------------|----------------|----------------|----------------|--------------------| ```cpp using namespace utl; table::create({ 16, 16, 16, 16, 20 }); table::set_formats({ table::NONE, table::DEFAULT(), table::FIXED(2),table::SCIENTIFIC(3), table::BOOL }); table::hline(); table::cell("Method", "Threads", "Speedup", "Error", "Err. within range"); table::hline(); table::cell("Gauss", 16, 11.845236, 1.96e-4, false); table::cell("Jacobi", 16, 15.512512, 1.37e-5, false); table::cell("Seidel", 16, 13.412321, 1.74e-6, true ); table::cell("Relaxation", 16, 13.926783, 1.17e-6, true ); table::hline(); ``` -------------------------------- ### Get C++ Stopwatch elapsed time as formatted string Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_time.md The `elapsed_string()` method of the `Stopwatch` class returns the time elapsed since the last `start()` call or construction as a formatted `std::string`. The formatting follows the conventions of the `time::to_string()` function, providing a human-readable output. ```APIDOC std::string elapsed_string() const; ``` -------------------------------- ### Get C++ Stopwatch elapsed time as Clock::duration Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_time.md The `elapsed()` method of the `Stopwatch` class returns the time that has passed since the last call to `start()` or the `Stopwatch`'s construction. The returned value is a `Clock::duration`, representing the elapsed time in its native integer-based format. ```APIDOC duration elapsed() const; ``` -------------------------------- ### Get Specific JSON Node Type (C++) Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_json.md These are shortcut versions of `T& get()` for all possible JSON value types (object, array, string, number, bool, null). They return a reference to the value if the node holds the corresponding type. ```cpp object_type& get_object(); array_type & get_array(); string_type& get_string(); number_type& get_number(); bool_type & get_bool(); null_type & get_null(); const object_type& get_object() const; const array_type & get_array() const; const string_type& get_string() const; const number_type& get_number() const; const bool_type & get_bool() const; const null_type & get_null() const; ``` -------------------------------- ### Configure CMake Project for UTL Library Source: https://github.com/dmitribogdanov/utl/blob/master/CMakeLists.txt This CMake snippet defines the minimum required CMake version, sets up the UTL project with its version, description, and homepage URL, and includes necessary directories for headers, tests, and benchmarks. It ensures compatibility across a range of CMake versions and organizes the project structure. ```CMake cmake_minimum_required(VERSION 3.9.1...3.22.1) # should also work with all newer versions, the range specified # here is the based in the highest version tested in practice project( UTL VERSION 2.0.0 DESCRIPTION "Collection of self-contained utility libraries." HOMEPAGE_URL "https://github.com/DmitriBogdanov/UTL" ) # Source include_directories("include") # Tests & Benchmarks add_subdirectory("tests") add_subdirectory("benchmarks") ``` -------------------------------- ### Get Struct Fields as Tuple of References (C++) Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_struct_reflect.md Returns a std::tuple containing perfectly-forwarded references to all fields of the input value. This allows accessing struct members using a tuple-like API, preserving their original value category (const, l-value, r-value) and enabling generic algorithms. For example, if value is a const Struct&, the return type is std::tuple for an int x field. This effectively means that field_view allows struct members to be accessed exactly as one would expect when working with struct members directly, except using a tuple API. ```cpp template constexpr auto field_view(S&& value) noexcept; ``` -------------------------------- ### Get Current Date and Time using utl::time Library Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_time.md This snippet shows a simpler and more robust way to get the current date and time string using the utl::time::datetime_string() function. It emphasizes that this approach is thread-safe, compiles across different platforms, and includes internal error handling. ```cpp const auto result = time::datetime_string(); // thread-safe, compiles everywhere, handles possible format errors ``` -------------------------------- ### Get C++ Timer elapsed time as floating-point durations Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_time.md These methods provide various ways to retrieve the elapsed time from the `Timer` as floating-point durations. They offer convenience functions like `elapsed_ns()`, `elapsed_us()`, `elapsed_ms()`, `elapsed_sec()`, `elapsed_min()`, and `elapsed_hours()` to get the elapsed time directly in specific units, represented as `double`. ```APIDOC ns elapsed_ns() const; us elapsed_us() const; ms elapsed_ms() const; sec elapsed_sec() const; min elapsed_min() const; hours elapsed_hours() const; ``` -------------------------------- ### Execute Shell Commands with UTL C++ Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_shell.md This C++ snippet illustrates how to execute a shell command using `utl::shell::run_command`. It captures the command's exit status, standard output, and standard error. A warning notes that `std::system` might not work in online compilers. ```C++ const auto res = utl::shell::run_command("echo TEXT"); // usually used to invoke scripts and other executables assert(res.status == 0); assert(res.out == "TEXT"); assert(res.err == ""); ``` -------------------------------- ### Get C++ Stopwatch elapsed time as floating-point durations Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_time.md These methods provide various ways to retrieve the elapsed time from the `Stopwatch` as floating-point durations. They offer convenience functions like `elapsed_ns()`, `elapsed_us()`, `elapsed_ms()`, `elapsed_sec()`, `elapsed_min()`, and `elapsed_hours()` to get the elapsed time directly in specific units, represented as `double`. ```APIDOC ns elapsed_ns() const; us elapsed_us() const; ms elapsed_ms() const; sec elapsed_sec() const; min elapsed_min() const; hours elapsed_hours() const; ``` -------------------------------- ### Generate LaTeX-Compatible Table with UTL C++ Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_table.md This C++ snippet demonstrates how to use the UTL library to create a table and configure it for LaTeX output. It sets column widths, defines formatters for different data types (e.g., fixed-point, scientific, boolean), and populates the table with sample data. The `table::set_latex_mode(true)` call is crucial for rendering the table in a LaTeX-compatible format, as shown in the example output. ```C++ using namespace utl; table::create({ 10, 8, 8, 20, 18 }); table::set_formats({ table::NONE, table::DEFAULT(), table::FIXED(2),table::SCIENTIFIC(3), table::BOOL }); table::set_latex_mode(true); // <- adding this line makes table render in LaTeX format table::hline(); table::cell("Method", "Threads", "Speedup", "Error", "Err. within range"); table::hline(); table::cell("Gauss", 16, 11.845236, 1.96e-4, false); table::cell("Jacobi", 16, 15.512512, 1.37e-5, false); table::cell("Seidel", 16, 13.412321, 1.74e-6, true ); table::cell("Relaxation", 16, 13.926783, 1.17e-6, true ); table::hline(); ``` -------------------------------- ### C++: Flags class get underlying enum value Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_bit.md Returns the underlying `enum class` value. ```cpp constexpr E get() const noexcept; ``` -------------------------------- ### Demonstrate Sparse Matrix IO Formats in C++ Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_mvl.md This snippet illustrates the creation of a `mvl::SparseMatrix` from triplet data and its subsequent display using various `mvl::format` functions. It showcases human-readable outputs such as vector, matrix, and dictionary representations, alongside export formats like raw text and JSON array. A note is included regarding the automatic collapsing of large matrices for human-readable formats. ```C++ using namespace utl; // Create sparse matrix from triplets mvl::SparseMatrix mat(3, 4, { {0, 0, 3.14 }, {0, 1, 4.24 }, {1, 1, 7.15 }, {2, 2, 2.38 }, {2, 3, 734.835 } }); // Showcase different IO formats std::cout // Human-readable formats << "\n## as_vector() ##\n\n" << mvl::format::as_vector( mat) << "\n## as_matrix() ##\n\n" << mvl::format::as_matrix( mat) << "\n## as_dictionary() ##\n\n" << mvl::format::as_dictionary(mat) // Export formats << "\n## as_raw_text() ##\n\n" << mvl::format::as_raw_text( mat) << "\n## as_json_array() ##\n\n" << mvl::format::as_json_array(mat); // Human-readable formats will automatically collapse matrices above certain size to following format: // > Tensor [size = 250000] (500 x 500): // > ``` ```Output ## as_vector() ## Tensor [size = 5] (3 x 4): { 3.14, 4.24, 7.15, 2.38, 734.835 } ## as_matrix() ## Tensor [size = 5] (3 x 4): [ 3.14 4.24 - - ] [ - 7.15 - - ] [ - - 2.38 734.835 ] ## as_dictionary() ## Tensor [size = 5] (3 x 4): (0, 0) = 3.14 (0, 1) = 4.24 (1, 1) = 7.15 (2, 2) = 2.38 (2, 3) = 734.835 ## as_raw_text() ## 3.14 4.24 0 0 0 7.15 0 0 0 0 2.38 734.835 ## as_json_array() ## [ [ 3.14, 4.24, 0, 0 ], [ 0, 7.15, 0, 0 ], [ 0, 0, 2.38, 734.835 ] ] ``` -------------------------------- ### GenericTensor Constructors: Initialization Options Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_mvl.md The `GenericTensor` class provides a comprehensive set of constructors for various initialization scenarios. This includes default, copy, and move constructors, as well as constructors for copying/moving across different template parameter boundaries. Specific constructors are available for initializing matrix-like tensors with dimensions, initial values, data pointers, or initializer lists. ```APIDOC // Default GenericTensor(); // requires CONTAINER // Copy/move GenericTensor(const self& other); GenericTensor(self&& other); self& operator=(const self& other); self& operator=(self&& other); // Copy over template parameter boundaries template GenericTensor(const GenericTensor<...>& other); template self& operator=(const GenericTensor<...>& other); // Move over template parameter boundaries template GenericTensor(GenericTensor<...>&& other); template self& operator=(GenericTensor<...>&& other); // 'Matrix' ctors (requires MATRIX && DENSE && CONTAINER) explicit GenericTensor(size_type rows, size_type cols, const_reference value = value_type()); explicit GenericTensor(size_type rows, size_type cols, Callable init_func); explicit GenericTensor(size_type rows, size_type cols, pointer data_ptr); GenericTensor(std::initializer_list> init_list); ``` -------------------------------- ### Initialize C++ Matrix with Chained Operations Source: https://github.com/dmitribogdanov/utl/blob/master/docs/module_mvl.md This C++ snippet demonstrates how to initialize a `mvl::Matrix` by chaining `fill` and `transform` operations. It populates the matrix with random values from a normal distribution and then applies an absolute value transformation. The `move()` method is used to optimize assignment and avoid copies. ```cpp using namespace utl; std::random_device rd; std::default_random_engine gen(rd()); std::normal_distribution dist(0., 1.); const auto rand_value = [&]() { return dist(gen); }; const auto abs = [&](double x){ return std::abs(x); }; // Build 5x5 matrix where {a_ij} = |N(0, 1)| // '.move()' avoids a copy when assigning 'A' auto A = mvl::Matrix(5, 5).fill(rand_value).transform(abs).move(); std::cout << mvl::format::as_matrix(A); ```