Tag: #Informational

  • Universal Temperature Converter Python Script

    This script converts temperatures between Celsius, Fahrenheit, and Kelvin using a simple, menu-driven interface. It allows users to easily input a temperature value and select a conversion option to quickly view the result.

    Click to view script…
    #!/usr/bin/env python3
    
    def celsius_to_fahrenheit(c):
        return (c * 9/5) + 32
    
    def celsius_to_kelvin(c):
        return c + 273.15
    
    def fahrenheit_to_celsius(f):
        return (f - 32) * 5/9
    
    def fahrenheit_to_kelvin(f):
        return (f - 32) * 5/9 + 273.15
    
    def kelvin_to_celsius(k):
        return k - 273.15
    
    def kelvin_to_fahrenheit(k):
        return (k - 273.15) * 9/5 + 32
    
    def main():
        print("Temperature Converter")
        print("---------------------")
        print("Converts temperatures between Celsius, Fahrenheit, and Kelvin.\n")
        
        while True:
            print("Conversion options:")
            print("1. Celsius to Fahrenheit")
            print("2. Celsius to Kelvin")
            print("3. Fahrenheit to Celsius")
            print("4. Fahrenheit to Kelvin")
            print("5. Kelvin to Celsius")
            print("6. Kelvin to Fahrenheit")
            choice = input("Enter your choice (1-6) or 'q' to quit: ")
            
            if choice.lower() == 'q':
                print("Goodbye!")
                break
            
            try:
                choice = int(choice)
            except ValueError:
                print("Invalid input. Please enter a number between 1 and 6, or 'q' to quit.\n")
                continue
            
            if choice < 1 or choice > 6:
                print("Invalid choice. Please choose a valid conversion option.\n")
                continue
            
            temp_input = input("Enter the temperature value: ")
            try:
                temp = float(temp_input)
            except ValueError:
                print("Invalid temperature value. Please enter a numeric value.\n")
                continue
            
            if choice == 1:
                result = celsius_to_fahrenheit(temp)
                print(f"{temp}°C is equal to {result:.2f}°F\n")
            elif choice == 2:
                result = celsius_to_kelvin(temp)
                print(f"{temp}°C is equal to {result:.2f} K\n")
            elif choice == 3:
                result = fahrenheit_to_celsius(temp)
                print(f"{temp}°F is equal to {result:.2f}°C\n")
            elif choice == 4:
                result = fahrenheit_to_kelvin(temp)
                print(f"{temp}°F is equal to {result:.2f} K\n")
            elif choice == 5:
                result = kelvin_to_celsius(temp)
                print(f"{temp} K is equal to {result:.2f}°C\n")
            elif choice == 6:
                result = kelvin_to_fahrenheit(temp)
                print(f"{temp} K is equal to {result:.2f}°F\n")
                
    if __name__ == "__main__":
        main()
    
  • Retrieve Weather for Any City Python Script

    This Python script fetches current weather data for a specified city from wttr.in, converts the temperature to Fahrenheit, and displays the weather condition along with humidity. It provides a quick and API-key-free way to get up-to-date weather information right from your command line.

    Click to view script…
    #!/usr/bin/env python3
    import requests
    
    def get_weather(city):
        url = f"http://wttr.in/{city}?format=j1"
        try:
            response = requests.get(url)
            response.raise_for_status()
            data = response.json()
    
            # Extract current weather information
            current = data['current_condition'][0]
            temp_c = float(current.get('temp_C', 0))
            temp_f = (temp_c * 9/5) + 32  # Convert Celsius to Fahrenheit
            weather_desc = current.get('weatherDesc', [{}])[0].get('value', 'No description')
            humidity = current.get('humidity')
    
            print(f"\nWeather in {city.title()}:")
            print(f"  Temperature: {temp_f:.1f}°F")
            print(f"  Condition: {weather_desc}")
            print(f"  Humidity: {humidity}%")
        except requests.exceptions.RequestException as e:
            print("Error: Could not retrieve weather data.")
            print(e)
    
    if __name__ == "__main__":
        city = input("Enter a city name: ")
        get_weather(city)
    
  • Matrix Rain Effect Python Script

    This Python script simulates the iconic digital rain from The Matrix in your terminal using the curses library. Green characters cascade down your screen, and press any key to exit the mesmerizing effect.

    Click to view script…
    import curses
    import random
    import time
    
    def matrix_rain(stdscr):
        # Hide the cursor and set non-blocking input
        curses.curs_set(0)
        stdscr.nodelay(True)
        stdscr.timeout(50)
        
        # Initialize colors if supported
        if curses.has_colors():
            curses.start_color()
            curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
    
        sh, sw = stdscr.getmaxyx()  # Get screen height and width
        # Initialize each column with a random starting row
        columns = [random.randint(0, sh - 1) for _ in range(sw)]
    
        while True:
            stdscr.erase()  # Clear the screen for fresh drawing
            for x in range(sw):
                y = columns[x]
                # Generate a random printable ASCII character
                char = chr(random.randint(33, 126))
                try:
                    if curses.has_colors():
                        stdscr.addch(y, x, char, curses.color_pair(1))
                    else:
                        stdscr.addch(y, x, char)
                except curses.error:
                    # Ignore errors when drawing outside of the screen bounds
                    pass
    
                # Move the column down; reset to the top if at the bottom
                columns[x] = y + 1 if y < sh - 1 else 0
    
            stdscr.refresh()
            time.sleep(0.05)  # Adjust the speed of the rain
    
            # Exit the loop if any key is pressed
            if stdscr.getch() != -1:
                break
    
    def main():
        curses.wrapper(matrix_rain)
    
    if __name__ == '__main__':
        main()
  • Mac System Specs and Performance Dashboard Bash Script

    This script provides an organized summary of your Mac’s system information and performance metrics—including OS details, CPU specifications, memory size, disk usage, uptime, and battery status.

    Click to view script…
    #!/bin/bash
    # system_specs.sh - Display Mac system specs and performance info
    
    # Clear the terminal for a fresh display
    clear
    
    echo "======================================"
    echo "   Mac System Specs and Performance   "
    echo "======================================"
    
    # Operating System Information
    os_name=$(sw_vers -productName)
    os_version=$(sw_vers -productVersion)
    build_version=$(sw_vers -buildVersion)
    echo "Operating System: $os_name $os_version (Build $build_version)"
    
    # Computer Name (if set)
    computer_name=$(scutil --get ComputerName 2>/dev/null)
    if [ -n "$computer_name" ]; then
        echo "Computer Name: $computer_name"
    fi
    
    echo "--------------------------------------"
    
    # CPU Information
    cpu_brand=$(sysctl -n machdep.cpu.brand_string)
    physical_cpu=$(sysctl -n hw.physicalcpu)
    logical_cpu=$(sysctl -n hw.logicalcpu)
    echo "CPU: $cpu_brand"
    echo "Physical Cores: $physical_cpu"
    echo "Logical Cores: $logical_cpu"
    
    echo "--------------------------------------"
    
    # Memory (RAM) Information
    mem_bytes=$(sysctl -n hw.memsize)
    # Convert bytes to gigabytes (1GB = 1073741824 bytes)
    mem_gb=$(echo "scale=2; $mem_bytes/1073741824" | bc)
    echo "Memory (RAM): $mem_gb GB"
    
    echo "--------------------------------------"
    
    # Disk Usage for the Root Partition
    echo "Disk Usage (Root Partition):"
    # Display header and the line for '/' partition
    df -h / | awk 'NR==1 || $NF=="/"'
    echo "--------------------------------------"
    
    # Uptime and Load Average
    echo "Uptime and Load Average:"
    uptime
    echo "--------------------------------------"
    
    # Battery Information (if available)
    if command -v pmset &> /dev/null; then
        battery_info=$(pmset -g batt | head -1)
        echo "Battery Info: $battery_info"
    fi
    
    echo "======================================"