Monday, September 16, 2024

Scheduler creations in Linux-based OS machines and Windows

Scheduler creations in Linux-based OS machines


Useful link for crontab calculations: https://crontab.guru/

To install crontab in Linux, you can use the following commands:

1. Update the package list: sudo apt update

2. Install cron: sudo apt install cron

3. Start the cron service: sudo systemctl start cron

4. Enable cron to start on system boot: sudo systemctl enable cron 

You can create a cron job by editing the /etc/crontab file. To do this, you can:

Open the crontab configuration file for the current user: crontab -e

only once it will ask for "Select an editor" then select option 2 ( 2. /usr/bin/vim.basic) Enter

Add a line containing a cron expression and the path to a script like below

*/5 * * * * /usr/bin/sh /home/narendra/my_stress_suite.bash > /home/taccuser/narendra/cron_jobs/abc.txt 2>&1

Save (Ctrl+x) and exit the crontab file 

Here are some special characters you can use in the time fields:

Asterisk (*): Specifies that the command should be run for every instance of the field

Hyphen (-): Can be used to indicate a range

Comma (,): Can be used to specify a list of values for a field

Forward slash (/): Can be used to specify step values 

You can also use shorthand extensions to replace the time fields. Some of these options include:

@reboot, @yearly, @annually, @monthly, @weekly, @daily, and @hourly


For shell scripts:

*/5 * * * * /usr/bin/sh /home/narendra/my_stress_suite.bash > /home/taccuser/narendra/cron_jobs/abc.txt 2>&1

Explanation:

crontab -l   ==> Displays the contents of the crontab file associated with the current user on the screen

crontab -e   ==> By using this command we can modify the crontab configuration & save (Ctrl+x)

For python scripts

# cronjob format only weekends 7:30 AM

30 7 * * sat-sun  /usr/bin/python3 /home/narendra/my_stress_suite.py  >  /home/taccuser/narendra/cron_jobs/abc.txt 2>&1

cronjob format only on weekdays

30 7 * * mon-fri    --> Every day 7:30 AM but not on Sat and Sundays



Scheduler creations in Windows machines

truncate command in Linux is used to change the size of a file, either by shortening or extending itIt's a useful tool for managing file sizes and optimizing storage space

Syntax: truncate -s [number of bytes] filename_along_with_path

       Ex: truncate -s 0 narendra/cron_jobs/abc.txt

above command will delete the content of the file to make filesize 0 bytes (i.e, the file will present but data will be erased)


=======================================================================

RequestIf you find this information useful, please provide your valuable comments.







Wednesday, September 11, 2024

Small realtime usecase Python codes for student to maintain proficiency

"""
Use case 1: Write a Python code to validate the password, set by the user
Use case 2: Library management system 
Use case 3: Create a GUI application in Python for managing a basic contact book
Add Contact: Allows the user to enter a name, phone, and email, then adds the contact to the contact book.
View Contacts: Displays a list of all stored contacts.
Search Contact: Searches for a contact by name and shows the phone and email if found.
Delete Contact: Deletes a contact by name if it exists.
User Interface: Uses tkinter to create a simple GUI with input fields and buttons for interaction""""""
Use case 4: Poll Management
Use case 5:
Use case 6:

# W.A.P for chatbot Response
def chatbot_response(user_input):
user_input = user_input.lower()
if "hello" in user_input or "hi" in user_input:
return "Hello! How can I help you today?"
elif "weather" in user_input:
return "The weather is sunny today!"
else:
return "I'm sorry, I don't understand that."

user_input = input("You: ")
response = chatbot_response(user_input)
print("Chatbot:", response)
=========================================================================
"""
Write a python code to validate password, set by the user
Rules:
1. At least 8 characters should be present in the given password
2. At least One Capital letter & lowercase letter should present
3. At least 1 numerical value should present
4. At least 1 special character should present
5. space should not present in the given password
6. password & confirm password should be the same
"""
password = input("Enter New password: ")
Confirm_password = input("Re-enter password: ")
"""Check if password is at least 8 characters long"""
is_valid_length = len(password) >= 8

""" Check if password contains at least one uppercase letter """
has_uppercase = any(char.isupper() for char in password)
""" Check if password contains at least one lowercase letter """
has_lowercase = any(char.islower() for char in password)
""" Check if password contains at least one digit"""
has_digit = any(char.isdigit() for char in password)



"""Check if password contains at least one special character"""
special_characters = "!@#$%^&*()-_+=<>?/|\\{}[]:;\"',."
has_special_char = any(char in special_characters for char in password)

"""Check if password does not contain any spaces"""
has_no_spaces = " " not in password

""" Printing the results """
print(f"Password: {password}")
print(f"Valid Length: {is_valid_length}")
print(f"Contains Uppercase: {has_uppercase}")
print(f"Contains Lowercase: {has_lowercase}")
print(f"Contains Digit: {has_digit}")
print(f"Contains Special Character: {has_special_char}")
print(f"Contains No Spaces: {has_no_spaces}")

""" Final validation result """
if all([is_valid_length, has_uppercase, has_lowercase, has_digit, has_special_char, has_no_spaces]) and password == Confirm_password:
print("Given Password is valid.")
else:
print("Given Password is invalid.")

=========================================================================

# Library management system 

# Dictionary to store books and their availability
library = {
"The Great Gatsby": {"author": "F. Scott Fitzgerald", "available": True},
"1984": {"author": "George Orwell", "available": False},
"To Kill a Mockingbird": {"author": "Harper Lee", "available": True}
}

# Check availability of a book
def check_availability(book_title):
if book_title in library:
availability = library[book_title]["available"]
return f"{book_title} is {'available' if availability else 'not available'}."
else:
return f"{book_title} is not in the library."

# Print the availability of a specific book
print(check_availability("1984"))
print(check_availability("The Catcher in the Rye"))

# List all available books
available_books = [book for book, details in library.items() if details["available"]]
print("Available books:", available_books)

=========================================================================

"""

Create a GUI application in Python for managing a basic contact book

Add Contact: Allows the user to enter a name, phone, and email, then adds the contact to the contact book.
View Contacts: Displays a list of all stored contacts.
Search Contact: Searches for a contact by name and shows the phone and email if found.
Delete Contact: Deletes a contact by name if it exists.
User Interface: Uses tkinter to create a simple GUI with input fields and buttons for interaction"""

import tkinter as tk
from tkinter import messagebox
"""
tkinter: built-in Python library for creating GUIs. It provides widgets like buttons, labels, text boxes, and more.
messagebox: This is a module within tkinter used to create pop-up dialog boxes that display information, warnings, or errors to the use"""

contacts = {}


def validate_phone(phone): # Function to validate the phone number
"""
If the user enters a phone number with non-numeric characters or a phone number that is not exactly 10 digits long,
the program will show a warning message and stop the contact from being added.
Only if the phone number is valid (contains exactly 10 digits and no letters or symbols)
will the contact be successfully added to the contacts dictionary.
"""
return phone.isdigit() and len(phone) == 10


def add_contact():
"""
entry_name.get(), entry_phone.get(), and entry_email.get() retrieve the values from the input fields for the contact's name, phone number, and email.
If all three fields (name, phone, and email) are filled, the function checks if the contact already exists in the contacts dictionary.
If the contact exists, it shows a warning message using messagebox.showwarning().
If the contact is new, it adds the contact to the dictionary and shows a success message using messagebox.showinfo().
After adding, the input fields are cleared with entry_name.delete(0, tk.END) to prepare for a new entry.
If any field is left blank, it displays an input error warning.
"""
name = entry_name.get()
phone = entry_phone.get()
email = entry_email.get()

if name and phone and email:
if not validate_phone(phone): # Validate phone number
messagebox.showwarning("Invalid Phone", "Phone number must be 10 digits long and contain only numbers.")
return

if name in contacts:
messagebox.showwarning("Error", f"{name} already exists.")
else:
contacts[name] = {'phone': phone, 'email': email}
messagebox.showinfo("Success", f"Contact {name} added.")
entry_name.delete(0, tk.END)
entry_phone.delete(0, tk.END)
entry_email.delete(0, tk.END)
else:
messagebox.showwarning("Input Error", "Name, phone, and email are required.")


def view_contacts(): # Function to View All Contacts
"""
This contact list is then shown in a message box using messagebox.showinfo().
If no contacts are available, a message saying "No contacts available" is shown.
"""

if contacts:
contact_list = "\n".join([f"Name: {name}, Phone: {info['phone']}, Email: {info['email']}"
for name, info in contacts.items()])
messagebox.showinfo("Contact List", contact_list)
else:
messagebox.showinfo("Contact List", "No contacts available.")


def search_contact(): # Function to Search for a Contact
"""
The function retrieves the name entered in the entry_name field.
It checks if the name exists in the contacts dictionary.
If found, it shows the contact’s phone and email in a messagebox.
If not found, it shows a message saying the contact doesn't exist.
"""
name = entry_name.get()

if name in contacts:
contact_info = contacts[name]
messagebox.showinfo("Search Result", f"Name: {name}, Phone: {contact_info['phone']}, Email: {contact_info['email']}")
else:
messagebox.showinfo("Search Result", f"{name} not found.")


def delete_contact(): # Function to Delete a Contact
"""
The function retrieves the name entered in the entry_name field.
If the contact exists in the contacts dictionary, the contact is deleted using the del keyword.
A confirmation message is shown after deletion.
If the contact doesn't exist, a warning is shown
"""
name = entry_name.get()

if name in contacts:
del contacts[name]
messagebox.showinfo("Delete", f"{name} deleted.")
else:
messagebox.showwarning("Error", f"{name} not found.")


root = tk.Tk() # initializes the main application window.
root.title("Contact Book with Email") # sets the window's title to "Contact Book with Email"
root.geometry("400x400") # defines the size of the window (300x350 pixels)

"""
Labels and Entry Fields:

Label() creates text labels ("Name", "Phone", "Email") to indicate the purpose of each input field.
Entry() creates input fields where users can type the name, phone number, and email.
pack(pady=5) arranges the widgets (labels and input fields) vertically in the window with some space between them (padding of 5 pixels).
"""
label_name = tk.Label(root, text="Name")
label_name.pack(pady=5)
entry_name = tk.Entry(root)
entry_name.pack(pady=5)

label_phone = tk.Label(root, text="Phone")
label_phone.pack(pady=5)
entry_phone = tk.Entry(root)
entry_phone.pack(pady=5)

label_email = tk.Label(root, text="Email")
label_email.pack(pady=5)
entry_email = tk.Entry(root)
entry_email.pack(pady=5)

"""
Buttons for Operations

Button() creates clickable buttons for each operation: "Add Contact", "View Contacts", "Search Contact", and "Delete Contact".
command=... links each button to the respective function that handles the operation.
pack(pady=5) places the buttons with vertical padding between them for a better layout
"""

btn_add = tk.Button(root, text="Add Contact", command=add_contact)
btn_add.pack(pady=5)

btn_view = tk.Button(root, text="View Contacts", command=view_contacts)
btn_view.pack(pady=5)

btn_search = tk.Button(root, text="Search Contact", command=search_contact)
btn_search.pack(pady=5)

btn_delete = tk.Button(root, text="Delete Contact", command=delete_contact)
btn_delete.pack(pady=5)

"""
root.mainloop() starts the event loop of the application.
This keeps the window open and responsive, waiting for user interactions such as button clicks and text input.
"""
root.mainloop()


=========================================================================

# polling system  (EVM machine results printing)
# Dictionary to store poll results
poll_results = {
"Option A": 50,
"Option B": 50,
"Option C": 50,
"Option D": 50
}

# Adding new votes
def add_vote(option):
if option in poll_results:
poll_results[option] += 1
else:
poll_results[option] = 1

# Add votes
add_vote("Option A")
add_vote("Option B")
add_vote("Option E")
add_vote("Option B")
# Print poll results
for option, votes in poll_results.items():
print(f"{option}: {votes} votes")

=========================================================================

""" Sentiment analysis

 Example text to analyze"""
# text = "I love this product! It is amazing and works perfectly. I am very happy with it."

""" Lists of positive and negative words """
# positive_words = ["love", "amazing", "happy", "good", "great", "fantastic", "excellent", "positive", "enjoy"]
# negative_words = ["hate", "terrible", "bad", "worse", "awful", "horrible", "negative", "sad", "angry"]

"""Convert text to lowercase to ensure case-insensitive comparison """
# text_lower = text.lower()

""" Initialize counters for positive and negative words """
# positive_count = 0
# negative_count = 0

""" Count positive words in the text """
# for word in positive_words:
# positive_count += text_lower.count(word)

""" Count negative words in the text """
# for word in negative_words:
# negative_count += text_lower.count(word)

""" Determine the overall sentiment """
# if positive_count > negative_count:
# sentiment = "Positive"
# elif negative_count > positive_count:
# sentiment = "Negative"
# else:
# sentiment = "Neutral"

""" Print the results """
# print(f"Text: {text}")
# print(f"Positive words count: {positive_count}")
# print(f"Negative words count: {negative_count}")
# print(f"Overall sentiment: {sentiment}")

========================================================================


========================================================================


Request: If you find this information useful, please provide your valuable comments


 

Sunday, February 12, 2023

CPU & GPU Internel components with explanation

Terminology : 

BIOS (Basic Input/Output System) is the first software that runs when you power on your system, performing an initial pack of diagnostic tests (POST, or Power On Self-Test) to see if there are any issues with the hardware. 
POST is the first step in your hardware's boot sequence. The machine won't continue with the boot sequence if the POST fails.

BIOS contains instructions on controlling various hardware components such as hard disks, keyboards, and display screens.

VBIOS (Video basic input/output system) is the BIOS of a graphics card in a computer. 
                    VBIOS initializes the graphics card at the computer's boot time.

SBIOS (System Management BIOS):

Defines data structures that can be used to read management information produced by the BIOS of a computer. 
SBIOS eliminates the need for the operating system to probe hardware directly to discover what devices are present in the computer

To check SBIOS version cmd:  sudo dmidecode -s bios-version


UEFI (Unified Extensible Firmware Interface) is a newer standard that replaces the legacy BIOS.
UEFI offers more features and benefits, such as faster boot times, better security, larger disk support, and graphical user interface.


Dynamic Kernel Module Support (DKMS) is a program/framework that enables generating Linux kernel modules whose sources generally reside outside the kernel source tree.  

CMD:  sudo dkms status   This  command will give GPU kernel & OS-kernel (C.P.U)
Ex: 
CMD:  uname -r    This  command will give OS-kernel only
Ex: 

CMD: /usr/lib/modules/6.x.x-xx-generic/kernel/drivers

This is the OS kernel path where all the drivers (input / tty / Bluetooth / GPU/ PCI ..... ) will be located

What is Swap memory?  and what is the purpose of Swap memory?
  • Swap space (virtual memory) is a designated area on a hard drive that is used as an extension of physical memory (RAM). 
  • When the system's RAM becomes full, inactive pages are moved to the swap space, freeing up RAM for active processes
  • While swap space can help machines with a small amount of RAM, it should not be considered a replacement for more RAM.
How do we check Swap memory in our machine?

   commands to check swap memory: free -h          or     sudo swapon --show
   the output of  free -h  
                     total        used        free      shared  buff/cache   available
Mem:           125Gi       9.0Gi       113Gi       112Mi       2.8Gi       115Gi
Swap:           93Gi          0B        93Gi
  
the output of   sudo swapon --show  
        
NAME      TYPE       SIZE USED PRIO
/dev/sda3 partition 93.1G   0B   -2

Can we increase the swap memory? Ans: Yes. 

How to increase/ resize swap memory? / How to increase Swap Space in Ubuntu 22.04 LTS Jammy?

Steps to add Swap area in Ubuntu 22.04 LTS Linux

1. Check the current Swap Space

            cmdsudo swapon -s 

            result: if there is no swap memory means it will not show anything (empty)

                        otherwise shown as below

                Filename                                Type            Size            Used            Priority

                /swapfile                               file            31457276        0               -2

2. Turn off Swap

            cmd: sudo swapoff -a                             Command output shows: Nothing 

3. Create a Swap file on Ubuntu 22.04 to increase the size

   Note: While using the given command keep one thing in mind 40G means, 40GB of space you are about to allocate for Swap       

            cmd: sudo fallocate -l 40G /swapfile        Command output shows: Nothing  

4. Change file permission

            cmd:  sudo chmod 600 /swapfile              Command output shows: Nothing  

5. Mark SWAP space and activate it

            cmd:  sudo mkswap /swapfile

                    mkswap: /swapfile: warning: wiping old swap signature.

                    Setting up swapspace version 1, size = 100 GiB (107374178304 bytes)

                    no label, UUID=0764024e-ac01-4c29-91ab-bb64f7af33a3

            cmdsudo swapon /swapfile               Command output shows: Nothing 

        Note: After activating, can you check whether the Swap space is added to your system? By using the below cmd.

          cmd: sudo swapon -s     or     free -h

6. Set Ubuntu 22.04 SWAP file as permanent

            cmd:  echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

7. Set swap usage or swappiness

            cmd: sysctl vm.swappiness                  Command output shows:  vm.swappiness = 60

         However, this change is forgotten by the system after a reboot unless the following is entered in the system file /etc/sysctl.conf:

            cmdsudo nano /etc/sysctl.conf     Command will open a file, at the end of the file add vm.swappiness = 60  then save the file with the help of the options shown there. just check again if your change is saved or not?

       8. Now reload the sysctl configuration file

            cmdsudo sysctl -p

            cmdsudo reboot

for any clarification use this link: https://linux.how2shout.com/how-to-increase-swap-space-in-ubuntu-22-04-lts-jammy/#1_Check_current_Swap_Space.


How to avoid hanging issues on our laptops/Personal computers?
 1. Delete unwanted /unnecessary files and folders 📂 in laptops /PCs 💻 

    We have to delete files & folders from 3 locations

              a. Delete files & folders present in the prefetch folder

                  press windows+r  type prefetch press Enter button ==> then try to delete all files & folders  

   b. Delete files & folders present in the temp folder

                  press windows+r  type temp press Enter button ==> then try to delete all files & folders 

   c. Delete files & folders present in the %temp% folder

                  press windows+r  type %temp%  press Enter button  ==> then try to delete all files & folders 

              d. Delete malicious softwares

                              press windows+r  type MRT  press Enter button  ==> click on YES  --> Next --> enable quick scan Radio button, automatically malicious softwares will be removed.


Request: If you find this information useful, please provide your valuable comments.


Dockers and containers

What is docker?

Docker is an environment with its own OS+ user space (related packages & modules) that resides on a bare-metal system and uses system HW/Kernel resources to serve a different purpose.


We must understand 3 environments (Bare metal,  Docker, virtualization)

·        Bare metal is one kind of environment where we test our GPUs directly

·        Docker is one kind of environment that is separated from Bare metal.

       Virtualization is software, that makes computing environments independent of physical infrastructure. In contrast, cloud computing is a service that delivers shared computing resources (software and/or data) on demand via the Internet.

·        If you launch Docker, it has its own user space with all dependent packages and its own OS.

The beauty of the docker concept :


   Docker is platform-independent and can run on any machine regardless of the operating system present.


      Docker is controlled by a kernel space.

·        Kernel sitting very close to the hardware.                                                 

·        If Kernel space/Firmware is broken/crashed, we can’t do anything.

·        Both Bare-metal and Docker have the packages, Except Docker does not have kernel space. Docker will use kernel space which is available on the bare metal.

Docker architecture components & How does docker work? 

Docker architecture comprises 3 main components

1. Docker Client: This is the interface through which users interact. It communicates with the docker daemon.

2. Docker Host: Here, Docker daemon listens for docker API requests and manages various docker objects, including images, containers, networks, and volumes

3. Docker Registry: This is where Docker images are stored. Docker hub, for instance, is a widely used public registry 

          Docker & container related commands

sudo docker pull <docker_name_based_on_OS> cmd will pull the specific doker into the machine

sudo docker images  ==> cmd will list the available dockers in the present machine

sudo docker rmi  -f  docker_id ==> cmd will delete a single specific docker in the present machine

sudo docker rmi  -f  docker_id_1 docker_id_2 docker_id_3 ==> Will delete multiple dockers

sudo docker ps -a ==> cmd will list the available containers in the present machine

sudo docker rm container_id ==>cmd will delete a single specific container present in the machine

sudo docker rm container_id_1 container_id_2 container_id_3 ==> will delete multiple containers

docker system prune -a   ==> It will clear space on your device by doing the following tasks 

     This command will remove: 

            - all stopped containers

            - all networks not used by at least one container

            - all images without at least one container associated with them

            - all build cache


Ø   sudo dmesg: dmesg contains all kernel-related information (loading /unloading, module loading firmware loading. etc. lot of information).

Ø  sudo dmesg | grep -i error if you search like this it will give kernel/firmware-related error messages 

Ø  Any kernel-related error & other information you want to see then you must run sudo dmesg from the home directory,

su sudo dmesg -C  --> It will clear all kernel error messages

Ø  cd /var/log/ èin this folder the dmesg log file & other kernel log files are present.

èFirmware not loaded/ kernel crashed all information, You can use the command sudo dmesg | grep -i error to see the error messages.


Request: If you find this information useful, please provide your valuable comments.

Friday, November 18, 2022

Technical Info

 

Windows Subsystem for Linux Has Reached v1.0 Stable Release


Windows Subsystem for Linux (WSL) is a tool that lets you run a GNU/Linux environment inside a Windows system without needing a virtual machine or dual-boot.

https://news.itsfoss.com/wsl-stable-available/


Saturday, October 15, 2022

Pytorch framework & Tensorflow Framework

Pytorch and Tensorflow are the two most popular deep-learning frameworks. 


Pytorch was developed by Facebook and released to the public in 2016.

Pytorch is a low-level API for NLP(natural language processing) and computer vision. it is a more powerful version of Numpy.



TensorFlow was developed by Google and released to the public in 2015. Production and research are the main uses of TensorFlow.




Friday, July 15, 2022

AI ML DL

 




JenkinsThe leading open source automation server, Jenkins provides hundreds of plugins to support building, deploying, and automating any project.



Difference between Private Key and Public Key


KeyPrivate KeyPublic Key
AlgorithmPrivate key is used for both encrypting and decrypting the sensitive data. It is shared between the sender and receiver of encrypted data.Public key is used only for the purpose of encrypting the data.
PerformanceThe private key mechanism is faster.The public key mechanism is slower.
SecrecyThe private key is kept secret and not public to anyone apart from the sender and the receiver.The public key is free to use and the private key is kept secret only.
TypeThe private key mechanism is called "symmetric" because a single key is shared between two parties.The public key mechanism is called "asymmetric" because there are two keys for different purposes.
SharingThe private key is to be shared between two parties.The public key can be used by anyone but the private key is to be shared between two parties only.
TargetsPerformance testing checks the reliability, scalability, and speed of the system.