Install chromedriver Automatically while using Selenium in Python

pip install webdriver-manager
service = Service(executable_path=ChromeDriverManager().install())
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--start-maximized")
chrome_options.add_experimental_option("useAutomationExtension", False)
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
# Add headless option
chrome_options.add_argument("--headless")
self.driver = webdriver.Chrome(options=chrome_options, service=service)

 

Deploy applications in Run as Administrator mode in Windows using PyInstaller and Inno Setup

PyInstaller

venv\Scripts\pyinstaller.exe --noconsole --onefile --icon=images/icons8-anki-512.ico --manifest=MyAnki.exe.manifest --uac-admin -n MyAnki app.py

MyAnki.exe.manifest

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>

inno_setup.iss

[Setup]
PrivilegesRequired=admin

 

Modifying the column names of a Pandas DataFrame

Rename Specific Columns

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'Name': ['Alice', 'Bob'],
    'Age': [25, 30]
})

# Rename the 'Name' column to 'Full Name' and 'Age' to 'Age in Years'
df.rename(columns={'Name': 'Full Name', 'Age': 'Age in Years'}, inplace=True)

print(df)

Modify All Headers at Once

# Create a DataFrame
df = pd.DataFrame({
    'Name': ['Alice', 'Bob'],
    'Age': [25, 30]
})

# New column names
new_columns = ['Full Name', 'Age in Years']

# Assign the new column names to the DataFrame
df.columns = new_columns

print(df)

Apply a Function to Headers

# Create a DataFrame
df = pd.DataFrame({
    'Name': ['Alice', 'Bob'],
    'Age': [25, 30]
})

# Make all column names uppercase
df.columns = df.columns.str.upper()

print(df)

 

Remove Column from DataFrame in Pandas

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'Los Angeles', 'Chicago']
})

# Print the original DataFrame
print("Original DataFrame:")
print(df)

# Remove the 'Age' column
df = df.drop(columns=['Age'])

# Print the updated DataFrame
print("\nDataFrame After Removing 'Age' Column:")
print(df)

Remember to assign the result back to the DataFrame (or to a new variable) if you want to keep the change. If you just want to remove the column temporarily for a specific operation, you can use the inplace=True argument to modify the DataFrame in place:

df.drop(columns=['Age'], inplace=True)

You can remove a column from a DataFrame by its index

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'Los Angeles', 'Chicago']
})

# Print the original DataFrame
print("Original DataFrame:")
print(df)

# Index of the column to be removed
column_index = 1

# Get the name of the column at the specified index
column_name = df.columns[column_index]

# Drop the column by its name
df.drop(columns=[column_name], inplace=True)

# Print the updated DataFrame
print("\nDataFrame After Removing Column at Index 1:")
print(df)

Remove multiple columns at once from a DataFrame in Pandas

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'Los Angeles', 'Chicago'],
    'Country': ['USA', 'USA', 'USA']
})

# Print the original DataFrame
print("Original DataFrame:")
print(df)

# List of columns to be removed
columns_to_remove = ['Age', 'Country']

# Drop the specified columns
df.drop(columns=columns_to_remove, inplace=True)

# Print the updated DataFrame
print("\nDataFrame After Removing Columns:")
print(df)

If you want to remove multiple columns by their indices, you can use the following code:

# List of column indices to be removed
column_indices_to_remove = [1, 3]

# Get the names of the columns at the specified indices
columns_to_remove = df.columns[column_indices_to_remove]

# Drop the specified columns
df.drop(columns=columns_to_remove, inplace=True)

 

Combine two DataFrames in Pandas

Using concat to Stack DataFrames Vertically

If the two DataFrames have the same columns and you want to stack them vertically, you can use the pd.concat method:

import pandas as pd

# Define the first DataFrame
df1 = pd.DataFrame({
    'Name': ['Alice', 'Bob'],
    'Age': [25, 30],
    'City': ['New York', 'Los Angeles']
})

# Define the second DataFrame
df2 = pd.DataFrame({
    'Name': ['Charlie', 'David'],
    'Age': [35, 40],
    'City': ['Chicago', 'Houston']
})

# Concatenate the two DataFrames
result = pd.concat([df1, df2])

# Print the result
print(result)

Using merge to Join DataFrames Horizontally

If you want to join two DataFrames based on a common column (for example, an ID), you can use the pd.merge method:

# Define the first DataFrame
df1 = pd.DataFrame({
    'ID': [1, 2],
    'Name': ['Alice', 'Bob']
})

# Define the second DataFrame
df2 = pd.DataFrame({
    'ID': [1, 2],
    'Age': [25, 30]
})

# Merge the two DataFrames on the 'ID' column
result = pd.merge(df1, df2, on='ID')

# Print the result
print(result)

 

GET and POST requests using Python

pip install requests

Making a Get request

# importing the requests library
import requests

# api-endpoint
URL = "http://maps.googleapis.com/maps/api/geocode/json"

# location given here
location = "delhi technological university"

# defining a params dict for the parameters to be sent to the API
PARAMS = {'address':location}

# sending get request and saving the response as response object
r = requests.get(url = URL, params = PARAMS)

# extracting data in json format
data = r.json()


# extracting latitude, longitude and formatted address
# of the first matching location
latitude = data['results'][0]['geometry']['location']['lat']
longitude = data['results'][0]['geometry']['location']['lng']
formatted_address = data['results'][0]['formatted_address']

# printing the output
print("Latitude:%s\nLongitude:%s\nFormatted Address:%s"
    %(latitude, longitude,formatted_address))

Making a POST request

# importing the requests library
import requests

# defining the api-endpoint
API_ENDPOINT = "http://pastebin.com/api/api_post.php"

# your API key here
API_KEY = "XXXXXXXXXXXXXXXXX"

# your source code here
source_code = '''
print("Hello, world!")
a = 1
b = 2
print(a + b)
'''

# data to be sent to api
data = {'api_dev_key':API_KEY,
        'api_option':'paste',
        'api_paste_code':source_code,
        'api_paste_format':'python'}

# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)

# extracting response text
pastebin_url = r.text
print("The pastebin URL is:%s"%pastebin_url)

References
https://www.geeksforgeeks.org/get-post-requests-using-python/
https://www.w3schools.com/python/ref_requests_post.asp

Printing all DNS records using DNSPython in Python

import dns.resolver


def get_records(domain):
    """
    Get all the records associated to domain parameter.
    :param domain: 
    :return: 
    """
    ids = [
        'NONE',
        'A',
        'NS',
        'MD',
        'MF',
        'CNAME',
        'SOA',
        'MB',
        'MG',
        'MR',
        'NULL',
        'WKS',
        'PTR',
        'HINFO',
        'MINFO',
        'MX',
        'TXT',
        'RP',
        'AFSDB',
        'X25',
        'ISDN',
        'RT',
        'NSAP',
        'NSAP-PTR',
        'SIG',
        'KEY',
        'PX',
        'GPOS',
        'AAAA',
        'LOC',
        'NXT',
        'SRV',
        'NAPTR',
        'KX',
        'CERT',
        'A6',
        'DNAME',
        'OPT',
        'APL',
        'DS',
        'SSHFP',
        'IPSECKEY',
        'RRSIG',
        'NSEC',
        'DNSKEY',
        'DHCID',
        'NSEC3',
        'NSEC3PARAM',
        'TLSA',
        'HIP',
        'CDS',
        'CDNSKEY',
        'CSYNC',
        'SPF',
        'UNSPEC',
        'EUI48',
        'EUI64',
        'TKEY',
        'TSIG',
        'IXFR',
        'AXFR',
        'MAILB',
        'MAILA',
        'ANY',
        'URI',
        'CAA',
        'TA',
        'DLV',
    ]
    
    for a in ids:
        try:
            answers = dns.resolver.query(domain, a)
            for rdata in answers:
                print(a, ':', rdata.to_text())
    
        except Exception as e:
            print(e)  # or pass

if __name__ == '__main__':
    get_records('google.com')

References
https://gist.github.com/akshaybabloo/2a1df455e7643926739e934e910cbf2e