JustToThePoint English Website Version
JustToThePoint en español

Maximize your online presence with our exclusive offer: Get a stunning hero banner, the hero you need and deserve, at an unbeatable price! Bew, 689282782, bupparchard@gmail.com

Monitoring pc & website. Calendar, Tasks, Birthdays & Events Reminder, Countdoom

All warfare is based on deception, Sun tzu, The Art of War.

Sixth rule B. Cherry picking on data, variables and metrics, perverse incentives, false causality, sampling bias, the observer effect, and over manipulating the data can lead you to any desired outcome with “rigorous” standards. Futhermore, there are many infinites, but the biggest of them all is human’s stupidity and sheer arrogance, Apocalypse, Anawim, #justtothepoint.

Image 

Monitoring your computer & website

"""
File: monitoring.py
Author: Máximo Núñez Alarcón
Description: This code monitors your website and computer usage. 
It checks the internet connection, disk partitions, and then monitors CPU, memory, and disk usage for a specified duration. 
Finally, it checks if the website is online.
Usage: Run the script (python ./monitoring.py) to monitor your website and computer.
Dependencies: requests, os, my_progress (from util module)

Requirements: psutil, request, rich, and dotenv

Usage:
1. Ensure the required libraries are installed: pip install psutil requests rich python-dotenv
2. Set up a .env file with the necessary environment variables (e.g., TIME_MONITORING, WEBSITE).
3. Run the script to monitor your computer system and website status.
"""

import psutil
import time
from util import my_progress # It is used for displaying progress of the task
import requests
from rich.console import Console
from rich.rule import Rule
from dotenv import load_dotenv
import os

# Initialize Rich Console for colorful output
console = Console()

# Function to check if the website is online
def check_website(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            console.print(":thumbs_up:" + " Success! Website "+ url + " is online and working fine.")
        else:
            print(f"Error! Website {url} returned status code: {response.status_code}")
    except requests.RequestException as e:
        print(f"Error! Failed to connect to {url}: {e}")

# Function to check internet connection
def check_internet_connection():
    console.print(Rule(f'[bold green]Checking...[/bold green]'))
    try:
        response = requests.get("https://www.google.com", timeout=5)
        if response.status_code == 200:
            console.print(":thumbs_up:" + " Success! Internet connection is working fine.")
        else:
            print(f"Error! Failed to connect to Google. Status code: {response.status_code}")
    except requests.RequestException as e:
        print(f"Error! Failed to connect to Google: {e}")

# Function to monitor computer usage
def monitor_computer(cpu_usage, mem_usage, disk_usage, bars = 50):
    cpu_percentage = (cpu_usage / 100.0)
    cpu_bar = '█' * int (cpu_percentage * bars) + '-' * (bars -int(cpu_percentage * bars))

    mem_percent = (mem_usage / 100.0)
    mem_bar = '█' * int (mem_percent * bars) + '-' * (bars -int(mem_percent * bars))

    # Disk usage
    disk_percent = (disk_usage / 100.0)
    disk_bar = '█' * int(disk_percent * bars) + '-' * (bars - int(disk_percent * bars))

    
    print(f"CPU Usage: | {cpu_bar}| {cpu_usage:.2f}%  ", end = "")
    print(f"Mem Usage: | {mem_bar}| {mem_usage:.2f}%  ", end = "")
    print(f"Disk Usage: | {disk_bar}| {disk_usage:.2f}%  ", end = "\r")

# Main function for monitoring
def my_monitor():
    load_dotenv() # Load environment variables from .env file
    time_monitoring = int(os.getenv("TIME_MONITORING"))
    my_progress("Monitoring my GNU/Linux and website") # Display progress of the task

    # Print mounted partitions
    for partition in psutil.disk_partitions():
            if partition.fstype:  # Only show mounted partitions with a filesystem type
                print(f"\rPartitions {partition.device}, {partition.mountpoint} ")


    start_time = time.time()  # Record the start time
    while time.time() - start_time < 30:  # Run for half a minute (30 seconds)
        monitor_computer(psutil.cpu_percent(), psutil.virtual_memory().percent, psutil.disk_usage('/').percent, time_monitoring)
        time.sleep(0.5)

    check_internet_connection()
    load_dotenv() # Load environment variables from .env file
    website_url = os.getenv("WEBSITE") # Change this to your website URL
    check_website(website_url)    

# Execute the monitoring function    
if __name__ == '__main__':
    my_monitor()

Calendar, tasks, birthdays & events reminder in Python

"""
File: my_app.py
Author: Máximo Núñez Alarcón
Description: A collection of functions to manage tasks, calendars, and reminders.
Usage: Run the script to display reminders and pending tasks.
Dependencies: rich, datetime, os

Functions:
- myTasks(): Displays pending tasks with different styles based on their priority.
- myCalendar(calendar_file): Outputs reminders for upcoming events based on today's date.
- check_and_remind(birthday_file): Outputs reminders for today's birthdays, anniversaries, and events based on today's date.

Module-level Execution:
- Executes functions myCalendar(), check_and_remind(), and myTasks() to display reminders and tasks.

Note: Ensure that the necessary files (e.g., calendar.txt, birthdays.txt) are present in the 'assets' directory.
"""

from rich.console import Console
from rich.theme import Theme
from util import my_progress, border_msg, warning_msg, path_file
from datetime import datetime # Module for working with date and time
import re # -*- coding: UTF-8 -*-
import os

def myTasks(filename = 'assets/mytasks.txt'):
    """
    Prints pending tasks with different styles based on their priority.
    Ensure that the necessary file, e.g., assets/mytasks.txt is present in the 'assets' directory.
    Format mytasks.txt, a line for each task with the format: [H|N|L] Name and description of task
    Args:
        None

    Returns:
        None
    """
    my_progress("My pending tasks")
    console = Console()

    path_task = path_file(filename)
    try: 
        # Open the file in read mode
        with open(path_task, 'r') as file:
            # Iterate through each line in the file
            for line in file:
                # Strip leading and trailing whitespace from the line
                stripped_line = line.strip()
                if stripped_line.startswith('H'):
                    # Print the line
                    console.print(stripped_line, style="bold red")
                elif stripped_line.startswith('N'): # Check if the line starts with 'P'
                    # Print the line
                    console.print(stripped_line, style="bold cyan")
                elif stripped_line.startswith('L'): # Check if the line starts with 'P'
                    # Print the line
                    console.print(stripped_line, style="magenta")
    except FileNotFoundError:
        print(f"The file {path_task} was not found.")
    except Exception as e:
        print(f"An error occurred: {e}")

def myCalendar(calendar_file="assets/calendar.txt"):
    """
    Outputs reminders for upcoming events based on today's date, e.g. birthdays and anniversaries.
    Ensure that the necessary file, e.g., assets/calendar.txt is present in the 'assets' directory.
    Format calendar.txt, a line for each event with the format: DD-MM Event name and description
    
    Args:
        calendar_file (str): The path to the file containing event dates and descriptions, e.g., myCalendar("assets/calendar.txt")

    Returns:
        None
    """

    console = Console()
    # Get today's date in DD-MM format
    today = datetime.now().strftime('%d-%m')
    
    try:
        # Open the calendar file and read it line by line
        path_calendar = path_file(calendar_file)
        with open(path_calendar, 'r') as file:
            for line in file:
                # Each line is expected to be in "MM-DD Event" format
                date, event = line.strip().split(' ', 1)
                if date == today:
                    warning_msg("Event: 📅" + event)
    except FileNotFoundError:
        print(f"The file {path_calendar} was not found.")
    except Exception as e:
        print(f"An error occurred: {e}")


def check_and_remind(birthday_file="assets/birthdays.txt"):
    """
    This is a clone of birthday. Outputs reminders for today's birthdays, anniversaries, and events, e.g. birthdays and anniversaries.

    Args:
        birthday_file (str): The path to the file containing birthday dates and event descriptions, e.g., 'assets/birthdays'
        The file should be located inside your project folder.
        Example usage: check_and_remind("assets/birthdays.txt")
        Format: DD-MM Event, e.g., 12-25 Christmas Day (Navidad)
    Returns:
        None
    """
    # Get today's date in DD-MM format
    today = datetime.now().strftime('%d-%m')
    
    try:
        path_birthday = path_file(birthday_file)
        # Open the birthday file and read it line by line
        with open(path_birthday, 'r') as file:
            for line in file:
                # Each line is expected to be in "MM-DD Event" format
                date, event = line.strip().split(' ', 1)
                if date == today:
                    if event.upper().find("BIRTHDAY")==-1: # It is a birthday event.
                        console.print("Happy Birthday: " + ":birthday_cake: " + event) 
                        # We use the rich library to show an emoji.
                        # To see a list of all the emojis available: python -m rich.emoji
                    else:
                        console.print("Event: " + ":calendar: " + event)
    except FileNotFoundError:
        print(f"The file {path_birthday} was not found.")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    myCalendar("assets/calendar.txt")
    check_and_remind("assets/birthdays.txt")
    myTasks()

There is a function necessary for this code to work, mainly path_file.

Atomic time clock using Python

Countdoom is a Python package to fetch and digest the current Doomsday Clock world threat assessment from TheBulletin.org.

import asyncio
from typing import Dict, Union
from countdoom import CountdoomClient
from rich.console import Console

# Implement logic to fetch data asynchronously from the Doomsday Clock API
async def async_get_doomsday_clock() -> Dict[str, Union[str, float, None]]:
    """
    Get current Doomsday Clock value (aka fetch data from a Doomsday Clock API) asynchronously using AsyncIO.
    return: Dictionary of Doomsday Clock representation styles
    """
    client = CountdoomClient() 
    # client is an object of the CountdoomClient. This class handle the communication with the Doomsday Clock API.
    data = await client.fetch_data()
    #  This method from the class CountdoomClient, fetch_data(), performs the actual HTTP request to the Doomsday Clock API and returns the data.
    return data

def get_doomsday_clock():
    # The asyncio.run() function will start the asyncio event loop. 
    # Is is responsible for getting the event loop, running tasks until they are marked as complete, and then closing the event loop.  
    data = asyncio.run(async_get_doomsday_clock())
    # Format the clock data {'sentence': 'IT IS 90 SECONDS TO MIDNIGHT', 'clock': '11:58:30', 'time': '23:58:30', 'minutes': 1.5, 'countdown': 90.0}
    formatted_clock = f"\nDoomsday Clock.💥 Time to Midnight: {data['time']}. {data['sentence']}!"
    print(formatted_clock)
    
if __name__ == "__main__":
    get_doomsday_clock()

Greeting the user

import subprocess
import os
import getpass
from datetime import datetime
import requests

def greating_user(city):
    username = getpass.getuser() # It fetchs the current user's username and greets them.
    now = datetime.now() # Get the current date and time
    current_time = now.strftime("%Y-%m-%d %H:%M:%S") # Format the datetime object as a string
    print(f"Hello, {username}! Welcome to your Arch system.")
    print(f"Current date and time: {current_time}") # Print the formatted string
    subprocess.run(["curl", f"wttr.in/{city}?format=3"])

# It fetch a random quote from the "https://api.quotable.io/random" endpoint. If successful, it prints the quote; if not, it prints an error message.
def fetch_quote():
    try:
        response = requests.get("https://api.quotable.io/random") 
        if response.status_code == 200:
            data = response.json()
            return f"{data['content']} — {data['author']}"
        else:
            return "Could not fetch a quote at this time."
    except requests.RequestException:
        return "Could not fetch a quote due to a network error."
    
if __name__ == "__main__":
    city = "Malaga"
    greating_user(city)
    print(fetch_quote())
Bitcoin donation

JustToThePoint Copyright © 2011 - 2024 Anawim. ALL RIGHTS RESERVED. Bilingual e-books, articles, and videos to help your child and your entire family succeed, develop a healthy lifestyle, and have a lot of fun. Social Issues, Join us.

This website uses cookies to improve your navigation experience.
By continuing, you are consenting to our use of cookies, in accordance with our Cookies Policy and Website Terms and Conditions of use.