Programming Reference
Abstract Base Class
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): passDefine a blueprint for other classes to inherit.
Aiohttp Client
async with aiohttp.ClientSession() as s:
async with s.get(url) as res:
return await res.json()Make asynchronous HTTP requests.
Async Function
async def main():
await asyncio.sleep(1)Define a function that can run concurrently.
Asyncio Gathering
await asyncio.gather(task1, task2)Run multiple coroutines concurrently and wait for all.
Base64 Encode
import base64
encoded = base64.b64encode(b'data')Convert binary data to a Base64 string.
Binary Read
with open('file.bin', 'rb') as f:
data = f.read()Open and read files in binary mode.
CSV Read (Dict)
import csv
with open('d.csv') as f:
reader = csv.DictReader(f)Read CSV rows directly into dictionaries.
Custom Exception
class MyError(Exception): passCreate a user-defined error type.
Data Classes
from dataclasses import dataclass
@dataclass
class User: id: int; name: strAuto-generate init, repr, and eq methods.
Datetime Now
from datetime import datetime
now = datetime.now()Get current system date and time.
Datetime Parse
datetime.strptime('2024-01-01', '%Y-%m-%d')Convert a string into a datetime object.
Deep Copy
import copy
new_obj = copy.deepcopy(old_obj)Copy an object and all nested items inside it.
Dict Comprehension
{k: v for k, v in data if v > 0}Create a new dictionary using logic in one line.
Docstring
"""Multi-line description of function."""Standard way to document code modules/methods.
Environment Path
import sys
sys.path.append('path/to/mod')Add a custom directory to Python's module search.
Filter List
list(filter(lambda x: x > 0, l))Keep only items that meet a specific condition.
F-String Precision
print(f"{pi:.2f}")Format a float to a specific number of decimals.
Get Recursion Limit
import sys
sys.getrecursionlimit()Check the maximum depth of the call stack.
Hash Password
import hashlib
hashlib.sha256(b'pass').hexdigest()Generate a secure SHA-256 hash of a string.
Heap Queue
import heapq
heapq.nlargest(3, list)Efficiently find the largest items in a collection.
Inspect Object
import inspect
inspect.getsource(my_func)Retrieve the source code of a live object.
Itertools Chain
from itertools import chain
new_l = list(chain(l1, l2))Combine multiple iterables into one sequence.
Itertools Cycle
from itertools import cycle
c = cycle(['A', 'B', 'C'])Infinitely repeat a sequence of items.
Lambda Function
add = lambda x, y: x + yCreate a small, anonymous one-line function.
List Dir
import os
os.listdir('.')List all files and folders in a directory.
Logging Basic
import logging
logging.basicConfig(level=logging.INFO)Setup standard logging for debugging applications.
LRU Cache
from functools import lru_cache
@lru_cache(maxsize=32)Store function results to speed up repeated calls.
Math Constants
import math
print(math.pi, math.e)Access standard mathematical constants.
Memory Map
import mmapRead a large file directly from memory for speed.
Named Tuple
from collections import namedtuple
P = namedtuple('P', ['x', 'y'])Create tuple-like objects with named fields.
Partial Function
from functools import partial
hex = partial(int, base=16)Fix some arguments of a function and return new.
Pathlib Join
from pathlib import Path
p = Path('dir') / 'file.txt'Modern, readable way to handle file paths.
Pickle Save
import pickle
pickle.dump(obj, open('o.pkl', 'wb'))Serialize and save a Python object to disk.
Platform Info
import platform
platform.system()Check if code is running on Windows, Linux, or Mac.
Pretty Print
from pprint import pprint
pprint(complex_dict)Print nested data structures in a readable way.
Property Decorator
@property
def name(self): return self._nameTurn a class method into a read-only attribute.
Pydantic Model
from pydantic import BaseModel
class Schema(BaseModel): id: intStrict data validation and settings management.
Pytest Mark
@pytest.mark.skip(reason='...')Skip specific tests during a test run.
Pytest Setup
def test_func():
assert func(1) == 2Standard unit test assertion boilerplate.
Random Range
import random
random.randint(1, 10)Generate a random integer between two values.
Regex Match
import re
re.search(r'\d+', text)Find a pattern within a string using regex.
Regex Sub
re.sub(r'\s+', '_', text)Replace patterns in a string using regex.
Reload Module
import importlib
importlib.reload(module)Reload an imported module without restarting.
Reverse List
l.reverse() # or l[::-1]Flip the order of items in a list.
Set Operations
set1.intersection(set2)Find common elements between two sets.
Shallow Copy
new_l = old_l.copy()Create a new collection with references to items.
Signal Handler
import signal
signal.signal(signal.SIGINT, handler)Capture system signals like Ctrl+C.
Singleton Pattern
_instance = None
def __new__(cls): ...Ensure a class has only one instance.
Sorted Function
sorted(l, reverse=True)Return a new sorted list from an iterable.
SQLlite Connect
import sqlite3
db = sqlite3.connect('app.db')Interact with a local SQL database file.
Static Method
@staticmethod
def info(): return "text"Define a class method that doesn't need 'self'.
String Formatting
"Hello {}".format(name)Classic way to inject variables into strings.
Temp File
import tempfile
with tempfile.TemporaryFile() as t:Create a file that deletes itself when closed.
Threading Basic
import threading
t = threading.Thread(target=f)Run code in a separate system thread.
Time Delta
from datetime import timedelta
future = now + timedelta(days=7)Calculate dates in the future or past.
Time Strftime
now.strftime("%Y-%m-%d %H:%M")Format a datetime object into a custom string.
Traceback Print
import traceback
traceback.print_exc()Print the full error history to the console.
Type Hinting
def greet(name: str) -> str:Annotate variable types for better IDE support.
Unpack List
first, *middle, last = [1, 2, 3, 4]Assign list elements to variables using stars.
Yield Generator
def count():
yield 1; yield 2Create an iterator that produces values lazily.
ACTIVATE ENV
conda activate my_envSwitch to a specific conda environment.
ACTIVE ENV PATH
conda info --active-env-pathDisplay the file path of the currently active environment.
ADD CHANNEL
conda config --add channels conda-forgeAdd a new channel to the top of the priority list.
ADD CHANNEL BOTTOM
conda config --append channels conda-forgeAdd a new channel to the end of the priority list.
ADD LAB EXTENSION
conda install -c conda-forge jupyterlabInstall JupyterLab into the environment.
ARCHITECTURE INFO
conda info --systemView OS and architecture details (e.g., win-64, osx-arm64).
AUTO-ACTIVATE BASE
conda config --set auto_activate_base falseDisable automatic activation of the base environment.
BATCH INSTALL
conda install --file requirements.txtInstall multiple packages from a text file list.
CHECK CONDA VERSION
conda --versionVerify the currently installed version of Conda.
CHECK PYTHON PATH
which pythonVerify which conda environment Python is executing from.
CHECK UNUSED
conda clean --dry-run --allPreview what files would be deleted by a clean command.
CLEAN ALL
conda clean --allRemove unused packages and caches to save disk space.
CLEAN INDEX CACHE
conda clean -iRemove the index cache to fix package search issues.
CLEAN PACKAGES
conda clean -pRemove unused cached packages.
CLEAN TARBALLS
conda clean -tRemove cached package tarballs.
CLEAR ALL CACHES
conda clean -aThe most aggressive cleanup for disk space.
CLONE ENVIRONMENT
conda create --name new_env --clone old_envCreate an exact copy of an existing environment.
COMPARE ENVS
conda compare env1.txtCompare an environment against an environment file.
CONFIG DESCRIBE
conda config --describeShow descriptions of all available configuration parameters.
CONFIG GET
conda config --get channelsView specific configuration settings.
CONFIG SET VALUE
conda config --set show_channel_urls yesEnable/disable specific conda features via config.
CONFIG SHOW
conda config --showDisplay all current configuration settings.
CONFIG SHOW SOURCES
conda config --show-sourcesShow where config settings are being pulled from (.condarc).
CONFIG WRITE
conda config --set key valueModify the condarc file from the command line.
CREATE ENV FROM FILE
conda env create -f environment.ymlBuild an environment from a YAML configuration file.
CREATE ENV PATH
conda create --prefix ./envsCreate an environment in a specific folder path.
CREATE ENV SPEC
conda create --name new_env --file spec.txtCreate an environment from an explicit spec list.
CREATE ENV WITH PYTHON
conda create -n my_env python=3.9Create environment with a specific Python version.
CREATE ENVIRONMENT
conda create --name my_envCreate a new, empty conda environment.
DEACTIVATE ENV
conda deactivateExit the current environment and return to base.
DESCRIBE ENV
conda env export --name my_envView the YAML structure of a specific environment.
DETAILED SEARCH
conda search package_name --infoShow detailed metadata for a specific package search.
DISABLE CHANNEL
conda config --remove channels channel_nameRemove a specific channel from your configuration.
DISABLE UPDATE
conda install package_name --no-update-depsInstall package without updating existing dependencies.
DRY RUN INSTALL
conda install package_name --dry-runPreview changes before actually installing a package.
ENV EXPORT NO BUILDS
conda env export --no-buildsExport environment without platform-specific build tags.
EXPORT ENVIRONMENT
conda env export > environment.ymlSave environment details to a YAML file for sharing.
EXPORT EXPLICIT
conda list --explicit > spec.txtCreate an explicit platform-specific package list.
EXPORT HISTORY
conda env export --from-history > env.ymlExport only packages explicitly installed by the user.
FIND ENV BY NAME
conda info --envs | grep my_envLocate an environment path using a keyword search.
FORCE REINSTALL
conda install --force-reinstall package_nameOverwrite an existing installation of a package.
FULL SYSTEM INFO
conda info --allShow detailed information about the conda installation.
GET BASE PATH
conda info --baseShow the location of the base conda installation.
HELP COMMAND
conda install --helpGet documentation for any specific conda command.
INIT SHELL
conda init bashInitialize conda for a specific shell (bash, zsh, powershell).
INSTALL FROM CHANNEL
conda install -c conda-forge package_nameInstall a package from a specific channel.
INSTALL MULTIPLE
conda install numpy scipy pandasInstall several packages in a single command.
INSTALL PACKAGE
conda install package_nameInstall a package into the active environment.
INSTALL SPEC VERSION
conda install package_name=1.2.3Install a very specific version of a package.
JSON OUTPUT
conda list --jsonFormat conda output as JSON for script processing.
LIST CHANNEL URLS
conda config --show channel_urlsCheck if channel origins are shown in list output.
LIST ENVIRONMENTS
conda env listShow all environments created on your system.
LIST EXPLICIT
conda list --explicitList packages as URLs for exact environment replication.
LIST IN ENV
conda list -n my_envList packages for an environment without activating it.
LIST PACKAGES
conda listList all packages installed in the active environment.
LIST UNTRACKED
conda list --untrackedList files in the environment not managed by conda.
LIST WITH REGEX
conda list "^py"List packages matching a regular expression.
LOCAL INSTALL
conda install /path/to/package.tar.bz2Install a package from a local file.
LOGS VIEW
ls $CONDA_PREFIX/conda-meta/historyManually check the raw history log of an environment.
NOTICE UPDATES
conda config --set notify_outdated_conda trueGet alerts when a newer conda version is available.
OFFLINE INSTALL
conda install package_name --offlineTry to install package using only local cached files.
OVERRIDE CHANNELS
conda install package --override-channels -c my_channelIgnore default channels and use only the one specified.
PACKAGE CONTENTS
conda list --exportList packages in a format compatible with requirements files.
PRUNE ENV
conda env update --file env.yml --pruneSync environment with file and remove unlisted packages.
QUIET MODE
conda install package -qRun installation with minimal terminal output.
REMOVE ALL CACHES
conda clean --index-cache --tarballs --packagesTargeted cleanup of specific conda cache types.
REMOVE ENV PATH
conda env remove -p ./envsDelete an environment using its directory path.
REMOVE ENVIRONMENT
conda remove --name my_env --allDelete an entire environment and all its packages.
REMOVE FROM ALL ENVS
conda clean --packagesRemove cached versions of packages not in use anywhere.
REMOVE PACKAGE
conda remove package_nameUninstall a package from the active environment.
RENAME ENVIRONMENT
conda rename -n old_name new_nameChange the name of an existing environment.
RESET CONFIG
conda config --remove-key key_nameDelete a specific configuration key and value.
REVISION HISTORY
conda list --revisions
conda install --revision 2See history of changes and roll back to a previous state.
RUN COMMAND
conda run -n my_env python script.pyRun a command inside an environment without activating it.
SEARCH FOR PACKAGE
conda search package_nameCheck if a package is available in current channels.
SEARCH FOR VERSION
conda search python=3.10Find all available sub-versions of a package.
SEARCH PLATFORM
conda search package --platform win-64Search for packages available on other operating systems.
SEARCH VIRTUAL
conda info --virtualList "virtual" packages detected from the system (libc, etc).
SET CHANNEL PRIORITY
conda config --set channel_priority strictEnsure conda only pulls from top priority channels.
SET PROXY
conda config --set proxy_servers.http http://user:pass@host:portConfigure conda to work behind a corporate proxy.
SET SOLVER
conda config --set solver libmambaSwitch to the faster libmamba solver (Conda 23.1+).
SHOW ENVS ONLY
conda info -eShort command to list all environment names.
SHOW PKGS PATHS
conda info --pkgs-dirsShow where conda stores downloaded package files.
TEST PACKAGE
conda test package_nameRun built-in tests for an installed conda package.
UNSUBSCRIBE CHANNEL
conda config --remove channels channel_urlStop tracking a specific remote channel URL.
UPDATE ALL
conda update --allUpdate all packages in the current environment.
UPDATE COND
conda update -n base condaUpdate the conda package manager itself.
UPDATE ENV SPECS
conda env update -n my_env --file environment.ymlModify an existing environment to match a YAML file.
UPDATE ENVIRONMENT
conda env update -f environment.ymlUpdate an environment based on a YAML file.
UPDATE PACKAGE
conda update package_nameUpdate a specific package to its latest compatible version.
UPGRADE CONDA BASE
conda upgrade -n base condaUpgrade core conda to the latest stable release.
USE DEFAULT CHANNELS
conda config --remove channels channel_nameRevert to using only the default conda channels.
VALIDATE ENV
conda list --verifyCheck if all packages in the env have valid metadata.
VERIFY PACKAGES
conda verify package_nameVerify the integrity of installed packages.
VIEW CONDARC
cat ~/.condarcView the content of the hidden conda config file.
VIEW ENV HISTORY
conda list --revisionsLook at every install/update event in this environment.
WAIT FOR LOCK
conda install --lockWait for a process lock if another conda instance is running.
WHO INSTALLED
conda list --explicitCheck package origins via explicit URLs.
Y/N AUTO-CONFIRM
conda install package -yAutomatically answer "Yes" to all prompts during install.
ZIP ENVIRONMENT
conda-pack -n my_env -o my_env.tar.gzArchive an environment for relocation (requires conda-pack).
APPEND FILE
cat file1 >> file2Append the contents of one file to the end of another.
ARCHIVE DIRECTORY
tar -czvf archive.tar.gz dir/Create a compressed gzip archive of a folder.
BACKGROUND JOB
command &Run a terminal command in the background.
BASE64 DECODE
echo "str" | base64 --decodeDecode a base64 string via terminal.
BASH HISTORY
historyView a list of all recently executed commands.
CALCULATOR
echo "scale=2; 10/3" | bcPerform math calculations directly in the shell.
CALENDAR
calDisplay a simple text-based calendar.
CHANGE GROUP
chgrp groupname fileChange the group ownership of a file.
CHANGE OWNER
chown user:group fileChange the user and group ownership of a file.
CHANGE PERMISSIONS
chmod 755 fileModify read, write, and execute permissions.
CHECK DISK USAGE
du -sh *Show human-readable size of files in directory.
CLEAR TERMINAL
clearClear all text from the current terminal window.
COPY DIRECTORY
cp -r dir1 dir2Copy a directory and all its contents recursively.
COPY FILE
cp file1 file2Copy a file from one location to another.
COUNT LINES
wc -l fileCount the number of lines in a text file.
CPU INFO
lscpuDisplay detailed information about the CPU architecture.
CREATE DIRECTORY
mkdir new_folderCreate a new directory in the current path.
CREATE EMPTY FILE
touch file.txtCreate a new file or update a timestamp.
CREATE SYMLINK
ln -s /path/to/file linknameCreate a symbolic link to a file or folder.
CRON JOBS
crontab -eEdit the list of scheduled background tasks.
CURL GET
curl http://api.comSend an HTTP GET request to a URL.
CURRENT DIRECTORY
pwdPrint the full path of the working directory.
CURRENT USER
whoamiDisplay the username of the active session.
DISK FREE SPACE
df -hShow available disk space on all mounted filesystems.
DISPLAY DATE
datePrint the current system date and time.
DNS LOOKUP
dig domain.comQuery DNS records for a specific domain.
DOWNLOAD FILE
wget http://url.com/fileDownload a file from the internet to local storage.
EDIT WITH NANO
nano file.txtOpen a simple terminal-based text editor.
EDIT WITH VIM
vim file.txtOpen the advanced Vi IMproved text editor.
ENVIRONMENT VARS
printenvList all active environment variables.
EXTRACT TAR
tar -xzvf archive.tar.gzExtract files from a compressed tar archive.
FILE DETAILS
stat file.txtShow detailed status and metadata of a file.
FILE TYPE
file picture.pngDetermine the actual format of a file.
FIND BY NAME
find . -name "*.log"Search for files based on their filename.
FIND BY SIZE
find / -size +100MFind all files larger than 100MB.
FIND EXECUTABLE
which pythonLocate the path of a command executable.
FIND TEXT
grep -r "pattern" .Search for text within files recursively.
FOLLOW LOG
tail -f access.logView a file's content in real-time as it updates.
FREE MEMORY
free -mShow used and available RAM in megabytes.
GENERATE SSH KEY
ssh-keygen -t rsaCreate a new pair of SSH public/private keys.
GET IP ADDRESS
curl ifconfig.meQuickly find your public IP address.
GREP IGNORE CASE
grep -i "text" fileSearch for text regardless of capitalization.
GREP LINE NUMBER
grep -n "text" fileFind text and display the corresponding line number.
HARDWARE INFO
sudo lshw -shortDisplay a brief summary of system hardware.
HEAD OF FILE
head -n 10 fileView the first 10 lines of a file.
HOSTNAME
hostname -IDisplay the internal IP address of the host.
HTTP HEADERS
curl -I http://site.comFetch only the HTTP headers from a URL.
JSON PRETTY PRINT
cat data.json | jq .Format and colorize JSON output (requires jq).
KILL BY NAME
pkill -f process_nameStop a process using its name instead of PID.
KILL PROCESS
kill -9 1234Forcefully stop a process using its ID.
LIST ALL FILES
ls -laList all files, including hidden ones, with details.
LIST BLOCK DEVICES
lsblkList all hard drives and partitions.
LIST OPEN FILES
lsof -i :8000Find which process is using a specific port.
LIST PCI DEVICES
lspciList all PCI buses and devices (GPUs, etc).
LIST PROCESSES
ps auxView all currently running processes on the system.
LIST USB DEVICES
lsusbList all USB controllers and connected devices.
LOCATE FILE
locate file.txtQuickly find a file using an indexed database.
MAKE EXECUTABLE
chmod +x script.shGrant execute permissions to a script file.
MANUAL PAGE
man commandOpen the official documentation for a command.
MONITOR CPU
topDisplay real-time system resource usage.
MONITOR GPU
nvidia-smiCheck NVIDIA GPU usage and temperature.
MOVE FILE
mv file1 destination/Move or rename files and directories.
NETWORK INTERFACES
ip addrShow all network interfaces and IP addresses.
NETWORK STATS
netstat -tulnView all active listening ports and connections.
OPEN DIRECTORY
cd folder_nameChange the current working directory.
PARENT DIRECTORY
cd ..Move up one level in the folder hierarchy.
PING HOST
ping google.comCheck network connectivity to a remote host.
READ FILE
cat file.txtDisplay the entire content of a file in terminal.
REBOOT SYSTEM
sudo rebootImmediately restart the computer.
RELOAD BASHRC
source ~/.bashrcApply changes made to the bash config file.
REMOVE DIRECTORY
rm -rf folder/Forcefully delete a directory and its contents.
REMOVE FILE
rm file.txtDelete a file from the system permanently.
RENAME FILE
mv old.txt new.txtRename a file by moving it to a new name.
REPLACE TEXT
sed -i 's/old/new/g' fileFind and replace text within a file via CLI.
RSYNC COPY
rsync -avz local/ remote:/pathSync files between folders or remote servers.
SEARCH HISTORY
history | grep "cmd"Search your command history for a specific string.
SEND SHUTDOWN
sudo shutdown nowTurn off the computer immediately.
SESSIONS (SCREEN)
screen -S session_nameStart a persistent terminal session.
SESSIONS (TMUX)
tmux new -s sessionStart a terminal multiplexer session.
SHOW GROUPS
groups usernameList all groups a specific user belongs to.
SORT FILE
sort file.txtAlphabetically sort the lines in a text file.
SSH CONNECT
ssh user@hostLog into a remote server securely via SSH.
SUDO PRIVILEGE
sudo commandRun a command with administrative/root rights.
SYSTEM LOGS
journalctl -xeView system logs and error messages.
SYSTEM UPTIME
uptimeShow how long the system has been running.
TAIL OF FILE
tail -n 10 fileView the last 10 lines of a file.
TRACEROUTE
traceroute google.comTrace the path packets take to a network host.
UNIQUE LINES
uniq file.txtRemove duplicate lines from a sorted file.
UNMOUNT DISK
sudo umount /dev/sdb1Safely unmount a disk partition or USB drive.
UPDATE PACKAGES
sudo apt updateRefresh the list of available software updates.
UPGRADE SYSTEM
sudo apt upgradeInstall all available software updates.
USER GUID
id -u usernameDisplay the unique User ID for a person.
VIEW KERNEL
uname -aShow the OS version and kernel release info.
VIEW PATH
echo $PATHDisplay the directories included in the system PATH.
WHO IS LOGGED IN
wShow who is logged in and what they are doing.
WORDS COUNT
wc -w fileCount the total number of words in a file.
WRITE TO FILE
echo "text" > file.txtOverwrites a file with the specified string.
XARGS COMMAND
find . -name "*.bak" | xargs rmPass output of one command as arguments to another.
ZIP FILE
zip archive.zip file1 file2Compress files into a standard ZIP archive.
ACTIVATE SHEET
Sheets("Sheet1").ActivateBrings a specific worksheet to the foreground.
ADD NEW SHEET
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "NewSheet"Create a new worksheet at the end of the workbook.
AUTO-FIT COLUMNS
Columns("A:Z").AutoFitAdjust column widths to fit the content automatically.
AUTO-FILTER OFF
If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilterMode = FalseRemove any active filters from the worksheet.
BOLD TEXT
Range("A1:A10").Font.Bold = TrueApply bold formatting to a specific range.
CALL SUBROUTINE
Call MyMacroExecute another macro from within the current code.
CELL BACKGROUND COLOR
Range("A1").Interior.Color = RGB(255, 0, 0)Change a cell's background color using RGB values.
CELL COMMENT
Range("A1").AddComment "This is a note"Add a text comment/note to a specific cell.
CENTER ALIGN
Range("A1:C1").HorizontalAlignment = xlCenterHorizontally center content within cells.
CLEAR ALL
Cells.ClearDelete everything (content and formatting) on the sheet.
CLEAR CONTENTS
Range("A1:D10").ClearContentsRemove values but keep cell formatting intact.
CLOSE WORKBOOK
ActiveWorkbook.Close SaveChanges:=TrueClose the current file and save changes.
COLUMN WIDTH
Columns("B").ColumnWidth = 25Set a specific width for a column.
CONCATENATE STRINGS
fullText = str1 & " " & str2Combine two or more strings together.
COPY RANGE
Range("A1:A10").Copy Destination:=Range("B1")Copy data from one location to another.
COUNT SHEETS
sheetCount = Sheets.CountGet the total number of worksheets in the workbook.
CREATE FOLDER
MkDir "C:\MyFolder"Create a new directory on the hard drive.
CURRENT DATE
todayDate = DateStore the current system date in a variable.
CUSTOM MESSAGE BOX
MsgBox "Process Complete", vbInformation, "Done"Display a popup window with an info icon.
DELETE COLUMN
Columns("C").DeletePermanently remove a column from the sheet.
DELETE ROW
Rows(5).DeletePermanently remove a specific row.
DELETE SHEET
Application.DisplayAlerts = False
Sheets("Temp").Delete
Application.DisplayAlerts = TrueDelete a sheet without showing a warning prompt.
DISABLE EVENTS
Application.EnableEvents = FalseStop macros from triggering other macros.
DISABLE REFRESH
Application.ScreenUpdating = FalseHide Excel updates while macro runs (increases speed).
DO UNTIL LOOP
Do Until Cells(i, 1) = ""
i = i + 1
LoopRepeat code until a specific condition is met.
ERROR HANDLING
On Error Resume NextSkip lines that cause errors (use with caution).
EXIT SUB
If x = 0 Then Exit SubImmediately stop the macro if a condition is met.
FILE EXISTS CHECK
If Dir("C:\file.xlsx") <> "" ThenCheck if a file exists before opening it.
FIND AND REPLACE
Cells.Replace What:="Old", Replacement:="New"Replace text across the entire worksheet.
FIND LAST COLUMN
lastCol = Cells(1, Columns.Count).End(xlToLeft).ColumnGet index of the last used column in Row 1.
FIND LAST ROW
lastRow = Cells(Rows.Count, 1).End(xlUp).RowGet index of the last used row in Column A.
FIND STRING
Set found = Cells.Find(What:="SearchTerm")Search for specific data within the sheet.
FIXED STRING LENGTH
newStr = Left(str & Space(10), 10)Pad a string with spaces to a fixed length.
FONT COLOR
Range("A1").Font.Color = vbBlueChange the text color of a specific cell.
FONT SIZE
Range("A1").Font.Size = 14Adjust the font size of the text.
FOR EACH LOOP
For Each ws In Worksheets
Debug.Print ws.Name
Next wsIterate through every sheet in the workbook.
FOR LOOP
For i = 1 To 10
Cells(i, 1).Value = i
Next iStandard loop to repeat code a specific number of times.
FREEZE PANES
ActiveWindow.FreezePanes = TrueFreeze the rows/columns at the current selection.
GET ACTIVE CELL
addr = ActiveCell.AddressStore the address of the currently selected cell.
GET CELL VALUE
val = Range("A1").ValueRetrieve data from a cell and store it in a variable.
GET COMPUTER NAME
cName = Environ("COMPUTERNAME")Retrieve the PC name using environment variables.
GET SCREEN SIZE
w = Application.WidthGet the width of the Excel application window.
GET USERNAME
uName = Environ("USERNAME")Retrieve the Windows login name of the user.
GET WORKBOOK NAME
wbName = ThisWorkbook.NameReturn the filename of the macro-enabled workbook.
HIDE COLUMN
Columns("B").Hidden = TrueMake a specific column invisible.
HIDE ROW
Rows("5:10").Hidden = TrueMake specific rows invisible.
HIDE SHEET
Sheets("Sheet1").Visible = xlSheetHiddenHide a worksheet from the tab bar.
IF THEN ELSE
If x > 10 Then
msg = "High"
Else
msg = "Low"
End IfBasic conditional logic structure.
INPUT BOX
userInput = InputBox("Enter Name")Prompt the user to type in a value.
INSERT COLUMN
Columns("B").InsertAdd a new blank column to the left of Column B.
INSERT ROW
Rows(2).InsertAdd a new blank row above Row 2.
IS NUMERIC CHECK
If IsNumeric(Range("A1")) ThenVerify if a cell contains a number or text.
KILL FILE
Kill "C:\temp.txt"Delete a file from the hard drive via VBA.
LAST SAVED DATE
dt = ThisWorkbook.BuiltinDocumentProperties("Last Save Time")Retrieve the timestamp of the last file save.
LOWERCASE STRING
lowStr = LCase("EXCEL")Convert text to all lowercase letters.
MERGE CELLS
Range("A1:B2").MergeCombine multiple cells into one large cell.
MOVE SHEET
Sheets("Sheet1").Move After:=Sheets(3)Reorder worksheets within the workbook.
NAMED RANGE
ThisWorkbook.Names.Add Name:="MyData", RefersTo:="=Sheet1!$A$1:$B$10"Programmatically create a named range.
NEW WORKBOOK
Workbooks.AddCreate a brand new Excel file.
NUMBER FORMAT
Range("A1").NumberFormat = "$#,##0.00"Apply currency formatting to a cell.
OPEN WORKBOOK
Workbooks.Open "C:\data.xlsx"Open an existing Excel file from a path.
PASTE VALUES ONLY
Range("B1").PasteSpecial Paste:=xlPasteValuesPaste data without copying the formulas or formatting.
PROTECT SHEET
ActiveSheet.Protect Password:="123"Lock the sheet to prevent editing.
QUIT EXCEL
Application.QuitClose the entire Excel application.
REFRESH ALL
ActiveWorkbook.RefreshAllUpdate all PivotTables and Data Connections.
REMOVE DUPLICATES
Range("A1:C100").RemoveDuplicates Columns:=1, Header:=xlYesDelete duplicate rows based on a specific column.
RENAME SHEET
ActiveSheet.Name = "Report"Change the name of the current worksheet.
RESET STATUS BAR
Application.StatusBar = FalseReturn control of the status bar to Excel.
ROW HEIGHT
Rows(1).RowHeight = 30Set a specific height for a row.
SAVE AS PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\Doc.pdf"Export the current sheet as a PDF file.
SAVE WORKBOOK
ActiveWorkbook.SaveSave the current progress of the file.
SELECT RANGE
Range("A1:B10").SelectHighlight a specific block of cells.
SELECT TRIAL
Select Case Range("A1").Value
Case 1: MsgBox "One"
Case Else: MsgBox "Other"
End SelectAdvanced "If" logic for multiple scenarios.
SEND KEYS
Application.SendKeys "^p"Simulate keyboard shortcuts (e.g., Ctrl+P for Print).
SET CELL FORMULA
Range("B1").Formula = "=SUM(A1:A10)"Inject an Excel formula into a cell.
SET CELL VALUE
Range("A1").Value = "Hello World"Write text or numbers into a specific cell.
SHEET EXISTS
Function SheetExists(n As String) As BooleanBoilerplate to check if a sheet name already exists.
SORT DATA
Range("A1:B10").Sort Key1:=Range("A1"), Order1:=xlAscendingAlphabetize a range based on the first column.
STATUS BAR MESSAGE
Application.StatusBar = "Processing..."Show custom text in the bottom Excel bar.
STRING LENGTH
n = Len("Text")Count how many characters are in a string.
STRING REPLACE
newVal = Replace("A-B-C", "-", "")Swap parts of a string within a variable.
THICK BORDERS
Range("A1").BorderAround Weight:=xlThickAdd a heavy border around a selection.
TIME STAMP
Range("A1").Value = NowInsert the current date and time into a cell.
TIMER START
startTime = TimerCapture the current time to measure macro speed.
TOGGLE GRIDLINES
ActiveWindow.DisplayGridlines = FalseHide or show the cell gridlines.
TRIM SPACES
cleanStr = Trim(" Text ")Remove leading and trailing spaces from text.
UNHIDE ALL SHEETS
For Each ws In Worksheets: ws.Visible = True: Next wsLoop through and make every sheet visible.
UNPROTECT SHEET
ActiveSheet.Unprotect Password:="123"Unlock a sheet using the required password.
UPPERCASE STRING
upStr = UCase("excel")Convert text to all capital letters.
USER INPUT DIALOG
Set r = Application.InputBox("Select Range", Type:=8)Ask the user to physically click/select a range.
VAL CONVERSION
num = Val("123")Convert a string number into a real numeric type.
VARIABLE DECLARE
Dim myVar As StringProperly define a variable type for memory efficiency.
VLOOKUP IN VBA
res = Application.VLookup("Key", Range("A1:B10"), 2, False)Run an Excel VLookup within your macro code.
WAIT / SLEEP
Application.Wait (Now + TimeValue("0:00:05"))Pause macro execution for 5 seconds.
WHILE LOOP
While x < 10: x = x + 1: WendExecute code as long as a condition is true.
WORKBOOK PATH
p = ThisWorkbook.PathGet the folder path where the current file is saved.
WORKSHEET FUNCTION
res = Application.WorksheetFunction.Max(Range("A:A"))Access standard Excel functions through VBA.
WRAP TEXT
Range("A1").WrapText = TrueEnable text wrapping within a cell.
ZOOM LEVEL
ActiveWindow.Zoom = 85Set the zoom percentage of the current window.
ABORT MERGE
git merge --abortStop the merge process and return to the state before the merge started.
ABORT REBASE
git rebase --abortStop an in-progress rebase and return the branch to its original state.
ADD ALL CHANGES
git add .Stage all new, modified, and deleted files in the current directory.
ADD BY EXTENSION
git add *.txtStage all files with a specific extension.
ADD REMOTE
git remote add origin [url]Link your local repository to a remote server.
ADD SPECIFIC FILE
git add filename.txtStage a single file for the next commit.
AMEND COMMIT
git commit --amend -m "new message"Replace the last commit with a new message or staged changes.
APPLY STASH
git stash applyBring back changes from the stash without removing them from the stash list.
BLAME FILE
git blame filename.txtSee who changed which line of a file and when.
BRANCH LIST
git branchList all local branches in the current repository.
BRANCH LIST REMOTE
git branch -rList all branches currently tracked on the remote server.
CHERRY PICK
git cherry-pick [commit-hash]Apply the changes from a specific commit to your current branch.
CHECKOUT BRANCH
git checkout [branch-name]Switch from your current branch to another branch.
CHECKOUT COMMIT
git checkout [hash]View the state of the repository at a specific point in time.
CHECKOUT FILE
git checkout -- filename.txtDiscard local changes in a specific file and revert to the last commit.
CLEAN DRY RUN
git clean -nPreview which untracked files will be deleted.
CLEAN UNTRACKED
git clean -fForcefully delete all untracked files from the working directory.
CLONE REPO
git clone [url]Download an existing repository from a remote source.
CLONE SPECIFIC BRANCH
git clone -b [name] [url]Clone only a single specific branch from a repository.
COMMIT CHANGES
git commit -m "message"Record staged changes to the repository history.
COMMIT STAGED ONLY
git commit -a -m "message"Automatically stage and commit all modified files (skips new files).
CONFIG EMAIL
git config --global user.email "you@example.com"Set the email address associated with your commits.
CONFIG LIST
git config --listShow all current configuration settings for Git.
CONFIG NAME
git config --global user.name "Your Name"Set the username associated with your commits.
CREATE BRANCH
git branch [branch-name]Create a new branch pointer at the current commit.
CREATE AND SWITCH
git checkout -b [branch-name]Create a new branch and switch to it immediately.
DELETE BRANCH
git branch -d [name]Delete a branch that has already been merged.
DELETE BRANCH FORCE
git branch -D [name]Delete a branch regardless of its merge status.
DELETE REMOTE BRANCH
git push origin --delete [name]Remove a branch from the remote server.
DELETE REMOTE TAG
git push origin --delete [tagname]Remove a specific tag from the remote server.
DELETE TAG
git tag -d [tagname]Remove a specific tag from your local repository.
DESCRIBE COMMIT
git describe --tagsFind the most recent tag reachable from a commit.
DIFF BRANCHES
git diff [branch1]..[branch2]Compare the differences between two branches.
DIFF STAGED
git diff --stagedShow changes between the staging area and the last commit.
DIFF UNSTAGED
git diffShow changes in the working directory that are not yet staged.
DROP STASH
git stash dropDiscard the most recent set of stashed changes.
FETCH REMOTE
git fetch originDownload history from the remote without merging it.
FETCH ALL REMOTES
git fetch --allRetrieve updates from all configured remote repositories.
FORCED PUSH
git push origin [branch] --forceOverwrite remote history with your local history (use with caution).
GREP REPO
git grep "text"Search for a string in the entire repository history.
IGNORE FILE
echo "node_modules/" >> .gitignorePrevent specific files or folders from being tracked.
INIT REPO
git initInitialize a brand new Git repository in the current folder.
LIST REMOTES
git remote -vList all remote connections and their URLs.
LIST STASHES
git stash listShow all sets of changes currently saved in the stash.
LIST TAGS
git tagList all tags (versions) in the repository.
LOG GRAPH
git log --graph --oneline --allVisualize the branch and merge history in the console.
LOG ONELINE
git log --onelineView commit history in a condensed, single-line format.
LOG STATS
git log --statShow which files were changed and how many lines were added/deleted.
MERGE BRANCH
git merge [branch-name]Join the history of another branch into your current branch.
MOVE FILE
git mv [old-path] [new-path]Rename or move a file and stage the change automatically.
PATCH ADD
git add -pReview and stage changes piece by piece (hunks).
POP STASH
git stash popRecover stashed changes and remove them from the stash list.
PULL CHANGES
git pull origin [branch]Fetch from remote and immediately merge into the current branch.
PULL REBASE
git pull --rebase origin [branch]Fetch changes and re-apply your local commits on top of them.
PUSH BRANCH
git push origin [branch]Upload local commits to a specific remote branch.
PUSH TAGS
git push --tagsUpload all local tags to the remote repository.
REBASE BRANCH
git rebase [base-branch]Move your current branch's commits to a new starting point.
REBASE INTERACTIVE
git rebase -i HEAD~5Modify, squash, or delete commits in the last 5 entries.
REF LOG
git reflogShow a log of all changes made to the local HEAD (useful for recovery).
REMOVE FILE
git rm filename.txtRemove a file from the working directory and the index.
REMOVE FROM INDEX
git rm --cached filename.txtStop tracking a file but keep it in the local folder.
REMOVE REMOTE
git remote remove originDisconnect the local repository from a remote server.
RENAME BRANCH
git branch -m [new-name]Change the name of the current branch.
RESET HARD
git reset --hard HEADDiscard all local changes and match the last commit exactly.
RESET SOFT
git reset --soft HEAD~1Undo the last commit but keep changes in the staging area.
RESTORE FILE
git restore [filename]Revert a file to its state in the last commit.
REVERT COMMIT
git revert [commit-hash]Create a new commit that undoes the changes of a previous one.
REV-PARSE HEAD
git rev-parse HEADShow the full SHA-1 hash of the current commit.
SET UPSTREAM
git push -u origin [branch]Push and set the default remote tracking branch.
SHOW COMMIT
git show [commit-hash]Display the details and file changes of a specific commit.
SHOW REMOTE
git remote show originView detailed information about a remote and its branches.
STASH CHANGES
git stashTemporarily save modified, tracked files to a clean state.
STASH INCLUDE UNTRACKED
git stash -uStash changes including new files that aren't tracked yet.
STASH MESSAGE
git stash save "message"Save a stash with a specific label for easy identification.
STATUS
git statusShow the state of the working directory and staging area.
STATUS SHORT
git status -sView a simplified, compact version of the repository status.
SUBMODULE ADD
git submodule add [url]Add a different repository as a subdirectory of this one.
SUBMODULE UPDATE
git submodule update --initInitialize and update all submodules in the repo.
TAG COMMIT
git tag [tagname]Create a simple pointer to a specific commit (versioning).
TAG MESSAGE
git tag -a [v1.0] -m "message"Create an annotated tag with a descriptive message.
UNDO COMMIT
git reset --soft HEAD~1Roll back the last commit but keep changes staged.
UNDO STAGING
git restore --staged [filename]Unstage a file but keep the changes in the working directory.
UNSET CONFIG
git config --unset [key]Remove a specific configuration setting.
UPDATE REMOTE URL
git remote set-url origin [new-url]Change the URL of an existing remote connection.
VERIFY REPO
git fsckCheck the integrity of the Git database and objects.
VIEW BRANCH LOGS
git log [branch1]..[branch2]See commits that exist in branch2 but not in branch1.
VISUALIZE HISTORY
gitkLaunch a built-in graphical interface to browse the repo.
WHATCHANGED
git whatchangedView commit logs with the list of files impacted.
WORKTREE ADD
git worktree add ../new-dir [branch]Check out a branch into a separate physical directory.
WORKTREE LIST
git worktree listShow all linked working trees for the current repository.