DNA Sequence Pattern Finder

import matplotlib.pyplot as plt


# ---------------------------------------

# Basic DNA Validation

# ---------------------------------------

def validate_dna(sequence):

    sequence = sequence.upper()

    valid = set("ATCG")

    return all(base in valid for base in sequence)



# ---------------------------------------

# GC Content Calculation

# ---------------------------------------

def gc_content(sequence):

    gc_count = sequence.count("G") + sequence.count("C")

    return (gc_count / len(sequence)) * 100



# ---------------------------------------

# Motif Finder

# ---------------------------------------

def find_motif(sequence, motif):

    sequence = sequence.upper()

    motif = motif.upper()

    positions = []


    for i in range(len(sequence) - len(motif) + 1):

        if sequence[i:i+len(motif)] == motif:

            positions.append(i)


    return positions



# ---------------------------------------

# Mutation Comparison

# ---------------------------------------

def compare_sequences(seq1, seq2):

    mutations = []


    min_len = min(len(seq1), len(seq2))


    for i in range(min_len):

        if seq1[i] != seq2[i]:

            mutations.append((i, seq1[i], seq2[i]))


    return mutations



# ---------------------------------------

# GC Content Visualization (Sliding Window)

# ---------------------------------------

def gc_sliding_window(sequence, window_size=20):

    gc_values = []


    for i in range(len(sequence) - window_size + 1):

        window = sequence[i:i+window_size]

        gc_values.append(gc_content(window))


    return gc_values



def plot_gc_distribution(sequence):

    window_size = 20

    gc_values = gc_sliding_window(sequence, window_size)


    plt.figure(figsize=(10, 4))

    plt.plot(gc_values)

    plt.title("GC Content Distribution (Sliding Window)")

    plt.xlabel("Position")

    plt.ylabel("GC %")

    plt.show()



# ---------------------------------------

# MAIN

# ---------------------------------------

if __name__ == "__main__":

    dna = input("Enter DNA sequence: ").strip().upper()


    if not validate_dna(dna):

        print("❌ Invalid DNA sequence (Only A, T, C, G allowed)")

        exit()


    print("\n🧬 DNA Analysis Results\n")


    # GC Content

    gc = gc_content(dna)

    print(f"GC Content: {gc:.2f}%")


    # Motif Search

    motif = input("\nEnter motif to search (e.g., ATG): ").strip().upper()

    positions = find_motif(dna, motif)


    if positions:

        print(f"Motif '{motif}' found at positions: {positions}")

    else:

        print(f"Motif '{motif}' not found.")


    # Mutation Comparison

    compare = input("\nCompare with another sequence? (y/n): ").strip().lower()

    if compare == "y":

        dna2 = input("Enter second DNA sequence: ").strip().upper()


        if len(dna) != len(dna2):

            print("⚠ Sequences have different lengths. Comparing minimum length.")


        mutations = compare_sequences(dna, dna2)


        if mutations:

            print("\nMutations found:")

            for pos, base1, base2 in mutations:

                print(f"Position {pos}: {base1} → {base2}")

        else:

            print("No mutations detected.")


    # GC Distribution Plot

    plot = input("\nPlot GC content distribution? (y/n): ").strip().lower()

    if plot == "y":

        plot_gc_distribution(dna)


Color Contrast Accessibility Checker

import tkinter as tk

from tkinter import colorchooser

import math


# ---------------------------------------

# WCAG Calculation Functions

# ---------------------------------------


def hex_to_rgb(hex_color):

    hex_color = hex_color.lstrip("#")

    return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))



def linearize(value):

    value = value / 255

    if value <= 0.03928:

        return value / 12.92

    else:

        return ((value + 0.055) / 1.055) ** 2.4



def relative_luminance(rgb):

    r, g, b = rgb

    r = linearize(r)

    g = linearize(g)

    b = linearize(b)


    return 0.2126 * r + 0.7152 * g + 0.0722 * b



def contrast_ratio(color1, color2):

    L1 = relative_luminance(color1)

    L2 = relative_luminance(color2)


    lighter = max(L1, L2)

    darker = min(L1, L2)


    return (lighter + 0.05) / (darker + 0.05)



def wcag_result(ratio):

    result = ""


    if ratio >= 7:

        result += "AAA (Normal Text) \n"

    elif ratio >= 4.5:

        result += "AA (Normal Text) \n"

    else:

        result += "Fails AA (Normal Text) \n"


    if ratio >= 4.5:

        result += "AAA (Large Text) \n"

    elif ratio >= 3:

        result += "AA (Large Text) \n"

    else:

        result += "Fails Large Text \n"


    return result



# ---------------------------------------

# GUI

# ---------------------------------------


class ContrastChecker:

    def __init__(self, root):

        self.root = root

        self.root.title("WCAG Color Contrast Checker")

        self.root.geometry("500x400")


        self.color1 = "#000000"

        self.color2 = "#FFFFFF"


        self.build_ui()


    def build_ui(self):

        tk.Label(self.root, text="Foreground Color").pack(pady=5)

        tk.Button(self.root, text="Choose Color 1",

                  command=self.pick_color1).pack()


        tk.Label(self.root, text="Background Color").pack(pady=5)

        tk.Button(self.root, text="Choose Color 2",

                  command=self.pick_color2).pack()


        tk.Button(self.root, text="Check Contrast",

                  command=self.check_contrast).pack(pady=15)


        self.preview = tk.Label(self.root, text="Preview Text",

                                font=("Arial", 16))

        self.preview.pack(pady=10)


        self.result_label = tk.Label(self.root, text="", justify="left")

        self.result_label.pack(pady=10)


    def pick_color1(self):

        color = colorchooser.askcolor()[1]

        if color:

            self.color1 = color


    def pick_color2(self):

        color = colorchooser.askcolor()[1]

        if color:

            self.color2 = color


    def check_contrast(self):

        rgb1 = hex_to_rgb(self.color1)

        rgb2 = hex_to_rgb(self.color2)


        ratio = contrast_ratio(rgb1, rgb2)


        self.preview.config(

            fg=self.color1,

            bg=self.color2

        )


        result = f"Contrast Ratio: {ratio:.2f}:1\n\n"

        result += wcag_result(ratio)


        self.result_label.config(text=result)



# ---------------------------------------

# RUN

# ---------------------------------------


if __name__ == "__main__":

    root = tk.Tk()

    app = ContrastChecker(root)

    root.mainloop()


Project Time Tracker with App Detection

import time

import sqlite3

import psutil

import win32gui

from datetime import datetime


DB_NAME = "time_tracker.db"

CHECK_INTERVAL = 1  # seconds



# ----------------------------------------

# Database Setup

# ----------------------------------------

def init_db():

    conn = sqlite3.connect(DB_NAME)

    cursor = conn.cursor()


    cursor.execute("""

        CREATE TABLE IF NOT EXISTS app_usage (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            app_name TEXT,

            window_title TEXT,

            start_time TEXT,

            end_time TEXT,

            duration REAL

        )

    """)


    conn.commit()

    conn.close()



# ----------------------------------------

# Get Active Window Info

# ----------------------------------------

def get_active_window():

    hwnd = win32gui.GetForegroundWindow()

    window_title = win32gui.GetWindowText(hwnd)


    try:

        pid = win32gui.GetWindowThreadProcessId(hwnd)[1]

        process = psutil.Process(pid)

        app_name = process.name()

    except:

        app_name = "Unknown"


    return app_name, window_title



# ----------------------------------------

# Save Session

# ----------------------------------------

def save_session(app_name, window_title, start_time, end_time):

    duration = (end_time - start_time).total_seconds()


    conn = sqlite3.connect(DB_NAME)

    cursor = conn.cursor()


    cursor.execute("""

        INSERT INTO app_usage (app_name, window_title, start_time, end_time, duration)

        VALUES (?, ?, ?, ?, ?)

    """, (

        app_name,

        window_title,

        start_time.strftime("%Y-%m-%d %H:%M:%S"),

        end_time.strftime("%Y-%m-%d %H:%M:%S"),

        duration

    ))


    conn.commit()

    conn.close()



# ----------------------------------------

# Tracking Loop

# ----------------------------------------

def track_time():

    print("šŸ—‚ Project Time Tracker Started (Press Ctrl+C to stop)\n")


    current_app, current_title = get_active_window()

    start_time = datetime.now()


    try:

        while True:

            time.sleep(CHECK_INTERVAL)

            new_app, new_title = get_active_window()


            if new_app != current_app or new_title != current_title:

                end_time = datetime.now()

                save_session(current_app, current_title, start_time, end_time)


                current_app, current_title = new_app, new_title

                start_time = datetime.now()


    except KeyboardInterrupt:

        print("\nStopping tracker...")

        end_time = datetime.now()

        save_session(current_app, current_title, start_time, end_time)

        print("Session saved.")



# ----------------------------------------

# Summary Report

# ----------------------------------------

def show_summary():

    conn = sqlite3.connect(DB_NAME)

    cursor = conn.cursor()


    cursor.execute("""

        SELECT app_name, SUM(duration)/60 as total_minutes

        FROM app_usage

        GROUP BY app_name

        ORDER BY total_minutes DESC

    """)


    results = cursor.fetchall()

    conn.close()


    print("\n Time Usage Summary (Minutes):\n")

    for app, minutes in results:

        print(f"{app:20} {minutes:.2f} min")



# ----------------------------------------

# MAIN

# ----------------------------------------

if __name__ == "__main__":

    init_db()


    print("1. Start Tracking")

    print("2. Show Summary")


    choice = input("Choose option: ").strip()


    if choice == "1":

        track_time()

    elif choice == "2":

        show_summary()

    else:

        print("Invalid choice.")


Smart Log File Analyzer

import re

import pandas as pd

import numpy as np

from sklearn.ensemble import IsolationForest

import matplotlib.pyplot as plt


# -------------------------------------

# Log Pattern (Apache Common Log)

# -------------------------------------

log_pattern = re.compile(

    r'(?P<ip>\S+) - - \[(?P<time>.*?)\] '

    r'"(?P<method>\S+) (?P<url>\S+) \S+" '

    r'(?P<status>\d+) (?P<size>\d+)'

)


# -------------------------------------

# Parse Log File

# -------------------------------------

def parse_log(file_path):

    data = []


    with open(file_path, "r", encoding="utf-8", errors="ignore") as f:

        for line in f:

            match = log_pattern.search(line)

            if match:

                data.append(match.groupdict())


    df = pd.DataFrame(data)


    df["status"] = df["status"].astype(int)

    df["size"] = df["size"].astype(int)


    return df



# -------------------------------------

# Feature Engineering

# -------------------------------------

def extract_features(df):

    ip_counts = df.groupby("ip").size().reset_index(name="request_count")

    status_4xx = df[df["status"].between(400, 499)].groupby("ip").size().reset_index(name="errors")

    status_5xx = df[df["status"].between(500, 599)].groupby("ip").size().reset_index(name="server_errors")


    features = ip_counts.merge(status_4xx, on="ip", how="left")

    features = features.merge(status_5xx, on="ip", how="left")


    features.fillna(0, inplace=True)


    return features



# -------------------------------------

# Anomaly Detection

# -------------------------------------

def detect_anomalies(features):

    model = IsolationForest(contamination=0.05, random_state=42)


    X = features[["request_count", "errors", "server_errors"]]


    features["anomaly_score"] = model.fit_predict(X)

    features["is_suspicious"] = features["anomaly_score"] == -1


    return features



# -------------------------------------

# Visualization

# -------------------------------------

def visualize(features):

    plt.figure(figsize=(10, 5))


    normal = features[features["is_suspicious"] == False]

    suspicious = features[features["is_suspicious"] == True]


    plt.scatter(normal["request_count"], normal["errors"], label="Normal")

    plt.scatter(suspicious["request_count"], suspicious["errors"], label="Suspicious", marker="x")


    plt.xlabel("Request Count")

    plt.ylabel("4xx Errors")

    plt.legend()

    plt.title("Log Anomaly Detection")

    plt.show()



# -------------------------------------

# MAIN

# -------------------------------------

if __name__ == "__main__":

    path = input("Enter log file path: ").strip()


    print("Parsing logs...")

    df = parse_log(path)


    print(f"Loaded {len(df)} log entries.")


    features = extract_features(df)


    print("Detecting anomalies...")

    analyzed = detect_anomalies(features)


    suspicious = analyzed[analyzed["is_suspicious"] == True]


    print("\n Suspicious IP Addresses:\n")

    print(suspicious[["ip", "request_count", "errors", "server_errors"]])


    visualize(analyzed)


    analyzed.to_csv("log_analysis_report.csv", index=False)

    print("\n Report saved as log_analysis_report.csv")


Image Perspective Corrector

import cv2

import numpy as np


# ----------------------------------

# Order points correctly

# ----------------------------------

def order_points(pts):

    rect = np.zeros((4, 2), dtype="float32")


    s = pts.sum(axis=1)

    rect[0] = pts[np.argmin(s)]   # top-left

    rect[2] = pts[np.argmax(s)]   # bottom-right


    diff = np.diff(pts, axis=1)

    rect[1] = pts[np.argmin(diff)]  # top-right

    rect[3] = pts[np.argmax(diff)]  # bottom-left


    return rect



# ----------------------------------

# Perspective transform

# ----------------------------------

def four_point_transform(image, pts):

    rect = order_points(pts)

    (tl, tr, br, bl) = rect


    widthA = np.linalg.norm(br - bl)

    widthB = np.linalg.norm(tr - tl)

    maxWidth = max(int(widthA), int(widthB))


    heightA = np.linalg.norm(tr - br)

    heightB = np.linalg.norm(tl - bl)

    maxHeight = max(int(heightA), int(heightB))


    dst = np.array([

        [0, 0],

        [maxWidth - 1, 0],

        [maxWidth - 1, maxHeight - 1],

        [0, maxHeight - 1]

    ], dtype="float32")


    M = cv2.getPerspectiveTransform(rect, dst)

    warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))


    return warped



# ----------------------------------

# Detect document contour

# ----------------------------------

def detect_document(image):

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    blurred = cv2.GaussianBlur(gray, (5, 5), 0)


    edged = cv2.Canny(blurred, 75, 200)


    contours, _ = cv2.findContours(

        edged.copy(),

        cv2.RETR_LIST,

        cv2.CHAIN_APPROX_SIMPLE

    )


    contours = sorted(contours, key=cv2.contourArea, reverse=True)


    for contour in contours:

        peri = cv2.arcLength(contour, True)

        approx = cv2.approxPolyDP(contour, 0.02 * peri, True)


        if len(approx) == 4:

            return approx.reshape(4, 2)


    return None



# ----------------------------------

# Main

# ----------------------------------

if __name__ == "__main__":

    path = input("Enter image path: ").strip()


    image = cv2.imread(path)


    if image is None:

        print(" Could not load image.")

        exit()


    orig = image.copy()

    doc_cnt = detect_document(image)


    if doc_cnt is None:

        print(" Document edges not detected.")

        exit()


    warped = four_point_transform(orig, doc_cnt)


    # Convert to scanned look

    warped_gray = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)

    warped_thresh = cv2.adaptiveThreshold(

        warped_gray, 255,

        cv2.ADAPTIVE_THRESH_GAUSSIAN_C,

        cv2.THRESH_BINARY,

        11, 2

    )


    cv2.imshow("Original", orig)

    cv2.imshow("Scanned Output", warped_thresh)


    cv2.imwrite("scanned_output.jpg", warped_thresh)

    print(" Saved as scanned_output.jpg")


    cv2.waitKey(0)

    cv2.destroyAllWindows()