### Install and Use XML Mapping Library Source: https://programming-idioms.org/cheatsheet/Ruby Installs the 'xml-mapping' gem and demonstrates how to define a class with XML mapping capabilities. It shows how to map attributes and text nodes, initialize an object, and save it to XML format. ```shell gem install xml-mapping ``` ```ruby require 'xml/mapping' class Person include XML::Mapping attr_accessor :name, :surname, :age, :children text_node :from, "@from" text_node :name, "Name" text_node :surname, "Surname" def initialize(name, surname, ..) # ... end end x = Person.new(..) x.save_to_xml.write($stdout,2) # nicely prints x.save_to_file('data.xml') ``` -------------------------------- ### Print Hello World in D Source: https://programming-idioms.org/cheatsheet/D Prints the literal string 'Hello world!' to standard output. This is a basic example demonstrating output functionality. ```d import std.stdio; void main() { writeln("Hello world!"); } ``` ```d pragma(msg, "Hello World"); ``` -------------------------------- ### Print Hello World in C# Source: https://programming-idioms.org/cheatsheet/Csharp Prints the literal string 'Hello, World!' to the standard output. This is a basic introductory example in C#. ```csharp using System; Console.WriteLine("Hello, World!"); ``` -------------------------------- ### Print Hello World in Clojure Source: https://programming-idioms.org/cheatsheet/Clojure Prints the literal string 'Hello World' to standard output. This is a basic introductory example for Clojure. ```clojure (println "Hello World") ``` -------------------------------- ### Print Hello World in Kotlin Source: https://programming-idioms.org/cheatsheet/Kotlin Prints the literal string 'Hello world!' to the standard output. This is a basic introductory example for outputting text. ```kotlin println("Hello world!") ``` -------------------------------- ### Get list size in Ada Source: https://programming-idioms.org/cheatsheet/Ada Retrieves the number of elements in a list or vector. This example uses Ada.Containers.Vectors and assigns the Length attribute to a variable. ```Ada with Ada.Containers.Vectors; use Ada.Containers; N : Count_Type := X.Length; ``` -------------------------------- ### PHP: Print Hello World Source: https://programming-idioms.org/cheatsheet/PHP Demonstrates how to print the string 'Hello World' to standard output in PHP. Includes examples using 'echo', short echo syntax, and PHP_EOL for newlines. ```PHP echo "Hello World" . PHP_EOL; ``` ```PHP ``` ```PHP ``` -------------------------------- ### Count Backwards Loop Source: https://programming-idioms.org/cheatsheet/Cpp Prints numbers in descending order from a starting value down to zero. This C++ example uses a standard for loop to iterate backwards. ```cpp for (int i = 5; i >= 0; --i) { std::cout << i; } ``` -------------------------------- ### Get hexadecimal representation of an integer Source: https://programming-idioms.org/cheatsheet/Scala Assigns the hexadecimal representation (base 16) of an integer `x` to a string `s`. For example, 999 is converted to "3e7". ```scala val s = x.toString(16) ``` -------------------------------- ### Print Hello World in C++ Source: https://programming-idioms.org/cheatsheet/Cpp Demonstrates how to print the string "Hello World" to standard output using various C++ iostream and cstdio functions. Includes examples using std::cout, printf, and std::print with different header inclusions and namespaces. ```cpp #include std::cout << "Hello World" << std::endl; ``` ```cpp #include using namespace std; cout << "Hello World"; ``` ```cpp #include printf("Hello World"); ``` ```cpp #include fprintf(stdout, "Hello World"); ``` ```cpp #include std::print("Hello World"); ``` -------------------------------- ### Execute Function After Delay - PHP Source: https://programming-idioms.org/cheatsheet/PHP Schedules a function call to execute after a specified delay. In this example, `f(42)` is called 30 seconds after the script starts executing. ```PHP sleep(30); f(42); ``` -------------------------------- ### Create and Use a Queue Source: https://programming-idioms.org/cheatsheet/Pascal Demonstrates the creation and basic usage of a generic queue (TQueue). It involves creating a queue, enqueuing two elements, dequeuing one element, and then freeing the queue. ```Pascal type TQ = specialize TQueue; var x, y, z: TSomeType; Q: TQ; begin Q := TQ.Create; Q.Push(x); Q.Push(y); z := Q.Front; Q.Pop; Q.Free; end. ``` -------------------------------- ### Get Fraction and Exponent of Real Number Source: https://programming-idioms.org/cheatsheet/Ruby Given a real number, this function prints the fractional part and the exponent of its internal representation. For example, for 3.14, it approximates the output to '0.785 2'. ```ruby puts Math::frexp(a) ``` -------------------------------- ### Print 'Hello' 10 Times Using a Loop - Pascal Source: https://programming-idioms.org/cheatsheet/Pascal Demonstrates how to loop a specified number of times (10 in this case) to execute a command, printing 'Hello' in each iteration. ```Pascal var i: integer; begin for i:=1 to 10 do WriteLn('Hello'); end; ``` -------------------------------- ### Launch parallel tasks and wait Source: https://programming-idioms.org/cheatsheet/D Launches 1000 parallel tasks using `parallel` and `iota`, then waits for their completion. The wait is implicit in the parallel foreach loop. ```d import std.stdio; import std.parallelism; import std.range; foreach(i; parallel(iota(1,1001))){ f(i); } writeln("Finished"); ``` -------------------------------- ### Get Compiler Version and Options Source: https://programming-idioms.org/cheatsheet/Ruby Assigns the compiler version and compilation options to variables at runtime and prints them. For interpreted languages, it shows the interpreter version. For example, it might output GCC version and flags. ```ruby puts version = RUBY_VERSION ``` -------------------------------- ### Read command line argument Source: https://programming-idioms.org/cheatsheet/Rust Retrieves command line arguments passed to the program. This example shows how to get the first argument after the program name and provides a fallback value if no argument is present. Uses `env::args()`. ```Rust use std::env; let first_arg = env::args().skip(1).next(); let fallback = "".to_owned(); let x = first_arg.unwrap_or(fallback); ``` ```Rust use std::env; let x = env::args().nth(1).unwrap_or("".to_string()); ``` -------------------------------- ### Get current date/time in Java Source: https://programming-idioms.org/cheatsheet/Java Obtains the current date and time using standard Java types. The primary example uses `java.time.Instant`, introduced in Java 8. Alternative implementations show using `java.util.Date` and `System.currentTimeMillis`. ```java import java.time.Instant; Instant d = Instant.now(); ``` ```java import static java.util.Calendar.getInstance; import java.util.Date; Date a = getInstance().getTime(); String d = "%tc".formatted(a); ``` ```java import static java.lang.System.currentTimeMillis; long a = currentTimeMillis(); String d = "%tc".formatted(a); ``` -------------------------------- ### Create Folder in Filesystem (All Parents) in Go Source: https://programming-idioms.org/cheatsheet/Go Creates a directory at the specified path, including any necessary parent directories, using `os.MkdirAll`. This is more robust than `os.Mkdir` as it ensures the entire path exists. It returns an error if the directory cannot be created. Requires the 'os' package. ```go import "os" func createFolderRecursive(path string) error { err := os.MkdirAll(path, os.ModeDir) return err } ``` -------------------------------- ### Create a Map (Associative Array) in Clojure Source: https://programming-idioms.org/cheatsheet/Clojure Creates a new map named `x` initialized with key-value pairs. Keys are strings like 'One', 'Two', 'Three', and values are integers. The example shows how to retrieve a value using `get`. ```clojure (def x {"One" 1 "Two" 2 "Three" 3}) ``` -------------------------------- ### Print Hello World in Go Source: https://programming-idioms.org/cheatsheet/Go Prints the literal string "Hello World" to standard output. Requires the 'fmt' package. ```Go import "fmt" fmt.Println("Hello World") ``` -------------------------------- ### Check if String Contains Word in Lua Source: https://programming-idioms.org/cheatsheet/Lua Determines if a string 's' contains a specific 'word' as a substring. The 'find' method returns the starting index if found (truthy) or nil otherwise (falsy). Alternative implementations show how to get a direct boolean result. ```lua ok = s:find(word, 1, true) ``` ```lua ok = false if s:find(word, 1, true) then ok = true end ``` ```lua ok = s:find(word, 1, true) ~= nil ``` -------------------------------- ### Print 'Hello, world!' Literal String - Pascal Source: https://programming-idioms.org/cheatsheet/Pascal Prints the literal string 'Hello, world!' to standard output. This is a basic introductory example. ```Pascal WriteLn('Hello, world!'); ``` -------------------------------- ### Get String Length in Bytes - Lua Source: https://programming-idioms.org/cheatsheet/Lua Assign to 'n' the number of bytes in the string 's'. This can differ from the number of characters. For example, if 'n' includes more bytes than characters (e.g., trailing zero, length field), it will be reflected. One byte equals 8 bits. ```lua local n = #s ``` -------------------------------- ### Measure Function Call Duration using Nanoseconds() (Go) Source: https://programming-idioms.org/cheatsheet/Go An alternative method to measure function call duration in nanoseconds using the 'time' package. It captures the start time, calls the function, calculates the duration, and then uses the 'Nanoseconds()' method to get the duration in nanoseconds as an int64. Requires the 'time' package. ```Go import "time" t1 := time.Now() foo() t := time.Since(t1) ns := t.Nanoseconds() fmt.Printf("%dns\n", ns) ``` -------------------------------- ### Print 'Hello' 10 times in C Source: https://programming-idioms.org/cheatsheet/C Illustrates how to use a for loop in C to repeat a task a fixed number of times. This example prints the string 'Hello' ten times, each on a new line. ```c #include int main() { for (int i = 0; i < 10; i++) { printf("Hello\n"); } return 0; } ``` -------------------------------- ### Print Hello World in JavaScript Source: https://programming-idioms.org/cheatsheet/JS Demonstrates how to print the string 'Hello World!' to the browser document or console using JavaScript. Includes discouraged and recommended methods like `document.write` and `console.log`. ```javascript document.write("Hello World!"); ``` ```javascript console.log('Hello World'); ``` ```javascript console.log('Hello World') ``` -------------------------------- ### Check String Prefix Source: https://programming-idioms.org/cheatsheet/Pascal Checks if a string starts with a given prefix. String indices in Pascal start at 1. ```Pascal b := pos(prefix, s) = 1; ``` -------------------------------- ### Load from HTTP GET Request into String (D) Source: https://programming-idioms.org/cheatsheet/D Performs an HTTP GET request to a URL and stores the response body in a string. Requires 'std.net.curl' and 'std.conv'. ```d import std.net.curl; import std.conv; // Assuming 'u' is the URL string // string s = u.get.to!string; ``` -------------------------------- ### Print Hello World in Lisp Source: https://programming-idioms.org/cheatsheet/Lisp Demonstrates printing the literal string "Hello, world!" to standard output in Lisp. Includes alternative implementations using `princ`, `print`, and `format`. ```lisp (princ "Hello, world!") ``` ```lisp (print "Hello World") ``` ```lisp (format T "Hello World") ``` -------------------------------- ### Check String Prefix (Elixir) Source: https://programming-idioms.org/cheatsheet/Elixir Checks if a string `s` starts with a given `prefix`. Returns a boolean value: `true` if it starts with the prefix, `false` otherwise. ```elixir String.starts_with?(s,prefix) ``` -------------------------------- ### Get File Size (Perl) Source: https://programming-idioms.org/cheatsheet/Perl Retrieves the size of a file in bytes. The `-s` file test operator is used to efficiently get the file size. ```perl my $x = -s $path; ``` -------------------------------- ### Create and use a queue (Perl) Source: https://programming-idioms.org/cheatsheet/Perl Demonstrates the creation of a queue, enqueuing elements, and then dequeuing an element into a variable. This snippet requires a queue implementation, likely from a CPAN module, though the specific implementation is not shown. ```Perl use strict; # Queue creation, enqueue, and dequeue operations would follow here. ``` -------------------------------- ### Create temporary directory (Go) Source: https://programming-idioms.org/cheatsheet/Go Creates a new temporary directory on the filesystem for writing. It returns the directory path as a string and an error. Cleanup of the directory and its contents should be handled with `os.RemoveAll()`. ```Go import "os" dir, err := os.MkdirTemp("", "") ``` -------------------------------- ### Load HTTP GET Request into String Source: https://programming-idioms.org/cheatsheet/Pascal Performs an HTTP GET request to a given URL and stores the response body in a string. Uses the 'fphttpclient' unit. ```Pascal uses fphttpclient; with TFPHTTPClient.Create(nil) do try s := get(u); finally Free; end; ``` -------------------------------- ### Print 'Hello World' in C Source: https://programming-idioms.org/cheatsheet/C Demonstrates the basic syntax for printing a literal string to standard output in C. It requires the stdio.h header file for the printf function. ```c #include int main() { printf("Hello World\n"); return 0; } ``` -------------------------------- ### Alternative: Get list size (D) Source: https://programming-idioms.org/cheatsheet/D An alternative generic method to get the size of a list or array, working with built-in arrays and containers implementing an input range interface. ```D import std.range.primitives; n = walkLength(x); ``` -------------------------------- ### Get list size in Lua Source: https://programming-idioms.org/cheatsheet/Lua Sets the variable 'n' to the number of elements in the list 'x'. This is a common way to get the length of a table acting as a sequence. ```lua local n = #x ``` -------------------------------- ### Loop and Print 'Hello' 10 times in Go Source: https://programming-idioms.org/cheatsheet/Go Executes a loop to print the string "Hello" ten times. Demonstrates standard for loop and alternative using strings.Repeat. ```Go import "fmt" for i := 0; i < 10; i++ { fmt.Println("Hello") } ``` ```Go import "fmt" import "strings" fmt.Println(strings.Repeat("Hello\n", 10)) ``` ```Go import "fmt" for range 10 { fmt.Println("Hello") } ``` -------------------------------- ### Get File Size (Elixir) Source: https://programming-idioms.org/cheatsheet/Elixir Assigns the size of a local file in bytes to a variable `_x_`. It uses `File.stat!()` to get file information and then extracts the size. ```elixir def main(path) do _x = path |> File.stat!() |> Map.get(:size) end ``` -------------------------------- ### Check String Prefix - Fortran Source: https://programming-idioms.org/cheatsheet/Fortran Determines if a given string starts with a specific prefix. It utilizes the `index` function to find the starting position of the prefix within the string. ```Fortran logical :: b b = index (string, prefix) == 1 ``` -------------------------------- ### Create Folder in Filesystem (Single) in Go Source: https://programming-idioms.org/cheatsheet/Go Creates a directory at the specified path using `os.Mkdir`. This function will only create the directory if its parent directory already exists. It returns an error if the directory cannot be created. Requires the 'os' package. ```go import "os" func createFolder(path string) error { err := os.Mkdir(path, os.ModeDir) return err } ``` -------------------------------- ### Print Hello World in Python Source: https://programming-idioms.org/cheatsheet/Python Demonstrates how to print the literal string 'Hello World' to standard output in Python. It shows multiple ways to achieve this, including direct print statements and using sys.stdout. ```python print("Hello World") ``` ```python print('Hello World') ``` ```python from sys import stdout stdout.write('Hello World') ``` -------------------------------- ### Load from HTTP GET Request (Perl) Source: https://programming-idioms.org/cheatsheet/Perl Makes an HTTP GET request to a specified URL and stores the response body in a string. This requires the `HTTP::Tiny` module. ```perl use HTTP::Tiny qw(); # The code to make the request and store the response is missing in the provided snippet. ``` -------------------------------- ### Initialize Arbitrary Precision Quotient from String Source: https://programming-idioms.org/cheatsheet/Go Initializes a big.Rat quotient 'q' from a string representation. The string 'str' should include the numerator, a slash, and the denominator. ```Go import "math/big" q := new(big.Rat) q.SetString(str) ``` -------------------------------- ### Get File Size in Rust Source: https://programming-idioms.org/cheatsheet/Rust Assigns the length (in bytes) of a file at a given `path` to a variable `x`. It uses `std::fs::metadata` to get file metadata. ```rust use std::fs; // Assuming 'path' is a valid path string or Path object // let x = fs::metadata(path)?.len(); ``` -------------------------------- ### Prolog: Print Hello World Source: https://programming-idioms.org/cheatsheet/Prolog Prints the literal string 'Hello, world!' to standard output. This is a basic introductory example for Prolog output. ```Prolog write('Hello, world!\n') ``` ```Prolog format("Hello world~n") ``` -------------------------------- ### Load HTTP GET Request Body into String (XMLHttpRequest) Source: https://programming-idioms.org/cheatsheet/JS Loads the body of an HTTP GET request into a string using the native XMLHttpRequest object. This is an asynchronous operation. ```javascript var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) s = xmlHttp.responseText; } xmlHttp.open("GET", u, true); xmlHttp.send(null); ``` -------------------------------- ### Create Temporary Directory (Haskell) Source: https://programming-idioms.org/cheatsheet/Haskell Demonstrates the creation of a temporary directory for writing using `System.IO.Temp.withTempDirectory`. The directory is managed similarly to temporary files. ```Haskell import System.IO.Temp withTempDirectory $ \d -> do -- do something with d ``` -------------------------------- ### Get Current Date and Time in C# Source: https://programming-idioms.org/cheatsheet/Csharp Assigns the current date and time value to a variable of type DateTime. This is a standard way to get the current timestamp in C#. ```csharp DateTime d = DateTime.Now; ``` -------------------------------- ### Get Value from Map in Java Source: https://programming-idioms.org/cheatsheet/Java Retrieves the value associated with a specific key from a map. If the key is not found, `get()` returns null. `getOrDefault()` can be used to provide a default value. ```java import java.util.Map; Map m = Map.of("a", 1, "b", 2); Integer k = 1; // Using get() Integer v = m.get(k); // Using getOrDefault() Integer vOrDefault = m.getOrDefault(k, 0); ``` -------------------------------- ### Print Hello World in Dart Source: https://programming-idioms.org/cheatsheet/Dart Prints the literal string 'Hello World' to the standard output. This is a basic example demonstrating string output. ```dart print("Hello World"); ``` -------------------------------- ### Create and Initialize List (Fortran) Source: https://programming-idioms.org/cheatsheet/Fortran Declares an integer array 'items' of size 3 and initializes it with the values 'a', 'b', and 'c' using list initialization syntax. ```Fortran integer, dimension(3) :: items items = [a,b,c] ``` -------------------------------- ### Load HTTP GET Request Body into String (jQuery) Source: https://programming-idioms.org/cheatsheet/JS Loads the body of an HTTP GET request into a string using the jQuery library. Requires the jQuery library to be included. ```javascript ``` $.get(u, function(data){ s = data; }); ``` ``` -------------------------------- ### Create Temporary Directory (Ruby) Source: https://programming-idioms.org/cheatsheet/Ruby Shows how to create a temporary directory on the filesystem for writing purposes in Ruby using the 'tmpdir' library. ```ruby require 'tmpdir' td = Dir.mktmpdir ``` -------------------------------- ### Load from HTTP GET Request into File (D) Source: https://programming-idioms.org/cheatsheet/D Makes an HTTP GET request and saves the response body directly to a file without loading the entire content into memory. Requires 'std.net.curl'. ```d import std.net.curl; // Assuming 'u' is the URL string // download(u, "result.txt"); ``` -------------------------------- ### Print Hello 10 times in Kotlin Source: https://programming-idioms.org/cheatsheet/Kotlin Demonstrates looping constructs to execute a print statement a fixed number of times. It shows multiple ways to achieve repetition. ```kotlin (0..9).forEach { println("Hello") } ``` ```kotlin repeat(10) { println("Hello") } ``` ```kotlin for(x in 1..10) { println("Hello") } ``` -------------------------------- ### Get File Size (Haskell) Source: https://programming-idioms.org/cheatsheet/Haskell Assigns the size of a local file to a variable. This idiom uses `System.IO.withFile` to open the file in read mode and `hFileSize` to get its size in bytes. ```Haskell import System.IO filesize = withFile path ReadMode hFileSize ``` -------------------------------- ### Get Folder Containing Current Program (C) Source: https://programming-idioms.org/cheatsheet/C Determines the directory path of the currently running executable. It uses readlink to get the executable path and dirname to extract the directory. ```c #include #include #include #include #include #include int main() { char exe[PATH_MAX], real_exe[PATH_MAX]; ssize_t r; char *dir; if ((r = readlink("/proc/self/exe", exe, PATH_MAX)) < 0) exit(1); if (r == PATH_MAX) r -= 1; exe[r] = 0; if (realpath(exe, real_exe) == NULL) exit(1); dir = dirname(real_exe); puts(dir); } ``` -------------------------------- ### Print Hello World in Scala Source: https://programming-idioms.org/cheatsheet/Scala Prints the literal string 'Hello, World!' to standard output. This is a basic idiom for demonstrating program output. ```Scala println("Hello, World!") ``` -------------------------------- ### PHP: Print Hello 10 times Source: https://programming-idioms.org/cheatsheet/PHP Illustrates looping constructs in PHP to print 'Hello' ten times. Shows examples using a traditional 'for' loop and the 'foreach' loop with 'range()'. ```PHP for ($i = 0; $i < 10; $i++) { echo 'Hello' . PHP_EOL; } ``` ```PHP foreach(range(1, 10) as $i) echo 'Hello'. PHP_EOL; ``` -------------------------------- ### Get the last element of a list Source: https://programming-idioms.org/cheatsheet/Lisp Assigns the last element of the list `items` to the variable `x`. It uses `last` to get the last cons cell and `car` to extract the element. ```lisp (setf x (car (last items))) ``` -------------------------------- ### Create a map with initial content in OCaml Source: https://programming-idioms.org/cheatsheet/Caml Creates a string-to-integer map using 'Map.Make' and populates it with initial key-value pairs. ```ocaml module StringMap = Map.Make(String) let x = StringMap.empty |> StringMap.add "one" 1 |> StringMap.add "two" 2 |> StringMap.add "three" 3 ``` -------------------------------- ### Load from HTTP GET Request into String (Common Lisp) Source: https://programming-idioms.org/cheatsheet/Lisp Performs an HTTP GET request to a specified URL and stores the response body in a string. Requires the 'dexador' library. ```common-lisp (ql:quickload 'dexador) ``` ```common-lisp (defvar *s* (string (dex:get u))) ``` -------------------------------- ### Find substring position (Lua) Source: https://programming-idioms.org/cheatsheet/Lua Finds the starting position 'i' of substring 'y' within string 'x'. Returns nil if 'y' is not found. Indices start at 1. Can specify character or byte index. ```Lua i = x:find(y) ``` -------------------------------- ### Loop and Print 'Hello' 10 Times in Lisp Source: https://programming-idioms.org/cheatsheet/Lisp Shows how to loop a specific number of times (10) and execute a command (print 'Hello') in each iteration using Lisp's `loop` construct. ```lisp (loop repeat 10 do (write-line "Hello")) ``` -------------------------------- ### Load HTTP GET request body into string (Ruby) Source: https://programming-idioms.org/cheatsheet/Ruby Fetches the content of a URL using an HTTP GET request and stores the response body in a string. Requires the 'net/http' library. ```Ruby require 'net/http' u = URI("http://example.com/index.html") s = Net::HTTP.get_response(u).body ``` -------------------------------- ### Print Hello 10 times in C++ Source: https://programming-idioms.org/cheatsheet/Cpp Shows how to loop and print the string "Hello" followed by a newline character ten times. It includes implementations using standard for loops with iostream and cstdio, as well as alternative methods involving string data pointers. ```cpp #include using namespace std; for (int i = 0; i < 10; ++i) cout << "Hello\n"; ``` ```cpp #include std::string a {"Hello"}; char const* p {a.data()}; for (int i {}; i != 10; ++i) printf("%s\n", p); ``` ```cpp #include char* a {"Hello"}; for (int i {}; i != 10; ++i) printf("%s\n", a); ``` -------------------------------- ### Get file size Source: https://programming-idioms.org/cheatsheet/Go Assigns the length (in bytes) of a local file at the given 'path' to the variable 'x'. Uses os.Stat to get file information and returns errors if the file cannot be accessed. ```Go import "os" info, err := os.Stat(path) if err != nil { return err } x := info.Size() ``` -------------------------------- ### Create Folder on Filesystem (Java) Source: https://programming-idioms.org/cheatsheet/Java Creates a directory at the specified path on the filesystem. This operation may throw a SecurityException if the program lacks the necessary permissions. ```Java import java.io.File; boolean ok = new File(path).mkdirs(); ``` -------------------------------- ### Print Hello 10 Times in D Source: https://programming-idioms.org/cheatsheet/D Demonstrates looping to execute code a constant number of times. It prints 'Hello' ten times using a foreach loop. ```d import std.stdio; void main() { foreach(i; 0..10) writeln("Hello"); } ``` ```d import std.stdio : writeln; import std.range : iota; import std.algorithm.iteration : each; void main() { iota(0,10).each!(a => "Hello".writeln); } ``` -------------------------------- ### Conditional assignment Source: https://programming-idioms.org/cheatsheet/Haskell Assigns a value to a variable 'x' based on a condition. If 'condition' is true, 'x' gets 'a'; otherwise, it gets 'b'. An alternative using assignment guards is also shown. ```haskell x = if condition then 'a' else 'b' ``` ```haskell let x | condition = "a" | otherwise = "b" ``` -------------------------------- ### Extract substring (Haskell) Source: https://programming-idioms.org/cheatsheet/Haskell Extracts a substring from string 's' starting at index 'i' (inclusive) and ending at index 'j' (exclusive). It handles multibyte characters correctly. Character indices start at 0. ```Haskell t = drop i (take j s) ``` -------------------------------- ### Create and Use a Stack (Java) Source: https://programming-idioms.org/cheatsheet/Java Demonstrates the creation and basic usage of a Java Stack. It includes pushing an element 'x' onto the stack and then popping it into variable 'y'. 'T' represents the generic type of the stack elements. ```java import java.util.Stack; // Assuming T is the element type and x is an instance of T Stack s = new Stack<>(); s.push(x); T y = s.pop(); ``` -------------------------------- ### Get String Byte Length in Go Source: https://programming-idioms.org/cheatsheet/Go Shows how to get the number of bytes in a string 's' using the built-in 'len()' function. It clarifies that this count represents bytes, not necessarily characters (runes). ```go n := len(s) ``` -------------------------------- ### Print Hello World in Java Source: https://programming-idioms.org/cheatsheet/Java Prints the literal string 'Hello World' to the standard output. It shows a basic direct print statement and an alternative using a static import for brevity. ```Java System.out.println("Hello World"); ``` ```Java import static java.lang.System.out; ... out.print("Hello World"); ``` -------------------------------- ### Initialize Arbitrary Precision Quotient from Big Integers Source: https://programming-idioms.org/cheatsheet/Go Initializes a big.Rat quotient 'q' from two big.Int values 'a' and 'b'. Subsequent computations with 'q' will have arbitrary precision. ```Go import "math/big" q := new(big.Rat) q.SetFrac(a, b) ``` -------------------------------- ### Get Folder Containing Current Program in Go Source: https://programming-idioms.org/cheatsheet/Go Determines the directory path where the currently running executable is located. It first gets the absolute path of the program arguments and then extracts the directory component. ```Go import "os" import "path/filepath" programPath := os.Args[0] absolutePath, err := filepath.Abs(programPath) if err != nil { return err } dir := filepath.Dir(absolutePath) ``` -------------------------------- ### Extract Substring Source: https://programming-idioms.org/cheatsheet/Scheme Extracts a substring 't' from string 's', starting at character index 'i' (inclusive) and ending at index 'j' (exclusive). Character indices start at 0. Handles multibyte characters correctly. ```scheme (define t (substring s i j)) ``` -------------------------------- ### Create and Initialize a List (C#) Source: https://programming-idioms.org/cheatsheet/Csharp Declares and initializes a new generic list with specified elements. It shows initialization using List and an alternative using arrays. ```csharp using System.Collections.Generic; var items = new List{a,b,c}; ``` ```csharp T[] items = new T[] { a, b, c }; ``` -------------------------------- ### Create Folder Source: https://programming-idioms.org/cheatsheet/Csharp Creates a directory at the specified file system path. ```csharp Directory.CreateDirectory(path); ``` -------------------------------- ### Extract Substring (Clojure) Source: https://programming-idioms.org/cheatsheet/Clojure Extracts a substring 't' from string 's' starting at index 'i' (inclusive) and ending at index 'j' (exclusive). Character indices start at 0. Handles multibyte characters correctly. ```clojure (def t (subs s i j)) ``` -------------------------------- ### Print 'Hello World' in Lua Source: https://programming-idioms.org/cheatsheet/Lua Demonstrates how to print a literal string 'Hello World' to the standard output using Lua. It shows two common methods: `print()` and `io.write()`. ```lua print("Hello World") ``` ```lua io.write("Hello world") ``` -------------------------------- ### Load HTTP GET Request Response into String in Java Source: https://programming-idioms.org/cheatsheet/Java Makes an HTTP GET request to a specified URL and stores the response body in a string. Uses Java's HttpClient API or HttpsURLConnection. ```Java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; // ... String s = HttpClient.newHttpClient().send(HttpRequest.newBuilder() .uri(URI.create(u)) .GET() .build(), HttpResponse.BodyHandlers.ofString()) .body(); ``` ```Java import java.io.IOException; import javax.net.ssl.HttpsURLConnection; // ... HttpsURLConnection h = null; try { h = (HttpsURLConnection) u.openConnection(); h.setRequestMethod("GET"); byte a[] = h.getInputStream().readAllBytes(); String s = new String(a); } catch (IOException e) { throw new RuntimeException(e); } finally { if (h != null) h.disconnect(); } ``` -------------------------------- ### Create Temporary File (Ruby) Source: https://programming-idioms.org/cheatsheet/Ruby Demonstrates how to create a temporary file on the filesystem in Ruby using the 'tempfile' library. A unique filename is generated in the system's temporary directory. ```ruby require 'tempfile' file = Tempfile.new('foo') ``` -------------------------------- ### Load from HTTP GET request into a string in C# Source: https://programming-idioms.org/cheatsheet/Csharp Performs an HTTP GET request to a specified URL 'u' and stores the response body in a string 's'. Uses the HttpClient class for making the request. ```csharp using System.Net.Http; var client = new HttpClient(); s = await client.GetStringAsync(u); ``` -------------------------------- ### Load from HTTP GET request into a string (Scala) Source: https://programming-idioms.org/cheatsheet/Scala Fetches content from a URL using an HTTP GET request and stores the response body in a string. Requires network access and appropriate URL handling. ```scala val s = scala.io.Source.fromURL(u).getLines().mkString("\n") ``` -------------------------------- ### Allocate 1MB Byte Buffer (GC Heap) Source: https://programming-idioms.org/cheatsheet/D Creates a new byte buffer `buf` of 1,000,000 bytes allocated on the GC heap. ```d import std.c.stdlib; import core.memory; void[] buf = GC.malloc(1024 * 1024)[0..1024 * 1024]; ``` -------------------------------- ### Print Hello World 10 Times in Python Source: https://programming-idioms.org/cheatsheet/Python Shows various Python methods to print 'Hello' ten times. Techniques include standard for loops, sequence repetition, while loops, recursion, and using itertools.repeat. ```python for _ in range(10): print("Hello") ``` ```python print("Hello\n"*10) ``` ```python i = 0 while i < 10: print('Hello') i += 1 ``` ```python def f(count=10): print('Hello') if count == 1: return f(count - 1) f() ``` ```python from itertools import repeat from os import linesep print(*repeat('Hello', 10), sep=linesep) ``` ```python print(*('Hello',) * 10, sep='\n') ``` -------------------------------- ### Load from HTTP GET Request Source: https://programming-idioms.org/cheatsheet/Groovy Makes an HTTP GET request to a given URL and stores the response body in a string. The URL object must be of type URL. Supports specifying character encoding. ```Groovy String s = u.text // For specific encoding: // u.getText('UTF-8') ``` -------------------------------- ### Create Temporary Directory Source: https://programming-idioms.org/cheatsheet/Pascal Creates a new temporary directory on the filesystem for writing. It generates a unique GUID, converts it to a string, and then uses CreateDir to create a new directory within the system's temporary directory path. ```Pascal uses sysutils; ``` ```Pascal var GUID: TGUID; Succes: Boolean; begin CreateGUID(GUID); Succes := CreateDir(GetTempDir + GUIDToString(GUID)); end. ``` -------------------------------- ### Load from HTTP GET Request into String (Python) Source: https://programming-idioms.org/cheatsheet/Python Performs an HTTP GET request to a specified URL 'u' and stores the response body into a string 's'. Two common libraries, urllib.request and requests, are demonstrated. ```Python import urllib.request with urllib.request.urlopen(u) as f: s = f.read() ``` ```Python import requests s = requests.get(u).content.decode() ``` -------------------------------- ### Create Temporary File (C) Source: https://programming-idioms.org/cheatsheet/C Creates a new temporary file on the filesystem using `mkstemp`. The provided template string 'tmpl' must contain six 'X' characters, which will be replaced by unique characters. ```c #include const char tmpl[] = "XXXXXX.tmp"; int fd = mkstemp(tmpl); ``` -------------------------------- ### Load HTTP GET request to string in PHP Source: https://programming-idioms.org/cheatsheet/PHP Makes an HTTP request with the GET method to a specified URL and stores the response body in a string. This utilizes the built-in file_get_contents function which can perform HTTP requests. ```php $s = file_get_contents($u); ``` -------------------------------- ### Load from HTTP GET Request into File (Common Lisp) Source: https://programming-idioms.org/cheatsheet/Lisp Performs an HTTP GET request to a URL and saves the response body directly to a file, optimizing for memory usage. Requires 'dexador' and 'serapeum' libraries. ```common-lisp (ql:quickload '("serapeum" "dexador")) ``` ```common-lisp (serapeum:write-stream-into-file (dex:get u :want-stream t) #P"result.txt" :direction :output :if-exists :supersede :if-does-not-exist :create) ``` -------------------------------- ### Print Hello World in Ada Source: https://programming-idioms.org/cheatsheet/Ada Prints the literal string 'Hello World!' to standard output. This is a basic example demonstrating output operations. ```Ada with Ada.Text_IO; use Ada.Text_IO; Put_Line ("Hello World!"); ``` -------------------------------- ### Create a Queue (Java) Source: https://programming-idioms.org/cheatsheet/Java Creates a new queue 'q' using ArrayDeque, enqueues two elements 'x' and 'y', and then dequeues an element into variable 'z'. This demonstrates basic queue operations. ```java import java.util.ArrayDeque; import java.util.Deque; Deque q = new ArrayDeque<>(); q.offer(x); q.offer(y); T z = q.poll(); ``` -------------------------------- ### Load HTTP GET Request Body into String in Clojure Source: https://programming-idioms.org/cheatsheet/Clojure Makes an HTTP GET request to a given URL 'u' and stores the response body in the string 's'. This is a simple way to fetch content from a URL. ```clojure (def s (slurp u)) ``` -------------------------------- ### Print Hello 10 Times in Java Source: https://programming-idioms.org/cheatsheet/Java Demonstrates multiple ways to print 'Hello' ten times using loops and streams. Includes traditional for loops, while loops, and Java 8+ stream operations. ```Java for(int i=0;i<10;i++) System.out.println("Hello"); ``` ```Java System.out.print("Hello\n".repeat(10)); ``` ```Java import static java.lang.System.out; ... int i = 0; while (i++ < 10) out.println("Hello"); ``` ```Java import static java.lang.System.out; ... for (int i = 0; i++ < 10; out.println("Hello")); ``` ```Java import static java.lang.System.out; ... int i = 0; do out.println("Hello"); while (i++ < 10); ``` ```Java import static java.util.stream.IntStream.range; ... range(0, 10).forEach(x -> out.println("Hello")); ``` ```Java import static java.lang.System.out; import static java.util.stream.Stream.generate; ... generate(() -> "Hello%n") .limit(10) .forEach(out::printf); ``` -------------------------------- ### Get Tomorrow's Date String using Chaining in Perl Source: https://programming-idioms.org/cheatsheet/Perl Alternative implementation for getting tomorrow's date string using object chaining with the `DateTime` module. This provides a more compact way to achieve the same result. ```Perl use DateTime; $t = DateTime->today->add(days => 1)->ymd; ``` -------------------------------- ### Create Temporary Directory (C#) Source: https://programming-idioms.org/cheatsheet/Csharp Creates a new temporary directory on the filesystem for writing. It combines Path.GetTempPath(), Guid.NewGuid(), and Directory.CreateDirectory() for this purpose. ```csharp using System.IO; string newDir = Path.GetTempPath() + Guid.NewGuid(); Directory.CreateDirectory(newDir); ``` -------------------------------- ### Load from HTTP GET request into a file using Perl Source: https://programming-idioms.org/cheatsheet/Perl Makes an HTTP GET request to a URL and stores the response body in a file. It attempts to save data as it arrives to avoid holding the entire content in memory. ```Perl use HTTP::Tiny qw(); my $response = HTTP::Tiny->new->mirror($u, 'result.txt'); ``` -------------------------------- ### Create Directory (Rust) Source: https://programming-idioms.org/cheatsheet/Rust Creates a directory at the specified path. This function does not create parent directories if they do not exist. Use create_dir_all for recursive directory creation. ```Rust use std::fs; fn create_directory(path: &str) -> std::io::Result<()>{ fs::create_dir(path)?; Ok(()) } ``` -------------------------------- ### Print Hello World in Objective-C Source: https://programming-idioms.org/cheatsheet/Obj-C Prints the literal string 'Hello world' to standard output. Requires importing the 'stdio.h' library. ```Objective-C #import NSLog(@"Hello world\n"); ``` -------------------------------- ### Perform HTTP GET Request and Handle Response in Go Source: https://programming-idioms.org/cheatsheet/Go Fetches data from a URL using an HTTP GET request. It includes error handling for the request and response, and ensures the response body is properly closed and discarded. ```Go resp, err := http.Get(u) if err != nil { return err } defer func() { io.Copy(io.Discard, resp.Body) resp.Body.Close() }() if resp.StatusCode != 200 { return fmt.Errorf("Status: %v", resp.Status) } _, err = io.Copy(out, resp.Body) if err != nil { return err } ``` -------------------------------- ### Create temporary file (Go) Source: https://programming-idioms.org/cheatsheet/Go Creates a new temporary file on the filesystem. It returns a file handle and an error. The file path can be accessed via `tmpfile.Name()`, and cleanup is recommended using `os.Remove()`. ```Go import "os" tmpfile, err := os.CreateTemp("", "") ``` -------------------------------- ### Measure Procedure Execution Duration Source: https://programming-idioms.org/cheatsheet/Pascal Measures the duration of a procedure's execution. It records the start time using GetTickCount64, executes the procedure 'f', and then calculates the duration by subtracting the start time from the current time. The duration is returned. ```Pascal var Start, Duration: DWord; // replaces TDateTime begin Start := GetTickCount64; // better than Now f; Duration := GetTickCount64 - Start; end. ``` -------------------------------- ### Load HTTP GET request body into file (Ruby) Source: https://programming-idioms.org/cheatsheet/Ruby Downloads content from a URL via HTTP GET and saves it to a file, attempting to stream the data without loading the entire content into memory. Requires 'net/http' and 'open-uri'. ```Ruby require 'net/http' u = URI('http://example.com/large_file') Net::HTTP.start(u.host, u.port) do |http| request = Net::HTTP::Get.new(u) http.request(request) do |response| open('result.txt', 'w') do |file| response.read_body do |chunk| file.write(chunk) end end end end ``` ```Ruby require 'open-uri' response = URI.open(u).read File.write("result.txt", response) ``` -------------------------------- ### Create Folder (Node.js) Source: https://programming-idioms.org/cheatsheet/JS Creates a directory at the specified path using Node.js's file system promises API. ```javascript import { mkdir } from 'fs/promises'; await mkdir(path); ``` -------------------------------- ### Create and Use a Queue Source: https://programming-idioms.org/cheatsheet/Rust Demonstrates the creation of a queue using `VecDeque`, enqueuing elements, and dequeuing an element from the front. ```Rust use std::collections::VecDeque; let mut q = VecDeque::new(); q.push_back(x); q.push_back(x); let z = q.pop_front(); ``` -------------------------------- ### Load HTTP GET Request Body into String (Fetch API - Promise) Source: https://programming-idioms.org/cheatsheet/JS Loads the body of an HTTP GET request into a string using the Fetch API with Promises. This API is not available in older IE versions without a polyfill. ```javascript fetch(u) .then(res => res.text()) .then(text => s = text) ``` -------------------------------- ### Create Quotient from int64 Values Source: https://programming-idioms.org/cheatsheet/Go Creates a big.Rat quotient 'q' from two int64 values 'a' and 'b'. This facilitates subsequent arbitrary precision arithmetic. ```Go import "math/big" q := big.NewRat(a, b) ``` -------------------------------- ### Load from HTTP GET Request into File (Python) Source: https://programming-idioms.org/cheatsheet/Python Makes an HTTP GET request to a URL 'u' and saves the response body directly to a file named 'result.txt'. It prioritizes saving data as it arrives to avoid high memory usage. ```Python import urllib filename, headers = urllib.request.urlretrieve(u, 'result.txt') ``` ```Python import requests with open("results.txt", "wb") as fh: fh.write(requests.get(u).content) ``` -------------------------------- ### List Files in Directory in Java Source: https://programming-idioms.org/cheatsheet/Java Retrieves a list of files and subdirectories within a specified directory. This does not perform a recursive listing. Two common approaches involve using File.listFiles() to get File objects or File.list() to get an array of names. ```Java import java.io.File; // Assuming d is the directory path string final File directory = new File(d); final File[] x = directory.listFiles(); ``` ```Java import java.io.File; // Assuming d is the directory path string String x[] = new File(d).list(); ``` -------------------------------- ### Create a Map (Associative Array) - Pascal Source: https://programming-idioms.org/cheatsheet/Pascal Demonstrates creating a specialized map 'TMap' from the 'fgl' unit to store key-value pairs, where keys are strings and values are integers, and initializing it with some data. ```Pascal uses fgl; type TMap = specialize TFPGMap; var x: TMap; begin x := TMap.Create; x['one'] := 1; x['two'] := 2; end. ``` -------------------------------- ### Create Directory Source: https://programming-idioms.org/cheatsheet/Perl Creates a directory at the specified path on the filesystem using the Path::Tiny module. This is a convenient way to ensure a directory exists before writing files to it. ```perl use Path::Tiny qw(path); path($path)->mkpath; ``` -------------------------------- ### Get Environment Variable in Go Source: https://programming-idioms.org/cheatsheet/Go Reads an environment variable. `os.LookupEnv` is used to get the value and a boolean indicating if it was set. If not set, a default value of "none" is assigned. Handles cases where environment variables might not be supported. ```go import "os" func getEnvVar(key string) string { value, ok := os.LookupEnv(key) if !ok { value = "none" } return value } ``` -------------------------------- ### Load from HTTP GET request into a file Source: https://programming-idioms.org/cheatsheet/Go Makes an HTTP GET request to URL 'u' and saves the response body directly to a file named 'result.txt'. It attempts to stream the data as it arrives to avoid holding the entire content in memory. ```Go import "fmt" import "io" import "net/http" import "os" out, err := os.Create("result.txt") if err != nil { return err } deffer out.Close() res, err := http.Get(u) if err != nil { return err } deffer res.Body.Close() _, err = io.Copy(out, res.Body) if err != nil { return err } ``` -------------------------------- ### Print Hello World in Elixir Source: https://programming-idioms.org/cheatsheet/Elixir Prints the literal string 'Hello World' to standard output. Demonstrates basic I/O operations in Elixir. ```elixir IO.puts "Hello World" ``` ```elixir "Hello World" |> IO.puts ``` -------------------------------- ### Load HTTP GET Request into String in Rust Source: https://programming-idioms.org/cheatsheet/Rust Fetches data from a URL using an HTTP GET request and stores the response body into a string. Supports multiple implementations using crates like reqwest and ureq. Note that some implementations are synchronous. ```rust extern crate reqwest; use reqwest::Client; let client = Client::new(); let s = client.get(u).send().and_then(|res| res.text())?; ``` ```rust let s = ureq::get(u).call().into_string()?; ``` ```rust use std::io::Read; let mut response = reqwest::blocking::get(u)?; let mut s = String::new(); response.read_to_string(&mut s)?; ``` -------------------------------- ### Print Hello World in Groovy Source: https://programming-idioms.org/cheatsheet/Groovy Prints the literal string 'Hello World' to standard output. ```Groovy println 'Hello World' ``` -------------------------------- ### Get Environment Variable with Default (cmp.Or) in Go Source: https://programming-idioms.org/cheatsheet/Go A concise method to get an environment variable and provide a default value using `cmp.Or`. If `os.Getenv` returns an empty string, `cmp.Or` will return the provided default value. Requires the 'cmp' package. ```go import "os" import "cmp" func getEnvVarWithDefault(key string) string { return cmp.Or(os.Getenv(key), "none") } ``` -------------------------------- ### Print Hello World in Scheme Source: https://programming-idioms.org/cheatsheet/Scheme Prints the literal string 'Hello World' to standard output. ```scheme (display "Hello World") ``` -------------------------------- ### Get Current Executable Name in Go Source: https://programming-idioms.org/cheatsheet/Go Retrieves the base name of the currently executing program. It uses `os.Args[0]` to get the program path and `filepath.Base` to extract just the filename. An alternative implementation using `os.Executable` is also provided for Go 1.8+. ```Go import "os" import "path/filepath" path := os.Args[0] s = filepath.Base(path) ``` ```Go import ( "os" "path/filepath" ) path, err := os.Executable() if err != nil { panic(err) } s = filepath.Base(path) ```