### Build a Simple HTTP Server with Python Source: https://context7.com/codecrafters-io/build-your-own-x/llms.txt Demonstrates a basic HTTP server using Python's socket library. It listens on a specified port, accepts incoming connections, and returns a static 'Hello, World!' response. ```python import socket def handle_request(request): http_response = b"HTTP/1.1 200 OK\n\nHello, World!\n" return http_response def serve_forever(): listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listen_socket.bind(('', 8888)) listen_socket.listen(1) while True: client_connection, client_address = listen_socket.accept() request = client_connection.recv(1024) http_response = handle_request(request) client_connection.sendall(http_response) client_connection.close() ``` -------------------------------- ### Operating System: Kernel Entry Point (C) Source: https://context7.com/codecrafters-io/build-your-own-x/llms.txt Provides a basic C implementation for a kernel's entry point, demonstrating how to interact with video memory to display text on the screen. This snippet is foundational for understanding OS development. ```c // Example: Simple kernel entry point (from Kernel 101) void kernel_main(void) { const char *str = "Hello, Kernel World!"; char *vidptr = (char*)0xb8000; // Video memory address unsigned int i = 0; unsigned int j = 0; // Clear screen while (j < 80 * 25 * 2) { vidptr[j] = ' '; vidptr[j+1] = 0x07; j = j + 2; } // Print string j = 0; while (str[j] != '\0') { vidptr[i] = str[j]; vidptr[i+1] = 0x07; ++j; i = i + 2; } } ``` -------------------------------- ### Create a Minimal Container with Go Source: https://context7.com/codecrafters-io/build-your-own-x/llms.txt Uses Linux namespaces and syscalls to create an isolated process environment. It demonstrates process isolation by setting hostnames and chrooting the filesystem. ```go package main import ("fmt", "os", "os/exec", "syscall") func main() { switch os.Args[1] { case "run": run() case "child": child() } } func run() { cmd := exec.Command("/proc/self/exe", append([]string{"child"}, os.Args[2:]...)...) cmd.SysProcAttr = &syscall.SysProcAttr{Cloneflags: syscall.CLONE_NEWUTS | syscall.CLONE_NEWPID | syscall.CLONE_NEWNS} cmd.Run() } func child() { syscall.Sethostname([]byte("container")) syscall.Chroot("/") cmd := exec.Command(os.Args[2], os.Args[3:]...) cmd.Run() } ``` -------------------------------- ### Implement Unix Shell Command Parsing and Process Management in C Source: https://context7.com/codecrafters-io/build-your-own-x/llms.txt This snippet demonstrates the core loop of a Unix shell, including tokenizing input strings and spawning child processes using fork and execvp. It handles basic command execution and process synchronization using waitpid. ```c #include #include #include #include #include #define LSH_TOK_BUFSIZE 64 #define LSH_TOK_DELIM " \t\r\n\a" char **lsh_split_line(char *line) { int bufsize = LSH_TOK_BUFSIZE, position = 0; char **tokens = malloc(bufsize * sizeof(char*)); char *token; token = strtok(line, LSH_TOK_DELIM); while (token != NULL) { tokens[position] = token; position++; token = strtok(NULL, LSH_TOK_DELIM); } tokens[position] = NULL; return tokens; } int lsh_launch(char **args) { pid_t pid, wpid; int status; pid = fork(); if (pid == 0) { if (execvp(args[0], args) == -1) { perror("lsh"); } exit(EXIT_FAILURE); } else if (pid < 0) { perror("lsh"); } else { do { wpid = waitpid(pid, &status, WUNTRACED); } while (!WIFEXITED(status) && !WIFSIGNALED(status)); } return 1; } ``` -------------------------------- ### Train a Neural Network with Python Source: https://context7.com/codecrafters-io/build-your-own-x/llms.txt Implements a basic feedforward neural network using NumPy. It demonstrates weight initialization, forward propagation, and backpropagation to train the model over 60,000 iterations. ```python syn0 = 2 * np.random.random((3,4)) - 1 syn1 = 2 * np.random.random((4,1)) - 1 for j in range(60000): l0 = X l1 = sigmoid(np.dot(l0, syn0)) l2 = sigmoid(np.dot(l1, syn1)) l2_error = y - l2 l2_delta = l2_error * sigmoid(l2, deriv=True) l1_error = l2_delta.dot(syn1.T) l1_delta = l1_error * sigmoid(l1, deriv=True) syn1 += l1.T.dot(l2_delta) syn0 += l0.T.dot(l1_delta) ``` -------------------------------- ### Neural Network: Simple Network Implementation (Python) Source: https://context7.com/codecrafters-io/build-your-own-x/llms.txt Demonstrates the implementation of a basic neural network in Python using NumPy. It includes the sigmoid activation function and its derivative, along with the initialization of input and output datasets. ```python # Example: Simple neural network (from A Neural Network in 11 lines of Python) import numpy as np # Sigmoid function and derivative def sigmoid(x, deriv=False): if deriv: return x * (1 - x) return 1 / (1 + np.exp(-x)) # Input dataset X = np.array([[0,0,1], [0,1,1], [1,0,1], [1,1,1]]) # Output dataset y = np.array([[0], [1], [1], [0]]) # Seed random numbers np.random.seed(1) ``` -------------------------------- ### Implement a Blockchain with Python Source: https://context7.com/codecrafters-io/build-your-own-x/llms.txt Provides a foundational blockchain structure including block creation, hashing using SHA-256, and a proof-of-work algorithm to validate blocks. ```python import hashlib, json from time import time class Blockchain: def __init__(self): self.chain = [] self.current_transactions = [] self.new_block(previous_hash='1', proof=100) def new_block(self, proof, previous_hash=None): block = {'index': len(self.chain) + 1, 'timestamp': time(), 'transactions': self.current_transactions, 'proof': proof, 'previous_hash': previous_hash or self.hash(self.chain[-1])} self.current_transactions = [] self.chain.append(block) return block @staticmethod def hash(block): return hashlib.sha256(json.dumps(block, sort_keys=True).encode()).hexdigest() def proof_of_work(self, last_proof): proof = 0 while self.valid_proof(last_proof, proof) is False: proof += 1 return proof @staticmethod def valid_proof(last_proof, proof): return hashlib.sha256(f'{last_proof}{proof}'.encode()).hexdigest()[:4] == "0000" ``` -------------------------------- ### Implement Virtual DOM and Rendering in JavaScript Source: https://context7.com/codecrafters-io/build-your-own-x/llms.txt This snippet demonstrates a minimal React-like library. It includes functions for creating virtual DOM elements and a recursive renderer that transforms these objects into actual browser DOM nodes. ```javascript function createElement(type, props, ...children) { return { type, props: { ...props, children: children.map(child => typeof child === "object" ? child : createTextElement(child) ), }, }; } function createTextElement(text) { return { type: "TEXT_ELEMENT", props: { nodeValue: text, children: [], }, }; } function render(element, container) { const dom = element.type === "TEXT_ELEMENT" ? document.createTextNode("") : document.createElement(element.type); Object.keys(element.props) .filter(key => key !== "children") .forEach(name => { dom[name] = element.props[name]; }); element.props.children.forEach(child => render(child, dom)); container.appendChild(dom); } const element = createElement( "div", { id: "foo" }, createElement("a", null, "bar"), createElement("b") ); render(element, document.getElementById("root")); ``` -------------------------------- ### 3D Renderer: Ray-Sphere Intersection and Render Loop (C++) Source: https://context7.com/codecrafters-io/build-your-own-x/llms.txt Demonstrates fundamental concepts in 3D graphics rendering, including calculating ray-sphere intersections and the basic structure of a render loop. This snippet is useful for understanding the core logic behind ray tracing. ```cpp // Example: Basic ray-sphere intersection (from Ray Tracing in One Weekend) bool hit_sphere(const vec3& center, double radius, const ray& r) { vec3 oc = r.origin() - center; auto a = dot(r.direction(), r.direction()); auto b = 2.0 * dot(oc, r.direction()); auto c = dot(oc, oc) - radius*radius; auto discriminant = b*b - 4*a*c; return (discriminant > 0); } // Render loop for (int j = image_height-1; j >= 0; --j) { for (int i = 0; i < image_width; ++i) { auto u = double(i) / (image_width-1); auto v = double(j) / (image_height-1); ray r(origin, lower_left_corner + u*horizontal + v*vertical - origin); color pixel_color = ray_color(r); write_color(std::cout, pixel_color); } } ``` -------------------------------- ### Implement Git Object Storage in Python Source: https://context7.com/codecrafters-io/build-your-own-x/llms.txt This module provides functions to write and read Git objects from the file system. It handles object serialization, SHA-1 hashing, and zlib compression to mimic Git's internal storage mechanism. ```python import hashlib import zlib import os def object_write(repo, obj): data = obj.serialize() result = obj.fmt + b' ' + str(len(data)).encode() + b'\x00' + data sha = hashlib.sha1(result).hexdigest() path = os.path.join(repo.gitdir, "objects", sha[0:2], sha[2:]) os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, 'wb') as f: f.write(zlib.compress(result)) return sha def object_read(repo, sha): path = os.path.join(repo.gitdir, "objects", sha[0:2], sha[2:]) with open(path, "rb") as f: raw = zlib.decompress(f.read()) x = raw.find(b' ') fmt = raw[0:x] y = raw.find(b'\x00', x) size = int(raw[x:y].decode("ascii")) return raw[y+1:] ``` -------------------------------- ### Programming Language: Lisp Interpreter (Python) Source: https://context7.com/codecrafters-io/build-your-own-x/llms.txt A Python implementation of a simple Lisp interpreter, covering tokenization, parsing, and basic expression evaluation. This snippet is valuable for learning about language design and interpreter implementation. ```python # Example: Simple Lisp interpreter (from How to Write a Lisp Interpreter in Python) def tokenize(chars): """Convert a string of characters into a list of tokens.""" return chars.replace('(', ' ( ').replace(')', ' ) ').split() def parse(program): """Read a Scheme expression from a string.""" return read_from_tokens(tokenize(program)) def read_from_tokens(tokens): """Read an expression from a sequence of tokens.""" if len(tokens) == 0: raise SyntaxError('unexpected EOF') token = tokens.pop(0) if token == '(': L = [] while tokens[0] != ')': L.append(read_from_tokens(tokens)) tokens.pop(0) # pop off ')' return L elif token == ')': raise SyntaxError('unexpected )') else: return atom(token) def atom(token): """Numbers become numbers; every other token is a symbol.""" try: return int(token) except ValueError: try: return float(token) except ValueError: return Symbol(token) ``` -------------------------------- ### Implement Regex Engine Matching Logic in JavaScript Source: https://context7.com/codecrafters-io/build-your-own-x/llms.txt A lightweight regex matcher implementation using recursive backtracking. It supports basic character matching, the dot wildcard, start/end anchors, and the Kleene star operator. ```javascript function match(pattern, text) { if (pattern[0] === '^') { return matchHere(pattern.slice(1), text); } let idx = 0; do { if (matchHere(pattern, text.slice(idx))) { return true; } } while (idx++ < text.length); return false; } function matchHere(pattern, text) { if (pattern.length === 0) return true; if (pattern[1] === '*') { return matchStar(pattern[0], pattern.slice(2), text); } if (pattern[0] === '$' && pattern.length === 1) { return text.length === 0; } if (text.length !== 0 && (pattern[0] === '.' || pattern[0] === text[0])) { return matchHere(pattern.slice(1), text.slice(1)); } return false; } function matchStar(c, pattern, text) { do { if (matchHere(pattern, text)) return true; } while (text.length !== 0 && (text[0] === c || c === '.') && (text = text.slice(1))); return false; } ``` -------------------------------- ### Database: B-Tree Node Structure (C) Source: https://context7.com/codecrafters-io/build-your-own-x/llms.txt Illustrates the structure of internal and leaf nodes within a B-Tree, a common data structure for database indexing. This C code defines headers and helper functions for accessing key-value pairs in leaf nodes. ```c // Example: Simple B-Tree node structure (from Let's Build a Simple Database) typedef struct { uint32_t num_cells; uint32_t right_child; } InternalNodeHeader; typedef struct { uint32_t num_cells; uint32_t next_leaf; } LeafNodeHeader; void* leaf_node_cell(void* node, uint32_t cell_num) { return node + LEAF_NODE_HEADER_SIZE + cell_num * LEAF_NODE_CELL_SIZE; } void* leaf_node_key(void* node, uint32_t cell_num) { return leaf_node_cell(node, cell_num); } void* leaf_node_value(void* node, uint32_t cell_num) { return leaf_node_cell(node, cell_num) + LEAF_NODE_KEY_SIZE; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.