### p5.js Setup and Draw Functions Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/p5.md The core functions in p5.js. `setup()` runs once at the start, and `draw()` runs repeatedly for animation. ```javascript function setup() { // the setup function gets executed just once when the window is loaded } function draw() { // the draw function gets called every single frame // if the framerate is set to 30, it would get called 30 times every second } ``` -------------------------------- ### Processing Program Entry Point: setup() Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/processing.md The `setup()` function is the program's entry point in Processing. It runs once when the program starts and is used for static initialization like setting background colors or canvas size. ```processing // In Processing, the program entry point is a function named setup() with a // void return type. // Note! The syntax looks strikingly similar to that of C++. void setup() { // This prints out the classic output "Hello World!" to the console when run. println("Hello World!"); // Another language with a semi-column trap, aint it? } // Normally, we put all the static codes inside the setup() method as the name // suggest since it only runs once. // It can range from setting the background colours, setting the canvas size. background(color); // setting the background colour size(width,height,[renderer]); // setting the canvas size with optional // parameter defining renderer // You will see more of them throughout this document. ``` -------------------------------- ### Class Inheritance Example (Partial) Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/phix.md An incomplete example showing the start of a 'Pair' class intended for inheritance or composition, with fields and a getter method for 'x'. ```Phix class Pair -- any 2 objects public sequence xy public integer x,y function get_x() return xy[1] end function function get_y() return xy[2] end function ``` -------------------------------- ### Direct3D 9 Initialization and Setup Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/directx9.md Includes necessary headers and declares Direct3D interfaces. Ensure 'd3d9.lib' and 'd3dx9.lib' are linked, and the DirectX SDK (June 2010) is installed for 'd3dx9.lib'. The subsystem must be set to Windows. ```cpp #include #include #include using namespace Microsoft::WRL; ComPtr _d3d{ }; ComPtr _device{ }; ``` -------------------------------- ### Install Python Libraries Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/pythonstatcomp.md Before starting, install necessary libraries using pip. This tutorial is best followed in a Jupyter notebook for inline plots and documentation lookup. ```python """ To get started, pip install the following: jupyter, numpy, scipy, pandas, matplotlib, seaborn, requests. Make sure to do this tutorial in a Jupyter notebook so that you get the inline plots and easy documentation lookup. The shell command to open one is simply `jupyter notebook`, then click New -> Python. """ ``` -------------------------------- ### Basic Compojure App with http-kit Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/compojure.md Sets up a minimal Compojure application that responds with 'Hello World' to GET requests on the root path and runs it using the http-kit server. Requires Leiningen for project setup and dependency management. ```clojure (ns myapp.core (:require [compojure.core :refer :all] [org.httpkit.server :refer [run-server]])) ; httpkit is a server (defroutes myapp (GET "/" [] "Hello World")) (defn -main [] (run-server myapp {:port 5000})) ``` -------------------------------- ### Git Initial Setup and Configuration Source: https://context7.com/adambard/learnxinyminutes-docs/llms.txt Covers essential Git commands for initial setup, including configuring global user name, email, and default editor. ```bash # Initial setup git config --global user.name "Your Name" git config --global user.email "you@example.com" git config --global core.editor "vim" ``` -------------------------------- ### Clone Repos and Install Dependencies Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/CONTRIBUTING.md Clone the website and docs repositories, then install Python dependencies using pip. ```sh # Clone website git clone https://github.com/adambard/learnxinyminutes-site # Clone docs (this repo) nested in website git clone https://github.com//learnxinyminutes-docs ./learnxinyminutes-site/source/docs/ # Install dependencies cd learnxinyminutes-site pip install -r requirements.txt ``` -------------------------------- ### Pod Configuration: String Example Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/raku-pod.md Example of specifying a string value for a configuration option in Pod. ```pod :nonexec-reason('SyntaxError') ``` -------------------------------- ### Pod Configuration: List Example Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/raku-pod.md Example of specifying a list as configuration for a Pod block using colon-pair syntax. ```pod :tags('Pod', 'Raku') ``` -------------------------------- ### Install Composer Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/php-composer.md Installs the composer.phar binary locally or globally. Ensure ~/bin is in your PATH for global installation. ```sh # Installs the composer.phar binary into the current directory curl -sS https://getcomposer.org/installer | php ``` ```sh # If you use this approach, you will need to invoke composer like this: php composer.phar about ``` ```sh # Installs the binary into ~/bin/composer # Note: make sure ~/bin is in your shell's PATH environment variable curl -sS https://getcomposer.org/installer | php -- --install-dir=~/bin --filename=composer ``` -------------------------------- ### Installing and Importing PowerShell Modules Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/powershell.md Shows how to install a module from the PowerShell Gallery using Install-Module and then import it for use. It also demonstrates invoking a function from the imported module with named parameters. ```powershell Install-Module dbaTools Import-Module dbaTools $query = "SELECT * FROM dbo.sometable" $queryParams = @{ SqlInstance = 'testInstance' Database = 'testDatabase' Query = $query } Invoke-DbaQuery @queryParams ``` -------------------------------- ### Pod Configuration: Hash Example Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/raku-pod.md Example of specifying a hash as configuration for a Pod block using colon-pair syntax. ```pod :feeds{url => 'raku.org'} ``` -------------------------------- ### Install docutils with easy_install Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/rst.md Use easy_install to install the docutils package for Restructured Text processing. ```bash $ easy_install docutils ``` -------------------------------- ### Pod Configuration: Integer Example Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/raku-pod.md Example of specifying an integer value for a configuration option in Pod. ```pod :post-number(6) ``` -------------------------------- ### LFE HTTP Request Example Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/lfe.md Shows how to make multiple simultaneous HTTP requests in LFE. It includes functions to parse URL arguments, start the inets service, and perform individual GET requests, handling both success and error responses. ```lfe (defun parse-args (flag) "Given one or more command-line arguments, extract the passed values. For example, if the following was passed via the command line: $ erl -my-flag my-value-1 -my-flag my-value-2 One could then extract it in an LFE program by calling this function: (let ((args (parse-args 'my-flag))) ... ) In this example, the value assigned to the arg variable would be a list containing the values my-value-1 and my-value-2." (let ((`#(ok ,data) (init:get_argument flag))) (lists:merge data))) (defun get-pages () "With no argument, assume 'url parameter was passed via command line." (let ((urls (parse-args 'url))) (get-pages urls))) (defun get-pages (urls) "Start inets and make (potentially many) HTTP requests." (inets:start) (plists:map (lambda (x) (get-page x)) urls)) (defun get-page (url) "Make a single HTTP request." (let* ((method 'get) (headers '()) (request-data `#(,url ,headers)) (http-options ()) (request-options '(#(sync false)))) (httpc:request method request-data http-options request-options) (receive (`#(http #(,request-id #(error ,reason))) (io:format "Error: ~p~n" `(,reason))) (`#(http #(,request-id ,result)) (io:format "Result: ~p~n" `(,result)))))) ``` -------------------------------- ### Sample Dockerfile Instructions Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/docker.md A basic Dockerfile demonstrating how to set a base image, define environment variables, update packages, copy files, and set an entrypoint or command. ```dockerfile FROM # define base image ENV USERNAME='admin'\ PWD='****' # optionally define environmental variables, real credentials # should be handled more securely (like using .env file) RUN apt-get update # run linux commands inside container env, does not affect host env # This executes during the time of image creation COPY # executes on the host, copies files from src (usually on the host) to target # on the container ENTRYPOINT ["some-script.sh"] # executes an entire script as an entrypoint CMD [,...] # always part of dockerfile, introduces entry point linux command e.g. # `CMD node server.js` # This executes after image creation only when the container from the image # is running. ``` -------------------------------- ### Get ZFS Compression Options Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/zfs.md Use 'zfs get -help' to view available compression algorithms and their settings. This command lists all possible values for the compression property. ```bash # Get compression options $ zfs get -help ...compression NO YES on | off | lzjb | gzip | gzip-[1-9] | zle | lz4 | zstd | zstd-[1-19] | zstd-fast | zstd-fast-[1-10,20,30,40,50,60,70,80,90,100,500,1000] ... ``` -------------------------------- ### Tmux Configuration Example Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/tmux.md Example ~/.tmux.conf file for customizing tmux behavior, including keybindings, history limit, and mouse support. Reload the config with 'r' after changes. ```tmux # Example tmux.conf # 2015.12 ### General ########################################################################### # Scrollback/History limit set -g history-limit 2048 # Index Start set -g base-index 1 # Mouse set-option -g -q mouse on # Force reload of config file unbind r bind r source-file ~/.tmux.conf ### Keybinds ########################################################################### # Unbind C-b as the default prefix unbind C-b # Set new default prefix set-option -g prefix ` # Return to previous window when prefix is pressed twice bind C-a last-window bind ` last-window # Allow swapping C-a and ` using F11/F12 bind F11 set-option -g prefix C-a bind F12 set-option -g prefix ` # Keybind preference setw -g mode-keys vi set-option -g status-keys vi # Moving between panes with vim movement keys bind h select-pane -L bind j select-pane -D bind k select-pane -U bind l select-pane -R # Window Cycle/Swap bind e previous-window bind f next-window bind E swap-window -t -1 bind F swap-window -t +1 # Easy split pane commands bind = split-window -h bind - split-window -v unbind "" unbind % # Activate inner-most session (when nesting tmux) to send commands bind a send-prefix ``` -------------------------------- ### Run Vim Tutor Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/fa/vim.md Launches the Vim tutorial for beginners. ```bash $ vimtutor ``` -------------------------------- ### Pod Block Pre-configuration Example Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/raku-pod.md Example of using the `=config` directive to pre-configure block types. This sets all `=head1` blocks to be formatted as bold and underlined, and numbered. ```pod =config head1 :formatted('B', 'U') :numbered ``` -------------------------------- ### PCRE Example: Matching Start of Line Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/pcre.md Matches non-space characters from the beginning of the line. `^` asserts the start of the string, and `\S+` matches one or more non-whitespace characters. ```regex ^\S+ ``` -------------------------------- ### OpenGL Application Setup and Cleanup Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/opengl.md Demonstrates the basic structure of an OpenGL application, including setting the clear color, creating a shader program, handling events, and deleting the program upon exit. Ensure proper resource management. ```cpp // Now we can create a shader program with a vertex and a fragment shader. // ... glClearColor(0.0f, 0.0f, 0.0f, 1.0f); GLuint program = createShaderProgram("vertex.glsl", "fragment.glsl"); sf::Event event{ }; // ... // We also have to delete the program at the end of the application. // ... } glDeleteProgram(program); return 0; } // ... ``` -------------------------------- ### Get Git Help Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/git.md Access detailed guides and reminders for Git commands. You can check available commands, get specific command help, or use the `--help` flag. ```bash # Quickly check available commands git help # Check all available commands git help -a # Command specific help - user manual # git help git help add git help commit git help init # or git --help git add --help git commit --help git init --help ``` -------------------------------- ### PCRE Example: Literal Match Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/pcre.md Matches the literal string 'GET'. This is a case-sensitive match. ```regex GET ``` -------------------------------- ### Initialize a New Project with Composer Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/php-composer.md Starts a new project by creating a composer.json file through an interactive questionnaire. ```sh # Create a new project in the current folder composer init # runs an interactive questionnaire asking you for details about your project. Leaving them blank is fine unless you are making other projects dependent on this one. ``` -------------------------------- ### Install Niva Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/niva.md Instructions for cloning the Niva repository, building the JVM Niva project, and setting up the Language Server Protocol (LSP) for VS Code. ```bash git clone https://github.com/gavr123456789/Niva.git cd Niva ./gradlew buildJvmNiva # LSP here https://github.com/gavr123456789/niva-vscode-bundle ``` -------------------------------- ### ATS Hello World and Basic Functions Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/ats.md Demonstrates basic ATS syntax for printing, defining functions with and without currying, and using let bindings. Includes examples of polymorphic functions and type parameters. ```ats #include "share/atspre_define.hats" #include "share/atspre_staload.hats" // To compile, either use // $ patscc -DATS_MEMALLOC_LIBC program.dats -o program // or install the ats-acc wrapper https://github.com/sparverius/ats-acc and use // $ acc pc program.dats // C-style line comments /* and C-style block comments */ (* as well as ML-style block comments *) /*************** Part 1: the ML fragment ****************/ val () = print "Hello, World!\n" // No currying fn add (x: int, y: int) = x + y // fn vs fun is like the difference between let and let rec in OCaml/F# fun fact (n: int): int = if n = 0 then 1 else n * fact (n-1) // Multi-argument functions need parentheses when you call them; single-argument // functions can omit parentheses val forty_three = add (fact 4, 19) // let is like let in SML fn sum_and_prod (x: int, y: int): (int, int) = let val sum = x + y val prod = x * y in (sum, prod) end // 'type' is the type of all heap-allocated, non-linear types // Polymorphic parameters go in {} after the function name fn id {a:type} (x: a) = x // ints aren't heap-allocated, so we can't pass them to 'id' // val y: int = id 7 // doesn't compile // 't@ype' is the type of all non-linear potentially unboxed types. It is a // supertype of 'type'. // Templated parameters go in {} before the function name fn {a:t@ype} id2 (x: a) = x val y: int = id2 7 // works // can't have polymorphic t@ype parameters // fn id3 {a:t@ype} (x: a) = x // doesn't compile // explicitly specifying type parameters: fn id4 {a:type} (x: a) = id {a} x // {} for non-template parameters fn id5 {a:type} (x: a) = id2 x // <> for template parameters fn id6 {a:type} (x: a) = id {..} x // {..} to explicitly infer it // Heap allocated shareable datatypes // using datatypes leaks memory datatype These (a:t@ype, b:t@ype) = This of a | That of b | These of (a, b) // Pattern matching using 'case' fn {a,b: t@ype} from_these (x: a, y: b, these: These(a,b)): (a, b) = case these of | This(x) => (x, y) // Shadowing of variable names is fine; here, x shadows // the parameter x | That(y) => (x, y) | These(x, y) => (x, y) // Partial pattern match using 'case-' // Will throw an exception if passed This fn {a,b:t@ype} unwrap_that (these: These(a,b)): b = case- these of | That(y) => y | These(_, y) => y ``` -------------------------------- ### Delete Rows from a Table Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/sql.md Removes rows from a table that meet specific criteria. This example deletes rows where the 'lname' starts with 'M'. ```sql DELETE FROM tablename1 WHERE lname LIKE 'M%'; ``` -------------------------------- ### Start a Web Server in Go Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/go.md Starts an HTTP web server on port 8080 using http.ListenAndServe. The server handles requests using the 'pair' type, which implements the http.Handler interface. ```go go func() { err := http.ListenAndServe(":8080", pair{}) fmt.Println(err) }() ``` -------------------------------- ### Iterative Function Application with Scan Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/kdb+.md Applies a function iteratively using the 'scan' adverb (\). This example doubles a starting value 5 times. ```q {x * 2}\ [5;1] ``` -------------------------------- ### Run a Container in Detached Mode Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/docker.md Starts a container in the background, returning control to the terminal. The example uses an Ubuntu image and runs a 'sleep' command. ```bash docker run -d ubuntu sleep 60s ``` -------------------------------- ### DirectX 9 Texture Loading and Setup Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/directx9.md Demonstrates how to declare a texture, modify vertex structures to include texture coordinates, update the vertex declaration, load a texture from a file, and set it on the device. Ensure the texture file exists at the specified path. ```cpp // First we need to declare a ComPtr for the texture. ComPtr _texture{ }; // Then we have to change the vertex struct. struct VStruct { float x, y, z; float u, v; // Add texture u and v coordinates D3DCOLOR color; }; // In the vertex declaration we have to add the texture coordinates. // the top left of the texture is u: 0, v: 0. std::vector vertices { VStruct{ -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, ... }, // bottom left VStruct{ -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, ... }, // top left VStruct{ 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, ... }, // top right VStruct{ 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, ... } // bottom right }; // Next is the vertex declaration. std::vector vertexDecl{ {0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0}, // Add a 2d float vector used for texture coordinates. {0, 12, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0}, // The color offset is not (3 + 2) * sizeof(float) = 20 bytes {0, 20, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0}, D3DDECL_END() }; // Now we have to load the texture and pass its to the shader. // ... _device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); // Create a Direct3D texture from a png file. result = D3DXCreateTextureFromFile(_device.Get(), // direct3d device "texture.png", // texture path &_texture); // receiving texture pointer if (FAILED(result)) return -1; // Attach the texture to shader stage 0, which is equal to texture register 0 // in the pixel shader. _device->SetTexture(0, _texture.Get()); ``` -------------------------------- ### Go variadic parameters example Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/go.md Demonstrates how to define and use variadic functions that can accept a variable number of arguments of any type. ```go // Functions can have variadic parameters. func learnVariadicParams(myStrings ...any) { // any is an alias for interface{} // Iterate each value of the variadic. // The underscore here is ignoring the index argument of the array. for _, param := range myStrings { fmt.Println("param:", param) } // Pass variadic value as a variadic parameter. fmt.Println("params:", fmt.Sprintln(myStrings...)) learnErrorHandling() } ``` -------------------------------- ### Running Ansible Playbook with Roles Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/ansible.md Example of how to execute an Ansible playbook that utilizes roles, specifically for installing Apache2. Ensure your environment is sourced and the playbook is correctly specified. ```bash $ source environment.sh $ # Now we would run the above playbook with roles (venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/simple_role.yml --tags apache2 ``` -------------------------------- ### Database Context with Entity Framework in C# Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/csharp.md Defines a DbContext for connecting to a database using Entity Framework. This setup is suitable for LinqToSql examples and EntityFramework Code First. ```csharp /// /// Used to connect to DB for LinqToSql example. /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) /// https://docs.microsoft.com/ef/ef6/modeling/code-first/workflows/new-database /// public class BikeRepository : DbContext { public BikeRepository() : base() { } public DbSet Bikes { get; set; } } ``` -------------------------------- ### Initialize raylib Window and Basic Setup in C Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/raylib.md Initializes a raylib window with specified dimensions and title. It demonstrates setting configuration flags like anti-aliasing and VSync, setting the target FPS, and defining a key to close the window. This is the foundational setup for any raylib application. ```c #include int main(void) { const int screenWidth = 800; const int screenHeight = 450; // Before initialising raylib we can set configuration flags SetConfigFlags(FLAG_MSAA_4X_HINT | FLAG_VSYNC_HINT); // raylib doesn't require us to store any instance structures // At the moment raylib can handle only one window at a time InitWindow(screenWidth, screenHeight, "MyWindow"); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set a key that closes the window // Could be 0 for no key SetExitKey(KEY_DELETE); // raylib defines two types of cameras: Camera3D and Camera2D // Camera is a typedef for Camera3D Camera camera = { .position = {0.0f, 0.0f, 0.0f}, .target = {0.0f, 0.0f, 1.0f}, .up = {0.0f, 1.0f, 0.0f}, .fovy = 70.0f, .projection = CAMERA_PERSPECTIVE }; // raylib supports loading of models, animations, images and sounds // from various different file formats Model myModel = LoadModel("my_model.obj"); Font someFont = LoadFont("some_font.ttf"); // Creates a 100x100 render texture RenderTexture renderTexture = LoadRenderTexture(100, 100); // WindowShouldClose checks if the user is closing the window // This might happen using a shortcut, window controls // or the key we set earlier while (!WindowShouldClose()) { // BeginDrawing needs to be called before any draw call BeginDrawing(); { // Sets the background to a certain color ClearBackground(BLACK); if (IsKeyDown(KEY_SPACE)) DrawCircle(400, 400, 30, GREEN); // Simple draw text DrawText("Congrats! You created your first window!", 190, // x 200, // y 20, // font size LIGHTGRAY ); // For most functions there are several versions // These are usually postfixed with Ex, Pro // or sometimes Rec, Wires (only for 3D), Lines (only for 2D) DrawTextEx(someFont, "Text in another font", (Vector2) {10, 10}, 20, // font size 2, // spacing LIGHTGRAY); // Required for drawing 3D, has 2D equivalent BeginMode3D(camera); { DrawCube((Vector3) {0.0f, 0.0f, 3.0f}, 1.0f, 1.0f, 1.0f, RED); // White tint when drawing will keep the original color DrawModel(myModel, (Vector3) {0.0f, 0.0f, 3.0f}, 1.0f, //Scale WHITE); } // End 3D mode so we can draw normally again EndMode3D(); // Start drawing onto render texture BeginTextureMode(renderTexture); { // It behaves the same as if we just called `BeginDrawing()` ClearBackground(RAYWHITE); BeginMode3D(camera); { DrawGrid(10, // Slices 1.0f // Spacing ); } EndMode3D(); } EndTextureMode(); // render textures have a Texture2D field DrawTexture(renderTexture.texture, 40, 378, BLUE); } EndDrawing(); } // Unloading loaded objects UnloadFont(someFont); UnloadModel(myModel); // Close window and OpenGL context CloseWindow(); return 0; } ``` -------------------------------- ### Forth Loop Examples (?do/do/loop) Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/forth.md Illustrates Forth's loop structures. '?do' is a compile-only word that expects end and start numbers on the stack. 'i' provides the current loop index. ```Forth : myloop ( -- ) 5 0 ?do cr . ``` ```Forth myloop ``` ```Forth : one-to-12 ( -- ) 12 0 do i . loop ; ``` ```Forth one-to-12 ``` ```Forth : loop-forever 1 1 do i square . loop ; ``` ```Forth loop-forever ``` ```Forth : threes ( n n -- ) ?do i . 3 +loop ; ``` ```Forth 15 0 threes ``` -------------------------------- ### Enum with Assigned Type in C++ Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/c++.md Enums can be assigned an underlying type (e.g., uint8_t) starting from C++11, useful for serialization. This example shows assigning specific values and an underlying type. ```cpp enum ECarTypes : uint8_t { Sedan, // 0 Hatchback, // 1 SUV = 254, // 254 Hybrid // 255 }; void WriteByteToFile(uint8_t InputValue) { // Serialize the InputValue to a file } void WritePreferredCarTypeToFile(ECarTypes InputCarType) { // The enum is implicitly converted to a uint8_t due to its declared enum type WriteByteToFile(InputCarType); } ``` -------------------------------- ### SFML Window and OpenGL Setup Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/opengl.md This snippet demonstrates how to create an SFML window with a specific OpenGL context version and initialize GLEW for modern OpenGL features. It also sets up the clear color and a basic event loop. ```cpp // Creating an SFML window and OpenGL basic setup. #include #include #include #include int main() { // First we tell SFML how to setup our OpenGL context. sf::ContextSettings context{ 24, // depth buffer bits 8, // stencil buffer bits 4, // MSAA samples 3, // major opengl version 3 }; // minor opengl version // Now we create the window, enable VSync // and set the window active for OpenGL. sf::Window window{ sf::VideoMode{ 1024, 768 }, "opengl window", sf::Style::Default, context }; window.setVerticalSyncEnabled(true); window.setActive(true); // After that we initialise GLEW and check if an error occurred. GLenum error; glewExperimental = GL_TRUE; if ((err = glewInit()) != GLEW_OK) std::cout << glewGetErrorString(err) << std::endl; // Here we set the color glClear will clear the buffers with. glClearColor(0.0f, // red 0.0f, // green 0.0f, // blue 1.0f); // alpha // Now we can start the event loop, poll for events and draw objects. sf::Event event{ }; while (window.isOpen()) { while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close; } // Tell OpenGL to clear the color buffer // and the depth buffer, this will clear our window. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Flip front- and backbuffer. window.display(); } return 0; } ``` -------------------------------- ### Inform 7: Creating and Initializing Instances Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/inform7.md Create named instances of defined classes and set their properties, including numbers, text, and relationships. ```inform7 Block1 is a datablock. The sequence number of Block1 is 1. The name of Block1 is "Block One." ``` -------------------------------- ### Define and use item structure with typed fields Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/tailspin.md Fields get auto-typed. You cannot assign the wrong type to a field. This example defines an 'item' with typed fields for inventory ID, name, and length. ```Tailspin def item: { inventory-id: 23, name: 'thingy', length: 12"m" }; 'Field inventory-id $item.inventory-id -> get-number-type; ' -> !OUT::write 'Field name $item.name -> get-string-type; ' -> !OUT::write 'Field length $item.length -> get-number-type; ' -> !OUT::write ``` -------------------------------- ### Create a Basic PyQt Window Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/pyqt.md This snippet demonstrates how to create a simple window with a label using PyQt. Ensure PyQt4 is installed. ```python import sys from PyQt4 import QtGui def window(): # Create an application object app = QtGui.QApplication(sys.argv) # Create a widget where our label will be placed in w = QtGui.QWidget() # Add a label to the widget b = QtGui.QLabel(w) # Set some text for the label b.setText("Hello World!") # Give some size and placement information w.setGeometry(100, 100, 200, 50) b.move(50, 20) # Give our window a nice title w.setWindowTitle("PyQt") # Have everything display w.show() # Execute what we have asked for, once all setup sys.exit(app.exec_()) if __name__ == '__main__': window() ``` -------------------------------- ### GDScript Override Functions Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/gdscript.md Explains the convention for overriding built-in functions, noting that functions starting with an underscore are typically overridable, but most functions can be overridden in practice. Mentions _init as an example initialization function. ```gdscript # Override functions # By a convention built-in overridable functions start with an underscore, # but in practice you can override virtually any function. # _init is called when object gets initialized ``` -------------------------------- ### Download and Run Ada Projects with Alire Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/ada.md Alire is a package manager for Ada that can automatically install the toolchain. Use 'alr search' to find projects, 'alr get' to download, and 'alr run' to execute. ```bash $ alr search learnadainy ``` ```bash $ alr get learnadainy ``` ```bash $ cd learnadainy ``` ```bash $ alr run empty ``` ```bash $ alr run hello ``` ```bash $ alr run learnadainy ``` -------------------------------- ### Go defer statement example Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/go.md Demonstrates the 'defer' keyword, showing that deferred calls are executed after the surrounding function returns, in LIFO order. ```go // A defer statement pushes a function call onto a list. The list of saved // calls is executed AFTER the surrounding function returns. defer fmt.Println("deferred statements execute in reverse (LIFO) order.") defer fmt.Println("\nThis line is being printed first because") // Defer is commonly used to close a file, so the function closing the // file stays near the function opening the file. return true ``` -------------------------------- ### Guards in Gleam Pattern Matching Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/gleam.md Demonstrates how to use guards (`if` keyword) in pattern matching to add conditions that must evaluate to `True` for a pattern to match. This example checks if a list starts with a specific value. ```gleam let list_starts_with = fn(the_list: List(value), the_value: value) -> Bool { case the_list { [head, ..] if head == the_value -> True _ -> False } } io.debug(list_starts_with([10, 20, 30], 10)) ``` -------------------------------- ### Basic Parallel "Hello, World!" with OpenMP Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/openmp.md A simple C program demonstrating the basic OpenMP parallel region. The number of "Hello, World!" outputs will match the number of threads available. ```cpp #include int main() { #pragma omp parallel { printf("Hello, World!\n"); } return 0; } ``` -------------------------------- ### Jinja2 Filter Examples Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/ansible.md Illustrates the use of Jinja2 filters for common operations like getting the first item of a list or providing a default value for an undefined variable. These filters enhance template flexibility. ```jinja2 # get first item of the list {{ some_list | first() }} # if variable is undefined - use default value {{ some_variable | default('default_value') }} ``` -------------------------------- ### Class Instantiation and Method Calls in Java Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/java.md Illustrates how to create an instance of a class using the 'new' keyword and how to invoke its methods. It's recommended to use setter and getter methods for object property management. ```java Bicycle trek = new Bicycle(); trek.speedUp(3); trek.setCadence(100); System.out.println("trek info: " + trek.toString()); ``` -------------------------------- ### Go goto statement example Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/go.md A simple demonstration of the 'goto' statement to jump to a labeled statement. ```go // When you need it, you'll love it. goto love love: learnFunctionFactory() // func returning func is fun(3)(3) learnDefer() // A quick detour to an important keyword. learnInterfaces() // Good stuff coming up! ``` -------------------------------- ### Install docutils with pip Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/rst.md Use pip, a common Python package installer, to install the docutils package. ```bash $ pip install docutils ``` -------------------------------- ### Open Fish Web Configuration Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/fish.md Launch the web-based interface for configuring Fish shell settings. ```bash > fish_config ``` -------------------------------- ### For Loop with range(start, stop) Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/python.md Iterate over a sequence of numbers within a specified range, starting from 'start' and ending before 'stop'. ```python for i in range(4, 8): print(i) ``` -------------------------------- ### Get all enum values and serialize them Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/sorbet.md To get all the values in the enum, use `.values`. The `#serialize` method gets the enum string value. ```ruby sig { returns(T::Array[String]) } def crayon_names Crayon.values.map(&:serialize) end ``` -------------------------------- ### Initializing a New CUE Module Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/cue.md Use `cue mod init` to create a new module, which establishes a `cue.mod/` directory for module metadata and organizes project files under a specified module name (e.g., `example.com/mymodule`). ```bash mkdir mymodule && cd mymodule cue mod init example.com/mymodule ``` -------------------------------- ### For Loop with range(start, stop, step) Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/python.md Iterate over a sequence of numbers with a defined step. The loop starts at 'start', increments by 'step', and stops before 'stop'. ```python for i in range(4, 8, 2): print(i) ``` -------------------------------- ### Go Program Structure and Entry Point Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/go.md Demonstrates the basic structure of a Go program, including package declaration, imports, and the main function as the entry point for executable programs. It also shows how to print output to the console. ```go // Single line comment /* Multi- line comment */ /* A build tag is a line comment starting with //go:build and can be executed by go build -tags="foo bar" command. Build tags are placed before the package clause near or at the top of the file followed by a blank line or other line comments. */ //go:build prod || dev || test // A package clause starts every source file. // main is a special name declaring an executable rather than a library. package main // Import declaration declares library packages referenced in this file. import ( "fmt" // A package in the Go standard library. "io" // Implements some I/O utility functions. m "math" // Math library with local alias m. "net/http" // Yes, a web server! _ "net/http/pprof" // Profiling library imported only for side effects "os" // OS functions like working with the file system "strconv" // String conversions. ) // A function definition. Main is special. It is the entry point for the // executable program. Love it or hate it, Go uses brace brackets. func main() { // Println outputs a line to stdout. // It comes from the package fmt. fmt.Println("Hello world!") // Call another function within this package. beyondHello() } // Functions have parameters in parentheses. // If there are no parameters, empty parentheses are still required. func beyondHello() { var x int // Variable declaration. Variables must be declared before use. x = 3 // Variable assignment. // "Short" declarations use := to infer the type, declare, and assign. y := 4 sum, prod := learnMultiple(x, y) // Function returns two values. fmt.Println("sum:", sum, "prod:", prod) // Simple output. learnTypes() // < y minutes, learn more! } /* <- multiline comment Functions can have parameters and (multiple!) return values. Here `x`, `y` are the arguments and `sum`, `prod` is the signature (what's returned). Note that `x` and `sum` receive the type `int`. */ func learnMultiple(x, y int) (sum, prod int) { return x + y, x * y // Return two values. } ``` -------------------------------- ### Create a Container Without Starting Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/docker.md Creates a new container from a specified image but does not automatically start it. This is useful for setting up container configurations before explicit starting. ```bash docker create alpine ``` -------------------------------- ### Loading Kdb+ Scripts Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/kdb+.md Shows how to load Kdb+ scripts from the q session using the '\l' command or from the command prompt by passing the script as an argument. ```q \l learnkdb.q ``` ```q q learnkdb.q ``` -------------------------------- ### Evaluating Unified Configurations with Imports Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/cue.md This example demonstrates unifying a top-level `main.cue` file with configurations from a `config` package. The `cue eval` command unifies files in the current directory, respecting package declarations and import paths. ```cue //main.cue package main import "example.com/mymodule/config" configuredBar: config.bar ``` ```cue //a.cue package config foo: 100 bar: int ``` ```cue //b.cue package config bar: 200 ``` -------------------------------- ### Get and Set ZFS Dataset Properties Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/zfs.md Use 'zfs get' to retrieve properties and 'zfs set' to modify them. 'zfs get all' shows all properties for a dataset. ```bash # Get all properties $ zfs get all zroot/usr/home NAME PROPERTY VALUE SOURCE zroot/home type filesystem - zroot/home creation Mon Oct 20 14:44 2014 - zroot/home used 11.9G - zroot/home available 94.1G - zroot/home referenced 11.9G - zroot/home mounted yes - ... # Get property from dataset $ zfs get compression zroot/usr/home NAME PROPERTY VALUE SOURCE zroot/home compression off default # Set property on dataset $ zfs set compression=lz4 zroot/lamb # Get a set of properties from all datasets $ zfs list -o name,quota,reservation NAME QUOTA RESERV zroot none none zroot/ROOT none none zroot/ROOT/default none none zroot/tmp none none zroot/usr none none zroot/home none none zroot/var none none ... ``` -------------------------------- ### Get Dictionary Keys and Values in Julia Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/julia.md Use `keys` to get a collection of all keys and `values` to get a collection of all values in a dictionary. Note that the order is not guaranteed. ```julia keys(filledDict) ``` ```julia values(filledDict) ``` -------------------------------- ### Inform 7: Demonstrating Phrase Calls with Parameters Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/inform7.md Demonstrate how to call phrases with multiple parameters, including using local variables to hold object references. ```inform7 Block2 is a datablock. Block2 is broken. The sequence number of Block2 is 2. The name of Block2 is "Block two." To demonstrate calling a phrase with two parameters: Let the second block be block2; fix the second block using Block1; say the sequence number of the second block. ``` -------------------------------- ### Stop and Start Containers Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/docker.md Commands to stop a running container or start a stopped container. `docker start -a` can be used to attach a detached container back to the terminal. ```bash docker stop hello-world ``` ```bash docker start hello-world ``` ```bash docker start -a ubuntu ``` -------------------------------- ### Array slicing with custom start index Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/tailspin.md Demonstrates array slicing with different start indexes. By default, array indexing starts at 1. Negative indexes count from the end. ```Tailspin [1..5] -> $(-2..2) -> '$; ' -> !OUT::write ``` ```Tailspin 0:[1..5] -> $(-2..2) -> '$; ' -> !OUT::write ``` ```Tailspin -2:[1..5] -> $(-2..2) -> '$; ' -> !OUT::write ``` -------------------------------- ### AngularJS ng-show Directive Example Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/angularjs.md This example demonstrates the ng-show directive, which makes an HTML element visible when its expression evaluates to true. It mirrors the ng-hide example by toggling visibility. ```html

First Name:
Last Name:

Full Name: {{firstName + " " + lastName}}

``` -------------------------------- ### Install Python on macOS Source: https://github.com/adambard/learnxinyminutes-docs/blob/master/CONTRIBUTING.md Use Homebrew to install Python on macOS systems. ```sh brew install python ```