Command | Example | Description |
---|---|---|
<!DOCTYPE html> | <!DOCTYPE html> | Declares the document type. |
<html> | <html lang='en'> | Root element of an HTML document. |
<head> | <head> ... </head> | Contains metadata, links to scripts, and styles. |
<body> | <body> ... </body> | Holds the content of the HTML document. |
<div> | <div class='container'> ... </div> | Defines a section or division in the document. |
<span> | <span class='highlight'> ... </span> | Inline container for text or other elements. |
<h1> to <h6> | <h1>Main Title</h1> | Defines HTML headings, from h1 (highest) to h6 (lowest). |
<p> | <p>This is a paragraph.</p> | Defines a paragraph. |
<a> | <a href='https://example.com'>Link</a> | Defines a hyperlink. |
<img> | <img src='image.jpg' alt='Description'> | Embeds an image in the document. |
<ul> and <ol> | <ul><li>Item 1</li><li>Item 2</li></ul> | Defines unordered (ul) and ordered (ol) lists. |
<li> | <li>List item</li> | Defines a list item. |
<table> | <table><tr><td>Cell</td></tr></table> | Defines a table. |
<tr>, <td>, <th> | <tr><th>Header</th><td>Data</td></tr> | Defines table rows (tr), data cells (td), and header cells (th). |
<form> | <form action='/submit'><input type='text'></form> | Defines an HTML form for user input. |
<input> | <input type='text' name='username'> | Defines an input control. |
<button> | <button type='submit'>Submit</button> | Defines a clickable button. |
<label> | <label for='username'>Username:</label> | Defines a label for an input element. |
<select> and <option> | <select><option value='1'>Option 1</option></select> | Defines a dropdown list (select) and its options (option). |
<textarea> | <textarea rows='4' cols='50'></textarea> | Defines a multi-line text input control. |
<iframe> | <iframe src='https://example.com'></iframe> | Embeds another document within the current document. |
<link> | <link rel='stylesheet' href='styles.css'> | Defines the relationship between the current document and an external resource (most used to link stylesheets). |
<meta> | <meta charset='UTF-8'> | Defines metadata about the HTML document, such as character set, author, and viewport settings. |
<script> | <script src='script.js'></script> | Defines a client-side script, such as JavaScript. |
<style> | <style> body { background-color: lightblue; } </style> | Defines internal CSS styles. |
<header> | <header> ... </header> | Defines a header for a document or section. |
<footer> | <footer> ... </footer> | Defines a footer for a document or section. |
<nav> | <nav> ... </nav> | Defines navigation links. |
<article> | <article> ... </article> | Defines an independent, self-contained content piece. |
<section> | <section> ... </section> | Defines a section in a document. |
<aside> | <aside> ... </aside> | Defines content aside from the main content (like sidebars). |
<figure> and <figcaption> | <figure><img src='image.jpg'><figcaption>Description</figcaption></figure> | Defines self-contained content, like images with captions. |
<blockquote> | <blockquote cite='https://example.com'>Quote</blockquote> | Defines a section that is quoted from another source. |
<cite> | <cite>Citation</cite> | Defines the title of a work being cited. |
<time> | <time datetime='2023-10-01'>October 1, 2023</time> | Defines a specific time (or range of time). |
<mark> | <mark>This is highlighted text.</mark> | Defines text that has been highlighted or marked for reference. |
Command | Example | Description |
---|---|---|
color | color: #333; | Sets the text color of an element. |
background-color | background-color: #fff; | Sets the background color of an element. |
margin | margin: 10px; | Defines the outer spacing of an element. |
padding | padding: 10px; | Defines the inner spacing of an element. |
display | display: flex; | Specifies the display behavior of an element (e.g., block, inline, flex, grid). |
position | position: absolute; | Sets the positioning method of an element (e.g., static, relative, absolute, fixed). |
top | top: 10px; | Specifies the top position of a positioned element. |
left | left: 10px; | Specifies the left position of a positioned element. |
width | width: 100px; | Sets the width of an element. |
height | height: 100px; | Sets the height of an element. |
font-size | font-size: 16px; | Sets the font size of text within an element. |
font-family | font-family: 'Arial', sans-serif; | Specifies the font family for text within an element. |
text-align | text-align: center; | Aligns text within an element (e.g., left, right, center, justify). |
border | border: 1px solid #000; | Sets the border properties of an element. |
border-radius | border-radius: 5px; | Rounds the corners of an element's border. |
box-shadow | box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3); | Adds a shadow effect to an element's box. |
opacity | opacity: 0.5; | Sets the transparency level of an element. |
overflow | overflow: hidden; | Specifies how to handle content that overflows an element's box (e.g., visible, hidden, scroll). |
z-index | z-index: 10; | Sets the stack order of positioned elements. |
@media | @media (max-width: 600px) { ... } | Defines responsive styles for different screen sizes or conditions. |
@keyframes | @keyframes myAnimation { from { opacity: 0; } to { opacity: 1; } } | Defines keyframes for CSS animations. |
@font-face | @font-face { font-family: 'MyFont'; src: url('myfont.woff2'); } | Defines custom fonts to be used in CSS. |
transition | transition: all 0.3s ease; | Specifies the transition effect for property changes. |
transform | transform: rotate(45deg); | Applies a 2D or 3D transformation to an element. |
flex | flex: 1; | Defines how a flex item will grow or shrink within a flex container. |
grid-template-columns | grid-template-columns: repeat(3, 1fr); | Defines the columns of a grid layout. |
grid-template-rows | grid-template-rows: auto 1fr; | Defines the rows of a grid layout. |
:hover | .button:hover { background-color: #f00; } | Styles an element when it is hovered over by the mouse. |
:focus | .input:focus { border-color: #00f; } | Styles an element when it is focused (e.g., input field). |
:active | .button:active { background-color: #0f0; } | Styles an element when it is being activated (e.g., clicked). |
:before | .element:before { content: 'Prefix'; } | Inserts content before an element. |
:after | .element:after { content: 'Suffix'; } | Inserts content after an element. |
::placeholder | .input::placeholder { color: #999; } | Styles the placeholder text of an input field. |
list-style-type | list-style-type: disc; | Sets the type of list item marker (e.g., disc, circle, square). |
text-decoration | text-decoration: underline; | Adds decoration to text (e.g., underline, overline, line-through). |
cursor | cursor: pointer; | Sets the type of cursor to be displayed when hovering over an element. |
white-space | white-space: nowrap; | Controls how whitespace is handled within an element (e.g., normal, nowrap, pre). |
text-transform | text-transform: uppercase; | Controls the capitalization of text (e.g., uppercase, lowercase, capitalize). |
letter-spacing | letter-spacing: 2px; | Sets the spacing between characters in text. |
line-height | line-height: 1.5; | Sets the height of a line box. |
background-image | background-image: url('image.jpg'); | Sets a background image for an element. |
background-size | background-size: cover; | Specifies the size of a background image. |
@import | @import 'styles.css'; | Imports styles from another CSS file. |
content | content: 'Hello'; | Inserts content into an element (used with :before and :after). |
filter | filter: grayscale(100%); | Applies graphical effects like blur or grayscale to an element. |
object-fit | object-fit: cover; | Specifies how an element's content should be resized to fit its container. |
object-position | object-position: center; | Sets the position of an element's content within its container. |
transition-delay | transition-delay: 0.5s; | Specifies the delay before a transition effect starts. |
transition-property | transition-property: opacity; | Specifies the CSS properties to which a transition effect is applied. |
transition-duration | transition-duration: 1s; | Specifies the duration of a transition effect. |
transition-timing-function | transition-timing-function: ease-in-out; | Specifies the timing function for a transition effect. |
align-items | align-items: center; | Aligns flex items along the cross axis in a flex container. |
justify-content | justify-content: space-between; | Justifies flex items along the main axis in a flex container. |
align-self | align-self: flex-start; | Overrides the align-items property for a specific flex item. |
@supports | @supports (display: grid) { ... } | Defines styles that apply only if a certain CSS feature is supported. |
grid-gap | grid-gap: 10px; | Sets the gap between grid items in a grid layout. |
grid-area | grid-area: header; | Defines a grid item's area within a grid layout. |
grid-column | grid-column: 1 / 3; | Specifies the start and end positions of a grid item in columns. |
grid-row | grid-row: 1 / 2; | Specifies the start and end positions of a grid item in rows. |
grid-auto-flow | grid-auto-flow: row; | Specifies how grid items are placed in a grid layout. |
grid-template-areas | grid-template-areas: 'header header' 'sidebar content'; | Defines named areas within a grid layout. |
scroll-behavior | scroll-behavior: smooth; | Specifies the scrolling behavior for a container. |
scroll-snap-type | scroll-snap-type: x mandatory; | Defines the snapping behavior for scrollable containers. |
scroll-snap-align | scroll-snap-align: start; | Specifies the alignment of scroll snap points. |
scroll-padding | scroll-padding: 10px; | Sets the padding for scroll snap containers. |
scroll-margin | scroll-margin: 10px; | Sets the margin for scroll snap elements. |
scroll-margin-top | scroll-margin-top: 10px; | Sets the top margin for scroll snap elements. |
scroll-margin-bottom | scroll-margin-bottom: 10px; | Sets the bottom margin for scroll snap elements. |
scroll-margin-left | scroll-margin-left: 10px; | Sets the left margin for scroll snap elements. |
scroll-margin-right | scroll-margin-right: 10px; | Sets the right margin for scroll snap elements. |
scroll-padding-top | scroll-padding-top: 10px; | Sets the top padding for scroll snap containers. |
scroll-padding-bottom | scroll-padding-bottom: 10px; | Sets the bottom padding for scroll snap containers. |
scroll-padding-left | scroll-padding-left: 10px; | Sets the left padding for scroll snap containers. |
scroll-padding-right | scroll-padding-right: 10px; | Sets the right padding for scroll snap containers. |
scroll-snap-stop | scroll-snap-stop: always; | Specifies whether scroll snap points should stop scrolling. |
scroll-snap-type-x | scroll-snap-type-x: mandatory; | Defines the snapping behavior for horizontal scrollable containers. |
scroll-snap-type-y | scroll-snap-type-y: mandatory; | Defines the snapping behavior for vertical scrollable containers. |
scroll-snap-align-x | scroll-snap-align-x: start; | Specifies the alignment of scroll snap points horizontally. |
scroll-snap-align-y | scroll-snap-align-y: start; | Specifies the alignment of scroll snap points vertically. |
scroll-snap-margin | scroll-snap-margin: 10px; | Sets the margin for scroll snap elements. |
scroll-snap-padding | scroll-snap-padding: 10px; | Sets the padding for scroll snap containers. |
scroll-snap-margin-top | scroll-snap-margin-top: 10px; | Sets the top margin for scroll snap elements. |
scroll-snap-margin-bottom | scroll-snap-margin-bottom: 10px; | Sets the bottom margin for scroll snap elements. |
scroll-snap-margin-left | scroll-snap-margin-left: 10px; | Sets the left margin for scroll snap elements. |
scroll-snap-margin-right | scroll-snap-margin-right: 10px; | Sets the right margin for scroll snap elements. |
Command | Example | Description |
---|---|---|
git status | git status | Displays the state of the working directory. |
git init | git init | Initializes a new Git repository. |
git clone | git clone https://github.com/user/repo.git | Clones a repository into a new directory. |
git add | git add file.txt | Adds file contents to the index (staging area). |
git commit | git commit -m 'Commit message' | Records changes to the repository. |
git push | git push origin master | Updates remote refs along with associated objects. |
git pull | git pull | Fetches from and integrates with another repository or branch. |
git fetch | git fetch origin | Downloads objects and refs from another repository. |
git branch | git branch | Lists, creates, or deletes branches. |
git checkout | git checkout branch_name | Switches branches or restores working tree files. |
git merge | git merge feature_branch | Joins two or more development histories together. |
git rebase | git rebase master | Reapplies commits on top of another base tip. |
git log | git log | Shows the commit logs. |
git diff | git diff | Shows changes between commits, commit and working tree, etc. |
git remote | git remote -v | Manages set of tracked repositories. |
git reset | git reset --soft HEAD~1 | Resets current HEAD to the specified state. |
git revert | git revert commit_hash | Creates a new commit that undoes changes from a previous commit. |
git stash | git stash | Temporarily shelves changes in the working directory. |
git tag | git tag v1.0 | Creates, lists, or deletes tags. |
git cherry-pick | git cherry-pick commit_hash | Applies changes introduced by existing commits. |
git show | git show commit_hash | Displays various types of objects. |
git blame | git blame file.txt | Shows what revision and author last modified each line of a file. |
git config | git config --global user.name 'Your Name' | Gets and sets repository or global options. |
git clean | git clean -f | Removes untracked files from the working tree. |
git archive | git archive --format=zip -o repo.zip master | Creates an archive of files from a named tree. |
git bisect | git bisect start | Uses binary search to find the commit that introduced a bug. |
git reflog | git reflog | Shows the history of HEAD and branch references. |
git shortlog | git shortlog -s -n | Summarizes git log output. |
git submodule | git submodule add repository_url | Initializes, updates, or inspects submodules. |
git pull --rebase | git pull --rebase | Fetches and rebases changes. |
git merge --squash | git merge --squash feature_branch | Combines changes into a single commit without a merge commit. |
git commit --amend | git commit --amend | Modifies the last commit. |
git remote add | git remote add origin https://github.com/user/repo.git | Adds a new remote repository. |
git rm | git rm file.txt | Removes files from the working tree and the index. |
git mv | git mv oldname.txt newname.txt | Moves or renames a file or directory. |
git fetch --all | git fetch --all | Fetches updates from all remotes. |
git push --force | git push --force origin master | Forces a push to update the remote repository. |
git reset --hard | git reset --hard HEAD~1 | Resets the working tree and index to a previous state. |
git log --oneline | git log --oneline | Shows a compact summary of commit logs. |
git log --graph | git log --graph --all | Displays commit history as a graph. |
git diff --staged | git diff --staged | Shows differences between the index and the last commit. |
git rebase -i | git rebase -i HEAD~3 | Performs an interactive rebase to edit commit history. |
git stash pop | git stash pop | Applies stashed changes and removes the stash. |
git stash apply | git stash apply | Applies stashed changes without removing the stash. |
git stash list | git stash list | Lists all stashed changes. |
git tag -a | git tag -a v1.0 -m 'Version 1.0' | Creates an annotated tag. |
git tag -d | git tag -d v1.0 | Deletes a tag. |
git remote remove | git remote remove origin | Removes a remote repository. |
git cherry | git cherry -v | Identifies commits not present in the upstream branch. |
git bundle | git bundle create repo.bundle --all | Creates a bundle file of repository objects. |
git commit -v | git commit -v | Commits with verbose output. |
git config --global user.name | git config --global user.name 'Your Name' | Sets the global Git username. |
git config --global user.email | git config --global user.email 'you@example.com' | Sets the global Git email address. |
git init --bare | git init --bare repo.git | Creates a bare Git repository (without a working directory). |
git push origin --delete | git push origin --delete branch_name | Deletes a branch on the remote repository. |
git fetch origin | git fetch origin | Fetches updates from the 'origin' remote. |
git remote show origin | git remote show origin | Displays detailed information about the remote repository. |
git diff HEAD~1 | git diff HEAD~1 | Shows the changes between the last commit and its predecessor. |
git describe | git describe --tags | Describes a commit using the nearest tag. |
git gc | git gc | Cleans up unnecessary files and optimizes the repository. |
git fsck | git fsck | Verifies the connectivity and validity of the objects in the repository. |
git worktree | git worktree add ../new_worktree branch_name | Manages multiple working trees attached to the same repository. |
git apply | git apply patchfile.patch | Applies a patch file to the repository. |
git merge --no-ff | git merge --no-ff feature_branch | Merges a branch and creates a merge commit even if a fast-forward is possible. |
git commit -m | git commit -m 'Commit message' | Commits staged changes with a message. |
git pull origin master | git pull origin master | Pulls updates from the master branch of the origin remote. |
git rebase master | git rebase master | Rebases the current branch onto the master branch. |
git log --stat | git log --stat | Shows commit logs with file change statistics. |
git diff --cached | git diff --cached | Shows changes between the index and the last commit. |
git add -p | git add -p | Interactively stages changes in patches. |
git checkout -b | git checkout -b new_branch | Creates a new branch and switches to it. |
git branch -d | git branch -d branch_name | Deletes a branch that has been fully merged. |
git branch -D | git branch -D branch_name | Force-deletes a branch. |
git branch -m | git branch -m old_branch new_branch | Renames a branch. |
git remote update | git remote update | Fetches updates for all remotes. |
git push origin master | git push origin master | Pushes the master branch to the origin remote. |
git pull --all | git pull --all | Pulls updates from all remotes. |
git merge --abort | git merge --abort | Aborts the current merge process. |
git rebase --abort | git rebase --abort | Aborts an ongoing rebase process. |
git commit --allow-empty | git commit --allow-empty -m 'Empty commit' | Creates an empty commit. |
git commit --fixup | git commit --fixup commit_hash | Creates a fixup commit for the specified commit. |
git commit --squash | git commit --squash commit_hash | Creates a squash commit for the specified commit. |
git stash save | git stash save 'Work in progress' | Saves the current changes to the stash. |
git stash drop | git stash drop stash@{0} | Drops a specific stash entry. |
git stash clear | git stash clear | Clears all stash entries. |
git rebase --continue | git rebase --continue | Continues the rebase process after resolving conflicts. |
git checkout -- | git checkout -- file.txt | Discards changes in the working directory for the specified file. |
git update-index | git update-index --assume-unchanged file.txt | Updates the index with specified file status. |
git ls-files | git ls-files | Lists files in the index. |
git grep | git grep 'search_term' | Searches for a term in tracked files. |
git merge-base | git merge-base branch1 branch2 | Finds the best common ancestor of two branches. |
git remote prune | git remote prune origin | Removes stale references from the remote. |
git log --decorate | git log --decorate | Shows commit logs with reference names. |
git log --all | git log --all | Shows the commit logs for all branches. |
git remote rename | git remote rename oldname newname | Renames a remote repository. |
git rev-parse | git rev-parse HEAD | Parses and resolves a Git revision identifier. |
git reflog expire | git reflog expire --expire=now --all | Expires older reflog entries. |
git reflog show | git reflog show | Displays the reflog. |
git diff-tree | git diff-tree -p commit_hash | Shows differences between tree objects. |
git archive --format=zip | git archive --format=zip -o repo.zip HEAD | Creates a ZIP archive of the repository. |
git cherry-pick --no-commit | git cherry-pick --no-commit commit_hash | Applies changes from a commit without automatically committing. |
Command | Example | Description |
---|---|---|
print() | print('Hello, World!') | Outputs text to console. |
len() | len([1, 2, 3]) | Returns the number of items in an object. |
range() | for i in range(5): print(i) | Generates a sequence of numbers. |
input() | name = input('Enter your name: ') | Reads a line of input from the user. |
type() | type(123) | Returns the type of an object. |
str() | str(123) | Converts a value to a string. |
int() | int('123') | Converts a value to an integer. |
float() | float('3.14') | Converts a value to a float. |
list() | list('abc') | Creates a list from an iterable. |
dict() | dict(a=1, b=2) | Creates a dictionary. |
set() | set([1, 2, 3]) | Creates a set. |
tuple() | tuple([1, 2, 3]) | Creates a tuple. |
open() | open('file.txt', 'r') | Opens a file. |
with open() as | with open('file.txt', 'r') as f: pass | Context manager for file operations. |
def function | def my_function(): pass | Defines a function. |
lambda | lambda x: x * 2 | Creates an anonymous function. |
map() | list(map(lambda x: x*2, [1,2,3])) | Applies a function to each item in an iterable. |
filter() | list(filter(lambda x: x > 1, [0,1,2,3])) | Filters items in an iterable based on a condition. |
reduce() | from functools import reduce; reduce(lambda x, y: x+y, [1,2,3]) | Performs a rolling computation on an iterable (requires functools). |
enumerate() | for i, val in enumerate(['a','b']): print(i, val) | Iterates with an automatic counter. |
zip() | list(zip([1,2], ['a','b'])) | Aggregates elements from multiple iterables. |
sorted() | sorted([3,1,2]) | Returns a new sorted list from the items in an iterable. |
reversed() | list(reversed([1,2,3])) | Returns an iterator that accesses the given sequence in reverse order. |
sum() | sum([1,2,3]) | Sums the items of an iterable. |
max() | max([1,2,3]) | Returns the maximum value in an iterable. |
min() | min([1,2,3]) | Returns the minimum value in an iterable. |
abs() | abs(-5) | Returns the absolute value of a number. |
round() | round(3.14159, 2) | Rounds a number to a given precision. |
format() | format(1234, ',') | Formats a value using a format specifier. |
f-string | f'Hello, {name}' | Creates a formatted string literal. |
join() | ','.join(['a','b','c']) | Joins elements of an iterable into a single string. |
split() | 'a,b,c'.split(',') | Splits a string into a list based on a delimiter. |
replace() | 'hello'.replace('l', 'L') | Replaces specified characters or substrings in a string. |
strip() | ' hello '.strip() | Removes leading and trailing whitespace from a string. |
list comprehension | [x*2 for x in range(5)] | Creates a new list by applying an expression to each item in an iterable. |
generator expression | (x*2 for x in range(5)) | Creates a generator for lazy evaluation. |
yield | def gen(): yield 1 | Yields a value from a generator function. |
next() | next(iter([1,2,3])) | Retrieves the next item from an iterator. |
iter() | iter([1,2,3]) | Returns an iterator for an object. |
isinstance() | isinstance(123, int) | Checks whether an object is an instance of a class or a tuple of classes. |
issubclass() | issubclass(bool, int) | Checks whether a class is a subclass of another. |
super() | super().__init__() | Calls a method from a parent class. |
class definition | class MyClass: pass | Defines a new class. |
__init__ method | def __init__(self, value): self.value = value | Initializes a class instance (constructor). |
__str__ method | def __str__(self): return str(self.value) | Returns a string representation of an object. |
property() | x = property(fget, fset) | Creates a managed attribute. |
decorator | @my_decorator def func(): pass | Modifies or enhances a function or method. |
@staticmethod | class MyClass: @staticmethod def my_static(): pass | Defines a static method that does not receive the instance or class as an argument. |
@classmethod | class MyClass: @classmethod def my_class(cls): pass | Defines a method that receives the class as the first argument. |
try/except | try: 1/0 except ZeroDivisionError: pass | Handles exceptions during execution. |
try/except/else/finally | try: x = 1/1 except Exception: pass else: print('Success') finally: print('Done') | Provides a complete exception handling structure. |
raise | raise ValueError('Invalid input') | Raises an exception. |
assert | assert 2 + 2 == 4 | Tests if a condition is true and raises an error if not. |
import | import math | Imports a module. |
from ... import | from math import pi | Imports specific attributes or functions from a module. |
as keyword | import numpy as np | Creates an alias for a module or object. |
dir() | dir(math) | Lists the attributes and methods of an object. |
help() | help(print) | Displays the documentation for an object. |
id() | id(123) | Returns the unique identifier of an object. |
hasattr() | hasattr(obj, 'attr') | Checks if an object has a given attribute. |
getattr() | getattr(obj, 'attr', None) | Retrieves the value of an attribute from an object. |
setattr() | setattr(obj, 'attr', 10) | Sets the value of an attribute on an object. |
delattr() | delattr(obj, 'attr') | Deletes an attribute from an object. |
globals() | globals() | Returns a dictionary representing the current global symbol table. |
locals() | locals() | Returns a dictionary representing the current local symbol table. |
exec() | exec('print("Hello")') | Executes dynamically created Python code. |
eval() | eval('1 + 2') | Evaluates a Python expression from a string. |
compile() | compile('print(123)', '<string>', 'exec') | Compiles source code into a code object. |
lambda advanced | lambda x, y: x if x > y else y | Demonstrates a lambda with a conditional expression. |
recursion | def factorial(n): return 1 if n==0 else n*factorial(n-1) | Implements a recursive function. |
list slicing | my_list[1:3] | Extracts a portion of a list using slicing. |
dictionary comprehension | {x: x*x for x in range(5)} | Creates a dictionary using comprehension syntax. |
set comprehension | {x for x in range(5)} | Creates a set using comprehension syntax. |
exception chaining | raise ValueError('error') from None | Chains exceptions to maintain the original traceback. |
with contextlib | from contextlib import contextmanager @contextmanager def my_context(): yield | Uses contextlib to create a custom context manager. |
file reading | with open('file.txt', 'r') as f: data = f.read() | Reads data from a file. |
file writing | with open('file.txt', 'w') as f: f.write('Hello') | Writes data to a file. |
json.load() | import json json.load(f) | Loads JSON data from a file. |
json.dump() | import json json.dump(data, f) | Serializes data as JSON and writes it to a file. |
regex re.search() | import re re.search('pattern', 'string') | Searches a string for a pattern match. |
regex re.match() | import re re.match('pattern', 'string') | Matches a pattern at the beginning of a string. |
regex re.findall() | import re re.findall('pattern', 'string') | Finds all non-overlapping matches of a pattern in a string. |
re.sub() | import re re.sub('a', 'b', 'apple') | Substitutes occurrences of a pattern within a string. |
datetime.now() | from datetime import datetime datetime.now() | Returns the current date and time. |
time.sleep() | import time time.sleep(1) | Pauses execution for a specified number of seconds. |
os.path.join() | import os os.path.join('folder', 'file.txt') | Joins one or more path components into a single path. |
os.listdir() | import os os.listdir('.') | Lists the files in a directory. |
sys.argv | import sys print(sys.argv) | Provides access to command-line arguments. |
argparse.ArgumentParser | import argparse parser = argparse.ArgumentParser() | Parses command-line arguments. |
logging.basicConfig | import logging logging.basicConfig(level=logging.INFO) | Configures basic logging settings. |
logging.debug | import logging logging.debug('Debug message') | Logs a message with level DEBUG. |
logging.info | import logging logging.info('Info message') | Logs a message with level INFO. |
logging.warning | import logging logging.warning('Warning message') | Logs a message with level WARNING. |
logging.error | import logging logging.error('Error message') | Logs a message with level ERROR. |
logging.critical | import logging logging.critical('Critical error') | Logs a message with level CRITICAL. |
threading.Thread | import threading t = threading.Thread(target=func) | Creates a new thread to run a function concurrently. |
multiprocessing.Process | import multiprocessing p = multiprocessing.Process(target=func) | Creates a new process to run a function concurrently. |
asyncio.run() | import asyncio asyncio.run(main()) | Runs an asynchronous function using the asyncio event loop. |
await keyword | await async_func() | Waits for an asynchronous function to complete. |
async def | async def async_func(): pass | Defines an asynchronous function. |
__main__ check | if __name__ == '__main__': main() | Ensures code runs only when the script is executed directly. |
Command | Example | Description |
---|---|---|
console.log() | console.log('Hello, World!'); | Outputs a message to the web console. |
document.getElementById() | document.getElementById('myId'); | Selects an element by its ID. |
setTimeout() | setTimeout(() => { alert('Hello'); }, 1000); | Executes a function after a specified delay. |
addEventListener() | element.addEventListener('click', function() { /* code */ }); | Attaches an event listener to an element. |
fetch() | fetch('https://api.example.com/data').then(response => response.json()); | Makes a network request to retrieve data from a server. |
JSON.parse() | JSON.parse('{"key":"value"}'); | Parses a JSON string and returns a JavaScript object. |
JSON.stringify() | JSON.stringify({ key: 'value' }); | Converts a JavaScript object to a JSON string. |
Array.map() | [1, 2, 3].map(x => x * 2); | Creates a new array with the results of calling a provided function on every element in the calling array. |
Array.filter() | [1, 2, 3].filter(x => x > 1); | Creates a new array with all elements that pass the test implemented by the provided function. |
Array.reduce() | [1, 2, 3].reduce((acc, x) => acc + x, 0); | Executes a reducer function on each element of the array, resulting in a single output value. |
Promise.then() | Promise.resolve(1).then(value => value + 1); | Adds fulfillment and rejection handlers to the promise and returns a new promise resolving to the return value of the called handler. |
async/await | (async () => { const data = await fetch('https://api.example.com/data'); })(); | `async` functions enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains. |
$() (jQuery) | $('#myId').hide(); | `$()` is a shorthand for jQuery's `jQuery()` function. It selects elements and can perform various operations on them. |
.classList.add() | $('element').classList.add('new-class'); | `classList.add()` adds one or more classnames to an element's class attribute. |
.classList.remove() | $('element').classList.remove('old-class'); | `classList.remove()` removes one or more class names from an element's class attribute. |
.classList.toggle() | $('element').classList.toggle('active'); | `classList.toggle()` toggles a class name on an element's class attribute. |
.classList.contains() | $('element').classList.contains('active'); | `classList.contains()` checks if an element has a specific class name. |
.querySelector() | $('selector').querySelector('.myClass'); | `querySelector()` returns the first element that matches a specified CSS selector(s). |
.querySelectorAll() | $('selector').querySelectorAll('.myClass'); | `querySelectorAll()` returns all elements that match a specified CSS selector(s). |
.innerHTML | $('element').innerHTML = '<p>New content</p>'; | `innerHTML` sets or returns the HTML content (inner HTML) of an element. |
.textContent | $('element').textContent = 'New text'; | `textContent` sets or returns the text content of an element. |
.style.propertyName | $('element').style.backgroundColor = 'red'; | `style.propertyName` sets or returns the value of a specified CSS property of an element. |
.setAttribute() | $('element').setAttribute('data-id', '123'); | `setAttribute()` sets the value of an attribute on the specified element. |
.getAttribute() | $('element').getAttribute('data-id'); | `getAttribute()` returns the value of a specified attribute on the element. |
.removeAttribute() | $('element').removeAttribute('data-id'); | `removeAttribute()` removes a specified attribute from an element. |
.appendChild() | $('parent').appendChild($('child')); | `appendChild()` adds a new child node to the end of the list of children of a specified parent node. |
.removeChild() | $('parent').removeChild($('child')); | `removeChild()` removes a child node from the DOM and returns the removed node. |
.replaceChild() | $('parent').replaceChild($('newChild'), $('oldChild')); | `replaceChild()` replaces a child node within the specified parent node with a new node. |
.insertBefore() | $('parent').insertBefore($('newNode'), $('referenceNode')); | `insertBefore()` inserts a new node before a reference node as a child of a specified parent node. |
.cloneNode() | $('element').cloneNode(true); | `cloneNode()` creates a copy of the specified node, optionally including its children. |
.focus() | $('input').focus(); | `focus()` sets focus on the specified element, making it active for user input. |
.blur() | $('input').blur(); | `blur()` removes focus from the specified element. |
.scrollIntoView() | $('element').scrollIntoView(); | `scrollIntoView()` scrolls the element into view, aligning it within the visible area of the browser window. |
.classList.toggle() | $('element').classList.toggle('active'); | `classList.toggle()` toggles a class name on an element's class attribute. |
.classList.contains() | $('element').classList.contains('active'); | `classList.contains()` checks if an element has a specific class name. |
.classList.replace() | $('element').classList.replace('old-class', 'new-class'); | `classList.replace()` replaces an existing class name with a new one. |
Command | Example | Description |
---|---|---|
ls | ls -la | Lists files in a directory with details. |
cd | cd /path/to/directory | Changes the current directory. |
pwd | pwd | Prints the current working directory. |
mkdir | mkdir new_folder | Creates a new directory. |
rmdir | rmdir old_folder | Removes an empty directory. |
cp | cp source.txt destination.txt | Copies files or directories. |
mv | mv oldname.txt newname.txt | Moves or renames files and directories. |
rm | rm file.txt | Removes files. |
touch | touch newfile.txt | Creates an empty file or updates its timestamp. |
cat | cat file.txt | Concatenates and displays file content. |
less | less file.txt | Views file contents one page at a time. |
more | more file.txt | Views file contents one page at a time (simpler than less). |
grep | grep 'pattern' file.txt | Searches for patterns in a file. |
find | find . -name '*.txt' | Searches for files in a directory hierarchy. |
chmod | chmod 755 script.sh | Changes file permissions. |
chown | chown user:group file.txt | Changes file ownership. |
man | man ls | Displays the manual page for a command. |
echo | echo 'Hello, World!' | Prints text to the terminal. |
nano | nano file.txt | Opens a simple text editor. |
vim | vim file.txt | Opens an advanced text editor. |
top | top | Displays real-time running processes. |
ps | ps aux | Shows current processes. |
kill | kill 1234 | Sends a signal to a process (commonly to terminate). |
df | df -h | Displays disk space usage in human-readable format. |
du | du -sh folder/ | Shows the disk usage of a directory. |
tar | tar -czvf archive.tar.gz folder/ | Archives files and directories. |
gzip | gzip file.txt | Compresses a file using gzip. |
gunzip | gunzip file.txt.gz | Decompresses a gzip file. |
zip | zip archive.zip file1.txt file2.txt | Packages and compresses files into a ZIP archive. |
unzip | unzip archive.zip | Extracts files from a ZIP archive. |
scp | scp file.txt user@remote:/path/ | Securely copies files between hosts. |
ssh | ssh user@remote | Connects to a remote host securely. |
wget | wget http://example.com/file.txt | Downloads files from the internet. |
curl | curl http://example.com | Transfers data from or to a server. |
ifconfig | ifconfig | Displays or configures network interface parameters. |
ip addr | ip addr show | Displays IP address information. |
netstat | netstat -tuln | Displays network connections and listening ports. |
ping | ping google.com | Checks network connectivity to a host. |
traceroute | traceroute google.com | Traces the network path to a host. |
uname -a | uname -a | Displays detailed system information. |
history | history | Shows the command history. |
alias | alias ll='ls -la' | Creates a shortcut for a command. |
sudo | sudo apt-get update | Executes a command with superuser privileges. |
apt-get update | sudo apt-get update | Updates the package lists (Debian/Ubuntu). |
apt-get upgrade | sudo apt-get upgrade | Upgrades installed packages (Debian/Ubuntu). |
yum update | sudo yum update | Updates packages on RHEL/CentOS systems. |
systemctl status | systemctl status nginx | Checks the status of a service. |
systemctl restart | sudo systemctl restart nginx | Restarts a service. |
df -h | df -h | Shows disk usage in human-readable form. |
du -sh | du -sh folder/ | Shows the size of a directory in human-readable form. |
lsblk | lsblk | Lists block devices. |
fdisk -l | sudo fdisk -l | Lists disk partitions. |
mount | mount /dev/sda1 /mnt | Mounts a filesystem. |
umount | umount /mnt | Unmounts a filesystem. |
ln -s | ln -s /path/to/original /path/to/link | Creates a symbolic link. |
rsync | rsync -av source/ destination/ | Synchronizes files and directories. |
cron | sudo service cron status | Refers to the cron daemon for scheduled tasks. |
crontab -l | crontab -l | Lists the current user's cron jobs. |
env | env | Displays the current environment variables. |
export | export PATH=$PATH:/new/path | Sets an environment variable for the session. |
printenv | printenv | Prints all or part of the environment. |
sed | sed 's/old/new/g' file.txt | Stream editor for filtering and transforming text. |
awk | awk '{print $1}' file.txt | Pattern scanning and processing language. |
cut | cut -d',' -f1 file.csv | Cuts out selected portions of each line of a file. |
sort | sort file.txt | Sorts lines of text in a file. |
uniq | uniq file.txt | Filters out repeated lines in a file. |
wc | wc -l file.txt | Counts lines, words, and characters in a file. |
diff | diff file1.txt file2.txt | Compares two files line by line. |
patch | patch < changes.patch | Applies a diff file to an original. |
ssh-keygen | ssh-keygen -t rsa | Generates a new SSH key pair. |
scp -r | scp -r folder/ user@remote:/path/ | Recursively copies directories over SSH. |
nc | nc -l 1234 | Netcat; used for reading and writing data over network connections. |
lsof | lsof -i | Lists open files and the processes that opened them. |
strace | strace -p 1234 | Traces system calls and signals. |
dd | dd if=/dev/zero of=file.bin bs=1M count=10 | Converts and copies files at a low level. |
watch | watch -n 1 date | Runs a command periodically, showing output fullscreen. |
tail | tail -n 10 file.txt | Outputs the last part of a file. |
head | head -n 10 file.txt | Outputs the first part of a file. |
free -m | free -m | Displays memory usage in megabytes. |
uptime | uptime | Shows how long the system has been running. |
dmesg | dmesg | less | Prints kernel-related messages. |
vmstat | vmstat 1 5 | Reports virtual memory statistics. |
iostat | iostat | Reports CPU and I/O statistics. |
htop | htop | Interactive process viewer. |
screen | screen | Terminal multiplexer. |
tmux | tmux | Terminal multiplexer for managing multiple sessions. |
chroot | chroot /new/root /bin/bash | Runs a command with a different root directory. |
iptables | sudo iptables -L | Administers IPv4 packet filtering and NAT. |
ufw | sudo ufw status | Manages a simple firewall (Uncomplicated Firewall). |
systemctl enable | sudo systemctl enable nginx | Enables a service to start on boot. |
systemctl disable | sudo systemctl disable nginx | Disables a service from starting on boot. |
service | sudo service apache2 restart | Runs a System V init script. |
locate | locate filename | Finds files by name using a prebuilt database. |
updatedb | sudo updatedb | Updates the file database used by locate. |
xargs | find . -name '*.txt' | xargs grep 'pattern' | Builds and executes command lines from standard input. |
bc | echo '3.14*2' | bc -l | Calculator language for precision arithmetic. |
date | date | Displays or sets the system date and time. |
cal | cal | Displays a calendar. |
whoami | whoami | Prints the current user. |
last | last | Shows a list of last logged-in users. |
journalctl | journalctl -xe | Queries and displays logs from the systemd journal. |