Tag: #Informational

  • iTunes Top Songs & Albums Purchases Python Script

    This Python script fetches and displays the current top songs or albums based on purchases from the iTunes Store. Users can select a category and the number of entries to view, with rankings clearly labeled to reflect purchase trends as of the check date.

    Click to view script…
    #!/usr/bin/env python3
    # iTunes Top Purchases Scraper
    # Purpose: Fetches and displays the current top songs or albums based on purchases from the iTunes Store.
    # Note: This script shows purchase-based rankings, not streaming data.
    
    import requests
    from datetime import datetime
    
    # Define categories with their display names and RSS feed paths
    categories = {
        1: {'name': 'Top Songs (Purchases)', 'path': 'topsongs'},
        2: {'name': 'Top Albums (Purchases)', 'path': 'topalbums'}
    }
    
    def main():
        """Main function to run the iTunes Top Purchases Scraper."""
        # Inform the user that the data reflects purchases, not streaming
        print("Welcome! This script shows top songs or albums based on purchases from the iTunes Store (not streaming data).")
        
        # Display category options
        print("\nSelect a category:")
        for key, value in categories.items():
            print(f"{key}. {value['name']}")
        
        # Get and validate category choice
        choice_input = input("Enter the number of your choice: ")
        try:
            choice = int(choice_input)
            if choice not in categories:
                raise ValueError
        except ValueError:
            print("Invalid choice. Please run the script again and enter 1 or 2.")
            return
        
        category = categories[choice]
        category_name = category['name']
        
        # Get and validate number of entries
        limit_input = input("Enter the number of entries to display (1-100, default 10): ")
        if limit_input.strip() == "":
            limit = 10
        else:
            try:
                limit = int(limit_input)
                if limit < 1 or limit > 100:
                    print("Limit must be between 1 and 100. Using default of 10.")
                    limit = 10
            except ValueError:
                print("Invalid input. Using default of 10.")
                limit = 10
        
        # Construct the RSS feed URL
        url = f"https://itunes.apple.com/us/rss/{category['path']}/limit={limit}/json"
        
        # Record the current date and time
        check_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # Fetch data from the iTunes RSS feed
        try:
            response = requests.get(url)
            response.raise_for_status()
            data = response.json()
        except requests.exceptions.RequestException as e:
            print(f"Error fetching data: {e}")
            return
        
        # Extract entries from the JSON response
        feed = data.get('feed', {})
        entries = feed.get('entry', [])
        
        if not entries:
            print("No data available for this category.")
            return
        
        # Display the results
        print(f"\n{category_name} as of {check_date}")
        print(f"{'Rank':<5} {'Name':<50} {'Artist':<30}")
        print("-" * 85)
        
        for i, entry in enumerate(entries, start=1):
            name = entry.get('im:name', {}).get('label', 'N/A')
            artist = entry.get('im:artist', {}).get('label', 'N/A')
            print(f"{i:<5} {name:<50} {artist:<30}")
    
    if __name__ == '__main__':
        main()
  • iOS App Store Comparison Tool Python Script

    This Python script enables users to compare multiple iOS apps by inputting their names, retrieving details like ratings, versions, and descriptions from the iTunes Search API. It displays a side-by-side overview of each app’s name, short description, rating count, rating stars, current version, and the date the check was initiated.

    Click to view script…
    import requests
    from datetime import datetime
    
    # Initialize a list to store app names
    app_names = []
    while True:
        app_name = input("Enter app name: ")
        app_names.append(app_name)
        another = input("Do you want to add another app? (y/n): ").lower()
        if another != 'y':
            break
    
    # Record the current date and time when the check is initiated
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # Initialize a list to store app data
    apps_data = []
    
    # Query the iTunes Search API for each app
    for app_name in app_names:
        try:
            response = requests.get(
                "https://itunes.apple.com/search",
                params={"term": app_name, "country": "us", "media": "software"}
            )
            response.raise_for_status()  # Raise an exception for HTTP errors
            data = response.json()
    
            if data["resultCount"] > 0:
                # Take the first result as the most relevant app
                app = data["results"][0]
                
                # Create a short description from the first 20 words of the full description
                words = app["description"].split()
                short_description = " ".join(words[:20]) + "..." if len(words) > 20 else " ".join(words)
                
                # Get the rating stars, formatting to one decimal place if available
                rating_stars = app.get("averageUserRating", "N/A")
                if rating_stars != "N/A":
                    rating_stars = f"{rating_stars:.1f}"
                
                # Compile the app information
                app_info = {
                    "app_name": app["trackName"],
                    "short_description": short_description,
                    "rating_count": app.get("userRatingCount", 0),
                    "rating_stars": rating_stars,
                    "current_version": app.get("version", "N/A"),
                    "check_date": current_time
                }
            else:
                app_info = {
                    "app_name": app_name,
                    "error": "App not found"
                }
        except requests.exceptions.RequestException as e:
            app_info = {
                "app_name": app_name,
                "error": f"Error fetching data: {e}"
            }
        
        apps_data.append(app_info)
    
    # Display the information for all apps
    for app_info in apps_data:
        if "error" in app_info:
            print(f"App Name: {app_info['app_name']}")
            print(f"Error: {app_info['error']}")
        else:
            print(f"App Name: {app_info['app_name']}")
            print(f"Short Description: {app_info['short_description']}")
            print(f"Rating Count: {app_info['rating_count']}")
            print(f"Rating Stars: {app_info['rating_stars']}")
            print(f"Current Version: {app_info['current_version']}")
            print(f"Check Date: {app_info['check_date']}")
        print("-" * 40)
  • iOS App Store Rating Checker Python Script

    This Python script allows users to input an iOS app name and retrieves its overall rating and total number of ratings from the iTunes Search API. It also displays the current date and time when the data was checked, providing a simple way to monitor app performance on the App Store.

    Click to view script…
    import requests
    from datetime import datetime
    
    # Get the app name from the user
    app_name = input("Enter the app name: ")
    
    # Base URL for the iTunes Search API
    base_url = "https://itunes.apple.com/search"
    
    # Parameters for the API request
    params = {
        "term": app_name,
        "country": "us",
        "media": "software"
    }
    
    try:
        # Send GET request to the API
        response = requests.get(base_url, params=params)
        response.raise_for_status()  # Raise an exception for HTTP errors
    
        # Parse the JSON response
        data = response.json()
    
        # Check if any apps were found
        if data["resultCount"] > 0:
            # Extract the first app's data
            app = data["results"][0]
            rating = app.get("averageUserRating", "N/A")
            if rating != "N/A":
                rating = f"{rating:.1f}"  # Format rating to one decimal place
            count = app.get("userRatingCount", "N/A")
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
            # Print the results
            print(f"App Name: {app['trackName']}")
            print(f"Overall Rating: {rating}")
            print(f"Total Ratings: {count}")
            print(f"Date Checked: {current_time}")
        else:
            print("No apps found with that name.")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data: {e}")
  • Apple Product Spec Scraper Python Script

    This Python script searches Wikipedia for an Apple product by name, extracts key specifications like dimensions, weight, and camera details from the infobox, and formats the data for easy reading, with special handling for model-specific variations like “Pro” and “Pro Max.”

    This script relies on four Python libraries: requests fetches data from Wikipedia’s API, BeautifulSoup (from bs4) parses the HTML content to extract infobox details, sys handles command-line arguments for the product name input, and re provides regular expression support to clean up text by removing citation markers and extra whitespace. To install the external libraries, use pip: run pip install requests beautifulsoup4 in your terminal or command prompt, while sys and re are part of Python’s standard library and require no additional installation.

    Click to view script…
    import requests
    from bs4 import BeautifulSoup
    import sys
    import re
    
    # Define the fields we want to show
    desired_fields = [
        "First released",
        "Dimensions",
        "Weight",
        "Operating system",
        "System-on-chip",
        "Memory",
        "Storage",
        "Battery",
        "Rear camera",
        "Front camera",
        "Display",
    ]
    
    # Define fields that have model-specific values (e.g., Pro vs. Pro Max)
    model_specific_fields = ["Dimensions", "Weight", "Battery", "Display"]
    
    def search_wikipedia(query):
        """Search Wikipedia for the given query and return the title of the first result."""
        search_url = "https://en.wikipedia.org/w/api.php"
        params = {
            "action": "query",
            "list": "search",
            "srsearch": query,
            "format": "json"
        }
        response = requests.get(search_url, params=params)
        data = response.json()
        if data['query']['search']:
            return data['query']['search'][0]['title']
        return None
    
    def get_page_html(title):
        """Retrieve the HTML content of the Wikipedia page with the given title."""
        parse_url = "https://en.wikipedia.org/w/api.php"
        params = {
            "action": "parse",
            "page": title,
            "format": "json"
        }
        response = requests.get(parse_url, params=params)
        data = response.json()
        return data['parse']['text']['*']
    
    def extract_infobox(html):
        """Extract key-value pairs from the infobox in the HTML content."""
        soup = BeautifulSoup(html, 'html.parser')
        infobox = soup.find('table', {'class': 'infobox'})
        if infobox:
            rows = infobox.find_all('tr')
            info = {}
            for row in rows:
                header = row.find('th')
                data = row.find('td')
                if header and data:
                    key = header.text.strip()
                    value = data.text.strip()
                    info[key] = value
            return info
        return None
    
    def clean_text(text):
        """Remove citation numbers and extra spaces from the text."""
        return re.sub(r'\[\d+\]', '', text).strip()
    
    def format_model_values(value):
        """Format model-specific values for fields like dimensions, weight, etc."""
        if "Pro Max:" in value:
            pro_part, pro_max_part = value.split("Pro Max:", 1)
            pro_value = clean_text(pro_part.replace("Pro: ", "", 1).strip())
            pro_max_value = clean_text(pro_max_part.strip())
            return f"- Pro: {pro_value}\n- Pro Max: {pro_max_value}"
        elif "16 Pro Max:" in value:
            pro_part, pro_max_part = value.split("16 Pro Max:", 1)
            pro_value = clean_text(pro_part.replace("16 Pro: ", "", 1).strip())
            pro_max_value = clean_text(pro_max_part.strip())
            return f"- 16 Pro: {pro_value}\n- 16 Pro Max: {pro_max_value}"
        return clean_text(value)
    
    def main():
        if len(sys.argv) < 2:
            print("Usage: python3 apple_product_finder.py <product name>")
            sys.exit(1)
        product_name = " ".join(sys.argv[1:])
        title = search_wikipedia(product_name + " Apple")
        if not title:
            print("No product found.")
            return
        html = get_page_html(title)
        infobox = extract_infobox(html)
        if infobox:
            print(f"Key information for {title}:")
            for key in desired_fields:
                if key in infobox:
                    value = infobox[key]
                    if key in model_specific_fields:
                        formatted_value = format_model_values(value)
                        print(f"{key}:\n{formatted_value}")
                    else:
                        print(f"{key}: {clean_text(value)}")
        else:
            print("No infobox found for this product.")
    
    if __name__ == "__main__":
        main()
  • iTunes TV Show Seasons Release Finder Swift Script

    This Swift script lets you search for a TV show by title from the macOS Terminal, displaying its initial release date and a chronological list of seasons with their release dates, all pulled from the iTunes Store API. Perfect for TV enthusiasts wanting quick access to show timelines!

    Click to view script…
    #!/usr/bin/env swift
    
    import Foundation
    
    // Define structs to match the iTunes Search API response for TV seasons
    struct SearchResponse: Codable {
        let resultCount: Int
        let results: [TVSeason]
    }
    
    struct TVSeason: Codable {
        let artistName: String      // The TV show's name
        let collectionName: String  // The season's name
        let releaseDate: Date       // The season's release date
    }
    
    // Check for command-line arguments
    if CommandLine.arguments.count < 2 {
        print("Usage: \(CommandLine.arguments[0]) <tv show title>")
        exit(1)
    }
    
    // Combine all arguments after the script name into a single TV show title
    let tvShowTitle = CommandLine.arguments[1...].joined(separator: " ")
    
    // Construct the API URL for searching TV seasons
    let baseURL = "https://itunes.apple.com/search"
    let queryItems = [
        URLQueryItem(name: "term", value: tvShowTitle),
        URLQueryItem(name: "media", value: "tvShow"),
        URLQueryItem(name: "entity", value: "tvSeason"),
        URLQueryItem(name: "country", value: "us")
    ]
    var urlComponents = URLComponents(string: baseURL)!
    urlComponents.queryItems = queryItems
    guard let url = urlComponents.url else {
        print("Invalid URL.")
        exit(1)
    }
    
    // Set up semaphore to handle asynchronous URLSession task
    let semaphore = DispatchSemaphore(value: 0)
    var exitCode: Int32 = 0  // Exit code for the script
    
    // Perform the network request
    let session = URLSession.shared
    let task = session.dataTask(with: url) { data, response, error in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            exitCode = 1
        } else if let data = data {
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601 // Handle ISO 8601 date format
            do {
                let searchResponse = try decoder.decode(SearchResponse.self, from: data)
                if searchResponse.resultCount > 0 {
                    let seasons = searchResponse.results
                    let showName = seasons[0].artistName
                    // Sort seasons by release date
                    let sortedSeasons = seasons.sorted { $0.releaseDate < $1.releaseDate }
                    // Display show info and initial release date
                    if let firstReleaseDate = sortedSeasons.first?.releaseDate {
                        let dateFormatter = DateFormatter()
                        dateFormatter.dateStyle = .long
                        let formattedDate = dateFormatter.string(from: firstReleaseDate)
                        print("TV Show: \(showName)")
                        print("Initial Release Date: \(formattedDate)")
                    } else {
                        print("TV Show: \(showName)")
                        print("Release date not available.")
                    }
                    // List all seasons
                    print("Seasons:")
                    for season in sortedSeasons {
                        let seasonDateFormatter = DateFormatter()
                        seasonDateFormatter.dateStyle = .long
                        let seasonFormattedDate = seasonDateFormatter.string(from: season.releaseDate)
                        print("- \(season.collectionName): \(seasonFormattedDate)")
                    }
                    exitCode = 0
                } else {
                    print("No TV show found for \"\(tvShowTitle)\".")
                    exitCode = 1
                }
            } catch {
                print("Error decoding JSON: \(error)")
                exitCode = 1
            }
        } else {
            print("No data received.")
            exitCode = 1
        }
        semaphore.signal() // Signal completion
    }
    
    // Start the task and wait for it to complete
    task.resume()
    semaphore.wait()
    exit(exitCode)

  • iTunes Movie Release Lookup Swift Script

    This Swift script searches the iTunes Store for a movie by title, provided as a command-line argument, and prints the release date of the first matching result. It uses the iTunes Search API and handles errors gracefully with appropriate exit codes

    Click to view script…
    #!/usr/bin/env swift
    
    import Foundation
    
    // Define structs to match the iTunes Search API response
    struct SearchResponse: Codable {
        let resultCount: Int
        let results: [Movie]
    }
    
    struct Movie: Codable {
        let trackName: String
        let releaseDate: Date
    }
    
    // Check for command-line arguments
    if CommandLine.arguments.count < 2 {
        print("Usage: \(CommandLine.arguments[0]) <movie title>")
        exit(1)
    }
    
    // Combine all arguments after the script name into a single movie title
    let movieTitle = CommandLine.arguments[1...].joined(separator: " ")
    
    // Construct the API URL
    let baseURL = "https://itunes.apple.com/search"
    let queryItems = [
        URLQueryItem(name: "term", value: movieTitle),
        URLQueryItem(name: "media", value: "movie"),
        URLQueryItem(name: "entity", value: "movie")
    ]
    var urlComponents = URLComponents(string: baseURL)!
    urlComponents.queryItems = queryItems
    guard let url = urlComponents.url else {
        print("Invalid URL.")
        exit(1)
    }
    
    // Set up semaphore to handle asynchronous URLSession task
    let semaphore = DispatchSemaphore(value: 0)
    var exitCode: Int32 = 0  // Explicitly typed as Int32 to match exit() requirement
    
    // Perform the network request
    let session = URLSession.shared
    let task = session.dataTask(with: url) { data, response, error in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            exitCode = 1
        } else if let data = data {
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601 // Handle ISO 8601 date format from API
            do {
                let searchResponse = try decoder.decode(SearchResponse.self, from: data)
                if searchResponse.resultCount > 0 {
                    let movie = searchResponse.results[0] // Take the first result
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateStyle = .long
                    let formattedDate = dateFormatter.string(from: movie.releaseDate)
                    print("Release date of \(movie.trackName): \(formattedDate)")
                    exitCode = 0
                } else {
                    print("No results found for \"\(movieTitle)\".")
                    exitCode = 1
                }
            } catch {
                print("Error decoding JSON: \(error)")
                exitCode = 1
            }
        } else {
            print("No data received.")
            exitCode = 1
        }
        semaphore.signal() // Signal completion of the network task
    }
    
    // Start the task and wait for it to complete
    task.resume()
    semaphore.wait()
    exit(exitCode)
  • macOS User Login and Uptime Report Bash Script

    This script provides system administrators with a clear overview of the system’s current uptime and detailed last login information for human user accounts (UID ≥ 500). It displays key details such as the terminal, login date, login time, and session status for each account.

    Click to view script…
    #!/bin/bash
    # Title: Detailed macOS User Last Login Checker with System Uptime
    # Description:
    # This script lists human user accounts (UID ≥ 500) on macOS and displays detailed information about their last login session.
    # It also shows the current system uptime at the top.
    #
    # The output includes:
    #   - System Uptime: How long the machine has been running since the last boot.
    #   - Username     : The account name.
    #   - Terminal     : The terminal device used during login.
    #   - Login Date   : The date of the login (Day Month Date).
    #   - Login Time   : The time when the login occurred.
    #   - Login Status : Indicates if the session is still active or has ended.
    #
    # Note: "Never logged in" is shown if no login record exists.
    #
    # Retrieve and display system uptime
    systemUptime=$(uptime)
    echo "System Uptime: $systemUptime"
    echo ""
    
    # Print header for the login details
    echo "Username | Terminal | Login Date       | Login Time | Login Status"
    echo "---------------------------------------------------------------------"
    
    # List users with their UniqueIDs and process each one.
    dscl . -list /Users UniqueID | while read username uid; do
        if [ "$uid" -ge 500 ]; then
            # Retrieve the most recent login record for the user
            loginInfo=$(last -1 "$username" | head -n 1)
            
            # Check if there is a valid login record
            if echo "$loginInfo" | grep -q "wtmp begins"; then
                echo "$username |    -     |       -        |     -    | Never logged in"
            else
                # Parse the login record:
                #   Field 1: Username (redundant here)
                #   Field 2: Terminal (e.g., ttys000)
                #   Fields 3-5: Login Date (e.g., "Mon Feb 17")
                #   Field 6: Login Time (e.g., "05:44")
                #   Fields 7+: Login Status (e.g., "still logged in" or the session end time)
                terminal=$(echo "$loginInfo" | awk '{print $2}')
                login_date=$(echo "$loginInfo" | awk '{print $3, $4, $5}')
                login_time=$(echo "$loginInfo" | awk '{print $6}')
                login_status=$(echo "$loginInfo" | cut -d' ' -f7-)
                
                # Output the parsed details in a table-like format
                printf "%-8s | %-8s | %-16s | %-10s | %s\n" "$username" "$terminal" "$login_date" "$login_time" "$login_status"
            fi
        fi
    done
    
    # Legend:
    #   System Uptime - How long the system has been running since the last boot.
    #   Username      - The account name.
    #   Terminal      - The terminal device used during login.
    #   Login Date    - The date of the login (Day Month Date).
    #   Login Time    - The time of the login.
    #   Login Status  - The current status of the login session.
  • Enhanced macOS User Account Details Bash Script

    This Bash script retrieves and displays detailed information for all human user accounts (UID ≥ 500) on macOS, including the username, UID, admin privileges, full name, home directory, and default shell. It provides a clear and organized summary that is useful for system administrators to review and manage user configurations.

    Click to view script…
    #!/bin/bash
    # This script lists user accounts (UID >= 500) and shows additional details:
    # Username, UID, Admin Privileges (true/false), Full Name, Home Directory, and Shell
    
    # Print header for clarity
    echo "Username : UID : Has Admin Privileges : Full Name : Home Directory : Shell"
    
    # List all users with their UniqueID and process each line
    dscl . -list /Users UniqueID | while read username uid; do
        # Only process accounts with UID >= 500 (typically non-system, human user accounts)
        if [ "$uid" -ge 500 ]; then
            # Check if the user belongs to the 'admin' group
            if id -Gn "$username" 2>/dev/null | grep -qw "admin"; then
                adminFlag="true"
            else
                adminFlag="false"
            fi
    
            # Get the user's full name (if set). The command outputs a line like "RealName: John Doe"
            fullName=$(dscl . -read /Users/"$username" RealName 2>/dev/null | sed 's/RealName: //')
            
            # Get the user's home directory
            homeDir=$(dscl . -read /Users/"$username" NFSHomeDirectory 2>/dev/null | sed 's/NFSHomeDirectory: //')
            
            # Get the user's default shell
            shell=$(dscl . -read /Users/"$username" UserShell 2>/dev/null | sed 's/UserShell: //')
            
            # Output the collected information in a clear, colon-separated format
            echo "$username : $uid : $adminFlag : $fullName : $homeDir : $shell"
        fi
    done
  • Earth–Mars Orbital Transfer Animation Python Script

    This Python script animates a simplified simulation of Earth and Mars orbiting the Sun along circular paths, while a spacecraft travels between them using a basic interpolation trajectory with a sinusoidal arc. It dynamically updates the planet positions and labels to clearly indicate which is Earth (blue) and which is Mars (red).

    This script uses NumPy for efficient numerical computations and trigonometric functions, and Matplotlib (including mpl_toolkits.mplot3d for 3D rendering and matplotlib.animation for dynamic visualizations) to animate the planetary orbits and spacecraft trajectory. To install these libraries, open your Terminal and run:

    pip install numpy matplotlib

    (Use pip3 if you’re working with Python 3.)

    Click to view script…
    #!/usr/bin/env python3
    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D  # needed for 3D projection
    from matplotlib.animation import FuncAnimation
    
    # -----------------------------------------
    # 1) Orbital and Planetary Parameters
    # -----------------------------------------
    # Simplified units: 1 "unit" = 1 Astronomical Unit (AU)
    # Time is in days
    
    # Orbital radii (approx in AU)
    R_EARTH = 1.0
    R_MARS  = 1.52
    
    # Orbital periods (approx in days)
    T_EARTH = 365.0
    T_MARS  = 687.0
    
    # Angular velocities (radians per day)
    w_EARTH = 2.0 * np.pi / T_EARTH
    w_MARS  = 2.0 * np.pi / T_MARS
    
    # Initial phases (starting positions)
    phi_earth0 = 0.0
    phi_mars0  = 0.0
    
    # Radii of the planets (for plotting spheres)
    EARTH_RADIUS = 0.05
    MARS_RADIUS  = 0.03
    
    # -----------------------------------------
    # 2) Define Planet Position Functions
    # -----------------------------------------
    def planet_position(time, R, omega, phi0=0.0):
        """
        Returns the (x, y, z) position of a planet orbiting in the XY plane.
        """
        x = R * np.cos(omega * time + phi0)
        y = R * np.sin(omega * time + phi0)
        z = 0.0
        return np.array([x, y, z])
    
    # -----------------------------------------
    # 3) Spacecraft Trajectory
    # -----------------------------------------
    def find_launch_day(t_range):
        """
        Finds a launch day in t_range where the Earth-Mars distance is minimized.
        """
        best_day = None
        min_dist = 1e9
        for t in t_range:
            earth_pos = planet_position(t, R_EARTH, w_EARTH, phi_earth0)
            mars_pos  = planet_position(t, R_MARS,  w_MARS,  phi_mars0)
            dist = np.linalg.norm(mars_pos - earth_pos)
            if dist < min_dist:
                min_dist = dist
                best_day = t
        return best_day
    
    def spacecraft_trajectory(t, t_launch, t_arrival, home_func, target_func):
        """
        Computes a simple interpolated trajectory between two planets.
        Outside the travel window, it holds the departure or arrival position.
        """
        if t <= t_launch:
            return home_func(t_launch)
        elif t >= t_arrival:
            return target_func(t_arrival)
        else:
            # Fraction of travel completed
            frac = (t - t_launch) / (t_arrival - t_launch)
            pos_home = home_func(t_launch)
            pos_target = target_func(t_arrival)
            # Add a sinusoidal 'arc' in the Z direction for visual flair
            arc_height = 0.2 * np.sin(np.pi * frac)
            interp = (1 - frac) * pos_home + frac * pos_target
            interp[2] += arc_height
            return interp
    
    # -----------------------------------------
    # 4) Set Up the Animation Plot
    # -----------------------------------------
    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot(111, projection='3d')
    
    # Function to draw a sphere (used for Earth and Mars)
    def plot_sphere(ax, center, radius, color, alpha=1.0):
        u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
        x = center[0] + radius * np.cos(u) * np.sin(v)
        y = center[1] + radius * np.sin(u) * np.sin(v)
        z = center[2] + radius * np.cos(v)
        ax.plot_surface(x, y, z, color=color, alpha=alpha)
    
    # Global variables to store our plot elements
    earth_surf = None
    mars_surf = None
    spacecraft_marker, = ax.plot([], [], [], 'go', markersize=6)
    earth_label = None
    mars_label = None
    
    # Time settings for the simulation (e.g., 1200 days)
    total_frames = 1000
    times = np.linspace(0, 1200, total_frames)
    
    # Find a simplistic launch day within the first 300 days
    launch_day = find_launch_day(range(300))
    travel_time = 180.0  # days for Earth-to-Mars travel
    arrival_day = launch_day + travel_time
    
    # Return trip parameters (optional)
    stay_time_on_mars = 100.0
    return_launch_day = arrival_day + stay_time_on_mars
    return_arrival_day = return_launch_day + 200.0
    
    # Utility to get the x, y, z coordinates for a sphere surface
    def _sphere_xyz(center, radius, n_u=20, n_v=10):
        u = np.linspace(0, 2*np.pi, n_u)
        v = np.linspace(0, np.pi, n_v)
        u, v = np.meshgrid(u, v)
        x = center[0] + radius * np.cos(u) * np.sin(v)
        y = center[1] + radius * np.sin(u) * np.sin(v)
        z = center[2] + radius * np.cos(v)
        return x, y, z
    
    # -----------------------------------------
    # 5) Animation Update Function
    # -----------------------------------------
    def update(frame):
        global earth_surf, mars_surf, earth_label, mars_label
    
        # Current time in days
        t = times[frame]
    
        # Update positions for Earth and Mars
        earth_pos = planet_position(t, R_EARTH, w_EARTH, phi_earth0)
        mars_pos  = planet_position(t, R_MARS,  w_MARS,  phi_mars0)
    
        # Remove old spheres if they exist
        if earth_surf is not None:
            earth_surf.remove()
        if mars_surf is not None:
            mars_surf.remove()
    
        # Plot new spheres for Earth and Mars
        earth_surf = ax.plot_surface(*_sphere_xyz(earth_pos, EARTH_RADIUS),
                                     color='blue', alpha=0.6)
        mars_surf = ax.plot_surface(*_sphere_xyz(mars_pos, MARS_RADIUS),
                                    color='red', alpha=0.6)
        
        # Remove old labels if they exist
        if earth_label is not None:
            earth_label.remove()
        if mars_label is not None:
            mars_label.remove()
        
        # Add new text labels above each planet
        earth_label = ax.text(earth_pos[0], earth_pos[1], earth_pos[2] + EARTH_RADIUS + 0.05,
                              'Earth', color='blue', fontsize=10, weight='bold')
        mars_label = ax.text(mars_pos[0], mars_pos[1], mars_pos[2] + MARS_RADIUS + 0.05,
                             'Mars', color='red', fontsize=10, weight='bold')
        
        # Update spacecraft position based on current time
        if t < return_launch_day:
            # Outbound: Earth to Mars
            sc_pos = spacecraft_trajectory(t, launch_day, arrival_day,
                                           lambda tau: planet_position(tau, R_EARTH, w_EARTH, phi_earth0),
                                           lambda tau: planet_position(tau, R_MARS,  w_MARS,  phi_mars0))
        else:
            # Return: Mars to Earth
            sc_pos = spacecraft_trajectory(t, return_launch_day, return_arrival_day,
                                           lambda tau: planet_position(tau, R_MARS, w_MARS, phi_mars0),
                                           lambda tau: planet_position(tau, R_EARTH, w_EARTH, phi_earth0))
        
        # Update the spacecraft marker (green dot)
        spacecraft_marker.set_data([sc_pos[0]], [sc_pos[1]])
        spacecraft_marker.set_3d_properties([sc_pos[2]])
        
        # Return all updated artists
        return earth_surf, mars_surf, spacecraft_marker, earth_label, mars_label
    
    # -----------------------------------------
    # 6) Plot Aesthetics and Animation Setup
    # -----------------------------------------
    ax.set_xlim(-1.6, 1.6)
    ax.set_ylim(-1.6, 1.6)
    ax.set_zlim(-0.6, 0.6)
    ax.set_xlabel('X (AU)')
    ax.set_ylabel('Y (AU)')
    ax.set_zlabel('Z')
    ax.set_title('Earth–Mars Orbits with Spacecraft Launch')
    
    # Draw the Sun at the origin as a yellow sphere
    plot_sphere(ax, [0, 0, 0], 0.1, 'yellow', alpha=0.9)
    
    # Create the animation
    anim = FuncAnimation(fig, update, frames=total_frames, interval=30, blit=False)
    
    plt.show()
  • Animated Algorithm Playground Swift Script

    This Swift script visually demonstrates the bubble sort algorithm by animating each step in the terminal as it sorts a randomly generated array of numbers from unsorted to sorted order.

    Click to view script…
    #!/usr/bin/env swift
    
    import Foundation
    
    // Function to clear the terminal screen using ANSI escape codes.
    func clearScreen() {
        print("\u{001B}[2J", terminator: "")
        print("\u{001B}[H", terminator: "")
    }
    
    // Function to display the array as bars with their values.
    func displayArray(_ arr: [Int]) {
        for value in arr {
            let bar = String(repeating: "▇", count: value)
            print("\(bar) (\(value))")
        }
    }
    
    // Generate an array of 20 random integers between 1 and 20.
    var numbers = (0..<20).map { _ in Int.random(in: 1...20) }
    
    // Show the initial unsorted array.
    clearScreen()
    print("Initial Array:")
    displayArray(numbers)
    print("\nPress Enter to start the animated bubble sort...")
    _ = readLine()
    
    // Bubble sort with animation.
    let n = numbers.count
    
    for i in 0..<n {
        var didSwap = false
        for j in 0..<n - i - 1 {
            if numbers[j] > numbers[j + 1] {
                numbers.swapAt(j, j + 1)
                didSwap = true
    
                // Clear screen and show the current state of the array.
                clearScreen()
                print("Bubble Sort Animation - Pass \(i + 1), Swap at index \(j) and \(j + 1):")
                displayArray(numbers)
                usleep(200000) // Pause for 0.2 seconds
            }
        }
        // If no swaps occurred, the array is sorted.
        if !didSwap {
            break
        }
    }
    
    // Final sorted array.
    clearScreen()
    print("Sorted Array:")
    displayArray(numbers)
    print("\nSorting complete!")