Tag: cheat sheet

  • MySQL CLI Quick Reference

    Connecting to MySQL

    • Login to MySQL:
      mysql -u username -p

    Prompts for a password.

    • Specify Database on Login:
      mysql -u username -p -D database_name

    Basic Commands

    • Show all databases:
      SHOW DATABASES;
    • Select a database:
      USE database_name;
    • Show all tables in the current database:
      SHOW TABLES;
    • Describe the structure of a table:
      DESCRIBE table_name;
    • Show the current MySQL user:
      SELECT USER();
    • Show current database:
      SELECT DATABASE();
    • Show process list:
      SHOW PROCESSLIST;
    • Show full process list (to see full queries):
      SHOW FULL PROCESSLIST;
    • Exit MySQL:
      EXIT;

    CRUD Operations

    • Create a new database:
      CREATE DATABASE database_name;
    • Create a new table:
      CREATE TABLE table_name (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100),
        age INT
      );
    • Insert data into a table:
      INSERT INTO table_name (name, age) VALUES ('John', 30);
    • Select data from a table:
      SELECT * FROM table_name;
    • Update data in a table:
      UPDATE table_name SET age = 31 WHERE name = 'John';
    • Delete data from a table:
      DELETE FROM table_name WHERE name = 'John';
    • Drop a table:
      DROP TABLE table_name;

    Loading .sql Files

    To load and execute an SQL file that contains queries or database structure (e.g., schema.sql or data.sql):

    Method 1: From Inside the MySQL Prompt
    1. Open MySQL:
       mysql -u username -p
    1. Select the database you want to load the file into:
       USE database_name;
    1. Load the SQL file:
       SOURCE /path/to/your/file.sql;
    Method 2: Directly from the Command Line

    You can execute the SQL file directly from the command line without entering the MySQL prompt:

    mysql -u username -p database_name < /path/to/your/file.sql

    This method runs the .sql file directly into the specified database.

    Common Tips

    • View running MySQL queries:
      Use SHOW FULL PROCESSLIST; to view running queries, especially helpful for debugging long-running queries.
    • Check MySQL version:
      SELECT VERSION();
    • Enable SQL logging:
      Use SET GLOBAL general_log = 'ON'; to start logging all queries. To view the log, check the path from the following:
      SHOW VARIABLES LIKE 'general_log_file';

    These commands and tips should help you navigate MySQL efficiently!

  • Difference between String Concatenation and String Interpolation in Python

    Difference between String Concatenation and String Interpolation in Python

    # String Concatenation
    name = "John"
    age = 25
    print("Hello, my name is " + name + " and I am " + str(age) + " years old.")
    
    # String Interpolation
    name = "John"
    age = 25
    print(f"Hello, my name is {name} and I am {age} years old.")
    
    # String Interpolation with format()
    name = "John"
    age = 25
    print("Hello, my name is {} and I am {} years old.".format(name, age))
    
    # String Interpolation with format() and positional arguments
    name = "John"
    age = 25
    print("Hello, my name is {0} and I am {1} years old.".format(name, age))
    
    # String Interpolation with format() and keyword arguments
    name = "John"
    age = 25
    print("Hello, my name is {name} and I am {age} years old.".format(name=name, age=age))
    
    # String Interpolation with format() and mixed arguments
    name = "John"
    age = 25
    print("Hello, my name is {0} and I am {age} years old.".format(name, age=age))
    
  • `for` loops in Python

    `for` loops in Python

    # for loops
    # About for loops
    # for loops are used to iterate over a sequence (list, tuple, string) or other 
    # iterable objects.
    
    # Syntax
    # for variable in sequence:
    #    code block
    # Examples
    
    # Iterate over a list
    # A list is a collection which is ordered and changeable.
    print("\nIterate over a list")
    fruits = ["apple", "banana", "cherry"]
    for fruit in fruits:
        print(fruit)
        # Output
        # apple
        # banana
        # cherry
    
    # Iterate over a string
    # A string is a sequence of characters
    print("\nIterate over a string")
    for letter in "apple":
        print(letter)
        # Output
        # a
        # p
        # p
        # l
        # e
    
    # Iterate over a range
    # A range is a sequence of numbers, starting from 0 by default, and increments
    print("\nIterate over a range")
    for i in range(5):
        print(i)
        # Output
        # 0
        # 1
        # 2
        # 3
        # 4
        # Note: The range() function returns a sequence of numbers, starting from 0 
        # by default, and increments by 1 (by default), and stops before a 
        # specified number.
    
    # Iterate over a tuple
    # A tuple is a collection which is ordered and unchangeable.
    print("\nIterate over a tuple")
    colors = ("red", "green", "blue")
    for color in colors:
        print(color)
        # Output
        # red
        # green
        # blue
    
    # Iterate over a dictionary
    # A dictionary is a collection which is unordered, changeable and indexed.
    print("\nIterate over a dictionary")
    person = {
        "name": "Alice",
        "age": 25,
        "is_active": True
    }
    for key in person:
        print(key, person[key])
        # Output
        # name Alice
        # age 25
        # is_active True
        # Note: The for loop iterates over the keys of the dictionary.
    
    # Iterate over a dictionary using items() method
    # The items() method returns a view object that displays a list of a given
    # dictionary's key-value tuple pair.
    print("\nIterate over a dictionary using items() method")
    for key, value in person.items():
        print(key, value)
        # Output
        # name Alice
        # age 25
        # is_active True
        # Note: The for loop iterates over the key-value pairs of the dictionary.
        if key == "age" and value >= 18:
            print(person["name"], "is an adult.")
    
    # Iterate over a dictionary using values() method
    # The values() method returns a view object that displays a list of all the
    # values in the dictionary.
    print("\nIterate over a dictionary using values() method")
    for value in person.values():
        print(value)
        # Output
        # Alice
        # 25
        # True
        # Note: The for loop iterates over the values of the dictionary.
    
    # Iterate over a dictionary using keys() method
    # The keys() method returns a view object that displays a list of all the keys
    # in the dictionary.
    print("\nIterate over a dictionary using keys() method")
    for key in person.keys():
        print(key)
        # Output
        # name
        # age
        # is_active
        # Note: The for loop iterates over the keys of the dictionary.
    
    # Iterate over a dictionary using get() method
    # The get() method returns the value of the specified key.
    print("\nIterate over a dictionary using get() method")
    print(person.get("name"))
    
    # Nested for loops
    
    # clients
    clients = [
        {"name": "Alice", "age": 25},
        {"name": "Bob", "age": 30},
        {"name": "Charlie", "age": 35}
    ]
    # products
    products = ["apple", "banana", "cherry"]
    inventory = {
        "apple": 10,
        "banana": 20,
        "cherry": 30
    }
    # orders
    orders = [
        {"client": "Alice", "product": "apple"},
        {"client": "Bob", "product": "banana"},
        {"client": "Charlie", "product": "cherry"}
    ]
    
    # Iterate over clients
    print("\nIterate over clients")
    for client in clients:
        print(client["name"], client["age"])
        # Output
        # Alice 25
        # Bob 30
        # Charlie 35
    
    # Iterate over products
    print("\nIterate over products")
    for product in products:
        print(product)
        # Output
        # apple
        # banana
        # cherry
    
    # Iterate over orders
    print("\nIterate over orders")
    for order in orders:
        print(order["client"], order["product"])
        # Output
        # Alice apple
        # Bob banana
        # Charlie cherry
    
    # Iterate over orders and products and update inventory
    print("\nIterate over orders and products and update inventory")
    for order in orders:
        for product in products:
            if order["product"] == product:
                inventory[product] -= 1
                print(order["client"], "ordered", order["product"])
                print("Inventory of", product, "is", inventory[product])
                # Output
                # Alice ordered apple
                # Inventory of apple is 9
                # Bob ordered banana
                # Inventory of banana is 19
                # Charlie ordered cherry
                # Inventory of cherry is 29
    # Note: The nested for loop iterates over the orders and products and updates
    # the inventory of the products.
    
  • MySQL Query Cheat Sheet

    MySQL Query Cheat Sheet

    -- Create a new database
    -- This creates a new database named "sandbox". This is not necessary if you already have a database to work with.
    CREATE DATABASE database_name;
    
    -- Use a specific database
    -- This selects the "sandbox" database for use. Replace "sandbox" with the name of the database you want to use.
    USE database_name;
    
    -- Create a new table
    -- This creates a new table named "table_name" with columns "column1" and "column2" of data types "datatype1" and "datatype2" respectively. Replace "table_name", "column1", "column2", "datatype1", and "datatype2" with the desired names and data types.
    CREATE TABLE table_name (
        column1 datatype,
        column2 datatype,
        ...
    );
    
    -- Insert data into a table
    -- This inserts a new row into the "table_name" table with values "value1" and "value2" for columns "column1" and "column2" respectively. Replace "table_name", "column1", "column2", "value1", and "value2" with the desired table name, column names, and values.
    INSERT INTO table_name (column1, column2, ...)
    VALUES (value1, value2, ...);
    
    -- Select all rows from a table
    -- This selects all rows from the "table_name" table. Replace "table_name" with the name of the table you want to select from.
    SELECT * FROM table_name;
    
    -- Select specific columns from a table
    -- This selects specific columns "column1" and "column2" from the "table_name" table. Replace "column1", "column2", and "table_name" with the desired column names and table name.
    SELECT column1, column2, ... FROM table_name;
    
    -- Filter rows using WHERE clause
    -- This selects all rows from the "table_name" table where the condition is met. Replace "table_name" with the name of the table you want to select from and "condition" with the desired condition.
    SELECT * FROM table_name WHERE condition;
    
    -- Update data in a table
    -- This updates the "column1" and "column2" columns in the "table_name" table with new values "value1" and "value2" where the condition is met. Replace "table_name", "column1", "column2", "value1", "value2", and "condition" with the desired table name, column names, values, and condition.
    UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
    
    -- Delete data from a table
    -- This deletes rows from the "table_name" table where the condition is met. Replace "table_name" with the name of the table you want to delete from and "condition" with the desired condition.
    DELETE FROM table_name WHERE condition;
    
    -- Join two or more tables
    -- This joins the "table1" and "table2" tables on the "column" column. Replace "table1", "table2", and "column" with the names of the tables and column you want to join on.
    SELECT * FROM table1 JOIN table2 ON table1.column = table2.column;
    
    -- Order rows in ascending or descending order
    -- This selects all rows from the "table_name" table and orders them in ascending or descending order based on the "column" column. Replace "table_name" and "column" with the name of the table and column you want to order by, and "ASC" or "DESC" with the desired order.
    SELECT * FROM table_name ORDER BY column ASC/DESC;
    
    -- Limit the number of rows returned
    -- This selects the first "number" rows from the "table_name" table. Replace "table_name" with the name of the table you want to select from and "number" with the desired number of rows.
    SELECT * FROM table_name LIMIT number;
    
    -- Group rows and perform aggregate functions
    -- This groups rows in the "table_name" table by the "column" column and counts the number of rows in each group. Replace "table_name" and "column" with the name of the table and column you want to group by.
    SELECT column, COUNT(*) FROM table_name GROUP BY column;
    
    -- Create an index on a table
    -- This creates an index named "index_name" on the "column" column in the "table_name" table. Replace "index_name", "table_name", and "column" with the desired index name, table name, and column.
    CREATE INDEX index_name ON table_name (column);
    
    -- Drop a table
    -- This drops the "table_name" table. Replace "table_name" with the name of the table you want to drop. This is a destructive operation and cannot be undone.
    DROP TABLE table_name;
    
    -- Drop a database
    -- This drops the "database_name" database. Replace "database_name" with the name of the database you want to drop. This is a destructive operation and cannot be undone.
    DROP DATABASE database_name;
    
    -- Show all databases
    SHOW DATABASES;
    
    -- Show all tables in a database
    SHOW TABLES;
    
    -- Show the structure of a table
    -- This shows the columns, data types, and other information about the "table_name" table. Replace "table_name" with the name of the table you want to show the structure of.
    DESC table_name;
    
    -- Show the indexes on a table
    -- This shows the indexes on the "table_name" table. Replace "table_name" with the name of the table you want to show the indexes of.
    SHOW INDEX FROM table_name;
    
    -- Show the status of the server
    -- This shows various status information about the server, such as the number of connections, queries, and other statistics.
    SHOW STATUS;
    
    -- Show the current user
    SELECT USER();
    
    -- Show the current database
    SELECT DATABASE();
    
    -- Show the version of MySQL
    SELECT VERSION();
    
    -- Show the current date and time
    SELECT NOW();
    
    -- Show the current time zone
    SELECT @@time_zone;
    
    -- Join two or more tables
    -- This joins the "table1" and "table2" tables on the "column" column.
    -- A join combines rows from two or more tables based on a related column between them.
    SELECT * FROM table1 JOIN table2 ON table1.column = table2.column;
    
    -- Left join two or more tables
    -- This left joins the "table1" and "table2" tables on the "column" column.
    -- A left join returns all rows from the left table and the matched rows from the right table.
    SELECT * FROM table1 LEFT JOIN table2 ON table1.column = table2.column;
    
    -- Right join two or more tables
    -- This right joins the "table1" and "table2" tables on the "column" column.
    -- A right join returns all rows from the right table and the matched rows from the left table.
    SELECT * FROM table1 RIGHT JOIN table2 ON table1.column = table2.column;
    
    -- Full outer join two or more tables
    -- This full outer joins the "table1" and "table2" tables on the "column" column.
    -- A full outer join returns all rows when there is a match in either the left or right table.
    SELECT * FROM table1 FULL OUTER JOIN table2 ON table1.column = table2.column;
    
    -- Cross join two or more tables
    -- This cross joins the "table1" and "table2" tables.
    -- A cross join returns the Cartesian product of the two tables, i.e., all possible combinations of rows.
    SELECT * FROM table1 CROSS JOIN table2;
    
    
  • Linux Commands Cheat Sheet

    Linux Commands Cheat Sheet

    Here’s a list of common commands along with their descriptions and usage examples:

    1. ls – List Directory Contents
      • Usage: ls [options] [directory]
      • Example: ls -l /home (lists all files in /home with detailed information)
    2. cd – Change Directory
      • Usage: cd [directory]
      • Example: cd /home/user/Documents (changes the current directory to /home/user/Documents)
    3. pwd – Print Working Directory
      • Usage: pwd
      • Example: pwd (displays the path of the current directory)
    4. cat – Concatenate and Display Files
      • Usage: cat [options] [file]
      • Example: cat file.txt (displays the content of file.txt)
    5. cp – Copy Files and Directories
      • Usage: cp [options] source destination
      • Example: cp file1.txt file2.txt (copies file1.txt to file2.txt)
    6. mv – Move or Rename Files and Directories
      • Usage: mv [options] source destination
      • Example: mv file1.txt /home/user/Documents (moves file1.txt to /home/user/Documents)
    7. rm – Remove Files or Directories
      • Usage: rm [options] file
      • Example: rm file.txt (removes file.txt)
    8. mkdir – Create a New Directory
      • Usage: mkdir [options] directory
      • Example: mkdir new_folder (creates a new directory named new_folder)
    9. rmdir – Remove Empty Directories
      • Usage: rmdir [options] directory
      • Example: rmdir old_folder (removes the directory old_folder if it’s empty)
    10. grep – Search Text Using Patterns
      • Usage: grep [options] pattern [file]
      • Example: grep "hello" file.txt (searches for the word “hello” in file.txt)
    11. find – Search for Files in a Directory Hierarchy
      • Usage: find [path] [options] [expression]
      • Example: find /home -name "file.txt" (finds all files named “file.txt” in /home)
    12. chmod – Change File Modes or Access Control Lists
      • Usage: chmod [options] mode file
      • Example: chmod 755 script.sh (sets the permission of script.sh to 755)
    13. chown – Change File Owner and Group
      • Usage: chown [options] owner[:group] file
      • Example: chown user:group file.txt (changes the owner of file.txt to ‘user’ and the group to ‘group’)
    14. tail – Output the Last Part of Files
      • Usage: tail [options] [file]
      • Example: tail -n 5 file.txt (displays the last 5 lines of file.txt)
    15. head – Output the First Part of Files
      • Usage: head [options] [file]
      • Example: head -n 5 file.txt (displays the first 5 lines of file.txt)
    16. man – Interface to the System Reference Manuals
      • Usage: man [command]
      • Example: man ls (displays the manual page for the ls command)

    This is just a basic set of commands, and there are many more commands and options in Linux. For detailed information and more commands, you can always use the man command followed by the command name to read the manual pages.

  • Image Tag Cheat Sheet

    Image Tag Cheat Sheet

    Basic Usage

    <img src="path/to/image.jpg" alt="Image description" />

    Attributes

    AttributeDescription
    srcThe path to the image file.
    altThe text to display if the image fails to load.
    widthThe width of the image in pixels.
    heightThe height of the image in pixels.
    titleThe text to display when the user hovers over the image.

    Example

    <img src="path/to/image.jpg" alt="Image description" width="200" height="200" title="Image title" />

    Notes

    • The alt attribute is required for accessibility. It is used by screen readers to describe the image to visually impaired users.
    • The width and height attributes are optional. If you do not specify them, the image will be displayed at its original size.
    • The title attribute is optional. It is used to provide additional information about the image when the user hovers over it.
  • Regex Cheat Sheet

    Regex Cheat Sheet

    Simple Examples

    • hello: Matches the string “hello” exactly.
    • 123: Matches the string “123” exactly.
    • .: Matches any single character.
    • \d: Matches any digit character (0-9).
    • \w: Matches any word character (a-z, A-Z, 0-9, _).
    • \s: Matches any whitespace character (space, tab, newline).

    Examples

    • hello world: Matches the string “hello world” exactly.
    • hello|world: Matches either “hello” or “world”.
    • hello.*: Matches “hello” followed by zero or more characters.
    • hello\s: Matches “hello” followed by a whitespace character.
    • hello\d: Matches “hello” followed by a digit character.
    • hello\w: Matches “hello” followed by a word character.
    • hello\s\d: Matches “hello” followed by a whitespace character and a digit character.

    Quantifiers

    • a+: Matches one or more “a” characters.
    • a*: Matches zero or more “a” characters.
    • a?: Matches zero or one “a” character.
    • a{3}: Matches exactly three “a” characters.
    • a{3,}: Matches three or more “a” characters.
    • a{3,5}: Matches between three and five “a” characters.

    Character Classes

    • [abc]: Matches any of the characters “a”, “b”, or “c”.
    • [^abc]: Matches any character that is not “a”, “b”, or “c”.
    • [a-z]: Matches any lowercase letter.
    • [A-Z]: Matches any uppercase letter.
    • [0-9]: Matches any digit character.
    • [\w]: Matches any word character.
    • [\W]: Matches any non-word character.
    • [\s]: Matches any whitespace character.
    • [\S]: Matches any non-whitespace character.

    Anchors

    • ^hello: Matches “hello” at the beginning of a line.
    • world$: Matches “world” at the end of a line.
    • \bhello\b: Matches “hello” as a whole word.
    • \Bhello\B: Matches “hello” not as a whole word.

    Groups

    • (hello): Matches “hello” and captures it as a group.
    • (hello|world): Matches either “hello” or “world”.
    • (?:hello): Matches “hello” but does not capture it as a group.
    • (?=hello): Matches any string that is followed by “hello”.
    • (?!hello): Matches any string that is not followed by “hello”.

    Flags

    • /hello/i: Matches “hello” case-insensitively.
    • /hello/g: Matches all occurrences of “hello”.
    • /hello/m: Matches “hello” across multiple lines.
    • /hello/s: Matches “hello” across multiple lines and allows “.” to match newline characters.

    Special Characters

    • \: Escapes a special character.
    • .: Matches any single character except newline characters.
    • ^: Matches the beginning of a line.
    • $: Matches the end of a line.
    • *: Matches zero or more of the preceding character.
    • +: Matches one or more of the preceding character.
    • ?: Matches zero or one of the preceding character.
    • (: Begins a capturing group.
    • ): Ends a capturing group.
    • [: Begins a character class.
    • ]: Ends a character class.
    • {: Begins a quantifier.
    • }: Ends a quantifier.
    • |: Matches either the expression before or after the operator.
    • /: Begins and ends a regular expression.
    • i: Makes the regex case-insensitive.
    • g: Matches all occurrences of the pattern.
    • m: Makes the ^ and $ anchors match the beginning and end of lines.
    • s: Allows . to match newline characters.
    • \n: Matches a newline character.
    • \r: Matches a carriage return character.
    • \t: Matches a tab character.
    • \v: Matches a vertical tab character.
    • \0: Matches a null character (U+0000 NULL).
    • \xhh: Matches a character with the given hex code (e.g. \x0A matches a newline character).
    • \uhhhh: Matches a character with the given Unicode code point (e.g. \u0009 matches a tab character).
    • \cX: Matches a control character using caret notation (e.g. \cJ matches a newline character).
    • \u{hhhh}: Matches a character with the given Unicode code point (e.g. \u{0009} matches a tab character).

    Lookarounds

    • (?=hello): Positive lookahead. Matches any string that is followed by “hello”.
    • (?!hello): Negative lookahead. Matches any string that is not followed by “hello”.
    • (?<=hello): Positive lookbehind. Matches any string that is preceded by “hello”.
    • (?<!hello): Negative lookbehind. Matches any string that is not preceded by “hello”.

    Unicode Categories

    • \p{L}: Matches any letter character.
    • \p{M}: Matches any combining mark character.
    • \p{Z}: Matches any separator character.
    • \p{S}: Matches any symbol character.
    • \p{N}: Matches any number character.
    • \p{P}: Matches any punctuation character.
    • \p{C}: Matches any control character.
    • \p{Ll}: Matches any lowercase letter.
    • \p{Lu}: Matches any uppercase letter.
    • \p{Lt}: Matches any titlecase letter.
    • \p{L&}: Matches any letter character.
    • \p{Lm}: Matches any modifier letter.
    • \p{Lo}: Matches any other letter character.
    • \p{Mn}: Matches any non-spacing mark character.
    • \p{Mc}: Matches any spacing combining mark character.
    • \p{Me}: Matches any enclosing mark character.
    • \p{Zs}: Matches any space separator character.
    • \p{Zl}: Matches any line separator character.
    • \p{Zp}: Matches any paragraph separator character.
    • \p{Sm}: Matches any mathematical symbol character.
    • \p{Sc}: Matches any currency symbol character.
    • \p{Sk}: Matches any modifier symbol character.
    • \p{So}: Matches any other symbol character.
    • \p{Nd}: Matches any decimal digit character.
    • \p{Nl}: Matches any letter number character.
    • \p{No}: Matches any other number character.
    • \p{Pc}: Matches any connector punctuation character.
    • \p{Pd}: Matches any dash punctuation character.
    • \p{Ps}: Matches any open punctuation character.
    • \p{Pe}: Matches any close punctuation character.
    • \p{Pi}: Matches any initial punctuation character.
    • \p{Pf}: Matches any final punctuation character.
    • \p{Po}: Matches any other punctuation character.
    • \p{Cc}: Matches any control character.
    • \p{Cf}: Matches any format character.
    • \p{Cs}: Matches any surrogate character.
    • \p{Co}: Matches any private-use character.
    • \p{Cn}: Matches any unassigned code point.

    POSIX Classes

    • [:alnum:]: Matches any alphanumeric character.
    • [:alpha:]: Matches any alphabetic character.
    • [:ascii:]: Matches any ASCII character.
    • [:blank:]: Matches any whitespace character.
    • [:cntrl:]: Matches any control character.
    • [:digit:]: Matches any digit character.
    • [:graph:]: Matches any visible character.
    • [:lower:]: Matches any lowercase character.
    • [:print:]: Matches any printable character.
    • [:punct:]: Matches any punctuation character.
    • [:space:]: Matches any whitespace character.
    • [:upper:]: Matches any uppercase character.
    • [:word:]: Matches any word character.
    • [:xdigit:]: Matches any hexadecimal digit character.
  • JavaScript String Cheat Sheet v2

    JavaScript String Cheat Sheet v2

    I was looking through the site for the old post, which was… less than helpful. Here’s the updated cheat sheet for quick reference.