<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://jinansh230705.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://jinansh230705.github.io/" rel="alternate" type="text/html" /><updated>2025-05-14T06:58:58+00:00</updated><id>https://jinansh230705.github.io/feed.xml</id><title type="html">Jinansh’s Blog</title><subtitle>trying blogs, just for fun</subtitle><author><name>Jinansh Mehta</name></author><entry><title type="html">Command Line Interface (CLI) Usage Guide</title><link href="https://jinansh230705.github.io/2025/05/13/Materio-auth-cli-docs.html" rel="alternate" type="text/html" title="Command Line Interface (CLI) Usage Guide" /><published>2025-05-13T17:00:43+00:00</published><updated>2025-05-13T17:00:43+00:00</updated><id>https://jinansh230705.github.io/2025/05/13/Materio-auth-cli-docs</id><content type="html" xml:base="https://jinansh230705.github.io/2025/05/13/Materio-auth-cli-docs.html"><![CDATA[<p>This guide demonstrates how to interact with the Materio authentication API using command-line tools like <code>curl</code> and tools for script automation.</p>

<h2 id="api-endpoints">API Endpoints</h2>

<p>The authentication system provides the following API endpoints:</p>

<table>
  <thead>
    <tr>
      <th>Endpoint</th>
      <th>Method</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code>/.netlify/functions/signup</code></td>
      <td>POST</td>
      <td>Register a new user</td>
    </tr>
    <tr>
      <td><code>/.netlify/functions/login</code></td>
      <td>POST</td>
      <td>Authenticate a user</td>
    </tr>
    <tr>
      <td><code>/.netlify/functions/forgot-password</code></td>
      <td>POST</td>
      <td>Request password reset</td>
    </tr>
    <tr>
      <td><code>/.netlify/functions/forgot-password</code></td>
      <td>PUT</td>
      <td>Reset password using recovery key</td>
    </tr>
    <tr>
      <td><code>/.netlify/functions/profile</code></td>
      <td>GET</td>
      <td>Get user profile</td>
    </tr>
    <tr>
      <td><code>/.netlify/functions/profile</code></td>
      <td>PUT</td>
      <td>Update user profile</td>
    </tr>
    <tr>
      <td><code>/.netlify/functions/profile</code></td>
      <td>DELETE</td>
      <td>Delete user account</td>
    </tr>
  </tbody>
</table>

<h2 id="base-url">Base URL</h2>

<p><code>https://auth-materioa.netlify.app</code> is the actual auth API base URL.</p>

<h2 id="authentication">Authentication</h2>

<p>Most endpoints require authentication via a JWT token. After logging in, you’ll receive a token that should be passed in the <code>Authorization</code> header in the format: <code>Bearer YOUR_TOKEN</code>.</p>

<h2 id="examples">Examples</h2>

<h3 id="1-user-signup">1. User Signup</h3>

<pre><code class="language-bash">curl -X POST https://auth-materioa.netlify.app/.netlify/functions/signup \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "username": "username123",
    "displayName": "User Name",
    "password": "secure-password"
  }'
</code></pre>

<h4 id="response">Response:</h4>

<pre><code class="language-json">{
  "message": "User created successfully",
  "user": {
    "id": "user-uuid",
    "username": "username123",
    "displayName": "User Name",
    "email": "user@example.com",
    "profilePicture": null,
    "createdAt": "2025-05-13T12:34:56.789Z",
    "updatedAt": "2025-05-13T12:34:56.789Z"
  },
  "token": "your.jwt.token",
  "recoveryKey": "abcdef-123456-ghijkl"
}
</code></pre>

<h3 id="2-user-login">2. User Login</h3>

<pre><code class="language-bash">curl -X POST https://auth-materioa.netlify.app/.netlify/functions/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "user@example.com",
    "password": "secure-password"
  }'
</code></pre>

<blockquote>
  <p>Note: The <code>username</code> field accepts either an email address or a username. The system automatically detects if it’s an email format and searches the appropriate field in the database.</p>
</blockquote>

<h4 id="response-1">Response:</h4>

<pre><code class="language-json">{
  "token": "your.jwt.token",
  "user": {
    "id": "user-uuid",
    "username": "username123",
    "displayName": "User Name",
    "email": "user@example.com",
    "profilePicture": null,
    "createdAt": "2025-05-13T12:34:56.789Z",
    "updatedAt": "2025-05-13T12:34:56.789Z"
  }
}
</code></pre>

<h3 id="3-get-user-profile">3. Get User Profile</h3>

<pre><code class="language-bash">curl -X GET https://auth-materioa.netlify.app/.netlify/functions/profile \
  -H "Authorization: Bearer your.jwt.token"
</code></pre>

<h4 id="response-2">Response:</h4>

<pre><code class="language-json">{
  "user": {
    "id": "user-uuid",
    "username": "username123",
    "displayName": "User Name",
    "email": "user@example.com",
    "profilePicture": null,
    "createdAt": "2025-05-13T12:34:56.789Z",
    "updatedAt": "2025-05-13T12:34:56.789Z"
  }
}
</code></pre>

<h3 id="4-update-user-profile">4. Update User Profile</h3>

<pre><code class="language-bash">curl -X PUT https://auth-materioa.netlify.app/.netlify/functions/profile \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your.jwt.token" \
  -d '{
    "username": "updated_username",
    "displayName": "Updated Name"
  }'
</code></pre>

<h4 id="response-3">Response:</h4>

<pre><code class="language-json">{
  "message": "Profile updated successfully",
  "user": {
    "id": "user-uuid",
    "username": "updated_username",
    "displayName": "Updated Name",
    "email": "user@example.com",
    "profilePicture": null,
    "createdAt": "2025-05-13T12:34:56.789Z",
    "updatedAt": "2025-05-13T14:00:00.000Z"
  }
}
</code></pre>

<h3 id="5-change-password">5. Change Password</h3>

<pre><code class="language-bash">curl -X PUT https://auth-materioa.netlify.app/.netlify/functions/profile \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your.jwt.token" \
  -d '{
    "currentPassword": "secure-password",
    "newPassword": "new-secure-password"
  }'
</code></pre>

<h4 id="response-4">Response:</h4>

<pre><code class="language-json">{
  "message": "Profile updated successfully",
  "user": {
    "id": "user-uuid",
    "username": "username123",
    "displayName": "User Name",
    "email": "user@example.com",
    "profilePicture": null,
    "createdAt": "2025-05-13T12:34:56.789Z",
    "updatedAt": "2025-05-13T15:00:00.000Z"
  }
}
</code></pre>

<h3 id="6-generate-new-recovery-key">6. Generate New Recovery Key</h3>

<pre><code class="language-bash">curl -X PUT https://auth-materioa.netlify.app/.netlify/functions/profile \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your.jwt.token" \
  -d '{
    "currentPassword": "secure-password",
    "generateNewRecoveryKey": true
  }'
</code></pre>

<h4 id="response-5">Response:</h4>

<pre><code class="language-json">{
  "message": "Profile updated successfully",
  "user": {
    "id": "user-uuid",
    "username": "username123",
    "displayName": "User Name",
    "email": "user@example.com",
    "profilePicture": null,
    "createdAt": "2025-05-13T12:34:56.789Z",
    "updatedAt": "2025-05-13T16:00:00.000Z"
  },
  "recoveryKey": "new-recovery-key-123456"
}
</code></pre>

<h3 id="7-reset-password-with-recovery-key">7. Reset Password with Recovery Key</h3>

<pre><code class="language-bash">curl -X PUT https://auth-materioa.netlify.app/.netlify/functions/forgot-password \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "recoveryKey": "abcdef-123456-ghijkl",
    "newPassword": "new-secure-password"
  }'
</code></pre>

<h4 id="response-6">Response:</h4>

<pre><code class="language-json">{
  "message": "Password reset successfully"
}
</code></pre>

<h3 id="8-request-password-reset-get-recovery-key">8. Request Password Reset (Get Recovery Key)</h3>

<pre><code class="language-bash">curl -X POST https://auth-materioa.netlify.app/.netlify/functions/forgot-password \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com"
  }'
</code></pre>

<h4 id="response-7">Response:</h4>

<pre><code class="language-json">{
  "message": "If this email exists in our system, a recovery key has been sent."
}
</code></pre>

<h3 id="9-delete-account">9. Delete Account</h3>

<pre><code class="language-bash">curl -X DELETE https://auth-materioa.netlify.app/.netlify/functions/profile \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your.jwt.token" \
  -d '{
    "password": "secure-password"
  }'
</code></pre>

<h4 id="response-8">Response:</h4>

<pre><code class="language-json">{
  "message": "Account deleted successfully"
}
</code></pre>

<h2 id="bash-script-examples">Bash Script Examples</h2>

<h3 id="user-registration-and-login">User Registration and Login</h3>

<pre><code class="language-bash">#!/bin/bash

# Configuration
API_URL="https://auth-materioa.netlify.app/.netlify/functions"
EMAIL="user@example.com"
PASSWORD="secure-password"
USERNAME="username123"
DISPLAY_NAME="User Name"

# Function to handle API errors
handle_error() {
  if [ $? -ne 0 ]; then
    echo "Error: API call failed"
    exit 1
  fi
  
  if echo "$1" | grep -q "error"; then
    echo "API Error: $(echo "$1" | jq -r '.error // .message')"
    exit 1
  fi
}

# Sign up a new user
echo "Creating new user..."
SIGNUP_RESPONSE=$(curl -s -X POST "$API_URL/signup" \
  -H "Content-Type: application/json" \
  -d "{
    \"email\": \"$EMAIL\",
    \"username\": \"$USERNAME\",
    \"displayName\": \"$DISPLAY_NAME\",
    \"password\": \"$PASSWORD\"
  }")

handle_error "$SIGNUP_RESPONSE"

# Extract token and recovery key
TOKEN=$(echo "$SIGNUP_RESPONSE" | jq -r '.token')
RECOVERY_KEY=$(echo "$SIGNUP_RESPONSE" | jq -r '.recoveryKey')

echo "User created successfully!"
echo "Recovery Key: $RECOVERY_KEY"
echo "JWT Token: $TOKEN"

# Save token to file for later use
echo "$TOKEN" &gt; auth_token.txt

# Get user profile
echo -e "\nFetching user profile..."
PROFILE_RESPONSE=$(curl -s -X GET "$API_URL/profile" \
  -H "Authorization: Bearer $TOKEN")

handle_error "$PROFILE_RESPONSE"

echo "User Profile:"
echo "$PROFILE_RESPONSE" | jq

echo -e "\nAuthentication completed successfully!"
</code></pre>

<h3 id="full-user-management-script">Full User Management Script</h3>

<pre><code class="language-bash">#!/bin/bash

# Configuration
API_URL="https://auth-materioa.netlify.app/.netlify/functions"
TOKEN_FILE="auth_token.txt"

# Command line arguments
ACTION=$1
shift

# Help message
show_help() {
  echo "Usage: ./materio-auth.sh [ACTION] [OPTIONS]"
  echo ""
  echo "Actions:"
  echo "  signup EMAIL USERNAME DISPLAYNAME PASSWORD  - Create a new user"
  echo "  login EMAIL PASSWORD                      - Login existing user"
  echo "  profile                                   - Get current user profile"
  echo "  update-profile USERNAME DISPLAYNAME       - Update user profile"
  echo "  change-password CURRENT_PWD NEW_PWD       - Change user password"
  echo "  gen-recovery                              - Generate new recovery key"
  echo "  reset-password EMAIL RECOVERY_KEY NEW_PWD - Reset password with recovery key"
  echo "  delete-account PASSWORD                   - Delete current user account"
  echo "  help                                      - Show this help message"
}

# Function to handle API errors
handle_error() {
  if [ $? -ne 0 ]; then
    echo "Error: API call failed"
    return 1
  fi
  
  if echo "$1" | grep -q "error"; then
    echo "API Error: $(echo "$1" | jq -r '.error // .message')"
    return 1
  fi
  
  return 0
}

# Get saved token
get_token() {
  if [ ! -f "$TOKEN_FILE" ]; then
    echo "Error: Not logged in. Please login first."
    exit 1
  fi
  
  TOKEN=$(cat "$TOKEN_FILE")
  if [ -z "$TOKEN" ]; then
    echo "Error: Invalid token. Please login again."
    exit 1
  fi
  
  echo "$TOKEN"
}

# Sign up a new user
signup() {
  local email=$1
  local username=$2
  local displayName=$3
  local password=$4
  
  if [ -z "$email" ] || [ -z "$username" ] || [ -z "$displayName" ] || [ -z "$password" ]; then
    echo "Error: Missing required parameters"
    show_help
    exit 1
  fi
  
  echo "Creating new user..."
  SIGNUP_RESPONSE=$(curl -s -X POST "$API_URL/signup" \
    -H "Content-Type: application/json" \
    -d "{
      \"email\": \"$email\",
      \"username\": \"$username\",
      \"displayName\": \"$displayName\",
      \"password\": \"$password\"
    }")
  
  if handle_error "$SIGNUP_RESPONSE"; then
    TOKEN=$(echo "$SIGNUP_RESPONSE" | jq -r '.token')
    RECOVERY_KEY=$(echo "$SIGNUP_RESPONSE" | jq -r '.recoveryKey')
    
    echo "$TOKEN" &gt; "$TOKEN_FILE"
    
    echo "User created successfully!"
    echo "Recovery Key: $RECOVERY_KEY"
    echo "JWT Token saved to $TOKEN_FILE"
  fi
}

# Login user
login() {
  local email=$1
  local password=$2
  
  if [ -z "$email" ] || [ -z "$password" ]; then
    echo "Error: Missing required parameters"
    show_help
    exit 1
  fi
  
  echo "Logging in..."
  LOGIN_RESPONSE=$(curl -s -X POST "$API_URL/login" \
    -H "Content-Type: application/json" \
    -d "{
      \"email\": \"$email\",
      \"password\": \"$password\"
    }")
  
  if handle_error "$LOGIN_RESPONSE"; then
    TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.token')
    echo "$TOKEN" &gt; "$TOKEN_FILE"
    echo "Login successful!"
    echo "JWT Token saved to $TOKEN_FILE"
  fi
}

# Get user profile
get_profile() {
  TOKEN=$(get_token)
  
  echo "Fetching user profile..."
  PROFILE_RESPONSE=$(curl -s -X GET "$API_URL/profile" \
    -H "Authorization: Bearer $TOKEN")
  
  if handle_error "$PROFILE_RESPONSE"; then
    echo "User Profile:"
    echo "$PROFILE_RESPONSE" | jq
  fi
}

# Update user profile
update_profile() {
  local username=$1
  local displayName=$2
  
  if [ -z "$username" ] || [ -z "$displayName" ]; then
    echo "Error: Missing required parameters"
    show_help
    exit 1
  fi
  
  TOKEN=$(get_token)
  
  echo "Updating profile..."
  UPDATE_RESPONSE=$(curl -s -X PUT "$API_URL/profile" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{
      \"username\": \"$username\",
      \"displayName\": \"$displayName\"
    }")
  
  if handle_error "$UPDATE_RESPONSE"; then
    echo "Profile updated successfully!"
    echo "$UPDATE_RESPONSE" | jq
  fi
}

# Change password
change_password() {
  local currentPassword=$1
  local newPassword=$2
  
  if [ -z "$currentPassword" ] || [ -z "$newPassword" ]; then
    echo "Error: Missing required parameters"
    show_help
    exit 1
  fi
  
  TOKEN=$(get_token)
  
  echo "Changing password..."
  CHANGE_RESPONSE=$(curl -s -X PUT "$API_URL/profile" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{
      \"currentPassword\": \"$currentPassword\",
      \"newPassword\": \"$newPassword\"
    }")
  
  if handle_error "$CHANGE_RESPONSE"; then
    echo "Password changed successfully!"
  fi
}

# Generate new recovery key
gen_recovery() {
  local currentPassword=$1
  
  if [ -z "$currentPassword" ]; then
    echo "Error: Current password required"
    show_help
    exit 1
  fi
  
  TOKEN=$(get_token)
  
  echo "Generating new recovery key..."
  RECOVERY_RESPONSE=$(curl -s -X PUT "$API_URL/profile" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{
      \"currentPassword\": \"$currentPassword\",
      \"generateNewRecoveryKey\": true
    }")
  
  if handle_error "$RECOVERY_RESPONSE"; then
    NEW_KEY=$(echo "$RECOVERY_RESPONSE" | jq -r '.recoveryKey')
    echo "New recovery key: $NEW_KEY"
  fi
}

# Reset password with recovery key
reset_password() {
  local email=$1
  local recoveryKey=$2
  local newPassword=$3
  
  if [ -z "$email" ] || [ -z "$recoveryKey" ] || [ -z "$newPassword" ]; then
    echo "Error: Missing required parameters"
    show_help
    exit 1
  fi
  
  echo "Resetting password..."
  RESET_RESPONSE=$(curl -s -X PUT "$API_URL/forgot-password" \
    -H "Content-Type: application/json" \
    -d "{
      \"email\": \"$email\",
      \"recoveryKey\": \"$recoveryKey\",
      \"newPassword\": \"$newPassword\"
    }")
  
  if handle_error "$RESET_RESPONSE"; then
    echo "Password reset successfully!"
  fi
}

# Delete account
delete_account() {
  local password=$1
  
  if [ -z "$password" ]; then
    echo "Error: Password required"
    show_help
    exit 1
  fi
  
  TOKEN=$(get_token)
  
  echo "WARNING: You are about to delete your account. This action cannot be undone."
  read -p "Are you sure? (y/n): " CONFIRM
  
  if [ "$CONFIRM" != "y" ]; then
    echo "Account deletion cancelled."
    exit 0
  fi
  
  echo "Deleting account..."
  DELETE_RESPONSE=$(curl -s -X DELETE "$API_URL/profile" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{
      \"password\": \"$password\"
    }")
  
  if handle_error "$DELETE_RESPONSE"; then
    echo "Account deleted successfully!"
    rm -f "$TOKEN_FILE"
  fi
}

# Main execution logic based on action
case "$ACTION" in
  signup)
    signup "$1" "$2" "$3" "$4"
    ;;
  login)
    login "$1" "$2"
    ;;
  profile)
    get_profile
    ;;
  update-profile)
    update_profile "$1" "$2"
    ;;
  change-password)
    change_password "$1" "$2"
    ;;
  gen-recovery)
    gen_recovery "$1"
    ;;
  reset-password)
    reset_password "$1" "$2" "$3"
    ;;
  delete-account)
    delete_account "$1"
    ;;
  help|--help|-h)
    show_help
    ;;
  *)
    echo "Unknown action: $ACTION"
    show_help
    exit 1
    ;;
esac
</code></pre>

<h2 id="python-script-example">Python Script Example</h2>

<p>Here’s a simple Python client for the auth API:</p>

<pre><code class="language-python">#!/usr/bin/env python3
import argparse
import json
import os
import requests
import sys

# Configuration
API_URL = "https://auth-materioa.netlify.app/.netlify/functions"
TOKEN_FILE = "auth_token.txt"

def save_token(token):
    """Save token to file"""
    with open(TOKEN_FILE, 'w') as f:
        f.write(token)
    print(f"Token saved to {TOKEN_FILE}")

def get_token():
    """Get token from file"""
    try:
        with open(TOKEN_FILE, 'r') as f:
            token = f.read().strip()
            if not token:
                raise ValueError("Empty token")
            return token
    except (IOError, ValueError) as e:
        print(f"Error reading token: {e}")
        print("Please login first")
        sys.exit(1)

def handle_response(response):
    """Handle API response and errors"""
    try:
        response.raise_for_status()
        return response.json()
    except requests.exceptions.HTTPError as e:
        try:
            error_data = response.json()
            error_msg = error_data.get('error') or error_data.get('message') or str(e)
            print(f"API Error: {error_msg}")
        except:
            print(f"HTTP Error: {e}")
        sys.exit(1)
    except requests.exceptions.RequestException as e:
        print(f"Request Error: {e}")
        sys.exit(1)
    except json.JSONDecodeError:
        print("Error: Invalid JSON response")
        sys.exit(1)

def signup(args):
    """Create a new user"""
    data = {
        "email": args.email,
        "username": args.username,
        "displayName": args.display_name,
        "password": args.password
    }
    
    print("Creating new user...")
    response = requests.post(f"{API_URL}/signup", json=data)
    result = handle_response(response)
    
    token = result.get('token')
    recovery_key = result.get('recoveryKey')
    
    save_token(token)
    print("User created successfully!")
    print(f"Recovery Key: {recovery_key}")
    return result

def login(args):
    """Login existing user"""
    data = {
        "email": args.email,
        "password": args.password
    }
    
    print("Logging in...")
    response = requests.post(f"{API_URL}/login", json=data)
    result = handle_response(response)
    
    token = result.get('token')
    save_token(token)
    print("Login successful!")
    return result

def get_profile(args):
    """Get user profile"""
    token = get_token()
    headers = {"Authorization": f"Bearer {token}"}
    
    print("Fetching user profile...")
    response = requests.get(f"{API_URL}/profile", headers=headers)
    result = handle_response(response)
    
    print("User Profile:")
    print(json.dumps(result, indent=2))
    return result

def update_profile(args):
    """Update user profile"""
    token = get_token()
    headers = {"Authorization": f"Bearer {token}"}
    
    data = {}
    if args.username:
        data["username"] = args.username
    if args.display_name:
        data["displayName"] = args.display_name
    
    print("Updating profile...")
    response = requests.put(f"{API_URL}/profile", headers=headers, json=data)
    result = handle_response(response)
    
    print("Profile updated successfully!")
    print(json.dumps(result, indent=2))
    return result

def change_password(args):
    """Change user password"""
    token = get_token()
    headers = {"Authorization": f"Bearer {token}"}
    
    data = {
        "currentPassword": args.current_password,
        "newPassword": args.new_password
    }
    
    print("Changing password...")
    response = requests.put(f"{API_URL}/profile", headers=headers, json=data)
    result = handle_response(response)
    
    print("Password changed successfully!")
    return result

def generate_recovery(args):
    """Generate new recovery key"""
    token = get_token()
    headers = {"Authorization": f"Bearer {token}"}
    
    data = {
        "currentPassword": args.current_password,
        "generateNewRecoveryKey": True
    }
    
    print("Generating new recovery key...")
    response = requests.put(f"{API_URL}/profile", headers=headers, json=data)
    result = handle_response(response)
    
    recovery_key = result.get('recoveryKey')
    print(f"New recovery key: {recovery_key}")
    return result

def reset_password(args):
    """Reset password with recovery key"""
    data = {
        "email": args.email,
        "recoveryKey": args.recovery_key,
        "newPassword": args.new_password
    }
    
    print("Resetting password...")
    response = requests.put(f"{API_URL}/forgot-password", json=data)
    result = handle_response(response)
    
    print("Password reset successfully!")
    return result

def delete_account(args):
    """Delete user account"""
    token = get_token()
    headers = {"Authorization": f"Bearer {token}"}
    
    data = {
        "password": args.password
    }
    
    print("WARNING: You are about to delete your account. This action cannot be undone.")
    confirm = input("Are you sure? (y/n): ")
    
    if confirm.lower() != 'y':
        print("Account deletion cancelled.")
        return
    
    print("Deleting account...")
    response = requests.delete(f"{API_URL}/profile", headers=headers, json=data)
    result = handle_response(response)
    
    print("Account deleted successfully!")
    
    # Remove token file
    if os.path.exists(TOKEN_FILE):
        os.remove(TOKEN_FILE)
    
    return result

def main():
    parser = argparse.ArgumentParser(description="Materio Auth CLI")
    subparsers = parser.add_subparsers(dest='command', help='Command to run')
    
    # Signup parser
    signup_parser = subparsers.add_parser('signup', help='Create a new user')
    signup_parser.add_argument('email', help='User email')
    signup_parser.add_argument('username', help='Username')
    signup_parser.add_argument('display_name', help='Display name')
    signup_parser.add_argument('password', help='Password')
    
    # Login parser
    login_parser = subparsers.add_parser('login', help='Login existing user')
    login_parser.add_argument('email', help='User email')
    login_parser.add_argument('password', help='Password')
    
    # Profile parser
    profile_parser = subparsers.add_parser('profile', help='Get user profile')
    
    # Update profile parser
    update_parser = subparsers.add_parser('update-profile', help='Update user profile')
    update_parser.add_argument('--username', help='New username')
    update_parser.add_argument('--display-name', help='New display name')
    
    # Change password parser
    change_pwd_parser = subparsers.add_parser('change-password', help='Change password')
    change_pwd_parser.add_argument('current_password', help='Current password')
    change_pwd_parser.add_argument('new_password', help='New password')
    
    # Generate recovery key parser
    gen_recovery_parser = subparsers.add_parser('gen-recovery', help='Generate new recovery key')
    gen_recovery_parser.add_argument('current_password', help='Current password')
    
    # Reset password parser
    reset_pwd_parser = subparsers.add_parser('reset-password', help='Reset password with recovery key')
    reset_pwd_parser.add_argument('email', help='User email')
    reset_pwd_parser.add_argument('recovery_key', help='Recovery key')
    reset_pwd_parser.add_argument('new_password', help='New password')
    
    # Delete account parser
    delete_parser = subparsers.add_parser('delete-account', help='Delete user account')
    delete_parser.add_argument('password', help='Current password')
    
    args = parser.parse_args()
    
    # Execute appropriate function based on command
    if args.command == 'signup':
        signup(args)
    elif args.command == 'login':
        login(args)
    elif args.command == 'profile':
        get_profile(args)
    elif args.command == 'update-profile':
        update_profile(args)
    elif args.command == 'change-password':
        change_password(args)
    elif args.command == 'gen-recovery':
        generate_recovery(args)
    elif args.command == 'reset-password':
        reset_password(args)
    elif args.command == 'delete-account':
        delete_account(args)
    else:
        parser.print_help()
        sys.exit(1)

if __name__ == "__main__":
    main()
</code></pre>

<h2 id="usage-examples">Usage Examples</h2>

<h3 id="using-the-python-script">Using the Python Script</h3>

<pre><code class="language-bash"># Installation
chmod +x materio_auth.py

# Sign up
./materio_auth.py signup user@example.com username123 "User Name" secure-password

# Login
./materio_auth.py login user@example.com secure-password

# Get profile
./materio_auth.py profile

# Update profile
./materio_auth.py update-profile --username new_username --display-name "New Name"

# Change password
./materio_auth.py change-password current-password new-password

# Generate new recovery key
./materio_auth.py gen-recovery current-password

# Reset password with recovery key
./materio_auth.py reset-password user@example.com recovery-key-123 new-password

# Delete account
./materio_auth.py delete-account current-password
</code></pre>

<h2 id="security-considerations">Security Considerations</h2>

<ol>
  <li><strong>Token Management</strong>: When using these scripts in production, store tokens securely.</li>
  <li><strong>Password Input</strong>: Consider using hidden input for passwords in production scripts.</li>
  <li><strong>Error Handling</strong>: Add proper error handling based on your specific needs.</li>
  <li><strong>Logging</strong>: Limit or disable logging of sensitive information in production.</li>
</ol>

<p>These examples should help you integrate the authentication system with your existing tools and workflows.</p>]]></content><author><name>Jinansh Mehta</name></author><category term="Other" /><summary type="html"><![CDATA[This guide demonstrates how to interact with the Materio authentication API using command-line tools like curl and tools for script automation.]]></summary></entry><entry><title type="html">Basic Questions</title><link href="https://jinansh230705.github.io/2025/03/31/Computer-Networks-Viva-Questions.html" rel="alternate" type="text/html" title="Basic Questions" /><published>2025-03-31T00:00:00+00:00</published><updated>2025-03-31T00:00:00+00:00</updated><id>https://jinansh230705.github.io/2025/03/31/Computer%20Networks%20Viva%20Questions</id><content type="html" xml:base="https://jinansh230705.github.io/2025/03/31/Computer-Networks-Viva-Questions.html"><![CDATA[<ol>
  <li>
    <p><strong>What is a computer network?</strong><br />
A computer network is a system of interconnected devices that communicate and share resources using protocols over wired or wireless connections.</p>
  </li>
  <li><strong>What are the types of computer networks?</strong>
    <ul>
      <li><strong>LAN (Local Area Network)</strong> – Covers a small area like a home, school, or office.</li>
      <li><strong>MAN (Metropolitan Area Network)</strong> – Covers a city or a large campus.</li>
      <li><strong>WAN (Wide Area Network)</strong> – Covers large geographic areas like countries or continents (e.g., the Internet).</li>
    </ul>
  </li>
  <li><strong>What is the difference between the Internet and an intranet?</strong>
    <ul>
      <li><strong>Internet</strong> is a global network connecting millions of private, public, academic, business, and government networks.</li>
      <li><strong>Intranet</strong> is a private network restricted to an organization for internal communication.</li>
    </ul>
  </li>
  <li><strong>What are the different types of network topologies?</strong>
    <ul>
      <li><strong>Bus</strong> – Uses a single backbone cable; failure in the cable affects the entire network.</li>
      <li><strong>Star</strong> – All devices connect to a central hub or switch; failure of the hub affects the network.</li>
      <li><strong>Ring</strong> – Each device connects to two others, forming a ring; failure in one device can break the loop.</li>
      <li><strong>Mesh</strong> – Every device connects to every other device, ensuring redundancy.</li>
      <li><strong>Hybrid</strong> – A mix of two or more topologies.</li>
    </ul>
  </li>
  <li><strong>What is a MAC address?</strong><br />
A <strong>Media Access Control (MAC) address</strong> is a unique identifier assigned to a network interface card (NIC) by the manufacturer. It is used for communication within a network segment.</li>
</ol>

<hr />

<h3 id="osi--tcpip-model-questions"><strong>OSI &amp; TCP/IP Model Questions</strong></h3>
<ol>
  <li><strong>What are the seven layers of the OSI model?</strong>
    <ul>
      <li><strong>Physical</strong> – Transmission of raw data over the medium.</li>
      <li><strong>Data Link</strong> – Handles error detection and framing (e.g., MAC address).</li>
      <li><strong>Network</strong> – Manages routing and IP addressing.</li>
      <li><strong>Transport</strong> – Ensures reliable transmission (e.g., TCP, UDP).</li>
      <li><strong>Session</strong> – Establishes and maintains sessions between applications.</li>
      <li><strong>Presentation</strong> – Formats, encrypts, and compresses data.</li>
      <li><strong>Application</strong> – Provides network services to end users (e.g., HTTP, FTP).</li>
    </ul>
  </li>
  <li><strong>Compare TCP and UDP.</strong>
    <ul>
      <li><strong>TCP (Transmission Control Protocol)</strong>: Reliable, connection-oriented, ensures data delivery (e.g., web browsing, email).</li>
      <li><strong>UDP (User Datagram Protocol)</strong>: Unreliable, connectionless, faster, used in real-time applications (e.g., video streaming, VoIP).</li>
    </ul>
  </li>
  <li><strong>What is encapsulation in networking?</strong><br />
Encapsulation is the process of adding headers and trailers to data as it moves through the OSI layers before transmission.</li>
</ol>

<hr />

<h3 id="ip-addressing--routing"><strong>IP Addressing &amp; Routing</strong></h3>
<ol>
  <li>
    <p><strong>What is an IP address?</strong><br />
An <strong>IP address</strong> is a numerical label assigned to a device for identification and communication over a network.</p>
  </li>
  <li><strong>Differentiate between IPv4 and IPv6.</strong>
    <ul>
      <li><strong>IPv4</strong>: 32-bit address, uses decimal notation, supports ~4.3 billion addresses.</li>
      <li><strong>IPv6</strong>: 128-bit address, uses hexadecimal notation, supports trillions of addresses.</li>
    </ul>
  </li>
  <li>
    <p><strong>What is a subnet mask?</strong><br />
   A <strong>subnet mask</strong> separates the network and host portions of an IP address to determine which devices belong to the same subnet.</p>
  </li>
  <li><strong>What is the difference between static and dynamic IP addresses?</strong>
    <ul>
      <li><strong>Static IP</strong>: Manually assigned, does not change, used in servers.</li>
      <li><strong>Dynamic IP</strong>: Assigned by <strong>DHCP (Dynamic Host Configuration Protocol)</strong>, changes periodically.</li>
    </ul>
  </li>
  <li>
    <p><strong>What is a default gateway?</strong><br />
   A <strong>default gateway</strong> is a router that connects a local network to external networks, forwarding packets that need to reach other networks.</p>
  </li>
  <li><strong>What is NAT (Network Address Translation)?</strong><br />
   NAT allows multiple devices on a local network to share a single public IP address, improving security and conserving IP addresses.</li>
</ol>

<hr />

<h3 id="networking-devices--protocols"><strong>Networking Devices &amp; Protocols</strong></h3>
<ol>
  <li>
    <p><strong>What is the function of a router?</strong><br />
   A router forwards data between different networks based on IP addresses.</p>
  </li>
  <li>
    <p><strong>What is a switch?</strong><br />
   A switch operates at the <strong>data link layer</strong>, directing data only to the intended recipient, improving efficiency over hubs.</p>
  </li>
  <li><strong>What is the difference between a hub, switch, and router?</strong>
    <ul>
      <li><strong>Hub</strong>: Broadcasts data to all devices in a network.</li>
      <li><strong>Switch</strong>: Sends data only to the intended device.</li>
      <li><strong>Router</strong>: Connects different networks and directs traffic based on IP addresses.</li>
    </ul>
  </li>
  <li>
    <p><strong>What is ARP (Address Resolution Protocol)?</strong><br />
   ARP maps an <strong>IP address to a MAC address</strong> for communication within a network.</p>
  </li>
  <li>
    <p><strong>What is DNS (Domain Name System)?</strong><br />
   DNS translates domain names (e.g., google.com) into IP addresses (e.g., 142.250.183.238).</p>
  </li>
  <li><strong>What is DHCP (Dynamic Host Configuration Protocol)?</strong><br />
   DHCP automatically assigns <strong>IP addresses</strong> to devices in a network.</li>
</ol>

<hr />

<h3 id="security--miscellaneous-questions"><strong>Security &amp; Miscellaneous Questions</strong></h3>
<ol>
  <li>
    <p><strong>What is a firewall?</strong><br />
   A firewall is a security system that monitors and controls incoming and outgoing network traffic based on security rules.</p>
  </li>
  <li>
    <p><strong>What is a VPN (Virtual Private Network)?</strong><br />
   A VPN encrypts data and routes it through a secure server, masking the user’s actual IP address for privacy.</p>
  </li>
  <li>
    <p><strong>What is a proxy server?</strong><br />
   A proxy server acts as an intermediary between a user and the internet, often used for security, anonymity, or content filtering.</p>
  </li>
  <li>
    <p><strong>What is bandwidth?</strong><br />
   Bandwidth is the maximum data transfer rate of a network or internet connection, measured in <strong>bps (bits per second)</strong>.</p>
  </li>
  <li>
    <p><strong>What is latency?</strong><br />
   Latency is the time taken for a data packet to travel from source to destination, usually measured in <strong>milliseconds (ms)</strong>.</p>
  </li>
  <li>
    <p><strong>What is ping?</strong><br />
   <strong>Ping</strong> is a network command that tests the reachability of a host and measures round-trip time (RTT).</p>
  </li>
  <li>
    <p><strong>What is packet switching?</strong><br />
   Packet switching breaks data into packets that travel independently to their destination, allowing efficient and fast transmission (e.g., the Internet).</p>
  </li>
  <li><strong>What is the difference between unicast, multicast, and broadcast?</strong>
    <ul>
      <li><strong>Unicast</strong> – One-to-one communication.</li>
      <li><strong>Multicast</strong> – One-to-many (specific group).</li>
      <li><strong>Broadcast</strong> – One-to-all devices in a network.</li>
    </ul>
  </li>
  <li>
    <p><strong>What is a man-in-the-middle (MITM) attack?</strong><br />
   A MITM attack occurs when an attacker secretly intercepts and possibly alters communication between two parties.</p>
  </li>
  <li><strong>What is a denial-of-service (DoS) attack?</strong><br />
   A DoS attack floods a network or server with excessive traffic to disrupt normal operation.</li>
</ol>

<hr />

<h3 id="bonus-tricky-questions"><strong>Bonus: Tricky Questions</strong></h3>
<ol>
  <li>
    <p><strong>Why is TCP more reliable than UDP?</strong><br />
   TCP provides <strong>error checking, retransmissions, congestion control, and three-way handshake</strong>, ensuring data is delivered correctly.</p>
  </li>
  <li>
    <p><strong>How does HTTPS work?</strong><br />
   HTTPS uses <strong>SSL/TLS encryption</strong> to secure communication between a client and a server, preventing eavesdropping and data tampering.</p>
  </li>
  <li>
    <p><strong>What happens when you type a URL in a browser and press Enter?</strong></p>
    <ul>
      <li>DNS resolves the domain name to an IP address.</li>
      <li>Browser establishes a <strong>TCP connection</strong> with the server.</li>
      <li>HTTP/HTTPS request is sent to the server.</li>
      <li>Server responds with the requested webpage.</li>
      <li>Browser renders the webpage.</li>
    </ul>
  </li>
</ol>

<hr />

<h3 id="network-devices-and-osi-layers"><strong>Network Devices and OSI Layers</strong></h3>

<ol>
  <li><strong>Which device operates at the Physical Layer (Layer 1)?</strong>
    <ul>
      <li><strong>Hubs, Repeaters, Cables (Ethernet, Fiber Optic), and Network Interface Cards (NICs)</strong> work at the <strong>Physical Layer</strong>.</li>
      <li>They deal with raw data transmission, signals, and bit representation.</li>
    </ul>
  </li>
  <li><strong>Which device operates at the Data Link Layer (Layer 2)?</strong>
    <ul>
      <li><strong>Switches and Bridges</strong> operate at the <strong>Data Link Layer</strong>.</li>
      <li>They use <strong>MAC addresses</strong> for forwarding frames within a network.</li>
    </ul>
  </li>
  <li><strong>Which device operates at the Network Layer (Layer 3)?</strong>
    <ul>
      <li><strong>Routers and Layer 3 Switches</strong> operate at the <strong>Network Layer</strong>.</li>
      <li>They use <strong>IP addresses</strong> for routing packets across different networks.</li>
    </ul>
  </li>
  <li><strong>Which device operates at the Transport Layer (Layer 4)?</strong>
    <ul>
      <li><strong>Firewalls and Load Balancers</strong> work at the <strong>Transport Layer</strong>.</li>
      <li>They handle <strong>port numbers, segmentation, and flow control</strong> (e.g., TCP and UDP).</li>
    </ul>
  </li>
  <li><strong>Which device operates at the Session Layer (Layer 5)?</strong>
    <ul>
      <li>Some <strong>Gateways</strong> and <strong>Proxies</strong> operate at the <strong>Session Layer</strong>.</li>
      <li>They establish, maintain, and terminate communication sessions.</li>
    </ul>
  </li>
  <li><strong>Which device operates at the Presentation Layer (Layer 6)?</strong>
    <ul>
      <li><strong>Encryption/Decryption Devices (SSL/TLS)</strong> and <strong>Data Compressors</strong> work at the <strong>Presentation Layer</strong>.</li>
      <li>They format data for compatibility and security.</li>
    </ul>
  </li>
  <li><strong>Which device operates at the Application Layer (Layer 7)?</strong>
    <ul>
      <li><strong>Web Servers, Email Servers, Proxies, and DNS Servers</strong> operate at the <strong>Application Layer</strong>.</li>
      <li>They interact with end-user applications like browsers, email clients, and file transfers.</li>
    </ul>
  </li>
</ol>

<hr />

<h3 id="more-layer-specific-questions"><strong>More Layer-Specific Questions</strong></h3>

<ol>
  <li><strong>What is the role of a repeater in networking?</strong>
    <ul>
      <li>A repeater regenerates and amplifies weak signals to extend transmission distances.</li>
      <li>It operates at <strong>Layer 1 (Physical Layer)</strong>.</li>
    </ul>
  </li>
  <li><strong>What is the main function of a switch?</strong>
    <ul>
      <li>A switch intelligently forwards data to the correct device using <strong>MAC addresses</strong>.</li>
      <li>It operates at <strong>Layer 2 (Data Link Layer)</strong>.</li>
    </ul>
  </li>
  <li><strong>How does a router differ from a switch?</strong>
    <ul>
      <li>A <strong>router</strong> operates at <strong>Layer 3 (Network Layer)</strong> and routes packets based on <strong>IP addresses</strong>.</li>
      <li>A <strong>switch</strong> operates at <strong>Layer 2 (Data Link Layer)</strong> and forwards frames using <strong>MAC addresses</strong>.</li>
    </ul>
  </li>
  <li><strong>What is a Layer 3 switch?</strong>
    <ul>
      <li>A <strong>Layer 3 switch</strong> performs both <strong>switching (Layer 2)</strong> and <strong>routing (Layer 3)</strong> functions.</li>
      <li>It allows communication between different subnets.</li>
    </ul>
  </li>
  <li><strong>How does a firewall work, and at which layer does it operate?</strong>
    <ul>
      <li>A <strong>firewall</strong> monitors and filters incoming/outgoing traffic based on security rules.</li>
      <li>It primarily operates at <strong>Layer 4 (Transport Layer)</strong> but can extend to <strong>Layer 7 (Application Layer)</strong> in advanced configurations.</li>
    </ul>
  </li>
  <li><strong>What is the function of a proxy server, and which OSI layer does it belong to?</strong>
    <ul>
      <li>A <strong>proxy server</strong> acts as an intermediary between clients and servers, providing caching, security, and anonymity.</li>
      <li>It operates at <strong>Layer 7 (Application Layer)</strong>.</li>
    </ul>
  </li>
  <li><strong>At which layer does NAT (Network Address Translation) work?</strong>
    <ul>
      <li>NAT operates at <strong>Layer 3 (Network Layer)</strong> because it modifies IP addresses for internet access.</li>
    </ul>
  </li>
  <li><strong>What layer does DNS work in?</strong>
    <ul>
      <li>DNS (Domain Name System) works at <strong>Layer 7 (Application Layer)</strong> because it translates domain names into IP addresses.</li>
    </ul>
  </li>
  <li><strong>At which OSI layer does SSL/TLS encryption work?</strong>
    <ul>
      <li><strong>SSL/TLS encryption</strong> operates at <strong>Layer 6 (Presentation Layer)</strong> for encryption and decryption.</li>
    </ul>
  </li>
</ol>

<hr />

<h3 id="tricky-layer-questions"><strong>Tricky Layer Questions</strong></h3>

<ol>
  <li><strong>Can a device work at multiple OSI layers?</strong>
    <ul>
      <li>Yes, some devices like <strong>firewalls, proxies, and gateways</strong> operate at multiple layers.</li>
    </ul>
  </li>
  <li><strong>What is the highest OSI layer that a switch can operate at?</strong>
    <ul>
      <li>A basic switch operates at <strong>Layer 2</strong>, but <strong>Layer 3 switches</strong> can function at the <strong>Network Layer</strong>.</li>
    </ul>
  </li>
  <li><strong>What happens if a router fails?</strong>
    <ul>
      <li>Network packets cannot be forwarded between different networks, breaking external communication.</li>
    </ul>
  </li>
  <li><strong>Why are hubs considered obsolete?</strong>
    <ul>
      <li>Hubs send data to all devices, causing network congestion, whereas <strong>switches</strong> send data only to intended recipients.</li>
    </ul>
  </li>
</ol>

<hr />

<p>This should cover all the <strong>must-know viva questions</strong> about <strong>network devices and OSI layers</strong>. Let me know if you need more! 🚀</p>]]></content><author><name>Jinansh Mehta</name></author><category term="Other" /><summary type="html"><![CDATA[What is a computer network? A computer network is a system of interconnected devices that communicate and share resources using protocols over wired or wireless connections.]]></summary></entry><entry><title type="html">Some Links for free O’reilly Design Books</title><link href="https://jinansh230705.github.io/2025/02/02/some-links-for-free-oreilly-design-books.html" rel="alternate" type="text/html" title="Some Links for free O’reilly Design Books" /><published>2025-02-02T16:19:43+00:00</published><updated>2025-02-02T16:19:43+00:00</updated><id>https://jinansh230705.github.io/2025/02/02/some-links-for-free-oreilly-design-books</id><content type="html" xml:base="https://jinansh230705.github.io/2025/02/02/some-links-for-free-oreilly-design-books.html"><![CDATA[<p>Free O’Reilly Design Books</p>

<p>HUGE thanks to O’Reilly for making this resource free.</p>

<h3 id="2017-design-salary-survey-tools-trends-titles-what-pays-and-what-doesnt-for-design-professionals">2017 Design Salary Survey: Tools, Trends, Titles, What Pays (and What Doesn’t) for Design Professionals</h3>
<p><a href="http://www.oreilly.com/design/free/files/2017-design-salary-survey.pdf">Download PDF</a></p>

<h3 id="pair-design-better-together">Pair Design: Better Together</h3>
<p><a href="http://www.oreilly.com/design/free/files/pair-design.pdf">Download PDF</a></p>

<h3 id="design-frontiers-how-voice-sound-wearables-sustainability-and-other-factors-will-shape-experiences">Design Frontiers: How Voice, Sound, Wearables, Sustainability, and Other Factors Will Shape Experiences</h3>
<p><a href="http://www.oreilly.com/design/free/files/design-frontiers.pdf">Download PDF</a></p>

<h3 id="designing-for-mixed-reality-blending-data-ar-and-the-physical-world">Designing for Mixed Reality: Blending Data, AR, and the Physical World</h3>
<p><a href="http://www.oreilly.com/design/free/files/designing-for-mixed-reality.pdf">Download PDF</a></p>

<h3 id="design-in-venture-capital-how-design-drives-investment-and-company-success">Design in Venture Capital: How Design Drives Investment and Company Success</h3>
<p><a href="http://www.oreilly.com/design/free/files/design-in-venture-capital.pdf">Download PDF</a></p>

<h3 id="machine-learning-for-designers">Machine Learning for Designers</h3>
<p><a href="http://www.oreilly.com/design/free/files/machine-learning-for-designers.pdf">Download PDF</a></p>

<h3 id="design-essentials-a-curated-collection-of-chapters-from-the-oreilly-design-library">Design Essentials: A Curated Collection of Chapters from the O’Reilly Design Library</h3>
<p><a href="http://www.oreilly.com/design/free/files/design-fundamentals-volume-2.pdf">Download PDF</a></p>

<h3 id="designing-for-product-strategy-a-curated-collection-of-chapters-from-the-oreilly-design-library">Designing for Product Strategy: A Curated Collection of Chapters from the O’Reilly Design Library</h3>
<p><a href="http://www.oreilly.com/design/free/files/designing-for-product-strategy.pdf">Download PDF</a></p>

<h3 id="prototyping-for-physical-and-digital-products">Prototyping for Physical and Digital Products</h3>
<p><a href="http://www.oreilly.com/design/free/files/prototyping-for-physical-and-digital-products.pdf">Download PDF</a></p>

<h3 id="designing-for-cities-technology-and-the-urban-experience">Designing for Cities: Technology and the Urban Experience</h3>
<p><a href="http://www.oreilly.com/design/free/files/designing-for-cities.pdf">Download PDF</a></p>

<h3 id="designing-for-the-future-a-curated-collection-of-chapters-from-the-oreilly-library">Designing for the Future: A Curated Collection of Chapters from the O’Reilly Library</h3>
<p><a href="http://www.oreilly.com/design/free/files/designing-for-the-future.pdf">Download PDF</a></p>

<h3 id="designing-for-respect-ux-ethics-for-the-digital-age">Designing for Respect: UX Ethics for the Digital Age</h3>
<p><a href="http://www.oreilly.com/design/free/files/designing-for-respect.pdf">Download PDF</a></p>

<h3 id="design-for-voice-interfaces-building-products-that-talk">Design for Voice Interfaces: Building Products that Talk</h3>
<p><a href="http://www.oreilly.com/design/free/files/design-for-voice-interfaces.pdf">Download PDF</a></p>

<h3 id="experience-design-a-curated-collection-of-chapters-from-the-oreilly-design-library">Experience Design: A Curated Collection of Chapters from the O’Reilly Design Library</h3>
<p><a href="http://www.oreilly.com/design/free/files/experience-design.pdf">Download PDF</a></p>

<h3 id="designing-for-the-internet-of-things">Designing for the Internet of Things</h3>
<p><a href="http://www.oreilly.com/design/free/files/designing-for-the-internet-of-things.pdf">Download PDF</a></p>

<h3 id="user-experience-design-for-the-internet-of-things-why-its-more-than-ui-and-industrial-design">User Experience Design for the Internet of Things: Why It’s More than UI and Industrial Design</h3>
<p><a href="http://www.oreilly.com/design/free/files/user-experience-for-iot.pdf">Download PDF</a></p>

<h3 id="design-and-business-a-curated-collection-of-chapters-from-the-oreilly-design-library">Design and Business: A Curated Collection of Chapters from the O’Reilly Design Library</h3>
<p><a href="http://www.oreilly.com/design/free/files/design-and-business.pdf">Download PDF</a></p>]]></content><author><name>Jinansh Mehta</name></author><category term="Other" /><summary type="html"><![CDATA[Free O’Reilly Design Books]]></summary></entry><entry><title type="html">Python Cheatsheet for Beginners</title><link href="https://jinansh230705.github.io/2024/11/24/Python-Cheatsheet.html" rel="alternate" type="text/html" title="Python Cheatsheet for Beginners" /><published>2024-11-24T23:32:00+00:00</published><updated>2024-11-24T23:32:00+00:00</updated><id>https://jinansh230705.github.io/2024/11/24/Python-Cheatsheet</id><content type="html" xml:base="https://jinansh230705.github.io/2024/11/24/Python-Cheatsheet.html"><![CDATA[<h2 id="table-of-contents">Table of Contents</h2>
<ol>
  <li><a href="#introduction">Introduction</a></li>
  <li><a href="#basics">Basics</a></li>
  <li><a href="#data-types">Data Types</a></li>
  <li><a href="#control-flow">Control Flow</a></li>
  <li><a href="#functions">Functions</a></li>
  <li><a href="#modules">Modules</a></li>
  <li><a href="#file-handling">File Handling</a></li>
  <li><a href="#object-oriented-programming">Object-Oriented Programming</a></li>
  <li><a href="#error-handling">Error Handling</a></li>
  <li><a href="#common-built-in-functions">Common Built-in Functions</a></li>
  <li><a href="#advanced-topics">Advanced Topics</a></li>
</ol>

<hr />

<h2 id="introduction">Introduction</h2>
<p>Python is a high-level, versatile programming language known for its simplicity and readability. You can use Python for web development, data analysis, artificial intelligence, and much more.</p>

<hr />

<h2 id="basics">Basics</h2>
<h3 id="printing-and-comments">Printing and Comments</h3>
<p><strong>Printing</strong> is used to display output:</p>
<pre><code class="language-python">print("Hello, World!")  # This prints Hello, World! to the screen
</code></pre>

<p><strong>Comments</strong> are notes for the programmer and ignored by Python:</p>
<pre><code class="language-python"># This is a single-line comment

'''
This is a
multi-line comment
'''
</code></pre>

<h3 id="variables">Variables</h3>
<p>Variables store data. You don’t need to specify the type of a variable.</p>
<pre><code class="language-python">x = 5         # Integer
y = 3.14      # Float
name = "John" # String
is_happy = True  # Boolean

# You can print variables like this:
print("Name:", name)
</code></pre>

<h3 id="rules-for-variable-names">Rules for Variable Names</h3>
<ul>
  <li>Must start with a letter or an underscore.</li>
  <li>Can only contain letters, numbers, and underscores.</li>
  <li>Case-sensitive (<code>Name</code> and <code>name</code> are different).</li>
</ul>

<h3 id="input">Input</h3>
<p>The <code>input</code> function takes user input as a string:</p>
<pre><code class="language-python">user_name = input("What is your name? ")
print(f"Nice to meet you, {user_name}!")
</code></pre>

<hr />

<h2 id="data-types">Data Types</h2>
<p>Python has several data types to store different kinds of data.</p>

<h3 id="numbers">Numbers</h3>
<pre><code class="language-python">a = 10      # Integer
b = 3.14    # Float
c = 2 + 3j  # Complex number
</code></pre>

<h3 id="strings">Strings</h3>
<p>Strings are text data enclosed in quotes:</p>
<pre><code class="language-python">text = "Hello"
print(text.upper())  # Convert to uppercase
print(text[1])       # Access character at index 1
</code></pre>

<p><strong>String Concatenation</strong>:</p>
<pre><code class="language-python">first = "Hello"
second = "World"
combined = first + " " + second
print(combined)
</code></pre>

<p><strong>String Formatting</strong>:</p>
<pre><code class="language-python">name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
</code></pre>

<h3 id="lists">Lists</h3>
<p>Lists are ordered collections of items.</p>
<pre><code class="language-python">numbers = [1, 2, 3, 4]
print(numbers[0])    # Access first item
numbers.append(5)    # Add an item
numbers.pop()        # Remove last item
print(numbers)
</code></pre>

<h3 id="dictionaries">Dictionaries</h3>
<p>Dictionaries store data in key-value pairs.</p>
<pre><code class="language-python">person = {"name": "Alice", "age": 25}
print(person["name"])  # Access value by key
person["age"] = 26     # Update value
print(person)
</code></pre>

<h3 id="tuples">Tuples</h3>
<p>Tuples are immutable lists (cannot be changed after creation).</p>
<pre><code class="language-python">coordinates = (10, 20)
print(coordinates[0])
</code></pre>

<h3 id="sets">Sets</h3>
<p>Sets are collections of unique items.</p>
<pre><code class="language-python">unique_items = {1, 2, 3, 2}
unique_items.add(4)
print(unique_items)  # Output: {1, 2, 3, 4}
</code></pre>

<hr />

<h2 id="control-flow">Control Flow</h2>
<p>Control flow determines the order in which code runs.</p>

<h3 id="if-else">If-Else</h3>
<pre><code class="language-python">age = 18
if age &gt;= 18:
    print("You are an adult.")
elif age &gt; 13:
    print("You are a teenager.")
else:
    print("You are a child.")
</code></pre>

<h3 id="loops">Loops</h3>
<p><strong>For Loop</strong>:</p>
<pre><code class="language-python">for i in range(5):
    print(i)  # Outputs 0, 1, 2, 3, 4
</code></pre>

<p><strong>While Loop</strong>:</p>
<pre><code class="language-python">count = 0
while count &lt; 5:
    print(count)
    count += 1
</code></pre>

<hr />

<h2 id="functions">Functions</h2>
<p>Functions group reusable code.</p>

<h3 id="defining-functions">Defining Functions</h3>
<pre><code class="language-python">def greet(name):
    return f"Hello, {name}!"
print(greet("Alice"))
</code></pre>

<h3 id="default-parameters">Default Parameters</h3>
<pre><code class="language-python">def greet(name="stranger"):
    return f"Hello, {name}!"
print(greet())  # Outputs: Hello, stranger!
</code></pre>

<hr />

<h2 id="modules">Modules</h2>
<p>Modules are libraries of code you can import.</p>

<h3 id="importing-modules">Importing Modules</h3>
<pre><code class="language-python">import math
print(math.sqrt(16))
</code></pre>

<h3 id="installing-external-modules">Installing External Modules</h3>
<p>Use <code>pip</code> to install libraries:</p>
<pre><code class="language-bash">pip install requests
</code></pre>

<hr />

<h2 id="file-handling">File Handling</h2>
<h3 id="reading-and-writing-files">Reading and Writing Files</h3>
<pre><code class="language-python"># Write to a file
with open("example.txt", "w") as file:
    file.write("Hello, file!")

# Read from a file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
</code></pre>

<hr />

<h2 id="object-oriented-programming">Object-Oriented Programming</h2>
<p>OOP allows you to model real-world things using classes and objects.</p>

<h3 id="classes-and-objects">Classes and Objects</h3>
<pre><code class="language-python">class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    def bark(self):
        return f"{self.name} says Woof!"

dog = Dog("Buddy", "Golden Retriever")
print(dog.bark())
</code></pre>

<hr />

<h2 id="error-handling">Error Handling</h2>
<p>Handle errors gracefully with <code>try-except</code> blocks.</p>
<pre><code class="language-python">try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
finally:
    print("Done!")
</code></pre>

<hr />

<h2 id="common-built-in-functions">Common Built-in Functions</h2>
<h3 id="math-functions">Math Functions</h3>
<pre><code class="language-python">max([1, 2, 3])  # Find max
min([1, 2, 3])  # Find min
abs(-10)        # Absolute value
sum([1, 2, 3])  # Sum of elements
</code></pre>

<h3 id="string-functions">String Functions</h3>
<pre><code class="language-python">len("hello")          # String length
"hello".replace("e", "a")  # Replace characters
</code></pre>

<hr />

<h2 id="advanced-topics">Advanced Topics</h2>
<h3 id="list-comprehensions">List Comprehensions</h3>
<pre><code class="language-python">squares = [x**2 for x in range(5)]
print(squares)
</code></pre>

<h3 id="lambda-functions">Lambda Functions</h3>
<pre><code class="language-python">double = lambda x: x * 2
print(double(5))
</code></pre>

<hr />

<h3 id="-materio-2024">© Materio 2024</h3>]]></content><author><name>Jinansh Mehta</name></author><category term="Other" /><summary type="html"><![CDATA[Table of Contents Introduction Basics Data Types Control Flow Functions Modules File Handling Object-Oriented Programming Error Handling Common Built-in Functions Advanced Topics]]></summary></entry><entry><title type="html">Java</title><link href="https://jinansh230705.github.io/2024/08/28/Java-Cheetsheet.html" rel="alternate" type="text/html" title="Java" /><published>2024-08-28T00:00:00+00:00</published><updated>2024-08-28T00:00:00+00:00</updated><id>https://jinansh230705.github.io/2024/08/28/Java%20Cheetsheet</id><content type="html" xml:base="https://jinansh230705.github.io/2024/08/28/Java-Cheetsheet.html"><![CDATA[<p>This cheat sheet is a crash course for Java beginners and help review the basic syntax of the Java language.</p>

<h3 id="getting-started">#Getting started</h3>

<pre><code class="language-java">public class Hello {
  // main method
  public static void main(String[] args)
  {
    // Output: Hello, world!
    System.out.println("Hello, world!");
  }
}
</code></pre>

<pre><code>compiling and running
$ javac Hello.java
$ java Hello
Hello, world!
</code></pre>

<h3 id="variables">variables</h3>

<pre><code class="language-java">int num = 5;
float floatNum = 5.99f;
char letter = 'D';
boolean bool = true;
String site = "quickref.me";
</code></pre>

<h3 id="primitive-data-types">Primitive data types</h3>

<table>
  <thead>
    <tr>
      <th>Data Type</th>
      <th>Size</th>
      <th>Default</th>
      <th>Range</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>byte</td>
      <td>1 byte</td>
      <td>0</td>
      <td>-128 to 127</td>
    </tr>
    <tr>
      <td>short</td>
      <td>2 byte</td>
      <td>0</td>
      <td>-215 to 215-1</td>
    </tr>
    <tr>
      <td>int</td>
      <td>4 byte</td>
      <td>0</td>
      <td>-231 to 231-1</td>
    </tr>
    <tr>
      <td>long</td>
      <td>8 byte</td>
      <td>0</td>
      <td>-263 to 263-1</td>
    </tr>
    <tr>
      <td>float</td>
      <td>4 byte</td>
      <td>0.0f</td>
      <td>N/A</td>
    </tr>
    <tr>
      <td>double</td>
      <td>8 byte</td>
      <td>0.0d</td>
      <td>N/A</td>
    </tr>
    <tr>
      <td>char</td>
      <td>2 byte</td>
      <td>\u0000</td>
      <td>0 to 65535</td>
    </tr>
    <tr>
      <td>boolean</td>
      <td>N/A</td>
      <td>false</td>
      <td>true / false</td>
    </tr>
  </tbody>
</table>

<h3 id="type-casting">Type Casting</h3>

<pre><code class="language-java">// Widening
// byte&lt;short&lt;int&lt;long&lt;float&lt;double
int i = 10;
long l = i;               // 10

// Narrowing
double d = 10.02;
long l = (long)d;         // 10

String.valueOf(10);       // "10"
Integer.parseInt("10");   // 10
Double.parseDouble("10"); // 10.0
</code></pre>

<h3 id="user-input">User Input</h3>

<pre><code class="language-java">Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.println(str);

int num = in.nextInt();
System.out.println(num);
</code></pre>

<h2 id="java-strings">Java Strings</h2>

<h3 id="basic">Basic</h3>

<pre><code class="language-java">String str1 = "value";
String str2 = new String("value");
String str3 = String.valueOf(123);
</code></pre>

<h3 id="concatenation">concatenation</h3>

<pre><code class="language-java">String s = 3 + "str" + 3;     // 3str3
String s = 3 + 3 + "str";     // 6str
String s = "3" + 3 + "str";   // 33str
String s = "3" + "3" + "23";  // 3323
String s = "" + 3 + 3 + "23"; // 3323
String s = 3 + 3 + 23;        // 29
</code></pre>

<h3 id="stringbuilder">StringBuilder</h3>

<p>StringBuilder sb = new StringBuilder(10);</p>

<pre><code>┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
|   |   |   |   |   |   |   |   |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8  9
</code></pre>

<p>sb.append(“QuickRef”);</p>

<pre><code>┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | R | e | f |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9
</code></pre>

<p>sb.delete(5, 9);</p>

<pre><code>┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k |   |   |   |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9
</code></pre>

<p>sb.insert(0, “My “);</p>

<pre><code>┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y |   | Q | u | i | c | k |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9
</code></pre>

<p>sb.append(“!”);</p>

<pre><code>┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y |   | Q | u | i | c | k | ! |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9
</code></pre>

<h3 id="comparison">Comparison</h3>

<pre><code class="language-java">String s1 = new String("QuickRef");
String s2 = new String("QuickRef");

s1 == s2          // false
s1.equals(s2)     // true

"AB".equalsIgnoreCase("ab")  // true
</code></pre>

<h3 id="manipulation">manipulation</h3>

<pre><code class="language-java">String str = "Abcd";

str.toUpperCase();     // ABCD
str.toLowerCase();     // abcd
str.concat("#");       // Abcd#
str.replace("b", "-"); // A-cd

"  abc ".trim();       // abc
"ab".toCharArray();    // {'a', 'b'}
</code></pre>

<h3 id="information">information</h3>

<pre><code class="language-java">String str = "abcd";

str.charAt(2);       // c
str.indexOf("a")     // 0
str.indexOf("z")     // -1
str.length();        // 4
str.toString();      // abcd
str.substring(2);    // cd
str.substring(2,3);  // c
str.contains("c");   // true
str.endsWith("d");   // true
str.startsWith("a"); // true
str.isEmpty();       // false

</code></pre>

<h3 id="immutable">immutable</h3>

<pre><code class="language-java">String str = "hello";
str.concat("world");

// Outputs: hello
System.out.println(str);

</code></pre>

<hr />

<pre><code class="language-java">String str = "hello";
String concat = str.concat("world");

// Outputs: helloworld
System.out.println(concat);
</code></pre>

<p>Once created cannot be modified, any modification creates a new String</p>

<h2 id="java-arrays">Java Arrays</h2>

<h3 id="declare">Declare</h3>

<pre><code class="language-java">int[] a1;
int[] a2 = {1, 2, 3};
int[] a3 = new int[]{1, 2, 3};

int[] a4 = new int[3];
a4[0] = 1;
a4[2] = 2;
a4[3] = 3;
</code></pre>

<h3 id="modify">modify</h3>

<pre><code class="language-java">int[] a = {1, 2, 3};
System.out.println(a[0]); // 1

a[0] = 9;
System.out.println(a[0]); // 9

System.out.println(a.length); // 3
</code></pre>

<h3 id="loop-read--modify">Loop (Read &amp; Modify)</h3>

<pre><code class="language-java">int[] arr = {1, 2, 3};
for (int i=0; i &lt; arr.length; i++) {
    arr[i] = arr[i] * 2;
    System.out.print(arr[i] + " ");
}
// Outputs: 2 4 6
</code></pre>

<h3 id="loop-read">Loop (Read)</h3>

<pre><code class="language-java">String[] arr = {"a", "b", "c"};
for (int a: arr) {
    System.out.print(a + " ");
}
// Outputs: a b c
</code></pre>

<h3 id="multidimensional-arrays">multidimensional Arrays</h3>

<pre><code class="language-java">int[][] matrix = { {1, 2, 3}, {4, 5} };

int x = matrix[1][0];  // 4
// [[1, 2, 3], [4, 5]]
Arrays.deepToString(matrix)

for (int i = 0; i &lt; a.length; ++i) {
  for(int j = 0; j &lt; a[i].length; ++j) {
    System.out.println(a[i][j]);
  }
}
// Outputs: 1 2 3 4 5 6 7
</code></pre>

<h3 id="sort">sort</h3>

<pre><code class="language-java">char[] chars = {'b', 'a', 'c'};
Arrays.sort(chars);

// [a, b, c]
Arrays.toString(chars);
</code></pre>

<hr />

<h2 id="java-conditional">Java Conditional</h2>

<table>
  <thead>
    <tr>
      <th>Operators</th>
      <th> </th>
      <th> </th>
      <th> </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>+</td>
      <td>-</td>
      <td>*</td>
      <td>/</td>
    </tr>
    <tr>
      <td>%</td>
      <td>=</td>
      <td>++</td>
      <td>&gt;=</td>
    </tr>
    <tr>
      <td>!</td>
      <td>==</td>
      <td>!=</td>
      <td>&gt;</td>
    </tr>
    <tr>
      <td>&lt;</td>
      <td>&lt;=</td>
      <td>&amp;&amp;</td>
      <td>^</td>
    </tr>
    <tr>
      <td>?:</td>
      <td>instanceof</td>
      <td>–</td>
      <td>||</td>
    </tr>
    <tr>
      <td>~</td>
      <td>«</td>
      <td>»</td>
      <td>»&gt;</td>
    </tr>
    <tr>
      <td>&amp;</td>
      <td> </td>
      <td> </td>
      <td> </td>
    </tr>
  </tbody>
</table>

<h3 id="if-else">if else</h3>

<pre><code class="language-java">int k = 15;
if (k &gt; 20) {
  System.out.println(1);
} else if (k &gt; 10) {
  System.out.println(2);
} else {
  System.out.println(3);
}
</code></pre>

<h3 id="switch">switch</h3>

<pre><code class="language-java">int month = 3;
String str;
switch (month) {
  case 1:
    str = "January";
    break;
  case 2:
    str = "February";
    break;
  case 3:
    str = "March";
    break;
  default:
    str = "Some other month";
    break;
}

// Outputs: Result March
System.out.println("Result " + str);
</code></pre>

<h3 id="ternary-operator">ternary operator</h3>

<pre><code class="language-java">int a = 10;
int b = 20;
int max = (a &gt; b) ? a : b;

// Outputs: 20
System.out.println(max);
</code></pre>

<h2 id="java-loops">Java loops</h2>

<h3 id="for-loop">for loop</h3>

<pre><code class="language-java">for (int i = 0; i &lt; 10; i++) {
  System.out.print(i);
}
// Outputs: 0123456789

</code></pre>

<hr />

<pre><code class="language-java">for (int i = 0,j = 0; i &lt; 3; i++,j--) {
  System.out.print(j + "|" + i + " ");
}
// Outputs: 0|0 -1|1 -2|2

</code></pre>

<h3 id="enhanced-for-loop">Enhanced For loop</h3>

<pre><code class="language-java">int[] numbers = {1,2,3,4,5};

for (int number: numbers) {
  System.out.print(number);
}
// Outputs: 12345
</code></pre>

<p>Used to loop around array’s or List’s</p>

<h3 id="while-loop">while loop</h3>

<pre><code class="language-java">int count = 0;

while (count &lt; 5) {
  System.out.print(count);
  count++;
}
// Outputs: 01234
</code></pre>

<h3 id="do-while-loop">Do While Loop</h3>

<pre><code class="language-java">int count = 0;

do {
  System.out.print(count);
  count++;
} while (count &lt; 5);
// Outputs: 01234
</code></pre>

<h3 id="continue-statement">continue statement</h3>

<pre><code class="language-java">for (int i = 0; i &lt; 5; i++) {
  if (i == 3) {
    continue;
  }
  System.out.print(i);
}
// Outputs: 01245
</code></pre>

<h3 id="break-statement">break statement</h3>

<pre><code class="language-java">for (int i = 0; i &lt; 5; i++) {
  System.out.print(i);
  if (i == 3) {
    break;
  }
}
// Outputs: 0123
</code></pre>

<p><strong>most imp</strong></p>

<h1 id="jcfjava-collection-framework">JCF(Java collection Framework):</h1>

<ol>
  <li>List Interface
Ordered collection (also known as a sequence).</li>
</ol>

<ul>
  <li>ArrayList: Resizable array implementation.</li>
</ul>

<pre><code class="language-java">List&lt;String&gt; list = new ArrayList&lt;&gt;();
list.add("Element");
list.get(0);
list.size();
list.remove(0);
</code></pre>

<ul>
  <li>LinkedList: Doubly-linked list implementation.</li>
</ul>

<pre><code class="language-java">List&lt;String&gt; list = new LinkedList&lt;&gt;();
list.add("Element");
list.get(0);
list.size();
list.remove(0);
</code></pre>

<ol>
  <li>Set Interface
Collection that cannot contain duplicate elements.</li>
</ol>

<ul>
  <li>HashSet: Hash table implementation.</li>
</ul>

<pre><code class="language-java">Set&lt;String&gt; set = new HashSet&lt;&gt;();
set.add("Element");
set.contains("Element");
set.size();
set.remove("Element");
</code></pre>

<ul>
  <li>LinkedHashSet: Hash table and linked list implementation (orders elements by insertion order).</li>
</ul>

<pre><code class="language-java">Set&lt;String&gt; set = new LinkedHashSet&lt;&gt;();
set.add("Element");
set.contains("Element");
set.size();
set.remove("Element");
</code></pre>

<ul>
  <li>TreeSet: Red-black tree implementation (orders elements based on their values).</li>
</ul>

<pre><code class="language-java">Set&lt;String&gt; set = new TreeSet&lt;&gt;();
set.add("Element");
set.contains("Element");
set.size();
set.remove("Element");
</code></pre>

<ol>
  <li>Queue Interface
Collection designed for holding elements prior to processing.</li>
</ol>

<ul>
  <li>LinkedList (also implements Queue interface):</li>
</ul>

<pre><code class="language-java">Queue&lt;String&gt; queue = new LinkedList&lt;&gt;();
queue.add("Element");
queue.offer("Element"); // Similar to add but does not throw exception
queue.peek(); // Retrieves, but does not remove, the head of this queue
queue.poll(); // Retrieves and removes the head of this queue
</code></pre>

<ul>
  <li>PriorityQueue: Priority heap implementation (orders elements based on their natural ordering or by a Comparator provided at queue construction time).</li>
</ul>

<pre><code class="language-java">Queue&lt;String&gt; queue = new PriorityQueue&lt;&gt;();
queue.add("Element");
queue.offer("Element");
queue.peek();
queue.poll();
</code></pre>

<ol>
  <li>Deque Interface
Double-ended queue, supports element insertion and removal at both ends.</li>
</ol>

<ul>
  <li>ArrayDeque: Resizable array implementation of Deque.</li>
</ul>

<pre><code class="language-java">Deque&lt;String&gt; deque = new ArrayDeque&lt;&gt;();
deque.addFirst("Element");
deque.addLast("Element");
deque.offerFirst("Element");
deque.offerLast("Element");
deque.peekFirst();
deque.peekLast();
deque.pollFirst();
deque.pollLast();

</code></pre>

<ol>
  <li>Map Interface
Object that maps keys to values; cannot contain duplicate keys.</li>
</ol>

<ul>
  <li>HashMap: Hash table implementation.</li>
</ul>

<pre><code class="language-java">Map&lt;String, String&gt; map = new HashMap&lt;&gt;();
map.put("key", "value");
map.get("key");
map.containsKey("key");
map.size();
map.remove("key");
</code></pre>

<ul>
  <li>LinkedHashMap: Hash table and linked list implementation (orders elements by insertion order).</li>
</ul>

<pre><code class="language-java">Map&lt;String, String&gt; map = new LinkedHashMap&lt;&gt;();
map.put("key", "value");
map.get("key");
map.containsKey("key");
map.size();
map.remove("key");
</code></pre>

<ul>
  <li>TreeMap: Red-black tree implementation (orders elements based on their natural ordering or by a Comparator provided at map construction time).</li>
</ul>

<pre><code class="language-java">Map&lt;String, String&gt; map = new TreeMap&lt;&gt;();
map.put("key", "value");
map.get("key");
map.containsKey("key");
map.size();
map.remove("key");
</code></pre>

<ol>
  <li>Stack Class
Last-In-First-Out (LIFO) stack of objects.</li>
</ol>

<pre><code class="language-java">Stack&lt;String&gt; stack = new Stack&lt;&gt;();
stack.push("Element");
stack.peek(); // Looks at the object at the top of this stack without removing it
stack.pop(); // Removes the object at the top of this stack and returns that object
stack.isEmpty(); // Tests if this stack is empty
</code></pre>

<h2 id="additional-methods-and-tips">Additional Methods and Tips</h2>

<ul>
  <li>Iteration over Collections:</li>
</ul>

<pre><code class="language-java">// Using Iterator
Iterator&lt;String&gt; it = list.iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}

// Using enhanced for-loop
for (String element : list) {
    System.out.println(element);
}
</code></pre>

<ul>
  <li>sorting Lists:</li>
</ul>

<pre><code class="language-java">Collections.sort(list);
Collections.sort(list, Comparator.reverseOrder());
</code></pre>

<h1 id="java-interview-questions-for-freshers">Java Interview questions for Freshers</h1>

<details>
<summary>Is Java Platform Independent? Explain</summary>

Yes, Java is a Platform Independent language. Unlike many programming languages javac compiler compiles the program to form a bytecode or .class file. This file is independent of the software or hardware running but needs a JVM(Java Virtual Machine) file preinstalled in the operating system for further execution of the bytecode.

Although JVM is platform dependent, the bytecode can be created on any System and can be executed in any other system despite hardware or software being used which makes Java platform independent.

</details>

<details>
<summary>
Difference between JVM, JRE, and JDK.
</summary>
JVM: JVM also known as Java Virtual Machine is a part of JRE. JVM is a type of interpreter responsible for converting bytecode into machine-readable code. JVM itself is platform dependent but it interprets the bytecode which is the platform-independent reason why Java is platform-independent.

JRE: JRE stands for Java Runtime Environment, it is an installation package that provides an environment to run the Java program or application on any machine.

JDK: JDK stands for Java Development Kit which provides the environment to develop and execute Java programs. JDK is a package that includes two things Development Tools to provide an environment to develop your Java programs and, JRE to execute Java programs or applications.

</details>

<details>

<summary>What is JVM?</summary>
JVM stands for Java Virtual Machine it is a Java interpreter. It is responsible for loading, verifying, and executing the bytecode created in Java.

Although it is platform dependent which means the software of JVM is different for different Operating Systems it plays a vital role in making Java platform Independent.

</details>

<details>
<summary>What is JIT?</summary>
JIT stands for (Just-in-Time) compiler is a part of JRE(Java Runtime Environment), it is used for better performance of the Java applications during run-time. The use of JIT is mentioned in step by step process mentioned below:

- Source code is compiled with javac compiler to form bytecode
- Bytecode is further passed on to JVM
- JIT is a part of JVM, JIT is responsible for compiling bytecode into native machine code at run time.
- The JIT compiler is enabled throughout, while it gets activated when a method is invoked. For a compiled method, the JVM directly calls the compiled code, instead of interpreting it.
- As JVM calls the compiled code that increases the performance and speed of the execution.
</details>

<details>
<summary>Explain public static void main(String args[]) in Java.</summary>

Unlike any other programming language like C, C++, etc. In Java, we declared the main function as a public static void main (String args[]). The meanings of the terms are mentioned below:

public: the public is the access modifier responsible for mentioning who can access the element or the method and what is the limit. It is responsible for making the main function globally available. It is made public so that JVM can invoke it from outside the class as it is not present in the current class.
static: static is a keyword used so that we can use the element without initiating the class so to avoid the unnecessary allocation of the memory.
void: void is a keyword and is used to specify that a method doesn’t return anything. As the main function doesn’t return anything we use void.
main: main represents that the function declared is the main function. It helps JVM to identify that the declared function is the main function.
String args[]: It stores Java command-line arguments and is an array of type java.lang.String class.

</details>

<details>
<summary>What is Java String Pool?</summary>
A Java String Pool is a place in heap memory where all the strings defined in the program are stored. A separate place in a stack is there where the variable storing the string is stored. Whenever we create a new string object, JVM checks for the presence of the object in the String pool, If String is available in the pool, the same object reference is shared with the variable, else a new object is created.

<b>Example:</b>

String str1="Hello";
// "Hello" will be stored in String Pool
// str1 will be stored in stack memory

</details>

<details>
<summary>What will happen if we declare don’t declare the main as static?</summary>
We can declare the main method without using static and without getting any errors. But, the main method will not be treated as the entry point to the application or the program.
</details>

<details>
<summary>What are Packages in Java?
</summary>
Packages in Java can be defined as the grouping of related types of classes, interfaces, etc providing access to protection and namespace management.
</details>

<details>
<summary>Why Packages are used?</summary>
Packages are used in Java in order to prevent naming conflicts, control access, and make searching/locating and usage of classes, interfaces, etc easier.
</details>

<details>

<summary>What are the advantages of Packages in Java?</summary>
There are various advantages of defining packages in Java.

Packages avoid name clashes.
The Package provides easier access control.
We can also have the hidden classes that are not visible outside and are used by the package.
It is easier to locate the related classes.

</details>

<details>
<summary> How many types of packages are there in Java?</summary>
There are two types of packages in Java

- User-defined packages
- Build In packages

</details>

<details>
<summary> Explain different data types in Java.</summary>
There are 2 types of data types in Java as mentioned below:

Primitive Data Type
Non-Primitive Data Type or Object Data type
Primitive Data Type: Primitive data are single values with no special capabilities. There are 8 primitive data types:

- boolean: stores value true or false
- byte: stores an 8-bit signed two’s complement integer
- char: stores a single 16-bit Unicode character
- short: stores a 16-bit signed two’s complement integer
- int: stores a 32-bit signed two’s complement integer
- long: stores a 64-bit two’s complement integer
- float: stores a single-precision 32-bit IEEE 754 floating-point
- double: stores a double-precision 64-bit IEEE 754 floating-point
  Non-Primitive Data Type: Reference Data types will contain a memory address of the variable’s values because it is not able to directly store the values in the memory. Types of Non-Primitive are mentioned below:

- Strings
- Array
- Class
- Object
- Interface

</details>

<details>
<summary>What is the Wrapper class in Java?</summary>
Wrapper, in general, is referred to a larger entity that encapsulates a smaller entity. Here in Java, the wrapper class is an object class that encapsulates the primitive data types.

The primitive data types are the ones from which further data types could be created. For example, integers can further lead to the construction of long, byte, short, etc. On the other hand, the string cannot, hence it is not primitive.

Getting back to the wrapper class, Java contains 8 wrapper classes. They are Boolean, Byte, Short, Integer, Character, Long, Float, and Double. Further, custom wrapper classes can also be created in Java which is similar to the concept of Structure in the C programming language. We create our own wrapper class with the required data types.

</details>

<details>
<summary>Why do we need wrapper classes?</summary>
The wrapper class is an object class that encapsulates the primitive data types, and we need them for the following reasons:

- Wrapper classes are final and immutable
- Provides methods like valueOf(), parseInt(), etc.
- It provides the feature of autoboxing and unboxing.
</details>

<details>
<summary>What is a Class Variable?</summary>
In Java, a class variable (also known as a static variable) is a variable that is declared within a class but outside of any method, constructor, or block. Class variables are declared with the static keyword, and they are shared by all instances (objects) of the class as well as by the class itself. No matter how many objects are derived from a class, each class variable would only exist once.
</details>

<details>
<summary>Explain the difference between instance variable and a class variable.</summary>
<b> Instance Variable </b>:
 A class variable without a static modifier known as an instance variable is typically shared by all instances of the class. These variables can have distinct values among several objects. The contents of an instance variable are completely independent of one object instance from another because they are related to a specific object instance of the class.

**Class Variable**: Class Variable variable can be declared anywhere at the class level using the keyword static. These variables can only have one value when applied to various objects. These variables can be shared by all class members since they are not connected to any specific object of the class.

</details>

<details>
<summary>What is a static variable?</summary>
The static keyword is used to share the same variable or method of a given class. Static variables are the variables that once declared then a single copy of the variable is created and shared among all objects at the class level.
</details>

<details>
<summary> What is the difference between System.out, System.err, and System.in?</summary>
<b>System.out</b>
– It is a PrintStream that is used for writing characters or can be said it can output the data we want to write on the Command Line Interface console/terminal. 
<b>System.err</b>
– It is used to display error messages.

| System.out                                           | System.err                                             |
| ---------------------------------------------------- | ------------------------------------------------------ |
| It will print to the standard out of the system.     | It will print to the standard error.                   |
| It is mostly used to display results on the console. | It is mostly used to output error texts.               |
| It gives output on the console with the default      | It also gives output on the console but                |
| (black) color.                                       | most of the IDEs give it a red color to differentiate. |

System.in – It is an InputStream used to read input from the terminal Window. We can’t use the System.in directly so we use Scanner class for taking input with the system.in.

</details>

<details>
<summary>Difference in the use of print, println, and printf.</summary>
print, println, and printf all are used for printing the elements but print prints all the elements and the cursor remains in the same line. println shifts the cursor to next line. And with printf we can use format identifiers too.
</details>
<pre><code>
</code></pre>
<details>
<summary>What are operators?</summary>
Operators are the special types of symbols used for performing some operations over variables and values.
</details>

<details>
<summary>How many types of operators are available in Java? </summary>
All types of operators in Java are mentioned below:

1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
Postfix operators are considered as the highest precedence according to Java operator precedence.
</details>

<details>
<summary> Explain the difference between &gt;&gt; and &gt;&gt;&gt; operators.</summary>
Operators like &gt;&gt; and &gt;&gt;&gt; seem to be the same but act a bit differently. &gt;&gt; operator shifts the sign bits and the &gt;&gt;&gt; operator is used in shifting out the zero-filled bits.
</details>

<details>
<summary>Which Java operator is right associative?</summary>There is only one operator which is right associative which is = operator.
</details>

<details>
<summary>What is dot operator?</summary>The Dot operator in Java is used to access the instance variables and methods of class objects. It is also used to access classes and sub-packages from the package
</details>

<details>
<summary>What is covariant return type?</summary>
The covariant return type specifies that the return type may vary in the same direction as the subclass. It’s possible to have different return types for an overriding method in the child class, but the child’s return type should be a subtype of the parent’s return type and because of that overriding method becomes variant with respect to the return type.

We use covariant return type because of the following reasons:

Avoids confusing type casts present in the class hierarchy and makes the code readable, usable, and maintainable.
Gives liberty to have more specific return types when overriding methods.
Help in preventing run-time ClassCastExceptions on returns.

</details>

<details>
<summary> What is the transient keyword?</summary>The transient keyword is used at the time of serialization if we don’t want to save the value of a particular variable in a file. When JVM comes across a transient keyword, it ignores the original value of the variable and saves the default value of that variable data type.
</details>

<details>
<summary>What are the differences between String and StringBuffer?</summary>

| Feature                  | String                                                     | StringBuffer                                                  |
| ------------------------ | ---------------------------------------------------------- | ------------------------------------------------------------- |
| Mutability               | Immutable                                                  | Mutable                                                       |
| Thread Safety            | Not thread-safe                                            | Thread-safe                                                   |
| Performance              | Slower in concatenation and modification operations        | Faster in concatenation and modification operations           |
| Use Case                 | Suitable for fixed strings or when immutability is needed  | Suitable for strings that will undergo frequent modifications |
| Memory Allocation        | New memory is allocated for each modification              | Uses the same memory location for modifications               |
| String Pool              | Stored in the string pool if created without `new` keyword | Not stored in the string pool                                 |
| Methods for Modification | `concat()`, `substring()`, `replace()`, etc.               | `append()`, `insert()`, `delete()`, `reverse()`, etc.         |

</details>

<details>
<summary>What are the differences between StringBuffer and StringBuilder?</summary>

**StringBuffer**

StringBuffer provides functionality to work with the strings.
It is thread-safe (two threads can’t call the methods of StringBuffer simultaneously)
Comparatively slow as it is synchronized.
**StringBuilder**

StringBuilder is a class used to build a mutable string.
It is not thread-safe (two threads can call the methods concurrently)
Being non-synchronized, implementation is faster

</details>

<details>
<summary>How is the creation of a String using new() different from that of a literal?</summary>String using new() is different from the literal as when we declare string it stores the elements inside the stack memory whereas when it is declared using new() it allocates a dynamic memory in the heap memory. The object gets created in the heap memory even if the same content object is present.
</details>

<details>
<summary>What is an array in Java?</summary>
An Array in Java is a data structure that is used to store a fixed-size sequence of elements of the same type. Elements of an array can be accessed by their index, which starts from 0 and goes up to a length of minus 1. Array declaration in Java is done with the help of square brackets and size is also specified during the declaration. 
</details>

<details>
<summary>On which memory arrays are created in Java?</summary>Arrays in Java are created in heap memory. When an array is created with the help of a new keyword, memory is allocated in the heap to store the elements of the array. In Java, the heap memory is managed by the Java Virtual Machine(JVM) and it is also shared between all threads of the Java Program. The memory which is no longer in use by the program, JVM uses a garbage collector to reclaim the memory. Arrays in Java are created dynamically which means the size of the array is determined during the runtime of the program. The size of the array is specified during the declaration of the array and it cannot be changed once the array is created.
</details>

<details>
<summary>What is the difference between int array[] and int[] array?</summary>
Both int array[] and int[] array are used to declare an array of integers in java. The only difference between them is on their syntax no functionality difference is present between them.

int arr[] is a C-Style syntax to declare an Array.

int[] arr is a Java-Style syntax to declare an Array.

However, it is generally recommended to use Java-style syntax to declare an Array. As it is easy to read and understand also it is more consistent with other Java language constructs.

</details>

<details>
<summary>How to copy an array in Java?</summary>In Java there are multiple ways to copy an Array based on the requirements.

clone() method in Java: This method in Java is used to create a shallow copy of the given array which means that the new array will share the same memory as the original array.
int[] Arr = { 1, 2, 3, 5, 0};
int[] tempArr = Arr.clone();

arraycopy() method: To create a deep copy of the array we can use this method which creates a new array with the same values as the original array.
int[] Arr = {1, 2, 7, 9, 8};
int[] tempArr = new int[Arr.length];
System.arraycopy(Arr, 0, tempArr, 0, Arr.length);

copyOf() method: This method is used to create a new array with a specific length and copies the contents of the original array to the new array.
int[] Arr = {1, 2, 4, 8};
int[] tempArr = Arrays.copyOf(Arr, Arr.length);

copyOfRange() method: This method is very similar to the copyOf() method in Java, but this method also allows us to specify the range of the elements to copy from the original array.
int[] Arr = {1, 2, 4, 8};
int[] temArr = Arrays.copyOfRange(Arr, 0, Arr.length);

</details>

<details>
<summary>What do you understand by the jagged array?</summary>A jagged Array in Java is just a two-dimensional array in which each row of the array can have a different length. Since all the rows in a 2-d Array have the same length but a jagged array allows more flexibility in the size of each row. This feature is very useful in conditions where the data has varying lengths or when memory usage needs to be optimized.

Syntax:

int[][] Arr = new int[][] {
{1, 2, 8},
{7, 5},
{6, 7, 2, 6}
};

</details>

<p><a href="https://github.com/RupeshDev18/cheatsheet/blob/main/java.md">Source</a></p>]]></content><author><name>Jinansh Mehta</name></author><category term="Other" /><summary type="html"><![CDATA[This cheat sheet is a crash course for Java beginners and help review the basic syntax of the Java language. #Getting started]]></summary></entry><entry><title type="html">Github Pages for Jekyll Help</title><link href="https://jinansh230705.github.io/2024/08/28/some-useful-pages.html" rel="alternate" type="text/html" title="Github Pages for Jekyll Help" /><published>2024-08-28T00:00:00+00:00</published><updated>2024-08-28T00:00:00+00:00</updated><id>https://jinansh230705.github.io/2024/08/28/some-useful-pages</id><content type="html" xml:base="https://jinansh230705.github.io/2024/08/28/some-useful-pages.html"><![CDATA[<ol>
  <li>https://alexander-taran.github.io/2022/06/08/adopting-dark-theme-in-jekyll-blog.html</li>
  <li>https://blog.slowb.ro/dark-theme-for-minima-jekyll/</li>
  <li>https://jekyllrb.com/docs/</li>
  <li>https://stackoverflow.com/questions/68518590/does-minima-dark-skin-work-on-github-pages</li>
</ol>]]></content><author><name>Jinansh Mehta</name></author><category term="Other" /><summary type="html"><![CDATA[https://alexander-taran.github.io/2022/06/08/adopting-dark-theme-in-jekyll-blog.html https://blog.slowb.ro/dark-theme-for-minima-jekyll/ https://jekyllrb.com/docs/ https://stackoverflow.com/questions/68518590/does-minima-dark-skin-work-on-github-pages]]></summary></entry></feed>