Quick Reference

Ultimate Developer Cheatsheets

Comprehensive syntax references, patterns, and best practices for modern development

HTML5 & CSS3 Master Reference

HTML5 Essentials

<!-- Document Structure -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Page description">
    <title>Document Title</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <!-- Semantic Structure -->
    <header>
        <nav><!-- Navigation --></nav>
    </header>
    <main>
        <article>
            <section><!-- Content --></section>
        </article>
        <aside><!-- Sidebar --></aside>
    </main>
    <footer><!-- Footer --></footer>
</body>
</html>

<!-- Common Elements -->
<h1> to <h6>  <!-- Headings -->
<p>Paragraph</p>
<a href="url">Link</a>
<img src="image.jpg" alt="description">
<ul><li>List</li></ul>
<ol><li>Ordered List</li></ol>
<table><tr><td>Table</td></tr></table>

<!-- Forms -->
<form action="/submit" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
    
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>
    
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" minlength="8">
    
    <label for="message">Message:</label>
    <textarea id="message" name="message"></textarea>
    
    <label for="country">Country:</label>
    <select id="country" name="country">
        <option value="us">United States</option>
        <option value="ca">Canada</option>
    </select>
    
    <fieldset>
        <legend>Subscribe:</legend>
        <input type="radio" id="yes" name="subscribe" value="yes">
        <label for="yes">Yes</label>
        <input type="radio" id="no" name="subscribe" value="no">
        <label for="no">No</label>
    </fieldset>
    
    <button type="submit">Submit</button>
</form>

CSS3 Complete Reference

/* === Selectors === */
element               /* Tag selector */
#id                  /* ID selector */
.class               /* Class selector */
[attribute]          /* Attribute selector */
*                    /* Universal selector */

/* Combinators */
selector1 selector2  /* Descendant */
selector1 > selector2 /* Child */
selector1 + selector2 /* Adjacent sibling */
selector1 ~ selector2 /* General sibling */

/* Pseudo-classes */
:link, :visited, :hover, :active
:focus, :checked, :disabled
:first-child, :last-child, :nth-child(n)
:not(selector)

/* Pseudo-elements */
::before, ::after, ::first-letter, ::first-line

/* === Box Model === */
width: 100px;
height: 100px;
margin: 10px;       /* All sides */
margin: 5px 10px;   /* Top/Bottom Left/Right */
margin: 5px 10px 15px 20px; /* Top Right Bottom Left */
padding: 10px;      /* Same as margin */
border: 1px solid #000;
border-radius: 5px;
box-sizing: border-box; /* Include padding/border in width/height */

/* === Flexbox === */
.container {
  display: flex;
  flex-direction: row | row-reverse | column | column-reverse;
  flex-wrap: nowrap | wrap | wrap-reverse;
  justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly;
  align-items: stretch | flex-start | flex-end | center | baseline;
  align-content: flex-start | flex-end | center | space-between | space-around | stretch;
}

.item {
  order: <integer>;
  flex-grow: <number>; /* default 0 */
  flex-shrink: <number>; /* default 1 */
  flex-basis: <length> | auto; /* default auto */
  align-self: auto | flex-start | flex-end | center | baseline | stretch;
}

/* === Grid === */
.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 100px 200px;
  gap: 10px;
  grid-template-areas:
    "header header header"
    "sidebar main main";
}

.item {
  grid-column: 1 / 3;
  grid-row: 1;
  grid-area: header;
}

/* === Responsive Design === */
@media (min-width: 768px) {
  /* Styles for screens ≥768px */
}

/* === Transforms & Animations === */
transform: rotate(45deg) scale(1.2) translateX(10px);
transition: property duration timing-function delay;
animation: name duration timing-function delay iteration-count direction fill-mode;

@keyframes name {
  from { opacity: 0; }
  to { opacity: 1; }
}

JavaScript & ES6+ Complete Reference

Variables & Functions

// Variable Declarations
var variable1 = 'value'; // Function scope
let variable2 = 'value'; // Block scope
const constant = 'value'; // Block scope, immutable

// Data Types
typeof 'Hello'   // "string"
typeof 42        // "number"
typeof true      // "boolean"
typeof undefined // "undefined"
typeof null      // "object" (historical bug)
typeof {}        // "object"
typeof []        // "object"
typeof Symbol()  // "symbol"
typeof BigInt(1) // "bigint"

// Type Conversion
String(123)     // "123"
Number("123")   // 123
Boolean(1)      // true
parseInt("10")  // 10
parseFloat("10.5") // 10.5

// Functions
function name(param) { return value; }
const func = function(param) { };
const arrowFunc = (param) => { };

// Default Parameters
function greet(name = 'Guest') { }

// Rest Parameters
function sum(...numbers) { }

// Immediately Invoked Function Expression (IIFE)
(function() {
    // Code here
})();

// Closures
function outer() {
    let count = 0;
    return function inner() {
        return ++count;
    };
}

Objects & Arrays

// Object Literal
const obj = {
    property: 'value',
    method() { return this.property; }
};

// Accessing Properties
obj.property    // Dot notation
obj['property'] // Bracket notation

// Object Destructuring
const { property, method } = obj;

// Object Spread
const newObj = { ...obj, newProp: 'value' };

// Array Literal
const arr = [1, 2, 3];

// Array Methods
arr.push(4);       // Add to end
arr.pop();         // Remove from end
arr.shift();       // Remove from start
arr.unshift(0);    // Add to start
arr.slice(1, 3);   // Extract portion
arr.splice(1, 1);  // Remove/insert items
arr.concat([4,5]); // Combine arrays
arr.indexOf(2);    // Find index
arr.includes(2);   // Check existence

// Array Destructuring
const [first, second] = arr;

// Array Spread
const newArr = [...arr, 4, 5];

// Higher-Order Array Methods
arr.map(x => x * 2);       // Transform
arr.filter(x => x > 1);    // Filter
arr.reduce((acc, x) => acc + x, 0); // Reduce
arr.forEach(x => console.log(x)); // Iterate
arr.some(x => x > 2);      // Test some
arr.every(x => x > 0);     // Test all
arr.find(x => x > 1);      // Find first
arr.findIndex(x => x > 1); // Find index

ES6+ Features

// Arrow Functions
const add = (a, b) => a + b;

// Template Literals
const name = 'Alice';
const greeting = `Hello ${name}!`;

// Classes
class Person {
    constructor(name) {
        this.name = name;
    }
    
    greet() {
        return `Hello, ${this.name}!`;
    }
    
    static staticMethod() {
        return 'Static method';
    }
}

class Student extends Person {
    constructor(name, grade) {
        super(name);
        this.grade = grade;
    }
}

// Modules
// file.js
export const value = 42;
export function func() { }
export default class MyClass { }

// Importing
import { value, func } from './file';
import MyClass from './file';
import * as module from './file';

// Promises
const promise = new Promise((resolve, reject) => {
    // Async operation
    if (success) resolve(value);
    else reject(error);
});

promise
    .then(value => { })
    .catch(error => { })
    .finally(() => { });

// Async/Await
async function fetchData() {
    try {
        const response = await fetch(url);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error(error);
    }
}

// Optional Chaining
const street = user?.address?.street;

// Nullish Coalescing
const value = input ?? 'default';

DOM Manipulation

// Selecting Elements
document.getElementById('id');
document.querySelector('.class');
document.querySelectorAll('div');

// Creating Elements
const div = document.createElement('div');
div.textContent = 'Hello';
div.innerHTML = '<strong>Hello</strong>';

// Modifying Elements
element.classList.add('class');
element.classList.remove('class');
element.classList.toggle('class');
element.setAttribute('name', 'value');
element.getAttribute('name');
element.style.property = 'value';

// Events
element.addEventListener('click', event => {
    event.preventDefault();
    console.log(event.target);
});

// Common Events
'click', 'dblclick', 'mouseenter', 'mouseleave'
'keydown', 'keyup', 'keypress'
'submit', 'change', 'input', 'focus', 'blur'
'load', 'DOMContentLoaded', 'resize', 'scroll'

// Event Delegation
parent.addEventListener('click', event => {
    if (event.target.matches('.child')) {
        // Handle child click
    }
});

// AJAX with Fetch
fetch('url')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));

// Form Data
const formData = new FormData(form);
fetch('url', {
    method: 'POST',
    body: formData
});

Python 3 Comprehensive Reference

Python Basics

# Variables and Types
x = 5               # Integer
y = 3.14            # Float
name = "Python"     # String
is_true = True      # Boolean
nums = [1, 2, 3]    # List
info = {'key': 'value'} # Dictionary

# Type Conversion
int("10")       # 10
float("3.14")   # 3.14
str(10)         # "10"
list((1, 2, 3)) # [1, 2, 3]

# Strings
len("hello")            # 5
"hello".upper()         # "HELLO"
"HELLO".lower()         # "hello"
"hello world".split()   # ['hello', 'world']
" ".join(['hello', 'world']) # "hello world"
f"Value: {x}"           # f-string (Python 3.6+)

# Lists
nums = [1, 2, 3]
nums.append(4)      # [1, 2, 3, 4]
nums.insert(1, 1.5) # [1, 1.5, 2, 3, 4]
nums.remove(2)      # [1, 1.5, 3, 4]
nums.pop()          # returns 4, nums is [1, 1.5, 3]
nums[0]             # 1
nums[-1]            # 3 (last element)
nums[1:3]           # [1.5, 3] (slice)
nums[::-1]          # [3, 1.5, 1] (reverse)

# List Comprehensions
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]

Functions & Classes

# Functions
def greet(name="World"):
    """Greet someone by name"""
    return f"Hello, {name}!"

# Variable Arguments
def sum_all(*args):
    return sum(args)

# Keyword Arguments
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# Lambda Functions
square = lambda x: x * x

# Classes
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"My name is {self.name}"
    
    @classmethod
    def from_birth_year(cls, name, birth_year):
        age = datetime.date.today().year - birth_year
        return cls(name, age)
    
    @staticmethod
    def is_adult(age):
        return age >= 18

# Inheritance
class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade
    
    def study(self):
        return "Studying hard"

# Decorators
def debug(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@debug
def say_hello():
    print("Hello!")

File Handling & Modules

# Reading Files
with open('file.txt', 'r') as file:
    content = file.read()

# Writing Files
with open('file.txt', 'w') as file:
    file.write("Hello, World!")

# CSV Files
import csv
with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# JSON
import json
data = {'name': 'John', 'age': 30}
json_str = json.dumps(data)  # Convert to JSON string
data = json.loads(json_str)  # Convert from JSON string

# Working with Paths
from pathlib import Path
path = Path('folder/file.txt')
path.exists()       # Check if exists
path.is_file()      # Check if is file
path.parent         # Parent directory
path.name           # Filename with extension
path.stem           # Filename without extension
path.suffix         # File extension

# Modules
# mymodule.py
def func():
    return "Hello"

# main.py
import mymodule
from mymodule import func
import mymodule as mm
from package import module

Popular Libraries

# NumPy (Numerical Computing)
import numpy as np
arr = np.array([1, 2, 3])
arr.shape          # (3,)
zeros = np.zeros((2, 3)) # 2x3 array of 0s
arr.mean()         # 2.0
arr.sum()          # 6
np.dot(arr, arr)   # Dot product

# Pandas (Data Analysis)
import pandas as pd
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df.head()          # First 5 rows
df.describe()      # Statistics
df['A'].mean()     # Mean of column A
df[df['A'] > 1]    # Filter rows

# Matplotlib (Plotting)
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('Title')
plt.show()

# Requests (HTTP)
import requests
response = requests.get('https://api.example.com')
data = response.json()

# Flask (Web Framework)
from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, World!"

if __name__ == '__main__':
    app.run(debug=True)

Download Complete Cheatsheet Bundle

Get all these references in printable PDF format for offline access and quick lookup.