Blog

Go Lang Crash Course

Basics of Go

  • Variables and Constants:
package main

import "fmt"

func main() {
    var message string = "Hello, Go!"
    fmt.Println(message)

    const pi = 3.14159
    fmt.Println(pi)
}
  • Data Types and Type Conversion:
package main

import "fmt"

func main() {
    var age int = 25
    fmt.Println(age)

    var price float64 = 9.99
    fmt.Println(price)

    var isTrue bool = true
    fmt.Println(isTrue)

    var name string = "John"
    fmt.Println(name)

    // Type conversion
    var num int = 42
    var result float64 = float64(num)
    fmt.Println(result)
}

Operators

package main

import "fmt"

func main() {
    var a = 10
    var b = 5

    fmt.Println(a + b)
    fmt.Println(a - b)
    fmt.Println(a * b)
    fmt.Println(a / b)
    fmt.Println(a % b)

    var isTrue = true
    fmt.Println(!isTrue)
}

Control Structures: if-else and switch:

package main

import "fmt"

func main() {
    var num = 5

    if num > 0 {
        fmt.Println("Number is positive")
    } else if num < 0 {
        fmt.Println("Number is negative")
    } else {
        fmt.Println("Number is zero")
    }

    var day = "Monday"

    switch day {
    case "Monday":
        fmt.Println("It's Monday")
    case "Tuesday":
        fmt.Println("It's Tuesday")
    default:
        fmt.Println("It's another day")
    }
}

Loops: for and range

package main

import "fmt"

func main() {
    // For loop
    for i := 1; i <= 5; i++ {
        fmt.Println(i)
    }

    // Range loop
    nums := []int{1, 2, 3, 4, 5}
    for index, value := range nums {
        fmt.Println(index, value)
    }
}

Functions in Go

  • Simple Function:
package main

import "fmt"

func add(a, b int) int {
    return a + b
}

func main() {
    result := add(3, 5)
    fmt.Println(result)
}
  • Function with Multiple Return Values:
package main

import "fmt"

func divide(a, b int) (int, int) {
    quotient := a / b
    remainder := a % b
    return quotient, remainder
}

func main() {
    q, r := divide(10, 3)
    fmt.Println("Quotient:", q)
    fmt.Println("Remainder:", r)
}
  • Variadic Function:
package main

import "fmt"

func sum(numbers ...int) int {
    total := 0
    for _, num := range numbers {
        total += num
    }
    return total
}

func main() {
    result := sum(1, 2, 3, 4, 5)
    fmt.Println(result)
}
  • Anonymous Functions and Closures:
package main

import "fmt"

func main() {
    add := func(a, b int) int {
        return a + b


 }

    result := add(3, 5)
    fmt.Println(result)
}
  • Recursion:
package main

import "fmt"

func factorial(n int) int {
    if n == 0 {
        return 1
    }
    return n * factorial(n-1)
}

func main() {
    result := factorial(5)
    fmt.Println(result)
}

Arrays, Slices, and Maps in Go

  • Arrays:
package main

import "fmt"

func main() {
    var numbers [5]int
    numbers[0] = 1
    numbers[1] = 2
    numbers[2] = 3
    numbers[3] = 4
    numbers[4] = 5
    fmt.Println(numbers)

    var matrix [3][3]int
    matrix[0] = [3]int{1, 2, 3}
    matrix[1] = [3]int{4, 5, 6}
    matrix[2] = [3]int{7, 8, 9}
    fmt.Println(matrix)
}
  • Slices:
package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    fmt.Println(numbers)

    fmt.Println(numbers[1:4]) // Slicing a slice

    numbers = append(numbers, 6) // Appending an element
    fmt.Println(numbers)

    numbers = append(numbers[:2], numbers[3:]...) // Removing an element
    fmt.Println(numbers)
}
  • Maps:
package main

import "fmt"

func main() {
    person := map[string]string{
        "name":  "John",
        "age":   "30",
        "email": "john@example.com",
    }
    fmt.Println(person)

    fmt.Println(person["name"])

    person["city"] = "New York" // Adding a new key-value pair
    fmt.Println(person)

    delete(person, "age") // Removing a key-value pair
    fmt.Println(person)
}
  • Iterating over Slices and Maps:
package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    for index, value := range numbers {
        fmt.Println(index, value)
    }

    person := map[string]string{
        "name":  "John",
        "age":   "30",
        "email": "john@example.com",
    }
    for key, value := range person {
        fmt.Println(key, ":", value)
    }
}

Structs and Methods in Go

  • Structs:
package main

import "fmt"

type Person struct {
    name    string
    age     int
    address string
}

func main() {
    person := Person{"John", 30, "New York"}
    fmt.Println(person)

    fmt.Println(person.name)
    fmt.Println(person.age)
    fmt.Println(person.address)
}
  • Methods:
package main

import "fmt"

type Rectangle struct {
    width  float64
    height float64
}

func (r Rectangle) area() float64 {
    return r.width * r.height
}

func main() {
    rect := Rectangle{3.0, 4.0}
    fmt.Println(rect.area())
}

Packages and Error Handling in Go

  • Packages:
package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Println(math

.Sqrt(16))
}
  • Error Handling with error Type:
package main

import (
    "fmt"
    "math"
)

func calculateSqrt(num float64) (float64, error) {
    if num < 0 {
        return 0, fmt.Errorf("Cannot calculate square root of a negative number")
    }
    return math.Sqrt(num), nil
}

func main() {
    result, err := calculateSqrt(-9)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(result)
    }
}
  • Custom Error Types:
package main

import (
    "fmt"
    "math"
)

type NegativeNumberError struct {
    number float64
}

func (e NegativeNumberError) Error() string {
    return fmt.Sprintf("Cannot calculate square root of a negative number: %f", e.number)
}

func calculateSqrt(num float64) (float64, error) {
    if num < 0 {
        return 0, NegativeNumberError{num}
    }
    return math.Sqrt(num), nil
}

func main() {
    result, err := calculateSqrt(-9)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(result)
    }
}

Database Connection

  1. Installing and Importing Dependencies:
package main

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)
  1. Establishing a Database Connection:
func main() {
    // Database connection parameters
    db, err := sql.Open("mysql", "username:password@tcp(localhost:3306)/database_name")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    // Check if the connection is successful
    err = db.Ping()
    if err != nil {
        panic(err)
    }

    fmt.Println("Connected to the database!")
}
  1. Creating the “users” Table:
func main() {
    db, err := sql.Open("mysql", "username:password@tcp(localhost:3306)/database_name")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    createTableQuery := `
        CREATE TABLE IF NOT EXISTS users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(50) NOT NULL,
            age INT,
            city VARCHAR(50),
            salary FLOAT,
            added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        );
    `

    _, err = db.Exec(createTableQuery)
    if err != nil {
        panic(err)
    }

    fmt.Println("Table 'users' created successfully!")
}
  1. Inserting Data into the “users” Table:
func main() {
    db, err := sql.Open("mysql", "username:password@tcp(localhost:3306)/database_name")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    insertQuery := `
        INSERT INTO users (name, age, city, salary)
        VALUES (?, ?, ?, ?);
    `

    result, err := db.Exec(insertQuery, "John Doe", 30, "New York", 5000.0)
    if err != nil {
        panic(err)
    }

    lastInsertID, err := result.LastInsertId()
    if err != nil {
        panic(err)
    }

    fmt.Println("Inserted record ID:", lastInsertID)
}
  1. Querying Data from the “users” Table:
func main() {
    db, err := sql.Open("mysql", "username:password@tcp(localhost:3306)/database_name")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    selectQuery := `
        SELECT id, name, age, city, salary, added_at, updated_at
        FROM users;
    `

    rows, err := db.Query(selectQuery)
    if err != nil {
        panic(err)
    }
    defer rows.Close()

    for rows.Next() {
        var id int
        var name string
        var age int
        var city string
        var salary float64
        var addedAt string
        var updatedAt string

        err := rows.Scan(&id, &name, &age, &city, &salary, &addedAt, &updatedAt)
        if err != nil {
            panic(err)
        }

        fmt.Println("ID:", id)
        fmt.Println("Name:", name)
        fmt.Println("Age:", age)
        fmt.Println("City:", city)
        fmt.Println("Salary:", salary)
        fmt.Println("Added At:", addedAt)
        fmt

.Println("Updated At:", updatedAt)
        fmt.Println()
    }
}

Go and Gin Framework

  1. Retrieving All Users:
func main() {
    router := gin.Default()

    // ...

    router.GET("/users", func(c *gin.Context) {
        selectQuery := `
            SELECT id, name, age, city, salary, added_at, updated_at
            FROM users;
        `

        rows, err := db.Query(selectQuery)
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }
        defer rows.Close()

        users := []gin.H{}
        for rows.Next() {
            var id int
            var name string
            var age int
            var city string
            var salary float64
            var addedAt string
            var updatedAt string

            err := rows.Scan(&id, &name, &age, &city, &salary, &addedAt, &updatedAt)
            if err != nil {
                c.JSON(500, gin.H{"error": err.Error()})
                return
            }

            user := gin.H{
                "id":        id,
                "name":      name,
                "age":       age,
                "city":      city,
                "salary":    salary,
                "added_at":  addedAt,
                "updated_at": updatedAt,
            }

            users = append(users, user)
        }

        c.JSON(200, users)
    })

    // ...

    router.Run(":8080")
}
  1. Deleting a User:
func main() {
    router := gin.Default()

    // ...

    router.DELETE("/users/:id", func(c *gin.Context) {
        id := c.Param("id")

        deleteQuery := `
            DELETE FROM users
            WHERE id = ?;
        `

        result, err := db.Exec(deleteQuery, id)
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        rowsAffected, err := result.RowsAffected()
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        if rowsAffected == 0 {
            c.JSON(404, gin.H{"message": fmt.Sprintf("User with ID %s not found", id)})
        } else {
            c.JSON(200, gin.H{"message": fmt.Sprintf("User with ID %s deleted", id)})
        }
    })

    // ...

    router.Run(":8080")
}
  1. Adding a New User:
func main() {
    router := gin.Default()

    // ...

    router.POST("/users", func(c *gin.Context) {
        var user struct {
            Name   string  `json:"name"`
            Age    int     `json:"age"`
            City   string  `json:"city"`
            Salary float64 `json:"salary"`
        }

        if err := c.ShouldBindJSON(&user); err != nil {
            c.JSON(400, gin.H{"error": err.Error()})
            return
        }

        insertQuery := `
            INSERT INTO users (name, age, city, salary)
            VALUES (?, ?, ?, ?);
        `

        result, err := db.Exec(insertQuery, user.Name, user.Age, user.City, user.Salary)
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        lastInsertID, err := result.LastInsertId()
        if err != nil {
            c

.JSON(500, gin.H{"error": err.Error()})
            return
        }

        c.JSON(201, gin.H{"message": fmt.Sprintf("User created with ID %d", lastInsertID)})
    })

    // ...

    router.Run(":8080")
}
  1. Fetching a Single User:
func main() {
    router := gin.Default()

    // ...

    router.GET("/users/:id", func(c *gin.Context) {
        id := c.Param("id")

        selectQuery := `
            SELECT id, name, age, city, salary, added_at, updated_at
            FROM users
            WHERE id = ?;
        `

        row := db.QueryRow(selectQuery, id)

        var user struct {
            ID        int     `json:"id"`
            Name      string  `json:"name"`
            Age       int     `json:"age"`
            City      string  `json:"city"`
            Salary    float64 `json:"salary"`
            AddedAt   string  `json:"added_at"`
            UpdatedAt string  `json:"updated_at"`
        }

        err := row.Scan(&user.ID, &user.Name, &user.Age, &user.City, &user.Salary, &user.AddedAt, &user.UpdatedAt)
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        c.JSON(200, user)
    })

    // ...

    router.Run(":8080")
}
  1. Updating an Existing User:
func main() {
    router := gin.Default()

    // ...

    router.PUT("/users/:id", func(c *gin.Context) {
        id := c.Param("id")

        var user struct {
            Name   string  `json:"name"`
            Age    int     `json:"age"`
            City   string  `json:"city"`
            Salary float64 `json:"salary"`
        }

        if err := c.ShouldBindJSON(&user); err != nil {
            c.JSON(400, gin.H{"error": err.Error()})
            return
        }

        updateQuery := `
            UPDATE users
            SET name = ?, age = ?, city = ?, salary = ?
            WHERE id = ?;
        `

        result, err := db.Exec(updateQuery, user.Name, user.Age, user.City, user.Salary, id)
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        rowsAffected, err := result.RowsAffected()
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        if rowsAffected == 0 {
            c.JSON(404, gin.H{"message": fmt.Sprintf("User with ID %s not found", id)})
        } else {
            c.JSON(200, gin.H{"message": fmt.Sprintf("User with ID %s updated", id)})
        }
    })

    // ...

    router.Run(":8080")
}

Please make sure to replace "username", "password", and "database_name" with your actual MySQL database credentials and database name.

Python Crash Course

Certainly! Here are ten examples for each of the topics you mentioned:

BASICS

  1. Basics:
    Example 1: Printing a message
   print("Hello, World!")

Example 2: Arithmetic operations

   a = 10
   b = 5
   print("Addition:", a + b)
   print("Subtraction:", a - b)
   print("Multiplication:", a * b)
   print("Division:", a / b)
   print("Modulo:", a % b)

Example 3: String concatenation

   name = "Alice"
   age = 25
   print("My name is " + name + " and I am " + str(age) + " years old.")

Example 4: Using the input function

   name = input("Enter your name: ")
   print("Hello, " + name + "!")

Example 5: Conditional statements

   num = int(input("Enter a number: "))
   if num > 0:
       print("The number is positive.")
   elif num < 0:
       print("The number is negative.")
   else:
       print("The number is zero.")

Example 6: Working with loops (for loop)

   for i in range(5):
       print(i)

Example 7: Working with loops (while loop)

   count = 0
   while count < 5:
       print(count)
       count += 1

Example 8: Using the len() function

   text = "Hello, World!"
   print("Length:", len(text))

Example 9: Using the str() function

   num = 42
   text = "The answer is: " + str(num)
   print(text)

Example 10: Importing and using modules

   import math

   radius = 5
   area = math.pi * radius ** 2
   print("Area of the circle:", area)

CONDITIONAL STATEMENTS IF ELSE

  1. If-Else Statements:
    Example 1: Checking if a number is even or odd
   num = int(input("Enter a number: "))
   if num % 2 == 0:
       print("The number is even.")
   else:
       print("The number is odd.")

Example 2: Checking if a year is a leap year

   year = int(input("Enter a year: "))
   if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
       print("The year is a leap year.")
   else:
       print("The year is not a leap year.")

Example 3: Determining the maximum of three numbers

   num1 = float(input("Enter the first number: "))
   num2 = float(input("Enter the second number: "))
   num3 = float(input("Enter the third number: "))
   max_num = max(num1, num2, num3)
   print("The maximum number is:", max_num)

Example 4: Checking if a student passed or failed

   score = float(input("Enter the student's score: "))
   if score >= 60:
       print("The student passed.")
   else:
       print("The student failed.")

Example 5

: Categorizing a number into different ranges

   num = float(input("Enter a number: "))
   if num < 0:
       print("The number is negative.")
   elif num >= 0 and num <= 10:
       print("The number is between 0 and 10.")
   elif num > 10 and num <= 20:
       print("The number is between 10 and 20.")
   else:
       print("The number is greater than 20.")

Example 6: Checking if a person is eligible to vote

   age = int(input("Enter your age: "))
   if age >= 18:
       print("You are eligible to vote.")
   else:
       print("You are not eligible to vote yet.")

Example 7: Checking if a number is positive, negative, or zero (alternative approach)

   num = float(input("Enter a number: "))
   if num > 0:
       print("The number is positive.")
   elif num < 0:
       print("The number is negative.")
   else:
       print("The number is zero.")

Example 8: Checking if a character is a vowel or consonant

   char = input("Enter a character: ").lower()
   if char in ['a', 'e', 'i', 'o', 'u']:
       print("The character is a vowel.")
   else:
       print("The character is a consonant.")

Example 9: Checking if a number is a multiple of another number

   num1 = int(input("Enter the first number: "))
   num2 = int(input("Enter the second number: "))
   if num1 % num2 == 0:
       print(num1, "is a multiple of", num2)
   else:
       print(num1, "is not a multiple of", num2)

Example 10: Checking if a year is a leap year (alternative approach)

   year = int(input("Enter a year: "))
   if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
       print("The year is a leap year.")
   else:
       print("The year is not a leap year.")

For loop with range

  1. Printing numbers from 0 to 9:
for i in range(10):
    print(i)
  1. Printing even numbers from 2 to 10:
for i in range(2, 11, 2):
    print(i)
  1. Calculating the sum of numbers from 1 to 100:
total = 0
for i in range(1, 101):
    total += i
print("Sum:", total)
  1. Printing numbers in reverse order from 9 to 0:
for i in range(9, -1, -1):
    print(i)
  1. Multiplying each number in the range by 2 and printing the result:
for i in range(10):
    result = i * 2
    print(result)
  1. Printing the square of each number in the range from 1 to 5:
for i in range(1, 6):
    square = i ** 2
    print(square)
  1. Printing numbers in increments of 5 from 0 to 50:
for i in range(0, 51, 5):
    print(i)
  1. Checking if a number is divisible by 3 in the range from 1 to 20:
for i in range(1, 21):
    if i % 3 == 0:
        print(i, "is divisible by 3")
  1. Printing the ASCII value of each character in a string:
text = "Hello"
for char in text:
    ascii_value = ord(char)
    print(char, ":", ascii_value)
  1. Repeating a specific action a certain number of times using range:
for _ in range(5):
    print("Hello, world!")

LIST

  1. List:
    Example 1: Accessing list elements
   fruits = ["apple", "banana", "orange", "grape", "mango"]
   print(fruits[0])  # "apple"
   print(fruits[2])  # "orange"

Example 2: Modifying list elements

   numbers = [1, 2, 3, 4, 5]
   numbers[2] = 10
   print(numbers)  # [1, 2, 10, 4, 5]

Example 3: Appending elements to a list

   numbers = [1, 2, 3]
   numbers.append(4)
   print(numbers)  # [1, 2, 3, 4]

Example 4: Removing elements from a list

   fruits = ["apple", "banana", "orange", "grape"]
   fruits.remove("banana")
   print(fruits)  # ["apple", "orange", "grape"]

Example 5: Slicing a list

   numbers = [1, 2, 3, 4, 5]
   print(numbers[1:4])  # [2, 3, 4]

Example 6: Checking if an element exists in a list

   fruits = ["apple", "banana", "orange", "grape"]
   if "banana" in fruits:
       print("Banana is in the list.")

Example 7: Counting occurrences of an element in a list

   numbers = [1, 2, 3, 1, 2, 1, 4, 1]
   count = numbers.count(1)
   print("Number of occurrences:", count)

Example 8: Sorting a list

   numbers = [5, 3, 1, 4, 2]
   numbers.sort()
   print(numbers)  # [1, 2, 3, 4, 5]

Example 9: Reversing a list

   fruits = ["apple", "banana", "orange", "grape"]
   fruits.reverse()
   print(fruits)  # ["grape", "orange", "banana", "apple"]

Example 10: Combining two lists

   list1 = [1, 2, 3]
   list2 = [4, 5, 6]
   combined_list = list1 + list2
   print(combined_list)  # [1, 2, 3, 4, 5, 6]

DICTIONARY

  1. Example 1: Accessing dictionary values
   student = {"name": "Alice", "age": 20, "grade": "A"}
   print(student["name"])  # "Alice"
   print(student["age"])   # 20

Example 2: Adding new key-value pairs to a dictionary

   student = {"name": "Alice", "age": 20}
   student["grade"] = "A"
   print(student)  # {"name": "Alice", "age": 20, "grade": "A"}

Example 3: Modifying dictionary values

   student = {"name": "Alice", "age": 20, "grade": "A"}
   student["age"] = 21
   print(student)  # {"name": "Alice", "age": 21, "grade": "A"}

Example 4: Checking if a key exists in a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   if "age" in student:
       print("Age:", student["age"])  # Age: 20

Example 5: Removing a key-value pair from a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   del student["grade"]
   print(student)  # {"name": "Alice", "age": 20}

Example 6: Getting all keys from a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   keys = student.keys()
   print(keys)  # ["name", "age", "grade"]

Example 7: Getting all values from a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   values = student.values()
   print(values)  # ["Alice", 20, "A"]

Example 8: Checking the length of a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   length = len(student)
   print("Length:", length)  # Length: 3

Example 9: Clearing a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   student.clear()
   print(student)  # {}

Example 10: Copying a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   student_copy = student.copy()
   print(student_copy)  # {"name": "Alice", "age": 20, "grade": "A"}

LIST OF DICTIONARIES

employees = [
    {"name": "John", "age": 32, "department": "HR", "salary": 50000},
    {"name": "Emily", "age": 28, "department": "IT", "salary": 60000},
    {"name": "Michael", "age": 35, "department": "Finance", "salary": 70000},
    {"name": "Sophia", "age": 29, "department": "Sales", "salary": 55000},
    {"name": "Daniel", "age": 31, "department": "IT", "salary": 62000},
    {"name": "Olivia", "age": 27, "department": "HR", "salary": 48000},
    {"name": "William", "age": 33, "department": "Finance", "salary": 75000},
    {"name": "Ava", "age": 30, "department": "Sales", "salary": 58000},
    {"name": "James", "age": 34, "department": "IT", "salary": 65000},
    {"name": "Emma", "age": 26, "department": "HR", "salary": 52000}
]

Now, let’s provide 10 examples using the same list of employees:

  1. Accessing values in the list:
print(employees[0]["name"])     # Output: "John"
print(employees[3]["age"])      # Output: 29
  1. Modifying a value in the list:
employees[2]["salary"] = 72000
print(employees[2])             # Output: {'name': 'Michael', 'age': 35, 'department': 'Finance', 'salary': 72000}
  1. Adding a new key-value pair to a dictionary:
employees[1]["position"] = "Senior Software Engineer"
print(employees[1])             # Output: {'name': 'Emily', 'age': 28, 'department': 'IT', 'salary': 60000, 'position': 'Senior Software Engineer'}
  1. Removing a key-value pair from a dictionary:
del employees[4]["age"]
print(employees[4])             # Output: {'name': 'Daniel', 'department': 'IT', 'salary': 62000}
  1. Counting the number of dictionaries in the list:
count = len(employees)
print("Number of employees:", count)   # Output: Number of employees: 10
  1. Calculating the average age of all employees:
total_salary = 0
num_employees = len(employees)

for employee in employees:
    total_salary += employee["salary"]

average_salary = total_salary / num_employees

print("Average salary:", average_salary)
  1. Finding the employee with the highest salary:
max_salary = 0
employee_with_max_salary = None

for employee in employees:
    if employee["salary"] > max_salary:
        max_salary = employee["salary"]
        employee_with_max_salary = employee

print("Employee with the highest salary:")
print("Name:", employee_with_max_salary["name"])
print("Salary:", employee_with_max_salary["salary"])
  1. Finding all employees having highest salary:
max_salary = 0
employees_with_max_salary = []

for employee in employees:
    if employee["salary"] > max_salary:
        max_salary = employee["salary"]
        employees_with_max_salary = [employee]
    elif employee["salary"] == max_salary:
        employees_with_max_salary.append(employee)

print("Employees with the highest salary:")
for employee in employees_with_max_salary:
    print("Name:", employee["name"])
    print("Salary:", employee["salary"])
    print()
  1. Calculating total, average, highest and lowest salaries all employees:
total_salary = 0
highest_salary = float("-inf")
lowest_salary = float("inf")

for employee in employees:
    salary = employee["salary"]
    total_salary += salary

    if salary > highest_salary:
        highest_salary = salary

    if salary < lowest_salary:
        lowest_salary = salary

average_salary = total_salary / len(employees)

print("Total Salary:", total_salary)
print("Highest Salary:", highest_salary)
print("Lowest Salary:", lowest_salary)
print("Average Salary:", average_salary)
  1. Print all employees using PrettyTable:
# Print all employees
all_employees_table = PrettyTable(["Name", "Department", "Salary"])
for employee in employees:
    all_employees_table.add_row([employee["name"], employee["department"], employee["salary"]])
all_employees_table.title = "All Employees"
print(all_employees_table)

Mini Project

Print department wise highest salaried employees

Expected output

Demo

Basic

  1. WAP to read 2 numbers and print addition
  2. WAP to read 2 numbers and print subtraction
  3. WAP to read 2 numbers and print multiplication
  4. WAP to read 2 numbers and print division
  5. WAP to read 2 numbers and print modulus (Remainder)
  6. WAP to read radius and print area and circumference of circle
  7. WAP to read length and breadth and print area and perimeter of rectangle

Conditional Statement (if else)

  1. WAP to read a number and check if its positive or negative
  2. WAP to read a number and check it is even or odd
  3. WAP to read 2 numbers and find greatest among them
  4. WAP to read 3 numbers and find greatest among them
  5. WAP to read marks of 5 subjects and check the student is pass or failed
    1. add validation for marks less than 0
    2. add validation for marks greater than 100

Loops

  1. WAP to print hello world 10 times with numbering
  2. WAP to print square of numbers from 1 to 10
  3. WAP to print numbers from 1 to given number
  4. WAP to print cube of numbers from 1 to given number
  5. WAP to read a number and print table of that number
  6. WAP to execute Fizz Buzz Problem / Print number 1 to 100
    1. if number is divisible by 3 then print Fizz
    2. if number is divisible by 5 then print Buzz
    3. if number is divisible by both 3 and 5 then print Fizz Buzz
  7. WAP to execute lift program of 20 floor
    1. print number with delay of 1 sec (use time module’s sleep method)
    2. skip 13 number
    3. break after printing 13
  8. WAP to create random jackpot number and take input from user to guess the number. Based on level the attempt to guess the number should change
    1. Easy – 20 attempts
    2. Medium – 10 attempts
    3. Difficult – 5 attempts

Interview Questions

  1. What is the difference between html and html5
  2. Tag name available in html5
  3. What is javascript
  4. What is ajax and its benefits
  5. what is the different type of request available in ajax
  6. what is jquery and its benefits
  7. Main difference between javascript and jquery
  8. Event in jquery
  9. example of jquery event
  10. what is difference between CSS and CSS3
  11. what is media query in CSS
  12. What is bootstrap
  13. what is grid system in bootstrap
  14. What is JSON
  15. What is API
  16. What is PHP
  17. what is variable in PHP
  18. what types of variable available in PHP
  19. what is array in PHP
  20. how many types of array available in PHP
  21. difference between associative array and multidimentional array
  22. Difference between library function and user defined function in php
  23. Give me example of library function
  24. Difference between sessions and cookies
  25. What is difference between get and post method
  26. What is database
  27. What is table
  28. What is database MYSQL queries
  29. Type of relationship available in MYSQL
  30. Which datatype is use to store image in table
  31. What is OOPS
  32. Difference between classes and objects
  33. What is the different type array function in PHP
  34. Difference between concat() and array_push()
  35. Difference between constructor() and destructor()
  36. Types of error available in PHP
  37. Difference between library file and helper file
  38. Give me any three datatype of date and time
  39. What is blob in MYSQL
  40. Difference between RDBMS and DBMS
  41. Difference between string datatype and varchar datatype
  42. Difference between text datatype and String datatype
  43. What is datatype in MYSQL
  44. What are the meaning of classes and objects
  45. Difference between argument and parameter
  46. difference between cookies and local storage
  47. what is the difference between session storage and local storage
  48. Difference between notice error and warning error
  49. What is the library
  50. Difference between authentication and authorization
  51. What is MVC
  52. What is polymorphism
  53. Difference between Primary key and foreign key
  54. What is the full form of DOM and give its types
  55. Can table have more than one primary key

Interceptor

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import axios from 'axios';
// Add a request interceptor
axios.interceptors.request.use(
  config => {
    console.log("inside interceptor request", config)

    const token = "TOKEN FROM INTERCEPTORS"
    if (token) {
      console.log("INSIDE request use")
      config.headers['Authorization'] = 'Bearer ' + token
    }
    
    return config
  },
  error => {
    Promise.reject(error)
  }
)


axios.interceptors.response.use(
  config => {
    console.log("inside interceptor response", config)
    return config
  },
  error => {
    Promise.reject(error)
  }
)



const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

reportWebVitals();

App.js

import logo from './logo.svg';
import './App.css';
import { useEffect } from 'react';
import axios from 'axios';

function App() {

  useEffect(()=> {

    axios({
      method: 'get',
      url: 'http://localhost:1234/webservice.php'
    })
      .then(function (response) {
        console.log(response)
      });
    
  }, [])

  return (
    <>
    This is App component
    </>
  );
}

export default App;

webservice.php

<?php

header("Access-Control-Allow-Origin: *");

// echo "<pre>";
// print_r($_SERVER);

echo json_encode(["test" => "Hello world...."]);

Redux

src/store.js

import { combineReducers, configureStore } from "@reduxjs/toolkit";

const initial_state = { userid: 1, emailid: "admin@nstest.com" }

const adminreducer = (state = initial_state, {type, payload}) => {

  if(type == "SET_VAL") {
    console.log("INSIDE SET_VAL case")
    return {...state, emailid : payload.emailid }
  }

  return state
}

const userreducer = (state = { payload: {} }, {type, payload}) => {

    if(type == "SET_USER_VAL") {
      console.log("INSIDE SET_USER_VAL case")
      return {...state, payload : payload }
    }
  
    return state
  }


const reducer = combineReducers({adminreducer, userreducer})

const store = configureStore({reducer})

export default store;

src/index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import store from './store';
import { Provider } from 'react-redux';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
    <App />
    </Provider>
  </React.StrictMode>
);

reportWebVitals();

src/App.js

import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Admin from "./components/Admin";
import Contact from "./components/Contact";
import Home from "./components/Home";
import Layout from "./components/Layout";
import User from "./components/User";

function App() {

  const mystate = useSelector((state) => state)

  return (
    <div>
      This is app component <br />
      {mystate.payload}
      <Contact />
      <BrowserRouter>
        <Routes>
          <Route path="/" element={ <Layout />}>

            <Route index element={ <Home /> } />
            <Route path="admin" element={ <Admin /> } />
            <Route path="user" element={ <User /> } />

          </Route>
        </Routes>
      </BrowserRouter>
    </div>
  );
}

export default App;

src/components/Admin.js

import React, { useEffect } from 'react'
import { useDispatch } from 'react-redux'

export default function Admin() {

    const dispatch = useDispatch()

    useEffect(() => {
        console.log("Hello dispatcher...")
        dispatch({ type : "SET_VAL", payload: { "emailid" : "admin@devtest.com"} })
    }, [])

  return (
    <div>Admin</div>
  )
}

src/component/User.js

import React, { useEffect } from 'react'
import { useDispatch } from 'react-redux'

export default function User() {

    const dispatcher = useDispatch()

    useEffect(() => {
        console.log("Inside user use effect")

        dispatcher({ 
          "type" : "SET_USER_VAL", 
          payload : { emailid : "user@devtest.com", time: new Date().toJSON().slice(0, 10) }
        })

    }, [])

  return (
    <div>User</div>
  )
}

Setter and Getter for Redux

store.js

import { combineReducers, configureStore } from "@reduxjs/toolkit";

const appdata = (state = {}, {type, payload}) => {

  if(type == "SET_APP_DATA") {
    return {...state, [payload[0]]: payload[1] }
  }

  if(type == "DELETE_APP_DATA") {
    return {...state, [payload]: undefined }
  }

  return state
}

const reducer = combineReducers({appdata})
const store = configureStore({reducer})

export const setRedux = (key, val) => {
  store.dispatch({ type : "SET_APP_DATA", "payload": [key, val] })
}

export const getRedux = (key = undefined) => {
  return store.getState().appdata[key]
}

export const removeRedux = (key = undefined) => {
  store.dispatch({ type : "DELETE_APP_DATA", "payload": key })
}


export default store;

In component

setRedux("username", "admin")
setRedux("email", "admin@nstest.com")
setRedux("phoneno", "9876543210")

getRedux("email")
getRedux("name")

removeRedux("email")

Routing

npm i react-router-dom 
npx create-react-app routingapp

App.js

import Home from './components/Home';
import Blogs from './components/Blogs';
import Contact from './components/Contact';
import NoPage from './components/NoPage';
import { BrowserRouter, Outlet, Route, Routes } from 'react-router-dom';
import Layout from './components/Layout';

function App() {
  return (
    <>
    <h1>HELLO WORLD</h1>
    <BrowserRouter>
      <Routes>
        <Route path="/admin" element={<Layout />}>
          <Route index element={<Home />} />
          <Route path="contact" element={<Contact />} />
          <Route path="*" element={<NoPage />} />
        </Route>
        <Route path="/user" element={<Layout />}>
          <Route index element={<Home />} />
          <Route path="contact" element={<Contact />} />
          <Route path="blogs" element={<Blogs />} />
          <Route path="test" element={<div>This is test component</div>} />
          <Route path="*" element={<NoPage />} />    
        </Route>
      </Routes>
    </BrowserRouter>
    </>

  );
}

export default App;

Layout.js

import { Outlet, Link } from "react-router-dom";

export default function Layout() {
  return (
    <>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/blogs">Blogs</Link>
          </li>
          <li>
            <Link to="/contact">Contact</Link>
          </li>
        </ul>
      </nav>
      <Outlet />
    </>
  )
}

Outlet is the block where router components get loaded

Datatable

listing.html

<!-- https://datatables.net/examples/server_side/simple.html -->
<!-- https://datatables.net/manual/ajax -->
<!-- https://datatables.net/manual/ajax#Column-data-points -->
<!-- https://stackoverflow.com/questions/64526856/how-to-add-edit-delete-buttons-in-each-row-of-datatable -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
  
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/dataTables.bootstrap5.min.css">

    <script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
    <title>Document</title>
</head>
<body>
<table id="example" class="display table table-striped" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Address</th>
                <th>Salary</th>
                <th>Action</th>
            </tr>
        </thead>
    </table>
</body>
<script>
    $(document).ready(function () {
    $('#example').DataTable({
        processing: true,
        serverSide: true,
        ajax: 'http://ciacloud.in/juhi/rems/get_employees.php',
        columns: [
            { data: 'name'},
            { data: 'address'},
            { data: 'salary'},
            { 
                data: 'id',
                render: (data,type,row) => {
                    console.log({data,type,row})
                   return `<a href='edit_form.php?id=${data}'>Edit</a> | <a href='delete.php?id=${data}'>Delete</a>`;
                 }
            }
        ],
        columnDefs: [
            { orderable: false, targets: -1 },
            {
                "defaultContent": "-",
                "targets": "_all"
            }],
            order: [0,1,2,3],
    });
});
</script>
</html>

get_employees.php

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$params = $_REQUEST;
header('Access-Control-Allow-Origin: *');

$search = isset($params['search']['value'])  && $params['search']['value'] != '' ? $params['search']['value'] : '';

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $where = '';

  if($search !== '')
	  $where = " name LIKE '$search%' ";
  else
	  $where = " 1 = 1 ";

  $sort_columns = ['name', 'address', 'salary'];
  $sort_column_index = $params['order'][0]['column'];
  $sort_order = isset($params['order'][0]['dir']) && $params['order'][0]['dir'] != 1 ? $params['order'][0]['dir'] : 'desc';

  $order_by = " $sort_columns[$sort_column_index] $sort_order";
	
  $offset = $params['start'];
  $limit = $params['length'];

  $sql = "SELECT * FROM employees WHERE $where ORDER BY $order_by LIMIT $offset, $limit";
  $stmt = $conn->prepare($sql);
  $stmt->execute();

  // set the resulting array to associative
  $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
  $employees = $stmt->fetchAll();

} catch(PDOException $e) {
  echo "Error: " . $e->getMessage();
}

$count_sql = "SELECT COUNT(*) FROM employees WHERE $where";
$result = $conn->prepare($count_sql); 
$result->execute(); 
$totalRecords = $result->fetchColumn(); 

$conn = null;


$json_data = array(
		"draw"            => intval( $params['draw'] ),
		"recordsTotal"    => intval( $totalRecords ),
		"recordsFiltered" => intval($totalRecords),
		"data"            => $employees,
		"count_sql"	=> $count_sql,
		"sql"		=> $sql,
	);

echo json_encode($json_data);

Spring Boot

CalcController.java

package com.javatest.demo;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

class MyCalc {
    private int num1;
    private int num2;

    public int getNum1() {
        return num1;
    }
    public void setNum1(int num1) {
        this.num1 = num1;
    }
    public int getNum2() {
        return num2;
    }
    public void setNum2(int num2) {
        this.num2 = num2;
    }
    
    @Override
    public String toString() {
        return "MyCalc [num1=" + num1 + ", num2=" + num2 + "]";
    }
}

@RestController
public class CalcController {


    @RequestMapping("test")
    public String test() {
        return "Testing....";
    }

    /** Read query params */
    @RequestMapping("mycalc")
    @GetMapping
    public String getMet(@RequestParam("num1") int x, @RequestParam int y) {
        return String.format("%s + %s = %s", x, y, x+y);
    }

    /** Read raw json data */
    @PostMapping("mycalc")
    public String postMet(@RequestBody MyCalc obj) {
        int x = obj.getNum1();
        int y = obj.getNum2();

        return String.format("%s - %s = %s", x, y, x - y);
    }

    /** Read form data */
    @PutMapping("mycalc")
    public String putMet(
        @RequestParam("num1") int x,
        @RequestParam("num2") int y) {
        return String.format("%s * %s = %s", x, y, x * y);
    }

    /** Read from raw json */
    @DeleteMapping("mycalc")
    public String deleteMet(@RequestBody MyCalc obj) {
        int x = obj.getNum1();
        int y = obj.getNum2();
        return String.format("%s / %s = %s", x, y, x / y);
    }

}

src/main/resources/application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/<databasename>
spring.datasource.username=<username>
spring.datasource.password=<password>
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver

User.java (POJO/DAO/JPA)

package com.javatest.demo;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name="users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String age;
    private String city;
    private int quota;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public int getQuota() {
        return quota;
    }
    public void setQuota(int quota) {
        this.quota = quota;
    }


    
    // getters and setters

    
}

UserController.java

package com.javatest.demo;


import java.util.List;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.jpa.repository.JpaRepository;

interface UserRepository extends JpaRepository<User, Long> {
    // Custom queries can be defined here
}

@RestController
@RequestMapping("users")
public class UserController {
    
    private final UserRepository userRepository;
    
    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @RequestMapping("")
    public String index() {
        return "I am from index";
    }

    @RequestMapping("listing")
    public List<User> listing() {
        // List<User> users = new ArrayList<>();
        return userRepository.findAll();
    }

    @DeleteMapping("delete/{id}")
    public String deleteUser(@PathVariable Long id) {
        // Check if the user with the specified ID exists
        if (userRepository.existsById(id)) {
            userRepository.deleteById(id);
            return String.format("User %s is deleted successfully", id);
        } else {
            // Handle the case when the user does not exist (e.g., return an error response)
            // You can throw an exception or return an appropriate response based on your application's requirements.
        }
        return "";
    }

    @PostMapping("create")
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }


    @GetMapping("get-single/{id}")
    public User getUserById(@PathVariable Long id) {
        // Use the UserRepository to fetch the user by ID
        return userRepository.findById(id).orElse(null);
    }

    @PutMapping("/update/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
        // Check if the user with the specified ID exists
        userRepository.findById(id).orElse(null);

        // Set the ID of the updated user to the specified ID
        updatedUser.setId(id);

        // Save the updated user to the database
        return userRepository.save(updatedUser);
    }

}

DemoApplication.java (Run this file to serve spring boot application)

package com.javatest.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}

File Structure

.
├── HELP.md
├── mvnw
├── mvnw.cmd
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── javatest
│   │   │           └── demo
│   │   │               ├── CalcController.java
│   │   │               ├── DemoApplication.java
│   │   │               ├── User.java
│   │   │               └── UserController.java
│   │   └── resources
│   │       ├── application.properties
│   │       ├── static
│   │       └── templates
│   └── test
│       └── java
│           └── com
│               └── javatest
│                   └── demo
│                       └── DemoApplicationTests.java
└── target
    ├── classes
    │   ├── application.properties
    │   └── com
    │       └── javatest
    │           └── demo
    │               ├── CalcController.class
    │               ├── DemoApplication.class
    │               ├── MyCalc.class
    │               ├── User.class
    │               ├── UserController.class
    │               └── UserRepository.class
    └── test-classes
        └── com
            └── javatest
                └── demo
                    └── DemoApplicationTests.class

23 directories, 18 files

POC

VSCode Extesnsions

SQL DQL Test 2

  1. list all selling in 2019
  2. count all selling year wise order by selling
  3. select all selling in march month of year 2019
  4. count selling in 22 week of year 2020
  5. select all selling from 1st Feb 2019 to 31st Mar 2019
  6. select all customers who place orders in 2019
  7. select all customers from USA who placed order in 2019
  8. select all customers whose order is on hold
  9. select all customers who placed order in march month only
  10. select top 5 customers from USA (who has maximum orders from country USA)