Snippets Collections
from PIL import Image, ImageDraw, ImageOps

def convert_image_to_circle(image_path):
    my_image = Image.open(image_path)
    # create mask 
    mask = Image.new('L', my_image.size)
    draw = ImageDraw.Draw(mask)
    # draw white circle
    draw.ellipse((0, 0) + mask.size, fill = 255)

    # create output image
    output = ImageOps.fit(my_image, mask.size, centering=(0.5, 0.5))
    output.putalpha(mask)
    output.save('out.png')



convert_image_to_circle('test.png')
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import mido
import random

def generate_notes(notes_len):
    notes = []
    for i in range(notes_len):
        notes.append(random.randint(0, 127))

    return notes



def create_midi_file(notes):
    output_midi = mido.MidiFile()
    # create a track 
    track = mido.MidiTrack()
    # add track
    output_midi.tracks.append(track)

    # write notes
    for note in notes:
        track.append(mido.Message('note_on', note = note, velocity=64, time = 120))
        track.append(mido.Message('note_off', note = note, velocity=64, time = 120))

    # write midi file
    output_midi.save('out.mid')

notes = generate_notes(100)
create_midi_file(notes)
import tkinter as tk


root = tk.Tk()
root.attributes('-fullscreen', True)

# this is very important
def close_fullscreen():
    root.attributes('-fullscreen', False)

# add bt to close fullscreen mode this is very important
close_bt = tk.Button(root, text='Close full screen mode', command=close_fullscreen)
close_bt.pack(fill=tk.BOTH)

root.mainloop()
# Enable gzip compression for text-based files
http {
   gzip on;
   gzip_types text/plain text/css text/javascript;
}
def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n-1)
Write a function named only_ints that takes two parameters. Your function should return True if both parameters are integers, and False otherwise.

For example, calling only_ints(1, 2) should return True, while calling only_ints("a", 1) should return False.
ChatGPT
ChatGPT
Here's a Python function named only_ints that checks if both parameters are integers:

python
Copy code
def only_ints(param1, param2):
    return isinstance(param1, int) and isinstance(param2, int)

# Example usage:
print(only_ints(1, 2))   # Output: True
print(only_ints("a", 1))  # Output: False

Copy and Save

Share

Ask Copilot

This function uses the isinstance() function to check if both parameters are of type int. If both are integers, it returns True; otherwise, it returns False.
engine = db.create_engine('sqlite:///datacamp.sqlite')
conn = engine.connect()
metadata = db.MetaData()

Student = db.Table('Student', metadata,
              db.Column('Id', db.Integer(),primary_key=True),
              db.Column('Name', db.String(255), nullable=False),
              db.Column('Major', db.String(255), default="Math"),
              db.Column('Pass', db.Boolean(), default=True)
              )

metadata.create_all(engine)
from sqlalchemy import create_engine
engine = create_engine("sqlite+pysqlite:///:memory:", echo=True)

connection = engine.connect()
print("Connected to the database successfully")
connection.close()
pip install SQLAlchemy
0 0.961847 0.151807 0.945783 0.151807 0.929719 0.166265 0.923695 0.180723 0.923695 0.207229 0.903614 0.243373 0.853414 0.26506 0.833333 0.279518 0.799197 0.289157 0.787149 0.289157 0.783133 0.284337 0.781124 0.255422 0.7751 0.243373 0.773092 0.166265 0.76506 0.151807 0.746988 0.159036 0.692771 0.207229 0.668675 0.209639 0.654618 0.216867 0.620482 0.216867 0.592369 0.207229 0.574297 0.207229 0.568273 0.214458 0.568273 0.240964 0.580321 0.26747 0.580321 0.279518 0.568273 0.296386 0.554217 0.344578 0.53012 0.383133 0.502008 0.414458 0.447791 0.513253 0.413655 0.595181 0.385542 0.689157 0.373494 0.780723 0.383534 0.807229 0.381526 0.850602 0.395582 0.872289 0.437751 0.891566 0.475904 0.901205 0.516064 0.903614 0.556225 0.915663 0.588353 0.908434 0.594378 0.889157 0.586345 0.860241 0.616466 0.824096 0.630522 0.79759 0.648594 0.742169 0.648594 0.689157 0.65261 0.684337 0.662651 0.693976 0.668675 0.739759 0.676707 0.761446 0.686747 0.773494 0.712851 0.778313 0.722892 0.766265 0.728916 0.744578 0.722892 0.66747 0.708835 0.631325 0.680723 0.60241 0.688755 0.566265 0.710843 0.53494 0.730924 0.46506 0.746988 0.440964 0.787149 0.404819 0.821285 0.392771 0.85743 0.366265 0.893574 0.325301 0.953815 0.26988 0.96988 0.209639 0.96988 0.168675
coco/
└── annotations/
    └── coco_annotations.json
coco_to_yolo.py
coco_converted/
├── images/
└── labels/
    └── coco_annotations/
        └── image1.txt
        └── image2.txt
python coco_to_yolo.py
.\venv\Scripts\activate.ps1
.\venv\Scripts\activate
python -m venv venv
cd path\to\your\project\directory
coco/
└── annotations/
    └── coco_annotations.json
coco_to_yolo.py
from ultralytics.data.converter import convert_coco
convert_coco(labels_dir='annotations', use_segments=True)
import serial
import struct
import time  # Added import for time module

# Define communication constants and machine information
BAUD_RATE = 38400
DATA_BITS = 8
STOP_BITS = 1
PARITY = serial.PARITY_NONE
NODE_ID = 0x01

# Define commands for motor control
SET_CONTROLWORD_CMD = 0x2B
SET_OPERATION_MODE_CMD = 0x2F
SET_TARGET_POSITION_CMD = 0x41
READ_STATUSWORD_CMD = 0x4B
SET_PROFILE_SPEED_CMD = 0x23

# Define functions to calculate checksum and send commands
def calculate_checksum(data):
    return (-sum(data) % 256) & 0xFF

def send_command(serial_port, cmd, index, sub_index, data=None):
    if data is None:
        data = b''
    packet = bytes([NODE_ID, cmd, index & 0xFF, index >> 8, sub_index, *data])
    checksum = calculate_checksum(packet)
    packet += bytes([checksum])
    serial_port.write(packet)
    response = serial_port.read(8)
    return response

# Motor control functions
def move_to_position(serial_port, position):
    response = send_command(serial_port, SET_TARGET_POSITION_CMD, 0x607A, 0x00, data=list(struct.pack('<i', position)))
    print(f"Response (Move to Position {position}):", response.hex())

def set_speed(serial_port, speed):
    speed_bytes = struct.pack('<i', speed)
    response = send_command(serial_port, SET_PROFILE_SPEED_CMD, 0x6081, 0x00, data=list(speed_bytes))
    print(f"Response (Set Speed {speed}):", response.hex())

def start_motion(serial_port):
    response = send_command(serial_port, SET_CONTROLWORD_CMD, 0x6040, 0x00, data=[0x0F, 0x00, 0x00, 0x00])  # Start motion
    print("Response (Start motion):", response.hex())

def stop_motion(serial_port):
    response = send_command(serial_port, SET_CONTROLWORD_CMD, 0x6040, 0x00, data=[0x06, 0x00, 0x00, 0x00])  # Stop motion
    print("Response (Stop motion):", response.hex())

def move_to_positions(serial_port, positions):
    for pos in positions:
        move_to_position(serial_port, pos)
        time.sleep(1)  # Added delay to allow time for motion
        set_speed(serial_port, 200)  # Set speed to 200 RPM
        start_motion(serial_port)
        time.sleep(5)  # Added delay to simulate motion time
        stop_motion(serial_port)

# Main function
def main():
    serial_port = serial.Serial('COM3', baudrate=BAUD_RATE, bytesize=DATA_BITS, stopbits=STOP_BITS, parity=PARITY, timeout=1)

    try:
        positions = [5000001, 6000001, 7000001]
        move_to_positions(serial_port, positions)

    finally:
        serial_port.close()

if __name__ == "__main__":
    main()
class Solution(object):
  def lengthOfLongestSubstring(self, s):
    max_sub_length = 0
    start = 0
    s_length = len(s)
    
    for end in range(1, s_length):
      if s[end] in s[start:end]:
        start = s[start:end].index(s[end]) + 1 + start
      else:
        max_sub_length = max(max_sub_length, end - start + 1)
	return max_sub_length    
c3.Genai.UnstructuredQuery.Engine.REA.RetrieverConfig.make('materiality_retriever_config').getConfig().setConfigValue("numRetrievedPassages", 10)
import math


class Circle:
    def __init__(self, radius):
        self._radius = radius
        self._area = None

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError('Radius must be positive')

        if value != self._radius:
            self._radius = value
            self._area = None

    @property
    def area(self):
        if self._area is None:
            self._area = math.pi * self.radius ** 2

        return self._area
Code language: Python (python)
numbers = (*odd_numbers, *even_numbers)
print(numbers)
Code language: Python (python)
numbers = (*odd_numbers, *even_numbers)
print(numbers)
Code language: Python (python)
numbers = (*odd_numbers, *even_numbers)
print(numbers)
Code language: Python (python)
new_stocks = {symbol: price * 1.02 for (symbol, price) in stocks.items()}

Code language: Python (python)
cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico']

for item in enumerate(cities):
    print(item)
Code language: Python (python)
list_of_dicts = [
    {'name': 'Alice', 'age': 30},
    {'name': 'Bob', 'age': 25},
    {'name': 'Charlie', 'age': 35}
]
person = next((item for item in list_of_dicts if item.get('name') == 'Bob'),  "person not found." )
print(f"Found: {person}")
class Celsius:
    def __init__(self, temperature=0):
        # This calls the setter method `temperature(self, value)` below 
        self.temperature = temperature

    def to_farenheit(self):
        # This calls the getter method (`temperature(self)`) method below
        return (self.temperature * 1.8) + 32

    @property
	def temperature(self):
        """
        Getter method for the `temperature` property.
        If you create an instance of this class and then refer to the
            `temperature` property of that instance then this method will be called.

        Example:
            t = Celsius(37)
            t.temperature  <-- this is where this getter method is called
        """
        print("Getting value...")
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        """
        Setter method for the `temperature` property.
        If you create an instance of this class and then assign a value
            to the `temperature` property of that instance then this method will be called.

        Example:
            t = Celsius(37)  <-- this is where this setter method is called
            t.temperature  
        """
        print("Setting value...")
        if value < -273.15:
            raise ValueError("Temperature below -273 is not possible")
        self._temperature = value


human = Celsius(37)  # Setting value...
print(human.temperature)  # Getting value...
print(human.to_farenheit())  # Setting value...
coldest_thing = Celsius(-300)  # ValueError
class Dates:
    def __init__(self, date):
    	self.date = date

    def get_date(self):
    	return self.date

    @staticmethod
    def format_date_with_dashes(date):
      	# Replace / with -
    	return date.replace("/", "-")


slash_date = "10/20/2024"
# Calling format_date_with_dashes() like any other function, but preceded by it's class name
dash_date = Dates.format_date_with_dashes(slash_date)

print(dash_date)  # 10-20-2024
from datetime import date


# random Person
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_birth_year(cls, name, birth_year):
    	# Since `cls` refers to the class itself (`Person`), calling this
        #	`classmethod` creates an instance of `Person`.
    	return cls(name, date.today().year - birth_year)

    def display(self):
    	print(f"{self.name}'s age is: {self.age}")


bob = Person("Bob", 25)
bob.display()  # Bob's age is: 25

alice = Person.from_birth_year("Alice", 1985)
alice.display()  # Alice's age is: 39
class Rectangle:
    def __init__(self, length, width):
    	self.length = length
		self.width = width

    def area(self):
    	return self.length * self.width


class Square(Rectangle):
    def __init__(self, length):
        # Call the __init__ method of the parent class (Rectangle)
        # super() refers to the parent class of this class
        # Actually using the __init__ method of `Rectangle` here
        #	which needs 2 parameters, `length` and `width`. Since
        #	a square is length==width then we use `length` twice.
    	super().__init__(length, length)


my_square = Square(5)
my_square.area()  # 25
from abc import ABC, abstractmethod


class Shape(ABC):
# Shape is an abstract base class

    @abstractmethod
    def area(self):
        pass


class Circle(Shape):
# Circle is a class that inherits from the abstract Shape class

    def __init__(self, radius):
    	self.radius = radius
	
    def area(self):
   	# As a child of an Abstract class, this child class MUST define
    #	it's own implementation of this abstractmethod
    	return 3.14 * self.radius ** 2


class Square(Shape):
# Square is a class that inherits from the abstract Shape class

    def __init__(self, side):
    	self.side = side

    def area(self):
    # As a child of an Abstract class, this child class MUST define
    #	it's own implementation of this abstractmethod
    	return self.side ** 2
Test automation code involves creating test cases, handling different locators, interacting with various elements, and implementing assertions to validate expected outcomes. I am sharing a general example using Python with the popular testing framework, Selenium, for web automation.

from selenium import webdriver
from selenium.webdriver.common.by import By

# Set up the WebDriver (assuming Chrome for this example)
driver = webdriver.Chrome(executable_path='path/to/chromedriver.exe')

# Navigate to a website
driver.get('https://www.example.com')

# Find an element using its ID and perform an action (e.g., click)
element = driver.find_element(By.ID, 'example-button')
element.click()

# Perform an assertion to verify the expected result
assert "Example Domain" in driver.title

# Close the browser window
driver.quit()

# Demonstrated Python Program
# to read file character by character
file = open('file.txt', 'r')
 
while 1:
     
    # read by character
    char = file.read(1)          
    if not char: 
        break
         
    print(char)
 
file.close()
d = {}
with open("file.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[int(key)] = val
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import pandas as pd
import time

web = 'https://twitter.com/'
path = r"C:\Drivers\chromedriver-win64\chromedriver.exe"
options = webdriver.ChromeOptions()
service = Service(executable_path=path)
options.add_experimental_option("detach", True)
options.add_argument('window-size=1920x1080')

driver = webdriver.Chrome(service=service, options=options)
driver.get(web)  # Open the webpage

# Wait for the login button to be clickable
login_button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, '//a[contains(@href, "/login")]'))
)
login_button.click()
time.sleep(2)

# Wait for the username input field to be visible and then enter username
user_name = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.XPATH, '//input[contains(@autocomplete, "username")]'))
)
user_name.send_keys("mnis00014@gmail.com")

# Wait for the next button to be clickable and then click
next_button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, '//div[contains(@role, "button")]//span[text()="Next"]'))
)
next_button.click()

time.sleep(2)

# Wait for the password input field to be visible and then enter password
password = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.XPATH, '//input[contains(@autocomplete, "current-password")]'))
)
password.send_keys("Tw@mnis@2024")

# Wait for the login button to be clickable and then click
login_button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, '//div[contains(@role, "button")]//span[text()="Log in"]'))
)
login_button.click()

# closing driver
# driver.quit()
def retry(operation, attempts):
  for n in range(attempts):
    if operation():
      print("Attempt " + str(n) + " succeeded")
      break
    else:
      print("Attempt " + str(n) + " failed")

retry(create_user, 3)
retry(stop_service, 5)
def factorial(n):
    result = 1
    for x in range(0,10):
        result = result * x
    return x

for n in range(0,10):
  print(n, n*factorial(n+1))
# Handle pagination with Selenium
# Scrape Website (www.audible.com)

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import pandas as pd
import time

path = r"C:\Drivers\chromedriver-win64\chromedriver.exe"
website = "https://www.audible.com/search"

# Use the Service class to specify the path to chromedriver.exe
service = Service(executable_path=path)

# Use ChromeOptions for additional configurations
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)

# Initialize the WebDriver with the specified service and options
driver = webdriver.Chrome(service=service, options=options)

# Navigate to the specific website
driver.get(website)

# Wait for some time to ensure the page is loaded
time.sleep(5)

try:
    # Wait for the container to be present
    container = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CLASS_NAME, 'adbl-impression-container'))
    )

    # Wait for the products to be present within the container
    products = WebDriverWait(container, 10).until(
        EC.presence_of_all_elements_located((By.XPATH, './/li[contains(@class, "productListItem")]'))
    )

    book_title = []
    author_name = []
    run_time = []
    release_date = []

    for product in products:
        try:
            # Wait for the book title element to be present within each product
            book_title_elem = WebDriverWait(product, 5).until(
                EC.presence_of_element_located((By.XPATH, './/h3[contains(@class, "bc-heading")]'))
            )

            # Append book title
            book_title.append(book_title_elem.text)
            
            # Append author name
            author_name_elem = product.find_element(By.XPATH, './/li[contains(@class, "authorLabel")]')
            author_name.append(author_name_elem.text)

            # Append run time
            run_time_elem = product.find_element(By.XPATH, './/li[contains(@class, "runtimeLabel")]')
            run_time.append(run_time_elem.text)

            # Append release date
            release_date_elem = product.find_element(By.XPATH, './/li[contains(@class, "releaseDateLabel")]')
            release_date.append(release_date_elem.text)

        except TimeoutException:
            print("Timeout occurred while waiting for element within product.")
            # Handle the timeout situation here (e.g., skip this product or log the issue)

    # Create DataFrame and save to CSV
    df = pd.DataFrame({'book_title': book_title,
                       'author_name': author_name,
                       'run_time': run_time,
                       'release_date': release_date})

    df.to_csv('amazon_audible.csv', index=False)
    print(df)

except TimeoutException:
    print("Timeout occurred while waiting for container element.")
    # Handle the timeout situation here (e.g., retry navigating to the page or log the issue)

finally:
    # Quit the driver
    driver.quit()

# Import necessary libraries
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd
from selenium.common.exceptions import NoSuchElementException, TimeoutException

# Set the path to chromedriver.exe
path = r"C:\Drivers\chromedriver-win64\chromedriver.exe"
website = "https://www.adamchoi.co.uk/overs/detailed"

# Use the Service class to specify the path to chromedriver.exe
service = Service(executable_path=path)

# Use ChromeOptions for additional configurations
options = webdriver.ChromeOptions()

# Add the --headless option to run Chrome in headless mode (optional)
# options.add_argument("--headless")

# Add the --detach option to keep the browser open after the script finishes
options.add_experimental_option("detach", True)

# Initialize the WebDriver with the specified service and options
driver = webdriver.Chrome(service=service, options=options)

# Navigate to the specified website
driver.get(website)

try:
    # Wait for the "All matches" button to be clickable
    all_matches_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '//label[@analytics-event="All matches"]'))
    )

    # Click on the "All matches" button
    all_matches_button.click()

    # Wait for the matches to load (adjust the timeout as needed)
    WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.TAG_NAME, "tr"))
    )

    # Get all match elements
    matches = driver.find_elements(By.TAG_NAME, "tr")

    date = []
    home_team = []
    score = []
    away_team = []

    # Extract data from each match
    for match in matches:
        date.append(match.find_element("xpath", "./td[1]").text)
        home_team.append(match.find_element("xpath", "./td[2]").text)
        score.append(match.find_element("xpath", "./td[3]").text)
        away_team.append(match.find_element("xpath", "./td[4]").text)

except (NoSuchElementException, TimeoutException) as e:
    print(f"Error: {e}")

finally:
    # Close the WebDriver when you're done
    driver.quit()

# Create a DataFrame from the scraped data
df = pd.DataFrame({'date': date,
                   'home_team': home_team,
                   'score': score,
                   'away_team': away_team})

# Save the DataFrame to a CSV file
df.to_csv('football_data.csv', index=False)

# Print the DataFrame
print(df)
# ---------------------------    Chrome   ---------------------------------

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
import pandas as pd
import time

path = r"C:\Drivers\chromedriver-win64\chromedriver.exe"
website = "https://www.adamchoi.co.uk/overs/detailed"

# Use the Service class to specify the path to chromedriver.exe
service = Service(executable_path=path)

# Use ChromeOptions for additional configurations
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)

# Initialize the WebDriver with the specified service and options
driver = webdriver.Chrome(service=service, options=options)

# Navigate to the specified website
driver.get(website)

all_matches_button = driver.find_element("xpath", '//label[@analytics-event="All matches"]')
all_matches_button.click()

dropdown = Select(driver.find_element(By.ID, "country"))
dropdown.select_by_visible_text('Spain')

time.sleep(3)

matches = driver.find_elements(By.TAG_NAME, "tr")

date = []
home_team = []
score = []
away_team = []

for match in matches:
    date.append(match.find_element("xpath", "./td[1]").text)
    home_team.append(match.find_element("xpath", "./td[2]").text)
    score.append(match.find_element("xpath", "./td[3]").text)
    away_team.append(match.find_element("xpath", "./td[4]").text)

# Close the WebDriver when you're done
driver.quit()

df = pd.DataFrame({'date': date,
                   'home_team': home_team,
                   'score': score,
                   'away_team': away_team})
df.to_csv('football_data.csv', index=False)
print(df)
# ---------------------------    Chrome   ---------------------------------

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

path = r"C:\Drivers\chromedriver-win64\chromedriver.exe"
website = "https://www.adamchoi.co.uk/overs/detailed"

# Use the Service class to specify the path to chromedriver.exe
service = Service(executable_path=path)

# Use ChromeOptions for additional configurations
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)

# Initialize the WebDriver with the specified service and options
driver = webdriver.Chrome(service=service, options=options)

# Navigate to the specified website
driver.get(website)

all_matches_button = driver.find_element("xpath", '//label[@analytics-event="All matches"]')
all_matches_button.click()

matches = driver.find_elements(By.TAG_NAME, "tr")

date = []
home_team = []
score = []
away_team = []

for match in matches:
    date.append(match.find_element("xpath", "./td[1]").text)
    home_team.append(match.find_element("xpath", "./td[2]").text)
    home = match.find_element("xpath","./td[2]").text
    print(home)
    score.append(match.find_element("xpath", "./td[3]").text)
    away_team.append(match.find_element("xpath", "./td[4]").text)

# Close the WebDriver when you're done
# driver.quit()

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
import pandas as pd
import time

path = r"C:\Drivers\chromedriver-win64\chromedriver.exe"
website = "https://www.adamchoi.co.uk/overs/detailed"

# Use the Service class to specify the path to chromedriver.exe
service = Service(executable_path=path)

# Use ChromeOptions for additional configurations
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)

# Initialize the WebDriver with the specified service and options
driver = webdriver.Chrome(service=service, options=options)

# Navigate to the specified website
driver.get(website)

all_matches_button = driver.find_element("xpath", '//label[@analytics-event="All matches"]')
all_matches_button.click()

dropdown = Select(driver.find_element(By.ID, "country"))
dropdown.select_by_visible_text('Spain')

time.sleep(3)

matches = driver.find_elements(By.TAG_NAME, "tr")

date = []
home_team = []
score = []
away_team = []

for match in matches:
    date.append(match.find_element("xpath", "./td[1]").text)
    home_team.append(match.find_element("xpath", "./td[2]").text)
    score.append(match.find_element("xpath", "./td[3]").text)
    away_team.append(match.find_element("xpath", "./td[4]").text)

# Close the WebDriver when you're done
driver.quit()

df = pd.DataFrame({'date': date,
                   'home_team': home_team,
                   'score': score,
                   'away_team': away_team})
df.to_csv('football_data.csv', index=False)
print(df)
import fiftyone as fo
from fiftyone.zoo import load_zoo_dataset

def download_vehicle_images():
    # Specify the classes of interest (e.g., vehicles, cars)
    classes_of_interest = ["Car", "Truck", "Motorcycle", "Bus", "Van"]

    # Specify the maximum number of samples you want to download
    max_samples = 100  # You can adjust this number as needed

    # Load the Open Images V7 dataset using FiftyOne
    dataset = load_zoo_dataset(
        "open-images-v7",
        split="validation",
        label_types=["detections", "segmentations", "points"],
        classes=classes_of_interest,
        max_samples=max_samples,
    )

    # Save the downloaded dataset
    dataset.export(export_dir="/path/to/save/vehicle/images")

if __name__ == "__main__":
    # Execute the download function
    download_vehicle_images()
import cProfile

# Use `profile` if `cProfile` isn't available on your OS
# import profile


def adder(x, y):
	return x + y


cProfile.run('adder(10, 20)')
import timeit


def adder(x, y):
	return x + y


t = timeit.Timer(setup='from __main__ import adder', stmt='adder(10, 20)')
t.timeit()
while True:
    try:
        marks = float(input('Enter your marks to calculate your grade: \n'))
    except ValueError:
        print('Invalid input, try again')
        continue
    if marks > 100:
        print('your input must not be greater than 100')
    else:
        break

if 85 <= marks <= 100:
    print('You have grade A')
elif 65 <= marks < 85:
    print('You have grade B')
elif 41 <= marks < 65:
    print('You have grade C')
elif 0 <= marks < 41:
    print('You failed')
else:
    print('Invalid Marks')
How to write a great documentation (in 5 points)

1. Use question and answer look (more like FAQs)
2. Use pointers wherever possible
    a. maximum 5, preferably 3
    b. if goes beyond 5, try making sub-points instead
3. Diagrams wherever possible. a 🖼 is worth a 1000 words
4. Be precise, but accurate. And have  w h i t e  s p a c e s , increases readability.
5. Avoid similar synonyms, generous adjectives, spellnig and grammatical the mistakes
    a. repeat same words already used to refer something
    b. have links to go to something previously explained
    c. Avoid external links, instead provide a brief. Add link only for confidence (reduces distraction)
"""
Exercise 1.10: Evaluate a Gaussian Function
"""

from math import pi, exp, sqrt

m = 0
s = 2
x = 1

y = (1 / (sqrt(2 * pi) * s)*exp((-1/2) * (((x - m)/s) ** 2)))
print(y)

'''
Sample run:
    y = 0.176032663
'''
    
# If the program reached this point, that means the number is prime
return True  
# Loop through all numbers between 2 and n - 1, and check if n is NOT prime
i = 2
while i < n:
    if n % i == 0:
        return False
    i = i + 1
# Deal with special cases
if n == 0 or n == 1:
    return False
from flask import Flask, render_template
from flask.ext.wtf import Form, SubmitField, Field, TextInput

app = Flask(__name__)
app.config['SECRET_KEY'] = 'Shh!'


class CustomField(Field):
    widget = TextInput()
    
    def _value(self):
        if self.data:
            return u', '.join(self.data)
        else:
            return u''

    def process_formdata(self, valuelist):
        if valuelist:
            self.data = [x.strip() for x in valuelist[0].split(',')]
        else:
            self.data = []


class ExampleForm(Form):
    status = CustomField()
    submit = SubmitField('POST')
from sys import path
import os
path.append(os.path.realpath('../'))
# split()
# دالة تقوم بتقسيم السلسلة إلى قائمة من الكلمات باستخدام (المسافات أو أي نص آخر) كفاصل
# Syntax: string.split(sep=None, maxsplit=-1) -> list[LiteralString]
# sep => Separator    NOTE: By default any (whitespace) is a separator
# maxsplit => عايز التقسيم يكون في كام عنصر؟
# maxsplit => لو كتبت مثلا 2 ترجع 3عناصر وهكذا، يعني النتيجة بتكون +1 يعني التقسيم تم في 2 والباقي نزله في عنصر واحد الاخير

## أختها الوحيدة ##########################
# rsplit()  # Right Split
################################################################

txt1 = "welcome to the jungle"
txt2 = "welcome#to#the#jungle"

print("============(split)===================================")
x1 = txt1.split()           
x2 = txt1.split(" ",2)
x3 = txt2.split("#")
print(x1)                   # ['welcome', 'to', 'the', 'jungle']
print(x2)                   # ['welcome', 'to', 'the jungle']
print(x3)                   # ['welcome', 'to', 'the', 'jungle']

print("============(rsplit)===================================")
y1 = txt1.rsplit(None,2)
y2 = txt1.rsplit(" ",2)
print(y1)                    # ['welcome to', 'the', 'jungle']
print(y2)                    # ['welcome to', 'the', 'jungle']
person_info = {
    'Name': 'Ahmed',
    'Age': 25,
    'City': 'Cairo'
}
FROM python:3.9-slim-bullseye

ENV VIRTUAL_ENV=/opt/venv
RUN python3 -m venv $VIRTUAL_ENV
ENV PATH="$VIRTUAL_ENV/bin:$PATH"

# Install dependencies:
COPY requirements.txt .
RUN pip install -r requirements.txt

# Run the application:
COPY myapp.py .
CMD ["python", "myapp.py"]
Page segmentation modes:
  0    Orientation and script detection (OSD) only.
  1    Automatic page segmentation with OSD.
  2    Automatic page segmentation, but no OSD, or OCR.
  3    Fully automatic page segmentation, but no OSD. (Default)
  4    Assume a single column of text of variable sizes.
  5    Assume a single uniform block of vertically aligned text.
  6    Assume a single uniform block of text.
  7    Treat the image as a single text line.
  8    Treat the image as a single word.
  9    Treat the image as a single word in a circle.
 10    Treat the image as a single character.
 11    Sparse text. Find as much text as possible in no particular order.
 12    Sparse text with OSD.
 13    Raw line. Treat the image as a single text line,
                        bypassing hacks that are Tesseract-specific.
from fastapi import FastAPI, HTTPException, Security, status
from fastapi.security import APIKeyHeader


api_keys = [
    "my_api_key"
]

app = FastAPI()

api_key_header = APIKeyHeader(name="X-API-Key")

def get_api_key(api_key_header: str = Security(api_key_header)) -> str:
    if api_key_header in api_keys:
        return api_key_header
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid or missing API Key",
    )

@app.get("/protected")
def protected_route(api_key: str = Security(get_api_key)):
    # Process the request for authenticated users
    return {"message": "Access granted!"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)


wget https://blah/blah/stats --header="X-API-Key: key1"
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import io
import pandas as pd

app = FastAPI()

@app.get("/get_csv")
async def get_csv():
    df = pd.DataFrame(dict(col1 = 1, col2 = 2), index=[0])
    stream = io.StringIO()
    df.to_csv(stream, index = False)
    response = StreamingResponse(iter([stream.getvalue()]),
                                 media_type="text/csv"
                                )
    response.headers["Content-Disposition"] = "attachment; filename=export.csv"
    return response
Alternate command for 1 GPU:

sockeye-train \
    --prepared-data prepared --validation-source dev.en.bpe \
    --validation-target dev.de.bpe --output model --num-layers 6 \
    --transformer-model-size 1024 --transformer-attention-heads 16 \
    --transformer-feed-forward-num-hidden 4096 --amp --batch-type max-word \
    --batch-size 5000 --update-interval 80 --checkpoint-interval 500 \
    --max-updates 15000 --optimizer-betas 0.9:0.98 \
    --initial-learning-rate 0.06325 \
    --learning-rate-scheduler-type inv-sqrt-decay --learning-rate-warmup 4000 \
    --seed 1
# Best min size, in kB.
best_min_size = (32000 + 100000) * (1.073741824 * duration) / (8 * 1024)
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client


# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)

verification = client.verify \
                     .v2 \
                     .services('VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                     .verifications \
                     .create(to='+15017122661', channel='sms')

print(verification.sid)
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client


# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)

verification = client.verify \
                     .v2 \
                     .services('VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                     .verifications \
                     .create(to='+15017122661', channel='sms')

print(verification.sid)
1. Create File "Dockerfile" in same directory as "docker-compose.yaml"
2. Write 
FROM apache/airflow:2.0.2
RUN pip install --no-cache-dir geopandas another-package
3. Build new image:
docker build . --tag projectname-airflow:2.0.2
4. In "docker-compose.yaml" replace
image: ${AIRFLOW_IMAGE_NAME:-apache/airflow:2.0.2}
with 
image: ${AIRFLOW_IMAGE_NAME:-projectname-airflow:2.0.2}
5. In Shell move to directory an run
docker build . --tag projectname-airflow:2.0.2
6. Epic win
JupyterHub.ensureService({waitForReady:true})
import holidays
from datetime import datetime, timedelta


# Get current date/time
tday = datetime.now()
testday = datetime(2023,12,1,13,13,0)    # for debug only

tday = testday    # for debug only
aims_rec_date = tday.strftime('%Y-%m-%d')
aims_time = tday.strftime('%H:%M:%S')
same_day_despatch_cut_off_time = datetime.strptime(aims_rec_date + " 13:00:00", "%Y-%m-%d %H:%M:%S")
add_days = 0

print(f"*******************************\nReceipt: {aims_rec_date} @ {aims_time}")

# Early enough for same-day despatch?
wk_day = int(tday.strftime('%w'))
if wk_day in range(1,5+1):
    despatch_today = tday < same_day_despatch_cut_off_time
    print(f"Despatch today: {despatch_today}")
    if not despatch_today:
        add_days = 1
else:
    print("Weekend...")

# Set provisional despatch date
aims_despatch_date = (tday + timedelta(days=add_days))

# Only interested in these public holidays
occasions = [
    "New Year's Day",
    "Good Friday",
    "Easter Monday [England/Wales/Northern Ireland]",
    "May Day",
    "Spring Bank Holiday",
    "Late Summer Bank Holiday [England/Wales/Northern Ireland]",
    "Christmas Day",
    "Boxing Day",
]
uk_holidays = holidays.UnitedKingdom()

print(f"UK Holiday: {aims_despatch_date in uk_holidays}")

# Amend provisional despatch date if not working day
while aims_despatch_date in uk_holidays or int(aims_despatch_date.strftime('%w')) in [0,6]:
    print("****skip-a-day****")
    try:    # amend for public holiday
        occasion = uk_holidays[aims_despatch_date]
        if occasion in occasions:
            aims_despatch_date = (aims_despatch_date + timedelta(days=1))
            wk_day = aims_despatch_date.strftime('%w')
        else:
            break
    except Exception as e:    # amend for weekend
        aims_despatch_date = (aims_despatch_date + timedelta(days=1))
        wk_day = aims_despatch_date.strftime('%w')


print(f"Despatch: {aims_despatch_date.strftime('%Y-%m-%d')}\n*******************************\n")
# Assume -9999 is a missing data flag
df.replace(-9999, np.NaN)
# Alternatively, perform this when creating the dataframe:
pd.read_csv("https://www.atmos.albany.edu/products/metarCSV/world_metar_latest.csv", sep='\s+',na_values=['9999.00','-9999.0'])
import xarray as xr
import numpy as np
from xarray.core.duck_array_ops import isnull


array = xr.DataArray([1, np.nan, 3], dims="x")
array

%time np.sum(isnull(array.data), axis=()).sum()
# core/settings.py 

# other settings....

CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://redis:6379/",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient"
            },
        }
    }
t = int(input(""))
p = 0
mylist = []
if t >= 0 and t < 101:
    while p<t:
        a = int(input("a "))
        b = int(input("b "))
        c = int(input("c "))
        if a <= 20000 and a >= 1:
            if b <= 20000 and a >=1:
                if c <= 20000 and c >=1:
                    if a+b<=c or a+c<=b or b+c<=a:
                        txt = ("nelze sestrojit")
                    else:
                        if a == b and b == c and c == a:
                            txt = ("rovnostranny")
                        elif a == b or b == c or c == a:
                            txt = ("rovnoramenny")
                        else:
                            txt = ("obecny")
                else:
                    txt = ("moc velké nebo malé číslo")
            else:
                txt = ("moc velké nebo malé číslo")
        else:
            txt = ("moc velké nebo malé číslo")
        p = p+1
        mylist.append(txt)
        print(p)
    print(mylist)
else:
    print("syntax")
def res(vys):
    for x in vys:
        print(x)
try:
    s = int(input("s "))
    p = 0
    lst = []
    if s >=1 and s <=100:
        while p<s:
            z = input("z ")
            if len(z) >= 1 and len(z) <= 50:
                try:
                    num = int(z)
                    kys = type(num) == int
                except:
                    kys = z.isupper()     
                if kys == True:
                    pal = z[::-1]
                    if z == pal:
                        txt = "yes"
                    else:
                        txt = "no"
                else:
                    txt = "syntax"
            else:
                txt = "syntax"
            p = p+1
            lst.append(txt)
            print("")
        res(lst)
    else:
        print("syntax")
except:
    print("syntax")
import cv2
import numpy as np

img = cv2.imread('blackdots.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(gray_img, 170, 255, cv2.THRESH_BINARY) # <--- Try different values here

accum_size = 1
# Minimum distance between the centers of the detected circles.
minDist = 30
#First method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the higher threshold of the two passed to the Canny() edge detector (the lower one is twice smaller).
param1 = 50
# Second method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the accumulator threshold for the circle centers at the detection stage. The smaller it is, the more false circles may be detected. Circles, corresponding to the larger accumulator values, will be returned first.
param2 = 5
#
minRadius = 1
#
maxRadius = 10
circles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, accum_size, minDist,
                           param1=param1, param2=param2,
                           minRadius=minRadius, maxRadius=maxRadius)
circles = circles.reshape(1,circles.shape[1], circles.shape[2])
if circles is not None:
    circles = np.uint16(np.around(circles))
    for ind, i in enumerate(circles[0, :]):
        center = (i[0], i[1])
        radius = 15
        cv2.circle(img, center, radius, (255, 0, 255), 3)

thresh = cv2.resize(thresh, (1280, 720)) # <---- This is just for easier display
img = cv2.resize(img, (1280, 720)) # <---- This is just for easier display
cv2.imwrite('circles_black_dot.png', img)
cv2.imwrite('threshold_black_dots.png', thresh)
cdo -expr,'var = ((var > 0.005)) ? var : 0.05' infile outfile
# Create a virtual environment
python -m venv env

# Activate virtual environment
source env/bin/activate
print(c3.Pkg.file('meta://esg/src/model/mentionTracking/EsgMentionTrackingMl.MentionTrackingPipeline.py').readString())
ls = [1, 2, 9, 4, 5, 2, 3, 9, 1]
result = max(ls, key=ls.count)

# or
# result = max(set(ls), key=ls.count)
# STEP 1
# import libraries
import fitz
import io
from PIL import Image
  
# STEP 2
# file path you want to extract images from
file = "/content/pdf_file.pdf"
  
# open the file
pdf_file = fitz.open(file)
  
# STEP 3
# iterate over PDF pages
for page_index in range(len(pdf_file)):
    
    # get the page itself
    page = pdf_file[page_index]
    image_list = page.getImageList()
      
    # printing number of images found in this page
    if image_list:
        print(f"[+] Found a total of {len(image_list)} images in page {page_index}")
    else:
        print("[!] No images found on page", page_index)
    for image_index, img in enumerate(page.getImageList(), start=1):
        
        # get the XREF of the image
        xref = img[0]
          
        # extract the image bytes
        base_image = pdf_file.extractImage(xref)
        image_bytes = base_image["image"]
          
        # get the image extension
        image_ext = base_image["ext"]
# extract images from pdf file
import fitz
doc = fitz.open("file.pdf")
for i in range(len(doc)):
    for img in doc.getPageImageList(i):
        xref = img[0]
        pix = fitz.Pixmap(doc, xref)
        if pix.n < 5:       # this is GRAY or RGB
            pix.writePNG("p%s-%s.png" % (i, xref))
        else:               # CMYK: convert to RGB first
            pix1 = fitz.Pixmap(fitz.csRGB, pix)
            pix1.writePNG("p%s-%s.png" % (i, xref))
            pix1 = None
        pix = None
import subprocess as sp
import json
import os
import sys


for year in range(1980,2015):
    print(year)
    cmd=f' mv {year}/pl_*.nc plFiles/'
    #print(cmd)
    sp.run(cmd, shell=True)
#libraries
import datetime as dt
import xarray as xr
import fsspec
import s3fs
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd


#### AWS repository link - https://registry.opendata.aws/mur/

%%time
file_location = 's3://mur-sst/zarr'

ikey = fsspec.get_mapper(file_location, anon=True)

ds_sst = xr.open_zarr(ikey,consolidated=True)

ds_sst

data=ds_sst.sel(lat=slice(10,15),lon=slice(-68,-67))

data.analysed_sst[0,:,:].where(dataMask[0,:,:]==1).plot()


dataMask=ds_sst.mask.sel(lat=slice(10,15),lon=slice(-68,-67))
dataMask

data.analysed_sst[0,:,:].where(dataMask[0,:,:]==1).to_netcdf('testMUR.nc')

sst=xr.open_dataset('testMUR.nc')
sst.analysed_sst.plot()


#!/usr/bin/env python3
"""
License: MIT License
Copyright (c) 2023 Miel Donkers

Very simple HTTP server in python for logging requests
Usage::
    ./server.py [<port>]
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging

class S(BaseHTTPRequestHandler):
    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
        self._set_response()
        self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))

    def do_POST(self):
        content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
        post_data = self.rfile.read(content_length) # <--- Gets the data itself
        logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
                str(self.path), str(self.headers), post_data.decode('utf-8'))

        self._set_response()
        self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))

def run(server_class=HTTPServer, handler_class=S, port=8080):
    logging.basicConfig(level=logging.INFO)
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    logging.info('Starting httpd...\n')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    logging.info('Stopping httpd...\n')

if __name__ == '__main__':
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()
import re
s = "string. With. Punctuation?"
s = re.sub(r'[^\w\s]','',s)
# \w matches any word character (equivalent to [a-zA-Z0-9_])
# \s matches any whitespace character (equivalent to [\r\n\t\f\v ])
from serpapi import GoogleSearch

params = {
  "q": "Coffee",
  "location": "Austin, Texas, United States",
  "hl": "en",
  "gl": "us",
  "google_domain": "google.com",
  "api_key": "381f56d7198076f0606f9d563798774bd6f56899511e8b4770216e5facd8668f"
}

search = GoogleSearch(params)
results = search.get_dict()
from langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import Chroma
from langchain.document_loaders import TextLoader

# load the document and split it into chunks
loader = TextLoader("")
documents = loader.load()
len(documents)
print(documents[0])

# split it into chunks
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
docs = text_splitter.split_documents(documents)
len(docs)
print(docs[0])


# create the open-source embedding function
embedding_function = HuggingFaceEmbeddings

# load it into Chroma
db = Chroma.from_documents(docs, embedding_function, persist_directory="./chroma_db")

# query it
#query = "Question"
#docs = db.similarity_search(query)

# print results
print(docs[0].page_content)

docs = db2.similarity_search(query)
# Route to blacklist a creator
@app.route('/blacklist_creator/<int:creator_id>', methods=['POST'])
def blacklist_creator(creator_id):
    admin_id = session['user_id'] 

    
    creator_blacklist = CreatorBlacklist.query.filter_by(admin_id=admin_id, creator_id=creator_id).first()
    if creator_blacklist:
        flash('Creator is already blacklisted.', 'danger')
    else:
        creator_blacklist = CreatorBlacklist(admin_id=admin_id, creator_id=creator_id)
        db.session.add(creator_blacklist)
        db.session.commit()
        flash('Creator has been blacklisted.', 'success')

    return redirect(url_for('review_creator'))

# Route to whitelist a creator
@app.route('/whitelist_creator/<int:creator_id>', methods=['POST'])
def whitelist_creator(creator_id):
    admin_id = session['user_id']  
    creator_blacklist = CreatorBlacklist.query.filter_by(admin_id=admin_id, creator_id=creator_id).first()
    if creator_blacklist:
        db.session.delete(creator_blacklist)
        db.session.commit()
        flash('Creator has been whitelisted.','success')
    else:
        flash('Creator was not blacklisted.','danger')
    return redirect(url_for('review_creator'))  
docsearch.as_retriever(search_type="mmr")

# Retrieve more documents with higher diversity- useful if your dataset has many similar documents
docsearch.as_retriever(search_type="mmr", search_kwargs={'k': 6, 'lambda_mult': 0.25})

# Fetch more documents for the MMR algorithm to consider, but only return the top 5
docsearch.as_retriever(search_type="mmr", search_kwargs={'k': 5, 'fetch_k': 50})

# Only retrieve documents that have a relevance score above a certain threshold
docsearch.as_retriever(search_type="similarity_score_threshold", search_kwargs={'score_threshold': 0.8})

# Only get the single most similar document from the dataset
docsearch.as_retriever(search_kwargs={'k': 1})

# Use a filter to only retrieve documents from a specific paper
docsearch.as_retriever(search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}})
engine = create_engine(
    f"trino://{user}:{user_key}@{host}:{port}/{catalog}", 
    connect_args={
        "auth": BasicAuthentication(user, user_key),
        "http_scheme": "https",
    }
)
connection = engine.connect()
query = f"""

"""

pd.read_sql(query, connection)
'''def download_data(urls):
    filenames = []
    
    for i, link in enumerate(urls):
        try:
            result = requests.get(link, cookies={'urs_user': 'liviaalvzs', 'urs_pass': 'Ss1234567890?'})
            result.raise_for_status()
            
            basename = get_filenames_from_urls(link)
            filenames.append(basename)
            
            with open(basename, 'wb') as f:
                f.write(result.content)
            
            print(f'O arquivo do link {link} foi baixado com sucesso e salvo como {basename}.')
            
        except requests.exceptions.HTTPError as errh:
            print ("HTTP Error:",errh)
        except requests.exceptions.ConnectionError as errc:
            print ("Error Connecting:",errc)
        except requests.exceptions.Timeout as errt:
            print ("Timeout Error:",errt)
        except requests.exceptions.RequestException as err:
            print ("Something went wrong:",err)
        
    return filenames
python3 manage.py makemigrations  --settings=CheckInPlatform.settings.localpkt 

python3 manage.py migrate  --settings=CheckInPlatform.settings.localpkt
import pandas as pd
import sqlite3

# Create database
conn = sqlite3.connect('guests.db')
c = conn.cursor()

# Create table
c.execute('''CREATE TABLE guests
             (id INTEGER PRIMARY KEY AUTOINCREMENT,
              name TEXT,
              phone TEXT,
              email TEXT,
              visits INTEGER)''')

# Insert data
df = pd.read_csv('guests.csv')
df.to_sql('guests', conn, if_exists='append', index=False)

# Close connection
conn.close()
import os
import zipfile

def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file),
                       os.path.relpath(os.path.join(root, file),
                                       os.path.join(path, '..')))

with zipfile.ZipFile('/content/m1.Zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
    zipdir('/content/m1', zipf)
import numpy as np
import matplotlib.pyplot as plt

# Create a sample dataset
data = np.random.randn(1000)

# Calculate the number of bins
num_bins = 10

# Create a histogram
hist, bins = np.histogram(data, bins=num_bins)

# Plot the histogram
plt.bar(bins[:-1], hist, width=bins[1] - bins[0])
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.title("Histogram of Sample Data")
plt.show()
pip install -U pip setuptools
pip install wheel

!pip install eeconvert

pip install --upgrade urllib3

import pandas as pd
import geopandas as gpd
import datetime
import ee
import eeconvert

ee.Authenticate()
ee.Initialize()

from google.colab import drive
drive.mount('/content/drive')

Maiz_str = '/content/drive/MyDrive/Puntos/SHP/Col_2021_Maiz.shp'
Soja_str = '/content/drive/MyDrive/Puntos/SHP/Col_2021_Soja.shp'

df = gpd.read_file(Maiz_str, parse_dates=['Fecha_Siembra', 'Rango_Floor','Rango_Top'])
#df = gpd.read_file(Soja_str, parse_dates=['Fecha_Cosecha', 'Date_R3_Fr', 'Date_R6_Fr'])# en el registro 315 modifiqué el año 0201 por 2016 de la columna Fecha_Cosecha
#df = df.head(10)
display(df.columns)

df['Start_Date'] = pd.to_datetime(df['Rango_Flor']).dt.strftime('%Y-%m-%d')
df['End_Date'] = pd.to_datetime(df['Rango_Top_']).dt.strftime('%Y-%m-%d')


#df['Start_Date'] = pd.to_datetime(df['Date_R3_Fr']).dt.strftime('%Y-%m-%d')
#df['End_Date'] = pd.to_datetime(df['Date_R6_Fr']).dt.strftime('%Y-%m-%d')

df = df[df['Start_Date'].notna()]
df = df[df['End_Date'].notna()]
df = df[df['Longitud'].notna()]
df = df[df['Latitud'].notna()]

df = df[['Start_Date','End_Date', 'geometry', 'Parcela']]

new_df = pd.DataFrame([],columns=['id', 'longitude', 'latitude', 'time', 'NDVI', 'Parcela'])

for index, row in df.iterrows():
  newGDF = df.filter(items = [index], axis=0)
  fc = eeconvert.gdfToFc(newGDF)
  feature = fc.geometry().buffer(-125)
  print(row.Parcela)
  Start_Date = ee.Date(row.Start_Date)
  End_Date = ee.Date(row.End_Date)

  dataset = ee.ImageCollection("MODIS/061/MOD13Q1").select('NDVI').filter(ee.Filter.date(Start_Date,End_Date))
  NDVIvalues = dataset.getRegion(feature, 250).getInfo()
  NDVI_df = pd.DataFrame(NDVIvalues)
  NDVI_df.columns = NDVI_df.iloc[0]
  NDVI_df = NDVI_df.iloc[1:].reset_index(drop=True)
  NDVI_df.insert(1, "Parcela", row.Parcela)
  new_df = new_df.append(NDVI_df)

new_df.to_csv('/content/drive/MyDrive/Puntos/NDVI_Poligonos_Maiz.csv',header=True, index=False)
import os
import glob
import geopandas as gpd
import pandas as pd
import re

json_dir_name = "/Users/agroclimate/Documents/PriceFrobes/Uruguay/Poligonos/GeoJson/2023/"
json_pattern = os.path.join(json_dir_name,'*.geojson')
file_list = glob.glob(json_pattern)

collection = gpd.GeoDataFrame([])

for file in file_list:
    print(file)
    newGpd = gpd.read_file(file)
    newGpd['NAME'] = re.sub(r"[^a-zA-Z0-9]","_",os.path.basename(file)[:-8])
    collection = pd.concat([collection,newGpd])

collection = collection.loc[collection.geometry.geom_type=='Polygon']
collection.to_file('/Users/agroclimate/Documents/PriceFrobes/Uruguay/Poligonos/GeoJson/Col_2023_name.shp')
from shapely.geometry import *
import glob
import fiona
from zipfile import ZipFile
import pandas as pd
import io
import geopandas as gpd
from fastkml import kml
import shapely

def remove_third_dimension(geom):
    if geom.is_empty:
        return geom

    if isinstance(geom, Polygon):
        exterior = geom.exterior
        new_exterior = remove_third_dimension(exterior)

        interiors = geom.interiors
        new_interiors = []
        for int in interiors:
            new_interiors.append(remove_third_dimension(int))

        return Polygon(new_exterior, new_interiors)

    elif isinstance(geom, LinearRing):
        return LinearRing([xy[0:2] for xy in list(geom.coords)])

    elif isinstance(geom, LineString):
        return LineString([xy[0:2] for xy in list(geom.coords)])

    elif isinstance(geom, Point):
        return Point([xy[0:2] for xy in list(geom.coords)])

    elif isinstance(geom, MultiPoint):
        points = list(geom.geoms)
        new_points = []
        for point in points:
            new_points.append(remove_third_dimension(point))

        return MultiPoint(new_points)

    elif isinstance(geom, MultiLineString):
        lines = list(geom.geoms)
        new_lines = []
        for line in lines:
            new_lines.append(remove_third_dimension(line))

        return MultiLineString(new_lines)

    elif isinstance(geom, MultiPolygon):
        pols = list(geom.geoms)

        new_pols = []
        for pol in pols:
            new_pols.append(remove_third_dimension(pol))

        return MultiPolygon(new_pols)

    elif isinstance(geom, GeometryCollection):
        geoms = list(geom.geoms)

        new_geoms = []
        for geom in geoms:
            new_geoms.append(remove_third_dimension(geom))

        return GeometryCollection(new_geoms)

    else:
        raise RuntimeError("Currently this type of geometry is not supported: {}".format(type(geom)))
        
fiona.drvsupport.supported_drivers['kml'] = 'rw'
fiona.drvsupport.supported_drivers['KML'] = 'rw'
fiona.drvsupport.supported_drivers['libkml'] = 'rw'
fiona.drvsupport.supported_drivers['LIBKML'] = 'rw'

outDir = '/Users/agroclimate/Documents/PriceFrobes/Uruguay/Poligonos/GeoJson/2023/'
files = glob.glob('/Users/agroclimate/Documents/PriceFrobes/Uruguay/Poligonos/KMZ 2023/**/*.kml', recursive=True)

for file in files:
    print(file)
    polys = gpd.read_file(file, driver='KML')

    name = polys.Name
    geom = polys.geometry
    file_name = os.path.basename(file)[:-4]
    
    for (geom, name) in zip(geoms, names):
        geom = remove_third_dimension(geom)
        gdf = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[geom])
        
        gdf.to_file(outDir+file_name+ "_"+name+'.geojson', driver='GeoJSON')
from shapely.geometry import *
import glob
from zipfile import ZipFile
import pandas as pd
import io
import geopandas as gpd
from fastkml import kml
import shapely

def remove_third_dimension(geom):
    if geom.is_empty:
        return geom

    if isinstance(geom, Polygon):
        exterior = geom.exterior
        new_exterior = remove_third_dimension(exterior)

        interiors = geom.interiors
        new_interiors = []
        for int in interiors:
            new_interiors.append(remove_third_dimension(int))

        return Polygon(new_exterior, new_interiors)

    elif isinstance(geom, LinearRing):
        return LinearRing([xy[0:2] for xy in list(geom.coords)])

    elif isinstance(geom, LineString):
        return LineString([xy[0:2] for xy in list(geom.coords)])

    elif isinstance(geom, Point):
        return Point([xy[0:2] for xy in list(geom.coords)])

    elif isinstance(geom, MultiPoint):
        points = list(geom.geoms)
        new_points = []
        for point in points:
            new_points.append(remove_third_dimension(point))

        return MultiPoint(new_points)

    elif isinstance(geom, MultiLineString):
        lines = list(geom.geoms)
        new_lines = []
        for line in lines:
            new_lines.append(remove_third_dimension(line))

        return MultiLineString(new_lines)

    elif isinstance(geom, MultiPolygon):
        pols = list(geom.geoms)

        new_pols = []
        for pol in pols:
            new_pols.append(remove_third_dimension(pol))

        return MultiPolygon(new_pols)

    elif isinstance(geom, GeometryCollection):
        geoms = list(geom.geoms)

        new_geoms = []
        for geom in geoms:
            new_geoms.append(remove_third_dimension(geom))

        return GeometryCollection(new_geoms)

    else:
        raise RuntimeError("Currently this type of geometry is not supported: {}".format(type(geom)))
        
outDir = '/Users/agroclimate/Documents/PriceFrobes/Uruguay/Poligonos/GeoJson/2023/'
files = glob.glob('/Users/agroclimate/Documents/PriceFrobes/Uruguay/Poligonos/KMZ 2023/**/*.kmz', recursive=True)

for file in files:
    print(file)
    
    kmz = ZipFile(file, 'r')
    kml_content = kmz.open('doc.kml', 'r').read()

    k = kml.KML()
    k.from_string(kml_content)
    
    docs = list(k.features())
    
    folders = []
    for d in docs:
        folders.extend(list(d.features()))
    
    records = []
    
    while type(folders[0]) is not type(kml.Placemark('{http://www.opengis.net/kml/2.2}', 'id', 'name', 'description')):
        records = []
        for f in folders:
            records.extend(list(f.features()))
        folders = records
    
    names = [element.name for element in folders]

    geoms = [element.geometry for element in folders]
    
    file_name = os.path.basename(file)[:-4]
    
    for (geom, name) in zip(geoms, names):
        geom = remove_third_dimension(geom)
        gdf = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[geom])
        
        gdf.to_file(outDir+file_name+ "_"+name+'.geojson', driver='GeoJSON')
from google.colab import drive
drive.mount('/content/drive')
base_dir = "/content/drive/MyDrive/vision_computador"
os.chdir(base_dir)
print('actual direccion de trabajo:',base_dir)

# ingresar direccion de la carpeta de trabajo
WORKPLACE_DIR = None
assert WORKPLACE_DIR is not None, "[!] Enter the la direccion de la carpeta de trabajo."
# This function chooses at random which action to be performed within the range 
# of all the available actions.
def ActionChoice(available_actions_range):
    if(sum(PossibleAction)>0):
        next_action = int(ql.random.choice(PossibleAction,1))
    if(sum(PossibleAction)<=0):
        next_action = int(ql.random.choice(5,1))
    return next_action

# Sample next action to be performed
action = ActionChoice(PossibleAction)
I highly recommend you tf.data.Dataset for creating the dataset:

Do all processes (like resize and normalize) that you want on all images with dataset.map.
Instead of using train_test_split, Use dataset.take, datast.skip for splitting dataset.
Code for generating random images and label:

# !pip install autokeras
import tensorflow as tf
import autokeras as ak
import numpy as np

data = np.random.randint(0, 255, (45_000,32,32,3))
label = np.random.randint(0, 10, 45_000)
label = tf.keras.utils.to_categorical(label) 
 Save
Convert data & label to tf.data.Dataset and process on them: (only 55 ms for 45_000, benchmark on colab)

dataset = tf.data.Dataset.from_tensor_slices((data, label))
def resize_normalize_preprocess(image, label):
    image = tf.image.resize(image, (16, 16))
    image = image / 255.0
    return image, label

# %%timeit 
dataset = dataset.map(resize_normalize_preprocess, num_parallel_calls=tf.data.AUTOTUNE)
# 1 loop, best of 5: 54.9 ms per loop
 Save
Split dataset to 80% for train and 20% for test
Train and evaluate AutoKeras.ImageClassifier
dataet_size = len(dataset)
train_size = int(0.8 * dataet_size)
test_size = int(0.2 * len(dataset))

dataset = dataset.shuffle(32)
train_dataset = dataset.take(train_size)
test_dataset = dataset.skip(train_size)

print(f'Size dataset : {len(dataset)}')
print(f'Size train_dataset : {len(train_dataset)}')
print(f'Size test_dataset : {len(test_dataset)}')

clf = ak.ImageClassifier(overwrite=True, max_trials=1)
clf.fit(train_dataset, epochs=1)
print(clf.evaluate(test_dataset))
>>> import shutil, os

>>> os.chdir('C:\\')
>>> shutil.copy('C:\\spam.txt', 'C:\\delicious')
# C:\\delicious\\spam.txt'

>>> shutil.copy('eggs.txt', 'C:\\delicious\\eggs2.txt')
# 'C:\\delicious\\eggs2.txt'
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
>>> import os

>>> os.getcwd()
# 'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')

>>> os.getcwd()
# 'C:\\Windows\\System32'
>>> my_files = ['accounts.txt', 'details.csv', 'invite.docx']

>>> for filename in my_files:
...     print(os.path.join('C:\\Users\\asweigart', filename))
...
# C:\Users\asweigart\accounts.txt
# C:\Users\asweigart\details.csv
# C:\Users\asweigart\invite.docx
import csv

import json



# Open the JSON file

with open('data.json') as json_file:

    data = json.load(json_file)



# Create a new CSV file and write the data

with open('data.csv', 'w', newline='') as csv_file:

    writer = csv.DictWriter(csv_file, fieldnames=data[0].keys())

    writer.writeheader()

    for row in data:

        writer.writerow(row)
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
  
  
    <ul class="nav">
            <li><i class="fas fa-home"></i><a href="#">Home</a></li>
            <li><i class="fas fa-user"></i><a href="#">Profile</a></li>
            <li><i class="fas fa-envelope"></i><a href="#">Messages</a></li>
            <li><i class="fas fa-cog"></i><a href="#">Settings</a></li>
        </ul>
def pull_file(URL, savepath):
    r = requests.get(URL)
    with open(savepath, 'wb') as f:
        f.write(r.content)   
    # Use the print method for logging
    print(f"File pulled from {URL} and saved to {savepath}")

from airflow.operators.python_operator import PythonOperator

# Create the task
pull_file_task = PythonOperator(
    task_id='pull_file',
    # Add the callable
    python_callable=pull_file,
    # Define the arguments
    op_kwargs={'URL':'http://dataserver/sales.json', 'savepath':'latestsales.json'},
    dag=process_sales_dag
)
import pandas as pd
import geopandas as gps
import datetime
import ee

ee.Authenticate()
ee.Initialize()

from google.colab import drive
drive.mount('/content/drive')

"""Selccionar Cultivo"""
#Maiz_str = '/content/drive/MyDrive/Puntos/Maiz.csv'
#df = pd.read_csv(Maiz_str, parse_dates=['Fecha_Siembra', 'Rango_Floor','Rango_Top'])

Soja_str = '/content/drive/MyDrive/Puntos/Soja.csv'
df = pd.read_csv(Soja_str, parse_dates=['Fecha_Cosecha', 'R3', 'R6'])
# En archivo de soja fila 315, columna Fecha_Cosecha modifiqué año 0201 por 2016 

df['Start_Date'] = df['R3']
df['End_Date'] = df['R6']

df = df[df['Start_Date'].notna()]
df = df[df['End_Date'].notna()]
df = df[df['Longitud'].notna()]
df = df[df['Latitud'].notna()]

new_df = pd.DataFrame([],columns=['id', 'longitude', 'latitude', 'time', 'NDVI', 'Parcela','Codigo_Lote'])

for index, row in df.iterrows():

    feature = ee.Algorithms.GeometryConstructors.Point([row.Longitud,row.Latitud])

    Start_Date = ee.Date(row.Start_Date)
    End_Date = ee.Date(row.End_Date)

    dataset = ee.ImageCollection("MODIS/061/MOD13Q1").select('NDVI').filter(ee.Filter.date(Start_Date,End_Date))
    NDVIvalues = dataset.getRegion(feature, 250).getInfo()
    NDVI_df = pd.DataFrame(NDVIvalues)
    NDVI_df.columns = NDVI_df.iloc[0]
    NDVI_df = NDVI_df.iloc[1:].reset_index(drop=True)
    NDVI_df.insert(1, "Parcela", row.Parcela)
    NDVI_df.insert(1, "Codigo_Lote", row.Codigo_Lote)
    new_df = new_df.append(NDVI_df)

new_df.to_csv('/content/drive/MyDrive/Puntos/NDVI_Puntos.csv',header=True, index=False)
# Je to na tema co jsme delali ve fyzice jen cast tridy a nevim jestli je to latka ale pokud ano tak tohle muze byt jako kontrola kdyz by na to byl trrrreba tesst
# Tady je celej kod
# Nakodoval jsem to já, není to ukradnutý
# Mělo by to fungovat, 1x jsem to zkoušel počítat ručně a přes program. Řučně to trvalo tak 100x dýl a ještě to nebylo přesný. A funguje to
# Asi to neni nic extre protoze nejsem 6tilety študent, ale účel to plní




# Dalsi projekty kdyztak na kubasobr.blogspot.com
import random
import time
import math

import os

def Zacatek():
    ascii_art1 = """ .----------------.  .----------------.  .----------------.  .----------------. 
| .--------------. || .--------------. || .--------------. || .--------------. |
| |    _______   | || |     ____     | || | ____    ____ | || | ____   ____  | |
| |   /  ___  |  | || |   .'    `.   | || ||_   \  /   _|| || ||_  _| |_  _| | |
| |  |  (__ \_|  | || |  /  .--.  \  | || |  |   \/   |  | || |  \ \   / /   | |
| |   '.___`-.   | || |  | |    | |  | || |  | |\  /| |  | || |   \ \ / /    | |
| |  |`\____) |  | || |  \  `--'  /  | || | _| |_\/_| |_ | || |    \ ' /     | |
| |  |_______.'  | || |   `.____.'   | || ||_____||_____|| || |     \_/      | |
| |              | || |              | || |              | || |              | |
| '--------------' || '--------------' || '--------------' || '--------------' |
 '----------------'  '----------------'  '----------------'  '----------------' """
    print(ascii_art1)
    ascii_art2 = """      _       _          _       ____        _          
     | | __ _| | ___   _| |__   / ___|  ___ | |__  _ __ 
  _  | |/ _` | |/ / | | | '_ \  \___ \ / _ \| '_ \| '__|
 | |_| | (_| |   <| |_| | |_) |  ___) | (_) | |_) | |   
  \___/ \__,_|_|\_\\__,_|_.__/  |____/ \___/|_.__/|_|   
                                                        """
    print(ascii_art2)

    print("Vítejte u programu SOMV, který jsem vytvořil jako malý projekt do fyziky když jsem se nudil. SOMV stojí pro Směrodatná odchylka měření veličiny"+"\n"+"Program je určen jako pomůcka k měření. Program vám vypočítá SOMV a i Relativní odchylku  aby jste věděli jak přesně jste měřili"+"\n"+"Program vytvoří i graf s vámi danými hodnotami"+"\n"+"Je to vše naprogramované přes python, jelikož to je jediný co umím vcelku, max základy html css a javascript."+"\n"+"\n"+"NÁVOD k použití:"+"\n"+"Program se vás bude ptát na měřené hodnoty a vy je bude zadávat ve STEJNÝCH jednotkách(v nové verzi možná vylepším)"+"\n"+"Jakmile zadáte všechny hodnoty co chcete tak program sám řekne co dál."+"\n"+"Autorem je Jakub Šobr Videnska 1.B, update ohlášeny předem na kubasobr.blogspot.cz")


    print("")
    print("START PROGRAMU")
    random_cislo = random.randint(0,100)
    start_otazka = int(input("Napište číslo "+str(random_cislo) +" pro start programu: "))
    if start_otazka == random_cislo:
        Informace_funkce()
    else:
        print("")
        print("OZNÁMENÍ")
        print("Bud jste zadali špatné číslo a nebo nastalo v programu k chybě")
        print("Za pět sekund bude zapnuta začáteční funkce znovu.")
        print("")
        time.sleep(5)
        Zacatek()

def Informace_funkce():
    print("")
    print("PROGRAM STARTUJE")
    otazka_pocet_hodnot = int(input("INFORMACE 1 - Kolikrát jste provedli měření?: "))
    otazka_jednotka = input("INFORMACE 2 - Zadejte jednotku v níž jste prováděli měření (cm,dm,m,litr apod): ")
    tts = input("INFORMACE 3 - Chcete aby program výsledek zazněl jako text to speech? ano / ne: ")


    def Hlavni_funkce(pocet_hodnot,jednotka):
        print("")
        aktualni_cislo = 1
        hodnoty_list = []
        index = 0
        celkove = 0

        for _ in range(pocet_hodnot):
            hodnota = float(input("Zadejte hodnotu č."+str(aktualni_cislo)+" : "))
            celkove += hodnota
            hodnoty_list.insert(index, hodnota)
            index +=1
            aktualni_cislo +=1


        ar_prumer = celkove/pocet_hodnot
        def Casti(aritmeticky_prumer):
            index_cteni  = 0
            soucet_casti = 0
            for hodnota in hodnoty_list:
                cast = (hodnota - aritmeticky_prumer) ** 2
                soucet_casti += cast
                index_cteni += 1
            # Odmocní celkový součet
            citatel = soucet_casti ** 0.5
            jmenovatel = pocet_hodnot *(pocet_hodnot-1)

            odchylka = citatel /jmenovatel
            minus_interval = aritmeticky_prumer-odchylka
            plus_interval = aritmeticky_prumer+odchylka
            relativni_odchylka = odchylka/aritmeticky_prumer

            # Rounding
            round_odchylka = round(odchylka,3)
            round_minus_interval = round(minus_interval,3)
            round_plus_interval = round(plus_interval, 3)
            round_relativni_odchylka = round(relativni_odchylka, 3)

            # Uprava pro tts
            uprava_round_odchylka = str(round_odchylka).replace('.', ',')
            uprava_round_minus_interval = str(round_minus_interval).replace('.', ',')
            uprava_round_plus_interval = str(round_plus_interval).replace('.', ',')
            uprava_round_relativni_odchylka = str(round_relativni_odchylka).replace('.', ',')
            if odchylka > 0.5:
                text = ("Systém odhalil nepřesné měření! Odchylka je +- " + str(round_odchylka) + str(
                    jednotka) + " Reálná hodnota je někde mezi " + str(round_minus_interval) + " a " + str(
                    round_plus_interval) + ". Relativní odchylka je " + str(
                    round_relativni_odchylka) + " Děkujeme za použití programu.")
                presne_hodnoty = ("Odchylka = "+str(odchylka)+"\n"+"Interval = od "+str(minus_interval)+" po "+str(plus_interval)+"\n"+"Relativní odchylka = "+str(relativni_odchylka))
                print(text)
                presne_ot = int(input("Chcete vidět přesné hodnoty(1) nebo stačí obecnější?(2): "))
                if presne_ot == 1:
                    print(presne_hodnoty)

            else:
                text = ("Měření je v pořádku! Odchylka je +- " + str(round_odchylka) + str(
                    jednotka) + " Reálná hodnota je někde mezi " + str(round_minus_interval) + " a " + str(
                    round_plus_interval) + ". Relativní odchylka je " + str(
                    round_relativni_odchylka) + " Děkujeme za použití programu.")
                presne_hodnoty = ("Odchylka = "+str(odchylka)+"\n"+"Interval = od "+str(minus_interval)+" po "+str(plus_interval)+"\n"+"Relativní odchylka = "+str(relativni_odchylka))
                print(text)
                presne_ot = int(input("Chcete vidět přesné hodnoty(1) nebo stačí obecnější?(2): "))
                if presne_ot == 1:
                    print(presne_hodnoty)


            def Tts():
                # User Inteface
                if odchylka > 1:
                    text = ("Systém odhalil nepřesné měření! Odchylka je +- " + str(uprava_round_odchylka) + str(
                        jednotka) + " Reálná hodnota je někde mezi " + str(uprava_round_minus_interval) + " a " + str(
                        uprava_round_plus_interval) + ". Relativní odchylka je " + str(
                        uprava_round_relativni_odchylka) + " Děkujeme za použití programu.")
                    print(text)
                else:
                    text = ("Měření je v pořádku! Odchylka je +- " + str(uprava_round_odchylka) + str(
                        jednotka) + " Reálná hodnota je někde mezi " + str(uprava_round_minus_interval) + " a " + str(
                        uprava_round_plus_interval) + ". Relativní odchylka je " + str(
                        uprava_round_relativni_odchylka) + " Děkujeme za použití programu.")
                    print(text)

                from gtts import gTTS
                import os

                # Text, který chcete převést na hlas
                if odchylka > 1:
                    text = "Systém odhalil nepřesné měření! Odchylka je +-" + str(round_odchylka) + " " + str(
                        jednotka) + "Reálná hodnota je někde mezi " + str(round_minus_interval) + " a " + str(
                        round_plus_interval) + ". Relativní odchylka je " + str(
                        round_relativni_odchylka) + "Děkujeme za použití programu."
                else:
                    text = "Měření je v pořádku! Odchylka je +-" + str(round_odchylka) + " " + str(
                        jednotka) + "Reálná hodnota je někde mezi " + str(round_minus_interval) + " a " + str(
                        round_plus_interval) + ". Relativní odchylka je " + str(
                        round_relativni_odchylka) + "Děkujeme za použití programu."

                # Vytvoření instance gTTS s textem a nastavením jazyka na češtinu
                tts = gTTS(text, lang='cs')

                # Uložení hlasového souboru na disk
                tts.save("nahravka.mp3")

                # Přehrání hlasového souboru (vyžaduje externí přehrávač)
                os.system("nahravka.mp3")
            def graf_menu():
                text = """                   __ 
   __ _ _ __ __ _ / _|
  / _` | '__/ _` | |_ 
 | (_| | | | (_| |  _|
  \__, |_|  \__,_|_|  
  |___/               """
                print(text)
                otazka = input("Chcete zobrazit hodnoty ve grafu? ano / ne: ")
                if otazka == "ano":
                    graf()
                else:
                    print("Děkujeme za použití programu. Program se vypne za 10 sekund")
                    time.sleep(10)
            def graf():
                import matplotlib.pyplot as plt

                import matplotlib.pyplot as plt
                import numpy as np

                #hodnoty_list = [15, 18, 12, 25, 14]
                jednotka = "cm"
                poradi = list(range(1, pocet_hodnot + 1))  # Od 1 do pocet_hodnot

                # Příprava dat
                x = poradi
                y = hodnoty_list

                # Vytvoření čárového grafu
                plt.plot(x, y, label='Vámi změřené hodnoty', color='b')

                # Přidání první horizontální čáry na hodnotu 16 s červenou barvou
                plt.axhline(y=minus_interval, color='r', linestyle='-.', label='Mínusový interval')

                # Přidání druhé horizontální čáry na hodnotu 22 s červenou barvou
                plt.axhline(y=plus_interval, color='r', linestyle='-.', label='Plusový interval')

                # Přidání tučné zelené čáry na hodnotu 20
                plt.axhline(y=aritmeticky_prumer, color='g', linestyle='--', linewidth=3, label='Aritmetický průměr')

                # Vyplnění prostoru mezi červenými čarami
                plt.fill_between(x, minus_interval, plus_interval, color='yellow', alpha=0.5, label='Interval odchylky')

                # Nastavení popisků os
                plt.ylabel('Hodnoty v ' + jednotka)
                plt.xlabel('Pořadí')

                # Zobrazení legendy
                plt.legend()

                # Zobrazení grafu
                plt.show()

            if tts == "ano":
                Tts()
                graf_menu()
            else:
                graf_menu()

        Casti(ar_prumer)







    Hlavni_funkce(otazka_pocet_hodnot,otazka_jednotka)

Zacatek()
# made by jkob sobr 23 original
!pip install rasterstats
!pip install rasterio
!pip install leafmap

import glob
import pandas as pd
import rasterio
from rasterio.mask import mask
import geopandas as gps
from rasterstats import zonal_stats

from google.colab import drive
drive.mount('/content/drive')

files = glob.glob(f"/content/drive/MyDrive/Sura/Datos TMax/2011_15/SAMeT_CPTEC_TMAX_2013*.nc")
print(len(files))

grid_str = '/content/drive/MyDrive/Sura/Seccionales_Policiales_WGS84_Selected.shp'
poligonos = gps.read_file(grid_str)

df = pd.DataFrame([], columns=['fecha', 'median', 'CODIGOSECC'])

for file in files:

    with rasterio.open('netcdf:'+ file + ':tmax') as msla_nc:
        msla_nc_data = msla_nc.read(1)

    affine= msla_nc.transform

    print(file)
    for index, row in poligonos.iterrows():
        features = row.geometry

        zs = zonal_stats(features, msla_nc_data,affine=affine,all_touched= False,
                    stats="median")

        df = df.append(pd.DataFrame([[zs[0].get('median'), str(file)[-11:-3],row['CODIGOSECC']]],
                    columns=['median', 'fecha','CODIGOSECC']))

        print(row['CODIGOSECC'])

df.to_csv('/content/drive/MyDrive/Sura/Tmax2013.csv',header=True, index=False)


import glob
import pandas as pd

df = pd.DataFrame([], columns=['fecha', 'median', 'CODIGOSECC'])

files = glob.glob(f"/content/drive/MyDrive/Sura/Datos TMax/Tmax2*.csv")
print(len(files))
for file in files:
  df = df.append(pd.read_csv(file))
#print(df)
df['fecha'] = df['fecha'].astype(str)
df['year'] = df.fecha.str[:4]
df['month'] = df.fecha.str[4:6]
df['day'] = df.fecha.str[-2:]
#display(df.groupby('year').count())

df.to_csv('/content/drive/MyDrive/Sura/TmaxCompleto.csv',header=True, index=False)
import os
import requests
from bs4 import BeautifulSoup
import urllib.request
from urllib.parse import urljoin

base_url = 'http://ftp.cptec.inpe.br/'

baseDir = 'modelos/tempo/SAMeT/DAILY/TMAX/'

outputDir = '/Users/agroclimate/Documents/PriceFrobes/Uruguay/Sura/CPTEC/Faltantes/'

years = list(range(2022, 2023))
months = list(range(1,4))+list(range(10, 13))
#months = list(range(10, 13))
for year in years:

    for month in months:
        if month < 10:
            ftp_path = base_url + baseDir + str(year) + '/0' + str(month) + '/'
        elif month >= 10:
            ftp_path = base_url + baseDir + str(year) + '/' + str(month) + '/'
        
        # List folder content
        response = requests.get(ftp_path)
        
        soup = BeautifulSoup(response.content, 'html.parser')
        # Find all the 'a' tags (hyperlinks) on the page
        links = soup.find_all('a')

        # Extract filenames from the href attribute of 'a' tags
        files = [link['href'] for link in links if link.has_attr('href')]

        # Filter out directories and other unwanted links
        files = [filename for filename in files if filename.endswith('.nc')]
    
        for file in files:
            try:
                file_url = urljoin(ftp_path, file)

                to_download = (outputDir + file)

                # Download the file
                urllib.request.urlretrieve(file_url, to_download)

                print(f"Downloaded: {file}")

            except:
                print("Error")
SLP = SLP.assign_coords(longitude=(((SLP.longitude + 180) % 360) -180))
Z = Z.assign_coords(longitude=(((Z.longitude + 180) % 360) -180))
SLP = SLP.sortby(SLP['longitude'])
Z = Z.sortby(Z['longitude'])
.\env\Scripts\activate
find_item = input("Enter the item to be searched here:- ").lower()

items = {'wand': 5, 'telescope': 2, 'feather pen': 7}

for thing in items:
    if thing == find_item:
        print(f"{items[thing]} units of {thing} are present.")
        break
else:
    print('No stock left! You need to go and buy!!')
numbers = [51, 32, 63, 74, 45, 36, 47]

for i in numbers:
   pass
numbers = [51, 32, 63, 74, 45, 36, 47]

for num in numbers:
    if num % 2 == 0:
        continue
    else:
        print(num)
numbers = [51, 32, 63, 74, 45, 36, 47]

for num in numbers:
    if num % 5 == 0:
        print(num)
        break
wizard_list = ["Wand", "Cauldron", "crystal phials", \
        "telescope", "brass scales", "Owl", \
        "Cat", "Toad", \
        "Feather"]

for items in wizard_list:
    print(items)
wizard_list = ["Wand", "Cauldron", "crystal phials", \
        "telescope", "brass scales", "Owl", \
        "Cat", "Toad", \
        "Feather pen"]

print(wizard_list[0])
print(wizard_list[1])
print(wizard_list[2])
print(wizard_list[3])
print(wizard_list[4])
print(wizard_list[5])
print(wizard_list[6])
print(wizard_list[7])
print(wizard_list[8])
 _____________________
|  _________________  |
| | Pythonista   0. | |  .----------------.  .----------------.  .----------------.  .----------------. 
| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
|  ___ ___ ___   ___  | | |     ______   | || |      __      | || |   _____      | || |     ______   | |
| | 7 | 8 | 9 | | + | | | |   .' ___  |  | || |     /  \     | || |  |_   _|     | || |   .' ___  |  | |
| |___|___|___| |___| | | |  / .'   \_|  | || |    / /\ \    | || |    | |       | || |  / .'   \_|  | |
| | 4 | 5 | 6 | | - | | | |  | |         | || |   / ____ \   | || |    | |   _   | || |  | |         | |
| |___|___|___| |___| | | |  \ `.___.'\  | || | _/ /    \ \_ | || |   _| |__/ |  | || |  \ `.___.'\  | |
| | 1 | 2 | 3 | | x | | | |   `._____.'  | || ||____|  |____|| || |  |________|  | || |   `._____.'  | |
| |___|___|___| |___| | | |              | || |              | || |              | || |              | |
| | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' |
| |___|___|___| |___| |  '----------------'  '----------------'  '----------------'  '----------------' 
|_____________________|
                           Welcome to pythonista Calculator
                  We support the following operations on two numbers:
                  - subraction
                  + addition
                  * multiplication
                  / division
                  ** exponention
                  % modular division

Enter 1st number:- 13
Enter 2nd number:- 2 
Enter the operator here:- *
13 * 2 = 26
calc = """
 _____________________
|  _________________  |
| | Pythonista   0. | |  .----------------.  .----------------.  .----------------.  .----------------. 
| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
|  ___ ___ ___   ___  | | |     ______   | || |      __      | || |   _____      | || |     ______   | |
| | 7 | 8 | 9 | | + | | | |   .' ___  |  | || |     /  \     | || |  |_   _|     | || |   .' ___  |  | |
| |___|___|___| |___| | | |  / .'   \_|  | || |    / /\ \    | || |    | |       | || |  / .'   \_|  | |
| | 4 | 5 | 6 | | - | | | |  | |         | || |   / ____ \   | || |    | |   _   | || |  | |         | |
| |___|___|___| |___| | | |  \ `.___.'\  | || | _/ /    \ \_ | || |   _| |__/ |  | || |  \ `.___.'\  | |
| | 1 | 2 | 3 | | x | | | |   `._____.'  | || ||____|  |____|| || |  |________|  | || |   `._____.'  | |
| |___|___|___| |___| | | |              | || |              | || |              | || |              | |
| | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' |
| |___|___|___| |___| |  '----------------'  '----------------'  '----------------'  '----------------' 
|_____________________|
                           Welcome to pythonista Calculator
                  We support the following operations on two numbers:
                  - subraction
                  + addition
                  * multiplication
                  / division
                  ** exponention
                  % modular division
"""
print(calc)
first_number = int(input("Enter 1st number:- "))
second_number = int(input("Enter 2nd number:- "))
operator_ = input("Enter the operator here:- ")

if operator_ == "-":
    result = first_number - second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "+":
    result = first_number + second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "*":
    result = first_number * second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "/":
    result = first_number / second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "**":
    result = first_number ** second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "%":
    result = first_number % second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

else:
    print("You entered an invalid operator!!")
a = int(input("Enter value of a:-\n"))
b = int(input("Enter value of b:-\n"))
print("a is greater than b") if a > b else print("b is greater than a")
num = -19

if num>=0:
    if type(num)==float:
        print(f"{num} is a positive floating-point number.")
    elif type(num)==int:
        print(f"{num} is a positive integer.")

else:
    if type(num)==float:
        print(f"{num} is a negative floating-point number.")
    elif type(num)==int:
        print(f"{num} is a negative integer.")
age = 19

if age==18:
    print("You're 18 go through the next check to know whether you qualify for license or not.")
if age > 18:
    print("You are above 18 you do qualify age criteria for license.")
else:
    print(f"You are not yet 18 come after {18-age} years to qualify the age criteria.")
age = 19

if age==18:
    print("You're 18 go through the next check to know whether you qualify for license or not.")
elif age > 18:
    print("You are above 18 you do qualify age criteria for license.")
else:
    print(f"You are not yet 18 come after {18-age} years to qualify the age criteria.")
num = -19

if num>=0:
    print(f"{num} is a positive number.")
else:
    print(f"{num} is a negative number.")

print("This will always be printed")
Welcome to the fun world ladies and gentleman


⠀⠀⠀⠀⠀⠀⠀⣠⡔⠚⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠑⠢⢄⠀⢀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⢀⠔⠋⠻⢿⣷⣦⣤⣀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣽⣧⣷⠀⠀⠀⠀
⠀⠀⢀⠴⠁⠀⠀⠀⠀⢈⣹⣿⣿⣷⠀⠀⠀⠀⠀⢾⣿⣿⣟⠋⠁⠈⠳⡀⠀⠀
⠀⢠⠊⣀⣤⠴⠶⠖⢛⠻⣿⣿⣭⣀⣀⠀⠀⠀⠀⠀⠉⠻⡿⠳⠖⠶⠶⠟⠓⠲
⣴⢣⡞⡉⢄⠒⡈⠜⡀⢾⣏⠉⠙⠛⠻⠿⢿⣿⣶⣶⣿⠿⢷⡡⢘⡐⢢⠘⡄⢂
⣿⡏⡐⢌⠢⠑⡌⠂⢥⣿⣿⣦⣤⣀⣀⠀⠀⠀⠀⠀⠀⣀⣼⣷⠠⠘⡄⠣⡐⠂..
⡟⣷⠀⢆⠢⡑⣈⢡⡾⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡷⣅⠰⢁...⡡
⡇⠈⠻⣦⣴⣤⠶⠋⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠈⠉⠓⠒⢪
⡇⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡃⠀⠀⠀⠀⢸
⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⢸
⠘⡄⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀⠀⢀⠏
⠀⠙⣄⠀⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠀⣠⠏⠀
⠀⠀⠈⠢⡀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⠀⠀⢀⡴⠁⠀⠀
⠀⠀⠀⠀⠈⠲⢄⠀⠀⠀⠀⠀⠀⠉⠿⣿⣿⣿⣿⣿⠿⠋⠀⣠⠔⠋⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠙⠒⠤⣤⣀⣀⣀⣀⣀⣈⣉⣉⣠⠤⠖⠏⠁

Enter any of the words below and press enter to know its meaning in the fun world
['Bumfuzzle', 'Everywhen', 'Erf', 'Obelus', 'Bumbershoot']

Enter the word here:- Obelus
searching...

The meaning of 'Obelus' in our world is:-  the symbol used for division in a math problem
print("\nWelcome to the fun world ladies and gentleman\n")
print("""
⠀⠀⠀⠀⠀⠀⠀⣠⡔⠚⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠑⠢⢄⠀⢀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⢀⠔⠋⠻⢿⣷⣦⣤⣀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣽⣧⣷⠀⠀⠀⠀
⠀⠀⢀⠴⠁⠀⠀⠀⠀⢈⣹⣿⣿⣷⠀⠀⠀⠀⠀⢾⣿⣿⣟⠋⠁⠈⠳⡀⠀⠀
⠀⢠⠊⣀⣤⠴⠶⠖⢛⠻⣿⣿⣭⣀⣀⠀⠀⠀⠀⠀⠉⠻⡿⠳⠖⠶⠶⠟⠓⠲
⣴⢣⡞⡉⢄⠒⡈⠜⡀⢾⣏⠉⠙⠛⠻⠿⢿⣿⣶⣶⣿⠿⢷⡡⢘⡐⢢⠘⡄⢂
⣿⡏⡐⢌⠢⠑⡌⠂⢥⣿⣿⣦⣤⣀⣀⠀⠀⠀⠀⠀⠀⣀⣼⣷⠠⠘⡄⠣⡐⠂..
⡟⣷⠀⢆⠢⡑⣈⢡⡾⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡷⣅⠰⢁...⡡
⡇⠈⠻⣦⣴⣤⠶⠋⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠈⠉⠓⠒⢪
⡇⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡃⠀⠀⠀⠀⢸
⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⢸
⠘⡄⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀⠀⢀⠏
⠀⠙⣄⠀⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠀⣠⠏⠀
⠀⠀⠈⠢⡀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⠀⠀⢀⡴⠁⠀⠀
⠀⠀⠀⠀⠈⠲⢄⠀⠀⠀⠀⠀⠀⠉⠿⣿⣿⣿⣿⣿⠿⠋⠀⣠⠔⠋⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠙⠒⠤⣤⣀⣀⣀⣀⣀⣈⣉⣉⣠⠤⠖⠏⠁
""")

fun_world_dictionary = {'Bumfuzzle': "confused",
                        'Everywhen': "all the time",
                        'Erf': "plot of land",
                        'Obelus': " the symbol used for division in a math problem",
                        'Bumbershoot': "umbrella"}

# I know that it's not quiet funnny(ok not at all funny). But, please forgive me for that

print("Enter any of the words below and press enter to know its meaning in the fun world")
list_of_words = list(fun_world_dictionary.keys())
print(list_of_words, "\n")


word_to_be_searched = input("Enter the word here:- ")
print("searching...\n")
meaning =""

if word_to_be_searched=="Bumfuzzle":
    meaning= fun_world_dictionary['Bumfuzzle']

if word_to_be_searched=="Everywhen":
    meaning= fun_world_dictionary['Everywhen']

if word_to_be_searched=="Erf":
    meaning= fun_world_dictionary['Erf']

if word_to_be_searched=="Obelus":
    meaning= fun_world_dictionary['Obelus']

if word_to_be_searched=="Bumbershoot":
    meaning= fun_world_dictionary['Bumbershoot']


print(f"The meaning of '{word_to_be_searched}' in our world is:- {meaning}\n")
$ uvicorn main:app --reload --port 8000
import pip
import importlib
def import_with_auto_install(package):
    try:
        return importlib.import_module(package)
    except ImportError:
        pip.main(['install', package])
    return importlib.import_module(package)
# Example
if __name__ == '__main__':
    imp = import_with_auto_install('{insert module name here}')
    print(imp)
import requests
from bs4 import BeautifulSoup

def get_mining_districts():
    url = "https://www.tanzaniainvest.com/mining"
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
    
    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()  # Raise an exception for HTTP errors
        soup = BeautifulSoup(response.content, 'html.parser')
        
        mining_section = soup.find('span', {'id': 'District'})
        
        districts = []
        if mining_section:
            district_list = mining_section.find_next('ul')
            if district_list:
                district_items = district_list.find_all('li')
                for district_item in district_items:
                    district_name = district_item.text.strip()
                    districts.append(district_name)
                    
        return districts
    except requests.exceptions.RequestException as e:
        print("Error:", e)
        return None

if __name__ == "__main__":
    mining_districts = get_mining_districts()
    if mining_districts:
        for index, district in enumerate(mining_districts, start=1):
            print(f"{index}. {district}")
df['unique'] = ~df['value'].duplicated(keep=False)
print (df)
   value  unique
0      1    True
1      2   False
2      2   False
3      3    True
4      4   False
5      4   False
trophies = {"Music championship", "Coding Championship", \
    "Certified Associate in Python Programming (PCAP)", \
    "CompTIA Security+", \
    "MongoDB Certified Developer Associate Exam"}

print(trophies)
print(type(trophies))
⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣿⣿⣿⣷⣶⣴⣾⣿⣿⣿⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣀⣤⣤⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣤⣤⣤⣄⠀⠀⠀⠀
⠀⠀⠀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠀⠀⠀
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⠀⠀
⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠈⢻⣿⣿⣿⣿⣿⣿⣿
⢿⣿⣿⣿⣿⣿⣿⣿⡿⠻⣿⣿⣿⣿⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿
⢈⣿⣿⣿⣿⣿⣿⣯⡀⠀⠈⠻⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⡁
⣾⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⠈⠛⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⠈⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀
⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀
⠀⠀⠀⠀⠉⠛⠛⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠛⠛⠉⠁⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣿⠿⢿⡻⠿⣿⣿⣿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀

{'Liam': ('Yes', 'No', 'Yes'), 'Olivia': ('Yes', 'No', 'Yes'), 'Noah': ('Yes', 'Yes', 'Yes'), 'Emma': ('Yes', 'No', 'Yes')}
done = """
⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣿⣿⣿⣷⣶⣴⣾⣿⣿⣿⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣀⣤⣤⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣤⣤⣤⣄⠀⠀⠀⠀
⠀⠀⠀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠀⠀⠀
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⠀⠀
⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠈⢻⣿⣿⣿⣿⣿⣿⣿
⢿⣿⣿⣿⣿⣿⣿⣿⡿⠻⣿⣿⣿⣿⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿
⢈⣿⣿⣿⣿⣿⣿⣯⡀⠀⠈⠻⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⡁
⣾⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⠈⠛⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⠈⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀
⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀
⠀⠀⠀⠀⠉⠛⠛⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠛⠛⠉⠁⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣿⠿⢿⡻⠿⣿⣿⣿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀
"""
print(done)

name_homework_done = {"Liam": ("Yes", "No", "Yes"),
                      "Olivia": ("Yes", "No", "Yes"),
                      "Noah": ("Yes", "Yes", "Yes"),
                      "Emma": ("Yes", "No", "Yes")}
print(name_homework_done)
homework = ("Multiplication Table of Two", \
"A poem on environment", "Multiplication Table of Two",\
"Process of Photosynthesis",\
"Maps of the world", "glorious past revision",\
"Multiplication Table of Two")

print(homework)
print()
print(homework.index("Multiplication Table of Two"))
homework = ("Multiplication Table of Two", \
"A poem on environment", "Multiplication Table of Two",\
"Process of Photosynthesis",\
"Maps of the world", "glorious past revision",\
"Multiplication Table of Two")

print(homework)
print()
print(homework.count("Multiplication Table of Two"))
homework = ("Multiplication Table of Two", \
"A poem on environment", "Process of Photosynthesis",\
"Maps of the world", "glorious past revision")

print(homework)

HW = homework
print(HW)
homework1 = ("Multiplication Table of Two", \
"A poem on environment", "Process of Photosynthesis")

homework2 = ("Maps of the world", "glorious past revision")

homework = homework1 + homework2

print(homework)
s_tup = hello <class 'str'>
s1_tup = ('hello',) <class 'tuple'>
s2_tup = hello <class 'str'>       
s3_tup = ('hello',) <class 'tuple'>
s_tup = "hello"  # This will be a string
s1_tup = "hello",  # This will be a tuple
s2_tup = ("hello")  # This will be a string
s3_tup = ("hello",)  # This will be a tuple

print(f"s_tup = {s_tup} {type(s_tup)}")
print(f"s1_tup = {s1_tup} {type(s1_tup)}")
print(f"s2_tup = {s2_tup} {type(s2_tup)}")
print(f"s3_tup = {s3_tup} {type(s3_tup)}")
___________________________________ 
|#######====================#######|
|#(1)*UNITED STATES OF AMERICA*(1)#|
|#**          /===\   ********  **#|
|*# {G}      | (") |             #*|
|#*  ******  | /v\ |    O N E    *#|
|#(1)         \===/            (1)#|
|##=========ONE DOLLAR===========##|
------------------------------------

{'apple': [100, 10000, 1000], 'banana': [90, 9000, 900], 'spinach': [50, 4000, 800], 'pineapples': [100, 8000, 900]}
money = """
___________________________________
|#######====================#######|
|#(1)*UNITED STATES OF AMERICA*(1)#|
|#**          /===\   ********  **#|
|*# {G}      | (") |             #*|
|#*  ******  | /v\ |    O N E    *#|
|#(1)         \===/            (1)#|
|##=========ONE DOLLAR===========##|
------------------------------------
"""
print(money)

price_profit_revenue = {"apple": [100, 10000, 1000], 
                        "banana": [90, 9000, 900], 
                        "spinach": [50, 4000, 800], 
                        "pineapples": [100, 8000, 900]}

print(price_profit_revenue)
import csv
import sqlite3

chr_ranges = (0x00, 0x09), (0x0B, 0x20), (0x7F, 0xA0)  # 'special' character ranges
trans_table = {x: " " for r in chr_ranges for x in range(*r)} # 'special'->space trans. table

def trans_field(value):
    try:
        return value.translate(trans_table)  # try to translate and return
    except AttributeError:  # if there's no translate method on the passed value...
        return value  # return the original value

connection = sqlite3.connect("your_db")  # connect to the database
cursor = connection.cursor()  # grab a database cursor
results = cursor.execute("select * from your_table")  # execute the select query
header = [c[0] for c in cursor.description]  # get the column names for our CSV header

with open("output.csv", "w", newline="") as f:  # open("output.csv", "wb") on Python 2.x
    writer = csv.writer(f, delimiter="\t")  # create a CSV writer with \t as a delimiter
    writer.writerow(header)  # write the header (column names)
    for result in results:  # iterate over the returned results
        writer.writerow(map(trans_field, result))  # process result fields and write the row
            , ; ,     
        .'         '.
       /   ()   ()   \
      ;               ;
      ; :.  MADLIB .; ;
       \'.'-.....-'.'/
        '.'.-.-,_.'.'
          '(  (..-'
            '-'

Enter a name:- someone
Enter a skill:- programming
Enter any object:- laptop
Enter a verb:- typing
Enter another verb:- searching
Enter a verb again:- creating
Enter an adjective:- fast


-----------Original Story-----------
A teenage boy named John had just passed his driving test
and asked his Dad if he could start using the family car. The Dad
said he'd make a deal with John, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the car". John thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "John, you've brought your
grades up and I've observed that you have been studying your
Bible, but I'm disappointed you haven't had your hair cut."
John said, "You know, Dad, I've been thinking about that,
and I've noticed in my studies of the Bible that Samson had
long hair, John the Baptist had long hair, Moses had long hair,
and there's even strong evidence that Jesus had long hair." His
Dad replied,"Did you also notice that they all walked everywhere
they went?"

-----------Madlib Story-----------
A fast boy named someone had just passed his programming test
and asked his Dad if he could start using the family laptop. The Dad
said he'd make a typing with someone, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the laptop". someone thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "someone, you've brought your
grades up and I've observed that you have been studying your Bible,
but I'm disappointed you haven't had your hair cut."
someone said, "You know, Dad, I've been searching about that, and I've
noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's even
strong evidence that Jesus had long hair." His Dad replied,
"Did you also notice that they all creating everywhere they went?"
Madlib_logo ='''
            , ; ,     
        .'         '.
       /   ()   ()   \\
      ;               ;
      ; :.  MADLIB .; ;
       \\'.'-.....-'.'/
        '.'.-.-,_.'.'
          '(  (..-'
            '-'
'''
print(Madlib_logo)
#step1: Store story in a variable.
story = '''A teenage boy named John had just passed his driving test
and asked his Dad if he could start using the family car. The Dad
said he'd make a deal with John, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the car". John thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "John, you've brought your
grades up and I've observed that you have been studying your
Bible, but I'm disappointed you haven't had your hair cut."
John said, "You know, Dad, I've been thinking about that,
and I've noticed in my studies of the Bible that Samson had
long hair, John the Baptist had long hair, Moses had long hair,
and there's even strong evidence that Jesus had long hair." His
Dad replied,"Did you also notice that they all walked everywhere
they went?"'''

#step2: Input variables.
name = input("Enter a name:- ")
skill = input("Enter a skill:- ")
object_ = input("Enter any object:- ")
verb1 = input("Enter a verb:- ")
verb2 = input("Enter another verb:- ")
verb3 = input("Enter a verb again:- ")
adjective = input("Enter an adjective:- ")

#step3: Store the variables in a list
blanks = [name, skill, object_, verb1, verb2, verb3, adjective]

#step4: Merge variable in story using an f-string
changed_story = f'''A {blanks[6]} boy named {blanks[0]} had just passed his {blanks[1]} test
and asked his Dad if he could start using the family {blanks[2]}. The Dad
said he'd make a {blanks[3]} with {blanks[0]}, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the {blanks[2]}". {blanks[0]} thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "{blanks[0]}, you've brought your
grades up and I've observed that you have been studying your Bible,
but I'm disappointed you haven't had your hair cut."
{blanks[0]} said, "You know, Dad, I've been {blanks[4]} about that, and I've
noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's even
strong evidence that Jesus had long hair." His Dad replied,
"Did you also notice that they all {blanks[5]} everywhere they went?"'''

#step5: print both the stories
print(f"\n\n-----------Original Story-----------\n{story}\n\n-----------Madlib Story-----------\n{changed_story}")
            , ; ,     
        .'         '.
       /   ()   ()   \
      ;               ;
      ; :.  MADLIB .; ;
       \'.'-.....-'.'/
        '.'.-.-,_.'.'
          '(  (..-'
            '-'

Enter a name:- Emma
Enter a skill:- acting
Enter any object:- sword
Enter a verb:- crying
Enter another verb:- sleeping
Enter a verb again:- dancing
Enter an adjective:- magical


-----------Original Story-----------
A teenage boy named John had just passed his driving test
and asked his Dad if he could start using the family car. The Dad
said he'd make a deal with John, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the car". John thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "John, you've brought your
grades up and I've observed that you have been studying your
Bible, but I'm disappointed you haven't had your hair cut."
John said, "You know, Dad, I've been thinking about that,
and I've noticed in my studies of the Bible that Samson had
long hair, John the Baptist had long hair, Moses had long hair,
and there's even strong evidence that Jesus had long hair." His
Dad replied,"Did you also notice that they all walked everywhere
they went?"

-----------Madlib Story-----------
A magical boy named Emma had just passed his acting test
and asked his Dad if he could start using the family sword. The Dad
said he'd make a crying with Emma, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the sword". Emma thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "Emma, you've brought your
grades up and I've observed that you have been studying your Bible,
but I'm disappointed you haven't had your hair cut."
Emma said, "You know, Dad, I've been sleeping about that, and I've
noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's even
strong evidence that Jesus had long hair." His Dad replied,
"Did you also notice that they all dancing everywhere they went?"
Madlib_logo ='''
            , ; ,     
        .'         '.
       /   ()   ()   \\
      ;               ;
      ; :.  MADLIB .; ;
       \\'.'-.....-'.'/
        '.'.-.-,_.'.'
          '(  (..-'
            '-'
'''
print(Madlib_logo)
#step1: Store story in a variable.
story = '''A teenage boy named John had just passed his driving test
and asked his Dad if he could start using the family car. The Dad
said he'd make a deal with John, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the car". John thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "John, you've brought your
grades up and I've observed that you have been studying your
Bible, but I'm disappointed you haven't had your hair cut."
John said, "You know, Dad, I've been thinking about that,
and I've noticed in my studies of the Bible that Samson had
long hair, John the Baptist had long hair, Moses had long hair,
and there's even strong evidence that Jesus had long hair." His
Dad replied,"Did you also notice that they all walked everywhere
they went?"'''

#step2: Input variables.
name = input("Enter a name:- ")
skill = input("Enter a skill:- ")
object_ = input("Enter any object:- ")
verb1 = input("Enter a verb:- ")
verb2 = input("Enter another verb:- ")
verb3 = input("Enter a verb again:- ")
adjective = input("Enter an adjective:- ")

#step3: Merge variable in story using an f-string
changed_story = f'''A {adjective} boy named {name} had just passed his {skill} test
and asked his Dad if he could start using the family {object_}. The Dad
said he'd make a {verb1} with {name}, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the {object_}". {name} thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "{name}, you've brought your
grades up and I've observed that you have been studying your Bible,
but I'm disappointed you haven't had your hair cut."
{name} said, "You know, Dad, I've been {verb2} about that, and I've
noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's even
strong evidence that Jesus had long hair." His Dad replied,
"Did you also notice that they all {verb3} everywhere they went?"'''

#step4: print both the stories
print(f"\n\n-----------Original Story-----------\n{story}\n\n-----------Madlib Story-----------\n{changed_story}")
input_string = input()
input_string = input_string.upper() #to convert all letters of
#string to upper case
print(len(input_string)) #to count the total no. of characters
str_to_list = input_string.split(",") #to convert the string to list
#so that we can join the list with full stops
print(".".join(str_to_list)) #to join the elements of the list to
#form a full stop separated string
word="standard"
ans5 = word[1:4]
print(ans5)
#Output should be tan
word="standard"
ans4 = word[:6:2]
#Another way:- word[0:6:2]
print(ans4)
#Output should be sad
wrd="Toscana"
ans3 =wrd[3:6]
print(ans3)
#Output should be can
find_sum = 'Lorem Ipsum'
ans2 = find_sum[8:]
# Another way:- find_sum[8:11]
print(ans2)
#Output should be sum
word = 'Typesetting'
ans1 = word[:3] 
#Another way:- word[0:3]
print(ans1)
#output: Typ
word="standard"
ans5 =
print(ans5)
#Output should be tan
word="standard"
ans4 =
print(ans4)
#Output should be sad
wrd="Toscana"
ans3 =
print(ans3)
#Output should be can
find_sum = 'Lorem Ipsum'
ans2 =
print(ans2)
#Output should be sum
word = 'Typesetting'
ans1 = 
print(ans1)
#Output should be Typ
str1 = "I am happy"
print(str1[0]) # I
print(str1[1]) #  (whitespace)
print(str1[2]) # a
print(str1[3]) # m
print(str1[4]) #  (whitespace)
print(str1[5]) # h
print(str1[6]) # a
print(str1[7]) # p
print(str1[8]) # p
print(str1[9]) # y
son = "John"
father = "Dad"
thing = "car"
verb = "walked"
print(f'''A teenage boy named {son} had just passed his driving test
and asked his {father} if he could start using the family {thing}.
The {father} said he'd make a deal with {son}, "You bring your 
grades up from a C to a B average, study your Bible a little, and 
get your hair cut.
Then we'll talk about the {thing}". {son} thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the {father} said, "{son}, you've brought 
your grades up and I've observed that you have been studying your 
Bible, but I'm disappointed you haven't had your hair cut."
{son} said, "You know, {father}, I've been thinking about that, and
I've noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's
even strong evidence that Jesus had long hair." His {father} 
replied, "Did you also notice that they all {verb} everywhere they 
went?"''')
what ="f-string"
adjective = "fantastic"

print(f"{what} is {adjective}")
name = "Python"
age = 31
number = 284.242

print("I am %s I am %d years old. I support floating point numbers like %f." % (name, age, number))
action1 = "Sing"
action2 = "Dance"
action3 = "Be difficult"

print("Three things that python can't do:- {}, {}, and {}!!".format(action1, action2, action3))
#Keyword and position are also possible
show = "Monty Python's Flying Circus,"

print("Python is named after ", show, " a BBC comedy series from the 1970s.")
game = "PUBG"
print(game+" is a game!!")

#!!Don't forget to give a space before 'is' otherwise
#PUBGis a game!!   #This will be your ouptut
#-----GAME-----
diamonds = 10
#player won 
daimonds += 5
#player lost
diamonds -= 1
#player wants to see total no. of diamonds he has
print("The total no. of diamonds you have = ", diamonds)
import pandas as pd
import sqlalchemy as sa

engine = sa.create_engine("mssql+pyodbc://@mssqlLocal64")

def dump_tran_test_table(conn):
    print(conn.execute(sa.text("SELECT * FROM tran_test")).fetchall())

# set up test environment
with engine.begin() as conn:
    conn.exec_driver_sql("DROP TABLE IF EXISTS tran_test")
    conn.exec_driver_sql(
        "CREATE TABLE tran_test "
        "(txt varchar(10), id int primary key)"
    )
    conn.exec_driver_sql(
        "INSERT INTO tran_test (txt, id) VALUES "
        "('old_foo', 1), ('old_bar', 2)"
    )

# test
with engine.connect() as conn:
    tran = conn.begin()
    df = pd.DataFrame([("new_baz", 3)], columns=["txt", "id"])
    df.to_sql("tran_test", conn, index=False, if_exists="append")
    dump_tran_test_table(conn)
    """console output:
    [('old_foo', 1), ('old_bar', 2), ('new_baz', 3)]
    """
    tran.rollback()
    dump_tran_test_table(conn)
    """console output:
    [('old_foo', 1), ('old_bar', 2)]
    """
>>> import pandas as pd
>>> 
>>> df = pd.DataFrame(['1/2/2020','12/31/2020','20-Jun-20'],columns=['Date'])
>>> df
         Date
0    1/2/2020
1  12/31/2020
2   20-Jun-20
>>> 
>>> df['Date'] = pd.to_datetime(df['Date'])
>>> df
        Date
0 2020-01-02
1 2020-12-31
2 2020-06-20
>>> 
>>> df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%y-%m-%d')
>>> 
>>> df
       Date
0  20-01-02
1  20-12-31
2  20-06-20
>>> 


from langflow import CustomComponent

from langchain.llms.base import BaseLLM
from langchain.chains import LLMChain
from langchain import PromptTemplate
from langchain.schema import Document

import requests

class YourComponent(CustomComponent):
    display_name: str = "Custom Component"
    description: str = "Create any custom component you want!"

    def build_config(self):
        return { "url": { "multiline": True, "required": True } }

    def build(self, url: str, llm: BaseLLM, prompt: PromptTemplate) -> Document:
        response = requests.get(url)
        chain = LLMChain(llm=llm, prompt=prompt)
        result = chain.run(response.text[:300])
        return Document(page_content=str(result))
import emailvalidationio

client = emailvalidationio.Client('YOUR-API-KEY')
result = client.validate('support@emailvalidation.io')
print(result)
import requests
url = "https://api.currencyapi.com/v3/latest"
headers = {
    'apikey': 'YOUR-API-KEY'
}
response = requests.request("GET", url, headers=headers)
print(response.text
      
num_str = "10" #it is a string because it is inside quotes
num = 10.1 #it is an float
num_result = int(num_str) + num #telling python that num_str 
#is a number and to add it to num.
print(num_result)
print(type(num_result))
num_str = "10" #it is a string because it is inside quotes
num = 10.1 #it is an float
num_result = num_str + num
print(num_result)
print(type(num_result))
num1 = 10 #it is an integer
num2 = 10.1 #it is an float
num3 = num1 + num2 #it will be converted to float to avoid data loss
print(num3) #20.1
print(type(num3)) #it got converted to float datatype
#addition
print(8+9) #17
#division
print(8/9) #0.8888888888888888
#multiplication
print(8*9) #72
#finding remainder
print(8%9) #8
#These are all examples of arithmetic operators(+,/,*,%).
print(3+1j)
a = (3+1j) # This is also a variable we will discuss them next to next post.
print(type(a))
print(10 > 9)
print(10 == 9)
print(10 < 9)
player= "won" # this line creates a variable we will discuss them later. It prints nothing.
print(player=="won")
print(1)
print(1,1)
print(type(1))
#And so on.
print("Hiii")#this is an inline comment
print(" '#' This is not a comment this will be printed")
#First
#Put a
# hash 
#before all the lines
#you want to comment

print('This must be quite obvious, anyways the next option is:')

  #Second
"""put the
multi line either between three 
double quotes or"""
'''between
three
single quotes'''
#
#This is a single line comment
print("Hello World")
#print("This too will be treated as a comment")
#This is a comment.
print("however, this will be printed") #This is also a comment
import tkinter as tk
from tkinter import messagebox
import random
import smtplib
import tkinter.messagebox as mbox
from email.mime.multipart import MIMEMultipart
import time
from email.mime.base import MIMEBase
from email import encoders

import getpass
from email.mime.text import MIMEText
obsah_desifrovane_zpravy = ""


def tlacitko_klik():

    okno.destroy()
    menu = tk.Tk()
    menu.geometry("800x800")
    # menu.configure(bg="light gray")
    menu.title("HiddenLanguage")


    label1 = tk.Label(menu,text="\n" +"Šifrovat či Dešifrovat?",font=("Arial",30,"bold"))
    label1.pack()

    label2 = tk.Label(menu,text="Chcete šifrovat nebo dešifrovat?",font=("Arial",15))
    label2.pack()

    # --------------------------------
    def tlacitko_klik_sif():
        import json
        # Tady se vyčistí soubory txt ze speciálního nastavení = 1) nápověda v emailu, 2) přezdívka v emailu
        with open("napoveda_uzivatel", "w") as file:
            file.write("ano")

        data = data = {
    "chce_prezdivku": False,
    "prezdivka": "prezdivka"
                    }
        with open("prezdivka.json", "w") as json_file:
            json.dump(data, json_file)


        #Přes tento kod se uloží hodnoty a spustí funkce Šifrování a email.
        def ulozeni_hodnot_mail():
            # Získáme text z textboxu (Text widgetu)
            zprava_ke_skryti = textbox_obsah.get("1.0", "end-1c")  # "1.0" označuje začátek a "end-1c" označuje konec textu
            nazev_souboru_sifr = (str(textbot_nazev_souboru.get("1.0", "end-1c")) + ".txt")
            odesilatel = textbot_odesilatel.get("1.0", "end-1c")
            prijemce = textbot_prijemce.get("1.0", "end-1c")
            heslo = textbot_odesilatel_heslo.get("1.0", "end-1c")
            #List který slouží pro for i in range dole


            with open("zprava_ke_skryti.txt","w") as file:
                file.write(zprava_ke_skryti)
            with open(nazev_souboru_sifr, "w") as file:
                file.write(nazev_souboru_sifr)
            with open("odesilatel.txt","w") as file:
                file.write(odesilatel)
            with open("prijemce.txt","w") as file:
                file.write(prijemce)
            with open("heslo.txt", "w") as file:
                file.write(heslo)

            # Tady získáváme informace ke každé informaci v podobě True False (jestli je pole prázdné nebo ne) Stačí aby bylo jedno a bude error
            if not zprava_ke_skryti.strip() or not nazev_souboru_sifr.strip() or not odesilatel.strip() or not prijemce.strip() or not heslo.strip():
                messagebox.showinfo("Upozornění", "Vyplňte všechna pole!")

            if odesilatel.strip():
                if not odesilatel[-10:] == "@gmail.com":
                    messagebox.showinfo("Upozornění", "Jediná možná adresa u odesílatele e-mailu je @gmail.com!")

            Sifrovani(zprava_ke_skryti, nazev_souboru_sifr)
            with open("sifrovani.txt", "r") as file:
                sifrovany_text = file.read()
                #oznamena_sifra = tk.Label(sifrovani_okno, text=(
                        #"Vaše skrytá zakodovaná šifra zní takto: " + str(sifrovany_text)),
                #oznamena_sifra.place(x=150, y=650, width=600, height=100)
            email(odesilatel, prijemce, heslo, nazev_souboru_sifr)
            mbox.showinfo("Upozornění", "Úspěšně odeslán email!")

            # Tady vyčistíme všechny hodnoty aby nemohl spamovat maily zasebou
            textbox_obsah.delete("1.0", tk.END)
            textbot_nazev_souboru.delete("1.0", tk.END)
            textbot_odesilatel.delete("1.0", tk.END)
            textbot_prijemce.delete("1.0", tk.END)
            textbot_odesilatel_heslo.delete("1.0", tk.END)

            #sifrovani_okno.destroy()
            #time.sleep(2)
            #Uvodni_menu()



        #Vytvoření šifrovacího okna
        sifrovani_okno = tk.Tk()
        sifrovani_okno.geometry("1920x1080")
        sifrovani_okno.title("Šifrování")
        menu.destroy()

        def zpet_do_menu():
            sifrovani_okno.destroy()
            Uvodni_menu()

        label1 = tk.Label(sifrovani_okno ,text="Šifrování", font=("Arial", 30))
        label1.pack()

        label2 = tk.Label(sifrovani_okno,text="Níže napište svoji zprávu, jenž chcete šifrovat.", font=("Arial", 15))
        label2.pack()
        textbox_obsah = tk.Text(sifrovani_okno, height=10,width=50, font=("Arial", 15))
        textbox_obsah.pack(pady=20)


        label3 = tk.Label(sifrovani_okno,padx=30, text="Zde napište název pro soubor, v němž bude uložen kod.", font=("Arial", 15))
        label3.pack()
        textbot_nazev_souboru = tk.Text(sifrovani_okno, height=1,width=30, font=("Arial", 15))
        textbot_nazev_souboru.pack(pady=20)

        #EMAIL
        email_odesilatel_label = tk.Label(sifrovani_okno,padx=35, text="Zadejte váš email", font=("Arial", 15))
        email_odesilatel_label.pack()
        textbot_odesilatel = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_odesilatel.pack(pady=20)

        email_prijemce_label = tk.Label(sifrovani_okno, padx=45, text="Zadejte email dané osoby", font=("Arial", 15))
        email_prijemce_label.pack()
        textbot_prijemce = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_prijemce.pack(pady=20)

        email_odesilatel_label_heslo = tk.Label(sifrovani_okno, padx=50, text="Zadejte vaše heslo", font=("Arial", 15))
        email_odesilatel_label_heslo.pack()
        textbot_odesilatel_heslo = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_odesilatel_heslo.pack(pady=20)

        kontrola = tk.Button(sifrovani_okno,text="Odeslat", command=ulozeni_hodnot_mail,font=("Arial",20),bg = "gray", fg = "black", activebackground = "blue",activeforeground="white")
        kontrola.pack(pady=10)

        poznamka = tk.Label(sifrovani_okno, text="Kod v souboru, jemuž dáváte název je takový kod bez mezer, který je důležitý při dešifrování." + "\n" +"Odesílatel musí mít emailovou adresu od Gmailu. Příjemce nemusí." + "\n" +"Heslo vámi zadané se nikam neukládá a za to vám ručím. Celý programovací kod je veřejně přístupný.", font=("Arial", 10))
        poznamka.pack(pady=10)

        navraceni_do_menu = tk.Button(sifrovani_okno,text="Vrátit se do menu",command=zpet_do_menu,font=("Arial",12,"bold"),bg="blue",fg="white",activeforeground="black")
        navraceni_do_menu.pack()

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

        # Tady jsou definovány checkboxy které se ptají na návod a přezdívku
        #Funkce SE SPUSTÍ JAKMILE UŽIVATEL ZMÁČKNE TLAČÍTKO PRO ULOŽENÍ



        def otevri_vyskakovaci_okno():
            vyskakovaci_okno = tk.Toplevel()
            vyskakovaci_okno.geometry("900x500")
            vyskakovaci_okno.title("Nastavení nápovědy v mailu")


            # Tady je definován textbox který se objeví jakmile je v druhé možnosti zaškrtnuto jakože ano
            # Tady bude textbox, který se zobrazí pouze jakmile je zaškrtnutá možnost 1
            def on_text_click(event):
                if textbox.get("1.0",
                               tk.END).strip() == "Napište přezdívku, jenž se objeví v emailu. Dbejte na svoji anonymitu. Přece jen, je to k tomu vytvořené!":
                    textbox.delete("1.0", tk.END)  # Smazat původní text při kliknutí do pole
                    textbox.config(fg='black')  # Změnit barvu textu na černou

            def on_focus_out(event):
                if textbox.get("1.0", tk.END).strip() == "":
                    textbox.insert("1.0",
                                   "Napište přezdívku, jenž se objeví v emailu. Dbejte na svoji anonymitu. Přece jen, je to k tomu vytvořené!")  # Pokud uživatel nezadal žádný text, vrátit původní placeholder
                    textbox.config(fg='grey')  # Nastavit barvu textu na šedou

            # Placeholder - původní text, který se zobrazuje, dokud uživatel nezačne psát
            placeholder = "Napište přezdívku, jenž se objeví v emailu. Dbejte na svoji anonymitu. Přece jen, je to k tomu vytvořené!"

            textbox = tk.Text(vyskakovaci_okno, height=3, width=40, wrap="word", fg='grey',font=("Arial",10))
            textbox.insert("1.0", placeholder)
            textbox.bind('<FocusIn>', on_text_click)  # Při kliknutí do pole
            textbox.bind('<FocusOut>', on_focus_out)  # Když pole ztratí focus (kliknutí mimo pole)
            #KONEC TEXTBOXUUUUUUUUUUU

            def on_checkbox_click():
                if napoveda.get() == 1:
                    with open("napoveda_uzivatel", "w") as file:
                        file.write("ano")
                else:
                    with open("napoveda_uzivatel", "w") as file:
                        file.write("ne")

            def chce_jmeno_checkbox_klik():
                if chce_jmeno_y_n.get() == 1:
                    textbox.pack(pady=10)
                else:
                    textbox.pack_forget()

            # Zde jsou checkboxy a otazky
            label = tk.Label(vyskakovaci_okno, text="Nastavení nápovědy", font=("Arial", 20),activeforeground="blue")
            label.pack(pady=10)
            label_napoveda = tk.Label(vyskakovaci_okno,
                                      text="A) Pokud zaškrtnete checkbox, tak bude mail obsahovat návod k dešifrování zprávy." + "\n" + "Pokud nezaškrtnete checkbox, tak nápověda v mailu nebude.",font=("Arial",11),activeforeground="blue")
            label_napoveda.pack(pady=10)

            napoveda = tk.IntVar()
            checkbox = tk.Checkbutton(vyskakovaci_okno,
                                      text="Chci aby email obsahoval nápovědu k řešení",
                                      font=("Arial", 12), variable=napoveda, command=on_checkbox_click)
            checkbox.pack(pady=10)


            # Tady je část kodu jenž se zaobývá uživatelem
            label_uzivatel = tk.Label(vyskakovaci_okno,
                                      text="B) Tady je checkbox, který pokud zaškrtnete tak budete mít možnost vymyslet si vlastní přezdívku." + "\n" + "Pokud nezaškrtnete tuto možnost, tak počítač při odeslání mailu přečte název vašeho usera na pc např host nebo tomáš apod.",
                                      font=("Arial", 11), activeforeground="blue")
            label_uzivatel.pack(pady=10)

            chce_jmeno_y_n = tk.IntVar()
            jmeno_uzivatele = tk.Checkbutton(vyskakovaci_okno,
                                      text="Chci si sám vytvořit přezdívku",
                                      font=("Arial", 12), variable=chce_jmeno_y_n, command=chce_jmeno_checkbox_klik)
            jmeno_uzivatele.pack(pady=10)

            #Toto uloží hodnoty z checkboxu
            def ulozeni_hodnot():
                import json
                if chce_jmeno_y_n.get() == 1:
                    prezdivka = textbox.get("1.0", "end-1c")

                    data = {
    "chce_prezdivku": True,
    "prezdivka": prezdivka
                    }

                    with open("prezdivka.json", "w") as json_file:
                        json.dump(data, json_file)
                vyskakovaci_okno.destroy()


            odeslat_button = tk.Button(vyskakovaci_okno,height=3,width=20,text="Potvrdit",command=ulozeni_hodnot,font=("Arial",16,"bold"),bg="blue",fg="white",activeforeground="black")
            odeslat_button.place(x=320,y=360)


        specialni_nastaveni = tk.Button(sifrovani_okno,text="Speciální nastavení",command=otevri_vyskakovaci_okno,font=("Arial",12,"bold"),bg="red",fg="white",activeforeground="black")
        specialni_nastaveni.pack(pady=5)


        #Konfigurace mailu
        def email(odesilatel,prijemce,password,nazev_souboru):
            import json
            import datetime

            with open("prezdivka.json", "r") as json_file:
                nactena_data = json.load(json_file)

            chceprezdivku = nactena_data["chce_prezdivku"]
            if chceprezdivku == True:
                qw = nactena_data["prezdivka"]
            else:
                qw = getpass.getuser()

            # Získání aktuálního času
            cas = datetime.datetime.now()
            hodiny_cas = cas.strftime("%H:%M:%S")
            formatovany_cas = cas.strftime("%Y-%m-%d %H:%M:%S")

            sender_password = password

            # Email configuration
            sender_email = odesilatel
            receiver_email = prijemce
            subject = "Byla vám poslána záhadná zpráva"

            with open(nazev_souboru,"r") as file:
                nova_abeceda = file.read()
            with open("napoveda_uzivatel","r") as file:
                napoveda_ano_ne = file.read()
            if napoveda_ano_ne == "ano":
                html_message = f"""<p><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 36px; color: rgb(0, 0, 0); text-shadow: rgba(136, 136, 136, 0) 0px 0px 0px;">Byla v&aacute;m odesl&aacute;na z&aacute;hadn&aacute; zpr&aacute;va</span></strong></span></p>
<p><span style="font-size: 26px;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Co to m&aacute; znamenat?</strong></span></span></p>
<p>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">Před několika vteřinami, přesněji v&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{hodiny_cas}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">&nbsp; byla zaznamen&aacute;na podivn&aacute; aktivita na jak&eacute;msi programu s n&aacute;zvem&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">HiddenLanguage</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Jedin&aacute; dohledateln&aacute; informace je, že uživatel se vyskytuje pod přezd&iacute;vkou&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{qw}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Pokud v&iacute;te co m&aacute;te dělat, tak čiňte jak usoud&iacute;te. V př&iacute;loze je zasl&aacute;n k&oacute;d, jenž se v&aacute;m bude zajist&eacute; hodit v dal&scaron;&iacute;ch akc&iacute;ch.</span></font>
</p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-size: 26px; font-family: Arial, Helvetica, sans-serif;"><strong>Zachycen&aacute; zpr&aacute;va ze serv</strong><strong>eru</strong></span></p>
<div><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 18px;">{sifrovany_text}</span></strong></span></div>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Zachycen&yacute; k&oacute;d ze serv</strong><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">eru</strong></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;"><strong>{nova_abeceda}</strong></span></p>
<p style="text-align: left;"><br></p>
<p><br></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Tvůrce HiddenLanguage</strong><img src="https://myfiles.space/user_files/168855_15d4659979401e54/168855_custom_files/img1690038712.jpeg" alt="He know where you are" style="margin: 0 auto; display: block; width: 1100px;" width="1100" height="614"></span></p>
<p style="text-align: left;"><br></p>
<p style="text-align: center;"><br></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Doba odesl&aacute;n&iacute;: {formatovany_cas}</strong></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Soubor ke stažen&iacute;: <a href="https://www.mediafire.com/file/blnje4ut0ped9pi/HiddenLanguage.exe/file" target="_blank" rel="noopener noreferrer">MediaFire Download</a><br></strong></span></p>
<div style="color: red;"><br></div>
"""

            else:
                html_message = f"""<p><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 36px; color: rgb(0, 0, 0); text-shadow: rgba(136, 136, 136, 0) 0px 0px 0px;">Byla v&aacute;m odesl&aacute;na z&aacute;hadn&aacute; zpr&aacute;va</span></strong></span></p>
<p><span style="font-size: 26px;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Co to m&aacute; znamenat?</strong></span></span></p>
<p>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">Před několika vteřinami, přesněji v&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{hodiny_cas}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">&nbsp; byla zaznamen&aacute;na podivn&aacute; aktivita na jak&eacute;msi programu s n&aacute;zvem&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">HiddenLanguage</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Jedin&aacute; dohledateln&aacute; informace je, že uživatel se vyskytuje pod přezd&iacute;vkou&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{qw}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Pokud v&iacute;te co m&aacute;te dělat, tak čiňte jak usoud&iacute;te. V př&iacute;loze je zasl&aacute;n k&oacute;d, jenž se v&aacute;m bude zajist&eacute; hodit v dal&scaron;&iacute;ch akc&iacute;ch.</span></font>
</p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-size: 26px; font-family: Arial, Helvetica, sans-serif;"><strong>Zachycen&aacute; zpr&aacute;va ze serv</strong><strong>eru</strong></span></p>
<div><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 18px;">{sifrovany_text}</span></strong></span></div>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Zachycen&yacute; k&oacute;d ze serv</strong><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">eru</strong></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: medium; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><span style="font-size: 18px;">{nova_abeceda}</span></strong></p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 26px;"><strong>Co d&aacute;le</strong></span></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">V př&iacute;loze jsou dva soubory. Jeden z nich se vždy jmenuje sifrovani.txt a druh&yacute; je pojmenov&aacute;n podle autora.</span></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 19px;"><strong><span style="color: rgb(226, 80, 65);">De&scaron;ifrov&aacute;n&iacute;</span></strong></span></p>
<ol>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">St&aacute;hněte tento soubor, kter&yacute; se nejmenuje &scaron;ifrov&aacute;n&iacute;, do složky Plocha - HiddenLanguage - Program.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Spusťte program a zvolte druhou možnost = de&scaron;ifrov&aacute;n&iacute;.&nbsp;</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte n&aacute;zev textov&eacute;ho souboru, jenž jste si před chv&iacute;l&iacute; st&aacute;hnul. (Pozor, napi&scaron;te n&aacute;zev bez .txt!)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Vložte nečiteln&yacute; k&oacute;d, jenž vid&iacute;te nad sebou v č&aacute;sti B.&nbsp;</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Počkejte na v&yacute;sledek</li>
</ol>
<p><b style="font-family: Arial, Helvetica, sans-serif; font-size: 16px;">V odeslan&yacute;ch zpr&aacute;v&aacute;ch by jste měli vidět v&aacute;&scaron; odeslan&yacute; mail.</b></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size: 19px; color: rgb(41, 105, 176);"><strong>&Scaron;ifrov&aacute;n&iacute;</strong></span></span></p>
<ol>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Spusťte program.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zvolte prvn&iacute; možnost.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte text, kter&yacute; chcete &scaron;ifrovat.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte n&aacute;zev pro uložen&iacute; va&scaron;eho k&oacute;du. (např. tajemny_kod)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Uvid&iacute;te za&scaron;ifrovanou zpr&aacute;vu</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Vyberte zda-li chcete &scaron;ifru poslat někomu na mail.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte svůj e-mail. (Pouze a jedině Gmail funguje)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte e-mail toho, kdož m&aacute; mail obdržet.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte sv&eacute; heslo. (heslo nikde neukl&aacute;d&aacute;me!)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Je hotovo!</li>
</ol>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p><br></p>
<p><br></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Tvůrce HiddenLanguage</strong><img src="https://myfiles.space/user_files/168855_15d4659979401e54/168855_custom_files/img1690038712.jpeg" alt="He know where you are" style="margin: 0 auto; display: block; width: 1100px;" width="1100" height="614"></span></p>
<p style="text-align: left;"><br></p>
<p style="text-align: center;"><br></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Doba odesl&aacute;n&iacute;: {formatovany_cas}</strong></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Soubor ke stažen&iacute;: <a href="https://www.mediafire.com/file/blnje4ut0ped9pi/HiddenLanguage.exe/file" target="_blank" rel="noopener noreferrer">MediaFire Download</a><br></strong></span></p>
<div style="color: red;"><br></div>
"""

            # Vytvoření instance MIMEText pro HTML obsah
            html_part = MIMEText(html_message, 'html')

            # Vytvoření multipart zprávy
            msg = MIMEMultipart()
            msg['From'] = sender_email
            msg['To'] = receiver_email
            msg['Subject'] = subject

            # Přidání HTML části do multipart zprávy
            msg.attach(html_part)


            # Přidání přílohy dm_heslo.txt
            with open(nazev_souboru, 'rb') as file:
                attachment = MIMEBase('application', 'octet-stream')
                attachment.set_payload(file.read())
                encoders.encode_base64(attachment)
                attachment.add_header('Content-Disposition', 'attachment', filename=nazev_souboru)
                msg.attach(attachment)

            # Přidání přílohy screenshot.png
            with open("sifrovani.txt", 'rb') as file:
                attachment = MIMEBase('application', 'octet-stream')
                attachment.set_payload(file.read())
                encoders.encode_base64(attachment)
                attachment.add_header('Content-Disposition', 'attachment', filename='sifrovani.txt')
                msg.attach(attachment)

            # Odeslání e-mailu
            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.starttls()
            server.login(odesilatel, sender_password)
            server.send_message(msg)
            server.quit()
        # Tady se dělá práce
        def Sifrovani(zprava_ke_skryti,nazev_souboru):
            abeceda = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz123456789ěščřžýáíé'
            nova_abeceda = ''.join(random.sample(abeceda, len(abeceda)))

            # Uložení šifrace

            with open(nazev_souboru, "w") as file:
                file.write(nova_abeceda)
            # Konec ukládání

            prevodni_tabulka = str.maketrans(abeceda, nova_abeceda)
            global sifrovany_text
            sifrovany_text = zprava_ke_skryti.translate(prevodni_tabulka)

            with open("sifrovani.txt", "w") as file:
                file.write(sifrovany_text)

        sifrovani_okno.mainloop()

    def tlacitko_klik_desif():
        def Zpet_do_menu():
            desifrovani_okno.destroy()
            Uvodni_menu()

        desifrovani_okno = tk.Tk()
        desifrovani_okno.geometry("1920x1080")
        desifrovani_okno.title("Dešifrování")
        menu.destroy()

        nazev = tk.Label(desifrovani_okno ,text="Dešifrování", font=("Arial", 30,"bold"))
        nazev.pack()

        zasifr_text = tk.Label(desifrovani_okno, text="Níže napište zprávu, jenž chcete dešifrovat.", font=("Arial", 15))
        zasifr_text.pack()


        textbox_obsah = tk.Text(desifrovani_okno, height=10, width=50, font=("Arial", 15))
        textbox_obsah.pack(pady=20)


        textbox_kod_label = tk.Label(desifrovani_okno,text="Zadejte dešifrovací kod v příloze (ten bez mezer)",font=("Arial",15))
        textbox_kod_label.pack(pady=5)
        textbox_kod = tk.Text(desifrovani_okno,height=2, width=20,font=("Arial",15))
        textbox_kod.pack(pady=10)

        def Redirect():
            # Toto je kod který se spustí po kliknutí na dešifrovácí tlačitko
            zasifrovany_text_textbox = textbox_obsah.get("1.0", "end-1c")
            textbox_kod_obsah = textbox_kod.get("1.0", "end-1c")
            Desifrovani(zasifrovany_text_textbox,textbox_kod_obsah)

        output_label = tk.Label(desifrovani_okno,text="Obsah dešifrované zprávy",font=("Arial",15))
        output_label.pack(pady=15)
        output = tk.Text(desifrovani_okno,height=10,width=50,font=("Arial",15))
        output.pack()


        # Tlačítka
        tlacitko_desifrovani = tk.Button(desifrovani_okno, text="Dešifrovat zprávu", command=Redirect, height=1,
                                         width=15, font=("Arial", 15,"bold"), bg="blue", fg="white")
        tlacitko_desifrovani.pack(pady=20)


        zpet_do_menu = tk.Button(desifrovani_okno, text="Zpět do menu", command=Zpet_do_menu,
                                   font=("Arial", 15, "bold"), bg="blue", fg="white", activeforeground="black")
        zpet_do_menu.pack(pady=10)


        def Desifrovani(zasifrovany_text,zasifrovany_kod):
            sifrovana_abeceda = zasifrovany_kod

            def create_decryption_map(original_alphabet, shuffled_alphabet):
                decryption_map = {}
                for orig_char, shuffled_char in zip(original_alphabet, shuffled_alphabet):
                    decryption_map[shuffled_char] = orig_char
                return decryption_map

            # Příklad použití:
            original_alphabet = 'ABDCEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz123456789ěščřžýáíé#@!§'
            shuffled_alphabet = sifrovana_abeceda

            decryption_map = create_decryption_map(original_alphabet, shuffled_alphabet)

            # Dešifrování zprávy
            encrypted_message = zasifrovany_text
            decrypted_message = "".join(decryption_map.get(char, char) for char in encrypted_message)
            obsah_desifrovane_zpravy = decrypted_message

            output.delete("1.0", "end")  # Vymažeme obsah textového pole
            output.insert("1.0", obsah_desifrovane_zpravy)  # Vložíme dešifrovanou zprávu do textového pole









        #Tady budou věci po checkboxech
        desifrovani_okno.mainloop()

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



    def Audio():
        import webbrowser
        audio_okno = tk.Tk()
        audio_okno.title("Audio informace")
        audio_okno.geometry("600x500")
        audio_okno.configure(bg="black")

        nazev = tk.Label(audio_okno,text="Audio informace",font=("Arial",25,"bold"),fg="blue",bg="black")
        nazev.pack(pady=10)
        podnadpis = tk.Label(audio_okno,text="Zde uslyšíte základní informace o projektu" + "\n" + "Kliknutím na malé tlačítko budete přesměrování na zdroj tts" + "\n" + "Dole je tlačítko na nahlášení bugu" + "\n" + "Takže pokud jste našli jakýkoliv bug, tak neváhejte a kontaktujte mě.",font=("Arial",13),fg="white",bg="black")
        podnadpis.pack(pady=10)

        # Tady budeme definovat akci když klikne na tlačítko s url
        def Web():
            url = "https://www.speechtech.cz/speechtech-text-to-speech/speechtech-tts-online-demo/#Oldrich30"
            webbrowser.open(url)

        web_button = tk.Button(audio_okno,width=15,height=1,command=Web,text="Zdroj TTS",font=("Arial",13),bg="blue",fg="white",activebackground="white", activeforeground="blue")
        web_button.pack(pady=10)



        from playsound import playsound
        def zpet_do_menu():
            audio_okno.destroy()
            tlacitko_klik()


        def spustit_audio():
            import getpass
            username = getpass.getuser()
            cesta_audio = ("C:\\Users\\" + str(username) + "\\Desktop\\HiddenLanguageAudio.mp3")
            playsound(cesta_audio)

        spustit_audio = tk.Button(audio_okno,width=25,height=3,command=spustit_audio,text="Spustit audio",font=("Arial",15),bg="blue",fg="white",activebackground="white", activeforeground="blue")
        spustit_audio.pack(pady=10)

        # Button pro vypnuti progresu a audia
        zastavit_audio = tk.Button(audio_okno, width=15, height=1, command=zpet_do_menu, text="Zpět do menu",
                                       font=("Arial", 15), bg="blue", fg="white", activebackground="white",
                                       activeforeground="blue")
        zastavit_audio.pack(pady=10)

        # Tlačítko na bugy
        def copy_to_clipboard():
            import tkinter.messagebox as mbox
            import pyperclip
            text_to_copy = "g3c45g8mkcdhaoigpg5q@centrum.cz"  # Získáme text z vstupního pole
            pyperclip.copy(text_to_copy)  # Zkopírujeme text do schránky
            mbox.showinfo("Úspěch", "Moje anonymní e-mailová adresa zkopírována do schránky.")


        nahlaseni_bugu = tk.Button(audio_okno, width=13, height=1, command=copy_to_clipboard, text="Nahlásit bug",
                                       font=("Arial", 13), bg="red", fg="white", activebackground="white",
                                       activeforeground="blue")
        nahlaseni_bugu.pack(pady=10)






        audio_okno.mainloop()


    def navraceni_do_menu():
        menu.destroy()
        Uvodni_menu()

    prostor_button = tk.Frame(menu)
    prostor_button.columnconfigure(0,weight=10)
    prostor_button.columnconfigure(1,weight=10)
    prostor_button.columnconfigure(2,weight=10)
    prostor_button.columnconfigure(3,weight=10)

    # Tady je tlačítko na šifrování
    tlacitko_sif = tk.Button(prostor_button,text="Šifrovat", command=tlacitko_klik_sif,font=("Arial",15,"bold"),width=50,height=4,bg="red", fg="white",activebackground="#F07474",activeforeground="black")
    tlacitko_sif.grid(row=0,column=0,sticky=tk.W+tk.E)

    # Tady je tlačítko na dešifrování
    tlacitko_desif = tk.Button(prostor_button,text="Dešifrovat", command=tlacitko_klik_desif,font=("Arial",15,"bold"),width=50,height=4,bg="green", fg="white",activebackground="#9CEF99",activeforeground="black")
    tlacitko_desif.grid(row=1,column=0,sticky=tk.W+tk.E)

    # Nově přidané audio info zde
    tlacitko_audio = tk.Button(prostor_button, text="Informace", command=Audio,
                               font=("Arial", 15, "bold"), width=50, height=4, bg="black", fg="white",
                               activebackground="white", activeforeground="black")
    tlacitko_audio.grid(row=2, column=0, sticky=tk.W + tk.E)

    # Tady je tlačítko na zpět do menu
    tlacitko_menu = tk.Button(prostor_button, text="Zpět do menu", command=navraceni_do_menu, font=("Arial", 15, "bold"),width=50,height=4,
                               bg="purple", fg="white", activebackground="pink",
                               activeforeground="black")
    tlacitko_menu.grid(row=3,column=0,sticky=tk.W+tk.E)

    prostor_button.pack(pady=100)
    #(x=600, y=100, width=100, height=100)

    menu.mainloop()



def Uvodni_menu():
    # Vytvoření okna
    global okno
    okno = tk.Tk()
    okno.geometry("800x600")
    okno.title("HiddenLanguage")

    # widget s časem
    def update_time():
        current_time = time.strftime("%d.%m.%Y %H:%M:%S")  # Formát času (hodiny:minuty:sekundy)
        time_label.config(text=current_time)
        okno.after(1000, update_time)  # Znovu spustit funkci každou sekundu (1000 ms)


    # Vytvoření tlačítka
    nazev = tk.Label(okno, text="\n" + "HiddenLanguage", font=("Arial", 30, "bold"),fg="blue")
    nazev.pack()

    aktualni_update = tk.Label(okno, text="Aktuální verze 1.1 ze dne 2023-07-29", font=("Arial", 15, "bold"),fg="blue",bg="#A1B7FF")
    aktualni_update.pack()
    informace = tk.Label(okno,
                         text="Tento program umí šifrovat a dešifrovat zprávy." + "\n" + "Zašifrované zprávy může odeslat jakékoliv určené osobě na mail." + "\n" + "Více informací naleznete na kubasobr.blogspot.com" + "\n" + "Original HiddenLanguage, all rights reserved",
                         font=("Arial", 12))
    informace.pack()

    tlacitko = tk.Button(okno, text="Klikněte pro start!", command=tlacitko_klik, font=("Arial", 25, "bold"), height=5,
                         width=24, bg="blue", fg="white", activebackground="aqua", activeforeground="black")
    tlacitko.pack(padx=50, pady=20)

    copyright = tk.Label(okno, text="Naprogramoval Jakub Šobr 2023", font=("Arial", 9))
    copyright.pack()

    #WiDGET S AKTUÁLNÍM ČASEM CO SE AKTUALIZUJE PO 1s
    time_label = tk.Label(okno, font=("Helvetica", 24), bg="light gray")
    time_label.pack(fill=tk.BOTH, expand=True)
    update_time()


    # Spuštění smyčky událostí (main loop)
    okno.mainloop()

def Prihlaseni():

    import tkinter as tk
    import time

    def update_time():
        current_time = time.strftime("%d.%m %Y - %H:%M:%S")
        time_label.config(text=current_time)
        prihlaseni.after(1000, update_time)

    def tlacitko_potvrdit_heslo():
        uzivatel= entry_uzivatel.get()
        heslo = entry_password.get()
        if heslo == "***" and uzivatel == "***" or heslo == "host" and uzivatel == "host":
            label_error.config(text="Zadali jste správné heslo.", font=("Arial", 10), fg="blue")
            prihlaseni.destroy()
            # ... Pokračování s vaším kódem ...
            Uvodni_menu()
        else:
            label_error.config(text="Neplatné uživatelské jméno nebo heslo.",font=("Arial",10))
            entry_password.delete(0, tk.END)
            entry_uzivatel.delete(0, tk.END)

    def tlacitko_stisk_klavesy(event):
        tlacitko_klik()

    def on_close():
        pass  # Prázdná funkce zabrání zavření okna

    prihlaseni = tk.Tk()
    prihlaseni.geometry("800x700")
    prihlaseni.title("HiddenLanguage")

    prihlaseni.protocol("WM_DELETE_WINDOW", on_close)  # Zavolání funkce on_close při pokusu o zavření okna

    label = tk.Label(prihlaseni, text="Vítejte v aplikaci HiddenLanguage", font=("Arial", 30, "bold"))
    label.pack(pady=50)


    # TADY JE KOLONKA NA UŽIVATELE
    label_uzivatel = tk.Label(prihlaseni,text="Zadejte uživatelské jméno:",font=("Arial",20))
    label_uzivatel.pack()

    entry_uzivatel = tk.Entry(prihlaseni, font=("Arial", 20))
    entry_uzivatel.pack(pady=20)

    #KOLONKA NA HESLO
    label_password = tk.Label(prihlaseni, text="Zadejte heslo:", font=("Arial", 20))
    label_password.pack()

    entry_password = tk.Entry(prihlaseni, font=("Arial", 20), show="*")
    entry_password.pack(pady=20)
    #konec kolonky a potvrzení v podobe tlacitka


    prihlaseni_button = tk.Button(prihlaseni, text="Potvrdit",bg="blue",fg="white", font=("Arial", 20), command=tlacitko_potvrdit_heslo)
    prihlaseni_button.pack(pady=10)

    # Tady je ukončení programu definitivně!!
    def Konec():
        exit()
    konec = tk.Button(prihlaseni, text="Opustit aplikaci", command=Konec,
                                  font=("Arial", 12, "bold"), bg="red", fg="white", activeforeground="black")
    konec.pack()


    label_error = tk.Label(prihlaseni, text="", font=("Arial", 15), fg="red")
    label_error.pack()

    entry_password.bind("<Return>", tlacitko_stisk_klavesy)

    time_label = tk.Label(prihlaseni, font=("Helvetica", 24), bg="light gray")
    time_label.pack(fill=tk.BOTH, expand=True)
    update_time()

    prihlaseni.mainloop()
Prihlaseni()
Uvodni_menu()

#HiddenLanguage 2023 made by Jakub Šobr
#Můžete se podívat ale heslo FR FR nikde není ukládaný, nejsem cockot
#Ukládají se jenom soubory který se pak nahrávají do přílohy apod.
#Pokud se bojíte tak si udělejte API key od googlu https://console.cloud.google.com/ Crede
#Ostatní info v readme
#Import packages
import numpy as np
#import argparse
import cv2
import random
import pygame
from email.message import EmailMessage
import imutils
import time
import datetime
import imghdr
import os
from collections import Counter
import playsound
import requests
from playsound import playsound
#from imutils.video import VideoStream
from imutils.video import FPS
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# construct the argument parse and parse the arguments
#ap = argparse.ArgumentParser()
#ap.add_argument("-p", "--prototxt", required=True, help="path to Caffe 'deploy' prototxt file")
#ap.add_argument("-m", "--model", required=True, help="path to Caffe pre-trained model")
#ap.add_argument("-c", "--confidence", type=float, default=0.2, help="minimum probability to filter weak detections")
#args = vars(ap.parse_args())

protext="DNN_Object_Detection-master/DNN_Object_Detection-master/MobileNetSSD_deploy.prototxt.txt"
model="DNN_Object_Detection-master/DNN_Object_Detection-master/MobileNetSSD_deploy.caffemodel"

	# initialize the list of class labels MobileNet SSD was trained to
	# detect, then generate a set of bounding box colors for each class
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
REQ_CLASSES=["bird","cat","cow","dog","horse","sheep"]
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))

	#Load model
print("Loading Model...")
net=cv2.dnn.readNetFromCaffe(protext, model)
print("Starting camera feed...")

vs=cv2.VideoCapture(0, cv2.CAP_DSHOW)
	#vs=VideoStream(src=0).start()
time.sleep(2)
fps=FPS().start()

	#Set confidence threshold
conf_thresh=0.2

	#Animal detection counter
count=[]
flag=0
siren_loc=os.path.join(os.getcwd(),'Siren.wav')
global det
det=0
	#Read frame by frame
while vs:
	success, frame = vs.read()
	if not success:
		break
	frame = imutils.resize(frame, width=500)
	#Take the frame dimentions and convert it to a blob
	(h, w) = frame.shape[:2]
	blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300,300)), 0.007843, (300,300), 127.5)

	net.setInput(blob)
	detections = net.forward()
	#frame detection flag
	for i in np.arange(0, detections.shape[2]):
		#Probability associated with predictions
		confidence = detections[0,0,i,2]
		if confidence > conf_thresh:
			#Extract the class labels and dimentions of bounding box
			idx = int(detections[0,0,i,1])
			box = detections[0,0,i,3:7]*np.array([w,h,w,h])
			(startX, startY, endX, endY) = box.astype("int")

			#draw the box with labels
			if CLASSES[idx] in REQ_CLASSES:
				det+=1
				label="{}: {:.2f}%".format("Animal",confidence*100)
				cv2.rectangle(frame, (startX, startY), (endX, endY), (36,255,12), 2)
				if (startY-15) > 15:
					y = (startY - 15)
				else:
					y = (startY+15)
				print(f"Animal Intrusion Alert...!!! {len(count)}")
				path = r"siren/alert"
				file = os.path.join(path, random.choice(os.listdir(path)))
				pygame.mixer.init()
				pygame.mixer.music.load(file)
				pygame.mixer.music.play()
				if det >=10:
					nn = random.randint(0, 100)
					noOfFile = 'Animal' + str(nn) + '.jpg'
					print(type(noOfFile))
					cv2.imwrite("static/Animal_data/" + noOfFile, frame[startY:endY, startX:endX])
					ts = time.time()
					date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
					timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
					s1 = "a@gmail.com"
					msg = 'Hi countryman!!'
					msg1 = 'We have captured an animal in your forms at ' + timeStamp + ' on ' + date + ' please be safe. '
					t = 'Regards,'
					t1 = 'AI Farming Services.'
					mail_content1 = msg + ',' + '\n' + msg1 + '\n' + '\n' + t + '\n' + t1
					sender_address = 'dopatisukumar@gmail.com'
					sender_pass = 'rzihvvowxagwrwgd'
					receiver_address = 'sukumardopati@gmail.com'
					message1 = MIMEMultipart()
					message1['From'] = sender_address
					message1['To'] = receiver_address
					message1['Subject'] = 'Animal Detection Using OpenCV'
					message1.attach(MIMEText(mail_content1, 'plain'))
					session2 = smtplib.SMTP('smtp.gmail.com', 587)
					session2.starttls()
					session2.login(sender_address, sender_pass)
					text1 = message1.as_string()
					session2.sendmail(sender_address, receiver_address, text1)
					session2.quit()

					newMessage = EmailMessage()
					newMessage['Subject'] = "Animal Detection Using OpenC"
					newMessage['From'] = sender_address
					newMessage['To'] = receiver_address
					newMessage.set_content(mail_content1)

					with open('static/Animal_data/' + noOfFile, 'rb') as f:
						image_data = f.read()
						image_type = imghdr.what(f.name)
						image_name = f.name

					newMessage.add_attachment(image_data, maintype='image', subtype=image_type, filename=image_name)

					with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
						smtp.login(sender_address, sender_pass)
						smtp.send_message(newMessage)

					url = "https://www.fast2sms.com/dev/bulkV2"
					print(url)

					no = '9390517887'
					data = {
						"route": "q",
						"message": mail_content1,
						"language": "english",
						"flash": 0,
						"numbers": no,
					}
					headers = {
						"authorization": "NgtD58YWLjubd2wXVFHAyrP6xOmRvaKeECJ1GhQUBfSsMc7piob3ELPkxpFqQnT7Gu6sitdUIBXMCrSW",
						"Content-Type": "application/json"
					}
					response = requests.post(url, headers=headers, json=data)
					print(response)
					cv2.putText(frame, label, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (36,255,12), 2)


		#Show the frames
	cv2.imshow("Frame", frame)
	count.append(det)
	#Alerts only if at least 15 frames sucessfully detects animals in the last 36 frames (appx 2 sec)

	#if flag==1 and len(count) > c+36:
	#	flag=0
	if flag==1 and len(count) > c +(11*18):
		flag=0
	if Counter(count[len(count)-36:])[1] > 15 and flag==0:


		c=len(count)

	key = cv2.waitKey(1)
	if key == ord("q"):
		break
	fps.update()

fps.stop()
print("Elapsed time: {:.2f}".format(fps.elapsed()))
print("Approximate FPS: {:.2f}".format(fps.fps()))
vs.release()
cv2.destroyAllWindows()
#vs.stop()



import tkinter as tk
from tkinter import messagebox
import random
import smtplib

from email.mime.multipart import MIMEMultipart
import time
from email.mime.base import MIMEBase
from email import encoders

import getpass
from email.mime.text import MIMEText
obsah_desifrovane_zpravy = ""


def tlacitko_klik():

    okno.destroy()
    menu = tk.Tk()
    menu.geometry("800x700")
    # menu.configure(bg="light gray")
    menu.title("HiddenLanguage")


    label1 = tk.Label(menu,text="\n" +"Šifrovat či Dešifrovat?",font=("Arial",30,"bold"))
    label1.pack()

    label2 = tk.Label(menu,text="Chcete šifrovat nebo dešifrovat?",font=("Arial",15))
    label2.pack()

    def tlacitko_klik_sif():
        import json
        # Tady se vyčistí soubory txt ze speciálního nastavení = 1) nápověda v emailu, 2) přezdívka v emailu
        with open("napoveda_uzivatel", "w") as file:
            file.write("")

        data = {}
        with open("prezdivka.json", "w") as json_file:
            json.dump(data, json_file)


        #Přes tento kod se uloží hodnoty a spustí funkce Šifrování a email.
        def ulozeni_hodnot_mail():
            # Získáme text z textboxu (Text widgetu)
            zprava_ke_skryti = textbox_obsah.get("1.0", "end-1c")  # "1.0" označuje začátek a "end-1c" označuje konec textu
            nazev_souboru_sifr = (str(textbot_nazev_souboru.get("1.0", "end-1c")) + ".txt")
            odesilatel = textbot_odesilatel.get("1.0", "end-1c")
            prijemce = textbot_prijemce.get("1.0", "end-1c")
            heslo = textbot_odesilatel_heslo.get("1.0", "end-1c")
            #List který slouží pro for i in range dole


            with open("zprava_ke_skryti.txt","w") as file:
                file.write(zprava_ke_skryti)
            with open(nazev_souboru_sifr, "w") as file:
                file.write(nazev_souboru_sifr)
            with open("odesilatel.txt","w") as file:
                file.write(odesilatel)
            with open("prijemce.txt","w") as file:
                file.write(prijemce)
            with open("heslo.txt", "w") as file:
                file.write(heslo)

            # Tady získáváme informace ke každé informaci v podobě True False (jestli je pole prázdné nebo ne) Stačí aby bylo jedno a bude error
            if not zprava_ke_skryti.strip() or not nazev_souboru_sifr.strip() or not odesilatel.strip() or not prijemce.strip() or not heslo.strip():
                messagebox.showinfo("Upozornění", "Vyplňte všechna pole!")

            if odesilatel.strip():
                if not odesilatel[-10:] == "@gmail.com":
                    messagebox.showinfo("Upozornění", "Jediná možná adresa u odesílatele e-mailu je @gmail.com!")

            Sifrovani(zprava_ke_skryti, nazev_souboru_sifr)
            with open("sifrovani.txt", "r") as file:
                sifrovany_text = file.read()
                oznamena_sifra = tk.Label(sifrovani_okno, text=(
                        "Vaše skrytá zakodovaná šifra zní takto: " + str(sifrovany_text)),
                                          font=("Arial", 15))
                oznamena_sifra.place(x=150, y=650, width=600, height=100)
            email(odesilatel, prijemce, heslo, nazev_souboru_sifr)
            messagebox.showinfo("Upozornění", "Úspěšně odeslán email!")
            program_bude_ukoncen = tk.Label(sifrovani_okno,
                                            text="Toto okno bude do pár sekund zavřeno.Poté budete moci program použít znovu.")
            program_bude_ukoncen.place(x=250, y=650, width=600, height=100)
            time.sleep(5)
            sifrovani_okno.destroy()
            time.sleep(2)
            Uvodni_menu()



        #Vytvoření šifrovacího okna
        sifrovani_okno = tk.Tk()
        sifrovani_okno.geometry("1920x1080")
        sifrovani_okno.title("Šifrování")
        menu.destroy()

        def zpet_do_menu():
            sifrovani_okno.destroy()
            Uvodni_menu()

        label1 = tk.Label(sifrovani_okno ,text="Šifrování", font=("Arial", 30))
        label1.pack()

        label2 = tk.Label(sifrovani_okno,text="Níže napište svoji zprávu, jenž chcete šifrovat.", font=("Arial", 15))
        label2.pack()
        textbox_obsah = tk.Text(sifrovani_okno, height=10,width=50, font=("Arial", 15))
        textbox_obsah.pack(pady=20)


        label3 = tk.Label(sifrovani_okno,padx=30, text="Zde napište název pro soubor, v němž bude uložen kod.", font=("Arial", 15))
        label3.pack()
        textbot_nazev_souboru = tk.Text(sifrovani_okno, height=1,width=30, font=("Arial", 15))
        textbot_nazev_souboru.pack(pady=20)

        #EMAIL
        email_odesilatel_label = tk.Label(sifrovani_okno,padx=35, text="Zadejte váš email", font=("Arial", 15))
        email_odesilatel_label.pack()
        textbot_odesilatel = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_odesilatel.pack(pady=20)

        email_prijemce_label = tk.Label(sifrovani_okno, padx=45, text="Zadejte email dané osoby", font=("Arial", 15))
        email_prijemce_label.pack()
        textbot_prijemce = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_prijemce.pack(pady=20)

        email_odesilatel_label_heslo = tk.Label(sifrovani_okno, padx=50, text="Zadejte vaše heslo", font=("Arial", 15))
        email_odesilatel_label_heslo.pack()
        textbot_odesilatel_heslo = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_odesilatel_heslo.pack(pady=20)

        kontrola = tk.Button(sifrovani_okno,text="Odeslat", command=ulozeni_hodnot_mail,font=("Arial",20),bg = "gray", fg = "black", activebackground = "blue",activeforeground="white")
        kontrola.pack(pady=10)

        poznamka = tk.Label(sifrovani_okno, text="Kod v souboru, jemuž dáváte název je takový kod bez mezer, který je důležitý při dešifrování." + "\n" +"Odesílatel musí mít emailovou adresu od Gmailu. Příjemce nemusí." + "\n" +"Heslo vámi zadané se nikam neukládá a za to vám ručím. Celý programovací kod je veřejně přístupný.", font=("Arial", 10))
        poznamka.pack(pady=10)

        navraceni_do_menu = tk.Button(sifrovani_okno,text="Vrátit se do menu",command=zpet_do_menu,font=("Arial",12,"bold"),bg="blue",fg="white",activeforeground="black")
        navraceni_do_menu.pack()

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

        # Tady jsou definovány checkboxy které se ptají na návod a přezdívku
        #Funkce SE SPUSTÍ JAKMILE UŽIVATEL ZMÁČKNE TLAČÍTKO PRO ULOŽENÍ



        def otevri_vyskakovaci_okno():
            vyskakovaci_okno = tk.Toplevel()
            vyskakovaci_okno.geometry("900x500")
            vyskakovaci_okno.title("Nastavení nápovědy v mailu")


            # Tady je definován textbox který se objeví jakmile je v druhé možnosti zaškrtnuto jakože ano
            # Tady bude textbox, který se zobrazí pouze jakmile je zaškrtnutá možnost 1
            def on_text_click(event):
                if textbox.get("1.0",
                               tk.END).strip() == "Napište přezdívku, jenž se objeví v emailu. Dbejte na svoji anonymitu. Přece jen, je to k tomu vytvořené!":
                    textbox.delete("1.0", tk.END)  # Smazat původní text při kliknutí do pole
                    textbox.config(fg='black')  # Změnit barvu textu na černou

            def on_focus_out(event):
                if textbox.get("1.0", tk.END).strip() == "":
                    textbox.insert("1.0",
                                   "Napište přezdívku, jenž se objeví v emailu. Dbejte na svoji anonymitu. Přece jen, je to k tomu vytvořené!")  # Pokud uživatel nezadal žádný text, vrátit původní placeholder
                    textbox.config(fg='grey')  # Nastavit barvu textu na šedou

            # Placeholder - původní text, který se zobrazuje, dokud uživatel nezačne psát
            placeholder = "Napište přezdívku, jenž se objeví v emailu. Dbejte na svoji anonymitu. Přece jen, je to k tomu vytvořené!"

            textbox = tk.Text(vyskakovaci_okno, height=3, width=40, wrap="word", fg='grey',font=("Arial",10))
            textbox.insert("1.0", placeholder)
            textbox.bind('<FocusIn>', on_text_click)  # Při kliknutí do pole
            textbox.bind('<FocusOut>', on_focus_out)  # Když pole ztratí focus (kliknutí mimo pole)
            #KONEC TEXTBOXUUUUUUUUUUU

            def on_checkbox_click():
                if napoveda.get() == 1:
                    with open("napoveda_uzivatel", "w") as file:
                        file.write("ano")
                else:
                    with open("napoveda_uzivatel", "w") as file:
                        file.write("ne")

            def chce_jmeno_checkbox_klik():
                if chce_jmeno_y_n.get() == 1:
                    textbox.pack(pady=10)
                else:
                    textbox.pack_forget()

            # Zde jsou checkboxy a otazky
            label = tk.Label(vyskakovaci_okno, text="Nastavení nápovědy", font=("Arial", 20),activeforeground="blue")
            label.pack(pady=10)
            label_napoveda = tk.Label(vyskakovaci_okno,
                                      text="A) Pokud zaškrtnete checkbox, tak bude mail obsahovat návod k dešifrování zprávy." + "\n" + "Pokud nezaškrtnete checkbox, tak nápověda v mailu nebude.",font=("Arial",11),activeforeground="blue")
            label_napoveda.pack(pady=10)

            napoveda = tk.IntVar()
            checkbox = tk.Checkbutton(vyskakovaci_okno,
                                      text="Chci aby email obsahoval nápovědu k řešení",
                                      font=("Arial", 12), variable=napoveda, command=on_checkbox_click)
            checkbox.pack(pady=10)


            # Tady je část kodu jenž se zaobývá uživatelem
            label_uzivatel = tk.Label(vyskakovaci_okno,
                                      text="B) Tady je checkbox, který pokud zaškrtnete tak budete mít možnost vymyslet si vlastní přezdívku." + "\n" + "Pokud nezaškrtnete tuto možnost, tak počítač při odeslání mailu přečte název vašeho usera na pc např host nebo tomáš apod.",
                                      font=("Arial", 11), activeforeground="blue")
            label_uzivatel.pack(pady=10)

            chce_jmeno_y_n = tk.IntVar()
            jmeno_uzivatele = tk.Checkbutton(vyskakovaci_okno,
                                      text="Chci si sám vytvořit přezdívku",
                                      font=("Arial", 12), variable=chce_jmeno_y_n, command=chce_jmeno_checkbox_klik)
            jmeno_uzivatele.pack(pady=10)

            #Toto uloží hodnoty z checkboxu
            def ulozeni_hodnot():
                import json
                if chce_jmeno_y_n.get() == 1:
                    prezdivka = textbox.get("1.0", "end-1c")

                    data = {
    "chce_prezdivku": True,
    "prezdivka": prezdivka
                    }

                    with open("prezdivka.json", "w") as json_file:
                        json.dump(data, json_file)
                vyskakovaci_okno.destroy()


            odeslat_button = tk.Button(vyskakovaci_okno,height=3,width=20,text="Potvrdit",command=ulozeni_hodnot,font=("Arial",16,"bold"),bg="blue",fg="white",activeforeground="black")
            odeslat_button.place(x=320,y=360)


        specialni_nastaveni = tk.Button(sifrovani_okno,text="Speciální nastavení",command=otevri_vyskakovaci_okno,font=("Arial",12,"bold"),bg="red",fg="white",activeforeground="black")
        specialni_nastaveni.pack(pady=5)


        #Konfigurace mailu
        def email(odesilatel,prijemce,password,nazev_souboru):
            import json
            import datetime

            with open("prezdivka.json", "r") as json_file:
                nactena_data = json.load(json_file)

            chceprezdivku = nactena_data["chce_prezdivku"]
            if chceprezdivku == True:
                qw = nactena_data["prezdivka"]
            else:
                qw = getpass.getuser()

            # Získání aktuálního času
            cas = datetime.datetime.now()
            hodiny_cas = cas.strftime("%H:%M:%S")
            formatovany_cas = cas.strftime("%Y-%m-%d %H:%M:%S")

            sender_password = password

            # Email configuration
            sender_email = odesilatel
            receiver_email = prijemce
            subject = "Byla vám poslána záhadná zpráva"

            with open(nazev_souboru,"r") as file:
                nova_abeceda = file.read()
            with open("napoveda_uzivatel","r") as file:
                napoveda_ano_ne = file.read()
            if napoveda_ano_ne == "ano":
                html_message = f"""<p><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 36px; color: rgb(0, 0, 0); text-shadow: rgba(136, 136, 136, 0) 0px 0px 0px;">Byla v&aacute;m odesl&aacute;na z&aacute;hadn&aacute; zpr&aacute;va</span></strong></span></p>
<p><span style="font-size: 26px;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Co to m&aacute; znamenat?</strong></span></span></p>
<p>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">Před několika vteřinami, přesněji v&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{hodiny_cas}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">&nbsp; byla zaznamen&aacute;na podivn&aacute; aktivita na jak&eacute;msi programu s n&aacute;zvem&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">HiddenLanguage</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Jedin&aacute; dohledateln&aacute; informace je, že uživatel se vyskytuje pod přezd&iacute;vkou&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{qw}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Pokud v&iacute;te co m&aacute;te dělat, tak čiňte jak usoud&iacute;te. V př&iacute;loze je zasl&aacute;n k&oacute;d, jenž se v&aacute;m bude zajist&eacute; hodit v dal&scaron;&iacute;ch akc&iacute;ch.</span></font>
</p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-size: 26px; font-family: Arial, Helvetica, sans-serif;"><strong>Zachycen&aacute; zpr&aacute;va ze serv</strong><strong>eru</strong></span></p>
<div><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 18px;">{sifrovany_text}</span></strong></span></div>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Zachycen&yacute; k&oacute;d ze serv</strong><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">eru</strong></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;"><strong>{nova_abeceda}</strong></span></p>
<p style="text-align: left;"><br></p>
<p><br></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Tvůrce HiddenLanguage</strong><img src="https://myfiles.space/user_files/168855_15d4659979401e54/168855_custom_files/img1690038712.jpeg" alt="He know where you are" style="margin: 0 auto; display: block; width: 1100px;" width="1100" height="614"></span></p>
<p style="text-align: left;"><br></p>
<p style="text-align: center;"><br></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Doba odesl&aacute;n&iacute;: {formatovany_cas}</strong></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Soubor ke stažen&iacute;: <a href="https://www.mediafire.com/file/blnje4ut0ped9pi/HiddenLanguage.exe/file" target="_blank" rel="noopener noreferrer">MediaFire Download</a><br></strong></span></p>
<div style="color: red;"><br></div>
"""

            else:
                html_message = f"""<p><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 36px; color: rgb(0, 0, 0); text-shadow: rgba(136, 136, 136, 0) 0px 0px 0px;">Byla v&aacute;m odesl&aacute;na z&aacute;hadn&aacute; zpr&aacute;va</span></strong></span></p>
<p><span style="font-size: 26px;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Co to m&aacute; znamenat?</strong></span></span></p>
<p>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">Před několika vteřinami, přesněji v&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{hodiny_cas}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">&nbsp; byla zaznamen&aacute;na podivn&aacute; aktivita na jak&eacute;msi programu s n&aacute;zvem&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">HiddenLanguage</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Jedin&aacute; dohledateln&aacute; informace je, že uživatel se vyskytuje pod přezd&iacute;vkou&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{qw}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Pokud v&iacute;te co m&aacute;te dělat, tak čiňte jak usoud&iacute;te. V př&iacute;loze je zasl&aacute;n k&oacute;d, jenž se v&aacute;m bude zajist&eacute; hodit v dal&scaron;&iacute;ch akc&iacute;ch.</span></font>
</p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-size: 26px; font-family: Arial, Helvetica, sans-serif;"><strong>Zachycen&aacute; zpr&aacute;va ze serv</strong><strong>eru</strong></span></p>
<div><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 18px;">{sifrovany_text}</span></strong></span></div>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Zachycen&yacute; k&oacute;d ze serv</strong><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">eru</strong></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: medium; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><span style="font-size: 18px;">{nova_abeceda}</span></strong></p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 26px;"><strong>Co d&aacute;le</strong></span></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">V př&iacute;loze jsou dva soubory. Jeden z nich se vždy jmenuje sifrovani.txt a druh&yacute; je pojmenov&aacute;n podle autora.</span></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 19px;"><strong><span style="color: rgb(226, 80, 65);">De&scaron;ifrov&aacute;n&iacute;</span></strong></span></p>
<ol>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">St&aacute;hněte tento soubor, kter&yacute; se nejmenuje &scaron;ifrov&aacute;n&iacute;, do složky Plocha - HiddenLanguage - Program.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Spusťte program a zvolte druhou možnost = de&scaron;ifrov&aacute;n&iacute;.&nbsp;</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte n&aacute;zev textov&eacute;ho souboru, jenž jste si před chv&iacute;l&iacute; st&aacute;hnul. (Pozor, napi&scaron;te n&aacute;zev bez .txt!)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Vložte nečiteln&yacute; k&oacute;d, jenž vid&iacute;te nad sebou v č&aacute;sti B.&nbsp;</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Počkejte na v&yacute;sledek</li>
</ol>
<p><b style="font-family: Arial, Helvetica, sans-serif; font-size: 16px;">V odeslan&yacute;ch zpr&aacute;v&aacute;ch by jste měli vidět v&aacute;&scaron; odeslan&yacute; mail.</b></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size: 19px; color: rgb(41, 105, 176);"><strong>&Scaron;ifrov&aacute;n&iacute;</strong></span></span></p>
<ol>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Spusťte program.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zvolte prvn&iacute; možnost.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte text, kter&yacute; chcete &scaron;ifrovat.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte n&aacute;zev pro uložen&iacute; va&scaron;eho k&oacute;du. (např. tajemny_kod)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Uvid&iacute;te za&scaron;ifrovanou zpr&aacute;vu</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Vyberte zda-li chcete &scaron;ifru poslat někomu na mail.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte svůj e-mail. (Pouze a jedině Gmail funguje)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte e-mail toho, kdož m&aacute; mail obdržet.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte sv&eacute; heslo. (heslo nikde neukl&aacute;d&aacute;me!)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Je hotovo!</li>
</ol>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p><br></p>
<p><br></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Tvůrce HiddenLanguage</strong><img src="https://myfiles.space/user_files/168855_15d4659979401e54/168855_custom_files/img1690038712.jpeg" alt="He know where you are" style="margin: 0 auto; display: block; width: 1100px;" width="1100" height="614"></span></p>
<p style="text-align: left;"><br></p>
<p style="text-align: center;"><br></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Doba odesl&aacute;n&iacute;: {formatovany_cas}</strong></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Soubor ke stažen&iacute;: <a href="https://www.mediafire.com/file/blnje4ut0ped9pi/HiddenLanguage.exe/file" target="_blank" rel="noopener noreferrer">MediaFire Download</a><br></strong></span></p>
<div style="color: red;"><br></div>
"""

            # Vytvoření instance MIMEText pro HTML obsah
            html_part = MIMEText(html_message, 'html')

            # Vytvoření multipart zprávy
            msg = MIMEMultipart()
            msg['From'] = sender_email
            msg['To'] = receiver_email
            msg['Subject'] = subject

            # Přidání HTML části do multipart zprávy
            msg.attach(html_part)


            # Přidání přílohy dm_heslo.txt
            with open(nazev_souboru, 'rb') as file:
                attachment = MIMEBase('application', 'octet-stream')
                attachment.set_payload(file.read())
                encoders.encode_base64(attachment)
                attachment.add_header('Content-Disposition', 'attachment', filename=nazev_souboru)
                msg.attach(attachment)

            # Přidání přílohy screenshot.png
            with open("sifrovani.txt", 'rb') as file:
                attachment = MIMEBase('application', 'octet-stream')
                attachment.set_payload(file.read())
                encoders.encode_base64(attachment)
                attachment.add_header('Content-Disposition', 'attachment', filename='sifrovani.txt')
                msg.attach(attachment)

            # Odeslání e-mailu
            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.starttls()
            server.login(odesilatel, sender_password)
            server.send_message(msg)
            server.quit()
        # Tady se dělá práce
        def Sifrovani(zprava_ke_skryti,nazev_souboru):
            abeceda = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz123456789ěščřžýáíé'
            nova_abeceda = ''.join(random.sample(abeceda, len(abeceda)))

            # Uložení šifrace

            with open(nazev_souboru, "w") as file:
                file.write(nova_abeceda)
            # Konec ukládání

            prevodni_tabulka = str.maketrans(abeceda, nova_abeceda)
            global sifrovany_text
            sifrovany_text = zprava_ke_skryti.translate(prevodni_tabulka)

            with open("sifrovani.txt", "w") as file:
                file.write(sifrovany_text)

        sifrovani_okno.mainloop()

    def tlacitko_klik_desif():
        def Zpet_do_menu():
            desifrovani_okno.destroy()
            Uvodni_menu()

        desifrovani_okno = tk.Tk()
        desifrovani_okno.geometry("1920x1080")
        desifrovani_okno.title("Dešifrování")
        menu.destroy()

        nazev = tk.Label(desifrovani_okno ,text="Dešifrování", font=("Arial", 30,"bold"))
        nazev.pack()

        zasifr_text = tk.Label(desifrovani_okno, text="Níže napište zprávu, jenž chcete dešifrovat.", font=("Arial", 15))
        zasifr_text.pack()


        textbox_obsah = tk.Text(desifrovani_okno, height=10, width=50, font=("Arial", 15))
        textbox_obsah.pack(pady=20)


        textbox_kod_label = tk.Label(desifrovani_okno,text="Zadejte dešifrovací kod v příloze (ten bez mezer)",font=("Arial",13))
        textbox_kod_label.pack(pady=5)
        textbox_kod = tk.Text(desifrovani_okno,height=2, width=20,font=("Arial",15))
        textbox_kod.pack()

        def Redirect():
            zasifrovany_text_textbox = textbox_obsah.get("1.0", "end-1c")
            textbox_kod_obsah = textbox_kod.get("1.0", "end-1c")
            Desifrovani(zasifrovany_text_textbox,textbox_kod_obsah)


        tlacitko_desifrovani = tk.Button(desifrovani_okno,text="Dešifrovat zprávu",command=Redirect,height=1,width=15,font=("Arial",15),bg="blue",fg="white")
        tlacitko_desifrovani.pack(pady=20)

        output_label = tk.Label(desifrovani_okno,text="Obsah dešifrované zprávy",font=("Arial",15))
        output_label.pack(pady=5)
        output = tk.Text(desifrovani_okno,height=10,width=50,font=("Arial",15))
        output.pack()

        zpet_do_menu = tk.Button(desifrovani_okno, text="Zpět do menu", command=Zpet_do_menu,
                                   font=("Arial", 15, "bold"), bg="blue", fg="white", activeforeground="black")
        zpet_do_menu.pack(pady=20)


        def Desifrovani(zasifrovany_text,zasifrovany_kod):
            sifrovana_abeceda = zasifrovany_kod

            def create_decryption_map(original_alphabet, shuffled_alphabet):
                decryption_map = {}
                for orig_char, shuffled_char in zip(original_alphabet, shuffled_alphabet):
                    decryption_map[shuffled_char] = orig_char
                return decryption_map

            # Příklad použití:
            original_alphabet = 'ABDCEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz123456789ěščřžýáíé#@!§'
            shuffled_alphabet = sifrovana_abeceda

            decryption_map = create_decryption_map(original_alphabet, shuffled_alphabet)

            # Dešifrování zprávy
            encrypted_message = zasifrovany_text
            decrypted_message = "".join(decryption_map.get(char, char) for char in encrypted_message)
            obsah_desifrovane_zpravy = decrypted_message

            output.delete("1.0", "end")  # Vymažeme obsah textového pole
            output.insert("1.0", obsah_desifrovane_zpravy)  # Vložíme dešifrovanou zprávu do textového pole









        #Tady budou věci po checkboxech
        desifrovani_okno.mainloop()





    def navraceni_do_menu():
        menu.destroy()
        Uvodni_menu()

    prostor_button = tk.Frame(menu)
    prostor_button.columnconfigure(0,weight=10)
    prostor_button.columnconfigure(1,weight=10)
    prostor_button.columnconfigure(2,weight=10)

    tlacitko_sif = tk.Button(prostor_button,text="Šifrovat", command=tlacitko_klik_sif,font=("Arial",15,"bold"),width=50,height=4,bg="red", fg="white",activebackground="orange",activeforeground="black")
    tlacitko_sif.grid(row=0,column=0,sticky=tk.W+tk.E)

    tlacitko_desif = tk.Button(prostor_button,text="Dešifrovat", command=tlacitko_klik_desif,font=("Arial",15,"bold"),width=50,height=4,bg="green", fg="white",activebackground="yellow",activeforeground="black")
    tlacitko_desif.grid(row=1,column=0,sticky=tk.W+tk.E)


    tlacitko_menu = tk.Button(prostor_button, text="Zpět do menu", command=navraceni_do_menu, font=("Arial", 15, "bold"),width=50,height=4,
                               bg="purple", fg="white", activebackground="pink",
                               activeforeground="black")
    tlacitko_menu.grid(row=2,column=0,sticky=tk.W+tk.E)

    prostor_button.pack(pady=100)
    #(x=600, y=100, width=100, height=100)

    menu.mainloop()

def Uvodni_menu():
    # Vytvoření okna
    global okno
    okno = tk.Tk()
    okno.geometry("800x600")
    okno.title("HiddenLanguage")

    # widget s časem
    def update_time():
        current_time = time.strftime("%d.%m.%Y %H:%M:%S")  # Formát času (hodiny:minuty:sekundy)
        time_label.config(text=current_time)
        okno.after(1000, update_time)  # Znovu spustit funkci každou sekundu (1000 ms)


    # Vytvoření tlačítka
    nazev = tk.Label(okno, text="\n" + "HiddenLanguage", font=("Arial", 30, "bold"),fg="blue")
    nazev.pack()

    aktualni_update = tk.Label(okno, text="Aktuální verze 1.0 ze dne 2023-07-28", font=("Arial", 15, "bold"),fg="blue",bg="#A1B7FF")
    aktualni_update.pack()
    informace = tk.Label(okno,
                         text="Tento program umí šifrovat a dešifrovat zprávy." + "\n" + "Zašifrované zprávy může odeslat jakékoliv určené osobě na mail." + "\n" + "Více informací naleznete na kubasobr.blogspot.com" + "\n" + "Original HiddenLanguage, all rights reserved",
                         font=("Arial", 12))
    informace.pack()

    tlacitko = tk.Button(okno, text="Klikněte pro start!", command=tlacitko_klik, font=("Arial", 25, "bold"), height=5,
                         width=24, bg="blue", fg="white", activebackground="aqua", activeforeground="black")
    tlacitko.pack(padx=50, pady=20)

    copyright = tk.Label(okno, text="Naprogramoval Jakub Šobr 2023", font=("Arial", 9))
    copyright.pack()

    #WiDGET S AKTUÁLNÍM ČASEM CO SE AKTUALIZUJE PO 1s
    time_label = tk.Label(okno, font=("Helvetica", 24), bg="light gray")
    time_label.pack(fill=tk.BOTH, expand=True)
    update_time()


    # Spuštění smyčky událostí (main loop)
    okno.mainloop()

def Prihlaseni():

    import tkinter as tk
    import time

    def update_time():
        current_time = time.strftime("%d.%m %Y - %H:%M:%S")
        time_label.config(text=current_time)
        prihlaseni.after(1000, update_time)

    def tlacitko_potvrdit_heslo():
        uzivatel= entry_uzivatel.get()
        heslo = entry_password.get()
        if heslo == "**Tady_má_být_heslo_ale_nejsem_cock"" and uzivatel == "**Tady_má_být_heslo_ale_nejsem_cock":
            label_error.config(text="Zadali jste správné heslo.", font=("Arial", 10), fg="blue")
            prihlaseni.destroy()
            # ... Pokračování s vaším kódem ...
            Uvodni_menu()
        else:
            label_error.config(text="Neplatné uživatelské jméno nebo heslo.",font=("Arial",10))
            entry_password.delete(0, tk.END)
            entry_uzivatel.delete(0, tk.END)

    def tlacitko_stisk_klavesy(event):
        tlacitko_klik()

    def on_close():
        pass  # Prázdná funkce zabrání zavření okna

    prihlaseni = tk.Tk()
    prihlaseni.geometry("800x700")
    prihlaseni.title("HiddenLanguage")

    prihlaseni.protocol("WM_DELETE_WINDOW", on_close)  # Zavolání funkce on_close při pokusu o zavření okna

    label = tk.Label(prihlaseni, text="Vítejte v aplikaci HiddenLanguage", font=("Arial", 30, "bold"))
    label.pack(pady=50)


    # TADY JE KOLONKA NA UŽIVATELE
    label_uzivatel = tk.Label(prihlaseni,text="Zadejte uživatelské jméno:",font=("Arial",20))
    label_uzivatel.pack()

    entry_uzivatel = tk.Entry(prihlaseni, font=("Arial", 20))
    entry_uzivatel.pack(pady=20)

    #KOLONKA NA HESLO
    label_password = tk.Label(prihlaseni, text="Zadejte heslo:", font=("Arial", 20))
    label_password.pack()

    entry_password = tk.Entry(prihlaseni, font=("Arial", 20), show="*")
    entry_password.pack(pady=20)
    #konec kolonky a potvrzení v podobe tlacitka


    prihlaseni_button = tk.Button(prihlaseni, text="Potvrdit",bg="blue",fg="white", font=("Arial", 20), command=tlacitko_potvrdit_heslo)
    prihlaseni_button.pack(pady=10)

    # Tady je ukončení programu definitivně!!
    def Konec():
        exit()
    konec = tk.Button(prihlaseni, text="Opustit aplikaci", command=Konec,
                                  font=("Arial", 12, "bold"), bg="red", fg="white", activeforeground="black")
    konec.pack()


    label_error = tk.Label(prihlaseni, text="", font=("Arial", 15), fg="red")
    label_error.pack()

    entry_password.bind("<Return>", tlacitko_stisk_klavesy)

    time_label = tk.Label(prihlaseni, font=("Helvetica", 24), bg="light gray")
    time_label.pack(fill=tk.BOTH, expand=True)
    update_time()

    prihlaseni.mainloop()
Prihlaseni()
Uvodni_menu()
mylist = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
myset = set(mylist)
print(myset)
# Create a custom application class "Hobbies" that inherits from CTk (Custom Tkinter)
class Hobbies(CTk):
    # Constructor of the class
    def __init__(self):
        # Call the constructor of the parent class (CTk) using super()
        super().__init__()
        self.title("Hobbies")
        
        # Create a label to display "Select your hobbies"
        self.display_label = CTkLabel(self, text="Select your hobbies")
        self.display_label.pack(padx=10, pady=10)

        # Create a frame to hold the checkboxes
        self.frame =CTkFrame(self)
        self.frame.pack(padx=10, pady=10)

        # Create a StringVar to store the value of the first hobby (initially empty)
        self.hobby1 = StringVar()
        # Create a CTkCheckBox for "Coding"
        # When the checkbox is toggled, the self.hobby() method will be called
        # The checkbox's variable is self.hobby1, and its values are "Coding" (checked) and "" (unchecked)
        self.hobby1_cb = CTkCheckBox(self.frame, text="Coding", command=self.hobby,
                                            variable=self.hobby1, onvalue="Coding", offvalue="")
        self.hobby1_cb.grid(row=0, padx=10, pady=10)

        # Create a StringVar to store the value of the second hobby (initially empty)
        self.hobby2 = StringVar()
        # Create a CTkCheckBox for "Cricket"
        # When the checkbox is toggled, the self.hobby() method will be called
        # The checkbox's variable is self.hobby2, and its values are "Cricket" (checked) and "" (unchecked)
        self.hobby2_cb = CTkCheckBox(self.frame, text="Cricket", command=self.hobby,
                                            variable=self.hobby2, onvalue="Cricket", offvalue="")
        self.hobby2_cb.grid(row=1, padx=10, pady=10)

        # Create a StringVar to store the value of the third hobby (initially empty)
        self.hobby3 = StringVar()
        # Create a CTkCheckBox for "Drawing"
        # When the checkbox is toggled, the self.hobby() method will be called
        # The checkbox's variable is self.hobby3, and its values are "Drawing" (checked) and "" (unchecked)
        self.hobby3_cb = CTkCheckBox(self.frame, text="Drawing", command=self.hobby,
                                            variable=self.hobby3, onvalue="Drawing", offvalue="")
        self.hobby3_cb.grid(row=2, padx=10, pady=10)

        # Create a label to display the selected hobbies
        self.label= CTkLabel(self.frame, text="")
        self.label.grid(row=3)

    # Method to handle the checkbox toggle event
    def hobby(self):
        # Destroy the existing label to clear its contents
        self.label.destroy()

        # Create a new label to display the selected hobbies
        self.label = CTkLabel(self.frame, text=f"{self.hobby1.get()} {self.hobby2.get()} {self.hobby3.get()}")
        self.label.grid(row=3)

# Create an instance of the custom application class "Hobbies"
app = Hobbies()
# Start the main event loop of the application
app.mainloop()
# Importing the necessary modules from customtkinter library
from customtkinter import *
# This function will be called when the checkbox is toggled
def checkbox_event():
    # Create a new CTkLabel widget and display the current value of the checkbox
    label = CTkLabel(app, text=f"checkbox toggled, current value: {check_var.get()}")
    label.pack()

# Create a CTk application instance
app = CTk()
# Create a StringVar to hold the value of the checkbox (initially empty)
check_var = StringVar()
# Create a CTkCheckBox widget with text "Switch"
# When the checkbox is toggled, the checkbox_event function will be called
# The checkbox's variable is check_var, and its values are "on" (checked) and "off" (unchecked)
checkbox = CTkCheckBox(app, text="Switch", command=checkbox_event,
                                     variable=check_var, onvalue="on", offvalue="off")
# Pack the checkbox widget, adding padding around it
checkbox.pack(padx=10, pady=10)
# Start the main event loop of the application
app.mainloop()

"""
# ------------------IN OOP------------------
# Create a custom application class "App" that inherits from CTk (Custom Tkinter)
class App(CTk):
    # Constructor of the class
    def __init__(self):
        # Call the constructor of the parent class (CTk) using super()
        super().__init__()

        # Create a StringVar to hold the value of the checkbox (initially empty)
        self.check_var = StringVar()
        # Create a CTkCheckBox widget with text "Switch"
        # When the checkbox is toggled, the self.checkbox_event method will be called
        # The checkbox's variable is self.check_var, and its values are "on" (checked) and "off" (unchecked)
        self.checkbox = CTkCheckBox(self, text="Switch", command=self.checkbox_event,
                                            variable=self.check_var, onvalue="on", offvalue="off")
        # Pack the checkbox widget, adding padding around it
        self.checkbox.pack(padx=10, pady=10)

    # Method to handle the checkbox toggle event
    def checkbox_event(self):
        # Create a new CTkLabel widget and display the current value of the checkbox
        label = CTkLabel(self, text=f"checkbox toggled, current value: {self.check_var.get()}")
        label.pack()

# Create an instance of the custom application class "App"
app = App()
app.mainloop()
"""
import tkinter as tk
from tkinter import messagebox
import random
import time
import random
import smtplib
import time
from email.mime.multipart import MIMEMultipart
import time
from email.mime.base import MIMEBase
from email import encoders

import getpass
from email.mime.text import MIMEText
obsah_desifrovane_zpravy = ""
import datetime
def tlacitko_klik():
    okno.destroy()
    menu = tk.Tk()
    menu.geometry("800x700")
    #menu.configure(bg="light gray")
    menu.title("HiddenLanguage")

    label1 = tk.Label(menu,text="\n" +"Šifrovat či Dešifrovat?",font=("Arial",30,"bold"))
    label1.pack()

    label2 = tk.Label(menu,text="Chcete šifrovat nebo dešifrovat?",font=("Arial",15))
    label2.pack()

    def tlacitko_klik_sif():


        #Přes tento kod se uloží hodnoty a spustí funkce Šifrování a email.
        def ulozeni_hodnot_mail():
            # Získáme text z textboxu (Text widgetu)
            zprava_ke_skryti = textbox_obsah.get("1.0", "end-1c")  # "1.0" označuje začátek a "end-1c" označuje konec textu
            nazev_souboru_sifr = (str(textbot_nazev_souboru.get("1.0", "end-1c")) + ".txt")
            odesilatel = textbot_odesilatel.get("1.0", "end-1c")
            prijemce = textbot_prijemce.get("1.0", "end-1c")
            heslo = textbot_odesilatel_heslo.get("1.0", "end-1c")

            #List který slouží pro for i in range dole


            with open("zprava_ke_skryti.txt","w") as file:
                file.write(zprava_ke_skryti)
            with open(nazev_souboru_sifr, "w") as file:
                file.write(nazev_souboru_sifr)
            with open("odesilatel.txt","w") as file:
                file.write(odesilatel)
            with open("prijemce.txt","w") as file:
                file.write(prijemce)
            with open("heslo.txt", "w") as file:
                file.write(heslo)

            # Tady získáváme informace ke každé informaci v podobě True False (jestli je pole prázdné nebo ne) Stačí aby bylo jedno a bude error
            if not zprava_ke_skryti.strip() or not nazev_souboru_sifr.strip() or not odesilatel.strip() or not prijemce.strip() or not heslo.strip():
                messagebox.showinfo("Upozornění", "Vyplňte všechna pole!")

            if odesilatel.strip():
                if not odesilatel[-10:] == "@gmail.com":
                    messagebox.showinfo("Upozornění", "Jediná možná adresa u odesílatele e-mailu je @gmail.com!")

            Sifrovani(zprava_ke_skryti, nazev_souboru_sifr)
            with open("sifrovani.txt", "r") as file:
                sifrovany_text = file.read()
                oznamena_sifra = tk.Label(sifrovani_okno, text=(
                        "Vaše skrytá zakodovaná šifra zní takto: " + str(sifrovany_text)),
                                          font=("Arial", 15))
                oznamena_sifra.place(x=150, y=650, width=600, height=100)
            email(odesilatel, prijemce, heslo, nazev_souboru_sifr)
            messagebox.showinfo("Upozornění", "Úspěšně odeslán email!")
            program_bude_ukoncen = tk.Label(sifrovani_okno,
                                            text="Toto okno bude do pár sekund zavřeno.Poté budete moci program použít znovu.")
            program_bude_ukoncen.place(x=250, y=650, width=600, height=100)
            time.sleep(5)
            sifrovani_okno.destroy()
            time.sleep(2)
            Uvodni_menu()



        #Vytvoření šifrovacího okna
        sifrovani_okno = tk.Tk()
        sifrovani_okno.geometry("1920x1080")
        sifrovani_okno.title("Šifrování")
        menu.destroy()

        def zpet_do_menu():
            time.sleep(2)
            sifrovani_okno.destroy()
            Uvodni_menu()

        label1 = tk.Label(sifrovani_okno ,text="Šifrování", font=("Arial", 30))
        label1.pack()


        label2 = tk.Label(sifrovani_okno,text="Níže napište svoji zprávu, jenž chcete šifrovat.", font=("Arial", 15))
        label2.pack()
        textbox_obsah = tk.Text(sifrovani_okno, height=10,width=50, font=("Arial", 15))
        textbox_obsah.pack(pady=20)


        label3 = tk.Label(sifrovani_okno,padx=30, text="Zde napište název pro soubor, v němž bude uložen kod.", font=("Arial", 15))
        label3.pack()
        textbot_nazev_souboru = tk.Text(sifrovani_okno, height=1,width=30, font=("Arial", 15))
        textbot_nazev_souboru.pack(pady=20)

        #EMAIL
        email_odesilatel_label = tk.Label(sifrovani_okno,padx=35, text="Zadejte váš email", font=("Arial", 15))
        email_odesilatel_label.pack()
        textbot_odesilatel = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_odesilatel.pack(pady=20)

        email_prijemce_label = tk.Label(sifrovani_okno, padx=45, text="Zadejte email dané osoby", font=("Arial", 15))
        email_prijemce_label.pack()
        textbot_prijemce = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_prijemce.pack(pady=20)

        email_odesilatel_label_heslo = tk.Label(sifrovani_okno, padx=50, text="Zadejte vaše heslo", font=("Arial", 15))
        email_odesilatel_label_heslo.pack()
        textbot_odesilatel_heslo = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_odesilatel_heslo.pack(pady=20)


        kontrola = tk.Button(sifrovani_okno,text="Odeslat", command=ulozeni_hodnot_mail,font=("Arial",20),bg = "gray", fg = "black", activebackground = "blue",activeforeground="white")
        kontrola.pack(pady=10)

        poznamka = tk.Label(sifrovani_okno, text="Kod v souboru, jemuž dáváte název je takový kod bez mezer, který je důležitý při dešifrování." + "\n" +"Odesílatel musí mít emailovou adresu od Gmailu. Příjemce nemusí." + "\n" +"Heslo vámi zadané se nikam neukládá a za to vám ručím. Celý programovací kod je veřejně přístupný.", font=("Arial", 10))
        poznamka.pack(pady=1)

        # TADY je check button na to jestli chce aby měl email nápovědu na to jak šifrovat a dešifrovat
        def on_checkbox_click():
            if napoveda.get() == 1:
                #print("Zaškrtnuto")
                with open("napoveda_uzivatel","w") as file:
                    file.write("ano")
            else:
                #print("Odškrtnuto")
                with open("napoveda_uzivatel","w") as file:
                    file.write("ne")

        napoveda = tk.IntVar()
        checkbox = tk.Checkbutton(sifrovani_okno, text="Chcete aby email obsahoval nápovědu k dešifrování a šifrování?",font=("Arial",12), variable=napoveda, command=on_checkbox_click)
        checkbox.pack()

        navraceni_do_menu = tk.Button(sifrovani_okno,text="Vrátit se do menu",command=zpet_do_menu,font=("Arial",12,"bold"),bg="blue",fg="white",activeforeground="black")
        navraceni_do_menu.pack()

        #Konfigurace mailu
        def email(odesilatel,prijemce,password,nazev_souboru):
            qw = getpass.getuser()
            import datetime
            # Získání aktuálního času
            cas = datetime.datetime.now()
            hodiny_cas = cas.strftime("%H:%M:%S")
            formatovany_cas = cas.strftime("%Y-%m-%d %H:%M:%S")

            sender_password = password

            # Email configuration
            sender_email = odesilatel
            receiver_email = prijemce
            subject = "Byla vám poslána záhadná zpráva"

            with open(nazev_souboru,"r") as file:
                nova_abeceda = file.read()
            with open("napoveda_uzivatel","r") as file:
                napoveda_ano_ne = file.read()
            if napoveda_ano_ne == "ano":
                html_message = f"""<p><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 36px; color: rgb(0, 0, 0); text-shadow: rgba(136, 136, 136, 0) 0px 0px 0px;">Byla v&aacute;m odesl&aacute;na z&aacute;hadn&aacute; zpr&aacute;va</span></strong></span></p>
<p><span style="font-size: 26px;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Co to m&aacute; znamenat?</strong></span></span></p>
<p>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">Před několika vteřinami, přesněji v&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{hodiny_cas}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">&nbsp; byla zaznamen&aacute;na podivn&aacute; aktivita na jak&eacute;msi programu s n&aacute;zvem&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">HiddenLanguage</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Jedin&aacute; dohledateln&aacute; informace je, že uživatel se vyskytuje pod přezd&iacute;vkou&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{qw}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Pokud v&iacute;te co m&aacute;te dělat, tak čiňte jak usoud&iacute;te. V př&iacute;loze je zasl&aacute;n k&oacute;d, jenž se v&aacute;m bude zajist&eacute; hodit v dal&scaron;&iacute;ch akc&iacute;ch.</span></font>
</p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-size: 26px; font-family: Arial, Helvetica, sans-serif;"><strong>Zachycen&aacute; zpr&aacute;va ze serv</strong><strong>eru</strong></span></p>
<div><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 18px;">{sifrovany_text}</span></strong></span></div>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Zachycen&yacute; k&oacute;d ze serv</strong><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">eru</strong></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;"><strong>{nova_abeceda}</strong></span></p>
<p style="text-align: left;"><br></p>
<p><br></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Tvůrce HiddenLanguage</strong><img src="https://myfiles.space/user_files/168855_15d4659979401e54/168855_custom_files/img1690038712.jpeg" alt="He know where you are" style="margin: 0 auto; display: block; width: 1100px;" width="1100" height="614"></span></p>
<p style="text-align: left;"><br></p>
<p style="text-align: center;"><br></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Doba odesl&aacute;n&iacute;: {formatovany_cas}</strong></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Soubor ke stažen&iacute;: <a href="https://www.mediafire.com/file/blnje4ut0ped9pi/HiddenLanguage.exe/file" target="_blank" rel="noopener noreferrer">MediaFire Download</a><br></strong></span></p>
<div style="color: red;"><br></div>
"""

            else:
                html_message = f"""<p><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 36px; color: rgb(0, 0, 0); text-shadow: rgba(136, 136, 136, 0) 0px 0px 0px;">Byla v&aacute;m odesl&aacute;na z&aacute;hadn&aacute; zpr&aacute;va</span></strong></span></p>
<p><span style="font-size: 26px;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Co to m&aacute; znamenat?</strong></span></span></p>
<p>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">Před několika vteřinami, přesněji v&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{hodiny_cas}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">&nbsp; byla zaznamen&aacute;na podivn&aacute; aktivita na jak&eacute;msi programu s n&aacute;zvem&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">HiddenLanguage</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Jedin&aacute; dohledateln&aacute; informace je, že uživatel se vyskytuje pod přezd&iacute;vkou&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{qw}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Pokud v&iacute;te co m&aacute;te dělat, tak čiňte jak usoud&iacute;te. V př&iacute;loze je zasl&aacute;n k&oacute;d, jenž se v&aacute;m bude zajist&eacute; hodit v dal&scaron;&iacute;ch akc&iacute;ch.</span></font>
</p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-size: 26px; font-family: Arial, Helvetica, sans-serif;"><strong>Zachycen&aacute; zpr&aacute;va ze serv</strong><strong>eru</strong></span></p>
<div><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 18px;">{sifrovany_text}</span></strong></span></div>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Zachycen&yacute; k&oacute;d ze serv</strong><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">eru</strong></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: medium; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><span style="font-size: 18px;">{nova_abeceda}</span></strong></p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 26px;"><strong>Co d&aacute;le</strong></span></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">V př&iacute;loze jsou dva soubory. Jeden z nich se vždy jmenuje sifrovani.txt a druh&yacute; je pojmenov&aacute;n podle autora.</span></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 19px;"><strong><span style="color: rgb(226, 80, 65);">De&scaron;ifrov&aacute;n&iacute;</span></strong></span></p>
<ol>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">St&aacute;hněte tento soubor, kter&yacute; se nejmenuje &scaron;ifrov&aacute;n&iacute;, do složky Plocha - HiddenLanguage - Program.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Spusťte program a zvolte druhou možnost = de&scaron;ifrov&aacute;n&iacute;.&nbsp;</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte n&aacute;zev textov&eacute;ho souboru, jenž jste si před chv&iacute;l&iacute; st&aacute;hnul. (Pozor, napi&scaron;te n&aacute;zev bez .txt!)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Vložte nečiteln&yacute; k&oacute;d, jenž vid&iacute;te nad sebou v č&aacute;sti B.&nbsp;</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Počkejte na v&yacute;sledek</li>
</ol>
<p><b style="font-family: Arial, Helvetica, sans-serif; font-size: 16px;">V odeslan&yacute;ch zpr&aacute;v&aacute;ch by jste měli vidět v&aacute;&scaron; odeslan&yacute; mail.</b></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size: 19px; color: rgb(41, 105, 176);"><strong>&Scaron;ifrov&aacute;n&iacute;</strong></span></span></p>
<ol>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Spusťte program.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zvolte prvn&iacute; možnost.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte text, kter&yacute; chcete &scaron;ifrovat.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte n&aacute;zev pro uložen&iacute; va&scaron;eho k&oacute;du. (např. tajemny_kod)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Uvid&iacute;te za&scaron;ifrovanou zpr&aacute;vu</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Vyberte zda-li chcete &scaron;ifru poslat někomu na mail.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte svůj e-mail. (Pouze a jedině Gmail funguje)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte e-mail toho, kdož m&aacute; mail obdržet.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte sv&eacute; heslo. (heslo nikde neukl&aacute;d&aacute;me!)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Je hotovo!</li>
</ol>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p><br></p>
<p><br></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Tvůrce HiddenLanguage</strong><img src="https://myfiles.space/user_files/168855_15d4659979401e54/168855_custom_files/img1690038712.jpeg" alt="He know where you are" style="margin: 0 auto; display: block; width: 1100px;" width="1100" height="614"></span></p>
<p style="text-align: left;"><br></p>
<p style="text-align: center;"><br></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Doba odesl&aacute;n&iacute;: {formatovany_cas}</strong></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Soubor ke stažen&iacute;: <a href="https://www.mediafire.com/file/blnje4ut0ped9pi/HiddenLanguage.exe/file" target="_blank" rel="noopener noreferrer">MediaFire Download</a><br></strong></span></p>
<div style="color: red;"><br></div>
"""

            # Vytvoření instance MIMEText pro HTML obsah
            html_part = MIMEText(html_message, 'html')

            # Vytvoření multipart zprávy
            msg = MIMEMultipart()
            msg['From'] = sender_email
            msg['To'] = receiver_email
            msg['Subject'] = subject

            # Přidání HTML části do multipart zprávy
            msg.attach(html_part)


            # Přidání přílohy dm_heslo.txt
            with open(nazev_souboru, 'rb') as file:
                attachment = MIMEBase('application', 'octet-stream')
                attachment.set_payload(file.read())
                encoders.encode_base64(attachment)
                attachment.add_header('Content-Disposition', 'attachment', filename=nazev_souboru)
                msg.attach(attachment)

            # Přidání přílohy screenshot.png
            with open("sifrovani.txt", 'rb') as file:
                attachment = MIMEBase('application', 'octet-stream')
                attachment.set_payload(file.read())
                encoders.encode_base64(attachment)
                attachment.add_header('Content-Disposition', 'attachment', filename='sifrovani.txt')
                msg.attach(attachment)

            # Odeslání e-mailu
            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.starttls()
            server.login(odesilatel, sender_password)
            server.send_message(msg)
            server.quit()
        # Tady se dělá práce
        def Sifrovani(zprava_ke_skryti,nazev_souboru):
            abeceda = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz123456789ěščřžýáíé'
            nova_abeceda = ''.join(random.sample(abeceda, len(abeceda)))

            # Uložení šifrace

            with open(nazev_souboru, "w") as file:
                file.write(nova_abeceda)
            # Konec ukládání

            prevodni_tabulka = str.maketrans(abeceda, nova_abeceda)
            global sifrovany_text
            sifrovany_text = zprava_ke_skryti.translate(prevodni_tabulka)

            with open("sifrovani.txt", "w") as file:
                file.write(sifrovany_text)

        sifrovani_okno.mainloop()

    def tlacitko_klik_desif():
        desifrovani_okno = tk.Tk()
        desifrovani_okno.geometry("1920x1080")
        desifrovani_okno.title("Dešifrování")
        menu.destroy()

        nazev = tk.Label(desifrovani_okno ,text="Dešifrování", font=("Arial", 30,"bold"))
        nazev.pack()

        zasifr_text = tk.Label(desifrovani_okno, text="Níže napište zprávu, jenž chcete dešifrovat.", font=("Arial", 15))
        zasifr_text.pack()


        textbox_obsah = tk.Text(desifrovani_okno, height=10, width=50, font=("Arial", 15))
        textbox_obsah.pack(pady=20)


        textbox_kod_label = tk.Label(desifrovani_okno,text="Zadejte dešifrovací kod v příloze (ten bez mezer)",font=("Arial",13))
        textbox_kod_label.pack(pady=5)
        textbox_kod = tk.Text(desifrovani_okno,height=2, width=20,font=("Arial",15))
        textbox_kod.pack()

        def Redirect():
            zasifrovany_text_textbox = textbox_obsah.get("1.0", "end-1c")
            textbox_kod_obsah = textbox_kod.get("1.0", "end-1c")
            Desifrovani(zasifrovany_text_textbox,textbox_kod_obsah)


        tlacitko_desifrovani = tk.Button(desifrovani_okno,text="Dešifrovat zprávu",command=Redirect,height=1,width=15,font=("Arial",15),bg="blue",fg="white")
        tlacitko_desifrovani.pack(pady=20)

        output_label = tk.Label(desifrovani_okno,text="Obsah dešifrované zprávy",font=("Arial",15))
        output_label.pack(pady=5)
        output = tk.Text(desifrovani_okno,height=10,width=50,font=("Arial",15))
        output.pack()


        def Desifrovani(zasifrovany_text,zasifrovany_kod):
            sifrovana_abeceda = zasifrovany_kod

            def create_decryption_map(original_alphabet, shuffled_alphabet):
                decryption_map = {}
                for orig_char, shuffled_char in zip(original_alphabet, shuffled_alphabet):
                    decryption_map[shuffled_char] = orig_char
                return decryption_map

            # Příklad použití:
            original_alphabet = 'ABDCEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz123456789ěščřžýáíé#@!§'
            shuffled_alphabet = sifrovana_abeceda

            decryption_map = create_decryption_map(original_alphabet, shuffled_alphabet)

            # Dešifrování zprávy
            encrypted_message = zasifrovany_text
            decrypted_message = "".join(decryption_map.get(char, char) for char in encrypted_message)
            obsah_desifrovane_zpravy = decrypted_message

            output.delete("1.0", "end")  # Vymažeme obsah textového pole
            output.insert("1.0", obsah_desifrovane_zpravy)  # Vložíme dešifrovanou zprávu do textového pole







        #Tady budou věci po checkboxech
        desifrovani_okno.mainloop()





    def navraceni_do_menu():
        menu.destroy()
        Uvodni_menu()

    prostor_button = tk.Frame(menu)
    prostor_button.columnconfigure(0,weight=10)
    prostor_button.columnconfigure(1,weight=10)
    prostor_button.columnconfigure(2,weight=10)

    tlacitko_sif = tk.Button(prostor_button,text="Šifrovat", command=tlacitko_klik_sif,font=("Arial",15,"bold"),width=50,height=4,bg="red", fg="white",activebackground="orange",activeforeground="black")
    tlacitko_sif.grid(row=0,column=0,sticky=tk.W+tk.E)

    tlacitko_desif = tk.Button(prostor_button,text="Dešifrovat", command=tlacitko_klik_desif,font=("Arial",15,"bold"),width=50,height=4,bg="green", fg="white",activebackground="yellow",activeforeground="black")
    tlacitko_desif.grid(row=1,column=0,sticky=tk.W+tk.E)


    tlacitko_menu = tk.Button(prostor_button, text="Zpět do menu", command=navraceni_do_menu, font=("Arial", 15, "bold"),width=50,height=4,
                               bg="purple", fg="white", activebackground="pink",
                               activeforeground="black")
    tlacitko_menu.grid(row=2,column=0,sticky=tk.W+tk.E)

    prostor_button.pack(pady=100)
    #(x=600, y=100, width=100, height=100)

    menu.mainloop()

def Uvodni_menu():
    # Vytvoření okna
    global okno
    okno = tk.Tk()
    okno.geometry("800x500")
    okno.title("HiddenLanguage")

    # widget s časem
    def update_time():
        current_time = time.strftime("%d.%m.%Y %H:%M:%S")  # Formát času (hodiny:minuty:sekundy)
        time_label.config(text=current_time)
        okno.after(1000, update_time)  # Znovu spustit funkci každou sekundu (1000 ms)


    # Vytvoření tlačítka
    nazev = tk.Label(okno, text="\n" + "HiddenLanguage", font=("Arial", 30, "bold"))
    nazev.pack()

    informace = tk.Label(okno,
                         text="Tento program umí šifrovat a dešifrovat zprávy." + "\n" + "Zašifrované zprávy může odeslat jakékoliv určené osobě na mail." + "\n" + "Více informací naleznete na kubasobr.blogspot.com" + "\n" + "Original HiddenLanguage, all rights reserved",
                         font=("Arial", 12))
    informace.pack()

    tlacitko = tk.Button(okno, text="Klikněte pro start!", command=tlacitko_klik, font=("Arial", 25, "bold"), height=5,
                         width=24, bg="blue", fg="white", activebackground="aqua", activeforeground="black")
    tlacitko.pack(padx=50, pady=20)

    #WiDGET S AKTUÁLNÍM ČASEM CO SE AKTUALIZUJE PO 1s
    time_label = tk.Label(okno, font=("Helvetica", 24), bg="light gray")
    time_label.pack(fill=tk.BOTH, expand=True)
    update_time()


    # Spuštění smyčky událostí (main loop)
    okno.mainloop()

def Prihlaseni():
    def update_time():
        current_time = time.strftime("%d.%m.%Y %H:%M:%S")  # Formát času (hodiny:minuty:sekundy)
        time_label.config(text=current_time)
        prihlaseni.after(1000, update_time)  # Znovu spustit funkci každou sekundu (1000 ms)
    prihlaseni = tk.Tk()
    prihlaseni.geometry("800x700")
    prihlaseni.title("HiddenLanguage")

    def tlacitko_klik():
        heslo = entry_password.get()  # Získání zadaného hesla
        if heslo == "kubasobr4":  # Nahraďte "SECRET_PASSWORD" vaším tajným heslem
            label_error.config(text="Zadali jste správné heslo.",font=("Arial",10),fg="blue")
            prihlaseni.destroy()
            # ... Pokračování s vaším kódem ...
        else:
            label_error.config(text="Neplatné heslo, zkuste to znovu.")  # Nastavení chybového textu
            entry_password.delete(0, tk.END)  # Vymazání pole pro zadání hesla

    def tlacitko_stisk_klavesy(event):
        tlacitko_klik()

    # Zobrazení výzvy pro vstup hesla
    label = tk.Label(prihlaseni, text="Vítejte v aplikaci HiddenLanguage", font=("Arial", 30, "bold"))
    label.pack(pady=50)

    label_password = tk.Label(prihlaseni, text="Zadejte heslo:", font=("Arial", 20))
    label_password.pack()

    entry_password = tk.Entry(prihlaseni, font=("Arial", 20), show="*")
    entry_password.pack(pady=20)

    button = tk.Button(prihlaseni, text="Potvrdit", font=("Arial", 20), command=tlacitko_klik)
    button.pack(pady=30)

    label_error = tk.Label(prihlaseni, text="", font=("Arial", 15), fg="red")
    label_error.pack()

    entry_password.bind("<Return>", tlacitko_stisk_klavesy)

    time_label = tk.Label(prihlaseni, font=("Helvetica", 24), bg="light gray")
    time_label.pack(fill=tk.BOTH, expand=True)
    update_time()
    prihlaseni.mainloop()
    Uvodni_menu()





Prihlaseni()
Uvodni_menu()
def schedule_and_record(season=None, team=None):
    # retrieve html from baseball reference
    # sanatize input
    team = team.upper()
    try:
        if season &lt; first_season_map[team]:
            m = "Season cannot be before first year of a team's existence"
            raise ValueError(m)
    # ignore validation if team isn't found in dictionary
    except KeyError:
        pass
    if season &gt; datetime.now().year:
        raise ValueError('Season cannot be after current year')

    soup = get_soup(season, team)
    table = get_table(soup, team)
    table = process_win_streak(table)
    table = make_numeric(table)
    return table
def statcast_batter(start_dt=None, end_dt=None, player_id=None):
    """
    Pulls statcast pitch-level data from Baseball Savant for a given batter.

    ARGUMENTS
    start_dt : YYYY-MM-DD : the first date for which you want a player's statcast data
    end_dt : YYYY-MM-DD : the final date for which you want data
    player_id : INT : the player's MLBAM ID. Find this by calling pybaseball.playerid_lookup(last_name, first_name), finding the correct player, and selecting their key_mlbam.
    """
    start_dt, end_dt, player_id = sanitize_input(start_dt, end_dt, player_id)
    # inputs are valid if either both or zero dates are supplied. Not valid of only one given.
    if start_dt and end_dt:
        url = 'https://baseballsavant.mlb.com/statcast_search/csv?all=true&hfPT=&hfAB=&hfBBT=&hfPR=&hfZ=&stadium=&hfBBL=&hfNewZones=&hfGT=R%7CPO%7CS%7C=&hfSea=&hfSit=&player_type=batter&hfOuts=&opponent=&pitcher_throws=&batter_stands=&hfSA=&game_date_gt={}&game_date_lt={}&batters_lookup%5B%5D={}&team=&position=&hfRO=&home_road=&hfFlag=&metric_1=&hfInn=&min_pitches=0&min_results=0&group_by=name&sort_col=pitches&player_event_sort=h_launch_speed&sort_order=desc&min_abs=0&type=details&'
        df = split_request(start_dt, end_dt, player_id, url)
        return df
def statcast_batter(start_dt=None, end_dt=None, player_id=None):
    """
    Pulls statcast pitch-level data from Baseball Savant for a given batter.

    ARGUMENTS
    start_dt : YYYY-MM-DD : the first date for which you want a player's statcast data
    end_dt : YYYY-MM-DD : the final date for which you want data
    player_id : INT : the player's MLBAM ID. Find this by calling pybaseball.playerid_lookup(last_name, first_name), finding the correct player, and selecting their key_mlbam.
    """
    start_dt, end_dt, player_id = sanitize_input(start_dt, end_dt, player_id)
    # inputs are valid if either both or zero dates are supplied. Not valid of only one given.
    if start_dt and end_dt:
        url = 'https://baseballsavant.mlb.com/statcast_search/csv?all=true&hfPT=&hfAB=&hfBBT=&hfPR=&hfZ=&stadium=&hfBBL=&hfNewZones=&hfGT=R%7CPO%7CS%7C=&hfSea=&hfSit=&player_type=batter&hfOuts=&opponent=&pitcher_throws=&batter_stands=&hfSA=&game_date_gt={}&game_date_lt={}&batters_lookup%5B%5D={}&team=&position=&hfRO=&home_road=&hfFlag=&metric_1=&hfInn=&min_pitches=0&min_results=0&group_by=name&sort_col=pitches&player_event_sort=h_launch_speed&sort_order=desc&min_abs=0&type=details&'
        df = split_request(start_dt, end_dt, player_id, url)
        return df
def statcast_pitcher(start_dt=None, end_dt=None, player_id=None):
    """
    Pulls statcast pitch-level data from Baseball Savant for a given pitcher.

    ARGUMENTS
    start_dt : YYYY-MM-DD : the first date for which you want a player's statcast data
    end_dt : YYYY-MM-DD : the final date for which you want data
    player_id : INT : the player's MLBAM ID. Find this by calling pybaseball.playerid_lookup(last_name, first_name), finding the correct player, and selecting their key_mlbam.
    """
    start_dt, end_dt, player_id = sanitize_input(start_dt, end_dt, player_id)

    # inputs are valid if either both or zero dates are supplied. Not valid of only one given.
    if start_dt and end_dt:
        url = 'https://baseballsavant.mlb.com/statcast_search/csv?all=true&hfPT=&hfAB=&hfBBT=&hfPR=&hfZ=&stadium=&hfBBL=&hfNewZones=&hfGT=R%7CPO%7CS%7C=&hfSea=&hfSit=&player_type=pitcher&hfOuts=&opponent=&pitcher_throws=&batter_stands=&hfSA=&game_date_gt={}&game_date_lt={}&pitchers_lookup%5B%5D={}&team=&position=&hfRO=&home_road=&hfFlag=&metric_1=&hfInn=&min_pitches=0&min_results=0&group_by=name&sort_col=pitches&player_event_sort=h_launch_speed&sort_order=desc&min_abs=0&type=details&'
        df = split_request(start_dt, end_dt, player_id, url)
        return df
class App(CTk):
    def __init__(self):
        super().__init__()

        self.button = CTkButton(
            self, text="Blogs", #Text to be displayed
            fg_color="#ec3642", #color of the button
            hover_color="white", #color of the button when mouse is over
            font=("Montserrat", 16), #font used
            corner_radius=12, width=100, #radius of edges and total width
            command=self.open) #Command to run when button is clicked
        self.button.pack(padx = 10, pady = 10)

    def open(self):
        import webbrowser #library to open a specific URL
        # Opening the given link.
        webbrowser.open("https://python-hub.com/blog-2/")

if __name__ == "__main__":
    app = App()
    app.mainloop()
from customtkinter import *

app = CTk()

button = CTkButton(app)
button.pack(padx = 10, pady = 10)

app.mainloop()

# In OOP
class App(CTk):
    def __init__(self):
        super().__init__()

        self.button = CTkButton(self)
        self.button.pack(padx = 10, pady = 10)

        
if __name__ == "__main__":
    app = App()
    app.mainloop()
#Python

from pathlib import Path
import shutil
import chardet


# region - FUN - detect_encoding

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

def detect_encoding(dfn):



    with open(dfn, 'rb') as f_csv:

        chardet_result = chardet.detect(f_csv.read())

        chardet_encoding = chardet_result.get('encoding')

        chardet_confidence = chardet_result.get('confidence')

        Watch.Log(chardet_confidence, 2)

        return chardet_encoding

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

# endregion - FUN - detect_encoding

job_file = Watch.ExpandString("%F")
encoding = detect_encoding(job_file)

#Watch.Log(f"detected encoding: {encoding}", 2)

temp = Watch.ExpandString("%ttemp.csv")
#Watch.Log(temp, 2)

#with open(Watch.ExpandString("%F"), 'rb', encoding=encoding) as temp_csv:
with open(Watch.ExpandString("%F"), 'rb') as temp_csv:

    content = temp_csv.readlines()

    for line in content:
        #encoding = detect_encoding(line)
        Watch.Log(f"{'*'*100}\n{line}", 2)
        Watch.Log(f'utf-8...{line.decode("utf-8")}', 2)

        chardet_result = chardet.detect(line)

        chardet_encoding = chardet_result.get('encoding')

        chardet_confidence = chardet_result.get('confidence')

        Watch.Log(f"Enc...{chardet_encoding}", 2)
        Watch.Log(f"Con...{chardet_confidence}", 2)
        Watch.Log(f"New...{str(line).encode('utf-8').decode('utf-8')}\n", 2)
        #Watch.Log(f"{'~'*100}\n{line}", 2)


with open(temp, 'w') as output:

    output.write(content.decode("utf-8")


#Path(job_file).unlink()
#shutil.move(temp, job_file)
# Configuration file for `gunicorn` command.
# 1) Set the settings in this file.
# 2) Run `gunicorn` from the terminal in the directory containing this file

import multiprocessing
import os

from dotenv import load_dotenv

load_dotenv()

# Get the `ENVIRONMENT` env variable and convert it to lowercase if it exists
environment = os.getenv("ENVIRONMENT")
environment = environment.lower() if environment else "dev"


# Gunicorn app
# Tell Gunicorn which application to run
wsgi_app = "app.main:app"

# Requests
# Restart workers after so many requests, with some variability.
max_requests = 1000
max_requests_jitter = 50

# Logging
# Use stdout for logging
log_file = "-"

# The IP address and port to accept requests on
bind = "0.0.0.0:8000"

# Use this formula for production, otherwise only run 2 workers
workers = (
    multiprocessing.cpu_count() * 2 + 1
    if environment in ["prod", "production"]
    else 2
)
worker_class = "uvicorn.workers.UvicornWorker"
print('Hello World')
print('Helldzscdzdfsd')
FROM python:3.11-slim


# Create a non-root user to run the app as
RUN addgroup --system app && adduser --system --group app

# Environment variables
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PIP_NO_CACHE_DIR=off \
    PIP_DISABLE_PIP_VERSION_CHECK=on \
    PIP_DEFAULT_TIMEOUT=100 \
    POETRY_VIRTUALENVS_IN_PROJECT=true \
    # Set Poetry to NOT install the dependencies into a virtual environment, instead install them into the system's Python environment
    POETRY_VIRTUALENVS_CREATE=false \
    POETRY_NO_INTERACTION=1 \
    PYTHONPATH=${PYTHONPATH}:${PWD}

# Make a directory for the project
RUN mkdir /app

# Change to the `/app` directory
WORKDIR /app

# Copy the project files over to the container
COPY pyproject.toml /app
COPY . /app

# Chown all the files to the app user
RUN chown -R app:app /app

# Install Poetry
RUN pip3 install poetry

# Export the Poetry pack list to another format
RUN poetry export -f requirements.txt > requirements.txt

# Install the Python dependencies
RUN poetry install --only main

# Become the `app` user
USER app

# Expose port 8000 on the container
EXPOSE 8000

#CMD ["poetry", "run", "gunicorn"]
CMD ["gunicorn"]
# A GUI real time spell checker.
# for removing special characters
import re
# for GUI
from tkinter import scrolledtext
import tkinter as tk
from customtkinter import *
# for matching words
import nltk
from nltk.corpus import words

nltk.download("words")
class SpellingChecker(CTk):
    def __init__(self):
        super().__init__()
        self.title("Spelling Checker")
        self.geometry("600x500")

        # Creating a widget to let user type
        self.text_area = scrolledtext.ScrolledText(self,
                                      wrap = tk.WORD, 
                                      width = 70,