File: projects/birthDateToCurrentAge.py

from datetime import date                       # importing the date and time library


def ageCalculator(years, months, days):         # creating a function for age calculation
    age_day = 0                                 # initiating calculated age to 0
    age_months = 0
    age_year = 0

    today_day = int(today.strftime("%d"))       # assigning  current date to individual variable for calculation
    today_month = int(today.strftime("%m"))
    today_year = int(today.strftime("%y"))

    if today_day < day:                         # calculation for no of days
        today_day += 31
        age_day = today_day - days
    else:
        age_day = today_day - days

    if today_month < months:                    # calculation for no of months
        today_month += 12
        age_months = today_month - months
    else:
        age_months = today_month - months

    age_year = today_year - years               # no if years

    print(f"your age of today is :{today_year}-{today_month}-{today_day}")


today = date.today()                                                    # today's date
print("today's date is:", today)
birthDate = input('Enter your birth date in YYYY-MM-DD format:')        # taking input of date from user
year, month, day = map(int, birthDate.split('-'))
if month > 12 or day > 31 or year < int(today.strftime("%y")):          # invalid date checking
    print('invalid date')
    exit()
print("your date of birth is:", birthDate)
ageCalculator(year, month, day)                                         # calling function



File: projects/Merge_csv_files/merge_csv_files.py

import glob
import pandas as pd

extension = 'csv'
all_filenames = [i for i in glob.glob('*.{}'.format(extension))]

combined_csv = pd.concat([pd.read_csv(f) for f in all_filenames ])
combined_csv.to_csv( "combined_csv.csv", index=False, encoding='utf-8-sig')



File: projects/Calculate_age/calculate.py

# -*- coding: utf-8 -*-
import time
from calendar import isleap

# judge the leap year
def judge_leap_year(year):
    if isleap(year):
        return True
    else:
        return False


# returns the number of days in each month
def month_days(month, leap_year):
    if month in [1, 3, 5, 7, 8, 10, 12]:
        return 31
    elif month in [4, 6, 9, 11]:
        return 30
    elif month == 2 and leap_year:
        return 29
    elif month == 2 and (not leap_year):
        return 28


name = input("input your name: ")
age = input("input your age: ")
localtime = time.localtime(time.time())

year = int(age)
month = year * 12 + localtime.tm_mon
day = 0

begin_year = int(localtime.tm_year) - year
end_year = begin_year + year

# calculate the days
for y in range(begin_year, end_year):
    if (judge_leap_year(y)):
        day = day + 366
    else:
        day = day + 365

leap_year = judge_leap_year(localtime.tm_year)
for m in range(1, localtime.tm_mon):
    day = day + month_days(m, leap_year)

day = day + localtime.tm_mday
print("%s's age is %d years or " % (name, year), end="")
print("%d months or %d days" % (month, day))



File: projects/Leap_Year_Checker/leapyear.py

year = int(input("Enter a year:- "))   # Here, you take the input from the user

if(((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0)):   
    """
    if a year is a multiple of four and a multiple of 100 i.e. if it is a multiple of 400 it is not a leap year
    """
    print("{0} is a leap year!!".format(year))
    """
    printing the output
    """
else:
    print("{0} is not a leap year!!".format(year))



File: projects/Cli_todo/todo.py

import click

@click.group()
@click.pass_context
def todo(ctx):
    '''Simple CLI Todo App'''
    ctx.ensure_object(dict)
    #Open todo.txt – first line contains latest ID, rest contain tasks and IDs
    with open('./todo.txt') as f:
        content = f.readlines()
    #Transfer data from todo.txt to the context
    ctx.obj['LATEST'] = int(content[:1][0])
    ctx.obj['TASKS'] = {en.split('```')[0]:en.split('```')[1][:-1] for en in content[1:]}

@todo.command()
@click.pass_context
def tasks(ctx):
    '''Display tasks'''
    if ctx.obj['TASKS']:
        click.echo('YOUR TASKS\n**********')
        #Iterate through all the tasks stored in the context
        for i, task in ctx.obj['TASKS'].items():
            click.echo('• ' + task + ' (ID: ' + i + ')')
        click.echo('')
    else:
        click.echo('No tasks yet! Use ADD to add one.\n')

@todo.command()
@click.pass_context
@click.option('-add', '--add_task', prompt='Enter task to add')
def add(ctx, add_task):
    '''Add a task'''
    if add_task:
        #Add task to list in context 
        ctx.obj['TASKS'][ctx.obj['LATEST']] = add_task
        click.echo('Added task "' + add_task + '" with ID ' + str(ctx.obj['LATEST']))
        #Open todo.txt and write current index and tasks with IDs (separated by " ``` ")
        curr_ind = [str(ctx.obj['LATEST'] + 1)] 
        tasks = [str(i) + '```' + t for (i, t) in ctx.obj['TASKS'].items()]
        with open('./todo.txt', 'w') as f:
            f.writelines(['%s\n' % en for en in curr_ind + tasks])

@todo.command()
@click.pass_context
@click.option('-fin', '--fin_taskid', prompt='Enter ID of task to finish', type=int)
def done(ctx, fin_taskid):
    '''Delete a task by ID'''
    #Find task with associated ID
    if str(fin_taskid) in ctx.obj['TASKS'].keys():
        task = ctx.obj['TASKS'][str(fin_taskid)]
        #Delete task from task list in context
        del ctx.obj['TASKS'][str(fin_taskid)]
        click.echo('Finished and removed task "' + task + '" with id ' + str(fin_taskid))
        #Open todo.txt and write current index and tasks with IDs (separated by " ``` ")
        if ctx.obj['TASKS']:
            curr_ind = [str(ctx.obj['LATEST'] + 1)] 
            tasks = [str(i) + '```' + t for (i, t) in ctx.obj['TASKS'].items()]
            with open('./todo.txt', 'w') as f:
                f.writelines(['%s\n' % en for en in curr_ind + tasks])
        else:
            #Resets ID tracker to 0 if list is empty
            with open('./todo.txt', 'w') as f:
                f.writelines([str(0) + '\n'])
    else:
        click.echo('Error: no task with id ' + str(fin_taskid))

if __name__ == '__main__':
    todo()


File: projects/Fetch HTTP status code/fetch_http_status_code.py

#Program to fetch the http status code give the url/api
from urllib.request import urlopen
from urllib.error import URLError, HTTPError
import emoji

#Taking input url from user
requestURL = input("Enter the URL to be invoked: ")

#Gets the response from URL and prints the status code, corresponding emoji and message accordingly
try:
    response = urlopen(requestURL)
    #In case of success, prints success status code and thumbs_up emoji
    print('Status code : ' + str(response.code) + ' ' + emoji.emojize(':thumbs_up:'))
    print('Message : ' + 'Request succeeded. Request returned message - ' + response.reason)
except HTTPError as e:
    #In case of request failure, prints HTTP error status code and thumbs_down emoji
    print('Status : ' + str(e.code) + ' ' + emoji.emojize(':thumbs_down:'))
    print('Message : Request failed. Request returned reason - ' + e.reason)
except URLError as e:
    #In case of bad URL or connection failure, prints Win Error and thumbs_down emoji
    print('Status :',  str(e.reason).split(']')[0].replace('[','') +  ' ' + emoji.emojize(':thumbs_down:'))
    print('Message : '+ str(e.reason).split(']')[1])



File: projects/Organized_download_folder_with_different_categories/file-sortor.py

import os
import shutil
os.chdir("E:\downloads")
#print(os.getcwd())

#check number of files in  directory
files = os.listdir()

#list of extension (You can add more if you want)
extentions = {
    "images": [".jpg", ".png", ".jpeg", ".gif"],
    "videos": [".mp4", ".mkv"],
    "musics": [".mp3", ".wav"],
    "zip": [".zip", ".tgz", ".rar", ".tar"],
    "documents": [".pdf", ".docx", ".csv", ".xlsx", ".pptx", ".doc", ".ppt", ".xls"],
    "setup": [".msi", ".exe"],
    "programs": [".py", ".c", ".cpp", ".php", ".C", ".CPP"],
    "design": [".xd", ".psd"]


}


#sort to specific folder depend on extenstions
def sorting(file):
    keys = list(extentions.keys())
    for key in keys:
        for ext in extentions[key]:
            # print(ext)
            if file.endswith(ext):
                return key


#iterat through each file
for file in files:
    dist = sorting(file)
    if dist:
        try:
            shutil.move(file, "../download-sorting/" + dist)
        except:
            print(file + " is already exist")
    else:
        try:
            shutil.move(file, "../download-sorting/others")
        except:
            print(file + " is already exist")




File: projects/Random_Wikipedia_Article/wiki_random.py

from bs4 import BeautifulSoup
import requests

# Trying to open a random wikipedia article
# Special:Random opens random articles
res = requests.get("https://en.wikipedia.org/wiki/Special:Random")
res.raise_for_status()

# pip install htmlparser
wiki = BeautifulSoup(res.text, "html.parser")

r = open("random_wiki.txt", "w+", encoding='utf-8')

# Adding the heading to the text file
heading = wiki.find("h1").text

r.write(heading + "\n")
for i in wiki.select("p"):
    # Optional Printing of text
    # print(i.getText())
    r.write(i.getText())

r.close()
print("File Saved as random_wiki.txt")




File: projects/Baidu_POI_crawl/util.py

import requests
import json
import time
    
    
# call API
def get_baidu_poi(roi_key, city_str, baidu_ak, output):
    """
    inputs:
        roi_key: poi name
        city_str: city name
        baidu_ak: baidu web API AK
        output: file save path
    """
    now_time = time.strftime("%Y-%m-%d")
    page_num = 0
    logfile = open(output + "/" + now_time + ".log", "a+", encoding="utf-8")
    file = open(output + "/" + now_time + ".txt", "a+", encoding="utf-8")
    while True:
        try:
            URL = "http://api.map.baidu.com/place/v2/search?query=" + roi_key + \
                "&region=" + city_str + \
                "&output=json" +  \
                "&ak=" + baidu_ak + \
                "&scope=2" + \
                "&page_size=20" + \
                "&page_num=" + str(page_num)
            resp = requests.get(URL)
            res = json.loads(resp.text)
            if len(res["results"]) == 0:
                logfile.writelines(time.strftime("%Y-%m-%d-%H-%M-%S") + " " + city_str + " " + str(page_num) + "\n")
                break
            else:
                for r in res["results"]:
                    j_name = r["name"]
                    j_lat = r["location"]["lat"]
                    j_lon = r["location"]["lng"]
                    j_area = r["area"]
                    j_add = r["address"]
                    j_str = str(j_name) + "," + str(j_lon) + "," + str(j_lat) + "," + str(j_area) + "," + str(j_add) + "\n"
                    file.writelines(j_str)
            page_num += 1
            time.sleep(1)
        except:
            print("except")
            logfile.writelines(time.strftime("%Y-%m-%d-%H-%M-%S") + " " + city_str + " " + str(page_num) + "\n")
            break


File: projects/Baidu_POI_crawl/main.py

import os
import os.path as osp
from util import get_baidu_poi
import argparse


def run(args):
    baidu_web_ak = args.ak
    city_str = args.city
    roi_key = args.poi
    output = args.save
    if not osp.exists(output):
        os.makedirs(output)
    get_baidu_poi(roi_key, city_str, baidu_web_ak, output)
    print("current area completed")


parser = argparse.ArgumentParser(description="input parameters")
parser.add_argument("--ak", type=str, required=True, help="Baidu web ak")
parser.add_argument("--city", type=str, required=True, help="City name")
parser.add_argument("--poi", type=str, required=True, help="POI key")
parser.add_argument("--save", type=str, default="output", help="Save path")


if __name__ == "__main__":
    args = parser.parse_args()
    run(args)


File: projects/Capture_Video_Frames/capture_video_frames.py

import os
import shutil
import sys
import cv2

class FrameCapture:
    '''
        Class definition to capture frames
    '''
    def __init__(self, file_path):
        '''
            initializing directory where the captured frames will be stored.
            Also truncating the directory where captured frames are stored, if exists.
        '''
        self.directory = "captured_frames"
        self.file_path = file_path
        if os.path.exists(self.directory):
            shutil.rmtree(self.directory)
        os.mkdir(self.directory)

    def capture_frames(self):
        '''
            This method captures the frames from the video file provided.
            This program makes use of openCV library
        '''
        cv2_object = cv2.VideoCapture(self.file_path)

        frame_number = 0
        frame_found = 1

        while frame_found:
            frame_found, image = cv2_object.read()
            capture = f'{self.directory}/frame{frame_number}.jpg'
            cv2.imwrite(capture, image)

            frame_number += 1

if __name__ == '__main__':
    file_path = sys.argv[1]
    fc = FrameCapture(file_path)
    fc.capture_frames()



File: projects/Web_scraping_a_youtube_comment/webscrapindcomment.py

# -*- coding: utf-8 -*-
"""
Created on Tue Jul 21 16:55:39 2020

@author: hp
"""

from selenium import webdriver
import csv
import time

items=[]
driver=webdriver.Chrome(r"C:/Users/hp/Anaconda3/chromedriver.exe")

driver.get('https://www.youtube.com/watch?v=iFPMz36std4')

driver.execute_script('window.scrollTo(1, 500);')

#now wait let load the comments
time.sleep(5)

driver.execute_script('window.scrollTo(1, 3000);')


username_elems = driver.find_elements_by_xpath('//*[@id="author-text"]')
comment_elems = driver.find_elements_by_xpath('//*[@id="content-text"]')
for username, comment in zip(username_elems, comment_elems):
    item = {}
    item['Author'] = username.text
    item['Comment'] = comment.text
    items.append(item)
filename = 'C:/Users/hp/Desktop/commentlist.csv'
with open(filename, 'w', newline='', encoding='utf-8') as f: 
    w = csv.DictWriter(f,['Author','Comment']) 
    w.writeheader() 
    for item in items: 
        w.writerow(item) 



File: projects/Speech_to_text/speech_to_text.py

import speech_recognition

def record_voice():
	microphone = speech_recognition.Recognizer()	

	with speech_recognition.Microphone() as live_phone:
		microphone.adjust_for_ambient_noise(live_phone)

		print("I'm trying to hear you: ")
		audio = microphone.listen(live_phone)
		try:
			phrase = microphone.recognize_google(audio, language='en')
			return phrase
		except speech_recognition.UnkownValueError:
			return "I didn't understand what you said"

if __name__ == '__main__':
	phrase = record_voice()

	with open('you_said_this.txt','w') as file:
		file.write(phrase) 

	print('the last sentence you spoke was saved in you_said_this.txt') 



File: projects/Tic_tac_toe_with_ai/tic-tac-toe-AI.py

####	TIC TAC TOE    ####

#START;


#FUNCTIONS;

def default():
	#To be printed as Default;
    print("\nWelcome! Let's play TIC TAC TOE!\n")


def rules():
    print("The board will look like this!")
    print("The positions of this 3 x 3 board is same as the right side of your key board.\n")
    print(" 7 | 8 | 9 ")
    print("-----------")
    print(" 4 | 5 | 6 ")
    print("-----------")
    print(" 1 | 2 | 3 ")
    print("\nYou just have to input the position(1-9).")


def play():
	#Asking if the player is ready;
    return input("\nAre you ready to play the game? Enter [Y]es or [N]o.\t").upper().startswith('Y')


def names():
    #Player names input;
    
    p1_name=input("\nEnter NAME of PLAYER 1:\t").capitalize()
    p2_name=input("Enter NAME of PLAYER 2:\t").capitalize()
    return (p1_name, p2_name)


def choice():
    #Player choice input;
    p1_choice = ' '
    p2_choice = ' '
    while p1_choice != 'X' or p1_choice != 'O':          #while loop; if the entered value isn't X or O;
        
        #WHILE LOOP STARTS

        p1_choice = input(f"\n{p1_name}, Do you want to be X or O?\t")[0].upper()
        #The input above has [0].upper() in the end;
        #So the user can enter x, X, xxxx or XXX; the input will always be taken as X;
        #Thereby, increasing the user input window;

        if p1_choice == 'X' or p1_choice == 'O':
            #if entered value is X or O; get out of the loop; 
            break
        print("INVALID INPUT! Please Try Again!") 
        #if the entered value isn't X or O, re-run the while loop;

        #WHILE LOOP ENDS
    #Assigning the value to p2 and then diplaying the values;
    if p1_choice == 'X':
        p2_choice = 'O'
    elif p1_choice == 'O':
        p2_choice = 'X'
    
    return (p1_choice, p2_choice)



def first_player():
    #This function will randomly decide who will go first;
    import random
    return random.choice((0, 1))


def display_board(board, avail):
    print("    " + " {} | {} | {} ".format(board[7],board[8],board[9]) + "            " + " {} | {} | {} ".format(avail[7],avail[8],avail[9]))
    print("    " + "-----------" + "            " + "-----------")
    print("    " + " {} | {} | {} ".format(board[4],board[5],board[6]) + "            " + " {} | {} | {} ".format(avail[4],avail[5],avail[6]))
    print("    " + "-----------" + "            " + "-----------")
    print("    " + " {} | {} | {} ".format(board[1],board[2],board[3]) + "            " + " {} | {} | {} ".format(avail[1],avail[2],avail[3]))


def player_choice(board, name, choice):
    position = 0
    #Initialising position as 0^; so it passes through the while loop; 
    while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):
        position = int(input(f'\n{name} ({choice}), Choose your next position: (1-9) \t'))
        
        if position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position) or position == "": 
            #To check whether the given position is in the set [1-9] or whether it is empty or occupied;
            print(f"INVALID INPUT. Please Try Again!\n")   
    print("\n")        
    return position


# THIS IS THEFUNCTION WHERE AI IS ADDED:
def CompAI(board, name, choice):
    position = 0
    possibilities = [x for x, letter in enumerate(board) if letter == ' ' and x != 0]
    
    # including both X and O, since if computer will win, he will place a choice there, but if the component will win --> we have to block that move
    for let in ['O', 'X']:
        for i in possibilities:
            # Creating a copy of the board everytime, placing the move and checking if it wins;
            # Creating a copy like this  and not this boardCopy = board, since changes to boardCopy changes the original board;
            boardCopy = board[:]
            boardCopy[i] = let
            if(win_check(boardCopy, let)):
                position = i
                return position

    openCorners = [x for x in possibilities if x in [1, 3, 7, 9]]
    
    if len(openCorners) > 0:
        position = selectRandom(openCorners)
        return position

    if 5 in possibilities:
        position = 5
        return position

    openEdges = [x for x in possibilities if x in [2, 4, 6, 8]]
    
    if len(openEdges) > 0:
        position = selectRandom(openEdges)
        return position



def selectRandom(board):
    import random
    ln = len(board)
    r = random.randrange(0,ln)
    return board[r]


def place_marker(board, avail, choice, position):
    #To mark/replace the position on the board list;
    board[position] = choice
    avail[position] = ' '


def space_check(board, position):
    #To check whether the given position is empty or occupied;
    return board[position] == ' '


def full_board_check(board):
    #To check if the board is full, then the game is a draw;
    for i in range(1,10):
        if space_check(board, i):
            return False
    return True


def win_check(board, choice):
    #To check if one of the following patterns are true; then the respective player has won!;
    
    #HORIZONTAL CHECK;
    return ( 
       ( board[1] == choice and board[2] == choice and board[3] == choice )
    or ( board[4] == choice and board[5] == choice and board[6] == choice )
    or ( board[7] == choice and board[8] == choice and board[9] == choice )
    #VERTICAL CHECK;
    or ( board[1] == choice and board[4] == choice and board[7] == choice )
    or ( board[2] == choice and board[5] == choice and board[8] == choice )
    or ( board[3] == choice and board[6] == choice and board[9] == choice )
    #DIAGONAL CHECK;
    or ( board[1] == choice and board[5] == choice and board[9] == choice )
    or ( board[3] == choice and board[5] == choice and board[7] == choice )  )

def delay(mode):
    if mode == 2:
        import time
        time.sleep(2)

def replay():
    #If the users want to play the game again?
    return input('\nDo you want to play again? Enter [Y]es or [N]o: ').lower().startswith('y')





#MAIN PROGRAM STARTS;

print("\n\t\t NAMASTE! \n")
input("Press ENTER to start!")

default()
rules()


while True:
    ####################################################################################
    
    #Creating the board as a list; to be kept replacing it with user input;
    theBoard = [' ']*10
    
    #Creating the available options on the board:
    available = [str(num) for num in range(0,10)] # a List Comprehension
    #available = '0123456789'
    


    print("\n[0]. Player vs. Computer")
    print("[1]. Player vs. Player")
    print("[2]. Computer vs. Computer")
    mode = int(input("\nSelect an option [0]-[2]: "))
    if mode == 1:
        #Asking Names;
        p1_name, p2_name = names()
        # Asking Choices; Printing choices; X or O;
        p1_choice, p2_choice = choice()
        print(f"\n{p1_name}:", p1_choice)
        print(f"{p2_name}:", p2_choice)

    elif mode == 0:
        p1_name = input("\nEnter NAME of PLAYER who will go against the Computer:\t").capitalize()
        p2_name = "Computer"
        # Asking Choices; Printing choices; X or O;
        p1_choice, p2_choice = choice()
        print(f"\n{p1_name}:", p1_choice)
        print(f"{p2_name}:", p2_choice)
    
    else:
        p1_name = "Computer1"
        p2_name = "Computer2"
        p1_choice, p2_choice = "X", "O"
        print(f"\n{p1_name}:", p1_choice)
        print(f"\n{p2_name}:", p2_choice)


    
    #Printing randomly who will go first;
    if first_player():
        turn = p2_name
    else:
        turn = p1_name

    print(f"\n{turn} will go first!")
    
    #Asking the user, if ready to play the game; Output will be True or False;
    if(mode == 2):
        ent = input("\nThis is going to be fast! Press Enter for the battle to begin!\n")
        play_game = 1
    else:
        play_game = play()   
    
    while play_game:
        
        ############################
        #PLAYER1
        if turn == p1_name:
            
            #Displaying the board;
            display_board(theBoard, available)

            #Position of the input;
            if mode != 2:
                position = player_choice(theBoard, p1_name, p1_choice)
            else:
                position = CompAI(theBoard, p1_name, p1_choice)
                print(f'\n{p1_name} ({p1_choice}) has placed on {position}\n')
            
            #Replacing the ' ' at *position* to *p1_choice* in *theBoard* list; 
            place_marker(theBoard, available, p1_choice, position)
            
            #To check if Player 1 has won after the current input;
            if win_check(theBoard, p1_choice):
                display_board(theBoard, available)
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                if(mode):
                    print(f'\n\nCONGRATULATIONS {p1_name}! YOU HAVE WON THE GAME!\n\n')
                else:
                    print('\n\nTHE Computer HAS WON THE GAME!\n\n')
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                play_game = False
                
            else:
                #To check if the board is full; if yes, the game is a draw;
                if full_board_check(theBoard):
                    display_board(theBoard, available)
                    print("~~~~~~~~~~~~~~~~~~")
                    print('\nThe game is a DRAW!\n')
                    print("~~~~~~~~~~~~~~~~~~")
                    break
                #If none of the above is possible, next turn of Player 2;    
                else:
                    turn = p2_name
                    
                    
        ############################
        #PLAYER2            
        elif turn == p2_name:
            
            #Displaying the board;
            display_board(theBoard, available)

            #Position of the input;
            if(mode == 1):
                position = player_choice(theBoard, p2_name, p2_choice)
            else:
                position = CompAI(theBoard, p2_name, p2_choice)
                print(f'\n{p2_name} ({p2_choice}) has placed on {position}\n')
            
            #Replacing the ' ' at *position* to *p2_choice* in *theBoard* list; 
            place_marker(theBoard, available, p2_choice, position)
            
            #To check if Player 2 has won after the current input;
            if win_check(theBoard, p2_choice):
                display_board(theBoard, available)
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                if(mode):
                    print(f'\n\nCONGRATULATIONS {p2_name}! YOU HAVE WON THE GAME!\n\n')
                else:
                    print('\n\nTHE Computer HAS WON THE GAME!\n\n')
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                play_game = False
                
            else:
                #To check if the board is full; if yes, the game is a draw;
                if full_board_check(theBoard):
                    display_board(theBoard, available)
                    print("~~~~~~~~~~~~~~~~~~")
                    print('\nThe game is a DRAW!\n')
                    print("~~~~~~~~~~~~~~~~~~")
                    break
                #If none of the above is possible, next turn of Player 2;       
                else:
                    turn = p1_name
        
                    
    #If the users want to play the game again?                
    if replay():
        #if Yes;
        continue
    else:
        #if No;
        break
        
    ####################################################################################
    
print("\n\n\t\t\tTHE END!")



#END    


File: projects/Convert_a_image_to_pdf/convert_image_to_pdf.py

import sys
import img2pdf
import os

filepath = sys.argv[1]
if os.path.isdir(filepath):
    with open("output.pdf", "wb") as f:
        imgs = []
        for fname in os.listdir(filepath):
            if not fname.endswith(".jpg"):
                continue
            path = os.path.join(filepath, fname)
            if os.path.isdir(path):
                continue
            imgs.append(path)
        f.write(img2pdf.convert(imgs))
elif os.path.isfile(filepath):
    if filepath.endswith(".jpg"):
        with open("output.pdf", "wb") as f:
            f.write(img2pdf.convert(filepath))
else:
    print("please input file or dir")




File: projects/Split_File/split_files.py

import sys
import os
import shutil
import pandas as pd

class Split_Files:
    '''
        Class file for split file program
    '''
    def __init__(self, filename, split_number):
        '''
            Getting the file name and the split index
            Initializing the output directory, if present then truncate it.
            Getting the file extension
        '''
        self.file_name = filename
        self.directory = "file_split"
        self.split = int(split_number)
        if os.path.exists(self.directory):
            shutil.rmtree(self.directory)
        os.mkdir(self.directory)
        if self.file_name.endswith('.txt'):
            self.file_extension = '.txt'
        else:
            self.file_extension = '.csv'
        self.file_number = 1

    def split_data(self):
        '''
            spliting the input csv/txt file according to the index provided
        '''
        data = pd.read_csv(self.file_name, header=None)
        data.index += 1

        split_frame = pd.DataFrame()
        output_file = f"{self.directory}/split_file{self.file_number}{self.file_extension}"

        for i in range(1, len(data)+1):
            split_frame = split_frame.append(data.iloc[i-1])
            if i % self.split == 0:
                output_file = f"{self.directory}/split_file{self.file_number}{self.file_extension}"
                if self.file_extension == '.txt':
                    split_frame.to_csv(output_file, header=False, index=False, sep=' ')
                else:
                    split_frame.to_csv(output_file, header=False, index=False)
                split_frame.drop(split_frame.index, inplace=True)
                self.file_number += 1
        if not split_frame.empty:
            output_file = f"{self.directory}/split_file{self.file_number}{self.file_extension}"
            split_frame.to_csv(output_file, header=False, index=False)

if __name__ == '__main__':
    file, split_number = sys.argv[1], sys.argv[2]
    sp = Split_Files(file, split_number)
    sp.split_data()



File: projects/convert_png_images_to_ico_format/convert.py

from PIL import Image
# Take input image from present folder
img = Image.open('input.png')
# Generate and save output image to present folder
img.save('output.ico') 


File: projects/convert_png_images_to_ico_format/convertUI.py

import tkinter as tk
from PIL import Image

# Initialize Tkinter window
root = tk.Tk()
# Initialize variable to store image path
img = None
# Initialize font, background color, foreground color and width for the buttons
font = ('helvetica', 12, 'bold')
bg = 'blue'
fg = 'white'
width = 15

def getPNG():
    '''Function to get png image location and open it with pillow'''
    global img
    import_file_path = tk.filedialog.askopenfilename(filetypes=[("PNG File",'.png')])
    img = Image.open(import_file_path)

def convertToICO():
    global img
    '''Function to convert image from png to ico format with pillow and save to user specified location'''
    if img is None:
        tk.messagebox.showerror("Error", "No File selected")
    else:
        export_file_path = tk.filedialog.asksaveasfilename(defaultextension='.ico')
        img.save(export_file_path)
        tk.messagebox.showinfo("Success", "File converted and saved")

# Set the window title
root.title('PNG to ICO Converter')
canvas1 = tk.Canvas(root, width=500, height=350, bg='lightblue')
canvas1.pack()
# Set the screen title
label1 = tk.Label(root, text='PNG to ICO Converter', bg='lightblue')
label1.config(font=('helvetica', 20))
canvas1.create_window(250, 100, window=label1)
# Browse button to browse for image
browseButton = tk.Button(text="Import PNG File", command=getPNG, bg=bg, fg=fg, font=font, width=width)
canvas1.create_window(250, 150, window=browseButton)
# Convert button to convert selected image and save
saveAsButton = tk.Button(text='Convert PNG to ICO', command=convertToICO, bg=bg, fg=fg, font=font, width=width)
canvas1.create_window(250, 200, window=saveAsButton)
root.mainloop()



File: projects/Convert_XML_To_JSON/converter.py

import json
import xmltodict

with open('input.xml') as xml_file:
    parsed_data = xmltodict.parse(xml_file.read())

    xml_file.close()

    json_conversion = json.dumps(parsed_data)

    with open('output.json', 'w') as json_file:
        json_file.write(json_conversion)

        json_file.close()



File: projects/Write_a_script_to_download_a_random_image_from_unsplash_and_set_it_as_wallpaper/background_windows.py

from requests import get
import os
import ctypes
import sys

url = "https://source.unsplash.com/random"
file_name = "random.jpg"

def is_64bit():
    return sys.maxsize > 2 ** 32


def download(url, file_name):
    '''
    downloading the file and saving it
    '''
    with open(file_name, "wb") as file:
        response = get(url)
        file.write(response.content)


def setup(pathtofile,version):
    name_of_file = pathtofile
    path_to_file = os.path.join(os.getcwd(), name_of_file)
    SPI_SETDESKWALLPAPER = 20
    if is_64bit():
        ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, path_to_file, 0)
    else:
        ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, path_to_file, 0)


if __name__ == "__main__":
    try:
        download(url, file_name)
        setup(file_name)
    except Exception as e:
        print(f"Error {e}")
        raise NotImplementedError



File: projects/Write_a_script_to_download_a_random_image_from_unsplash_and_set_it_as_wallpaper/background_linux.py

from requests import get  # to make GET request
from os import system, getcwd, path


url = "https://source.unsplash.com/random"
filename = "random.jpg"


def download(url, file_name):
    '''
    downloading the file and saving it
    '''
    with open(file_name, "wb") as file:
        response = get(url)
        file.write(response.content)


def setup(pathtofile):
    '''
    setting the up file
    '''
    system("nitrogen --set-auto {}".format(path.join(getcwd(), pathtofile)))


if __name__ == "__main__":
    download(url, filename)
    setup(filename)



File: projects/GUI Rock-Paper-Scissors Game/Rock-Paper-Scissors Game.py

# Import Required Library
from tkinter import *
from tkinter import ttk
from random import *

# Create Object
root = Tk()

# Set geometry
root.geometry("500x500")

root.title("Rock-Paper-Scissors-Game")

# List of players
list = ["rock","paper","scissors"]

choose_number = randint(0,2)
print(choose_number) # For testing if it works

label = Label(root,text="Computer ",width = 20,height=4,font=("algerian",15))
label.pack()

def spin():
    choose_number = randint(0,2)
    label.config(text=list[choose_number])
    if user_select.get() == "Rock":
        user_select_value = 0
        print(user_select_value)
    elif user_select.get() == "Paper":
        user_select_value = 1
        print(user_select_value)
    elif user_select.get() == "Scissors":
        user_select_value = 2
        print(user_select_value)

    if user_select_value == 0:
        if choose_number == 0:
            wl_label.config(text="Tie! - "+" Computer:Bad luck")
        elif choose_number == 1:
            wl_label.config(text="YOU Loose - "+" Computer: I am better ")
        elif choose_number == 2 :
            wl_label.config(text="YOU Won - "+" Computer: You won by luck")

    elif user_select_value == 1:
        if choose_number == 1:
            wl_label.config(text="Tie! - "+" Computer: Nice game")
        elif choose_number == 0:
            wl_label.config(text="YOU Won - "+" Computer: Shit how you are better")
        elif choose_number == 2 :
            wl_label.config(text="YOU Loose - "+" Computer: booo")

    elif user_select_value == 2:
        if choose_number == 2:
            wl_label.config(text="Tie!")
        elif choose_number == 0:
            wl_label.config(text="YOU Loose - "+" Computer: I am playing this game since i was born")
        elif choose_number == 1 :
            wl_label.config(text="YOU Won")



# Adding dropdown box for Rock,Paper,Scissors
user_select = ttk.Combobox(root,value=["Rock","Paper","Scissors"])
user_select.current(0)
user_select.pack()

# Add Labels,Button
wl_label = Label(root,text="",font=("arial",10),width=50,height=4)
wl_label.pack()

button = Button(root,text="Spin!",font=("bell mt",10),command=spin)
button.pack()

root.mainloop()



File: projects/RockPaperScissors_Game/Rock_Paper_Scissors_Game.py

#START;

import random

#DEFAULT;
my_dict={'R':"Rock",'P':"Paper",'S':"Scissors"}
user_count=0
comp_count=0

#INPUT;
games=int(input("\nEnter the number of games you want to play: "))

while(comp_count+user_count<games):
	#WHILE LOOP STARTS;

	flag=0

	user_input=input("\nUser's Input: ")[0]
	user_input=user_input.upper()
	#The [0] after the input() will assign the first charcter of input to the variable;
	#Hence, the user can enter anything, anyway; 
	#Example: The user can enter Rock or rock or r or R or ro or any such thing which represents Rock;
	#It will always take input as a R
	#Thereby, increasing the user input window;

	for i in my_dict.keys():
		if(user_input==i):		#If the entered input is confined to Rock, Paper or Scissors;
			flag=1
			break
	if(flag!=1):				#If not, run the loop again;
		print("INVALID INPUT")
		continue

	comp_input=random.choice(list(my_dict.keys()))	#Random Key from the dictionary my_dict i.e. R,P or S;

	print("Computer's Input: ", my_dict[comp_input])
	if ( user_input=='R' and comp_input=='P' ) or ( user_input=='P' and comp_input=='S' ) or ( user_input=='S' and comp_input=='R' ):
		comp_count=comp_count+1
	elif ( user_input=='P' and comp_input=='R' ) or ( user_input=='S' and comp_input=='P' ) or ( user_input=='R' and comp_input=='S' ):
		user_count=user_count+1
	else:
		print("TIE")

	print("\nSCORE:")
	print("User Score:",user_count,"\tComputer Score:",comp_count,"\n")

	#LOOP ENDS;

print("\n\t\tFINAL SCORE:")
print("User Score:",user_count,"\t\t\tComputer Score:",comp_count,"\n")
if user_count>comp_count:
	print("\n\tCONGRATULATIONS! YOU WON!")
elif user_count<comp_count:
	print("\n\t\tSORRY! YOU LOST!")
else:
	print("\n\t\tOOPS! IT'S A TIE!")



#END;



File: projects/Write_script_to_compress_folder_and_files/zipfiles.py

import zipfile
import sys
import os


# compress file function
def zip_file(file_path):
    compress_file = zipfile.ZipFile(file_path + '.zip', 'w')
    compress_file.write(path, compress_type=zipfile.ZIP_DEFLATED)
    compress_file.close()


# Declare the function to return all file paths of the particular directory
def retrieve_file_paths(dir_name):
    # setup file paths variable
    file_paths = []

    # Read all directory, subdirectories and file lists
    for root, directories, files in os.walk(dir_name):
        for filename in files:
            # Create the full file path by using os module.
            file_path = os.path.join(root, filename)
            file_paths.append(file_path)

    # return all paths
    return file_paths


def zip_dir(dir_path, file_paths):
    # write files and folders to a zipfile
    compress_dir = zipfile.ZipFile(dir_path + '.zip', 'w')
    with compress_dir:
        # write each file separately
        for file in file_paths:
            compress_dir.write(file)


if __name__ == "__main__":
    path = sys.argv[1]

    if os.path.isdir(path):
        files_path = retrieve_file_paths(path)
        # print the list of files to be zipped
        print('The following list of files will be zipped:')
        for file_name in files_path:
            print(file_name)
        zip_dir(path, files_path)
    elif os.path.isfile(path):
        print('The %s will be zipped:' % path)
        zip_file(path)
    else:
        print('a special file(socket,FIFO,device file), please input file or dir')



File: projects/Language_translator/translator.py

from googletrans import Translator

translator = Translator()

language = {"bn": "Bangla",
            "en": "English",
            "ko": "Koren",
            "fr": "French",
            "de": "German",
            "he": "Hebrew",
            "hi": "Hindi",
            "it": "Italian",
            "ja": "Japanese",
            'la': "Latin",
            "ms": "Malay",
            "ne": "Nepali",
            "ru": "Russian",
            "ar": "Arabic",
            "zh": "Chinese",
            "es": "Spanish"
            }

allow = True  # variable to control correct language code input

while allow:  # checking if language code is valid

    user_code = input(
        f"Please input desired language code. To see the language code list enter 'options' \n")

    if user_code == "options":  # showing language options
        print("Code : Language")  # Heading of language option menu
        for i in language.items():
            print(f"{i[0]} => {i[1]}")
        print()  # adding an empty space

    else:  # validating user input
        for lan_code in language.keys():
            if lan_code == user_code:
                print(f"You have selected {language[lan_code]}")
                allow = False
        if allow:
            print("It's not a valid language code!")

while True:  # starting translation loop
    string = input(
        "\nWrite the text you want to translate: \nTo exit the program write 'close'\n")

    if string == "close":  # exit program command
        print(f"\nHave a nice Day!")
        break

    # translating method from googletrans
    translated = translator.translate(string, dest=user_code)

    # printing translation
    print(f"\n{language[user_code]} translation: {translated.text}")
    # printing pronunciation
    print(f"Pronunciation : {translated.pronunciation}")

    for i in language.items():  # checking if the source language is listed on language dict and printing it
        if translated.src == i[0]:
            print(f"Translated from : {i[1]}")



File: projects/Set_Alarm/alarm.py

import datetime
import os
import re
import subprocess


def rename_files_with_whitespaces(cd, files, extra_path=""):
    for file in files:
        if " " in file:
            renamed_file = file.replace(" ", "_")
            os.rename(os.path.join(cd, extra_path, file), os.path.join(cd, extra_path, renamed_file))


def clean_filename(file):
    return ' '.join(map(str.capitalize, file[:-4].split('_')))


def set_alarm():
    stop = False
    error = True
    while error:
        user_set_time = ":".join(map(lambda x: str(x).zfill(2), input("\nSet the alarm time (e.g. 01:10): ").split(":")))

        if re.match(r"^[0-9]{2}:[0-9]{2}$", user_set_time):
            playback_time = f"{user_set_time}:00.000000"
            error = False
        else:
            print(">>> Error: Time format invalid! Please try again!\n")
            
    cd = os.path.dirname(os.path.realpath(__file__))
    musics_path = os.path.join(cd, "musics")
    
    rename_files_with_whitespaces(cd, os.listdir(musics_path), "musics")

    musics = os.listdir(musics_path)
    if len(musics) < 1:
        print(">>> Error: No music in the musics folder! Please add music first!\n")
        exit()

    elif len(musics) == 1:
        print(">> Alarm music has been set default --> " + clean_filename(musics[0]))
        selected_music = musics[0]
    
    else:
        error = True
        while error:
            try:
                print("\nSelect any alarm music:\n")
                for i in range(1, len(musics) + 1):
                    print(f"{i}. {clean_filename(musics[i - 1])}")
                    
                user_input = int(input("\nEnter the index of the listed musics (e.g. 1): "))
                selected_music = musics[user_input - 1]
                print(">> Alarm music has been set --> "+ clean_filename(selected_music))
                error = False

            except:
                print(">>> Error: Invalid Index! Please try again!\n")
    
    print(f"\n>>> Alarm has been set successfully for {user_set_time}! Please dont close the program! <<<")
    while stop == False:
        current_time = str(datetime.datetime.now().time())
        if current_time >= playback_time:
            stop = True
            subprocess.run(('cmd', '/C', 'start', f"{cd}\\musics\\{selected_music}"))
            print(">>> Alarm ringing! Closing the program!! Bye Bye!!! <<<")

def display_header(header):
    print("")
    print("###########################".center(os.get_terminal_size().columns))
    print(f"###### {header} ######".center(os.get_terminal_size().columns))
    print("###########################".center(os.get_terminal_size().columns))

if __name__ == "__main__":
    display_header("Alarm Program")
    set_alarm()


File: projects/News_website_scraper/moneycontrol_scrapper.py

import re
import json
import requests
import datetime
from tqdm import tqdm
from bs4 import BeautifulSoup
from collections import defaultdict

submission = defaultdict(list)
#main url
src_url = 'https://www.moneycontrol.com/news/technical-call-221.html'

#get next page links and call scrap() on each link
def setup(url):
    nextlinks = []
    src_page = requests.get(url).text
    src = BeautifulSoup(src_page, 'lxml')

    #ignore <a> with void js as href
    anchors = src.find("div", attrs={"class": "pagenation"}).findAll(
        'a', {'href': re.compile('^((?!void).)*$')})
    nextlinks = [i.attrs['href'] for i in anchors]
    for idx, link in enumerate(tqdm(nextlinks)):
        scrap('https://www.moneycontrol.com'+link, idx)

#scraps passed page url 
def scrap(url, idx):
    src_page = requests.get(url).text
    src = BeautifulSoup(src_page, 'lxml')

    span = src.find("ul", {"id": "cagetory"}).findAll('span')
    img = src.find("ul", {"id": "cagetory"}).findAll('img')

    #<img> has alt text attr set as heading of news, therefore get img link and heading from same tag
    imgs = [i.attrs['src'] for i in img]
    titles = [i.attrs['alt'] for i in img]
    date = [i.get_text() for i in span]

    #list of dicts as values and indexed by page number
    submission[str(idx)].append({'title': titles})
    submission[str(idx)].append({'date': date})
    submission[str(idx)].append({'img_src': imgs})

#save data as json named by current date
def json_dump(data):
    date = datetime.date.today().strftime("%B %d, %Y")
    with open('moneycontrol_'+str(date)+'.json', 'w') as outfile:
        json.dump(submission, outfile)

setup(src_url)
json_dump(submission)




File: projects/Multi_language_OCR/multi_language_OCR.py

# Author: Acer Zhang
# Datetime: 2021/9/14 
# Copyright belongs to the author.
# Please indicate the source for reprinting.

language = """
Language 	        Abbreviation 		Language 	Abbreviation
Chinese & English 	ch 		            Arabic 	    ar
English 	        en 		            Hindi 	    hi
French 	            fr 		            Uyghur 	    ug
German 	            german 		        Persian 	fa
Japan 	            japan 		        Urdu    	ur
Korean 	            korean 		        Serbian(latin) 	rs_latin
Chinese Traditional 	chinese_cht 	Occitan 	oc
Italian 	        it 		            Marathi 	mr
Spanish 	        es 		            Nepali 	ne
Portuguese 	        pt 		            Serbian(cyrillic) 	rs_cyrillic
Russia 	            ru 		            Bulgarian 	bg
Ukranian 	        uk 		            Estonian 	et
Belarusian 	        be 		            Irish 	ga
Telugu 	            te 		            Croatian 	hr
Saudi Arabia 	    sa 		            Hungarian 	hu
Tamil 	            ta 		            Indonesian 	id
Afrikaans 	        af 		            Icelandic 	is
Azerbaijani 	    az 		            Kurdish 	ku
Bosnian 	        bs 		            Lithuanian 	lt
Czech 	            cs 		            Latvian 	lv
Welsh 	            cy 		            Maori   	mi
Danish 	            da 		            Malay 	    ms
Maltese 	        mt 		            Adyghe 	    ady
Dutch 	            nl 		            Kabardian 	kbd
Norwegian 	        no 		            Avar    	ava
Polish 	            pl 		            Dargwa 	    dar
Romanian 	        ro 		            Ingush  	inh
Slovak 	            sk 		            Lak     	lbe
Slovenian 	        sl 		            Lezghian 	lez
Albanian 	        sq 		            Tabassaran 	tab
Swedish 	        sv 		            Bihari  	bh
Swahili 	        sw 		            Maithili 	mai
Tagalog 	        tl 		            Angika 	    ang
Turkish 	        tr 		            Bhojpuri 	bho
Uzbek 	            uz 		            Magahi  	mah
Vietnamese 	        vi 		            Nagpur  	sck
Mongolian 	        mn 		            Newari  	new
Abaza 	            abq 		        Goan Konkani 	gom
"""

# Import AgentOCR python module
from agentocr import OCRSystem

# Choose OCR language
print(language)
config = input("Please enter the language you want to recognize:")
# Init OCRSystem
ocr = OCRSystem(config=config)
print("OCR system Initialization complete!")

# Start OCR!
while True:
    img = input("Please enter the path where the picture file is located:")
    results = ocr.ocr(img)
    for info in results:
        print(info)


File: projects/telegram_bot/main.py

'''
    BOT FOR TELEGRAM
'''

import random
import logging
from telegram import (ParseMode)
from telegram.ext import (Updater, CommandHandler)

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)


def error_callback(update, context):
    logger.warning('Update "%s" caused error "%s"', update, context.error)


def start(update, context):
    ''' 
        Start
    '''
    context.bot.send_message(update.message.chat_id,
                             "Welcome! to simple telegram bot", parse_mode=ParseMode.HTML)

    ''' 
        We can call other commands, without it being activated in the chat (/ help).
    '''
    coin(update, context)


def coin(update, context):
    '''
        ⚪️ / ⚫️ Currency
         Generate an elatory number between 1 and 2.
    '''
    cid = update.message.chat_id

    msg = "⚫️ face " if random.randint(1, 2) == 1 else "⚪️ cross"
    '''
        He responds directly on the channel where he has been spoken to.
    '''
    update.message.reply_text(msg)


def main():
    TOKEN = "1914536904:AAF4ZnqNvyg1pk-1pCPzTqhDYggAyf-1CF8"

    updater = Updater(TOKEN, use_context=True)

    dp = updater.dispatcher

    '''
        Events that will activate our bot.
    '''
    dp.add_handler(CommandHandler('start',	start))
    dp.add_handler(CommandHandler('coin',	coin))

    dp.add_error_handler(error_callback)

    '''
        The bot starts
    '''
    updater.start_polling()

    '''
        or leave listening. Keep it from stopping.
    '''
    updater.idle()


if __name__ == '__main__':
    print('[Telegram simple bot] Start...')
    main()


File: projects/Space_bullet_shooter_game/space_bullet_shooter.py

"""
 @Author : TheKnight
 Date : 6/09/2020

 copyright  © TheKight All Right Reserved



"""

import pygame
import random
import math
import time

from pygame import mixer




pygame.init()

clock = pygame.time.Clock()
# bg sound
mixer.music.load("bg.wav")
mixer.music.play(-1)


score_value = 0


# setting the display
screen = pygame.display.set_mode((800,600))

# background
bg = pygame.image.load("img2.png")

icon = pygame.image.load("icond.png")
pygame.display.set_caption("Space Bullet Shooter")
# display the icon
pygame.display.set_icon(icon)




# showing the bird imageo
playeimg = pygame.image.load("pl4.png")
playerx = 370
playery = 460

playerx_change = 0

def player(x,y):
	screen.blit(playeimg,(x,y))







 # moving the playerimag
 # for this we will use cordinate movement 
 # we will pass arugument to the function 


# for enemy
enemyimg =[]
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []

number_of_enemy = 6
for i in range(number_of_enemy):


	enemyimg.append(pygame.image.load("ens.png"))

	enemyX.append(random.randint(0,736))
	enemyY.append(random.randint(50,150))
	enemyX_change.append(4)
	enemyY_change.append(30)


# bullet
bulletimg = pygame.image.load("bullet.png")
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 20
bullet_state = "ready"
# function for enemy

def enemy(x,y,i):
	screen.blit(enemyimg[i],(x,y))


# function for fire bullet

def fire_bullet(x,y):
	global bullet_state
	bullet_state = "fire"
	screen.blit(bulletimg,(x+53,y+10))



# checking if collision
def is_collision(enemyX,enemyY,playerx,playery):

	distance = math.sqrt((math.pow(enemyX-bulletX,2))+(math.pow(enemyY-bulletY,2)))
	if distance < 27:
		return True

	else:
		return False



# showing score

font = pygame.font.Font("freesansbold.ttf",35)
score_cordinate_X = 10
Score_cordinate_Y=10
def showscore(x,y):
	score = font.render("Score : " + str(score_value),True,(255,255,255))
	screen.blit(score,(x,y))



OVER = pygame.font.Font("freesansbold.ttf",60)
# game over 
def game_over():
	over = OVER.render("GAME OVER   " 
	 ,True,(0,0,255))
	screen.blit(over,(250,250))


final = pygame.font.Font("freesansbold.ttf",50)
def final_score():
	finalscore = final.render("Total Score : " +str(score_value) ,True,(0,255,0))
	screen.blit(finalscore,(280,350))
	 

author = pygame.font.Font("freesansbold.ttf",16)
# showing author name

def author_name():
	subject = author.render("Copyright ©2020 TheKnight All Right Reseved By TheKnight " 
	 ,True,(0,255,0)) 
	screen.blit(subject,(170,580))


# game loop
running = True

while running:
	screen.fill((0,0,0))
	screen.blit(bg,(0,0))


	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			running = False

		# controlling the bird by arrow keys

		if event.type == pygame.KEYDOWN:
			if event.key == pygame.K_LEFT:
				playerx_change = -5

			if event.key == pygame.K_RIGHT:
				playerx_change = 5

			if event.key == pygame.K_SPACE:
				if bullet_state == "ready":
					bulletX = playerx
					bulletsound = mixer.Sound("bulletout.wav")
					bulletsound.play()
				
					fire_bullet(bulletX,bulletY)

			

		if event.type == pygame.KEYUP:
			if event.key == pygame.K_LEFT or event.key == pygame.K_LEFT:
				playerx_change = 0



	for i in range(number_of_enemy):

		# game over
		if enemyY[i] >440:

			for j in range(number_of_enemy):
				enemyY[j] =2000
			game_over()
			time.sleep(2)

			final_score()
			
			break





			
		enemyX[i] += enemyX_change[i]
		if enemyX[i] <=0:
			enemyX_change[i]= 4
			enemyY[i] += enemyY_change[i]

		elif enemyX[i]>=736:
			enemyX_change[i] = -4
			enemyY[i] += enemyY_change[i]


		# collision

		collision = is_collision(enemyX[i],enemyY[i],bulletX,bulletY)
		if collision:
			bulletsound = mixer.Sound("bulletshoot.wav")
			bulletsound.play()
			bulletY = 480
			bullet_state = "ready"

			score_value +=1

		
			enemyX[i] = random.randint(0,736)
			enemyY[i] = random.randint(50,150)


		enemy(enemyX[i],enemyY[i],i)




			


			
			

			
			
			
			



			





















	

	# checking boundries of spacechip
	playerx+=playerx_change

	if playerx <=0:
		playerx = 0
	elif playerx>=730:
		playerx = 730
	

	
	# playerx -=0.2
	# playery -=.2

	

	# bullet movement
	if bulletY <=0:
		bulletY=480
		bullet_state = "ready"
	if bullet_state == "fire":
		fire_bullet(bulletX,bulletY)
		bulletY -= bulletY_change
	
	player(playerx,playery)
	showscore(score_cordinate_X,Score_cordinate_Y)

	author_name()
	





	pygame.display.update()




File: projects/cat_command/cat.py

#!/usr/bin/python

import argparse
from pathlib import Path
from sys import stderr, stdout
import os

class CatError(Exception):
    pass

class Logger:
    def __init__(self, verbosity=False):
        self.verbose = verbosity

    def error(self, message):
        print(f'ERROR: {message}')

logger = Logger()

'''
    Read the selected text file 

    Example:
    your/path/file.txt
'''
def readFile(src: Path):

    '''
        if the given path is a directory
        ERROR the path is a directory
    '''
    if src.is_dir():

        logger.error(f'The path {src}: is a directory')

    else:

        with open(src, 'r') as f:
            for lines in f:
                print(lines, end='')

def cli() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        prog='cat',
        description='cat command implementation in python',
        epilog='Example: your/path/file.txt'
    )

    parser.add_argument(
        'source',
        type=Path,
        help='Source file'
    )

    return parser.parse_args()

def main():

    args = cli()

    try:

        readFile(args.source)

    except CatError as e:

        logger.error(e)

        exit(1)

    except KeyboardInterrupt:

        logger.error('\nInterrupt')

'''
    Start the program
'''
if __name__ == '__main__':
    main()



File: projects/Create_a_simple_stopwatch/stopwatch.py

import tkinter as Tkinter
from datetime import datetime
counter = 0
running = False


def counter_label(label):
    def count():
        if running:
            global counter
			# To manage the intial delay. 
            if counter == 0:
                display = 'Ready!'
            else:
                tt = datetime.utcfromtimestamp(counter)
                string = tt.strftime('%H:%M:%S')
                display = string
	
            label['text'] = display
	
			# label.after(arg1, arg2) delays by 
			# first argument given in milliseconds 
			# and then calls the function given as second argument. 
			# Generally like here we need to call the 
			# function in which it is present repeatedly. 
			# Delays by 1000ms=1 seconds and call count again. 
            label.after(1000, count)
            counter += 1
	
	# Triggering the start of the counter. 
    count()
	

# start function of the stopwatch 
def Start(label):
    global running
    running = True
    counter_label(label)
    start['state'] = 'disabled'
    stop['state'] = 'normal'
    reset['state'] = 'normal'
	

# Stop function of the stopwatch 
def Stop():
    global running
    start['state'] = 'normal'
    stop['state'] = 'disabled'
    reset['state'] = 'normal'
    running = False
	

# Reset function of the stopwatch 
def Reset(label):
	global counter
	counter = 0
	# If reset is pressed after pressing stop. 
	if not running:
		reset['state'] = 'disabled'
		label['text'] = '00:00:00'
	# If reset is pressed while the stopwatch is running. 
	else:
		label['text'] = '00:00:00'


root = Tkinter.Tk()
root.title("Stopwatch")

# Fixing the window size.
root.minsize(width=250, height=70)
label = Tkinter.Label(root, text='Ready!', fg='black', font='Verdana 30 bold')
label.pack()
f = Tkinter.Frame(root)
start = Tkinter.Button(f, text='Start', width=6, command=lambda: Start(label))
stop = Tkinter.Button(f, text='Stop', width=6, state='disabled', command=Stop)
reset = Tkinter.Button(f, text='Reset', width=6, state='disabled', command=lambda: Reset(label))
f.pack(anchor='center', pady=5)
start.pack(side='left')
stop.pack(side='left')
reset.pack(side='left')
root.mainloop()



File: projects/Battery_notification/battery.py

# pip install psutil
import psutil

battery = psutil.sensors_battery()
plugged = battery.power_plugged
percent = battery.percent

if percent <= 30 and plugged!=True:
 
    # pip install py-notifier
    # pip install win10toast
    from pynotifier import Notification

    Notification(
        title="Battery Low",
        description=str(percent) + "% Battery remain!!",
        duration=5,  # Duration in seconds
        
    ).send()



File: projects/export_mysql_to_csv_send_to_wocom/export_mysql_data_to_csv.py

# -*- coding: utf-8 -*-
import codecs
import configparser
import csv
import time

import pymysql
import requests as requests

ini = configparser.ConfigParser()
ini.read('config.ini')
wecom_key = ini.get('wecom', 'key')


def sql(sqlstr):  # 定义一个执行SQL的函数
    conn = pymysql.connect(host=ini.get('db', 'host'), user=ini.get('db', 'username'),
                           password=ini.get('db', 'password'), database=ini.get('db', 'database'))
    cursor = conn.cursor()
    cursor.execute(sqlstr)
    results = cursor.fetchall()  # 获取查询的所有记录
    cursor.close()
    conn.close()
    return results


def read_mysql_to_csv(filename):
    with codecs.open(filename=filename, mode='w', encoding='utf-8') as f:
        write = csv.writer(f, dialect='excel')
        results = sql(
            ini.get('message', 'sql')
        )
        for result in results:
            write.writerow(result)


def upload_file_robots(filename):
    url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=%(key)s&type=file" % {"key": wecom_key}
    data = {'file': open(filename, 'rb')}  # post jason
    response = requests.post(url=url, files=data)  # post 请求上传文件
    json_res = response.json()  # 返回转为json
    media_id = json_res['media_id']  # 提取返回ID
    return media_id  # 返回请求状态


def send_file_robots(media_id):
    wx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%(key)s' % {"key": wecom_key}
    data = {"msgtype": "file",
            "file": {"media_id": media_id}}  # post json
    r = requests.post(url=wx_url, json=data)
    return r


if __name__ == '__main__':
    filename = ini.get('message', 'title') + time.strftime('%y%m%d') + '.csv'
    read_mysql_to_csv(filename)
    print(send_file_robots(upload_file_robots(filename)))



File: projects/Convert_numbers_to_word/converter.py


one_digit_words = {
        '0': ["zero"],
        '1': ["one"],
        '2': ["two", "twen"],
        '3': ["three", "thir"],
        '4': ["four", "for"],
        '5': ["five", "fif"],
        '6': ["six"],
        '7': ["seven"],
        '8': ["eight"],
        '9': ["nine"],
    }

two_digit_words = ["ten", "eleven", "twelve"]
hundred = "hundred"
large_sum_words = ["thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion"]

def converter(n):
    word = []

    if n.startswith('-'):
        word.append("(negative)")
        n = n[1:]
    
    if len(n) % 3 != 0 and len(n) > 3:
        n = n.zfill(3 * (((len(n)-1) // 3) + 1))

    sum_list = [n[i:i + 3] for i in range(0, len(n), 3)]
    skip = False

    for i, num in enumerate(sum_list):
        if num != '000': skip = False
        
        for _ in range(len(num)):
            num = num.lstrip('0')
            if len(num) == 1:
                if (len(sum_list) > 1 or (len(sum_list) == 1 and len(sum_list[0]) == 3)) and i == len(sum_list) - 1 and (word[-1] in large_sum_words or hundred in word[-1]):
                    word.append("and")
                word.append(one_digit_words[num][0])
                num = num[1:]
                break

            if len(num) == 2:
                if num[0] != '0':
                    if (len(sum_list) > 1 or (len(sum_list) == 1 and len(sum_list[0]) == 3)) and i == len(sum_list) - 1:
                        word.append("and")
                    if num.startswith('1'):
                        if int(num[1]) in range(3):
                            word.append(two_digit_words[int(num[1])])
                        else:
                            number = one_digit_words[num[1]][1 if int(num[1]) in range(3, 6, 2) else 0] 
                            word.append(number + ("teen" if not number[-1] == 't' else "een"))
                    else:
                        word.append(one_digit_words[num[0]][1 if int(num[0]) in range(2, 6) else 0] + ("ty " if num[0] != '8' else 'y ') + (one_digit_words[num[1]][0] if num[1] != '0' else ""))
                    break
                else:
                    num = num[1:]
                    continue
                
            if len(num) == 3:
                if num[0] != '0':
                    word.append(one_digit_words[num[0]][0] + " " + hundred)
                    if num[1:] == '00': break
                num = num[1:]
 
        if len(sum_list[i:]) > 1 and not skip:
            word.append(large_sum_words[len(sum_list[i:]) - 2])
            skip = True
    
    word = " ".join(map(str.strip, word))
    return word[0].lstrip().upper() + word[1:].rstrip().lower() if "negative" not in word else word[:11].lstrip() + word[11].upper() + word[12:].rstrip().lower()

if __name__ == "__main__":
    while True:
        try:
            n = input("Enter any number to convert it into words or 'exit' to stop: ")
            if n == "exit":
                break
            int(n)
            print(n, "-->", converter(n))
        except ValueError:
            print("Error: Invalid Number!")


File: projects/Internet_connection_check/internet_connection_check.py

import requests
from requests.exceptions import ConnectionError

def internet_connection_test():
	url = 'https://www.google.com/'
	print(f'Attempting to connect to {url} to determine internet connection status.')
	
	try:
		print(url)
		resp = requests.get(url, timeout = 10)
		resp.text
		resp.status_code
		print(f'Connection to {url} was successful.')
		return True
	except ConnectionError as e:
		requests.ConnectionError
		print(f'Failed to connect to {url}.')
		return False
	except:
		print(f'Failed with unparsed reason.')
		return False

internet_connection_test()



File: projects/chatbot/simple-bot.py

import asyncio
from wechaty import Wechaty, Message

async def on_message(msg: Message):
    if msg.text() == 'ding':
        await msg.say('dong')
    
async def main():
    bot = Wechaty()
    bot.on('message', on_message)
    await bot.start()

asyncio.run(main())



File: projects/chatbot/bot.py

"""example code for ding-dong-bot with oop style"""
from typing import List, Optional, Union
import asyncio
from datetime import datetime
from wechaty_puppet import get_logger
from wechaty import (
    MessageType,
    FileBox,
    RoomMemberQueryFilter,
    Wechaty,
    Contact,
    Room,
    Message,
    Image,
    MiniProgram,
    Friendship,
    FriendshipType,
    EventReadyPayload
)

logger = get_logger(__name__)


class MyBot(Wechaty):
    """
    listen wechaty event with inherited functions, which is more friendly for
    oop developer
    """

    def __init__(self) -> None:
        """initialization function
        """
        self.login_user: Optional[Contact] = None
        super().__init__()

    async def on_ready(self, payload: EventReadyPayload) -> None:
        """listen for on-ready event"""
        logger.info('ready event %s...', payload)

    # pylint: disable=R0912,R0914,R0915
    async def on_message(self, msg: Message) -> None:
        """
        listen for message event
        """
        from_contact: Contact = msg.talker()
        text: str = msg.text()
        room: Optional[Room] = msg.room()
        msg_type: MessageType = msg.type()
        file_box: Optional[FileBox] = None
        if text == 'ding':
            conversation: Union[
                Room, Contact] = from_contact if room is None else room
            await conversation.ready()
            await conversation.say('dong')
            file_box = FileBox.from_url(
                'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/'
                'u=1116676390,2305043183&fm=26&gp=0.jpg',
                name='ding-dong.jpg')
            await conversation.say(file_box)

        elif msg_type == MessageType.MESSAGE_TYPE_IMAGE:
            logger.info('receving image file')
            # file_box: FileBox = await msg.to_file_box()
            image: Image = msg.to_image()

            hd_file_box: FileBox = await image.hd()
            await hd_file_box.to_file('./hd-image.jpg', overwrite=True)

            thumbnail_file_box: FileBox = await image.thumbnail()
            await thumbnail_file_box.to_file('./thumbnail-image.jpg', overwrite=True)
            artwork_file_box: FileBox = await image.artwork()
            await artwork_file_box.to_file('./artwork-image.jpg', overwrite=True)
            # reply the image
            await msg.say(hd_file_box)

        # pylint: disable=C0301
        elif msg_type in [MessageType.MESSAGE_TYPE_AUDIO, MessageType.MESSAGE_TYPE_ATTACHMENT, MessageType.MESSAGE_TYPE_VIDEO]:
            logger.info('receving file ...')
            file_box = await msg.to_file_box()
            if file_box:
                await file_box.to_file(file_box.name)

        elif msg_type == MessageType.MESSAGE_TYPE_MINI_PROGRAM:
            logger.info('receving mini-program ...')
            mini_program: Optional[MiniProgram] = await msg.to_mini_program()
            if mini_program:
                await msg.say(mini_program)

        elif text == 'get room members' and room:
            logger.info('get room members ...')
            room_members: List[Contact] = await room.member_list()
            names: List[str] = [
                room_member.name for room_member in room_members]
            await msg.say('\n'.join(names))

        elif text.startswith('remove room member:'):
            logger.info('remove room member:')
            if not room:
                await msg.say('this is not room zone')
                return

            room_member_name = text[len('remove room member:') + 1:]

            room_member: Optional[Contact] = await room.member(
                query=RoomMemberQueryFilter(name=room_member_name)
            )
            if room_member:
                if self.login_user and self.login_user.contact_id in room.payload.admin_ids:
                    await room.delete(room_member)
                else:
                    await msg.say('登录用户不是该群管理员...')

            else:
                await msg.say(f'can not fine room member by name<{room_member_name}>')
        elif text.startswith('get room topic'):
            logger.info('get room topic')
            if room:
                topic: Optional[str] = await room.topic()
                if topic:
                    await msg.say(topic)

        elif text.startswith('rename room topic:'):
            logger.info('rename room topic ...')
            if room:
                new_topic = text[len('rename room topic:') + 1:]
                await msg.say(new_topic)
        elif text.startswith('add new friend:'):
            logger.info('add new friendship ...')
            identity_info = text[len('add new friend:'):]
            weixin_contact: Optional[Contact] = await self.Friendship.search(weixin=identity_info)
            phone_contact: Optional[Contact] = await self.Friendship.search(phone=identity_info)
            contact: Optional[Contact] = weixin_contact or phone_contact
            if contact:
                await self.Friendship.add(contact, 'hello world ...')

        elif text.startswith('at me'):
            if room:
                talker = msg.talker()
                await room.say('hello', mention_ids=[talker.contact_id])

        elif text.startswith('my alias'):
            talker = msg.talker()
            alias = await talker.alias()
            await msg.say('your alias is:' + (alias or ''))

        elif text.startswith('set alias:'):
            talker = msg.talker()
            new_alias = text[len('set alias:'):]

            # set your new alias
            alias = await talker.alias(new_alias)
            # get your new alias
            alias = await talker.alias()
            await msg.say('your new alias is:' + (alias or ''))

        elif text.startswith('find friends:'):
            friend_name: str = text[len('find friends:'):]
            friend = await self.Contact.find(friend_name)
            if friend:
                logger.info('find only one friend <%s>', friend)

            friends: List[Contact] = await self.Contact.find_all(friend_name)

            logger.info('find friend<%d>', len(friends))
            logger.info(friends)

        else:
            pass

        if msg.type() == MessageType.MESSAGE_TYPE_UNSPECIFIED:
            talker = msg.talker()
            assert isinstance(talker, Contact)

    async def on_login(self, contact: Contact) -> None:
        """login event

        Args:
            contact (Contact): the account logined
        """
        logger.info('Contact<%s> has logined ...', contact)
        self.login_user = contact

    async def on_friendship(self, friendship: Friendship) -> None:
        """when receive a new friendship application, or accept a new friendship

        Args:
            friendship (Friendship): contains the status and friendship info,
                eg: hello text, friend contact object
        """
        MAX_ROOM_MEMBER_COUNT = 500
        # 1. receive a new friendship from someone
        if friendship.type() == FriendshipType.FRIENDSHIP_TYPE_RECEIVE:
            hello_text: str = friendship.hello()

            # accept friendship when there is a keyword in hello text
            if 'wechaty' in hello_text.lower():
                await friendship.accept()

        # 2. you have a new friend to your contact list
        elif friendship.type() == FriendshipType.FRIENDSHIP_TYPE_CONFIRM:
            # 2.1 invite the user to wechaty group
            # find the topic of room which contains Wechaty keyword
            wechaty_rooms: List[Room] = await self.Room.find_all('Wechaty')

            # 2.2 find the suitable room
            for wechaty_room in wechaty_rooms:
                members: List[Contact] = await wechaty_room.member_list()
                if len(members) < MAX_ROOM_MEMBER_COUNT:
                    contact: Contact = friendship.contact()
                    await wechaty_room.add(contact)
                    break

    async def on_room_join(self, room: Room, invitees: List[Contact],
                           inviter: Contact, date: datetime) -> None:
        """on_room_join when there are new contacts to the room

        Args:
                room (Room): the room instance
                invitees (List[Contact]): the new contacts to the room
                inviter (Contact): the inviter who share qrcode or manual invite someone
                date (datetime): the datetime to join the room
        """
        # 1. say something to welcome the new arrivals
        names: List[str] = []
        for invitee in invitees:
            await invitee.ready()
            names.append(invitee.name)

        await room.say(f'welcome {",".join(names)} to the wechaty group !')


async def main() -> None:
    """doc"""
    bot = MyBot()
    await bot.start()

asyncio.run(main())



File: projects/Alarm clock/alarm_clock.py

# Import Required Library
from tkinter import *
import datetime
import time
import winsound
from threading import *

# Create Object
root = Tk()

# Set geometry
root.geometry("400x200")

# Use Threading
def Threading():
	t1=Thread(target=alarm)
	t1.start()

def alarm():
	# Infinite Loop
	while True:
		# Set Alarm
		set_alarm_time = f"{hour.get()}:{minute.get()}:{second.get()}"

		# Wait for one seconds
		time.sleep(1)

		# Get current time
		current_time = datetime.datetime.now().strftime("%H:%M:%S")
		print(current_time,set_alarm_time)

		# Check whether set alarm is equal to current time or not
		if current_time == set_alarm_time:
			print("Time to Wake up")
			# Playing sound
			winsound.PlaySound("sound.wav",winsound.SND_ASYNC)

# Add Labels, Frame, Button, Optionmenus
Label(root,text="Alarm Clock",font=("Helvetica 20 bold"),fg="red").pack(pady=10)
Label(root,text="Set Time",font=("Helvetica 15 bold")).pack()

frame = Frame(root)
frame.pack()

hour = StringVar(root)
hours = ('00', '01', '02', '03', '04', '05', '06', '07',
		'08', '09', '10', '11', '12', '13', '14', '15',
		'16', '17', '18', '19', '20', '21', '22', '23', '24'
		)
hour.set(hours[0])

hrs = OptionMenu(frame, hour, *hours)
hrs.pack(side=LEFT)

minute = StringVar(root)
minutes = ('00', '01', '02', '03', '04', '05', '06', '07',
		'08', '09', '10', '11', '12', '13', '14', '15',
		'16', '17', '18', '19', '20', '21', '22', '23',
		'24', '25', '26', '27', '28', '29', '30', '31',
		'32', '33', '34', '35', '36', '37', '38', '39',
		'40', '41', '42', '43', '44', '45', '46', '47',
		'48', '49', '50', '51', '52', '53', '54', '55',
		'56', '57', '58', '59', '60')
minute.set(minutes[0])

mins = OptionMenu(frame, minute, *minutes)
mins.pack(side=LEFT)

second = StringVar(root)
seconds = ('00', '01', '02', '03', '04', '05', '06', '07',
		'08', '09', '10', '11', '12', '13', '14', '15',
		'16', '17', '18', '19', '20', '21', '22', '23',
		'24', '25', '26', '27', '28', '29', '30', '31',
		'32', '33', '34', '35', '36', '37', '38', '39',
		'40', '41', '42', '43', '44', '45', '46', '47',
		'48', '49', '50', '51', '52', '53', '54', '55',
		'56', '57', '58', '59', '60')
second.set(seconds[0])

secs = OptionMenu(frame, second, *seconds)
secs.pack(side=LEFT)

Button(root,text="Set Alarm",font=("Helvetica 15"),command=Threading).pack(pady=20)

# Execute Tkinter
root.mainloop()



File: projects/Duplicate files remover/duplicatefileremover.py

import hashlib
import os

# Returns the hash string of the given file name


def hashFile(filename):
    # For large files, if we read it all together it can lead to memory overflow, So we take a blocksize to read at a time
    BLOCKSIZE = 65536
    hasher = hashlib.md5()
    with open(filename, 'rb') as file:
        # Reads the particular blocksize from file
        buf = file.read(BLOCKSIZE)
        while(len(buf) > 0):
            hasher.update(buf)
            buf = file.read(BLOCKSIZE)
    return hasher.hexdigest()


if __name__ == "__main__":
    # Dictionary to store the hash and filename
    hashMap = {}

    # List to store deleted files
    deletedFiles = []
    filelist = [f for f in os.listdir() if os.path.isfile(f)]
    for f in filelist:
        key = hashFile(f)
        # If key already exists, it deletes the file
        if key in hashMap.keys():
            deletedFiles.append(f)
            os.remove(f)
        else:
            hashMap[key] = f
    if len(deletedFiles) != 0:
        print('Deleted Files')
        for i in deletedFiles:
            print(i)
    else:
        print('No duplicate files found')



File: projects/Speaking_Dictionary/SpeakingDictionary.py

import pyttsx3
from PyDictionary import PyDictionary
import speech_recognition as spr
from gtts import gTTS
import os

#Speaking class
class Speak:
    def SpeakWord(self, audio):
        #Having initial constructor of pyttsx3
        pSpeakEngine= pyttsx3.init('sapi5')
        pVoices= pSpeakEngine.getProperty('voices')

        #Speaking audio that got as parameter
        pSpeakEngine.setProperty('voices', pVoices[0].id)
        pSpeakEngine.say(audio)
        pSpeakEngine.runAndWait()

#Create Recognizer, Microphone instance
sRecog= spr.Recognizer()
sMic= spr.Microphone()

#Capture voice from microphone
with sMic as source:
    print("Speak 'Hello' to initiate Speaking Dictionary!")
    print("----------------------------------------------")

    sRecog.adjust_for_ambient_noise(source, duration= .2)
    rAudio= sRecog.listen(source)

    szHello= sRecog.recognize_google(rAudio, language= 'en-US') 
    szHello= szHello.lower()

#If you said 'Hello', initialize the speaking dictionary
if 'hello' in szHello:
    sSpeak= Speak()
    pDict= PyDictionary()

    print("Which word do you want to find? Please speak slowly.")
    sSpeak.SpeakWord("Which word do you want to find Please speak slowly")
    
    try:
        sRecog2= spr.Recognizer()
        sMic2= spr.Microphone()

        #Capture the word that the user want to find the meaning of 
        with sMic2 as source2:
            sRecog2.adjust_for_ambient_noise(source2, duration= .2)
            rAudio2= sRecog2.listen(source2)
                
            szInput= sRecog2.recognize_google(rAudio2, language= 'en-US')
            
            try:
                #Make sure that the recognizer got the correct word
                print("Did you said "+ szInput+ "? Please answer with yes or no.")
                sSpeak.SpeakWord("Did you said "+ szInput+ "Please answer with yes or no")
                
                sRecog2.adjust_for_ambient_noise(source2, duration= .2)
                rAudioYN= sRecog2.listen(source2)

                szYN= sRecog2.recognize_google(rAudioYN)
                szYN= szYN.lower()

                #If the user said 'yes' (When the recognizer got the correct word)
                if 'yes' in szYN:
                    szMeaning= pDict.meaning(szInput)

                    print("The meaning is ", end="")
                    for i in szMeaning:
                        print(szMeaning[i])
                        sSpeak.SpeakWord("The meaning is"+ str(szMeaning[i]))

                #When the recognizer got the wrong word
                else: sSpeak.SpeakWord("I am sorry Please try again")

            #When the recognizer couldn't understand the answer(yes or no)
            except spr.UnknownValueError: sSpeak.SpeakWord("Unable to understand the input Please try again")
            except spr.RequestError as e: sSpeak.SpeakWord("Unable to provide required output")

    #When the recognizer couldn't understand the word
    except spr.UnknownValueError: sSpeak.SpeakWord("Unable to understand the input Please try again")
    except spr.RequestError as e: sSpeak.SpeakWord("Unable to provide required output")




File: projects/detect_align_faces/main.py

#!/usr/bin/env python3
#
# Copyright(C) 2021 wuyaoping
#


import numpy as np
import os.path as osp
import sys
import cv2
import dlib

OUT_SIZE = (224, 224)
LEFT_EYE_RANGE = (36, 42)
RIGHT_EYE_RABGE = (42, 48)
LEFT_EYE_POS = (0.35, 0.3815)
DAT_PATH = "./dat/shape_predictor_68_face_landmarks.dat"


def main(files):
    detector = dlib.get_frontal_face_detector()
    sp = dlib.shape_predictor(DAT_PATH)

    for file in files:
        img = cv2.imread(file, cv2.IMREAD_ANYCOLOR)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        faces = detect_align_faces(detector, sp, img)
        for (idx, face) in enumerate(faces):
            face = cv2.cvtColor(face, cv2.COLOR_RGB2BGR)
            filename, ext = osp.splitext(file)
            filename += '_face_{:03}'.format(idx) + ext
            cv2.imwrite(filename, face)


def detect_align_faces(detector, sp, img):
    faces = detector(img, 1)
    res = []
    for face in faces:
        shape = sp(img, face)
        left, right = shape_to_pos(shape)
        left_center = np.mean(left, axis=0)
        right_center = np.mean(right, axis=0)

        dx = right_center[0] - left_center[0]
        dy = right_center[1] - left_center[1]
        angle = np.degrees(np.arctan2(dy, dx))
        dist = np.sqrt(dy ** 2 + dx ** 2)
        out_dist = OUT_SIZE[0] * (1 - 2 * LEFT_EYE_POS[0])
        scale = out_dist / dist
        center = ((left_center + right_center) // 2).tolist()

        mat = cv2.getRotationMatrix2D(center, angle, scale)
        mat[0, 2] += (0.5 * OUT_SIZE[0] - center[0])
        mat[1, 2] += (LEFT_EYE_POS[1] * OUT_SIZE[1] - center[1])
        res_face = cv2.warpAffine(img, mat, OUT_SIZE, flags=cv2.INTER_CUBIC)
        res.append(res_face)

    return res


def shape_to_pos(shape):
    parts = []
    for p in shape.parts():
        parts.append((p.x, p.y))

    left = parts[LEFT_EYE_RANGE[0]: LEFT_EYE_RANGE[-1]]
    right = parts[RIGHT_EYE_RABGE[0]: RIGHT_EYE_RABGE[-1]]

    return (np.array(left), np.array(right))


if __name__ == '__main__':
    main(sys.argv[1:])



File: projects/Convert_JSON_to_CSV/converter.py

import json

if __name__ == '__main__':
    try:
        with open('input.json', 'r') as f:
            data = json.loads(f.read())

        output = ','.join([*data[0]])
        for obj in data:
            output += f'\n{obj["Name"]},{obj["age"]},{obj["birthyear"]}'

        with open('output.csv', 'w') as f:
            f.write(output)
    except Exception as ex:
        print(f'Error: {str(ex)}')



File: projects/Number_guessing_game/main.py

import random

print("Number guessing game")

# randint function to generate the
# random number b/w 1 to 9
number = random.randint(1, 9)

# number of chances to be given
# to the user to guess the number
# or it is the inputs given by user
# into input box here number of
# chances are 5
chances = 0

print("Guess a number (between 1 and 9):")

# While loop to count the number
# of chances
while True:

    # Enter a number between 1 to 9
    guess = int(input())

    # Compare the user entered number
    # with the number to be guessed
    if guess == number:

        # if number entered by user
        # is same as the generated
        # number by randint function then
        # break from loop using loop
        # control statement "break"
        print(
            f'CONGRATULATIONS! YOU HAVE GUESSED THE \
            NUMBER {number} IN {chances} ATTEMPTS!')
        # Printing final statement using the f-strings method;
        break

    # Check if the user entered
    # number is smaller than
    # the generated number
    elif guess < number:
        print("Your guess was too low: Guess a number higher than", guess)

    # The user entered number is
    # greater than the generated
    # number
    else:
        print("Your guess was too high: Guess a number lower than", guess)

    # Increase the value of chance by 1
    chances += 1
    



File: projects/AudioBook/Audio-book.py

#Importing Libraries
#Importing Google Text to Speech library
from gtts import gTTS

#Importing PDF reader PyPDF2
import PyPDF2

#Open file Path
pdf_File = open('name.pdf', 'rb') 

#Create PDF Reader Object
pdf_Reader = PyPDF2.PdfFileReader(pdf_File)
count = pdf_Reader.numPages # counts number of pages in pdf
textList = []

#Extracting text data from each page of the pdf file
for i in range(count):
   try:
    page = pdf_Reader.getPage(i)    
    textList.append(page.extractText())
   except:
       pass

#Converting multiline text to single line text
textString = " ".join(textList)

print(textString)

#Set language to english (en)
language = 'en'

#Call GTTS
myAudio = gTTS(text=textString, lang=language, slow=False)

#Save as mp3 file
myAudio.save("Audio.mp3")



File: projects/Create_calculator_app/calculator.py

# -*- coding: utf-8 -*-
from tkinter import Tk, END, Entry, N, E, S, W, Button
from tkinter import font
from tkinter import Label
from functools import partial


def get_input(entry, argu):
    entry.insert(END, argu)


def backspace(entry):
    input_len = len(entry.get())
    entry.delete(input_len - 1)


def clear(entry):
    entry.delete(0, END)


def calc(entry):
    input_info = entry.get()
    try:
        output = str(eval(input_info.strip()))
    except ZeroDivisionError:
        popupmsg()
        output = ""
    clear(entry)
    entry.insert(END, output)


def popupmsg():
    popup = Tk()
    popup.resizable(0, 0)
    popup.geometry("120x100")
    popup.title("Alert")
    label = Label(popup, text="Cannot divide by 0 ! \n Enter valid values")
    label.pack(side="top", fill="x", pady=10)
    B1 = Button(popup, text="Okay", bg="#DDDDDD", command=popup.destroy)
    B1.pack()


def cal():
    root = Tk()
    root.title("Calc")
    root.resizable(0, 0)

    entry_font = font.Font(size=15)
    entry = Entry(root, justify="right", font=entry_font)
    entry.grid(row=0, column=0, columnspan=4,
               sticky=N + W + S + E, padx=5, pady=5)

    cal_button_bg = '#FF6600'
    num_button_bg = '#4B4B4B'
    other_button_bg = '#DDDDDD'
    text_fg = '#FFFFFF'
    button_active_bg = '#C0C0C0'

    num_button = partial(Button, root, fg=text_fg, bg=num_button_bg,
                         padx=10, pady=3, activebackground=button_active_bg)
    cal_button = partial(Button, root, fg=text_fg, bg=cal_button_bg,
                         padx=10, pady=3, activebackground=button_active_bg)

    button7 = num_button(text='7', bg=num_button_bg,
                         command=lambda: get_input(entry, '7'))
    button7.grid(row=2, column=0, pady=5)

    button8 = num_button(text='8', command=lambda: get_input(entry, '8'))
    button8.grid(row=2, column=1, pady=5)

    button9 = num_button(text='9', command=lambda: get_input(entry, '9'))
    button9.grid(row=2, column=2, pady=5)

    button10 = cal_button(text='+', command=lambda: get_input(entry, '+'))
    button10.grid(row=4, column=3, pady=5)

    button4 = num_button(text='4', command=lambda: get_input(entry, '4'))
    button4.grid(row=3, column=0, pady=5)

    button5 = num_button(text='5', command=lambda: get_input(entry, '5'))
    button5.grid(row=3, column=1, pady=5)

    button6 = num_button(text='6', command=lambda: get_input(entry, '6'))
    button6.grid(row=3, column=2, pady=5)

    button11 = cal_button(text='-', command=lambda: get_input(entry, '-'))
    button11.grid(row=3, column=3, pady=5)

    button1 = num_button(text='1', command=lambda: get_input(entry, '1'))
    button1.grid(row=4, column=0, pady=5)

    button2 = num_button(text='2', command=lambda: get_input(entry, '2'))
    button2.grid(row=4, column=1, pady=5)

    button3 = num_button(text='3', command=lambda: get_input(entry, '3'))
    button3.grid(row=4, column=2, pady=5)

    button12 = cal_button(text='*', command=lambda: get_input(entry, '*'))
    button12.grid(row=2, column=3, pady=5)

    button0 = num_button(text='0', command=lambda: get_input(entry, '0'))
    #button0.grid(row=5, column=0, columnspan=2, padx=3, pady=5, sticky=N + S + E + W)
    button0.grid(row=5, column=0,  pady=5)

    button13 = num_button(text='.', command=lambda: get_input(entry, '.'))
    button13.grid(row=5, column=1, pady=5)

    button14 = Button(root, text='/', fg=text_fg, bg=cal_button_bg, padx=10, pady=3,
                      command=lambda: get_input(entry, '/'))
    button14.grid(row=1, column=3, pady=5)

    button15 = Button(root, text='<-', bg=other_button_bg, padx=10, pady=3,
                      command=lambda: backspace(entry), activebackground=button_active_bg)
    button15.grid(row=1, column=0, columnspan=2,
                  padx=3, pady=5, sticky=N + S + E + W)

    button16 = Button(root, text='C', bg=other_button_bg, padx=10, pady=3,
                      command=lambda: clear(entry), activebackground=button_active_bg)
    button16.grid(row=1, column=2, pady=5)

    button17 = Button(root, text='=', fg=text_fg, bg=cal_button_bg, padx=10, pady=3,
                      command=lambda: calc(entry), activebackground=button_active_bg)
    button17.grid(row=5, column=3, pady=5)

    button18 = Button(root, text='^', fg=text_fg, bg=cal_button_bg, padx=10, pady=3,
                      command=lambda: get_input(entry, '**'))
    button18.grid(row=5, column=2, pady=5)
    def quit():
        exit['command'] = root.quit()
    exit = Button(root, text='Quit', fg='white', bg='black', command=quit, height=1, width=7)
    exit.grid(row=6, column=1)

    root.mainloop()


if __name__ == '__main__':
    cal()



File: projects/steganography/dct.py

#!/usr/bin/env python3
#
# Copyright(C) 2021 wuyaoping
#
# DCT algorithm has great a robust but lower capacity.

import numpy as np
import os.path as osp
import cv2

FLAG = '%'
# Select a part location from the middle frequency
LOC_MAX = (4, 1)
LOC_MIN = (3, 2)
# The difference between MAX and MIN,
# bigger to improve robust but make picture low quality.
ALPHA = 1

# Quantizer table
TABLE = np.array([
    [16, 11, 10, 16, 24, 40, 51, 61],
    [12, 12, 14, 19, 26, 58, 60, 55],
    [14, 13, 16, 24, 40, 57, 69, 56],
    [14, 17, 22, 29, 51, 87, 80, 62],
    [18, 22, 37, 56, 68, 109, 103, 77],
    [24, 35, 55, 64, 81, 104, 113, 92],
    [49, 64, 78, 87, 103, 121, 120, 101],
    [72, 92, 95, 98, 112, 100, 103, 99]
])


def insert(path, txt):
    img = cv2.imread(path, cv2.IMREAD_ANYCOLOR)
    txt = "{}{}{}".format(len(txt), FLAG, txt)
    row, col = img.shape[:2]
    max_bytes = (row // 8) * (col // 8) // 8
    assert max_bytes >= len(
        txt), "Message overflow the capacity:{}".format(max_bytes)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
    # Just use the Y plane to store message, you can use all plane
    y, u, v = cv2.split(img)
    y = y.astype(np.float32)
    blocks = []
    # Quantize blocks
    for r_idx in range(0, 8 * (row // 8), 8):
        for c_idx in range(0, 8 * (col // 8), 8):
            quantized = cv2.dct(y[r_idx: r_idx+8, c_idx: c_idx+8]) / TABLE
            blocks.append(quantized)
    for idx in range(len(txt)):
        encode(blocks[idx*8: (idx+1)*8], txt[idx])

    idx = 0
    # Restore Y plane
    for r_idx in range(0, 8 * (row // 8), 8):
        for c_idx in range(0, 8 * (col // 8), 8):
            y[r_idx: r_idx+8, c_idx: c_idx+8] = cv2.idct(blocks[idx] * TABLE)
            idx += 1
    y = y.astype(np.uint8)
    img = cv2.cvtColor(cv2.merge((y, u, v)), cv2.COLOR_YUV2BGR)
    filename, _ = osp.splitext(path)
    # DCT algorithm can save message even if jpg
    filename += '_dct_embeded' + '.jpg'
    cv2.imwrite(filename, img)
    return filename


# Encode a char into the blocks
def encode(blocks, data):
    data = ord(data)
    for idx in range(len(blocks)):
        bit_val = (data >> idx) & 1
        max_val = max(blocks[idx][LOC_MAX], blocks[idx][LOC_MIN])
        min_val = min(blocks[idx][LOC_MAX], blocks[idx][LOC_MIN])
        if max_val - min_val <= ALPHA:
            max_val = min_val + ALPHA + 1e-3
        if bit_val == 1:
            blocks[idx][LOC_MAX] = max_val
            blocks[idx][LOC_MIN] = min_val
        else:
            blocks[idx][LOC_MAX] = min_val
            blocks[idx][LOC_MIN] = max_val


# Decode a char from the blocks
def decode(blocks):
    val = 0
    for idx in range(len(blocks)):
        if blocks[idx][LOC_MAX] > blocks[idx][LOC_MIN]:
            val |= 1 << idx
    return chr(val)


def extract(path):
    img = cv2.imread(path, cv2.IMREAD_ANYCOLOR)
    row, col = img.shape[:2]
    max_bytes = (row // 8) * (col // 8) // 8
    img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
    y, u, v = cv2.split(img)
    y = y.astype(np.float32)
    blocks = []
    for r_idx in range(0, 8 * (row // 8), 8):
        for c_idx in range(0, 8 * (col // 8), 8):
            quantized = cv2.dct(y[r_idx: r_idx+8, c_idx: c_idx+8]) / TABLE
            blocks.append(quantized)
    res = ''
    idx = 0
    # Extract the length of the message
    while idx < max_bytes:
        ch = decode(blocks[idx*8: (idx+1)*8])
        idx += 1
        if ch == FLAG:
            break
        res += ch
    end = int(res) + idx
    assert end <= max_bytes, "Input image isn't correct."
    res = ''
    while idx < end:
        res += decode(blocks[idx*8: (idx+1)*8])
        idx += 1
    return res


if __name__ == '__main__':
    data = 'A collection of simple python mini projects to enhance your Python skills.'
    res_path = insert('./example.png', data)
    res = extract(res_path)
    print(res)



File: projects/steganography/lsb.py

#!/usr/bin/env python3
#
# Copyright(C) 2021 wuyaoping
#
# LSB algorithm has a great capacity but fragile.

import cv2
import math
import os.path as osp
import numpy as np

# Insert data in the low bit.
# Lower make picture less loss but lower capacity.
BITS = 2

HIGH_BITS = 256 - (1 << BITS)
LOW_BITS = (1 << BITS) - 1
BYTES_PER_BYTE = math.ceil(8 / BITS)
FLAG = '%'


def insert(path, txt):
    img = cv2.imread(path, cv2.IMREAD_ANYCOLOR)
    # Save origin shape to restore image
    ori_shape = img.shape
    max_bytes = ori_shape[0] * ori_shape[1] // BYTES_PER_BYTE
    # Encode message with length
    txt = '{}{}{}'.format(len(txt), FLAG, txt)
    assert max_bytes >= len(
        txt), "Message overflow the capacity:{}".format(max_bytes)
    data = np.reshape(img, -1)
    for (idx, val) in enumerate(txt):
        encode(data[idx*BYTES_PER_BYTE: (idx+1) * BYTES_PER_BYTE], val)

    img = np.reshape(data, ori_shape)
    filename, _ = osp.splitext(path)
    # png is lossless encode that can restore message correctly
    filename += '_lsb_embeded' + ".png"
    cv2.imwrite(filename, img)
    return filename


def extract(path):
    img = cv2.imread(path, cv2.IMREAD_ANYCOLOR)
    data = np.reshape(img, -1)
    total = data.shape[0]
    res = ''
    idx = 0
    # Decode message length
    while idx < total // BYTES_PER_BYTE:
        ch = decode(data[idx*BYTES_PER_BYTE: (idx+1)*BYTES_PER_BYTE])
        idx += 1
        if ch == FLAG:
            break
        res += ch
    end = int(res) + idx
    assert end <= total // BYTES_PER_BYTE, "Input image isn't correct."

    res = ''
    while idx < end:
        res += decode(data[idx*BYTES_PER_BYTE: (idx+1)*BYTES_PER_BYTE])
        idx += 1
    return res


def encode(block, data):
    data = ord(data)
    for idx in range(len(block)):
        block[idx] &= HIGH_BITS
        block[idx] |= (data >> (BITS * idx)) & LOW_BITS


def decode(block):
    val = 0
    for idx in range(len(block)):
        val |= (block[idx] & LOW_BITS) << (idx * BITS)
    return chr(val)


if __name__ == '__main__':
    data = 'A collection of simple python mini projects to enhance your Python skills.'
    input_path = "./example.png"
    res_path = insert(input_path, data)
    res = extract(res_path)
    print(res)



File: projects/Fetch_current_weather/fetch_current_weather.py

# Python program to find current weather details of any city using openweathermap api 
import requests 
  
# Enter your API key here 
api_key = "Your_API_Key"
  
# base_url variable to store url 
base_url = "http://api.openweathermap.org/data/2.5/weather?"
  
# Give city name 
city_name = input("Enter city name : ") 
   
complete_url = base_url + "appid=" + api_key + "&q=" + city_name 
response = requests.get(complete_url) 
x = response.json() 

if x["cod"] != "404": 
  
    y = x["main"] 
    current_temperature = y["temp"] 
    current_pressure = y["pressure"] 
    current_humidiy = y["humidity"]
    z = x["weather"] 
    weather_description = z[0]["description"] 
    print(" Temperature (in kelvin unit) = " +
                    str(current_temperature) + 
          "\n atmospheric pressure (in hPa unit) = " +
                    str(current_pressure) +
          "\n humidity (in percentage) = " +
                    str(current_humidiy) +
          "\n description = " +
                    str(weather_description)) 
  
else: 
    print(" City Not Found ") 


File: projects/Currency_converter/cc.py

""" 
THis program is capable of converting from one currency to another as of today itself. 
It uses the api at fixer.io and then calculates the value of the currency in terms of the other as of today.
"""

# https://github.com/chavarera/python-mini-projects/issues
# https://medium.com/@cereblanco/setup-black-and-isort-in-vscode-514804590bf9
# Source: https://fixer.io/quickstart
# Imp read: https://stackoverflow.com/questions/3139879/how-do-i-get-currency-exchange-rates-via-an-api-such-as-google-finance


import requests 
import json
import sys
from pprint import pprint

# The below 4 lines bring out the value of currency from the api at fixer.io.  I had to register there, the key is unique to me.
url = "http://data.fixer.io/api/latest?access_key=33ec7c73f8a4eb6b9b5b5f95118b2275"
data = requests.get(url).text
data2 = json.loads(data) #brings whether request was successful,timestamp etc
fx = data2["rates"]

currencies = [
    "AED : Emirati Dirham,United Arab Emirates Dirham",
    "AFN : Afghan Afghani,Afghanistan Afghani",
    "ALL : Albanian Lek,Albania Lek",
    "AMD : Armenian Dram,Armenia Dram",
    "ANG : Dutch Guilder,Netherlands Antilles Guilder,Bonaire,Cura&#231;ao,Saba,Sint Eustatius,Sint Maarten",
    "AOA : Angolan Kwanza,Angola Kwanza",
    "ARS : Argentine Peso,Argentina Peso,Islas Malvinas",
    "AUD : Australian Dollar,Australia Dollar,Christmas Island,Cocos (Keeling) Islands,Norfolk Island,Ashmore and Cartier Islands,Australian Antarctic Territory,Coral Sea Islands,Heard Island,McDonald Islands,Kiribati,Nauru",
    "AWG : Aruban or Dutch Guilder,Aruba Guilder",
    "AZN : Azerbaijan Manat,Azerbaijan Manat",
    "BAM : Bosnian Convertible Mark,Bosnia and Herzegovina Convertible Mark",
    "BBD : Barbadian or Bajan Dollar,Barbados Dollar",
    "BDT : Bangladeshi Taka,Bangladesh Taka",
    "BGN : Bulgarian Lev,Bulgaria Lev",
    "BHD : Bahraini Dinar,Bahrain Dinar",
    "BIF : Burundian Franc,Burundi Franc",
    "BMD : Bermudian Dollar,Bermuda Dollar",
    "BND : Bruneian Dollar,Brunei Darussalam Dollar",
    "BOB : Bolivian Bol&#237;viano,Bolivia Bol&#237;viano",
    "BRL : Brazilian Real,Brazil Real",
    "BSD : Bahamian Dollar,Bahamas Dollar",
    "BTC : Bitcoin,BTC, XBT",
    "BTN : Bhutanese Ngultrum,Bhutan Ngultrum",
    "BWP : Botswana Pula,Botswana Pula",
    "BYN : Belarusian Ruble,Belarus Ruble",
    "BYR : Belarusian Ruble,Belarus Ruble",
    "BZD : Belizean Dollar,Belize Dollar",
    "CAD : Canadian Dollar,Canada Dollar",
    "CDF : Congolese Franc,Congo/Kinshasa Franc",
    "CHF : Swiss Franc,Switzerland Franc,Liechtenstein,Campione d&#039;Italia,B&#252;singen am Hochrhein",
    "CLF : Chilean Unit of Account",
    "CLP : Chilean Peso,Chile Peso",
    "CNY : Chinese Yuan Renminbi,China Yuan Renminbi",
    "COP : Colombian Peso,Colombia Peso",
    "CRC : Costa Rican Colon,Costa Rica Colon",
    "CUC : Cuban Convertible Peso,Cuba Convertible Peso",
    "CUP : Cuban Peso,Cuba Peso",
    "CVE : Cape Verdean Escudo,Cape Verde Escudo",
    "CZK : Czech Koruna,Czech Republic Koruna",
    "DJF : Djiboutian Franc,Djibouti Franc",
    "DKK : Danish Krone,Denmark Krone,Faroe Islands,Greenland",
    "DOP : Dominican Peso,Dominican Republic Peso",
    "DZD : Algerian Dinar,Algeria Dinar",
    "EGP : Egyptian Pound,Egypt Pound,Gaza Strip",
    "ERN : Eritrean Nakfa,Eritrea Nakfa",
    "ETB : Ethiopian Birr,Ethiopia Birr,Eritrea",
    "EUR : Euro,Euro Member Countries,Andorra,Austria,Azores,Baleares (Balearic Islands),Belgium,Canary Islands,Cyprus,Finland,France,French Guiana,French Southern Territories,Germany,Greece,Guadeloupe,Holland (Netherlands),Holy See (Vatican City),Ireland (Eire),Italy,Luxembourg,Madeira Islands,Malta,Monaco,Montenegro,Netherlands",
    "FJD : Fijian Dollar,Fiji Dollar",
    "FKP : Falkland Island Pound,Falkland Islands (Malvinas) Pound",
    "GBP : British Pound,United Kingdom Pound,United Kingdom (UK),England,Northern Ireland,Scotland,Wales,Falkland Islands,Gibraltar,Guernsey,Isle of Man,Jersey,Saint Helena and Ascension,South Georgia and the South Sandwich Islands,Tristan da Cunha",
    "GEL : Georgian Lari,Georgia Lari",
    "GGP : Guernsey Pound,Guernsey Pound",
    "GHS : Ghanaian Cedi,Ghana Cedi",
    "GIP : Gibraltar Pound,Gibraltar Pound",
    "GMD : Gambian Dalasi,Gambia Dalasi",
    "GNF : Guinean Franc,Guinea Franc",
    "GTQ : Guatemalan Quetzal,Guatemala Quetzal",
    "GYD : Guyanese Dollar,Guyana Dollar",
    "HKD : Hong Kong Dollar,Hong Kong Dollar",
    "HNL : Honduran Lempira,Honduras Lempira",
    "HRK : Croatian Kuna,Croatia Kuna",
    "HTG : Haitian Gourde,Haiti Gourde",
    "HUF : Hungarian Forint,Hungary Forint",
    "IDR : Indonesian Rupiah,Indonesia Rupiah,East Timor",
    "ILS : Israeli Shekel,Israel Shekel,Palestinian Territories",
    "IMP : Isle of Man Pound,Isle of Man Pound",
    "INR : Indian Rupee,India Rupee,Bhutan,Nepal",
    "IQD : Iraqi Dinar,Iraq Dinar",
    "IRR : Iranian Rial,Iran Rial",
    "ISK : Icelandic Krona,Iceland Krona",
    "JEP : Jersey Pound,Jersey Pound",
    "JMD : Jamaican Dollar,Jamaica Dollar",
    "JOD : Jordanian Dinar,Jordan Dinar",
    "JPY : Japanese Yen,Japan Yen",
    "KES : Kenyan Shilling,Kenya Shilling",
    "KGS : Kyrgyzstani Som,Kyrgyzstan Som",
    "KHR : Cambodian Riel,Cambodia Riel",
    "KMF : Comorian Franc,Comorian Franc",
    "KPW : North Korean Won,Korea (North) Won",
    "KRW : South Korean Won,Korea (South) Won",
    "KWD : Kuwaiti Dinar,Kuwait Dinar",
    "KYD : Caymanian Dollar,Cayman Islands Dollar",
    "KZT : Kazakhstani Tenge,Kazakhstan Tenge",
    "LAK : Lao Kip,Laos Kip",
    "LBP : Lebanese Pound,Lebanon Pound",
    "LKR : Sri Lankan Rupee,Sri Lanka Rupee",
    "LRD : Liberian Dollar,Liberia Dollar",
    "LSL : Basotho Loti,Lesotho Loti",
    "LTL : Lithuanian litas",
    "LVL : Latvia Lats",
    "LYD : Libyan Dinar,Libya Dinar",
    "MAD : Moroccan Dirham,Morocco Dirham,Western Sahara",
    "MDL : Moldovan Leu,Moldova Leu",
    "MGA : Malagasy Ariary,Madagascar Ariary",
    "MKD : Macedonian Denar,Macedonia Denar",
    "MMK : Burmese Kyat,Myanmar (Burma) Kyat",
    "MNT : Mongolian Tughrik,Mongolia Tughrik",
    "MOP : Macau Pataca,Macau Pataca",
    "MRU : Mauritanian Ouguiya,Mauritania Ouguiya",
    "MUR : Mauritian Rupee,Mauritius Rupee",
    "MVR : Maldivian Rufiyaa,Maldives (Maldive Islands) Rufiyaa",
    "MWK : Malawian Kwacha,Malawi Kwacha",
    "MXN : Mexican Peso,Mexico Peso",
    "MYR : Malaysian Ringgit,Malaysia Ringgit",
    "MZN : Mozambican Metical,Mozambique Metical",
    "NAD : Namibian Dollar,Namibia Dollar",
    "NGN : Nigerian Naira,Nigeria Naira",
    "NIO : Nicaraguan Cordoba,Nicaragua Cordoba",
    "NOK : Norwegian Krone,Norway Krone,Bouvet Island,Svalbard,Jan Mayen,Queen Maud Land,Peter I Island",
    "NPR : Nepalese Rupee,Nepal Rupee,India (unofficially near India-Nepal border)",
    "NZD : New Zealand Dollar,New Zealand Dollar,Cook Islands,Niue,Pitcairn Islands,Tokelau",
    "OMR : Omani Rial,Oman Rial",
    "PAB : Panamanian Balboa,Panama Balboa",
    "PEN : Peruvian Sol,Peru Sol",
    "PGK : Papua New Guinean Kina,Papua New Guinea Kina",
    "PHP : Philippine Peso,Philippines Peso",
    "PKR : Pakistani Rupee,Pakistan Rupee",
    "PLN : Polish Zloty,Poland Zloty",
    "PYG : Paraguayan Guarani,Paraguay Guarani",
    "QAR : Qatari Riyal,Qatar Riyal",
    "RON : Romanian Leu,Romania Leu",
    "RSD : Serbian Dinar,Serbia Dinar",
    "RUB : Russian Ruble,Russia Ruble,Tajikistan,Abkhazia,South Ossetia",
    "RWF : Rwandan Franc,Rwanda Franc",
    "SAR : Saudi Arabian Riyal,Saudi Arabia Riyal",
    "SBD : Solomon Islander Dollar,Solomon Islands Dollar",
    "SCR : Seychellois Rupee,Seychelles Rupee",
    "SDG : Sudanese Pound,Sudan Pound",
    "SEK : Swedish Krona,Sweden Krona",
    "SGD : Singapore Dollar,Singapore Dollar",
    "SHP : Saint Helenian Pound,Saint Helena Pound",
    "SLL : Sierra Leonean Leone,Sierra Leone Leone",
    "SOS : Somali Shilling,Somalia Shilling",
    "SRD : Surinamese Dollar,Suriname Dollar",
    "STN : Sao Tomean Dobra,S&#227;o Tom&#233; and Pr&#237;ncipe Dobra",
    "SVC : Salvadoran Colon,El Salvador Colon",
    "SYP : Syrian Pound,Syria Pound",
    "SZL : Swazi Lilangeni,eSwatini Lilangeni",
    "THB : Thai Baht,Thailand Baht",
    "TJS : Tajikistani Somoni,Tajikistan Somoni",
    "TMT : Turkmenistani Manat,Turkmenistan Manat",
    "TND : Tunisian Dinar,Tunisia Dinar",
    "TOP : Tongan Pa&#039;anga,Tonga Pa&#039;anga",
    "TRY : Turkish Lira,Turkey Lira,North Cyprus",
    "TTD : Trinidadian Dollar,Trinidad and Tobago Dollar,Trinidad,Tobago",
    "TWD : Taiwan New Dollar,Taiwan New Dollar",
    "TZS : Tanzanian Shilling,Tanzania Shilling",
    "UAH : Ukrainian Hryvnia,Ukraine Hryvnia",
    "UGX : Ugandan Shilling,Uganda Shilling",
    "USD : US Dollar,United States Dollar,America,American Samoa,American Virgin Islands,British Indian Ocean Territory,British Virgin Islands,Ecuador,El Salvador,Guam,Haiti,Micronesia,Northern Mariana Islands,Palau,Panama,Puerto Rico,Turks and Caicos Islands,United States Minor Outlying Islands,Wake Island,East Timor",
    "UYU : Uruguayan Peso,Uruguay Peso",
    "UZS : Uzbekistani Som,Uzbekistan Som",
    "VEF : Venezuelan Bol&#237;var,Venezuela Bol&#237;var",
    "VND : Vietnamese Dong,Viet Nam Dong",
    "VUV : Ni-Vanuatu Vatu,Vanuatu Vatu",
    "WST : Samoan Tala,Samoa Tala",
    "XAF : Central African CFA Franc BEAC,Communaut&#233; Financi&#232;re Africaine (BEAC) CFA Franc BEAC,Cameroon,Central African Republic,Chad,Congo/Brazzaville,Equatorial Guinea,Gabon",
    "XAG : Silver Ounce,Silver",
    "XAU : Gold Ounce,Gold",
    "XCD : East Caribbean Dollar,East Caribbean Dollar,Anguilla,Antigua and Barbuda,Dominica,Grenada,The Grenadines and Saint Vincent,Montserrat",
    "XDR : IMF Special Drawing Rights,International Monetary Fund (IMF) Special Drawing Rights",
    "XOF : CFA Franc,Communaut&#233; Financi&#232;re Africaine (BCEAO) Franc,Benin,Burkina Faso,Ivory Coast,Guinea-Bissau,Mali,Niger,Senegal,Togo",
    "XPF : CFP Franc,Comptoirs Fran&#231;ais du Pacifique (CFP) Franc,French Polynesia,New Caledonia,Wallis and Futuna Islands",
    "YER : Yemeni Rial,Yemen Rial",
    "ZAR : South African Rand,South Africa Rand,Lesotho,Namibia",
    "ZMK : Zambian Kwacha,Zambia Kwacha",
    "ZMW : Zambian Kwacha,Zambia Kwacha",
    "ZWL : Zimbabwean Dollar,Zimbabwe Dollar",
]


# The below function calculates the actual conversion
def function1():
    query = input(
        "Please specify the amount of currency to convert, from currency, to currency (with space in between).\nPress SHOW to see list of currencies available. \nPress Q to quit. \n"
    )
    if query == "Q":
        sys.exit()
    elif query == "SHOW":
        pprint(currencies)
        function1()
    else:
        qty, fromC, toC = query.split(" ")
        fromC = fromC.upper()
        toC = toC.upper()
        qty = float(round(int(qty), 2))
        amount = round(qty * fx[toC] / fx[fromC], 2)
        print(f"{qty} of currency {fromC} amounts to {amount} of currency {toC} today")


try:
    function1()
except KeyError:
    print("You seem to have inputted wrongly, retry!")
    function1()


File: projects/Countdown_timer/main.py

import time

def countdown(t):
    while t:
        mins, secs = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(mins,secs)
        print(timer, end="\r")
        time.sleep(1)
        t -= 1

    print('Timer completed!')

t = input('Enter the time in seconds: ')

countdown(int(t))


File: projects/Encrypt_and_decrypt_text/aes_encode.py

from Crypto.Cipher import AES
from Crypto import Random
from binascii import b2a_hex
import sys

# get the plaintext
plain_text = sys.argv[1]

# The key length must be 16 (AES-128), 24 (AES-192), or 32 (AES-256) Bytes.
key = b'this is a 16 key'

# Generate a non-repeatable key vector with a length
# equal to the size of the AES block
iv = Random.new().read(AES.block_size)

# Use key and iv to initialize AES object, use MODE_CFB mode
mycipher = AES.new(key, AES.MODE_CFB, iv)

# Add iv (key vector) to the beginning of the encrypted ciphertext
# and transmit it together
ciphertext = iv + mycipher.encrypt(plain_text.encode())


# To decrypt, use key and iv to generate a new AES object
mydecrypt = AES.new(key, AES.MODE_CFB, ciphertext[:16])

# Use the newly generated AES object to decrypt the encrypted ciphertext
decrypttext = mydecrypt.decrypt(ciphertext[16:])

# output
file_out = open("encrypted.bin", "wb")
file_out.write(ciphertext[16:])
file_out.close()

print("The key k is: ", key)
print("iv is: ", b2a_hex(ciphertext)[:16])
print("The encrypted data is: ", b2a_hex(ciphertext)[16:])
print("The decrypted data is: ", decrypttext.decode())



File: projects/Tic_tac_toe/tic_tac_toe.py

squares = [' ']*9
players = 'XO'
board = '''
  0   1   2
  {0} | {1} | {2}
 -----------
3 {3} | {4} | {5} 5
 -----------
  {6} | {7} | {8}
  6   7   8
'''
win_conditions = [
    (0, 1, 2), (3, 4, 5), (6, 7, 8), # horizontals
    (0, 3, 6), (1, 4, 7), (2, 5, 8), # verticals
    (0, 4, 8), (2, 4, 6)             # diagonals
]

def check_win(player):
    for a, b, c in win_conditions:
        if {squares[a], squares[b], squares[c]} == {player}:
            return True

while True:
    print(board.format(*squares))
    if check_win(players[1]):
        print(f'{players[1]} is the winner!')
        break
    if ' ' not in squares:
        print('Cats game!')
        break
    move = input(f'{players[0]} to move [0-8] > ')
    if not move.isdigit() or not 0 <= int(move) <= 8 or squares[int(move)] != ' ':
        print('Invalid move!')
        continue
    squares[int(move)], players = players[0], players[::-1]



File: projects/Instagram_profile/InstgramProfile.py

import requests
from lxml import html
import re
import sys


def main(username):
    '''main function accept instagram username
    return an dictionary object containging profile deatils
    '''
    url = "https://www.instagram.com/{}/?hl=en".format(username)
    page = requests.get(url)
    tree = html.fromstring(page.content)
    data = tree.xpath('//meta[starts-with(@name,"description")]/@content')

    if data:
        data = tree.xpath('//meta[starts-with(@name,"description")]/@content')
        data = data[0].split(', ')
        followers = data[0][:-9].strip()
        following = data[1][:-9].strip()
        posts = re.findall(r'\d+[,]*', data[2])[0]
        name = re.findall(r'name":"\w*[\s]+\w*"', page.text)[-1][7:-1]
        aboutinfo = re.findall(r'"description":"([^"]+)"', page.text)[0]
        instagram_profile = {
            'success': True,
            'profile': {
                'name': name,
                'profileurl': url,
                'username': username,
                'followers': followers,
                'following': following,
                'posts': posts,
                'aboutinfo': aboutinfo
            }
        }
    else:
        instagram_profile = {
            'success': False,
            'profile': {}
        }
    return instagram_profile


#  python InstgramProfile.py username
if __name__ == "__main__":
    '''driver code'''

    if len(sys.argv) == 2:
        output = main(sys.argv[-1])
        print(output)
    else:
        print('=========>Invalid paramaters Valid Command is<=========== \
        \npython InstagramProfile.py username')



File: projects/Instagram_profile/profilepic.py

from tqdm import tqdm
import requests
import re
from PIL import Image  


#Function to download profile picture of instagram accounts
def pp_download(username):
    
    url = "https://www.instagram.com/{}/".format(username)
    x = re.match(r'^(https:)[/][/]www.([^/]+[.])*instagram.com', url)

    if x:
        check_url1 = re.match(r'^(https:)[/][/]www.([^/]+[.])*instagram.com[/].*\?hl=[a-z-]{2,5}', url)
        check_url2 = re.match(r'^(https:)[/][/]www.([^/]+[.])*instagram.com$|^(https:)[/][/]www.([^/]+[.])*instagram.com/$', url)
        check_url3 = re.match(r'^(https:)[/][/]www.([^/]+[.])*instagram.com[/][a-zA-Z0-9_]{1,}$', url)
        check_url4 = re.match(r'^(https:)[/][/]www.([^/]+[.])*instagram.com[/][a-zA-Z0-9_]{1,}[/]$', url)

        if check_url3:
            final_url = url + '/?__a=1'

        if check_url4:
            final_url = url + '?__a=1'

        if check_url2:
            final_url = print("Please enter an URL related to a profile")
            exit()

        if check_url1:
            alpha = check_url1.group()
            final_url = re.sub('\\?hl=[a-z-]{2,5}', '?__a=1', alpha)
            
    try:
        if check_url3 or check_url4 or check_url2 or check_url1:
            req = requests.get(final_url)
            get_status = requests.get(final_url).status_code
            get_content = req.content.decode('utf-8')

            if get_status == 200:
                print("\nDownloading the image...")
                find_pp = re.search(r'profile_pic_url_hd\":\"([^\'\" >]+)', get_content)
                pp_link = find_pp.group()
                pp_final = re.sub('profile_pic_url_hd":"', '', pp_link)
                file_size_request = requests.get(pp_final, stream=True)
                file_size = int(file_size_request.headers['Content-Length'])
                block_size = 1024 
                t=tqdm(total=file_size, unit='B', unit_scale=True, desc=username, ascii=True)
                with open(username + '.jpg', 'wb') as f:
                    for data in file_size_request.iter_content(block_size):
                        t.update(len(data))
                        f.write(data)
                t.close()
                #Show image  
                im = Image.open(username +".jpg")  
                im.show() 
                print("Profile picture downloaded successfully")

    except Exception:
        print('error')


File: projects/Instagram_profile/main.py

import requests
from lxml import html
import re
import sys
import pprint
from profilepic import pp_download

def banner():
    print('\t""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""')
    print('\t                         InstgramProfile data graber                    ')
    print('\t""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""')


def main(username):
    banner()
    '''main function accept instagram username
    return an dictionary object containging profile deatils
    '''

    url = "https://www.instagram.com/{}/?hl=en".format(username)
    page = requests.get(url)
    tree = html.fromstring(page.content)
    data = tree.xpath('//meta[starts-with(@name,"description")]/@content')

    if data:
        data = tree.xpath('//meta[starts-with(@name,"description")]/@content')
        data = data[0].split(', ')
        followers = data[0][:-9].strip()
        following = data[1][:-9].strip()
        posts = re.findall(r'\d+[,]*', data[2])[0]
        name = re.findall(r'name":"([^"]+)"', page.text)[0]
        aboutinfo = re.findall(r'"description":"([^"]+)"', page.text)[0]
        instagram_profile = {
            'success': True,
            'profile': {
                'name': name,
                'profileurl': url,
                'username': username,
                'followers': followers,
                'following': following,
                'posts': posts,
                'aboutinfo': aboutinfo
            }
        }
    else:
        instagram_profile = {
            'success': False,
            'profile': {}
        }
    return instagram_profile


#  python main.py username
if __name__ == "__main__":

    if len(sys.argv) == 2:
        output = main(sys.argv[-1])
        pp_download(sys.argv[-1])
        pprint.pprint(output)
        
    else:
        print('Invalid paramaters Valid Command \n\tUsage : python main.py username')



File: projects/Shutdown_or_restart_your_device/PowerOptions.py

import os
import platform

def shutdown():
    if platform.system() == "Windows":
        os.system('shutdown -s')
    elif platform.system() == "Linux" or platform.system() == "Darwin":
        os.system("shutdown -h now")
    else:
        print("Os not supported!")

def restart():
    if platform.system() == "Windows":
        os.system("shutdown -t 0 -r -f")
    elif platform.system() == "Linux" or platform.system() == "Darwin":
        os.system('reboot now')
    else:
        print("Os not supported!")


command = input("Use \'r\' for restart and \'s\' for shutdown: ").lower()

if command == "r":
    restart()
elif command == "s":
    shutdown()
else:
    print("Wrong letter")



File: projects/Find_out_hostname_and_ip_address/Hostname_IPaddress.py

# importing socket library
import socket

def get_hostname_IP():
    hostname = input("Please enter website address(URL):")
    try:
        print (f'Hostname: {hostname}')
        print (f'IP: {socket.gethostbyname(hostname)}')
    except socket.gaierror as error:
        print (f'Invalid Hostname, error raised is {error}')

get_hostname_IP()




File: projects/Bouncing_ball_simulator/ball_bounce.py

#This program shows the simulation of 5 balls bouncing under gravitational acceleration.
#It is also accompanied by eleastic collission with walls of the container.
#It is fun to watch.
import pygame,time,random

pygame.init()

#setting screen size of pygame window to 800 by 600 pixels
screen=pygame.display.set_mode((800,600))
background=pygame.image.load('background-img.jpg')

#Adding title
pygame.display.set_caption('Ball Bounce Simulation')

class ball:
    ball_image=pygame.image.load('ball.png')
    g=1
    def __init__(self):
        self.velocityX=4
        self.velocityY=4
        self.X=random.randint(0,768)
        self.Y=random.randint(0,350)

    def render_ball(self):
        screen.blit(ball.ball_image, (self.X,self.Y))
    def move_ball(self):
        #changing y component of velocity due to downward acceleration
        self.velocityY+=ball.g
        #changing position based on velocity
        self.X+=self.velocityX
        self.Y+=self.velocityY
        #collission with the walls lead to change in velocity
        if self.X<0 or self.X>768:
            self.velocityX*=-1
        if self.Y<0 and self.velocityY<0:
            self.velocityY*=-1
            self.Y=0
        if self.Y>568 and self.velocityY>0:
            self.velocityY*=-1
            self.Y=568
#list of balls created as objects
Ball_List=[ball(),ball(), ball(), ball(), ball()]

#The main program loop
running=True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running=False
    
    time.sleep(0.02)
    screen.blit(background, (0,0))
    for ball_item in Ball_List:
        ball_item.render_ball()
        ball_item.move_ball()
    pygame.display.update()


File: projects/Reduce_image_file_size/reduce_image_size.py

# import openCV library for image handling
import cv2

# read image to be resized by imread() function of openCV library
img = cv2.imread('input.jpg')
print(img.shape)

# set the ratio of resized image
k = 5
width = int((img.shape[1])/k)
height = int((img.shape[0])/k)

# resize the image by resize() function of openCV library
scaled = cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA)
print(scaled.shape)

# show the resized image using imshow() function of openCV library
cv2.imshow("Output", scaled)
cv2.waitKey(500)
cv2.destroyAllWindows()

# get the resized image output by imwrite() function of openCV library
cv2.imwrite('resized_output_image.jpg', scaled)



File: projects/Send_email_from_csv/Sending_mail.py

import csv
from email.message import EmailMessage
import smtplib


def get_credentials(filepath):
    with open("credentials.txt", "r") as f:
        email_address = f.readline()
        email_pass = f.readline()
    return (email_address, email_pass)


def login(email_address, email_pass, s):
    s.ehlo()
    # start TLS for security
    s.starttls()
    s.ehlo()
    # Authentication
    s.login(email_address, email_pass)
    print("login")


def send_mail():
    s = smtplib.SMTP("smtp.gmail.com", 587)
    email_address, email_pass = get_credentials("./credentials.txt")
    login(email_address, email_pass, s)

    # message to be sent
    subject = "Welcome to Python"
    body = """Python is an interpreted, high-level,
    general-purpose programming language.\n
    Created by Guido van Rossum and first released in 1991,
    Python's design philosophy emphasizes code readability\n
    with its notable use of significant whitespace"""

    message = EmailMessage()
    message.set_content(body)
    message['Subject'] = subject

    with open("emails.csv", newline="") as csvfile:
        spamreader = csv.reader(csvfile, delimiter=" ", quotechar="|")
        for email in spamreader:
            s.send_message(email_address, email[0], message)
            print("Send To " + email[0])

    # terminating the session
    s.quit()
    print("sent")


if __name__ == "__main__":
    send_mail()



File: projects/Sine_Wave/sine_wave.py

from turtle import *
from math import *


A = 50      # Amplitude
B = 100     # WaveLength
C = 0       # Horizontal Shift
D = 0       # Vertical Shift

penup()
# As x increases y increases and decreases as it is evaluated.
for x in range(-200, 200):
    # Sine Wave Equation
    y = A * sin((2 * pi / B) * (x + C)) + D
    goto(x, y)
    pendown()

hideturtle()
mainloop()



File: projects/Digital_clock/digital_clock.py

import tkinter as tk
from time import strftime


def light_theme():
    frame = tk.Frame(root, bg="white")
    frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.8)
    lbl_1 = tk.Label(frame, font=('calibri', 40, 'bold'),
                     background='White', foreground='black')
    lbl_1.pack(anchor="s")

    def time():
        string = strftime('%I:%M:%S %p')
        lbl_1.config(text=string)
        lbl_1.after(1000, time)
    time()


def dark_theme():
    frame = tk.Frame(root, bg="#22478a")
    frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.8)
    lbl_2 = tk.Label(frame, font=('calibri', 40, 'bold'),
                     background='#22478a', foreground='black')
    lbl_2.pack(anchor="s")

    def time():
        string = strftime('%I:%M:%S %p')
        lbl_2.config(text=string)
        lbl_2.after(1000, time)
    time()


root = tk.Tk()
root.title("Digital-Clock")
canvas = tk.Canvas(root, height=140, width=400)
canvas.pack()

frame = tk.Frame(root, bg='#22478a')
frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.8)
lbl = tk.Label(frame, font=('calibri', 40, 'bold'),
                     background='#22478a', foreground='black')
lbl.pack(anchor="s")

def time():
    string = strftime('%I:%M:%S %p')
    lbl.config(text=string)
    lbl.after(1000, time)
time()

menubar = tk.Menu(root)
theme_menu = tk.Menu(menubar, tearoff=0)
theme_menu.add_command(label="Light", command=light_theme)
theme_menu.add_command(label="Dark", command=dark_theme)
menubar.add_cascade(label="Theme", menu=theme_menu)
root.config(menu=menubar)
root.mainloop()



File: projects/Recursive_password_generator/generator.py

import random
import string

def stretch(text,maxlength):
    if len(text) < maxlength:
        randomChar = get_random_char()
        return stretch(text+randomChar,maxlength)
    else:
        return text

def get_random_char():
    chars = string.printable
    randomChar = chars[random.randint(0,len(chars)-1)]
    return randomChar

while 1:
    maxlen = input(' [?] Enter a length for your password (e for exit): ')
    try:
        maxlength = int(maxlen)
        print("'",stretch('',maxlength),"'\n")
    except:
        if maxlen == 'e':
            break
        print('Please Enter an integer')



File: projects/Plagarism_checker/plag.py

#pip install -U scikit-learn
#Make sure all the .txt files that need to be checked are in the same directory as the script
import os
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

user_files = [doc for doc in os.listdir() if doc.endswith('.txt')]
user_notes = [open(_file, encoding='utf-8').read()
                 for _file in user_files]


def vectorize(Text): return TfidfVectorizer().fit_transform(Text).toarray()
def similarity(doc1, doc2): return cosine_similarity([doc1, doc2])


vectors = vectorize(user_notes)
s_vectors = list(zip(user_files, vectors))
plagiarism_results = set()


def check_plagiarism():
    global s_vectors
    for student_a, text_vector_a in s_vectors:
        new_vectors = s_vectors.copy()
        current_index = new_vectors.index((student_a, text_vector_a))
        del new_vectors[current_index]
        for student_b, text_vector_b in new_vectors:
            sim_score = similarity(text_vector_a, text_vector_b)[0][1]
            student_pair = sorted((student_a, student_b))
            score = (student_pair[0], student_pair[1], sim_score)
            plagiarism_results.add(score)
    return plagiarism_results


for data in check_plagiarism():
    print(data)



File: projects/Decimal_to_binary_convertor_and_vice_versa/decimal_to_binary.py

try:
    menu = int(input("Choose an option: \n 1. Decimal to binary \n 2. Binary to decimal\n Option: "))
    if menu < 1 or menu > 2:
        raise ValueError
    if menu == 1:
        dec = int(input("Input your decimal number:\nDecimal: "))
        print("Binary: {}".format(bin(dec)[2:]))
    elif menu == 2:
        binary = input("Input your binary number:\n Binary: ")
        print("Decimal: {}".format(int(binary, 2)))
except ValueError:
    print ("please choose a valid option")



File: projects/Ascii_art/make_art.py

#!/usr/bin/env python3

import cv2
import numpy as np

import sys

symbols_list = ["#", "-", "*", ".", "+", "o"]
threshold_list = [0, 50, 100, 150, 200]

def print_out_ascii(array):
    """prints the coded image with symbols"""

    for row in array:
        for e in row:
        	# select symbol based on the type of coding
            print(symbols_list[int(e) % len(symbols_list)], end="")
        print()


def img_to_ascii(image):
    """returns the numeric coded image"""

    # resizing parameters
    # adjust these parameters if the output doesn't fit to the screen
    height, width = image.shape
    new_width = int(width / 20) 
    new_height = int(height / 40)

    # resize image to fit the printing screen
    resized_image = cv2.resize(image, (new_width, new_height),)

    thresh_image = np.zeros(resized_image.shape)

    for i, threshold in enumerate(threshold_list):
        # assign corresponding values according to the index of threshold applied
        thresh_image[resized_image > threshold] = i
    return thresh_image


if __name__ == "__main__":

    if len(sys.argv) < 2:
        print("Image Path not specified : Using sample_image.png\n")
        image_path = "sample_image.png"  # default image path

    if len(sys.argv) == 2:
        print("Using {} as Image Path\n".format(sys.argv[1]))
        image_path = sys.argv[1]

    image = cv2.imread(image_path, 0)  # read image

    ascii_art = img_to_ascii(image)
    print_out_ascii(ascii_art)



File: projects/Geocoding/geocoding.py

import requests

# Base Url for geocoding
url = "https://us1.locationiq.com/v1/search.php"

address = input("Input the address: ")

#Your unique private_token should replace value of the private_token variable.
#To know how to obtain a unique private_token please refer the README file for this script.
private_token = "Your_private_token"

data = {
    'key': private_token,
    'q': address,
    'format': 'json'
}

response = requests.get(url, params=data)

latitude = response.json()[0]['lat']
longitude = response.json()[0]['lon']

print(f"The latitude of the given address is: {latitude}")
print(f"The longitude of the given address is: {longitude}")
print("Thanks for using this script")



File: projects/Random_word_from_list/Random_word_from_list.py

import sys
import random

# check if filename is supplied as a command line argument
if sys.argv[1:]:
    filename = sys.argv[1]
else:
    filename = input("What is the name of the file? (extension included): ")

try:
    file = open(filename)
except (FileNotFoundError, IOError):
    print("File doesn't exist!")
    exit()
# handle exception

# get number of lines
num_lines = sum(1 for line in file if line.rstrip())

# generate a random number between possible interval
random_line = random.randint(0, num_lines)

# re-iterate from first line
file.seek(0)

for i, line in enumerate(file):
    if i == random_line:
        print(line.rstrip())  # rstrip removes any trailing newlines :)
        break



File: projects/dork_search_google/main.py

#!/usr/bin/python3

import sys
import re

# the error contans for sql injection vulnerable
errors = {'MySQL': 'error in your SQL syntax',
             'MiscError': 'mysql_fetch',
             'MiscError2': 'num_rows',
             'Oracle': 'ORA-01756',
             'JDBC_CFM': 'Error Executing Database Query',
             'JDBC_CFM2': 'SQLServer JDBC Driver',
             'MSSQL_OLEdb': 'Microsoft OLE DB Provider for SQL Server',
             'MSSQL_Uqm': 'Unclosed quotation mark',
             'MS-Access_ODBC': 'ODBC Microsoft Access Driver',
             'MS-Access_JETdb': 'Microsoft JET Database',
             'Error Occurred While Processing Request' : 'Error Occurred While Processing Request',
             'Server Error' : 'Server Error',
             'Microsoft OLE DB Provider for ODBC Drivers error' : 'Microsoft OLE DB Provider for ODBC Drivers error',
             'Invalid Querystring' : 'Invalid Querystring',
             'OLE DB Provider for ODBC' : 'OLE DB Provider for ODBC',
             'VBScript Runtime' : 'VBScript Runtime',
             'ADODB.Field' : 'ADODB.Field',
             'BOF or EOF' : 'BOF or EOF',
             'ADODB.Command' : 'ADODB.Command',
             'JET Database' : 'JET Database',
             'mysql_fetch_array()' : 'mysql_fetch_array()',
             'Syntax error' : 'Syntax error',
             'mysql_numrows()' : 'mysql_numrows()',
             'GetArray()' : 'GetArray()',
             'FetchRow()' : 'FetchRow()',
             'Input string was not in a correct format' : 'Input string was not in a correct format',
             'Not found' : 'Not found'}


try:
    import requests
    import googlesearch
    # the function to exploit the google hacking databases
    def Exploit(dork,total_page):
        # this require google search engine
        user_agent = {"User-agent":"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"}

        Total_page = int(total_page)

        for b in googlesearch.search(dork, num=Total_page):
            web = b+"'" # add ' to end the result url. to check if website is vuln by SQL Injection
            # using requests
            r = requests.get(web, headers=user_agent)
            webs = r.text
            # return errors dictionary to find the error problem matches
            for Type, ErrorMessage in errors.items():
                if re.search(ErrorMessage, webs):
                    # append the list of vulnerability website to result
                    print(" \033[41m\033[30mVULN\033[40m\033[37m {0}\n Vulnerability Type: \033[31m{1}".format(b,Type))

    # doing the while input
    while True:
        # going to ask your dork
        dork = input("[?] dork: [inurl:cart.php?id=]  ")
        total_page = input("[?] total page :  ")

        # if you input the empty dork. this will set the default dork as 'inurl:products.php?id='
        if not dork:
            Exploit(dork = "inurl:cart.php?id=",
                    total_page = total_page)
        else:
            Exploit(dork = dork,total_page = total_page)

except ImportError:
    # this error will display on your terminal if you havent
    # installed the google module
    print("[!] You havent installed the required modules!\n[+] to install that packages. run 'pip3 install -r requirements.txt' on your terminal\n")
    sys.exit()
except KeyboardInterrupt:
    sys.exit()



File: projects/Dns_record/dns_record.py

#Simple program to fetch dns record of a given website

import dns.resolver

#Dictionary to store the dns record of a website
dns_record = {}

#User defined website
website = input("Enter the name of the website: ")

#Fetching the 'A' record of the website and storing it in the dictionary
a_record = dns.resolver.resolve(website, 'A')
for ipval in a_record:
    dns_record['A_Record_IP'] = ipval.to_text()

#List to store the mx records of a website
mx_record_list = []

#Fetching the mx records and storing them in the dictionary
mx_record = dns.resolver.resolve(website,'MX')
for server in mx_record:
   mx_record_list.append(server)
for i, element in enumerate(mx_record_list):
    dns_record['MX_Record', i+1] = element

#Displaying the record on the screen
for key,value in dns_record.items():
    print(f"{key} = {value}")




File: projects/download GeeksForGeeks articles/downloader.py

# !/usr/bin/env python
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import json
import requests


# article url
# URL = "https://www.geeksforgeeks.org/what-can-i-do-with-python/"


def get_driver():
    # chrome options settings
    chrome_options = webdriver.ChromeOptions()
    settings = {
        "recentDestinations": [
            {"id": "Save as PDF", "origin": "local", "account": ""}
        ],
        "selectedDestinationId": "Save as PDF",
        "version": 2,
    }
    prefs = {
        "printing.print_preview_sticky_settings.appState": json.dumps(settings)
    }
    chrome_options.add_experimental_option("prefs", prefs)
    chrome_options.add_argument("--kiosk-printing")

    # launch browser with predefined settings
    browser = webdriver.Chrome(
        executable_path=ChromeDriverManager().install(), options=chrome_options
    )
    return browser


def download_article(URL):
    browser = get_driver()
    browser.get(URL)

    # launch print and save as pdf
    browser.execute_script("window.print();")
    browser.close()


if __name__ == "__main__":
    URL = input("provide article URL: ")
    # check if the url is valid/reachable
    if requests.get(URL).status_code == 200:
        try:
            download_article(URL)
            print("Your article is successfully downloaded")
        except Exception as e:
            print(e)
    else:
        print("Enter a valid working URL")



File: projects/Textfile_analysis/textfile_analysis.py

# -*- cofing: utf-8 -*-
import os
import sys
import collections
import string

script_name = sys.argv[0]

res = {
    "total_lines":"",
    "total_characters":"",
    "total_words":"",
    "unique_words":"",
    "special_characters":""
}

try:
    textfile = sys.argv[1]
    with open(textfile, "r", encoding = "utf_8") as f:

        data = f.read()
        res["total_lines"] = data.count(os.linesep)
        res["total_characters"] = len(data.replace(" ","")) - res["total_lines"]
        counter = collections.Counter(data.split())
        d = counter.most_common()
        res["total_words"] = sum([i[1] for i in d])
        res["unique_words"] = len([i[0] for i in d])
        special_chars = string.punctuation
        res["special_characters"] = sum(v for k, v in collections.Counter(data).items() if k in special_chars)

except IndexError:
    print('Usage: %s TEXTFILE' % script_name)
except IOError:
    print('"%s" cannot be opened.' % textfile)

print(res)


File: projects/Terminal_progress_bar_with_images_resizing/progress_bar_ with_images_resizing.py

from tqdm import tqdm
from PIL import Image
import os
from time import sleep


def Resize_image(size, image):
    if os.path.isfile(image):
        try:
            im = Image.open(image)
            im.thumbnail(size, Image.ANTIALIAS)
            im.save("resize/" + str(image) + ".jpg")
        except Exception as ex:
            print(f"Error: {str(ex)} to {image}")


path = input("Enter Path to images : ")
size = input("Size Height , Width : ")
size = tuple(map(int, size.split(",")))

os.chdir(path)

list_images = os.listdir(path)
if "resize" not in list_images:
    os.mkdir("resize")

for image in tqdm(list_images, desc="Resizing Images"):
    Resize_image(size, image)
    sleep(0.1)
print("Resizing Completed!")



File: projects/Captcha_Genrator/Captcha_Genrator.py

"""
Instructions
1. Install captcha: pip install captcha
2. download fonts and update the path in code
3. run the code
"""

from io import BytesIO
from tkinter import *
from random import *
from tkinter import messagebox
import string
from captcha.image import ImageCaptcha

image = ImageCaptcha(fonts=['C:/Users/Administrator/Downloads/ChelseaMarketsr.ttf', 'C:/Users/Administrator/Downloads/DejaVuSanssr.ttf'])

random=str(randint(100000,999999))
data = image.generate(random)
assert isinstance(data, BytesIO)
image.write(random,'out.png')

def verify():
    global random
    x=t1.get("0.0",END)
    if (int(x)==int(random)):
        messagebox.showinfo("sucsess", "verified")
    else:
        messagebox.showinfo("Alert", "Not verified")
        refresh()

def refresh():
        random=str(randint(100000,999999))
        data = image.generate(random)
        assert isinstance(data, BytesIO)
        image.write(random,'out.png')
        photo = PhotoImage(file="out.png")
        l1.config(image=photo,height=100,width=200)
        l1.update()
        UpdateLabel()
    
root=Tk()
photo = PhotoImage(file="out.png")

l1=Label(root,image=photo,height=100,width=200)
t1=Text(root,height=5,width=50)
b1=Button(root,text="submit",command=verify)
b2=Button(root,text="refresh",command=refresh)

l1.pack()
t1.pack()
b1.pack()
b2.pack()
root.mainloop()






File: projects/Merge_pdfs/merge_pdfs.py

#!/usr/bin/env python

from PyPDF2 import PdfFileMerger


# By appending in the end
def by_appending():
    merger = PdfFileMerger()
    # Either provide file stream
    f1 = open("samplePdf1.pdf", "rb")
    merger.append(f1)
    # Or direct file path
    merger.append("samplePdf2.pdf")

    merger.write("mergedPdf.pdf")


# By inserting at after an specified page no.
def by_inserting():
    merger = PdfFileMerger()
    merger.append("samplePdf1.pdf")
    merger.merge(0, "samplePdf2.pdf")
    merger.write("mergedPdf1.pdf")


if __name__ == "__main__":
    by_appending()
    by_inserting()



File: projects/Random_password_generator/python-password-generator.py

import random
import string

total = string.ascii_letters + string.digits + string.punctuation

length = 16

password = "".join(random.sample(total, length))

print(password)



File: projects/Random_password_generator/random_password_gen.py

import random
import math

alpha = "abcdefghijklmnopqrstuvwxyz"
num = "0123456789"
special = "@#$%&*"

# pass_len=random.randint(8,13)  #without User INput
pass_len = int(input("Enter Password Length"))

# length of password by 50-30-20 formula
alpha_len = pass_len//2
num_len = math.ceil(pass_len*30/100)
special_len = pass_len-(alpha_len+num_len)


password = []


def generate_pass(length, array, is_alpha=False):
    for i in range(length):
        index = random.randint(0, len(array) - 1)
        character = array[index]
        if is_alpha:
            case = random.randint(0, 1)
            if case == 1:
                character = character.upper()
        password.append(character)


# alpha password
generate_pass(alpha_len, alpha, True)
# numeric password
generate_pass(num_len, num)
# special Character password
generate_pass(special_len, special)
# suffle the generated password list
random.shuffle(password)
# convert List To string
gen_password = ""
for i in password:
    gen_password = gen_password + str(i)
print(gen_password)



File: projects/Easy_cartoonify/easy_cartoonify.py

import cv2
import os
from pathlib import Path

image_name = input("Please enter the name of the image file that you want to process:    ") ## User input for the name of the image file.
image_directory = input("Please enter the directory that may contain the image:    ") ## User input for the path of the image file.

## This function looks for and finds the desired file. You can specify a parent directory for the fundtion to look for, however if you have no idea where a file is; this functio will find it for you, just slower. If you have no idea where a file is, just type "/".
def find_the_image(file_name, directory_name):
    files_found = []
    for path, subdirs, files in os.walk(directory_name):
        for name in files:
            if(file_name == name):
                file_path = os.path.join(path,name)
                files_found.append(file_path)

    print(files_found[0])
    return files_found[0] ## Return the path.


image_path = Path(find_the_image(image_name, image_directory)) ## Inıtialize the path of the image file.
new_working_directory = image_path.parent ## Initialize the parent directory of the image path.
os.chdir(new_working_directory) ## Change the working directory of the script to the parent directory of the image path.


color_image = cv2.imread(find_the_image(image_name, image_directory))
##cv2.imshow("image_not_processed",color_image) ## Uncomment this to see the image without the process.
##cv2.waitKey()
##cv2.destroyAllWindows()

cartoon_style_selection = input("This script currently has 2 sytles. Please type 1 or 2.   ")

if (cartoon_style_selection == "1"):
    cartoon_image_style_1 = cv2.stylization(color_image, sigma_s=150, sigma_r=0.25) ## Cartoonify process. 
    cv2.imshow('cartoon_1', cartoon_image_style_1)
    cv2.waitKey()
    cv2.destroyAllWindows()
elif (cartoon_style_selection == "2"):
    cartoon_image_style_2  = cv2.stylization(color_image, sigma_s=60, sigma_r=0.5) ## Cartoonify process. 
    cv2.imshow('cartoon_2', cartoon_image_style_2)
    cv2.waitKey()
    cv2.destroyAllWindows()

else:
    print("Invalid style selection.")



File: projects/Unique_words_in_a_file/unique.py

import re

# script to fetch unique sorted words from a text file.
list_of_words = []

# Alternate Method to insert file
# filename = input("Enter file name: ")
filename = "text_file.txt"

with open(filename, "r") as f:
    for line in f:
        # if case is ignored then Great and great are same words
        list_of_words.extend(re.findall(r"[\w]+", line.lower()))
        # else use this alternate method:
        # list_of_words.extend(re.findall(r"[\w]+", line))

        
# Creating a dictionary to store the number of occurence of a word
unique = {}
for each in list_of_words:
    if each not in unique:
        unique[each] = 0
    unique[each] += 1
 
# Creating a list to sort the final unique words
s = []

# If occurence of a word(val) is 1 then it is unique
for key, val in unique.items():
    if val == 1:
        s.append(key)
        
print(sorted(s))
    




File: projects/S3_File_Upload/main.py

import boto3
from botocore.exceptions import NoCredentialsError

ACCESS_KEY = 'XXXXXXXXXXXXXXXXX'
SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
LOCAL_FILE = 'local_file_name'
BUCKET_NAME = 'bucket_name'
S3_FILE_NAME = 'file_name_on_s3'

def upload_to_s3(local_file, bucket, s3_file):
    ## This function is responsible for uploading the file into the S3 bucket using the specified credentials. 
    s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY,
                      aws_secret_access_key=SECRET_KEY)
    try:
        s3.upload_file(local_file, bucket, s3_file)
        print("Upload Successful")
        return True
    except FileNotFoundError:
        print("The file was not found")
        return False
    except NoCredentialsError:
        print("Credentials not available")
        return False


result = upload_to_s3(LOCAL_FILE, BUCKET_NAME, S3_FILE_NAME)


File: projects/text_to_morse_code/text_to_morse_code.py

#all_the symbols
symbols = {
    "a": ".-",
    "b": "-...",
    "c": "-.-.",
    "d": "-..",
    "e": ".",
    "f": "..-.",
    "g": ".-",
    "h": "....",
    "i": "..",
    "j": ".---",
    "k": "-.-",
    "l": ".-..",
    "m": "--",
    "n": "-.",
    "o": "---",
    "p": ".--.",
    "q": "--.-",
    "r": ".-.",
    "s": "...",
    "t": "-",
    "u": "..-",
    "v": "...-",
    "w": ".--",
    "x": "-..-",
    "y": "-.--",
    "z": "--..",
}

#the user has to tyoe a word
ask = input("type: ")


length = len(ask)
output = ""

for i in range(length):
    if ask[i] in symbols.keys():
        output = output + " " + symbols.get(ask[i])

print(output)   



File: projects/Convert_JPEG_to_PNG/converter_GUI.py

import tkinter as tk
from tkinter import filedialog
from PIL import Image
root = tk.Tk()   # Tkinter window initialized
root.title('Converter')     # Title of the window
canvas1 = tk.Canvas(root, width=300, height=250, bg='orange', relief='raised')
canvas1.pack()
label1 = tk.Label(root, text='File Converter', bg='lightsteelblue2')   # giving a title to the screen
label1.config(font=('helvetica', 20))
canvas1.create_window(150, 60, window=label1)
im1 = None  # variable to store path of image


def getJPG():
    '''Function to get image location and open it with pillow'''
    global im1
    import_file_path = filedialog.askopenfilename()
    im1 = Image.open(import_file_path)


font = ('helvetica', 12, 'bold')
bg = 'royalblue'
fg = 'white'
browseButton_JPG = tk.Button(text="      Import JPEG File     ", command=getJPG, bg=bg, fg=fg, font=font)   # Browse button
canvas1.create_window(150, 130, window=browseButton_JPG)


def convertToPNG():
    '''Function to change file extenstion to png and save it to User's prefered location '''
    global im1
    if im1 is None:
        tk.messagebox.showerror("Error", "No File selected")
    else:
        export_file_path = filedialog.asksaveasfilename(defaultextension='.png')
        im1.save(export_file_path)


saveAsButton_PNG = tk.Button(text='Convert JPEG to PNG', command=convertToPNG, bg=bg, fg=fg, font=font)      # Convert button
canvas1.create_window(150, 180, window=saveAsButton_PNG)
root.mainloop()



File: projects/Convert_JPEG_to_PNG/converter_terminal.py

from PIL import Image
im1 = Image.open('input.jpeg')  # takes input image from present folder
im1.save('output.png')          # output image is generated the folder



File: projects/capture_screenshot/screenshot.py

import os
import argparse
import pyautogui
import time

parser = argparse.ArgumentParser()

parser.add_argument("-p", "--path", help="absolute path to store screenshot.", default=r"./images")
parser.add_argument("-t", "--type", help="h (in hour) or m (in minutes) or s (in seconds)", default='h')
parser.add_argument("-f", "--frequency", help="frequency for taking screenshot per h/m/s.", default=1, type=int)

args = parser.parse_args()


sec = 0.

if args.type == 'h':
    sec = 60 * 60 / args.frequency
elif args.type == 'm':
    sec = 60 / args.frequency

if sec < 1.:
    sec = 1.
    

if os.path.isdir(args.path) != True:
    os.mkdir(args.path)


try:
    while True:
        t = time.localtime()
        current_time = time.strftime("%H_%M_%S", t)
        file = current_time + ".jpg"
        image = pyautogui.screenshot(os.path.join(args.path,file))
        print(f"{file} saved successfully.\n")
        time.sleep(sec)
        
except KeyboardInterrupt:
    print("End of script by user interrupt")

    








File: projects/Movie Information Scraper/movieInfoScraper.py

from bs4 import BeautifulSoup
import requests

# Function to get Movie Details


def getMovieDetails(movieName):
    # Base URL of IMDB website
    url = 'https://www.imdb.com'

    # Query to find movie title
    query = '/search/title?title='

    # Empty dictionary to store movie Details
    movieDetails = {}

    # Query formed
    movienamequery = query+'+'.join(movieName.strip().split(' '))

    # WebPage is obtained and parsed
    html = requests.get(url+movienamequery+'&title_type=feature')
    bs = BeautifulSoup(html.text, 'html.parser')

    # Gets the first movie that appears in title section
    result = bs.find('h3', {'class': 'lister-item-header'})

    if result is None:
        return None

    movielink = url+result.a.attrs['href']
    movieDetails['name'] = result.a.text

    # Gets the page with movie details
    html = requests.get(movielink)
    bs = BeautifulSoup(html.text, 'html.parser')
    # Year
    try:
        movieDetails['year'] = bs.find('span', {'id': 'titleYear'}).a.text
    except AttributeError:
        movieDetails['year'] = 'Not available'
    subtext = bs.find('div', {'class': 'subtext'})

    # Rating,Genres,Runtime,Release Date,

    movieDetails['genres'] = [
        i.text for i in subtext.findAll('a', {'title': None})]
    try:
        movieDetails['rating'] = bs.find(
            'div', {'class': 'ratingValue'}).span.text
        movieDetails['runtime'] = subtext.time.text.strip()
    except AttributeError:
        movieDetails['rating'] = 'Not yet rated'
        movieDetails['runtime'] = 'Not available'
    movieDetails['release_date'] = subtext.find(
        'a', {'title': 'See more release dates'}).text.strip()

    # Gets the credit section of the page
    creditSummary = bs.findAll('div', {'class': 'credit_summary_item'})

    # Directors,Writers and Cast
    movieDetails['directors'] = [i.text for i in creditSummary[0].findAll('a')]
    movieDetails['writers'] = [i.text for i in creditSummary[1].findAll(
        'a') if 'name' in i.attrs['href']]
    try:
        movieDetails['cast'] = [i.text for i in creditSummary[2].findAll(
            'a') if 'name' in i.attrs['href']]

    # For some films, writer details are not provided
    except IndexError:
        movieDetails['cast']=movieDetails['writers']
        movieDetails['writers']='Not found'

    # The plot is seperate AJAX call and does not come in the html page, So one more request to plotsummary page
    html = requests.get(movielink+'plotsummary')
    bs = BeautifulSoup(html.text, 'html.parser')

    # Plot
    movieDetails['plot'] = bs.find(
        'li', {'class': 'ipl-zebra-list__item'}).p.text.strip()

    # Returns the dictionary with movie details
    return movieDetails


if __name__ == "__main__":
    movieName = input('Enter the movie name whose details are to be fetched\n')
    movieDetails = getMovieDetails(movieName)
    if movieDetails is None:
        print('No movie of this name found !!!!!')
        quit()
    print('\n{movie} ({year})'.format(
        movie=movieDetails['name'], year=movieDetails['year']))
    print('Rating:', movieDetails['rating'])
    print('Runtime:', movieDetails['runtime'])
    print('Release Date:', movieDetails['release_date'])
    print('Genres:', ', '.join(movieDetails['genres']))
    print('Director:', ', '.join(movieDetails['directors']))
    print('Writer:', ', '.join(movieDetails['writers']))
    print('Cast:', ', '.join(movieDetails['cast']))
    print('Plot Summary:\n', movieDetails['plot'])



File: projects/Get_meta_information_of_images/author_utils.py

import ctypes as ctypes
from ctypes import wintypes as wintypes
import os
import sys


kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
advapi32 = ctypes.WinDLL('advapi32', use_last_error=True)

ERROR_INVALID_FUNCTION  = 0x0001
ERROR_FILE_NOT_FOUND    = 0x0002
ERROR_PATH_NOT_FOUND    = 0x0003
ERROR_ACCESS_DENIED     = 0x0005
ERROR_SHARING_VIOLATION = 0x0020

SE_FILE_OBJECT = 1
OWNER_SECURITY_INFORMATION = 0x00000001
GROUP_SECURITY_INFORMATION = 0x00000002
DACL_SECURITY_INFORMATION  = 0x00000004
SACL_SECURITY_INFORMATION  = 0x00000008
LABEL_SECURITY_INFORMATION = 0x00000010

_DEFAULT_SECURITY_INFORMATION = (OWNER_SECURITY_INFORMATION |
    GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION |
    LABEL_SECURITY_INFORMATION)

LPDWORD = ctypes.POINTER(wintypes.DWORD)
SE_OBJECT_TYPE = wintypes.DWORD
SECURITY_INFORMATION = wintypes.DWORD

class SID_NAME_USE(wintypes.DWORD):
    _sid_types = dict(enumerate('''
        User Group Domain Alias WellKnownGroup DeletedAccount
        Invalid Unknown Computer Label'''.split(), 1))

    def __init__(self, value=None):
        if value is not None:
            if value not in self.sid_types:
                raise ValueError('invalid SID type')
            wintypes.DWORD.__init__(value)

    def __str__(self):
        if self.value not in self._sid_types:
            raise ValueError('invalid SID type')
        return self._sid_types[self.value]

    def __repr__(self):
        return 'SID_NAME_USE(%s)' % self.value

PSID_NAME_USE = ctypes.POINTER(SID_NAME_USE)

class PLOCAL(wintypes.LPVOID):
    _needs_free = False
    def __init__(self, value=None, needs_free=False):
        super(PLOCAL, self).__init__(value)
        self._needs_free = needs_free

    def __del__(self):
        if self and self._needs_free:
            kernel32.LocalFree(self)
            self._needs_free = False

PACL = PLOCAL

class PSID(PLOCAL):
    def __init__(self, value=None, needs_free=False):
        super(PSID, self).__init__(value, needs_free)

    def __str__(self):
        if not self:
            raise ValueError('NULL pointer access')
        sid = wintypes.LPWSTR()
        advapi32.ConvertSidToStringSidW(self, ctypes.byref(sid))
        try:
            return sid.value
        finally:
            if sid:
                kernel32.LocalFree(sid)

class PSECURITY_DESCRIPTOR(PLOCAL):
    def __init__(self, value=None, needs_free=False):
        super(PSECURITY_DESCRIPTOR, self).__init__(value, needs_free)
        self.pOwner = PSID()
        self.pGroup = PSID()
        self.pDacl = PACL()
        self.pSacl = PACL()
        # back references to keep this object alive
        self.pOwner._SD = self
        self.pGroup._SD = self
        self.pDacl._SD = self
        self.pSacl._SD = self

    def get_owner(self, system_name=None):
        if not self or not self.pOwner:
            raise ValueError('NULL pointer access')
        return look_up_account_sid(self.pOwner, system_name)

    def get_group(self, system_name=None):
        if not self or not self.pGroup:
            raise ValueError('NULL pointer access')
        return look_up_account_sid(self.pGroup, system_name)

def _check_bool(result, func, args):
    if not result:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

# msdn.microsoft.com/en-us/library/aa376399
advapi32.ConvertSidToStringSidW.errcheck = _check_bool
advapi32.ConvertSidToStringSidW.argtypes = (
    PSID, # _In_   Sid
    ctypes.POINTER(wintypes.LPWSTR)) # _Out_ StringSid

# msdn.microsoft.com/en-us/library/aa379166
advapi32.LookupAccountSidW.errcheck = _check_bool
advapi32.LookupAccountSidW.argtypes = (
    wintypes.LPCWSTR, # _In_opt_  lpSystemName
    PSID,             # _In_      lpSid
    wintypes.LPCWSTR, # _Out_opt_ lpName
    LPDWORD,          # _Inout_   cchName
    wintypes.LPCWSTR, # _Out_opt_ lpReferencedDomainName
    LPDWORD,          # _Inout_   cchReferencedDomainName
    PSID_NAME_USE)    # _Out_     peUse

# msdn.microsoft.com/en-us/library/aa446645
advapi32.GetNamedSecurityInfoW.restype = wintypes.DWORD
advapi32.GetNamedSecurityInfoW.argtypes = (
    wintypes.LPWSTR,       # _In_      pObjectName
    SE_OBJECT_TYPE,        # _In_      ObjectType
    SECURITY_INFORMATION,  # _In_      SecurityInfo
    ctypes.POINTER(PSID),  # _Out_opt_ ppsidOwner
    ctypes.POINTER(PSID),  # _Out_opt_ ppsidGroup
    ctypes.POINTER(PACL),  # _Out_opt_ ppDacl
    ctypes.POINTER(PACL),  # _Out_opt_ ppSacl
    ctypes.POINTER(PSECURITY_DESCRIPTOR)) # _Out_opt_ ppSecurityDescriptor  

def look_up_account_sid(sid, system_name=None):
    SIZE = 256
    name = ctypes.create_unicode_buffer(SIZE)
    domain = ctypes.create_unicode_buffer(SIZE)
    cch_name = wintypes.DWORD(SIZE)
    cch_domain = wintypes.DWORD(SIZE)
    sid_type = SID_NAME_USE()
    advapi32.LookupAccountSidW(system_name, sid, name, ctypes.byref(cch_name),
        domain, ctypes.byref(cch_domain), ctypes.byref(sid_type))
    return name.value, domain.value, sid_type

def get_file_security(filename, request=_DEFAULT_SECURITY_INFORMATION):
    # N.B. This query may fail with ERROR_INVALID_FUNCTION
    # for some filesystems.
    pSD = PSECURITY_DESCRIPTOR(needs_free=True)
    error = advapi32.GetNamedSecurityInfoW(filename, SE_FILE_OBJECT, request,
                ctypes.byref(pSD.pOwner), ctypes.byref(pSD.pGroup),
                ctypes.byref(pSD.pDacl), ctypes.byref(pSD.pSacl),
                ctypes.byref(pSD))
    if error != 0:
        raise ctypes.WinError(error)
    return pSD

def get_author(filename):
    if isinstance(filename, bytes):
        if hasattr(os, 'fsdecode'):
            filename = os.fsdecode(filename)
        else:
            filename = filename.decode(sys.getfilesystemencoding())

    pSD = get_file_security(filename)
    owner_name, owner_domain, owner_sid_type = pSD.get_owner()
    if owner_domain:
        owner_name = '{}\\{}'.format(owner_domain, owner_name)
    return owner_name


File: projects/Get_meta_information_of_images/get_meta_from_pic.py

from PIL import Image
from PIL.ExifTags import TAGS
from author_utils import get_file_security, get_author
from gps_utils import get_location
import os
import sys
from datetime import datetime

def get_exif(image):
    image.verify()
    return image._getexif()


def get_labeled_exif(exif):
    labeled = {}
    for (key, val) in exif.items():
        labeled[TAGS.get(key)] = val

    return labeled

im = Image.open(sys.argv[1])

# get the image name
name = im.filename

# get the image size
w, h = im.size

# get the image file extension
_, file_extension = os.path.splitext(sys.argv[1])

# get the exif information
exif = get_exif(im)
labeled = get_labeled_exif(exif)

# get the file creation time
ctime = os.path.getctime(sys.argv[1])

# output information
print("ImageName: %s" %(name))
print("size: %sx%s" % (w, h))
print("FileExtension: %s" %(file_extension))
if ('ExifImageWidth' in labeled.keys()):
    print("ImageWidth: %s" % (labeled['ExifImageWidth']))
else:
    print("No ImageWidth")

if ('ExifImageHeight' in labeled.keys()):
    print("ImageHeight: %s" % (labeled['ExifImageHeight']))
else:
    print("No ImageHeight")

if ('DateTimeOriginal' in labeled.keys()):
    print("DateTimeOriginal: %s" % (labeled['DateTimeOriginal']))
else:
    print("No DateTimeOriginal")

print("CreateDate: %s" % (datetime.fromtimestamp(ctime).strftime('%Y-%m-%d %H:%M:%S')))
print("Author: %s" % (get_author(sys.argv[1])))
print("Location: %s" % (get_location(sys.argv[1])))



File: projects/Get_meta_information_of_images/gps_utils.py

import exifread
import requests
from geopy.geocoders import Nominatim

def format_lati_long(data):
	list_tmp=str(data).replace('[', '').replace(']', '').split(',')
	list=[ele.strip() for ele in list_tmp]
	if (list[-1].find('/') != -1):
		data_sec = int(list[-1].split('/')[0]) /(int(list[-1].split('/')[1])*3600)
	else:
		data_sec = int(list[-1])/3600
	data_minute = int(list[1])/60
	data_degree = int(list[0])
	result=data_degree + data_minute + data_sec
	return result

def get_location(filename):
    img=exifread.process_file(open(filename,'rb'))
    latitude=format_lati_long(str(img['GPS GPSLatitude']))
    longitude=format_lati_long(str(img['GPS GPSLongitude']))
    geolocator = Nominatim(user_agent = "your email")
    position = geolocator.reverse(str(latitude) + ',' + str(longitude))
    return position.address


File: projects/Hashing_passwords/hashing_passwords.py

# -*- cofing: utf-8 -*-
import argparse
import hashlib

# parsing
parser = argparse.ArgumentParser(description='hashing given password')
parser.add_argument('password', help='input password you want to hash')
parser.add_argument('-t', '--type', default='sha256',choices=['sha256', 'sha512', 'md5'] )
args = parser.parse_args() 

# hashing given password
password = args.password
hashtype = args.type
m = getattr(hashlib,hashtype)()
m.update(password.encode())

# output
print("< hash-type : " + hashtype + " >")
print(m.hexdigest())



File: projects/Unstructured Supplemenrary  Service Data/ussdtim.py

import time
import sys

print('Welcome To fastrack USSD Banking Project...')
time.sleep(8)

bank_list="""
1. Access Bank
2. Fidelity Bank
3. Guarantee Trust Bank
4. Heritage Bank
5. Polaris Bank
6. Stanbic IBTC
7. Unity Bank
8. Wema Bank
"""

gen_bvn = " "

def BVN_checker( ):
    global gen_bvn
    bvn = [str(i) for i in range (5)]
    gen_bvn= "".join(bvn)
    
       				
def open_acct( ):
	global gen_bvn
	print("Welcome to our online Account opening services.")
	print("loading...")
# creating an empty list to serve as a temporary place holder.
	temp_storage= [ ]
	f_name= input("Enter your first name:")
	s_name= input ("Enter your second name:")
	sex = input("Enter sex [M/F]:")
	BVN_checker( )
	temp_storage.append(f_name)
	temp_storage.append(s_name)
	temp_storage.append(sex)
	temp_storage.append(gen_bvn)
	details= " ".join(temp_storage)
	split_details = details.split(" ")
	#print(split_details)
	print(split_details[0]+" "+split_details[1])
	print(split_details[2])
	print("Your bvn is :"+split_details[3])
	print("1. Press # to go back to options menu\n2. Press * to exit")
	bck=input(":")
	if bck=='#':
	    options_menu( )
	else:
	    sys.exit( )
	
	exit( )
	
def upgrade_migrate( ):
		print("Welcome to our online Upgrade/Migration services.\n 1. Ugrade\n 2. Migrate")
		print("press # is go back to the Main Menu.")
		prompt = input("Enter preferred Choice:")
		if prompt=="1":
			time.sleep(5)
			print("Upgrading...")
			exit( )
		elif prompt == "2":
			time.sleep(5)
			print("Migrating...")
			exit( )
		elif prompt == "#":
			options_menu( )
		else:
			sys.exit( )

def balance ( ):
	print("ACCOUNT\tBALANCE\n CHECKER")
	print("press # is go back to the Main Menu.")
	pin=input("Enter your 4 digit pin:")
# isdigit( ) is used to  check for digits within a str while the nested if is used to make sure the user inputs 4 digits.

###```i am to put the pin trial in a while loop```###REMINDER!!!

	if len(pin)!=4:
	   	print("Make sure its a 4digit pin.")
	   	time.sleep(5)
	   	balance( )
	else:
	   		    if pin.isdigit( ):
	   		        time.sleep(5)
	   		        print("Loading...")
	   		        exit( )
	   		    elif pin== "#":
	   		        options_menu( )
	   		    else:
	   		        time.sleep(15)
	   		        print("wrong pin")
	   		        sys.exit( )
		
def transf( ):
	print("1. Transfer self\n2. Transfer others")
	print("press # is go back to the Main Menu.")
	trnsf=input(":")
	if trnsf == "#" :
	    options_menu( )
	elif trnsf == "1":
	    time.sleep(5)
	    print("Sending...")
	    exit( )
	elif trnsf=="2":
	    time.sleep(5)
	    num=int(input("Enter receivers mobile number:"))
	    print("Transferring to",num)
	    exit( )
	else:
	    if trnsf.isdigit( )!= True:
	        time.sleep(5)
	        print("Not an option")
	        sys.exit( )
	    elif trnsf.isdigit( ) and len(trnsf)>2:
	        time.sleep( 5)
	        print("wrong password.")
	        sys.exit( )
	    else:
	        time.sleep(10)
	        print("An error has occurred")
	        sys.exit( )
	        	
def funds( ):
	time.sleep(3)
	print(bank_list)
	bnk = input("Select receipients Bank:")
	acc_num= input("Entet account number:")
	print("Sending to",acc_num)
	hash= input("1.Press # to go back to options menu\n2. Press * to go exit.")
	if hash == "#":
	   options_menu( )
	elif hash == "*":
	    exit( )
	else:
														sys.exit( )											

																#--------------------------------------------------												
###i'm yet to catch an error for non -digit and more than one digit###REMINDER!!!						#-#------------------------------------------------------								
# This is the function for options.
def options_menu( ) :
	print("1. Open Account\n2. Upgrade/Migrate\n3. Balance\n4. Transfer\n5. Funds")
	select_options ={
	  '1':open_acct,
	  '2':upgrade_migrate,
	  '3': balance,
	  '4':transf,
	  '5':funds}
	choice=input("Enter an option:")
	if select_options.get(choice):
	   select_options[choice]()
	else:
		sys.exit()
		
# This is the function which prompts the user as to whether the user wishes to continue or stop transaction.
def exit( ):
	exit= input("Do you wish to make another transaction [Y/N] :")
	if exit== "N":
		sys.exit( )
	elif exit == "#":
	    options_menu( )
	else:
		log_in( )
		
# This is the function for logging using the fast code *919#			
def log_in( ):
    try:
        a=0
        while a<3:
            a+=1
            USSD=input("ENTER USSD:")
            if(USSD !="*919#"):
            	 print("please re-enter USSD ...")
            else:
            	print("Welcome to our online services how may we help you")
            	options_menu( ) 
            	exit( )
        else:
        	time.sleep(10)
        	print("checking discrepancies...")
        	time.sleep(5)
        	print("An error has occured.")
    
    except:
    		sys.exit( )
    		
log_in( )


File: projects/Fetch_and_store_tweets/fetch_store_tweet.py

import tweepy
import csv

# input your credentials here
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
hastag = ''

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth,wait_on_rate_limit=True)

# Open/Create a file to append data
csvFile = open('tweets.csv', 'a')
#Use csv Writer
csvWriter = csv.writer(csvFile)

for tweet in tweepy.Cursor(api.search,q=hastag,count=100,
                           lang="en",
                           since="2017-04-03").items():
    print (tweet.created_at, tweet.text)
    csvWriter.writerow([tweet.created_at, tweet.text.encode('utf-8')])


File: projects/Get_wifi_password/wifi.py

import subprocess

data = (
    subprocess.check_output(["netsh", "wlan", "show", "profiles"])
    .decode("utf-8")
    .split("\n")
)
profiles = [i.split(":")[1][1:-1] for i in data if "All User Profile" in i]
for i in profiles:
    results = (
        subprocess
        .check_output(["netsh", "wlan", "show", "profile", i, "key=clear"])
        .decode("utf-8")
        .split("\n")
    )
    results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]
    try:
        print("{:<30}|  {:<}".format(i, results[0]))
    except IndexError:
        print("{:<30}|  {:<}".format(i, ""))



File: projects/Qr_code_generator/generate_qrcode.py

import qrcode

input_URL = "https://www.google.com/"

qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=15,
    border=4,
)

qr.add_data(input_URL)
qr.make(fit=True)

img = qr.make_image(fill_color="red", back_color="white")
img.save("url_qrcode.png")

print(qr.data_list)



File: projects/Python_auto_draw/python-auto-draw.py

import pyautogui
import time

# time to change tabs from editor to paint;
time.sleep(10)

# it will remain clicked till program ends;
pyautogui.click()

# can be varied according to convininence
distance = 250

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

    # down
    pyautogui.dragRel(0, distance, duration = 0.1)

    # left
    pyautogui.dragRel(-distance, 0, duration = 0.1)

    distance -= 5

    #up
    pyautogui.dragRel(0, -distance, duration = 0.1)




File: projects/Image_watermark/watermark.py

import os
from PIL import Image

def watermark_photo(input_image_path,watermark_image_path,output_image_path):
    base_image = Image.open(input_image_path)
    watermark = Image.open(watermark_image_path).convert("RGBA")
    # add watermark to your image
    position = base_image.size
    newsize = (int(position[0]*8/100),int(position[0]*8/100))
    # print(position)
    watermark = watermark.resize(newsize)
    # print(newsize)
    # return watermark

    new_position = position[0]-newsize[0]-20,position[1]-newsize[1]-20
    # create a new transparent image
    transparent = Image.new(mode='RGBA',size=position,color=(0,0,0,0))
    # paste the original image
    transparent.paste(base_image,(0,0))
    # paste the watermark image
    transparent.paste(watermark,new_position,watermark)
    image_mode = base_image.mode
    print(image_mode)
    if image_mode == 'RGB':
        transparent = transparent.convert(image_mode)
    else:
        transparent = transparent.convert('P')
    transparent.save(output_image_path,optimize=True,quality=100)
    print("Saving"+output_image_path+"...")

folder = input("Enter Folder Path:")
watermark = input("Enter Watermark Path:")
os.chdir(folder)
files = os.listdir(os.getcwd())
print(files)

if not os.path.isdir("output"):
    os.mkdir("output")

c = 1
for f in files:
    if os.path.isfile(os.path.abspath(f)):
        if f.endswith(".png") or f.endswith(".jpg"):
            watermark_photo(f,watermark,"output/"+f)




File: projects/Snake Game/snake_game.py

from tkinter import *
import random

GAME_WIDTH = 700
GAME_HEIGHT = 700
SPEED = 100
SPACE_SIZE = 50
BODY_PARTS = 3
SNAKE_COLOR = "#00FF00"
FOOD_COLOR = "#FF0000"
BACKGROUND_COLOR = "#000000"


class Snake:

    def __init__(self):
        self.body_size = BODY_PARTS
        self.coordinates = []
        self.squares = []

        for i in range(0, BODY_PARTS):
            self.coordinates.append([0, 0])

        for x, y in self.coordinates:
            square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR, tag="snake")
            self.squares.append(square)


class Food:

    def __init__(self):

        x = random.randint(0, (GAME_WIDTH / SPACE_SIZE)-1) * SPACE_SIZE
        y = random.randint(0, (GAME_HEIGHT / SPACE_SIZE) - 1) * SPACE_SIZE

        self.coordinates = [x, y]

        canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=FOOD_COLOR, tag="food")


def next_turn(snake, food):

    x, y = snake.coordinates[0]

    if direction == "up":
        y -= SPACE_SIZE
    elif direction == "down":
        y += SPACE_SIZE
    elif direction == "left":
        x -= SPACE_SIZE
    elif direction == "right":
        x += SPACE_SIZE

    snake.coordinates.insert(0, (x, y))

    square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR)

    snake.squares.insert(0, square)

    if x == food.coordinates[0] and y == food.coordinates[1]:

        global score

        score += 1

        label.config(text="Score:{}".format(score))

        canvas.delete("food")

        food = Food()

    else:

        del snake.coordinates[-1]

        canvas.delete(snake.squares[-1])

        del snake.squares[-1]

    if check_collisions(snake):
        game_over()

    else:
        window.after(SPEED, next_turn, snake, food)


def change_direction(new_direction):

    global direction

    if new_direction == 'left':
        if direction != 'right':
            direction = new_direction
    elif new_direction == 'right':
        if direction != 'left':
            direction = new_direction
    elif new_direction == 'up':
        if direction != 'down':
            direction = new_direction
    elif new_direction == 'down':
        if direction != 'up':
            direction = new_direction


def check_collisions(snake):

    x, y = snake.coordinates[0]

    if x < 0 or x >= GAME_WIDTH:
        return True
    elif y < 0 or y >= GAME_HEIGHT:
        return True

    for body_part in snake.coordinates[1:]:
        if x == body_part[0] and y == body_part[1]:
            return True

    return False


def game_over():

    canvas.delete(ALL)
    canvas.create_text(canvas.winfo_width()/2, canvas.winfo_height()/2,
                       font=('consolas',70), text="GAME OVER", fill="red", tag="gameover")


window = Tk()
window.title("Snake game")
window.resizable(False, False)

score = 0
direction = 'down'

label = Label(window, text="Score:{}".format(score), font=('consolas', 40))
label.pack()

canvas = Canvas(window, bg=BACKGROUND_COLOR, height=GAME_HEIGHT, width=GAME_WIDTH)
canvas.pack()

window.update()

window_width = window.winfo_width()
window_height = window.winfo_height()
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()

x = int((screen_width/2) - (window_width/2))
y = int((screen_height/2) - (window_height/2))

window.geometry(f"{window_width}x{window_height}+{x}+{y}")

window.bind('<Left>', lambda event: change_direction('left'))
window.bind('<Right>', lambda event: change_direction('right'))
window.bind('<Up>', lambda event: change_direction('up'))
window.bind('<Down>', lambda event: change_direction('down'))

snake = Snake()
food = Food()

next_turn(snake, food)

window.mainloop()


File: projects/Website_blocker/website_blocker.py

import platform

if platform.system() == "Windows":
        pathToHosts=r"C:\Windows\System32\drivers\etc\hosts"
elif platform.system() == "Linux":
        pathToHosts=r"/etc/hosts"

redirect="127.0.0.1"
websites=["https://www.sislovesme.com/","https://motherless.com/","https://xhamster.com/","https://www.xnxx.com/","https://www.xvideos.com/","https://www.pornhub.com/"]

with open(pathToHosts,'r+') as file:
    content=file.read()
    for site in websites:
        if site in content:
            pass
        else:
            file.write(redirect+" "+site+"\n")
            


File: projects/Website_blocker/website_unblocker.py

import platform

if platform.system() == "Windows":
        pathToHosts=r"C:\Windows\System32\drivers\etc\hosts"
elif platform.system() == "Linux":
        pathToHosts=r"/etc/hosts"

websites=["https://www.sislovesme.com/","https://motherless.com/","https://xhamster.com/","https://www.xnxx.com/","https://www.xvideos.com/","https://www.pornhub.com/"]

with open(pathToHosts,'r+') as file:
    content=file.readlines()
    file.seek(0)
    for line in content:
        if not any(site in line for site in websites):
            file.write(line)
    file.truncate()
            


File: projects/Create_a_script_to_encrypt_files_and_folder/encrypt.py

import sys
import os
from Cryptodome.Cipher import AES
from Cryptodome import Random
from binascii import b2a_hex


def encrypt_dir(path):
    for root, _, files in os.walk("."):
        for file in files:
            file_path = os.path.join(root, file)
            print(file_path + " is encrypting.")
            encrypt_file(file_path)


def encrypt_file(path):
    # get the plaintext
    with open(path) as f:
        plain_text = f.read()

    # The key length must be 16 (AES-128), 24 (AES-192), or 32 (AES-256) Bytes.
    key = b'this is a 16 key'

    iv = Random.new().read(AES.block_size)
    mycipher = AES.new(key, AES.MODE_CFB, iv)
    ciphertext = iv + mycipher.encrypt(plain_text.encode())

    # output
    with open(path + ".bin", "wb") as file_out:
        file_out.write(ciphertext[16:])


path = sys.argv[1]
if os.path.isdir(path) and os.path.exists(path):
    encrypt_dir(path)
elif os.path.isfile(path) and os.path.exists(path):
    encrypt_file(path)
else:
    print("it's a special file(socket,FIFO,device file)")



File: projects/Split_folder_into_subfolders/split_and_copy.py

import glob
import os
from shutil import copy2
import sys


def get_files(path):
    '''
    return a list of files avialable in given folder
    '''
    files = glob.glob(f'{path}/*')
    return files


def getfullpath(path):
    '''
    Return absolute path of given file
    '''
    return os.path.abspath(path)


def copyfiles(src, dst):
    '''
    This function copy file from src to dst
    if dst dir is not there it will create new
    '''
    if not os.path.isdir(dst):
        os.makedirs(dst)
    copy2(src, dst)


def split(data, count):
    '''
    Split Given list of files and return generator
    '''
    for i in range(1, len(data), count):
        if i + count-1 > len(data):
            start, end = (i-1, len(data))
        else:
            start, end = (i-1, i+count-1)
        yield data[start:end]


def start_process(path, count):
    files = get_files(path)
    splited_data = split(files, count)

    for idx, folder in enumerate(splited_data):
        name = f'data_{idx}'
        for file in folder:
            copyfiles(getfullpath(file), getfullpath(name))


if __name__ == "__main__":
    '''
    driver code
    To run this script
    python split_and_copy.py <input folder path> <20>
    '''

    if len(sys.argv) != 3:
        print("Please provide correct parameters \
        \npython split_and_copy.py <input folder path> <count>")
        sys.exit(0)

    if len(sys.argv) == 3:
        path = sys.argv[1]
        if os.path.isdir(path):
            count = sys.argv[2]
            start_process(path, int(count))
        else:
            print('Given directory name is not an valid directory')
    else:
        print('Wrong paramter are provided')



File: projects/EasyVideoPlayer/EasyVideoPlayer.py

import cv2
import os
from pathlib import Path
from ffpyplayer.player import MediaPlayer


# User input for the name of the image file.
video_name = input("Name of the video file that you want to play:    ")

# User input for the path of the image file.
video_directory_guess = input("Directory that may contain the video:    ")


# This function finds your file. If you don't know the directory just type '/'
def find_the_video(file_name, directory_name):
    files_found = []
    for path, subdirs, files in os.walk(directory_name):
        for name in files:
            if(file_name == name):
                file_path = os.path.join(path, name)
                files_found.append(file_path)

    print(files_found)
    return files_found[0]  # Return the path.


# Initialize the path of the image file.
video_directory = Path(find_the_video(video_name, video_directory_guess))

# Initialize the parent directory of the image path.
new_working_directory = video_directory.parent

# Change the working directory of the script.
os.chdir(new_working_directory)


video_path = find_the_video(video_name, video_directory_guess)


def PlayVideo(video_path):

    video = cv2.VideoCapture(video_path)
    player = MediaPlayer(video_path)

    while True:
        grabbed, frame = video.read()
        audio_frame, val = player.get_frame()
        if not grabbed:
            print("End of video")
            break
        if cv2.waitKey(28) & 0xFF == ord("q"):
            break
        cv2.imshow("Video", frame)
        if val != 'eof' and audio_frame is not None:
            img, t = audio_frame
    video.release()
    cv2.destroyAllWindows()


PlayVideo(video_path)



File: projects/Check_website_connectivity/check_connectivity.py

import csv

import requests


status_dict = {"Website": "Status"}


def main():
    with open("websites.txt", "r") as fr:
        for line in fr:
            website = line.strip()
            status = requests.get(website).status_code
            status_dict[website] = "working" if status == 200 \
                else "not working"

    # print(status_dict)
    with open("website_status.csv", "w", newline="") as fw:
        csv_writers = csv.writer(fw)
        for key in status_dict.keys():
            csv_writers.writerow([key, status_dict[key]])


if __name__ == "__main__":
    main()



File: projects/MasterMind/Mastermind_GUIinterface.py

from tkinter import *
class medium:
    def user(self,color): # takes user' choice
        self.color=color
    def __init__(self): # generates random palette
        a=['#270101', '#F08B33', '#776B04', '#F1B848', '#8F715B', '#0486DB', '#C1403D', '#F3D4A0']
        import random
        self.b=[];n=4;
        while n!=0: 
            p=random.choice(a)
            if p not in self.b:
                self.b.append(p)
                n-=1
    def compare(self,g,l1):
        l=[] # hints           
        for x in range(4):
            if l1[x]==g[x]:
                l.append('red')
            elif l1[x]in g:
                l.append('gray')
        return l
class MasterMind():
    def __init__(self, root):
        obj=medium()
        self.gen=obj.b  # generated color combo
        self.colors = ['#270101', '#F08B33', '#776B04', '#F1B848', '#8F715B', '#0486DB', '#C1403D', '#F3D4A0']
        root.geometry('390x600')
        for y in range(20):
            Grid.rowconfigure(root, y, weight=1)
        for x in range(8):
            Grid.columnconfigure(root, x, weight=1)
        self.palette = [] # display of palette
        n,c=0,0
        for i in self.colors:
            self.palette.append(Button(root, bg=i, height=1, width=5, relief=SUNKEN))
            self.palette[n].grid(row=20, column=c)
            n+=1;c+=1;
        self.palette[0].config(command=lambda: self.guess(root, self.palette[0]['bg'],obj))         # binding function to palette
        self.palette[1].config(command=lambda: self.guess(root, self.palette[1]['bg'],obj))
        self.palette[2].config(command=lambda: self.guess(root, self.palette[2]['bg'],obj))
        self.palette[3].config(command=lambda: self.guess(root, self.palette[3]['bg'],obj))
        self.palette[4].config(command=lambda: self.guess(root, self.palette[4]['bg'],obj))
        self.palette[5].config(command=lambda: self.guess(root, self.palette[5]['bg'],obj))
        self.palette[6].config(command=lambda: self.guess(root, self.palette[6]['bg'],obj))
        self.palette[7].config(command=lambda: self.guess(root, self.palette[7]['bg'],obj))
        self.user_choice = []  # stores the widget
        self.code = []  # stores the colors
        self.key = []  # stores the hints
        global ccol, cro
        ccol,cro = 2,19
    def guess(self, root, choice,obj):
            global ccol
            global cro
            f=True  # boolean flag
            if cro != 1:
                self.user_choice.append(Button(root, bg=choice, height=1, width=5, relief=RAISED))
                if len(self.user_choice) < 4:
                    self.user_choice[-1].grid(row=cro, column=ccol)
                    self.code.append(self.user_choice[-1]['bg'])
                    ccol += 1
                elif len(self.user_choice) == 4:
                    self.user_choice[-1].grid(row=cro, column=ccol)
                    self.code.append(self.user_choice[-1]['bg'])
                    ccol += 1
                    ccol = 2
                    cro = cro-1
                    obj.user(self.code) # send the user's choice
                    self.key=obj.compare(self.code,self.gen) #get the hints
                    if self.key==['red','red','red','red']:
                        f=False
                        self.hint(root, self.key)
                        l=Label(root,text="CONGRATULATIONS!!!")
                        l.grid(row=0,columnspan=8)
                    else:
                        self.hint(root, self.key)
                        self.code = []
                        self.user_choice = []
            else:
                if f:
                    l=Label(root,text="You are a LOSER!!!!        ANSWER:")
                    l.grid(row=0,columnspan=4)
                    c=5
                    for i in self.gen:                        
                        b=Button(root,bg=i,height=1, width=5, relief=SUNKEN)
                        b.grid(row=0,column=c)
                        c+=1
    global hcol, hro
    hcol,hro = 8,19
    def hint(self, root, key):
        global hcol, hro
        a = []
        for i in key:
            a.append(Label(root, bg=i,relief=SUNKEN))
            a[-1].grid(row=hro, column=hcol, sticky=E)
            hcol += 1
        hro -= 1;hcol = 8;
master = Tk()
M = MasterMind(master)
master.mainloop()



File: projects/Extract_zip_files/extract_zip_files.py

import os
import zipfile
import sys
import argparse

# Code to add the cli
parser = argparse.ArgumentParser()
parser.add_argument("-l", "--zippedfile", required=True, help="Zipped file")
args = vars(parser.parse_args())

#Catching the user defined zip file
zip_file = args['zippedfile']

file_name = zip_file

#To check if the entered zip file is present in the directory
if os.path.exists(zip_file) == False:
    sys.exit("No such file present in the directory")

#Function to extract the zip file
def extract(zip_file):
    file_name = zip_file.split(".zip")[0]
    if zip_file.endswith(".zip"):
        
        #Will use this to save the unzipped file in the current directory
        current_working_directory = os.getcwd()
        new_directory = current_working_directory + "/" + file_name
        #Logic to unzip the file
        with zipfile.ZipFile(zip_file, 'r') as zip_object:
            zip_object.extractall(new_directory)
        print("Extracted successfully!!!")
    else:
        print("Not a zip file")

extract(zip_file) 



File: projects/Split_a_video_file_by_given_time_period/videosplitter.py

import ffmpeg
import argparse


parser = argparse.ArgumentParser(description='''Split A media file
                                            into two chunks''')
parser.add_argument('inputfile', help="Input filename")
parser.add_argument('starttime', type=float, help="Start time in seconds")
parser.add_argument('endtime', type=float, help="End time in seconds")
parser.add_argument('outputfile1', help="Output filename")
parser.add_argument('outputfile2', help="Output filename")

args = parser.parse_args()

in1 = ffmpeg.input(args.inputfile)

v1 = in1.filter('trim', start=float(args.starttime), end=(args.endtime))
v2 = in1.filter('trim', start=float(args.endtime))

out1 = ffmpeg.output(v1, args.outputfile1)
out2 = ffmpeg.output(v2, args.outputfile2)

out1.run()
out2.run()



File: projects/Fetch_open_ports/fetch_open_port.py

from socket import *
import time
startTime = time.time()

if __name__ == '__main__':
   target = input('Enter the host to be scanned: ')
   t_IP = gethostbyname(target)
   print ('Starting scan on host: ', t_IP)
   
   for i in range(50, 500):
      s = socket(AF_INET, SOCK_STREAM)
      
      conn = s.connect_ex((t_IP, i))
      if(conn == 0) :
         print ('Port %d: OPEN' % (i,))
      s.close()
print('Time taken:', time.time() - startTime)


File: projects/Drowsiness detection/drowsiness detection.py

import cv2
import os
from keras.models import load_model
import numpy as np
from pygame import mixer
import time


mixer.init()
sound = mixer.Sound('alarm.wav')

face = cv2.CascadeClassifier('haar cascade files\haarcascade_frontalface_alt.xml')
leye = cv2.CascadeClassifier('haar cascade files\haarcascade_lefteye_2splits.xml')
reye = cv2.CascadeClassifier('haar cascade files\haarcascade_righteye_2splits.xml')



lbl=['Close','Open']

model = load_model('models/cnncat2.h5')
path = os.getcwd()
cap = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_COMPLEX_SMALL
count=0
score=0
thicc=2
rpred=[99]
lpred=[99]

while(True):
    ret, frame = cap.read()
    height,width = frame.shape[:2] 

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    faces = face.detectMultiScale(gray,minNeighbors=5,scaleFactor=1.1,minSize=(25,25))
    left_eye = leye.detectMultiScale(gray)
    right_eye =  reye.detectMultiScale(gray)

    cv2.rectangle(frame, (0,height-50) , (200,height) , (0,0,0) , thickness=cv2.FILLED )

    for (x,y,w,h) in faces:
        cv2.rectangle(frame, (x,y) , (x+w,y+h) , (100,100,100) , 1 )

    for (x,y,w,h) in right_eye:
        r_eye=frame[y:y+h,x:x+w]
        count=count+1
        r_eye = cv2.cvtColor(r_eye,cv2.COLOR_BGR2GRAY)
        r_eye = cv2.resize(r_eye,(24,24))
        r_eye= r_eye/255
        r_eye=  r_eye.reshape(24,24,-1)
        r_eye = np.expand_dims(r_eye,axis=0)
        rpred = model.predict_classes(r_eye)
        if(rpred[0]==1):
            lbl='Open' 
        if(rpred[0]==0):
            lbl='Closed'
        break

    for (x,y,w,h) in left_eye:
        l_eye=frame[y:y+h,x:x+w]
        count=count+1
        l_eye = cv2.cvtColor(l_eye,cv2.COLOR_BGR2GRAY)  
        l_eye = cv2.resize(l_eye,(24,24))
        l_eye= l_eye/255
        l_eye=l_eye.reshape(24,24,-1)
        l_eye = np.expand_dims(l_eye,axis=0)
        lpred = model.predict_classes(l_eye)
        if(lpred[0]==1):
            lbl='Open'   
        if(lpred[0]==0):
            lbl='Closed'
        break

    if(rpred[0]==0 and lpred[0]==0):
        score=score+1
        cv2.putText(frame,"Closed",(10,height-20), font, 1,(255,255,255),1,cv2.LINE_AA)
    # if(rpred[0]==1 or lpred[0]==1):
    else:
        score=score-1
        cv2.putText(frame,"Open",(10,height-20), font, 1,(255,255,255),1,cv2.LINE_AA)
    
        
    if(score<0):
        score=0   
    cv2.putText(frame,'Score:'+str(score),(100,height-20), font, 1,(255,255,255),1,cv2.LINE_AA)
    if(score>15):
        #person is feeling sleepy so we beep the alarm
        cv2.imwrite(os.path.join(path,'image.jpg'),frame)
        try:
            sound.play()
            
        except:  # isplaying = False
            pass
        if(thicc<16):
            thicc= thicc+2
        else:
            thicc=thicc-2
            if(thicc<2):
                thicc=2
        cv2.rectangle(frame,(0,0),(width,height),(0,0,255),thicc) 
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()



File: projects/Drowsiness detection/model.py

import os
from keras.preprocessing import image
import matplotlib.pyplot as plt 
import numpy as np
from keras.utils.np_utils import to_categorical
import random,shutil
from keras.models import Sequential
from keras.layers import Dropout,Conv2D,Flatten,Dense, MaxPooling2D, BatchNormalization
from keras.models import load_model


def generator(dir, gen=image.ImageDataGenerator(rescale=1./255), shuffle=True,batch_size=1,target_size=(24,24),class_mode='categorical' ):

    return gen.flow_from_directory(dir,batch_size=batch_size,shuffle=shuffle,color_mode='grayscale',class_mode=class_mode,target_size=target_size)

BS= 32
TS=(24,24)
train_batch= generator('data/train',shuffle=True, batch_size=BS,target_size=TS)
valid_batch= generator('data/valid',shuffle=True, batch_size=BS,target_size=TS)
SPE= len(train_batch.classes)//BS
VS = len(valid_batch.classes)//BS
print(SPE,VS)


# img,labels= next(train_batch)
# print(img.shape)

model = Sequential([
    Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(24,24,1)),
    MaxPooling2D(pool_size=(1,1)),
    Conv2D(32,(3,3),activation='relu'),
    MaxPooling2D(pool_size=(1,1)),
#32 convolution filters used each of size 3x3
#again
    Conv2D(64, (3, 3), activation='relu'),
    MaxPooling2D(pool_size=(1,1)),

#64 convolution filters used each of size 3x3
#choose the best features via pooling
    
#randomly turn neurons on and off to improve convergence
    Dropout(0.25),
#flatten since too many dimensions, we only want a classification output
    Flatten(),
#fully connected to get all relevant data
    Dense(128, activation='relu'),
#one more dropout for convergence' sake :) 
    Dropout(0.5),
#output a softmax to squash the matrix into output probabilities
    Dense(2, activation='softmax')
])

model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])

model.fit_generator(train_batch, validation_data=valid_batch,epochs=15,steps_per_epoch=SPE ,validation_steps=VS)

model.save('models/cnnCat2.h5', overwrite=True)


File: projects/Wikipedia_search_wordcloud/wiki-search-cloud.py

from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt
import wikipedia
import sys
import warnings
# supressing unnecessary warnings
warnings.filterwarnings("ignore")


# function to search the wikipedia article and generate the wordcloud
def gen_cloud(topic):
    try:
        content = str(wikipedia.page(topic).content)
    except:
        print("Error, try searching something else...")
        sys.exit()
    STOPWORDS.add('==')
    stopwords = set(STOPWORDS)
    wordcloud = WordCloud(stopwords=stopwords, max_words=200, background_color="black", width=600, height=350).generate(content)
    return wordcloud


# function to save the wordcloud to current directory
def save_cloud(wordcloud):
    wordcloud.to_file("./wordcloud.png")


# function to display the wordcloud with matplotlib
def show_cloud(wordcloud):
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis("off")
    plt.show()


# driver code
if __name__ == '__main__':
    topic = input("What do you want to search: ").strip()
    wordcloud = gen_cloud(topic)
    save_cloud(wordcloud)
    print("Wordcloud saved to current directory as wordcloud.png")
    desc = input("Do you wish to see the output(y/n): ")
    if desc == 'y':
        show_cloud(wordcloud)
    sys.exit()



File: projects/convert_dictionary_to_python_object/conversion.py

class obj(object):
    def __init__(self, d):
        for x, y in d.items():
            setattr(self, x, obj(y) if isinstance(y, dict) else y)
data = {'a':5,'b':7,'c':{'d':8}}
ob = obj(data)



File: projects/String_search_from_multiple_files/findstring.py

import os

text = input("input text : ")

path = input("path : ")

# os.chdir(path)


def getfiles(path):
    f = 0
    os.chdir(path)
    files = os.listdir()
    # print(files)
    for file_name in files:
        abs_path = os.path.abspath(file_name)
        if os.path.isdir(abs_path):
            getfiles(abs_path)
        if os.path.isfile(abs_path):
            f = open(file_name, "r")
            if text in f.read():
                f = 1
                print(text + " found in ")
                final_path = os.path.abspath(file_name)
                print(final_path)
                return True

    if f == 1:
        print(text + " not found! ")
        return False


getfiles(path)



File: projects/Hello/Hello.py

# This is simple program to show how print statement works

print('Hello Python World')



File: projects/Diff_Util/diff.py

#!/usr/bin/env python3

# sys: for reading command-line arguments.
# rich: for coloring the text.
import sys
from rich import print

# Print Usage message if enough arguments are not passed.
if len(sys.argv) < 3:
    print("Usage:")
    print("\tMust provide two file names as command-line arguments.")
    print("\tdiff.py <orignal_file> <changed_file>")
    exit(1)

orignal = sys.argv[1]
changed = sys.argv[2]

# Read the contents of the files in lists.
orignal_contents = open(orignal, "r").readlines()
changed_contents = open(changed, "r").readlines()

color = "green"
symbol = f"[bold {color}][+]"

print()

# Determine which file has changed much.
if len(changed_contents) <= len(orignal_contents):
    color = "red"
    symbol = f"[bold {color}][-]"
    smallest_sloc, largest_sloc = changed_contents, orignal_contents
else:
    smallest_sloc, largest_sloc = orignal_contents, changed_contents

# Go over all the lines to check the changes.
for line in range(0, len(smallest_sloc)):
    if orignal_contents[line] == changed_contents[line]:
        # Ignore if the lines are same.
        continue
    else:
        # Display the changes on the respective lines of the files.
        print(f"[bold red][-] Line {line + 1}:[/bold red] {orignal_contents[line]}", end = "")
        print(f"[bold green][+] Line {line + 1}:[/bold green] {changed_contents[line]}")

        # Show the additions [+] or deletions [-] for the file that is the largest.
        if line == len(smallest_sloc) - 1:
            for new_line in range(line + 1, len(largest_sloc)):
                print(f"{symbol} Line {new_line + 1}:[/bold {color}] {largest_sloc[new_line]}")



File: projects/Todo_app/app.py

from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)


class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(200), nullable=False)
    completed = db.Column(db.Integer, default=0)
    pub_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

    def __repr__(self):
        return "<Task %r>" % self.id


@app.route("/", methods=["POST", "GET"])
def index():
    if request.method == "POST":
        task_content = request.form["task"]
        new_task = Todo(content=task_content)
        try:
            db.session.add(new_task)
            db.session.commit()
            return redirect("/")
        except:
            return "There is an issue"
    else:
        tasks = Todo.query.order_by(Todo.pub_date).all()
        return render_template("index.html", tasks=tasks)


@app.route("/delete/<int:id>")
def delete(id):
    task = Todo.query.get_or_404(id)
    try:
        db.session.delete(task)
        db.session.commit()
        return redirect("/")
    except:
        return "This is an Problem while deleting"


@app.route("/update/<int:id>", methods=["POST", "GET"])
def update(id):
    task = Todo.query.get_or_404(id)
    if request.method == "POST":
        task.content = request.form["task"]

        try:
            db.session.commit()
            return redirect("/")
        except:
            return "There is an issue"
    else:
        tasks = Todo.query.order_by(Todo.pub_date).all()

        return render_template("index.html", update_task=task, tasks=tasks)


if __name__ == "__main__":
    app.run(debug=True)




File: projects/Scraping Medium Articles/scraping_medium.py

import os
import sys
import requests
import re
from bs4 import BeautifulSoup

# switching to current running python files directory
os.chdir('\\'.join(__file__.split('/')[:-1]))

# function to get the html of the page
def get_page():
	global url
	url = input('Enter url of a medium article: ')
	# handling possible error
	if not re.match(r'https?://medium.com/',url):
		print('Please enter a valid website, or make sure it is a medium article')
		sys.exit(1)
	res = requests.get(url)
	res.raise_for_status()
	soup = BeautifulSoup(res.text, 'html.parser')
	return soup

# function to remove all the html tags and replace some with specific strings
def purify(text):
    rep = {"<br>": "\n", "<br/>": "\n", "<li>":  "\n"}
    rep = dict((re.escape(k), v) for k, v in rep.items()) 
    pattern = re.compile("|".join(rep.keys()))
    text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
    text = re.sub('\<(.*?)\>', '', text)
    return text

# function to compile all of the scraped text in one string
def collect_text(soup):
	fin = f'url: {url}\n\n'
	main = (soup.head.title.text).split('|')
	global title
	title = main[0].strip()
	fin += f'Title: {title.upper()}\n{main[1].strip()}'

	header = soup.find_all('h1')
	j = 1

	try:
		fin += '\n\nINTRODUCTION\n'
		for elem in list(header[j].previous_siblings)[::-1]:
			fin += f'\n{purify(str(elem))}'
	except:
		pass

	fin += f'\n\n{header[j].text.upper()}'
	for elem in header[j].next_siblings:
		if elem.name == 'h1':
			j+=1
			fin += f'\n\n{header[j].text.upper()}'
			continue
		fin += f'\n{purify(str(elem))}'
	return fin

# function to save file in the current directory
def save_file(fin):
	if not os.path.exists('./scraped_articles'):
		os.mkdir('./scraped_articles')
	fname = './scraped_articles/' + '_'.join(title.split()) + '.txt'
	with open(fname, 'w', encoding='utf8') as outfile:
		outfile.write(fin)
	print(f'File saved in directory {fname}')

# driver code
if __name__ == '__main__':
	fin = collect_text(get_page())
	save_file(fin)



File: projects/Dominant_color/find-color.py

import cv2
import numpy as np

path = input("Enter Path :- ")
try:
    img = cv2.imread(path)
    cv2.imshow("img", img)
except Exception:
    print("Path not found")
    exit()


array = np.array(img)
unique, counts = np.unique(array, return_counts=True)

ocurrance = dict(zip(unique, counts))


a1_sorted_keys = sorted(ocurrance, key=ocurrance.get, reverse=True)
print(a1_sorted_keys[:3])


# Create a blank 300x300 black image
image = np.zeros((300, 300, 3), np.uint8)
# Fill image with red color(set each pixel to red)
image[:] = a1_sorted_keys[:3]


c = a1_sorted_keys[0]

# Create a blank 300x300 black image
color = np.zeros((300, 300, 3), np.uint8)
# Fill image with red color(set each pixel to red)
color[:] = (c, c, c)

print("Tone : " + str(a1_sorted_keys[:3]))
cv2.imshow("Tone", image)
print("color : " + str([c, c, c]))
cv2.imshow("color", color)



File: projects/convert pdf to text/converter1.py

# -*- coding: utf-8 -*-


import PyPDF2
import os


if(os.path.isdir("temp") == False):
    os.mkdir("temp")
    
txtpath = ""
pdfpath = ""



pdfpath = input("Enter the name of your pdf file - please use backslash when typing in directory path: ")   #Provide the path for your pdf here
txtpath = input("Enter the name of your txt file - please use backslash when typing in directory path: ")   #Provide the path for the output text file  

BASEDIR = os.path.realpath("temp") # This is the sample base directory where all your text files will be stored if you do not give a specific path
print(BASEDIR)


if(len(txtpath) == 0):
    txtpath = os.path.join(BASEDIR,os.path.basename(os.path.normpath(pdfpath)).replace(".pdf", "")+".txt")
pdfobj = open(pdfpath, 'rb')

pdfread = PyPDF2.PdfFileReader(pdfobj)

x = pdfread.numPages


for i in range(x):
    pageObj = pdfread.getPage(i)
    with open(txtpath, 'a+') as f: 
        f.write((pageObj.extractText()))
    print(pageObj.extractText()) #This just provides the overview of what is being added to your output, you can remove it if want
                                    
    
    

pdfobj.close()  





File: projects/Password_generator/password_generator.py

from tkinter import*
from random import choice
import string

class App:
    def __init__(self):
        self.window = Tk()
        self.window.title('password_generator')
        self.window.iconbitmap('logo.ico')
        self.window.iconphoto(False, PhotoImage(file='logo.png'))
        self.window.geometry('500x255')
        self.window.config(bg='gray')

        #component creation
        self.label()
        self.entry()
        self.button()

    def label(self):
        label_title = Label(self.window, text='Welcome to password generator', font=('Courrier', 20), bg='gray', fg='black')
        label_title.pack()

    def entry(self):
        self.password_entry = Entry(self.window, font=('Courrier', 25), bg='white', fg='black', width=30, relief='solid')
        self.password_entry.pack(pady=50)

    def button(self):
        password_generator = Button(self.window, text="Generate_password",  font=('Courrier', 12), bg='white', fg='black', width=25, command=self.generate_password)
        password_generator.pack()

    def generate_password(self):
        characters = string.ascii_letters + string.punctuation + string.digits
        password = ""
        for x in range(28):
            password+=choice(characters)
        self.password_entry.delete(0, END)
        self.password_entry.insert(0, password)
        
#display
app = App()
app.window.mainloop()



File: projects/convert_Imgs/JPGtoPNG.py

from PIL import Image

im = Image.open("naruto_first.jpg").convert("RGB")
im.save("naruto.png", "png")



File: projects/convert_Imgs/convertDynamic.py

from PIL import Image
import sys
import os

try:
  im = None
  for root, dirs, files in os.walk("."):
    for filename in files:
        if filename.endswith('.jpg'):
          im = Image.open(filename).convert("RGB")
          im.save(filename.replace('jpg', 'png'), "png")
        elif filename.endswith('.png'):
          im = Image.open(filename).convert("RGB")
          im.save(filename.replace('png', 'jpg'), "jpeg")
        else:
          print('dont have image to convert')
except IOError:
  print('directory empty!')
  sys.exit()



File: projects/convert_Imgs/PNGtoJPG.py

from PIL import Image

im = Image.open("naruto_first.png").convert("RGB")
im.save("naruto.jpg", "jpeg")



File: projects/Store_emails_in_csv/store_emails.py

#!/usr/bin/env python

import csv
import email
from email import policy
import imaplib
import logging
import os
import ssl

from bs4 import BeautifulSoup


credential_path = "credentials.txt"
csv_path = "mails.csv"

logger = logging.getLogger('imap_poller')

host = "imap.gmail.com"
port = 993
ssl_context = ssl.create_default_context()


def connect_to_mailbox():
    # get mail connection
    mail = imaplib.IMAP4_SSL(host, port, ssl_context=ssl_context)

    with open(credential_path, "rt") as fr:
        user = fr.readline().strip()
        pw = fr.readline().strip()
        mail.login(user, pw)

    # get mail box response and select a mail box
    status, messages = mail.select("INBOX")
    return mail, messages


# get plain text out of html mails
def get_text(email_body):
    soup = BeautifulSoup(email_body, "lxml")
    return soup.get_text(separator="\n", strip=True)


def write_to_csv(mail, writer, N, total_no_of_mails):

    for i in range(total_no_of_mails, total_no_of_mails - N, -1):
        res, data = mail.fetch(str(i), "(RFC822)")

        response = data[0]
        if isinstance(response, tuple):
            msg = email.message_from_bytes(response[1], policy=policy.default)

            # get header data
            email_subject = msg["subject"]
            email_from = msg["from"]
            email_date = msg["date"]
            email_text = ""

            # if the email message is multipart
            if msg.is_multipart():
                # iterate over email parts
                for part in msg.walk():
                    # extract content type of email
                    content_type = part.get_content_type()
                    content_disposition = str(part.get("Content-Disposition"))
                    try:
                        # get the email email_body
                        email_body = part.get_payload(decode=True)
                        if email_body:
                            email_text = get_text(email_body.decode('utf-8'))
                    except Exception as exc:
                        logger.warning('Caught exception: %r', exc)
                    if (
                        content_type == "text/plain"
                        and "attachment" not in content_disposition
                    ):
                        # print text/plain emails and skip attachments
                        # print(email_text)
                        pass
                    elif "attachment" in content_disposition:
                        pass

            else:
                # extract content type of email
                content_type = msg.get_content_type()
                # get the email email_body
                email_body = msg.get_payload(decode=True)
                if email_body:
                    email_text = get_text(email_body.decode('utf-8'))

            if email_text is not None:
                # Write data in the csv file
                row = [email_date, email_from, email_subject, email_text]
                writer.writerow(row)
            else:
                logger.warning('%s:%i: No message extracted', "INBOX", i)

def main():
    mail, messages = connect_to_mailbox()

    logging.basicConfig(level=logging.WARNING)

    total_no_of_mails = int(messages[0])
    # no. of latest mails to fetch
    # set it equal to total_no_of_emails to fetch all mail in the inbox
    N = 2

    with open(csv_path, "wt", encoding="utf-8", newline="") as fw:
        writer = csv.writer(fw)
        writer.writerow(["Date", "From", "Subject", "Text mail"])
        try:
            write_to_csv(mail, writer, N, total_no_of_mails)
        except Exception as exc:
            logger.warning('Caught exception: %r', exc)


if __name__ == "__main__":
    main()



File: projects/Terminal_Based_Hangman_Game/hangman.py

import random
from json import load


# function to randomly get one word from words.py and convert the word to uppercase
def get_word():
    with open('words.json') as json_file:
        data = load(json_file)
    wordArray = data["word_list"]
    word = random.choice(wordArray)
    word = word.upper()
    return word


# function to play the game
def play(word):

    # intialise variable
    word_completion = "_" * len(word)  # generate a line to show the number of word
    guessed = False  # indicate the status of guess
    guessed_letters = []  # store guessed letters
    guessed_words = []  # store guessed words
    tries = 6  # user have 6 times of wrong
    # display message and the format of the hangman
    print("Let's play Hangman!")
    print(display_hangman(tries))
    print(word_completion)
    print("\n")
    print("Length of the word: ", len(word))
    print("\n")

    # user can keep guessing when the tries is more than 0 and the answer is not found yet.
    while not guessed and tries > 0:

        # Display message and ask for user input and convert it into uppercase
        guess = input("Please guess a letter or the word: ").upper()

        # check the length of the user input and is it alpha or not
        if len(guess) == 1 and guess.isalpha():

            # display message when user guess the same letter twice
            if guess in guessed_letters:
                print("You already guessed the letter", guess)

            # display message and deduct the tries when user guess the wrong letter
            elif guess not in word:
                print(guess, "is not in the word.")
                tries -= 1
                guessed_letters.append(guess)

            # dispay message and store the letter when the user guess the correct letter
            else:
                print("Good job,", guess, "is in the word!")
                guessed_letters.append(guess)
                word_as_list = list(word_completion)

                indices = [i for i, letter in enumerate(word) if letter == guess]
                for index in indices:
                    word_as_list[index] = guess

                # join the guess word in the word_completion
                word_completion = "".join(word_as_list)

                # if there is not blank space in word_completion change the status of guess to true
                if "_" not in word_completion:
                    guessed = True

        # check the length of the user input and is it alpha or not
        elif len(guess) == len(word) and guess.isalpha():
            # display message when user guess the same letter twice
            if guess in guessed_words:
                print("You already guessed the word", guess)

            # display message and deduct the tries when user guess the wrong letter
            elif guess != word:
                print(guess, "is not the word.")
                tries -= 1
                guessed_words.append(guess)

            # change the status of guess
            else:
                guessed = True
                word_completion = word

        # display error message for user
        else:
            print("Not a valid guess.")

        # display the format of hangman each time of guess
        print(display_hangman(tries))
        print(word_completion)
        print("\n")
        print("Length of the word: ", len(word))
        print("\n")

    # if the variable of guess is true means user win the game
    if guessed:
        print("Congrats, you guessed the word! You win!")
    # else means user lose the game.
    else:
        print("Sorry, you ran out of tries. The word was " + word + ". Maybe next time!")


# function to display the format of hangman
def display_hangman(tries):
    stages = ["""
                    --------
                    |      |
                    |      0
                    |     \\|/
                    |      |
                    |     / \\
                    -
              """,
              """
                    --------
                    |      |
                    |      0
                    |     \\|/
                    |      |
                    |     / 
                    -
              """,
              """
                    --------
                    |      |
                    |      0
                    |     \\|/
                    |      |
                    |    
                    -
              """,
              """
                    --------
                    |      |
                    |      0
                    |     \\|
                    |      |
                    |    
                    -
              """,
              """
                    --------
                    |      |
                    |      0
                    |      |
                    |      |
                    |    
                    -
              """,
              """
                    --------
                    |      |
                    |      0
                    |      
                    |      
                    |    
                    -
              """,
              """
                    --------
                    |      |
                    |      
                    |      
                    |      
                    |    
                    -
              """
              ]
    return stages[tries]


# main function to start the game
def main():
    word = get_word()
    play(word)
    while input("Play Again? (Y/N): ").upper() == "Y":
        word = get_word()
        play(word)


if __name__ == "__main__":
    main()



File: projects/Spell_checker/spell_checker.py

from textblob import TextBlob    # importing textblob library

t = 1
while t:
    a = input("Enter the word to be checked:- ")	 # incorrect spelling
    print("original text: "+str(a))     #printing original text

    b = TextBlob(a)  #correcting the text

    # prints the corrected spelling
    print("corrected text: "+str(b.correct()))
    t = int(input("Try Again? 1 : 0 "))



File: projects/Solver_linear_equations/linearEquations.py

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm

print('The 3 equations are entered individually, each value of the equation is entered separated by a space, for example: \ninput = 6 5 -3 4 \nThis will be equal to 6x + 5y- 3z = 4')

print('Enter values for equation 1: ')
a, b, c, d = map(float, input().split()) 

print('Enter values for equation 2: ')
e, f, g, h = map(float, input().split())

print('Enter values for equation 3: ')
i, j, k, l = map(float, input().split())
#solve the linear equation
A = np.array([[a,b,c],[e,f,g],[i,j,k]])
b_a = np.array([d,h,l])
sol = np.linalg.solve(A,b_a)
print(sol)


x,y = np.linspace(0,10,10), np.linspace(0,10,10)
X,Y = np.meshgrid(x,y)

Z1 = (d-a*X-b*Y)/c
Z2 =(h-e*X-f*Y)/g
Z3 =(l+X-Y)/k

#create 3d graphics

fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.plot_surface(X,Y,Z1,alpha=0.5,cmap=cm.Accent,rstride=100,cstride=100)
ax.plot_surface(X,Y,Z2,alpha=0.5,cmap=cm.Paired,rstride=100,cstride=100)
ax.plot_surface(X,Y,Z3,alpha=0.5,cmap=cm.Pastel1,rstride=100,cstride=100)
ax.plot((sol[0],),(sol[1],),(sol[2],),lw=2,c='k', marker='o', markersize=7, markeredgecolor='g', markerfacecolor='white')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')

plt.show()





File: projects/Download_images_from_website/scrap-img.py

from selenium import webdriver
import requests as rq
import os
from bs4 import BeautifulSoup
import time

# path= E:\web scraping\chromedriver_win32\chromedriver.exe
path = input("Enter Path : ")

url = input("Enter URL : ")

output = "output"


def get_url(path, url):
    driver = webdriver.Chrome(executable_path=r"{}".format(path))
    driver.get(url)
    print("loading.....")
    res = driver.execute_script("return document.documentElement.outerHTML")

    return res


def get_img_links(res):
    soup = BeautifulSoup(res, "lxml")
    imglinks = soup.find_all("img", src=True)
    return imglinks


def download_img(img_link, index):
    try:
        extensions = [".jpeg", ".jpg", ".png", ".gif"]
        extension = ".jpg"
        for exe in extensions:
            if img_link.find(exe) > 0:
                extension = exe
                break

        img_data = rq.get(img_link).content
        with open(output + "\\" + str(index + 1) + extension, "wb+") as f:
            f.write(img_data)
        
        f.close()
    except Exception:
        pass


result = get_url(path, url)
time.sleep(60)
img_links = get_img_links(result)
if not os.path.isdir(output):
    os.mkdir(output)

for index, img_link in enumerate(img_links):
    img_link = img_link["src"]
    print("Downloading...")
    if img_link:
        download_img(img_link, index)
print("Download Complete!!")



File: projects/Snapshot_of_given_website/snapshot_of_given_website.py

# -*- cofing: utf-8 -*-
import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import chromedriver_binary


script_name = sys.argv[0]

options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)

try:
    url = sys.argv[1]

    driver.get(url)
    page_width = driver.execute_script('return document.body.scrollWidth')
    page_height = driver.execute_script('return document.body.scrollHeight')
    driver.set_window_size(page_width, page_height)
    driver.save_screenshot('screenshot.png')
    driver.quit()
    print("SUCCESS")

except IndexError:
    print('Usage: %s URL' % script_name)


File: projects/Zip_Bruter/zipbruter.py

#!/usr/bin/python3

"""
Password cracker for ZIP files. Uses brute
force attack vector for this, so you must have
strong wordlist.

Usage:
    python3 zipbruter.py -f <encrypted_zip_file> -w <wordlist> -t <threads>
"""

from sys import exit as exit_
from os.path import isfile
from argparse import ArgumentParser
from _thread import start_new_thread
from queue import Queue
from zipfile import is_zipfile, ZipFile, BadZipfile


class ZipBruter:

    """Main ZipBruter class"""

    def __init__(self, file, word_list, threads) -> None:
        """Initialized function for ZipBruter"""
        self.file = file
        self.word_list = word_list
        self.threads = threads

        # Create FIFO queue
        self.queue = Queue()

    def worker(self) -> None:
        """
        Basically it listen queue and gets target password
        from FIFO queue and checks if zip passwd is true
        """
        while True:
            # gets target passwd
            passwd = self.queue.get()
            self.queue.task_done()

            if passwd is None:
                break

            try:
                with ZipFile(self.file) as zipfile:
                    zipfile.extractall(pwd=passwd.encode())
                print('Found passwd: %s' % passwd)
            except (RuntimeError, BadZipfile):
                pass

    def start_workers(self) -> None:
        """Start threads"""
        for _ in range(self.threads):
            start_new_thread(self.worker, ())

    def main(self) -> None:
        """Main entrypoint for program"""
        self.start_workers()

        for target_passwd in self.read_wordlist():
            self.queue.put(target_passwd)

        for _ in range(self.threads):
            self.queue.put(None)

        self.queue.join()

    def read_wordlist(self) -> str:
        """Read given wordlist file and yield target passwds"""
        with open(self.word_list, 'r') as file:
            for line in file.readlines():
                yield line.strip()


if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('-f', '--file', type=str, help='Target encrypted zip file.')
    parser.add_argument('-w', '--word-list', type=str, help='Wordlist to be used.')
    parser.add_argument('-t', '--threads', type=int, default=4, help='Thread count.')
    args = parser.parse_args()

    if not args.file or not args.word_list:
        exit_(1)

    if not is_zipfile(args.file):
        exit_(1)

    if not isfile(args.word_list):
        exit_(1)

    bruter = ZipBruter(args.file, args.word_list, args.threads)
    bruter.main()



File: projects/Scrape_quotes/quote_scraper.py

from bs4 import BeautifulSoup
import requests
import csv

# URL to the website
url='http://quotes.toscrape.com'

# Getting the html file and parsing with html.parser
html=requests.get(url)
bs=BeautifulSoup(html.text,'html.parser')

# Tries to open the file 
try:
    csv_file=open('quote_list.csv','w')
    fieldnames=['quote','author','tags']
    dictwriter=csv.DictWriter(csv_file,fieldnames=fieldnames)

    # Writes the headers
    dictwriter.writeheader()

    #While next button is found in the page the loop runs
    while True:
        # Loops through quote in the page
        for quote in bs.findAll('div',{'class':'quote'}):
            #Extract the text part of quote, author and tags
            text=quote.find('span',{'class':'text'}).text
            author=quote.find('small',{'class':'author'}).text
            tags=[]
            for tag in quote.findAll('a',{'class':'tag'}):
                tags.append(tag.text)
            #Writes the current quote,author and tags to a csv file
            dictwriter.writerow({'quote':text,'author':author,'tags':tags})
        
        #Finds the link to next page
        next=bs.find('li',{'class':'next'})
        if not next: 
            break

        #Gets and parses the html file of next page
        html=requests.get(url+next.a.attrs['href'])
        bs=BeautifulSoup(html.text,'html.parser')
except:
    print('Unknown Error!!!')
finally:
    csv_file.close()



    



File: projects/Wifi_windows_password_displayer/main.py

import glob
import os
import subprocess
import xml.etree.ElementTree as ET

class PwdDisplay:
    def __init__(self):
        # Définition du répertoire courant
        os.chdir("./")
        # Création du dossier mot de passe
        if not os.path.exists("passwords"):
            os.system("mkdir passwords")

        self.export_xml(command="netsh wlan export profile interface=wi-fi key=clear folder=passwords")
        self.display_password()

    def export_xml(self, command=None):
        with open("tmp.txt", "w") as tmp:
            export_command = command.split(' ')
            subprocess.run(export_command,stdout=tmp)
        os.remove("tmp.txt")

    def file_path(self) -> list[str]:
        # Obtention du chemin des fichiers xml
        chemin_fichiers = glob.glob("passwords/"+"*xml")
        return chemin_fichiers

    def get_ssid_pwd(self) -> list:
        ssid_pwd = {}
        for i in self.file_path():
            tree = ET.parse(i)
            root = tree.getroot()
            ssid = root[1][0][1].text # ssid
            pwd = root[4][0][1][2].text #pwd
            ssid_pwd[ssid] = pwd
        return ssid_pwd

    def display_password(self):
        index=1
        info = self.get_ssid_pwd()
        list_ssid, list_pwd = [], []
        print("Here is the list of Wi-Fi networks registered on this device : \n")
        for i in info:
            print(f"[{index}] {i}")
            list_ssid.append(i)
            list_pwd.append(info[i])
            index+=1

        nb = int(input("Please choose a number : "))
        print(f"SSID : {list_ssid[nb-1]}\nPassword : {list_pwd[nb-1]}\n")

    def __del__(self):
        print("Thanks for using my tool :)")
        # Supression des fichiers
        for i in self.file_path():
            if os.path.exists(i):
                os.remove(i)


if __name__ == '__main__':
    instance = PwdDisplay
    instance()



File: projects/All_links_from_given_webpage/get_links.py

import requests as rq
from bs4 import BeautifulSoup

url = input("Enter Link: ")
if ("https" or "http") in url:
    data = rq.get(url)
else:
    data = rq.get("https://" + url)
soup = BeautifulSoup(data.text, "html.parser")
links = []
for link in soup.find_all("a"):
    links.append(link.get("href"))

# Writing the output to a file (myLinks.txt) instead of to stdout
# You can change 'a' to 'w' to overwrite the file each time
with open("myLinks.txt", 'a') as saved:
    print(links[:10], file=saved)



File: projects/Games/QuizGame.py

print(" Welcome To My Quiz Game \n Interesting Game to Play")
Player = input(" Do you want to play the game? \n" )
if Player.lower() != 'yes':
    print("Good Bye")
    quit()  

name_player = input("Enter Your Name: ")

print("Let's Start the Game :) ",name_player)

score = 0

answer = input(' What is CPU stands for? \n ')
if answer.lower() == 'central processing unit':
    print("Correct")
    score += 1
else:
    print('Wrong')
 
answer = input(' What is GPU stands for? \n ')
if answer.lower() == 'graphical processing unit':
    print("Correct")
    score += 1
else:
    print('Wrong')

answer = input(' What is RAM stands for? \n ')
if answer.lower() == 'random access memory':
    print("Correct")
    score += 1
else:
    print('Wrong')

answer = input(' What is ROM stands for? \n ')
if answer.lower() == 'read only memory':
    print("Correct")
    score += 1
else:
    print('Wrong')

answer = input(' Mouse is an input device or output device? \n ')
if answer.lower() == 'input device':
    print("Correct")
    score += 1
else:
    print('Wrong')
    
print("You got the " + str(score)+ " correct answers")
print("You got the " + str((score/5) *100)+ " correct answers")



File: projects/Text_to_speech/txtToSpeech.py

from gtts import gTTS 
import os
file = open("abc.txt", "r").read()

speech = gTTS(text=file, lang='en', slow=False)
speech.save("voice.mp3")
os.system("voice.mp3")

#print(file)


File: projects/whatsapp_Bot/main.py

import pywhatkit
from datetime import datetime

now = datetime.now()

chour = now.strftime("%H")
mobile = input('Enter Mobile No of Receiver : ')
message = input('Enter Message you wanna send : ')
hour = int(input('Enter hour : '))
minute = int(input('Enter minute : '))

pywhatkit.sendwhatmsg(mobile,message,hour,minute)



File: projects/Time_to_load_website/time_to_load_website.py

from urllib.request import urlopen
import time


def get_load_time(url):
    """This function takes a user defined url as input
    and returns the time taken to load that url in seconds.

    Args:
        url (string): The user defined url.

    Returns:
        time_to_load (float): The time taken to load the website in seconds.
    """

    if ("https" or "http") in url:  # Checking for presence of protocols
        open_this_url = urlopen(url)  # Open the url as entered by the user
    else:
        open_this_url = urlopen("https://" + url)  # Adding https to the url
    start_time = time.time()  # Time stamp before the reading of url starts
    open_this_url.read()  # Reading the user defined url
    end_time = time.time()  # Time stamp after the reading of the url
    open_this_url.close()  # Closing the instance of the urlopen object
    time_to_load = end_time - start_time

    return time_to_load


if __name__ == '__main__':
    url = input("Enter the url whose loading time you want to check: ")
    print(f"\nThe time taken to load {url} is {get_load_time(url):.2} seconds.")



File: projects/Billing_system/biling_system.py

from tkinter import*
import random
import os
from tkinter import messagebox

# ============main============================
class Bill_App:
    def __init__(self, root):
        self.root = root
        self.root.geometry("1350x700+0+0")
        self.root.title("Billing Software")
        bg_color = "#badc57"
        title = Label(self.root, text="Billing Software", font=('times new roman', 30, 'bold'), pady=2, bd=12, bg="#badc57", fg="Black", relief=GROOVE)
        title.pack(fill=X)
    # ================variables=======================
        self.sanitizer = IntVar()
        self.mask = IntVar()
        self.hand_gloves = IntVar()
        self.dettol = IntVar()
        self.newsprin = IntVar()
        self.thermal_gun = IntVar()
    # ============grocery==============================
        self.rice = IntVar()
        self.food_oil = IntVar()
        self.wheat = IntVar()
        self.daal = IntVar()
        self.flour = IntVar()
        self.maggi = IntVar()
        #=============coldDtinks=============================
        self.sprite = IntVar()
        self.limka = IntVar()
        self.mazza = IntVar()
        self.coke = IntVar()
        self.fanta = IntVar()
        self.mountain_duo = IntVar()
    # ==============Total product price================
        self.medical_price = StringVar()
        self.grocery_price = StringVar()
        self.cold_drinks_price = StringVar()
    # ==============Customer==========================
        self.c_name = StringVar()
        self.c_phone = StringVar()
        self.bill_no = StringVar()
        x = random.randint(1000, 9999)
        self.bill_no.set(str(x))
        self.search_bill = StringVar()
    # ===============Tax================================
        self.medical_tax = StringVar()
        self.grocery_tax = StringVar()
        self.cold_drinks_tax = StringVar()
    # =============customer retail details======================
        F1 = LabelFrame(self.root, text="Customer Details", font=('times new roman', 15, 'bold'), bd=10, fg="Black", bg="#badc57")
        F1.place(x=0, y=80, relwidth=1)
        cname_lbl = Label(F1, text="Customer Name:", bg=bg_color, font=('times new roman', 15, 'bold'))
        cname_lbl.grid(row=0, column=0, padx=20, pady=5)
        cname_txt = Entry(F1, width=15, textvariable=self.c_name, font='arial 15', bd=7, relief=GROOVE)
        cname_txt.grid(row=0, column=1, pady=5, padx=10)

        cphn_lbl = Label(F1, text="Customer Phone:", bg="#badc57", font=('times new roman', 15, 'bold'))
        cphn_lbl.grid(row=0, column=2, padx=20, pady=5)
        cphn_txt = Entry(F1, width=15, textvariable=self.c_phone, font='arial 15', bd=7, relief=GROOVE)
        cphn_txt.grid(row=0, column=3, pady=5, padx=10)

        c_bill_lbl = Label(F1, text="Bill Number:", bg="#badc57", font=('times new roman', 15, 'bold'))
        c_bill_lbl.grid(row=0, column=4, padx=20, pady=5)
        c_bill_txt = Entry(F1, width=15, textvariable=self.search_bill, font='arial 15', bd=7, relief=GROOVE)
        c_bill_txt.grid(row=0, column=5, pady=5, padx=10)

        bil_btn = Button(F1, text="Search", command=self.find_bill, width=10, bd=7, font=('arial', 12, 'bold'), relief=GROOVE)
        bil_btn.grid(row=0, column=6, pady=5, padx=10)

    # ===================Medical====================================
        F2 = LabelFrame(self.root, text="Medical Purpose", font=('times new roman', 15, 'bold'), bd=10, fg="Black", bg="#badc57")
        F2.place(x=5, y=180, width=325, height=380)

        sanitizer_lbl = Label(F2, text="Sanitizer", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        sanitizer_lbl.grid(row=0, column=0, padx=10, pady=10, sticky='W')
        sanitizer_txt = Entry(F2, width=10, textvariable=self.sanitizer, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        sanitizer_txt.grid(row=0, column=1, padx=10, pady=10)

        mask_lbl = Label(F2, text="Mask", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        mask_lbl.grid(row=1, column=0, padx=10, pady=10, sticky='W')
        mask_txt = Entry(F2, width=10, textvariable=self.mask, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        mask_txt.grid(row=1, column=1, padx=10, pady=10)

        hand_gloves_lbl = Label(F2, text="Hand Gloves", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        hand_gloves_lbl.grid(row=2, column=0, padx=10, pady=10, sticky='W')
        hand_gloves_txt = Entry(F2, width=10, textvariable=self.hand_gloves, font=('times new roman', 16, 'bold'), bd=5, relief =GROOVE)
        hand_gloves_txt.grid(row=2, column=1, padx=10, pady=10)

        dettol_lbl = Label(F2, text="Dettol", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        dettol_lbl.grid(row=3, column=0, padx=10, pady=10, sticky='W')
        dettol_txt = Entry(F2, width=10, textvariable=self.dettol, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        dettol_txt.grid(row=3, column=1, padx=10, pady=10)

        newsprin_lbl = Label(F2, text="Newsprin", font =('times new roman', 16, 'bold'), bg = "#badc57", fg = "black")
        newsprin_lbl.grid(row=4, column=0, padx=10, pady=10, sticky='W')
        newsprin_txt = Entry(F2, width=10, textvariable=self.newsprin, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        newsprin_txt.grid(row=4, column=1, padx=10, pady=10)

        thermal_gun_lbl = Label(F2, text="Thermal Gun", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        thermal_gun_lbl.grid(row=5, column=0, padx=10, pady=10, sticky='W')
        thermal_gun_txt = Entry(F2, width=10, textvariable=self.thermal_gun, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        thermal_gun_txt.grid(row=5, column=1, padx=10, pady=10)

    # ==========GroceryItems=========================
        F3 = LabelFrame(self.root, text="Grocery Items", font=('times new roman', 15, 'bold'), bd=10, fg="Black", bg="#badc57")
        F3.place(x=340, y=180, width=325, height=380)

        rice_lbl = Label(F3, text="Rice", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        rice_lbl.grid(row=0, column=0, padx=10, pady=10, sticky='W')
        rice_txt = Entry(F3, width=10, textvariable=self.rice, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        rice_txt.grid(row=0, column=1, padx=10, pady=10)

        food_oil_lbl = Label(F3, text="Food Oil", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        food_oil_lbl.grid(row=1, column=0, padx=10, pady=10, sticky='W')
        food_oil_txt = Entry(F3, width=10, textvariable=self.food_oil, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        food_oil_txt.grid(row=1, column=1, padx=10, pady=10)

        wheat_lbl = Label(F3, text="Wheat", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        wheat_lbl.grid(row=2, column=0, padx=10, pady=10, sticky='W')
        wheat_txt = Entry(F3, width=10, textvariable=self.wheat, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        wheat_txt.grid(row=2, column=1, padx=10, pady=10)

        daal_lbl = Label(F3, text="Daal", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        daal_lbl.grid(row=3, column=0, padx=10, pady=10, sticky='W')
        daal_txt = Entry(F3, width=10, textvariable=self.daal, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        daal_txt.grid(row=3, column=1, padx=10, pady=10)

        flour_lbl = Label(F3, text="Flour", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        flour_lbl.grid(row=4, column=0, padx=10, pady=10, sticky='W')
        flour_txt = Entry(F3, width=10, textvariable=self.flour, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        flour_txt.grid(row=4, column=1, padx=10, pady=10)

        maggi_lbl = Label(F3, text="Maggi", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        maggi_lbl.grid(row=5, column=0, padx=10, pady=10, sticky='W')
        maggi_txt = Entry(F3, width=10, textvariable=self.maggi, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        maggi_txt.grid(row=5, column=1, padx=10, pady=10)

    # ===========ColdDrinks================================
        F4 = LabelFrame(self.root, text="Cold Drinks", font=('times new roman', 15, 'bold'), bd=10, fg="Black", bg="#badc57")
        F4.place(x=670, y=180, width=325, height=380)

        sprite_lbl = Label(F4, text="Sprite", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        sprite_lbl.grid(row=0, column=0, padx=10, pady=10, sticky='W')
        sprite_txt = Entry(F4, width=10, textvariable=self.sprite, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        sprite_txt.grid(row=0, column=1, padx=10, pady=10)

        limka_lbl = Label(F4, text="Limka", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        limka_lbl.grid(row=1, column=0, padx=10, pady=10, sticky='W')
        limka_txt = Entry(F4, width=10, textvariable=self.limka, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        limka_txt.grid(row=1, column=1, padx=10, pady=10)

        mazza_lbl = Label(F4, text="Mazza", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        mazza_lbl.grid(row=2, column=0, padx=10, pady=10, sticky='W')
        wheat_txt = Entry(F4, width=10, textvariable=self.mazza, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        wheat_txt.grid(row=2, column=1, padx=10, pady=10)

        coke_lbl = Label(F4, text="Coke", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        coke_lbl.grid(row=3, column=0, padx=10, pady=10, sticky='W')
        coke_txt = Entry(F4, width=10, textvariable=self.coke, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        coke_txt.grid(row=3, column=1, padx=10, pady=10)

        fanta_lbl = Label(F4, text="Fanta", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        fanta_lbl.grid(row=4, column=0, padx=10, pady=10, sticky='W')
        fanta_txt = Entry(F4, width=10, textvariable=self.fanta, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        fanta_txt.grid(row=4, column=1, padx=10, pady=10)

        mountain_duo_lbl = Label(F4, text="Mountain Duo", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
        mountain_duo_lbl.grid(row=5, column=0, padx=10, pady=10, sticky='W')
        mountain_duo_txt = Entry(F4, width=10, textvariable=self.mountain_duo, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
        mountain_duo_txt.grid(row=5, column=1, padx=10, pady=10)

    # =================BillArea======================
        F5 = Frame(self.root, bd=10, relief=GROOVE)
        F5.place(x=1010, y=180, width=350, height=380)

        bill_title = Label(F5, text="Bill Area", font='arial 15 bold', bd=7, relief=GROOVE)
        bill_title.pack(fill=X)
        scroll_y = Scrollbar(F5, orient=VERTICAL)
        self.txtarea = Text(F5, yscrollcommand=scroll_y.set)
        scroll_y.pack(side=RIGHT, fill=Y)
        scroll_y.config(command=self.txtarea.yview)
        self.txtarea.pack(fill=BOTH, expand=1)

    # =======================ButtonFrame=============
        F6 = LabelFrame(self.root, text="Bill Area", font=('times new roman', 14, 'bold'), bd=10, fg="Black", bg="#badc57")
        F6.place(x=0, y=560, relwidth=1, height=140)

        m1_lbl = Label(F6, text="Total Medical Price", font=('times new roman', 14, 'bold'), bg="#badc57", fg="black")
        m1_lbl.grid(row=0, column=0, padx=20, pady=1, sticky='W')
        m1_txt = Entry(F6, width=18, textvariable=self.medical_price, font='arial 10 bold', bd=7, relief=GROOVE)
        m1_txt.grid(row=0, column=1, padx=18, pady=1)

        m2_lbl = Label(F6, text="Total Grocery Price", font=('times new roman', 14, 'bold'), bg="#badc57", fg="black")
        m2_lbl.grid(row=1, column=0, padx=20, pady=1, sticky='W')
        m2_txt = Entry(F6, width=18, textvariable=self.grocery_price, font='arial 10 bold', bd=7, relief=GROOVE)
        m2_txt.grid(row=1, column=1, padx=18, pady=1)

        m3_lbl = Label(F6, text="Total Cold Drinks Price", font=('times new roman', 14, 'bold'), bg="#badc57", fg="black")
        m3_lbl.grid(row=2, column=0, padx=20, pady=1, sticky='W')
        m3_txt = Entry(F6, width=18, textvariable=self.cold_drinks_price, font='arial 10 bold', bd=7, relief=GROOVE)
        m3_txt.grid(row=2, column=1, padx=18, pady=1)

        m4_lbl = Label(F6, text="Medical Tax", font=('times new roman', 14, 'bold'), bg="#badc57", fg="black")
        m4_lbl.grid(row=0, column=2, padx=20, pady=1, sticky='W')
        m4_txt = Entry(F6, width=18, textvariable=self.medical_tax, font='arial 10 bold', bd=7, relief=GROOVE)
        m4_txt.grid(row=0, column=3, padx=18, pady=1)

        m5_lbl = Label(F6, text="Grocery Tax", font=('times new roman', 14, 'bold'), bg="#badc57", fg="black")
        m5_lbl.grid(row=1, column=2, padx=20, pady=1, sticky='W')
        m5_txt = Entry(F6, width=18, textvariable=self.grocery_tax, font='arial 10 bold', bd=7, relief=GROOVE)
        m5_txt.grid(row=1, column=3, padx=18, pady=1)

        m6_lbl = Label(F6, text="Cold Drinks Tax", font=('times new roman', 14, 'bold'), bg="#badc57", fg="black")
        m6_lbl.grid(row=2, column=2, padx=20, pady=1, sticky='W')
        m6_txt = Entry(F6, width=18, textvariable=self.cold_drinks_tax, font='arial 10 bold', bd=7, relief=GROOVE)
        m6_txt.grid(row=2, column=3, padx=18, pady=1)

    # =======Buttons-======================================
        btn_f = Frame(F6, bd=7, relief=GROOVE)
        btn_f.place(x=760, width=580, height=105)

        total_btn = Button(btn_f, command=self.total, text="Total", bg="#535C68", bd=2, fg="white", pady=15, width=12, font='arial 13 bold')
        total_btn.grid(row=0, column=0, padx=5, pady=5)

        generateBill_btn = Button(btn_f, command=self.bill_area, text="Generate Bill", bd=2, bg="#535C68", fg="white", pady=12, width=12, font='arial 13 bold')
        generateBill_btn.grid(row=0, column=1, padx=5, pady=5)

        clear_btn = Button(btn_f, command=self.clear_data, text="Clear", bg="#535C68", bd=2, fg="white", pady=15, width=12, font='arial 13 bold')
        clear_btn.grid(row=0, column=2, padx=5, pady=5)

        exit_btn = Button(btn_f, command=self.exit_app, text="Exit", bd=2, bg="#535C68", fg="white", pady=15, width=12, font='arial 13 bold')
        exit_btn.grid(row=0, column=3, padx=5, pady=5)
        self.welcome_bill()

#================totalBill==========================
    def total(self):
        self.m_h_g_p = self.hand_gloves.get()*12
        self.m_s_p = self.sanitizer.get()*2
        self.m_m_p = self.mask.get()*5
        self.m_d_p = self.dettol.get()*30
        self.m_n_p = self.newsprin.get()*5
        self.m_t_g_p = self.thermal_gun.get()*15
        self.total_medical_price = float(self.m_m_p+self.m_h_g_p+self.m_d_p+self.m_n_p+self.m_t_g_p+self.m_s_p)

        self.medical_price.set("Rs. "+str(self.total_medical_price))
        self.c_tax = round((self.total_medical_price*0.05), 2)
        self.medical_tax.set("Rs. "+str(self.c_tax))

        self.g_r_p = self.rice.get()*10
        self.g_f_o_p = self.food_oil.get()*10
        self.g_w_p = self.wheat.get()*10
        self.g_d_p = self.daal.get()*6
        self.g_f_p = self.flour.get()*8
        self.g_m_p = self.maggi.get()*5
        self.total_grocery_price = float(self.g_r_p+self.g_f_o_p+self.g_w_p+self.g_d_p+self.g_f_p+self.g_m_p)

        self.grocery_price.set("Rs. " + str(self.total_grocery_price))
        self.g_tax = round((self.total_grocery_price*5), 2)
        self.grocery_tax.set("Rs. " + str(self.g_tax))

        self.c_d_s_p = self.sprite.get()*10
        self.c_d_l_p = self.limka.get()*10
        self.c_d_m_p = self.mazza.get()*10
        self.c_d_c_p = self.coke.get()*10
        self.c_d_f_p = self.fanta.get()*10
        self.c_m_d = self.mountain_duo.get()*10
        self.total_cold_drinks_price = float(self.c_d_s_p+self.c_d_l_p+self.c_d_m_p+self.c_d_c_p+self.c_d_f_p+self.c_m_d)

        self.cold_drinks_price.set("Rs. "+str(self.total_cold_drinks_price))
        self.c_d_tax = round((self.total_cold_drinks_price * 0.1), 2)
        self.cold_drinks_tax.set("Rs. "+str(self.c_d_tax))

        self.total_bill = float(self.total_medical_price+self.total_grocery_price+self.total_cold_drinks_price+self.c_tax+self.g_tax+self.c_d_tax)

#==============welcome-bill==============================
    def welcome_bill(self):
        self.txtarea.delete('1.0', END)
        self.txtarea.insert(END, "\tWelcome Webcode Retail")
        self.txtarea.insert(END, f"\n Bill Number:{self.bill_no.get()}")
        self.txtarea.insert(END, f"\nCustomer Name:{self.c_name.get()}")
        self.txtarea.insert(END, f"\nPhone Number{self.c_phone.get()}")
        self.txtarea.insert(END, f"\n================================")
        self.txtarea.insert(END, f"\nProducts\t\tQTY\t\tPrice")

#=========billArea=================================================
    def bill_area(self):
        if self.c_name.get() == " " or self.c_phone.get() == " ":
            messagebox.showerror("Error", "Customer Details Are Must")
        elif self.medical_price.get() == "Rs. 0.0" and self.grocery_price.get() == "Rs. 0.0" and self.cold_drinks_price.get()=="Rs. 0.0":
            messagebox.showerror("Error", "No Product Purchased")
        else:
            self.welcome_bill()
    # ============medical===========================
        if self.sanitizer.get() != 0:
            self.txtarea.insert(END, f"\n Sanitizer\t\t{self.sanitizer.get()}\t\t{self.m_s_p}")
        if self.mask.get() != 0:
            self.txtarea.insert(END, f"\n Sanitizer\t\t{self.mask.get()}\t\t{self.m_m_p}")
        if self.hand_gloves.get() != 0:
            self.txtarea.insert(END, f"\n Hand Gloves\t\t{self.hand_gloves.get()}\t\t{self.m_h_g_p}")
        if self.dettol.get() != 0:
            self.txtarea.insert(END, f"\n Dettol\t\t{self.dettol.get()}\t\t{self.m_d_p}")
        if self.newsprin.get() != 0:
            self.txtarea.insert(END, f"\n Newsprin\t\t{self.newsprin.get()}\t\t{self.m_n_p}")
        if self.thermal_gun.get() != 0:
            self.txtarea.insert(END , f"\n Thermal Gun\t\t{self.sanitizer.get()}\t\t{self.m_t_g_p}")
    # ==============Grocery============================
        if self.rice.get() != 0:
            self.txtarea.insert(END, f"\n Rice\t\t{self.rice.get()}\t\t{self.g_r_p}")
        if self.food_oil.get() != 0:
            self.txtarea.insert(END, f"\n Food Oil\t\t{self.food_oil.get()}\t\t{self.g_f_o_p}")
        if self.wheat.get() != 0:
            self.txtarea.insert(END, f"\n Wheat\t\t{self.wheat.get()}\t\t{self.g_w_p}")
        if self.daal.get() != 0:
            self.txtarea.insert(END, f"\n Daal\t\t{self.daal.get()}\t\t{self.g_d_p}")
        if self.flour.get() != 0:
            self.txtarea.insert(END, f"\n Flour\t\t{self.flour.get()}\t\t{self.g_f_p}")
        if self.maggi.get() != 0:
            self.txtarea.insert(END, f"\n Maggi\t\t{self.maggi.get()}\t\t{self.g_m_p}")
        #================ColdDrinks==========================
        if self.sprite.get() != 0:
            self.txtarea.insert(END, f"\n Sprite\t\t{self.sprite.get()}\t\t{self.c_d_s_p}")
        if self.limka.get() != 0:
            self.txtarea.insert(END, f"\n Sanitizer\t\t{self.limka.get()}\t\t{self.c_d_l_p}")
        if self.mazza.get() != 0:
            self.txtarea.insert(END, f"\n Mazza\t\t{self.mazza.get()}\t\t{self.c_d_m_p}")
        if self.coke.get() != 0:
            self.txtarea.insert(END, f"\n Dettol\t\t{self.coke.get()}\t\t{self.c_d_c_p}")
        if self.fanta.get() != 0:
            self.txtarea.insert(END, f"\n Fanta\t\t{self.newsprin.get()}\t\t{self.c_d_f_p}")
        if self.mountain_duo.get() != 0:
            self.txtarea.insert(END, f"\n Mountain Duo\t\t{self.sanitizer.get()}\t\t{self.c_m_d}")
            self.txtarea.insert(END, f"\n--------------------------------")
        # ===============taxes==============================
        if self.medical_tax.get() != '0.0':
            self.txtarea.insert(END, f"\n Medical Tax\t\t\t{self.medical_tax.get()}")
        if self.grocery_tax.get() != '0.0':
            self.txtarea.insert(END, f"\n Grocery Tax\t\t\t{self.grocery_tax.get()}")
        if self.cold_drinks_tax.get() != '0.0':
            self.txtarea.insert(END, f"\n Cold Drinks Tax\t\t\t{self.cold_drinks_tax.get()}")

        self.txtarea.insert(END, f"\n Total Bil:\t\t\t Rs.{self.total_bill}")
        self.txtarea.insert(END, f"\n--------------------------------")
        self.save_bill()

    #=========savebill============================
    def save_bill(self):
        op = messagebox.askyesno("Save Bill", "Do you want to save the bill?")
        if op > 0:
            self.bill_data = self.txtarea.get('1.0', END)
            f1 = open("bills/"+str(self.bill_no.get())+".txt", "w")
            f1.write(self.bill_data)
            f1.close()
            messagebox.showinfo("Saved", f"Bill no:{self.bill_no.get()} Saved Successfully")
        else:
           return

    # ===================find_bill================================
    def find_bill(self):
        present = "no"
        for i in os.listdir("bills/"):
            if i.split('.')[0] == self.search_bill.get():
                f1 = open(f"bills/{i}", "r")
                self.txtarea.delete("1.0", END)
                for d in f1:
                    self.txtarea.insert(END, d)
                    f1.close()
                present = "yes"
        if present == "no":
            messagebox.showerror("Error", "Invalid Bill No")

    # ======================clear-bill======================
    def clear_data(self):
        op = messagebox.askyesno("Clear", "Do you really want to Clear?")
        if op > 0:
            self.sanitizer.set(0)
            self.mask.set(0)
            self.hand_gloves.set(0)
            self.dettol.set(0)
            self.newsprin.set(0)
            self.thermal_gun.set(0)
    # ============grocery==============================
            self.rice.set(0)
            self.food_oil.set(0)
            self.wheat.set(0)
            self.daal.set(0)
            self.flour.set(0)
            self.maggi.set(0)
    # =============coldDrinks=============================
            self.sprite.set(0)
            self.limka.set(0)
            self.mazza.set(0)
            self.coke.set(0)
            self.fanta.set(0)
            self.mountain_duo.set(0)
    # ====================taxes================================
            self.medical_price.set("")
            self.grocery_price.set("")
            self.cold_drinks_price.set("")

            self.medical_tax.set("")
            self.grocery_tax.set("")
            self.cold_drinks_tax.set("")

            self.c_name.set("")
            self.c_phone.set("")

            self.bill_no.set("")
            x = random.randint(1000, 9999)
            self.bill_no.set(str(x))

            self.search_bill.set("")
            self.welcome_bill()

    # ===========exit=======================
    def exit_app(self):
        op = messagebox.askyesno("Exit", "Do you really want to exit?")
        if op > 0:
            self.root.destroy()


root = Tk()
obj = Bill_App(root)
root.mainloop()





File: projects/Speed_Game/macOS/main.py

import tkinter.font as tkFont
from tkinter import messagebox
import pandas as pd
import os
import random
from PIL import Image, ImageTk
import time
import threading
from tkinter import messagebox

try:
    import tkinter as tk
except:
    import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.switch_frame(StartPage)

    def switch_frame(self, frame_class):
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()


class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)

        ImagePath = 'halloween.png'
        canv = tk.Canvas(self, width=600, height=500, bg='white')
        canv.pack(side='bottom')
        self.img = ImageTk.PhotoImage(Image.open(ImagePath).resize((600, 500), Image.ANTIALIAS))
        canv.create_image(0, 0, anchor="nw", image=self.img)

        labelFont = tkFont.Font(family="Arial", size=40, weight="bold", slant="italic")
        canv.create_text((600 // 2), (500 // 2) - 40, fill="white", text="Speed Game", font=labelFont)

        startBtnFont = tkFont.Font(family="Consolas", size=20)
        startBtn = tk.Button(canv, text="START", font=startBtnFont, foreground="black", background="black",
                             relief="ridge", borderwidth=5, highlightbackground="yellow",
                             activebackground="yellow", activeforeground="black",
                             command=lambda: master.switch_frame(CategoryPage))
        canv.create_window((600 // 2), (500 // 2) + 100, window=startBtn)


class CategoryPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)

        ImagePath = 'halloween.png'
        canv = tk.Canvas(self, width=600, height=500, bg='white')
        canv.pack(side='bottom')
        self.img = ImageTk.PhotoImage(Image.open(ImagePath).resize((600, 500), Image.ANTIALIAS))
        canv.create_image(0, 0, anchor="nw", image=self.img)

        labelFont = tkFont.Font(family="Arial", size=40, weight="bold", slant="italic")
        canv.create_text((600 // 2), (500 // 2) - 190, fill="white", text="Speed Game", font=labelFont)

        btnFont = tkFont.Font(family="Consolas", size=20)
        countryBtn = tk.Button(self, text="country", foreground="black",
                               width=15, height=1,
                               background="yellow", font=btnFont, relief="ridge",
                               borderwidth=5, highlightbackground="yellow",
                               activebackground="yellow", activeforeground="yellow",
                               command=lambda: master.switch_frame(CountryPage))
        canv.create_window((600 // 2), (500 // 2) - 100, window=countryBtn)

        prevBtn = tk.Button(self, text="preve page", foreground="black",
                            width=15, height=1,
                            background="yellow", font=btnFont, relief="ridge",
                            borderwidth=5, highlightbackground="yellow",
                            activebackground="yellow", activeforeground="yellow",
                            command=lambda: master.switch_frame(StartPage))
        canv.create_window((600 // 2), (500 // 2) - 10, window=prevBtn)


class CountryPage(tk.Frame):
    def __init__(self, master):
        global pass_count, answer, country_img
        global df, pass_window
        tk.Frame.__init__(self, master)

        filename = random.choice(os.listdir("./images"))
        code = filename.split(".")[0]

        # data not in excel file 
        while code.upper() not in df.index:
            filename = random.choice(os.listdir("./images"))
            code = filename.split(".")[0]

        countryPath = "./images/" + filename

        print(countryPath)
        print(df["country"][code.upper()])
        print(filename)
        answer = df["country"][code.upper()]

        backgroundPath = 'halloween.png'
        canv = tk.Canvas(self, width=600, height=500, bg='white')
        canv.pack()
        self.img1 = ImageTk.PhotoImage(Image.open(backgroundPath).resize((600, 500), Image.ANTIALIAS))
        canv.create_image(0, 0, anchor="nw", image=self.img1)

        titleFont = tkFont.Font(family="Arial", size=40, weight="bold", slant="italic")
        canv.create_text((600 // 2), (500 // 2) - 190, fill="white", text="Country", font=titleFont)

        self.img2 = ImageTk.PhotoImage(Image.open(countryPath).resize((180, 130), Image.ANTIALIAS))
        country_img = canv.create_image(210, 130, anchor="nw", image=self.img2)

        labelFont = tkFont.Font(family="Arial", size=17, slant="italic")
        BtnFont = tkFont.Font(family="Consolas", size=15)

        canv.create_text((600 // 2), (500 // 2) + 40, fill="white", text="answer", font=labelFont)

        input_text = tk.Entry(self, width=30)
        canv.create_window((600 // 2), (500 // 2) + 70, window=input_text)

        check_btn = tk.Button(self, text="check",
                              width=10, height=1, font=BtnFont, foreground="black",
                              background="yellow", relief="ridge",
                              activebackground="yellow", activeforeground="black",
                              command=lambda: self.checkBtn_click(master, input_text.get(), answer, canv,country_img))
        canv.create_window((600 // 2) - 80, (500 // 2) + 140, window=check_btn)

        pass_btn = tk.Button(self, text="pass: " + str(pass_count) + "/3",
                             width=10, height=1, font=BtnFont, foreground="black",
                             background="yellow", relief="ridge",
                             activebackground="yellow", activeforeground="black",
                             command=lambda: self.passBtn_click(tk, canv, country_img))
        pass_window = canv.create_window((600 // 2) + 80, (500 // 2) + 140, window=pass_btn)

        self.num = 180
        mins, secs = divmod(self.num, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        TimerFont = tkFont.Font(family="Arial", size=30, weight="bold", slant="italic")
        timer_text = canv.create_text(100, 100, fill="white", text=timeformat, font=TimerFont)
        canv.after(1, self.count, canv, timer_text)

    def count(self, canv, timer_text):
        mins, secs = divmod(self.num, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        canv.delete(timer_text)
        TimerFont = tkFont.Font(family="Arial", size=30, weight="bold", slant="italic")
        timer_text = canv.create_text(100, 100, fill="white", text=timeformat, font=TimerFont)
        self.num -= 1
        if self.num < 0:
            msgBox = tk.messagebox.askretrycancel('Exit App', 'Really Quit?')
            if msgBox == True:
                self.master.switch_frame(StartPage)
            else:
                self.master.switch_frame(FinishPage)
        else:
            canv.after(1000, self.count, canv, timer_text)

    # click check button
    def checkBtn_click(self, master, user_text, check_answer, canv, check_img):
        global answer, country_img
        global correct_count, problem_count
        problem_count -= 1

        user_text = user_text.upper().replace(" ", "")
        check_answer = check_answer.replace(" ", "")

        if (user_text == check_answer):
            # correct
            print('correct')
            ImagePath = 'correct.png'
            self.img3 = ImageTk.PhotoImage(Image.open(ImagePath).resize((100, 100), Image.ANTIALIAS))
            resultImage = canv.create_image(450, 30, anchor="nw", image=self.img3)
            correct_count += 1
        else:
            # wrong
            print('wrong')
            ImagePath = 'wrong.png'
            self.img4 = ImageTk.PhotoImage(Image.open(ImagePath).resize((100, 100), Image.ANTIALIAS))

            resultImage = canv.create_image(450, 30, anchor="nw", image=self.img4)

        # resolve 15 problems
        if problem_count <= 0:
            master.switch_frame(FinishPage)
        canv.after(1000, self.delete_img, canv, resultImage)
        filename = random.choice(os.listdir("./images"))
        code = filename.split(".")[0]

        # data not in excel file 
        while code.upper() not in df.index:
            filename = random.choice(os.listdir("./images"))
            code = filename.split(".")[0]

        countryPath = "./images/" + filename
        canv.after(1000,self.delete_img, canv, check_img)
        self.img2 = ImageTk.PhotoImage(Image.open(countryPath).resize((180, 130), Image.ANTIALIAS))
        country_img = canv.create_image(210, 130, anchor="nw", image=self.img2)
        answer = df["country"][code.upper()]

        print(answer)

    def passBtn_click(self, tk, canv, check_img):
        global pass_count, pass_window
        global country_img, answer
        pass_count = pass_count - 1
        if (pass_count < 0):
            print("패스 그만")
            pass_count = 0
            tk.messagebox.showerror('Pass', 'You Don\'t have pass ticket!')
        else:
            filename = random.choice(os.listdir("./images"))
            code = filename.split(".")[0]

            # data not in excel file 
            while code.upper() not in df.index:
                filename = random.choice(os.listdir("./images"))
                code = filename.split(".")[0]

            countryPath = "./images/" + filename
            canv.after(1000, self.delete_img, canv, check_img)
            self.img2 = ImageTk.PhotoImage(Image.open(countryPath).resize((180, 130), Image.ANTIALIAS))
            country_img = canv.create_image(210, 130, anchor="nw", image=self.img2)
            answer = df["country"][code.upper()]

        self.delete_img(canv, pass_window)
        BtnFont = tkFont.Font(family="Consolas", size=15)
        pass_btn = tk.Button(self, text="pass: " + str(pass_count) + "/3",
                             width=10, height=1, font=BtnFont, foreground="yellow",
                             background="black", relief="ridge",
                             activebackground="yellow", activeforeground="black",
                             command=lambda: self.passBtn_click(tk, canv, country_img))
        pass_window = canv.create_window((600 // 2) + 80, (500 // 2) + 140, window=pass_btn)

    def delete_img(self, canv, dele_img_name):
        canv.delete(dele_img_name)


class FinishPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        ImagePath = 'halloween.png'
        canv = tk.Canvas(self, width=600, height=500, bg='white')
        canv.pack(side='bottom')
        self.img = ImageTk.PhotoImage(Image.open(ImagePath).resize((600, 500), Image.ANTIALIAS))
        canv.create_image(0, 0, anchor="nw", image=self.img)

        labelFont = tkFont.Font(family="Arial", size=40, weight="bold")
        canv.create_text((600 // 2), (500 // 2) - 50, fill="white", text="total score : " + str(correct_count)+ "/15", font=labelFont)
        canv.create_text((600 // 2), (500 // 2) + 50, fill="white", text="Good Job!", font=labelFont)


if __name__ == "__main__":
    #pygame.init()
    #mySound = pygame.mixer.Sound("SpeedGameBgm.mp3")
    #mySound.play(-1)
    pass_count = 3
    problem_count = 15
    correct_count = 0
    answer = 0
    country_img = 0
    pass_window = 0

    df = pd.read_excel("./CountryCodeData.xlsx", index_col=0, names=["code", "country"])
    print(df["country"]["KR"])

    app = SampleApp()
    app.title("Speed Game")

    app.geometry('600x500+100+100')
    app.mainloop()



File: projects/Speed_Game/windows/main.py

import tkinter.font as tkFont
from tkinter import messagebox
import pandas as pd
import os
import random
from PIL import Image, ImageTk
import time
import threading
from tkinter import messagebox

try:
    import tkinter as tk
except:
    import tkinter as tk

import pygame


class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.switch_frame(StartPage)

    def switch_frame(self, frame_class):
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()


class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)

        ImagePath = 'halloween.png'
        canv = tk.Canvas(self, width=600, height=500, bg='white')
        canv.pack(side='bottom')
        self.img = ImageTk.PhotoImage(Image.open(ImagePath).resize((600, 500), Image.ANTIALIAS))
        canv.create_image(0, 0, anchor="nw", image=self.img)

        labelFont = tkFont.Font(family="Arial", size=40, weight="bold", slant="italic")
        canv.create_text((600 // 2), (500 // 2) - 40, fill="white", text="Speed Game", font=labelFont)

        startBtnFont = tkFont.Font(family="Consolas", size=20)
        startBtn = tk.Button(canv, text="START", font=startBtnFont, foreground="yellow", background="black",
                             relief="ridge", borderwidth=5, highlightbackground="yellow",
                             activebackground="yellow", activeforeground="black",
                             command=lambda: master.switch_frame(CategoryPage))
        canv.create_window((600 // 2), (500 // 2) + 100, window=startBtn)


class CategoryPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)

        ImagePath = 'halloween.png'
        canv = tk.Canvas(self, width=600, height=500, bg='white')
        canv.pack(side='bottom')
        self.img = ImageTk.PhotoImage(Image.open(ImagePath).resize((600, 500), Image.ANTIALIAS))
        canv.create_image(0, 0, anchor="nw", image=self.img)

        labelFont = tkFont.Font(family="Arial", size=40, weight="bold", slant="italic")
        canv.create_text((600 // 2), (500 // 2) - 190, fill="white", text="Speed Game", font=labelFont)

        btnFont = tkFont.Font(family="Consolas", size=20)
        countryBtn = tk.Button(self, text="country", foreground="yellow",
                               width=15, height=1,
                               background="black", font=btnFont, relief="ridge",
                               borderwidth=5, highlightbackground="yellow",
                               activebackground="yellow", activeforeground="black",
                               command=lambda: master.switch_frame(CountryPage))
        canv.create_window((600 // 2), (500 // 2) - 100, window=countryBtn)

        prevBtn = tk.Button(self, text="preve page", foreground="yellow",
                            width=15, height=1,
                            background="black", font=btnFont, relief="ridge",
                            borderwidth=5, highlightbackground="yellow",
                            activebackground="yellow", activeforeground="black",
                            command=lambda: master.switch_frame(StartPage))
        canv.create_window((600 // 2), (500 // 2) - 10, window=prevBtn)


class CountryPage(tk.Frame):
    def __init__(self, master):
        global pass_count, answer, country_img
        global df, pass_window
        tk.Frame.__init__(self, master)

        filename = random.choice(os.listdir("./images"))
        code = filename.split(".")[0]

        # 엑셀에 없는 이미지일 경우 예외처리
        while code.upper() not in df.index:
            filename = random.choice(os.listdir("./images"))
            code = filename.split(".")[0]

        countryPath = "./images/" + filename

        print(countryPath)
        print(df["country"][code.upper()])
        print(filename)
        answer = df["country"][code.upper()]

        backgroundPath = 'halloween.png'
        canv = tk.Canvas(self, width=600, height=500, bg='white')
        canv.pack()
        self.img1 = ImageTk.PhotoImage(Image.open(backgroundPath).resize((600, 500), Image.ANTIALIAS))
        canv.create_image(0, 0, anchor="nw", image=self.img1)

        titleFont = tkFont.Font(family="Arial", size=40, weight="bold", slant="italic")
        canv.create_text((600 // 2), (500 // 2) - 190, fill="white", text="Country", font=titleFont)

        self.img2 = ImageTk.PhotoImage(Image.open(countryPath).resize((180, 130), Image.ANTIALIAS))
        country_img = canv.create_image(210, 130, anchor="nw", image=self.img2)

        labelFont = tkFont.Font(family="Arial", size=17, slant="italic")
        BtnFont = tkFont.Font(family="Consolas", size=15)

        canv.create_text((600 // 2), (500 // 2) + 40, fill="white", text="answer", font=labelFont)

        input_text = tk.Entry(self, width=30)
        canv.create_window((600 // 2), (500 // 2) + 70, window=input_text)

        check_btn = tk.Button(self, text="check",
                              width=10, height=1, font=BtnFont, foreground="yellow",
                              background="black", relief="ridge",
                              activebackground="yellow", activeforeground="black",
                              command=lambda: self.checkBtn_click(master, input_text.get(), answer, canv,country_img))
        canv.create_window((600 // 2) - 80, (500 // 2) + 140, window=check_btn)

        pass_btn = tk.Button(self, text="pass: " + str(pass_count) + "/3",
                             width=10, height=1, font=BtnFont, foreground="yellow",
                             background="black", relief="ridge",
                             activebackground="yellow", activeforeground="black",
                             command=lambda: self.passBtn_click(tk, canv, country_img))
        pass_window = canv.create_window((600 // 2) + 80, (500 // 2) + 140, window=pass_btn)

        self.num = 180
        mins, secs = divmod(self.num, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        TimerFont = tkFont.Font(family="Arial", size=30, weight="bold", slant="italic")
        timer_text = canv.create_text(100, 100, fill="white", text=timeformat, font=TimerFont)
        canv.after(1, self.count, canv, timer_text)

    def count(self, canv, timer_text):
        mins, secs = divmod(self.num, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        canv.delete(timer_text)
        TimerFont = tkFont.Font(family="Arial", size=30, weight="bold", slant="italic")
        timer_text = canv.create_text(100, 100, fill="white", text=timeformat, font=TimerFont)
        self.num -= 1
        if self.num < 0:
            msgBox = tk.messagebox.askretrycancel('Exit App', 'Really Quit?')
            if msgBox == True:
                self.master.switch_frame(StartPage)
            else:
                self.master.switch_frame(FinishPage)
        else:
            canv.after(1000, self.count, canv, timer_text)

    # click check button
    def checkBtn_click(self, master, user_text, check_answer, canv, check_img):
        global answer, country_img
        global correct_count, problem_count
        problem_count -= 1

        user_text = user_text.upper().replace(" ", "")
        check_answer = check_answer.replace(" ", "")

        if (user_text == check_answer):
            # correct
            print('맞았습돠')
            ImagePath = 'correct.png'
            self.img3 = ImageTk.PhotoImage(Image.open(ImagePath).resize((100, 100), Image.ANTIALIAS))
            resultImage = canv.create_image(450, 30, anchor="nw", image=self.img3)
            correct_count += 1
        else:
            # wrong
            print('틀렸슴돠')
            ImagePath = 'wrong.png'
            self.img4 = ImageTk.PhotoImage(Image.open(ImagePath).resize((100, 100), Image.ANTIALIAS))

            resultImage = canv.create_image(450, 30, anchor="nw", image=self.img4)

        # resolve 15 problems
        if problem_count <= 0:
            master.switch_frame(FinishPage)
        canv.after(1000, self.delete_img, canv, resultImage)
        filename = random.choice(os.listdir("./images"))
        code = filename.split(".")[0]

        # 엑셀에 없는 이미지일 경우 예외처리
        while code.upper() not in df.index:
            filename = random.choice(os.listdir("./images"))
            code = filename.split(".")[0]

        countryPath = "./images/" + filename
        canv.after(1000,self.delete_img, canv, check_img)
        self.img2 = ImageTk.PhotoImage(Image.open(countryPath).resize((180, 130), Image.ANTIALIAS))
        country_img = canv.create_image(210, 130, anchor="nw", image=self.img2)
        answer = df["country"][code.upper()]

        print(answer)

    def passBtn_click(self, tk, canv, check_img):
        global pass_count, pass_window
        global country_img, answer
        pass_count = pass_count - 1
        if (pass_count < 0):
            print("패스 그만")
            pass_count = 0
            tk.messagebox.showerror('Pass', 'You Don\'t have pass ticket!')
        else:
            filename = random.choice(os.listdir("./images"))
            code = filename.split(".")[0]

            # 엑셀에 없는 이미지일 경우 예외처리
            while code.upper() not in df.index:
                filename = random.choice(os.listdir("./images"))
                code = filename.split(".")[0]

            countryPath = "./images/" + filename
            canv.after(1000, self.delete_img, canv, check_img)
            self.img2 = ImageTk.PhotoImage(Image.open(countryPath).resize((180, 130), Image.ANTIALIAS))
            country_img = canv.create_image(210, 130, anchor="nw", image=self.img2)
            answer = df["country"][code.upper()]

        self.delete_img(canv, pass_window)
        BtnFont = tkFont.Font(family="Consolas", size=15)
        pass_btn = tk.Button(self, text="pass: " + str(pass_count) + "/3",
                             width=10, height=1, font=BtnFont, foreground="yellow",
                             background="black", relief="ridge",
                             activebackground="yellow", activeforeground="black",
                             command=lambda: self.passBtn_click(tk, canv, country_img))
        pass_window = canv.create_window((600 // 2) + 80, (500 // 2) + 140, window=pass_btn)

    def delete_img(self, canv, dele_img_name):
        canv.delete(dele_img_name)


class FinishPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        ImagePath = 'halloween.png'
        canv = tk.Canvas(self, width=600, height=500, bg='white')
        canv.pack(side='bottom')
        self.img = ImageTk.PhotoImage(Image.open(ImagePath).resize((600, 500), Image.ANTIALIAS))
        canv.create_image(0, 0, anchor="nw", image=self.img)

        labelFont = tkFont.Font(family="Arial", size=40, weight="bold")
        canv.create_text((600 // 2), (500 // 2) - 50, fill="white", text="total score : " + str(correct_count)+ "/15", font=labelFont)
        canv.create_text((600 // 2), (500 // 2) + 50, fill="white", text="Good Job!", font=labelFont)


if __name__ == "__main__":
    pygame.init()
    mySound = pygame.mixer.Sound("SpeedGameBgm.mp3")
    mySound.play(-1)
    pass_count = 3
    problem_count = 15
    correct_count = 0
    answer = 0
    country_img = 0
    pass_window = 0

    df = pd.read_excel("./CountryCodeData.xlsx", index_col=0, names=["code", "country"])
    print(df["country"]["KR"])

    app = SampleApp()
    app.title("Speed Game")

    app.geometry('600x500+100+100')
    app.mainloop()



File: projects/Write_script_to_move_files_into_alphabetically_ordered_folder/main.py

'''
This script will sort and move the files in the directory
(the alphabetical order).

'apple.txt' --> 'A'
'ryan.txt' --> 'R'
'01010.txt' --> 'Misc'

'''
import os
import shutil

filenames = []


def getfoldername(filename):
    '''
    'Test.txt' --> 't'
    '010.txt' --> 'misc'
    'zebra.txt' --> 'z'
    'Alpha@@.txt' --> 'a'
    '!@#.txt' --> 'misc'
    '''
    if filename[0].isalpha():
        return filename[0].lower()
    else:
        return 'misc'


def readdirectory():
    '''
    read the filename in the current directory and append them to a list
    '''
    global filenames
    for files in os.listdir(os.getcwd()):
        if os.path.isfile(os.path.join(os.getcwd(), files)):
            filenames.append(files)
    filenames.remove('main.py')  # removing script from the file list


# getting the first letters of the file & creating a file in the current_dir
def createfolder():
    '''
    creating a folders
    '''
    global filenames
    for f in filenames:
        if os.path.isdir(getfoldername(f)):
            print("folder already created")
        else:
            os.mkdir(getfoldername(f))
            print('creating folder...')


# moving the file into the proper folder
def movetofolder():
    '''
    movetofolder('zebra.py','z')

    'zebra.py'(moved to) 'z'
    '''
    global filenames
    for i in filenames:
        filename = i
        file = getfoldername(i)
        source = os.path.join(os.getcwd(), filename)
        destination = os.path.join(os.getcwd(), file)
        print(f"moving {source} to {destination}")
        shutil.move(source, destination)


if __name__ == '__main__':
    readdirectory()
    createfolder()
    movetofolder()



File: projects/XKCD_downloader/xkcd_dowloader.py

import requests
from bs4 import BeautifulSoup as bs
import shutil
import argparse

# Code to add the cli

parser = argparse.ArgumentParser()
parser.add_argument("-l", "--issue", required=True, help="Comics Issue Number")
args = vars(parser.parse_args())


#Storing the comic issue number provided by the user
issue_number = args['issue']

#Complete url for the issue
url = "https://xkcd.com/"+ issue_number


response = requests.get(url)

#Checking if we can fetch the url or not
if response.status_code ==200:
    soup = bs(response.content, 'html.parser')
    image_link = soup.find_all('img')[2]['src']
    image_name = image_link.split('/')[-1]
    image_url = "https:" + image_link
    r = requests.get(image_url, stream=True)
    if r.status_code == 200:
        #This ensures the image file is loaded correctly
        r.raw.decode_content = True

        # Creating the image file 
        with open(image_name, 'wb') as f:
            shutil.copyfileobj(r.raw, f)

        print('Image successfully Downloaded: ', image_name)
    else:
        print('Image Couldn\'t be retreived')
else:
    print("Issue number is invalid")



File: projects/Network Usage Tracker/network_usage_tracker.py


# NETWORK USAGE TRACKER

# imported necessary library
from tkinter import *
import tkinter as tk
import tkinter.messagebox as mbox
from pil import ImageTk, Image
import time
import psutil
import socket

# Main Window & Configuration
window1 = tk.Tk() # created a tkinter gui window frame
window1.title("Network Usage Tracker") # title given is "DICTIONARY"
window1.geometry('1000x700')

# top label
start1 = tk.Label(text = "NETWORK USAGE\nTRACKER", font=("Arial", 55,"underline"), fg="magenta") # same way bg
start1.place(x = 150, y = 10)

def start_fun():
    window1.destroy()

# start button created
startb = Button(window1, text="START",command=start_fun,font=("Arial", 25), bg = "orange", fg = "blue", borderwidth=3, relief="raised")
startb.place(x =130 , y =590 )

# image on the main window
path = "Images/front.png"
# Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img1 = ImageTk.PhotoImage(Image.open(path))
# The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window1, image = img1)
panel.place(x = 320, y = 200)

# function created for exiting
def exit_win():
    if mbox.askokcancel("Exit", "Do you want to exit?"):
        window1.destroy()

# exit button created
exitb = Button(window1, text="EXIT",command=exit_win,font=("Arial", 25), bg = "red", fg = "blue", borderwidth=3, relief="raised")
exitb.place(x =730 , y = 590 )
window1.protocol("WM_DELETE_WINDOW", exit_win)
window1.mainloop()

# main window created
window = Tk()
window.title("Network Usage Tracker")
window.geometry("1000x700")

# top label
top1 = Label(window, text="NETWORK USAGE\nTRACKER", font=("Arial", 50,'underline'), fg="magenta")
top1.place(x = 190, y = 10)

top1 = Label(window, text="MAX LIMIT  :  1 MB/sec", font=("Arial", 50), fg="green")
top1.place(x = 130, y = 180)

# text area
path_text = Text(window, height=1, width=24, font=("Arial", 50), bg="white", fg="blue",borderwidth=2, relief="solid")
path_text.place(x=50, y = 300)

# l1 = Label(window, fg='blue', font=("Arial", 50))
# l1.place(x = 80, y = 300)

top1 = Label(window, text="Connection Status :", font=("Arial", 50), fg="green")
top1.place(x = 200, y = 450)

l2 = Label(window, fg='blue', font=("Arial", 30))
l2.place(x = 200, y = 530)

def convert_to_gbit(value):
    return value/1024./1024./1024.*8

# function defined to update the usage instantly
old_value = 0
def update_label():
    global old_value
    new_value = psutil.net_io_counters().bytes_sent + psutil.net_io_counters().bytes_recv
    # if old_value:
    # send_stat(new_value - old_value)
    x = "{0:.3f}".format(new_value - old_value)
    # l1.configure(text="")
    # l1.configure(text= "Usage : " + str(x) + " bytes/sec")
    path_text.delete("1.0", "end")
    path_text.insert(END, "Usage : " + str(x) + " bytes/sec")

    # for updating connection status
    IPaddress = socket.gethostbyname(socket.gethostname())
    if IPaddress == "127.0.0.1":
        l2.configure(text="No internet, your localhost is\n" + IPaddress)
    else:
        l2.configure(text="Connected, with the IP address\n" + IPaddress)

    # for checking max limit exceeded
    if(new_value - old_value>1000000):
        mbox.showinfo("Exceed Status", "Max Limit Usage Exceeded.")

    old_value = new_value

    time.sleep(0.5)
    window.after(1, update_label)

update_label()


# function for exiting window
def exit_win():
    if mbox.askokcancel("Exit", "Do you want to exit?"):
        window.destroy()

window.protocol("WM_DELETE_WINDOW", exit_win)
window.mainloop()


File: projects/Compute_IoU/Compute_IoU.py

import numpy as np

def Cal_IoU(GT_bbox, Pred_bbox):
    '''
    Args:
        GT_bbox:  the bounding box of the ground truth
        Pred_bbox: the bounding box of the predicted
    Returns:
        IoU: Intersection over Union
    '''
    #1. Calculate the area of the intersecting area
    ixmin = max(GT_bbox[0], Pred_bbox[0])
    iymin = max(GT_bbox[1], Pred_bbox[1])
    ixmax = min(GT_bbox[2], Pred_bbox[2])
    iymax = min(GT_bbox[3], Pred_bbox[3])
    iw = np.maximum(ixmax - ixmin + 1., 0.) # the weight of the area
    ih = np.maximum(iymax - iymin + 1., 0.) # the height of the area
    area = iw * ih

    #2. Calculate the area of all area
    #S = S1 + S2 - area
    S1 = (Pred_bbox[2] - GT_bbox[0] + 1) * (Pred_bbox[3] - GT_bbox[1] + 1)
    S2 = (GT_bbox[2] - GT_bbox[0] + 1) * (GT_bbox[3] - GT_bbox[1] + 1)
    S = S1 + S2 - area

    #3. Calculate the IoU
    iou = area / S
    return iou

if __name__ == "__main__":
    pred_bbox = np.array([40, 40, 100, 100])
    gt_bbox = np.array([70, 80, 110, 130])
    print(Cal_IoU(pred_bbox, gt_bbox))



File: projects/Find_imdb_rating/find_IMDb_rating.py

from bs4 import BeautifulSoup
import requests
import pandas as pd
import os

# Setting up session
s = requests.session()  

# List contaiting all the films for which data has to be scraped from IMDB
films = []

# Lists contaiting web scraped data
names = []
ratings = []
genres = []

# Define path where your films are present 
# For eg: "/Users/utkarsh/Desktop/films"
path = input("Enter the path where your films are: ")

# Films with extensions
filmswe = os.listdir(path)

for film in filmswe:
    # Append into my films list (without extensions)
    films.append(os.path.splitext(film)[0])
    # print(os.path.splitext(film)[0])

for line in films:
    # x = line.split(", ")
    title = line.lower()
    # release = x[1]
    query = "+".join(title.split()) 
    URL = "https://www.imdb.com/search/title/?title=" + query
    print(URL)
    # print(release)
    try: 
        response = s.get(URL)

        #getting contect from IMDB Website
        content = response.content

        # print(response.status_code)

        soup = BeautifulSoup(response.content, features="html.parser") 
        #searching all films containers found
        containers = soup.find_all("div", class_="lister-item-content")
        for result in containers:
            name1 = result.h3.a.text
            name = result.h3.a.text.lower()

            # Uncomment below lines if you want year specific as well, define year variable before this 
            # year = result.h3.find(
            # "span", class_="lister-item-year text-muted unbold"
            # ).text.lower() 

            #if film found (searching using name)
            if title in name:
                #scraping rating
                rating = result.find("div",class_="inline-block ratings-imdb-rating")["data-value"]
                #scraping genre
                genre = result.p.find("span", class_="genre")
                genre = genre.contents[0]

                #appending name, rating and genre to individual lists
                names.append(name1)
                ratings.append(rating)
                genres.append(genre)
                


    except Exception:
        print("Try again with valid combination of tile and release year")

#storing in pandas dataframe
df = pd.DataFrame({'Film Name':names,'Rating':ratings,'Genre':genres}) 

#making csv using pandas
df.to_csv('film_ratings.csv', index=False, encoding='utf-8')



File: projects/Web_page_summation/app.py

#!/usr/bin/python
from utils.summarize import summarize
import csv
import shutil
import os
import textwrap
import logging
import argparse
import sys


def parse_args(argv):
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description=textwrap.dedent('''\
            A command line utility for website summarization.
            -----------------------------------------------
            These are common commands for this app.'''))
    parser.add_argument(
        'action',
        help='This action should be summarize')
    parser.add_argument(
        '--url',
        help='A link to the website url'
    )
    parser.add_argument(
        '--sentence',
        help='Argument to define number of sentence for the summary',
        type=int,
        default=2)
    parser.add_argument(
        '--language',
        help='Argument to define language of the summary',
        default='English')
    parser.add_argument(
        '--path',
        help='path to csv file')

    return parser.parse_args(argv[1:])


def readCsv(path):
    print('\n\n Processing Csv file \n\n')
    sys.stdout.flush()
    data = []
    try:
        with open(path, 'r') as userFile:
            userFileReader = csv.reader(userFile)
            for row in userFileReader:
                data.append(row)
    except:
        with open(path, 'r', encoding="mbcs") as userFile:
            userFileReader = csv.reader(userFile)
            for row in userFileReader:
                data.append(row)       
    return data


def writeCsv(data, LANGUAGE, SENTENCES_COUNT):
    print('\n\n Updating Csv file \n\n')
    sys.stdout.flush()
    with open('beneficiary.csv', 'w') as newFile:
        newFileWriter = csv.writer(newFile)
        length = len(data)
        position = data[0].index('website')
        for i in range(1, length):
            if i == 1:
                _data = data[0]
                _data.append("summary")
                newFileWriter.writerow(_data)
            try:
                __data = data[i]
                summary = summarize(
                    (data[i][position]), LANGUAGE, SENTENCES_COUNT)
                __data.append(summary)
                newFileWriter.writerow(__data)
            except:
                print('\n\n Error Skipping line \n\n')
                sys.stdout.flush()


def processCsv(path, LANGUAGE, SENTENCES_COUNT):
    try:
        print('\n\n Proessing Started \n\n')
        sys.stdout.flush()
        data = readCsv(path)
        writeCsv(data, LANGUAGE, SENTENCES_COUNT)
    except:
        print('\n\n Invalid file in file path \n\n')
        sys.stdout.flush()


def main(argv=sys.argv):
        # Configure logging
    logging.basicConfig(filename='applog.log',
                        filemode='w',
                        level=logging.INFO,
                        format='%(levelname)s:%(message)s')
    args = parse_args(argv)
    action = args.action
    url = args.url
    path = args.path
    LANGUAGE = "english" if args.language is None else args.language
    SENTENCES_COUNT = 2 if args.sentence is None else args.sentence
    if action == 'bulk':
        if path is None:
            print(
                '\n\n Invalid Entry!, please Ensure you enter a valid file path \n\n')
            sys.stdout.flush()
            return
        # guide against errors
        try:
            processCsv(path, LANGUAGE, SENTENCES_COUNT)
        except:
            print(
                '\n\n Invalid Entry!, please Ensure you enter a valid file path \n\n')
            sys.stdout.flush()
        print('Completed')
        sys.stdout.flush()
        if os.path.isfile('beneficiary.csv'):
            return shutil.move('beneficiary.csv', path)
        return
    if action == 'simple':
        # guide against errors
        try:
            summarize(url, LANGUAGE, SENTENCES_COUNT)
        except:
            print(
                '\n\n Invalid Entry!, please Ensure you enter a valid web link \n\n')
            sys.stdout.flush()
        print('Completed')
        sys.stdout.flush()
    else:
        print(
            '\nAction command is not supported\n for help: run python3 app.py -h'
        )
        sys.stdout.flush()
        return


if __name__ == '__main__':
    main()



File: projects/Web_page_summation/utils/__init__.py




File: projects/Web_page_summation/utils/summarize.py

from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from sumy.parsers.html import HtmlParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.lex_rank import LexRankSummarizer as Summarizer
from sumy.nlp.stemmers import Stemmer
from sumy.utils import get_stop_words
import sys


def summarize(url=None, LANGUAGE='English', SENTENCES_COUNT=2):
    parser = HtmlParser.from_url(url, Tokenizer(LANGUAGE))
    stemmer = Stemmer(LANGUAGE)
    summarizer = Summarizer(stemmer)
    summarizer.stop_words = get_stop_words(LANGUAGE)
    result = ''
    for sentence in summarizer(parser.document, SENTENCES_COUNT):
        result = result + ' ' + str(sentence)
        try:
            result = result + ' ' + str(sentence)

        except:
            print(
                    '\n\n Invalid Entry!, please Ensure you enter a valid web link \n\n')
            sys.stdout.flush()
            return (
                    '\n\n Invalid Entry!, please Ensure you enter a valid web link \n\n')
    print('\n\n'+str(url)+'\n\n'+str(result))
    sys.stdout.flush()
    return result



File: projects/Web_page_summation/utils/test.py

import tensorflow as tf
from model import Model
from utils import build_dict, build_dataset, batch_iter, get_text_list
valid_article_path = '.'
valid_title_path = '.'
tf.reset_default_graph()
default_path = '.'


class args:
    pass


args.num_hidden = 150
args.num_layers = 2
args.beam_width = 10
args.glove = "store_true"
args.embedding_size = 300

args.learning_rate = 1e-3
args.batch_size = 64
args.num_epochs = 10
args.keep_prob = 0.8

args.toy = True

args.with_model = "store_true"


print("Loading dictionary...")
word_dict, reversed_dict, article_max_len, summary_max_len = build_dict(
    "valid", args.toy)
print("Loading validation dataset...")
valid_x = build_dataset(
    "valid", word_dict, article_max_len, summary_max_len, args.toy)
valid_x_len = [len([y for y in x if y != 0]) for x in valid_x]
print("Loading article and reference...")
article = get_text_list(valid_article_path, args.toy)
reference = get_text_list(valid_title_path, args.toy)

with tf.Session() as sess:
    print("Loading saved model...")
    model = Model(reversed_dict, article_max_len,
                  summary_max_len, args, forward_only=True)
    saver = tf.train.Saver(tf.global_variables())
    ckpt = tf.train.get_checkpoint_state(default_path + "saved_model/")
    saver.restore(sess, ckpt.model_checkpoint_path)

    batches = batch_iter(valid_x, [0] * len(valid_x), args.batch_size, 1)

    print("Writing summaries to 'result.txt'...")
    for batch_x, _ in batches:
        batch_x_len = [len([y for y in x if y != 0]) for x in batch_x]

        valid_feed_dict = {
            model.batch_size: len(batch_x),
            model.X: batch_x,
            model.X_len: batch_x_len,
        }

        prediction = sess.run(model.prediction, feed_dict=valid_feed_dict)
        prediction_output = [[reversed_dict[y]
                              for y in x] for x in prediction[:, 0, :]]
        summary_array = []
        with open(default_path + "result.txt", "a") as f:
            for line in prediction_output:
                summary = list()
                for word in line:
                    if word == "</s>":
                        break
                    if word not in summary:
                        summary.append(word)
                summary_array.append(" ".join(summary))
                # print(" ".join(summary), file=f)

    print('Summaries have been generated')



File: projects/Web_page_summation/utils/model.py

import tensorflow as tf
from tensorflow.contrib import rnn
from utils import get_init_embedding


class Model(object):
    def __init__(self, reversed_dict, article_max_len, summary_max_len, args, forward_only=False):
        self.vocabulary_size = len(reversed_dict)
        self.embedding_size = args.embedding_size
        self.num_hidden = args.num_hidden
        self.num_layers = args.num_layers
        self.learning_rate = args.learning_rate
        self.beam_width = args.beam_width
        if not forward_only:
            self.keep_prob = args.keep_prob
        else:
            self.keep_prob = 1.0
        self.cell = tf.nn.rnn_cell.BasicLSTMCell
        with tf.variable_scope("decoder/projection"):
            self.projection_layer = tf.layers.Dense(
                self.vocabulary_size, use_bias=False)

        self.batch_size = tf.placeholder(tf.int32, (), name="batch_size")
        self.X = tf.placeholder(tf.int32, [None, article_max_len])
        self.X_len = tf.placeholder(tf.int32, [None])
        self.decoder_input = tf.placeholder(tf.int32, [None, summary_max_len])
        self.decoder_len = tf.placeholder(tf.int32, [None])
        self.decoder_target = tf.placeholder(tf.int32, [None, summary_max_len])
        self.global_step = tf.Variable(0, trainable=False)

        with tf.name_scope("embedding"):
            if not forward_only and args.glove:
                init_embeddings = tf.constant(get_init_embedding(
                    reversed_dict, self.embedding_size), dtype=tf.float32)
            else:
                init_embeddings = tf.random_uniform(
                    [self.vocabulary_size, self.embedding_size], -1.0, 1.0)
            self.embeddings = tf.get_variable(
                "embeddings", initializer=init_embeddings)
            self.encoder_emb_inp = tf.transpose(
                tf.nn.embedding_lookup(self.embeddings, self.X), perm=[1, 0, 2])
            self.decoder_emb_inp = tf.transpose(tf.nn.embedding_lookup(
                self.embeddings, self.decoder_input), perm=[1, 0, 2])

        with tf.name_scope("encoder"):
            fw_cells = [self.cell(self.num_hidden)
                        for _ in range(self.num_layers)]
            bw_cells = [self.cell(self.num_hidden)
                        for _ in range(self.num_layers)]
            fw_cells = [rnn.DropoutWrapper(cell) for cell in fw_cells]
            bw_cells = [rnn.DropoutWrapper(cell) for cell in bw_cells]

            encoder_outputs, encoder_state_fw, encoder_state_bw = tf.contrib.rnn.stack_bidirectional_dynamic_rnn(
                fw_cells, bw_cells, self.encoder_emb_inp,
                sequence_length=self.X_len, time_major=True, dtype=tf.float32)
            self.encoder_output = tf.concat(encoder_outputs, 2)
            encoder_state_c = tf.concat(
                (encoder_state_fw[0].c, encoder_state_bw[0].c), 1)
            encoder_state_h = tf.concat(
                (encoder_state_fw[0].h, encoder_state_bw[0].h), 1)
            self.encoder_state = rnn.LSTMStateTuple(
                c=encoder_state_c, h=encoder_state_h)

        with tf.name_scope("decoder"), tf.variable_scope("decoder") as decoder_scope:
            decoder_cell = self.cell(self.num_hidden * 2)

            if not forward_only:
                attention_states = tf.transpose(self.encoder_output, [1, 0, 2])
                attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(
                    self.num_hidden * 2, attention_states, memory_sequence_length=self.X_len, normalize=True)
                decoder_cell = tf.contrib.seq2seq.AttentionWrapper(decoder_cell, attention_mechanism,
                                                                   attention_layer_size=self.num_hidden * 2)
                initial_state = decoder_cell.zero_state(
                    dtype=tf.float32, batch_size=self.batch_size)
                initial_state = initial_state.clone(
                    cell_state=self.encoder_state)
                helper = tf.contrib.seq2seq.TrainingHelper(
                    self.decoder_emb_inp, self.decoder_len, time_major=True)
                decoder = tf.contrib.seq2seq.BasicDecoder(
                    decoder_cell, helper, initial_state)
                outputs, _, _ = tf.contrib.seq2seq.dynamic_decode(
                    decoder, output_time_major=True, scope=decoder_scope)
                self.decoder_output = outputs.rnn_output
                self.logits = tf.transpose(
                    self.projection_layer(self.decoder_output), perm=[1, 0, 2])
                self.logits_reshape = tf.concat(
                    [self.logits, tf.zeros([self.batch_size, summary_max_len - tf.shape(self.logits)[1], self.vocabulary_size])], axis=1)
            else:
                tiled_encoder_output = tf.contrib.seq2seq.tile_batch(
                    tf.transpose(self.encoder_output, perm=[1, 0, 2]), multiplier=self.beam_width)
                tiled_encoder_final_state = tf.contrib.seq2seq.tile_batch(
                    self.encoder_state, multiplier=self.beam_width)
                tiled_seq_len = tf.contrib.seq2seq.tile_batch(
                    self.X_len, multiplier=self.beam_width)
                attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(
                    self.num_hidden * 2, tiled_encoder_output, memory_sequence_length=tiled_seq_len, normalize=True)
                decoder_cell = tf.contrib.seq2seq.AttentionWrapper(decoder_cell, attention_mechanism,
                                                                   attention_layer_size=self.num_hidden * 2)
                initial_state = decoder_cell.zero_state(
                    dtype=tf.float32, batch_size=self.batch_size * self.beam_width)
                initial_state = initial_state.clone(
                    cell_state=tiled_encoder_final_state)
                decoder = tf.contrib.seq2seq.BeamSearchDecoder(
                    cell=decoder_cell,
                    embedding=self.embeddings,
                    start_tokens=tf.fill([self.batch_size], tf.constant(2)),
                    end_token=tf.constant(3),
                    initial_state=initial_state,
                    beam_width=self.beam_width,
                    output_layer=self.projection_layer
                )
                outputs, _, _ = tf.contrib.seq2seq.dynamic_decode(
                    decoder, output_time_major=True, maximum_iterations=summary_max_len, scope=decoder_scope)
                self.prediction = tf.transpose(
                    outputs.predicted_ids, perm=[1, 2, 0])

        with tf.name_scope("loss"):
            if not forward_only:
                crossent = tf.nn.sparse_softmax_cross_entropy_with_logits(
                    logits=self.logits_reshape, labels=self.decoder_target)
                weights = tf.sequence_mask(
                    self.decoder_len, summary_max_len, dtype=tf.float32)
                self.loss = tf.reduce_sum(
                    crossent * weights / tf.to_float(self.batch_size))

                params = tf.trainable_variables()
                gradients = tf.gradients(self.loss, params)
                clipped_gradients, _ = tf.clip_by_global_norm(gradients, 5.0)
                optimizer = tf.train.AdamOptimizer(self.learning_rate)
                self.update = optimizer.apply_gradients(
                    zip(clipped_gradients, params), global_step=self.global_step)



File: projects/Web_page_summation/utils/comparison.py


# https://github.com/chakki-works/sumeval
# https://github.com/Tian312/awesome-text-summarization

from sumeval.metrics.rouge import RougeCalculator
from sumeval.metrics.bleu import BLEUCalculator


def eval_rouges(refrence_summary, model_summary):
    # refrence_summary = "tokyo shares close up #.## percent"
    # model_summary = "tokyo stocks close up # percent to fresh record high"

    rouge = RougeCalculator(stopwords=True, lang="en")

    rouge_1 = rouge.rouge_n(
        summary=model_summary,
        references=refrence_summary,
        n=1)

    rouge_2 = rouge.rouge_n(
        summary=model_summary,
        references=[refrence_summary],
        n=2)

    rouge_l = rouge.rouge_l(
        summary=model_summary,
        references=[refrence_summary])

    # You need spaCy to calculate ROUGE-BE

    rouge_be = rouge.rouge_be(
        summary=model_summary,
        references=[refrence_summary])

    bleu = BLEUCalculator()
    bleu_score = bleu.bleu(summary=model_summary,
                           references=[refrence_summary])

    # print("ROUGE-1: {}, ROUGE-2: {}, ROUGE-L: {}, ROUGE-BE: {}".format(
    #    rouge_1, rouge_2, rouge_l, rouge_be
    # ).replace(", ", "\n"))

    return rouge_1, rouge_2, rouge_l, rouge_be, bleu_score

# rouge_1, rouge_2,rouge_l,rouge_be = eval_rouges( "tokyo shares close up #.## percent",
#                                                "tokyo stocks close up # percent to fresh record high")
#
# print("ROUGE-1: {}, ROUGE-2: {}, ROUGE-L: {}, ROUGE-BE: {}".format(
#        rouge_1, rouge_2, rouge_l, rouge_be
#    ).replace(", ", "\n"))



File: projects/Web_page_summation/utils/utils.py

import re
import collections
import pickle
import numpy as np
from nltk.tokenize import word_tokenize
default_path = '.'
train_article_path = '.'
train_title_path = '.'
valid_article_path = '.'


def clean_str(sentence):
    sentence = re.sub("[#.]+", "#", sentence)
    return sentence


def get_text_list(data_path, toy):
    with open(data_path, "r", encoding="utf-8") as f:
        if not toy:
            return [clean_str(x.strip()) for x in f.readlines()][:200000]
        else:
            return [clean_str(x.strip()) for x in f.readlines()][:50]


def build_dict(step, toy=False):
    if step == "train":
        train_article_list = get_text_list(train_article_path, toy)
        train_title_list = get_text_list(train_title_path, toy)

        words = list()
        for sentence in train_article_list + train_title_list:
            for word in word_tokenize(sentence):
                words.append(word)

        word_counter = collections.Counter(words).most_common()
        word_dict = dict()
        word_dict["<padding>"] = 0
        word_dict["<unk>"] = 1
        word_dict["<s>"] = 2
        word_dict["</s>"] = 3
        for word, _ in word_counter:
            word_dict[word] = len(word_dict)

        with open(default_path + "word_dict.pickle", "wb") as f:
            pickle.dump(word_dict, f)

    elif step == "valid":
        with open(default_path + "word_dict.pickle", "rb") as f:
            word_dict = pickle.load(f)

    reversed_dict = dict(zip(word_dict.values(), word_dict.keys()))

    article_max_len = 50
    summary_max_len = 15

    return word_dict, reversed_dict, article_max_len, summary_max_len


def build_dataset(
        step, word_dict, article_max_len, summary_max_len, toy=False):
    if step == "train":
        article_list = get_text_list(train_article_path, toy)
        title_list = get_text_list(train_title_path, toy)
    elif step == "valid":
        article_list = get_text_list(valid_article_path, toy)
    else:
        raise NotImplementedError

    x = [word_tokenize(d) for d in article_list]
    x = [[word_dict.get(w, word_dict["<unk>"]) for w in d] for d in x]
    x = [d[:article_max_len] for d in x]
    x = [d + (article_max_len - len(d)) * [word_dict["<padding>"]] for d in x]

    if step == "valid":
        return x
    else:
        y = [word_tokenize(d) for d in title_list]
        y = [[word_dict.get(w, word_dict["<unk>"]) for w in d] for d in y]
        y = [d[:(summary_max_len - 1)] for d in y]
        return x, y


def batch_iter(inputs, outputs, batch_size, num_epochs):
    inputs = np.array(inputs)
    outputs = np.array(outputs)

    num_batches_per_epoch = (len(inputs) - 1) // batch_size + 1
    for epoch in range(num_epochs):
        for batch_num in range(num_batches_per_epoch):
            start_index = batch_num * batch_size
            end_index = min((batch_num + 1) * batch_size, len(inputs))
            yield inputs[start_index:end_index], outputs[start_index:end_index]


def get_init_embedding(reversed_dict, embedding_size):
    # glove_file = default_path + "glove/glove.6B.300d.txt"
    # word2vec_file = get_tmpfile(default_path + "word2vec_format.vec")
    # glove2word2vec(glove_file, word2vec_file)
    print("Loading Glove vectors...")
    # word_vectors = KeyedVectors.load_word2vec_format(word2vec_file)

    with open(default_path + "glove/model_glove_300.pkl", 'rb') as handle:
        word_vectors = pickle.load(handle)

    word_vec_list = list()
    for _, word in sorted(reversed_dict.items()):
        try:
            word_vec = word_vectors.word_vec(word)
        except KeyError:
            word_vec = np.zeros([embedding_size], dtype=np.float32)

        word_vec_list.append(word_vec)

    # Assign random vector to <s>, </s> token
    word_vec_list[2] = np.random.normal(0, 1, embedding_size)
    word_vec_list[3] = np.random.normal(0, 1, embedding_size)

    return np.array(word_vec_list)



File: projects/Web_page_summation/utils/train.py

import os
import tensorflow as tf
import time
from model import Model
from utils import build_dict, build_dataset, batch_iter
start = time.perf_counter()
default_path = '.'


class args:
    pass


args.num_hidden = 150
args.num_layers = 2
args.beam_width = 10
args.glove = "store_true"
args.embedding_size = 300

args.learning_rate = 1e-3
args.batch_size = 64
args.num_epochs = 10
args.keep_prob = 0.8

args.toy = False  # "store_true"

args.with_model = "store_true"


if not os.path.exists(default_path + "saved_model"):
    os.mkdir(default_path + "saved_model")
else:
    # if args.with_model:
    old_model_checkpoint_path = open(
        default_path + 'saved_model/checkpoint', 'r')
    old_model_checkpoint_path = "".join(
        [
            default_path + "saved_model/",
            old_model_checkpoint_path.read().splitlines()[0].split('"')[1]])


print("Building dictionary...")
word_dict, reversed_dict, article_max_len, summary_max_len = build_dict(
    "train", args.toy)
print("Loading training dataset...")
train_x, train_y = build_dataset(
    "train", word_dict, article_max_len, summary_max_len, args.toy)

tf.reset_default_graph()

with tf.Session() as sess:
    model = Model(reversed_dict, article_max_len, summary_max_len, args)
    sess.run(tf.global_variables_initializer())
    saver = tf.train.Saver(tf.global_variables())
    if 'old_model_checkpoint_path' in globals():
        print("Continuing from previous trained model:",
              old_model_checkpoint_path, "...")
        saver.restore(sess, old_model_checkpoint_path)

    batches = batch_iter(train_x, train_y, args.batch_size, args.num_epochs)
    num_batches_per_epoch = (len(train_x) - 1) // args.batch_size + 1

    print("\nIteration starts.")
    print("Number of batches per epoch :", num_batches_per_epoch)
    for batch_x, batch_y in batches:
        batch_x_len = list(
            map(lambda x: len([y for y in x if y != 0]), batch_x))
        batch_decoder_input = list(
            map(lambda x: [word_dict["<s>"]] + list(x), batch_y))
        batch_decoder_len = list(
            map(lambda x: len([y for y in x if y != 0]), batch_decoder_input))
        batch_decoder_output = list(
            map(lambda x: list(x) + [word_dict["</s>"]], batch_y))

        batch_decoder_input = list(
            map(
                lambda d: d + (summary_max_len - len(d)) * [word_dict["<padding>"]],
                batch_decoder_input))
        batch_decoder_output = list(
            map(
                lambda d: d + (summary_max_len - len(d)) * [word_dict["<padding>"]],
                batch_decoder_output))

        train_feed_dict = {
            model.batch_size: len(batch_x),
            model.X: batch_x,
            model.X_len: batch_x_len,
            model.decoder_input: batch_decoder_input,
            model.decoder_len: batch_decoder_len,
            model.decoder_target: batch_decoder_output
        }

        _, step, loss = sess.run(
            [model.update,
             model.global_step, model.loss], feed_dict=train_feed_dict)

        if step % 1000 == 0:
            print("step {0}: loss = {1}".format(step, loss))

        if step % num_batches_per_epoch == 0:
            hours, rem = divmod(time.perf_counter() - start, 3600)
            minutes, seconds = divmod(rem, 60)
            saver.save(sess, default_path +
                       "saved_model/model.ckpt", global_step=step)
            print(" Epoch {0}: Model is saved.".format(step // num_batches_per_epoch),
                  "Elapsed: {:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds), "\n")



File: projects/Web_page_summation/utils/prepare.py

import gzip

default_path = '.'

with gzip.open(default_path + "sumdata/train/train.article.txt.gz", "rb") as gz:
    with open(default_path + "sumdata/train/train.article.txt", "wb") as out:
        out.write(gz.read())

with gzip.open(default_path + "sumdata/train/train.title.txt.gz", "rb") as gz:
    with open(default_path + "sumdata/train/train.title.txt", "wb") as out:
        out.write(gz.read())



File: projects/Scrape_Hacker_News/main.py

import requests
import os
from bs4 import BeautifulSoup, SoupStrainer
# Makes Output Directory if it does not exist
if not os.path.exists(os.path.join(os.getcwd(), 'HackerNews')):
    os.makedirs(os.path.join(os.getcwd(), 'HackerNews'))
'''
@params page_no: The page number of HackerNews to fetch.
Adding only page number in order to add multiprocess support in future.
@params verbose: Adds verbose output to screen instead
of running the program silently.
'''


def fetch(page_no, verbose=False):
    # Should be unreachable, but just in case
    if page_no <= 0:
        raise ValueError('Number of Pages must be greater than zero')
    page_no = min(page_no, 20)
    i = page_no
    if verbose:
        print('Fetching Page {}...'.format(i))
    try:
        res = requests.get('https://news.ycombinator.com/?p=' + str(i))
        only_td = SoupStrainer('td')
        soup = BeautifulSoup(res.content, 'html.parser', parse_only=only_td)
        tdtitle = soup.find_all('td', attrs={'class': 'title'})
        tdmetrics = soup.find_all('td', attrs={'class': 'subtext'})
        with open(os.path.join('HackerNews', 'NewsPage{}.txt'.format(i)), 'w+') as f:
            f.write('-' * 80)
            f.write('\n')
            f.write('Page {}'.format(i))
            tdtitle = soup.find_all('td', attrs={'class': 'title'})
            tdrank = soup.find_all(
                'td',
                attrs={
                    'class': 'title',
                    'align': 'right'})
            tdtitleonly = [t for t in tdtitle if t not in tdrank]
            tdmetrics = soup.find_all('td', attrs={'class': 'subtext'})
            tdt = tdtitleonly
            tdr = tdrank
            tdm = tdmetrics
            num_iter = min(len(tdr), len(tdt))
            for idx in range(num_iter):
                f.write('\n' + '-' * 80 + '\n')
                rank = tdr[idx].find('span', attrs={'class': 'rank'})
                titl = tdt[idx].find('a', attrs={'class': 'storylink'})
                url = titl['href'] if titl and titl['href'].startswith(
                    'https') else 'https://news.ycombinator.com/' + titl['href']
                site = tdt[idx].find('span', attrs={'class': 'sitestr'})
                score = tdm[idx].find('span', attrs={'class': 'score'})
                time = tdm[idx].find('span', attrs={'class': 'age'})
                author = tdm[idx].find('a', attrs={'class': 'hnuser'})
                f.write(
                    '\nArticle Number: ' +
                    rank.text.replace(
                        '.',
                        '') if rank else '\nArticle Number: Could not get article number')
                f.write(
                    '\nArticle Title: ' +
                    titl.text if titl else '\nArticle Title: Could not get article title')
                f.write(
                    '\nSource Website: ' +
                    site.text if site else '\nSource Website: https://news.ycombinator.com')
                f.write(
                    '\nSource URL: ' +
                    url if url else '\nSource URL: No URL found for this article')
                f.write(
                    '\nArticle Author: ' +
                    author.text if author else '\nArticle Author: Could not get article author')
                f.write(
                    '\nArticle Score: ' +
                    score.text if score else '\nArticle Score: Not Scored')
                f.write(
                    '\nPosted: ' +
                    time.text if time else '\nPosted: Could not find when the article was posted')
                f.write('\n' + '-' * 80 + '\n')
    except (requests.ConnectionError, requests.packages.urllib3.exceptions.ConnectionError) as e:
        print('Connection Failed for page {}'.format(i))
    except requests.RequestException as e:
        print("Some ambiguous Request Exception occurred. The exception is " + str(e))


while(True):
    try:
        pages = int(
            input('Enter number of pages that you want the HackerNews for (max 20): '))
        v = input('Want verbose output y/[n] ?')
        verbose = v.lower().startswith('y')
        if pages > 20:
            print('A maximum of only 20 pages can be fetched')
        pages = min(pages, 20)
        for page_no in range(1, pages + 1):
            fetch(page_no, verbose)
        break
    except ValueError:
        print('\nInvalid input, probably not a positive integer\n')
        continue



File: projects/PDF to MP3/PDF__TO__MP3.py

import pyttsx3
import PyPDF2
from tkinter import filedialog

location = filedialog.askopenfilename()
full_text =""

with open(location, 'rb') as book:

	try:
		reader = PyPDF2.PdfFileReader(book)	

		audio = pyttsx3.init()

		print('\n')
		print('Recommended Speed ------> 115')

		set_speed = input('Please Enter Your Prefered Reading Speed --------> ')
		audio.setProperty('rate',int(set_speed))

		total_pages = reader.numPages

		print('\n')
		print('Location of File  -------> ' + location)
		print('\n')
		print('Total Number of Pages -------> ' + str(total_pages))

		try:
			for page in range(total_pages):
				next_page = reader.getPage(page)
				content = next_page.extractText()
				full_text += content

			audio.save_to_file(full_text, 'output.mp3')
			print("Converting... \n Please Wait....")
			audio.runAndWait()

		except:
			print('Task Failed Successfully! ')

	except:
		print('\n')
		print('---------> Cannot Read PDF <---------')
		print('\n')
		print('--------->Invalid PDF format <--------')
		print('\n')
		print('OR maybe there is something wrong with your brain that you are trying \n to convert a file that is not in .pdf format')


<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![forthebadge](https://forthebadge.com/images/badges/built-by-developers.svg)](https://forthebadge.com)
[![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com)
[![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](https://forthebadge.com)
[![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://forthebadge.com)

# Python-Mini-Projects

[![All Contributors](https://img.shields.io/github/contributors/Python-World/python-mini-projects)](#contributors-)
![Issues](https://img.shields.io/github/issues/Python-World/python-mini-projects)
![Pull Requests](https://img.shields.io/github/issues-pr/Python-World/python-mini-projects?)
![Forks](https://img.shields.io/github/forks/Python-World/python-mini-projects)
![Stars](https://img.shields.io/github/stars/Python-World/python-mini-projects)
![License](https://img.shields.io/github/license/Python-World/python-mini-projects)

A collection of simple python mini projects to enhance your Python skills.

If you want to learn about python, visit [here.](https://github.com/Python-World/Py-Resources)

If you are new to Github and open source then, visit [here.](https://towardsdatascience.com/getting-started-with-git-and-github-6fcd0f2d4ac6)

## Steps To Follow

- Select an issue and ask to be _assigned_ to it.
- Check existing scripts in the [projects](/projects/) directory.
- **Star** this repository.
- On the [python-mini-projects](https://github.com/Python-World/python-mini-projects) repo page, click the **Fork** button.
    <br><img src="https://help.github.com/assets/images/help/repository/fork_button.jpg" title="Fork image" width="400"/>
- **Clone** your forked repository to your local machine. This button will show you the URL to run.
    <br><img src="https://docs.github.com/assets/images/help/repository/code-button.png" title="Code button" width="400"/>

    For example, run this command inside your terminal:

    ```bash
    git clone https://github.com/<your-github-username>/python-mini-projects.git
    ```

    **Replace \<your-github-username\>!**

    Learn more about [forking](https://help.github.com/en/github/getting-started-with-github/fork-a-repo) and [cloning a repo](https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/cloning-a-repository).
- Before you make any changes, [keep your fork in sync](https://www.freecodecamp.org/news/how-to-sync-your-fork-with-the-original-git-repository/) to avoid merge conflicts:

    ```bash
    git remote add upstream https://github.com/Python-World/python-mini-projects.git
    git fetch upstream
    git pull upstream master
    git push
    ```
    
    Alternatively, GitHub also provides syncing now - click "Fetch upstream" at the top of your repo below "Code" button.

- If you run into a **merge conflict**, you have to resolve the conflict. There are a lot of guides online, or you can try this one by [opensource.com](https://opensource.com/article/20/4/git-merge-conflict).

- Checkout to development branch (*name your branch according to the issue name*).

    ```bash
    git checkout -b <branch-name>
    ```

- Create a folder in
  [projects directory](https://github.com/Python-World/python-mini-projects/tree/master/projects)
  according to issue name.
- Write your code and add to the respective folder in the projects directory, locally.
- Don't forget to add a `README.md` in your folder, according to the
   [README_TEMPLATE.](https://github.com/Python-World/python-mini-projects/blob/master/README_TEMPLATE.md)
- Add the changes with `git add`, `git commit` ([write a good commit message](https://chris.beams.io/posts/git-commit/), if possible):

    ```bash
    git add -A
    git commit -m "<your message>"
    ```

- Push the code _to your repository_.

    ```bash
    git push origin <branch-name>
    ```

- Go to the GitHub page of _your fork_, and **make a pull request**:

    ![pull request image](https://help.github.com/assets/images/help/pull_requests/choose-base-and-compare-branches.png)

    Read more about pull requests on the [GitHub help pages](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request).
- Now wait, until one of us *reviews your Pull Request*! If there are any conflicts, you will get a notification.

## README Template for scripts

[README Template](https://github.com/Python-World/python-mini-projects/blob/master/README_TEMPLATE.md)

## Connect On Social media

[Join WhatsApp group](https://chat.whatsapp.com/GlLTqQSbocLC23ntKU15O9)

## Contributors ✨

SR No   | Project | Author  
--- | --- | ---
1 | [Hello World](https://github.com/Python-World/python-mini-projects/tree/master/projects/Hello) | [Ravi Chavare](https://github.com/chavarera)
2 | [JSON to CSV](https://github.com/Python-World/python-mini-projects/tree/master/projects/Convert_JSON_to_CSV)| [Murilo Pagliuso](https://github.com/DarkCeptor44)
3 | [Random Password Generator](https://github.com/Python-World/python-mini-projects/tree/master/projects/Random_password_generator) | [Mitesh](https://github.com/Mitesh2499)
4 | [Instagram Profile Info](https://github.com/Python-World/python-mini-projects/tree/master/projects/Instagram_profile) | [Ravi Chavare](https://github.com/chavarera)
5 | [Search string in Files](https://github.com/Python-World/python-mini-projects/tree/master/projects/String_search_from_multiple_files) | [Mitesh](https://github.com/Mitesh2499)
6 | [Fetch links from Webpage](https://github.com/Python-World/python-mini-projects/tree/master/projects/All_links_from_given_webpage) | [Mitesh](https://github.com/Mitesh2499) & [Michael Mba](https://github.com/mikeysan)
7 | [Todo App With Flask](https://github.com/Python-World/python-mini-projects/tree/master/projects/Todo_app) | [Mitesh](https://github.com/Mitesh2499)
8 | [Add Watermark on Images](https://github.com/Python-World/python-mini-projects/tree/master/projects/Image_watermark) | [Mitesh](https://github.com/Mitesh2499)
9 | [WishList App Using Django](https://github.com/Python-World/python-mini-projects/tree/master/projects/WishList) | [Ravi Chavare](https://github.com/chavarera)
10 | [Split Folders into Subfolders](https://github.com/Python-World/python-mini-projects/tree/master/projects/Split_folder_into_subfolders) | [Ravi Chavare](https://github.com/chavarera)
11 | [Download bulk images](https://github.com/Python-World/python-mini-projects/tree/master/projects/Download_images_from_website) | [Mitesh](https://github.com/Mitesh2499)
12 | [Random word from file](https://github.com/Python-World/python-mini-projects/tree/master/projects/Random_word_from_list) | [Ravi Chavare](https://github.com/chavarera)
13 | [Battery notification](https://github.com/Python-World/python-mini-projects/tree/master/projects/Battery_notification) | [Mitesh](https://github.com/Mitesh2499)
14 | [Calculate age](https://github.com/Python-World/python-mini-projects/tree/master/projects/Calculate_age) | [Gaodong](https://github.com/xlgd)
15 | [Text file analysis](https://github.com/Python-World/python-mini-projects/tree/master/projects/Textfile_analysis) | [m044de](https://github.com/m044de/)
16 | [Generate image snipets](https://github.com/Python-World/python-mini-projects/tree/master/projects/Py_carbon_clips) | [ravi chavare](https://github.com/Python-World/)
17 | [Organize file system](https://github.com/Python-World/python-mini-projects/tree/master/projects/Organized_download_folder_with_different_categories) | [Mitesh](https://github.com/Mitesh2499)
18 | [Send emails](https://github.com/Python-World/python-mini-projects/tree/master/projects/Send_email_from_csv) | [Mitesh](https://github.com/Mitesh2499)
19 | [Get Ipaddress and Hostname of Website](https://github.com/Python-World/python-mini-projects/tree/master/projects/Find_out_hostname_and_ip_address) | [Nuh Mohammed](https://github.com/NuhMohammed)|
20 | [Progressbar using tqdm](https://github.com/Python-World/python-mini-projects/tree/master/projects/Terminal_progress_bar_with_images_resizing) | [Mitesh](https://github.com/Mitesh2499)
21 | [Get meta information of images](https://github.com/Python-World/python-mini-projects/tree/master/projects/Get_meta_information_of_images) | [Gaodong](https://github.com/xlgd)
22 | [Captures Frames from video](https://github.com/Python-World/python-mini-projects/tree/master/projects/Capture_Video_Frames) | [phileinSophos](https://github.com/phileinSophos/)
23 | [Fetch Wifi Saved Password Windows](https://github.com/Python-World/python-mini-projects/tree/master/projects/Get_wifi_password) |  [Mitesh](https://github.com/Mitesh2499)
24 | [Save Screenshot of given Website](https://github.com/Python-World/python-mini-projects/tree/master/projects/Snapshot_of_given_website) | [m044de](https://github.com/m044de/)
25 | [Split files using no of lines](https://github.com/Python-World/python-mini-projects/tree/master/projects/Split_File) | [phileinSophos](https://github.com/phileinSophos/)
26 | [Encrypt and decrypt text](https://github.com/Python-World/python-mini-projects/tree/master/projects/Encrypt_and_decrypt_text) | [Gaodong](https://github.com/xlgd)
27 | [Captures screenshot at regular interval of time](https://github.com/Python-World/python-mini-projects/tree/master/projects/capture_screenshot) | [d33pc](https://github.com/d33pc/)
28 | [Create password hash](https://github.com/Python-World/python-mini-projects/tree/master/projects/Hashing_passwords) | [m044de](https://github.com/m044de/)
29 | [Encrypt file and folders](https://github.com/Python-World/python-mini-projects/tree/master/projects/Create_a_script_to_encrypt_files_and_folder) | [Gaodong](https://github.com/xlgd)
30 | [Decimal to binary and vice versa](https://github.com/Python-World/python-mini-projects/tree/master/projects/Decimal_to_binary_convertor_and_vice_versa) | [Alan Anaya](https://github.com/alananayaa/)
31 | [Cli Based Todo Application](https://github.com/Python-World/python-mini-projects/tree/master/projects/Cli_todo) | [Audrey Yang](https://github.com/audrey-yang)
32 | [Currency Convertor cli app](https://github.com/Python-World/python-mini-projects/tree/master/projects/Currency_converter) | [github-of-wone](https://github.com/github-of-wone/)
33 | [Stopwatch Application](https://github.com/Python-World/python-mini-projects/tree/master/projects/Create_a_simple_stopwatch) | [Gaodong](https://github.com/xlgd)
34 | [CLI Proxy Tester](https://github.com/Python-World/python-mini-projects/tree/master/projects/cli_proxy_tester) | [Ingo Kleiber](https://github.com/IngoKl)
35 | [XML to JSON file Convertor](https://github.com/Python-World/python-mini-projects/tree/master/projects/Convert_XML_to_JSON) | [John Kirtley](https://github.com/johnkirtley)
36 | [Compress file and folders](https://github.com/Python-World/python-mini-projects/tree/master/projects/Write_script_to_compress_folder_and_files) | [Gaodong](https://github.com/xlgd)
37 | [Find IMDB movie ratings](https://github.com/Python-World/python-mini-projects/tree/master/projects/Find_imdb_rating) | [ShivSt](https://github.com/ShivSt)
38 | [Convert dictionary to python object](https://github.com/Python-World/python-mini-projects/tree/master/projects/convert_dictionary_to_python_object) | [Varun-22](https://github.com/Varun-22)
39 | [Move files to alphabetically arranged folders](https://github.com/Python-World/python-mini-projects/tree/master/projects/Write_script_to_move_files_into_alphabetically_ordered_folder) | [Chathura Nimesh](https://github.com/kana800/)
40 | [Scrape Youtube video comment](https://github.com/Python-World/python-mini-projects/tree/master/projects/Web_scraping_a_youtube_comment) | [Saicharan67](https://github.com/Saicharan67)
41 | [Website Summerization](https://github.com/Python-World/python-mini-projects/tree/master/projects/Web_page_summation) | [Believe Ohiozua](https://github.com/believeohiozua)
42 | [Text To speech(mp3)](https://github.com/Python-World/python-mini-projects/tree/master/projects/Text_to_speech) | [Sergej Dikun](https://github.com/Serhazor)
43 | [Image format conversion](https://github.com/Python-World/python-mini-projects/tree/master/projects/convert_Imgs) | [Ramon Ferreira](https://github.com/ramonfsk)
44 | [Save random article from wikipedia](https://github.com/Python-World/python-mini-projects/tree/master/projects/Random_Wikipedia_Article) | [Rakshit Puri](https://github.com/skate1512)
45 | [Check website connectivity](https://github.com/Python-World/python-mini-projects/tree/master/projects/Check_website_connectivity) | [Shiv Thakur](https://github.com/ShivSt)
46 | [Fetch city weather information](https://github.com/Python-World/python-mini-projects/tree/master/projects/Fetch_current_weather) | [Kushal Agrawal](https://github.com/kushal98)
47 | [Calculator App](https://github.com/Python-World/python-mini-projects/tree/master/projects/Create_calculator_app) | [Gaodong](https://github.com/xlgd)
48 | [Merge Csv files](https://github.com/Python-World/python-mini-projects/tree/master/projects/Merge_csv_files) | [Kushal Agrawal](https://github.com/kushal98)
49 | [Fetch tweets and save in csv](https://github.com/Python-World/python-mini-projects/tree/master/projects/Fetch_and_store_tweets) | [Kushal Agrawal](https://github.com/kushal98)
50 | [Language Translator using googletrans](https://github.com/Python-World/python-mini-projects/tree/master/projects/Language_translator) | [Ashiqur Rahman Tusher](https://github.com/ashikurt77)
51 | [Split video using timeperiod](https://github.com/Python-World/python-mini-projects/tree/master/projects/Split_a_video_file_by_given_time_period) | [Chathura Nimesh](https://github.com/kana800/)
52 | [Fetch unique words from file](https://github.com/Python-World/python-mini-projects/tree/master/projects/Unique_words_in_a_file) | [Rakshit Puri](https://github.com/skate1512)
53 | [Speech to text converter](https://github.com/Python-World/python-mini-projects/tree/master/projects/Speech_to_text) | [Paulo Henrique](https://github.com/Python-World/python-mini-projects/tree/master/projects/Speech%20to%20text)
54 | [Set Random Wallpaper](https://github.com/Python-World/python-mini-projects/tree/master/projects/Write_a_script_to_download_a_random_image_from_unsplash_and_set_it_as_wallpaper) | [Chathura Nimesh](https://github.com/kana800/)
55 | [Find Dominant color from image](https://github.com/Python-World/python-mini-projects/tree/master/projects/Dominant_color) | [Mitesh](https://github.com/Mitesh2499)
56 | [Ascii art](https://github.com/Python-World/python-mini-projects/tree/master/projects/Ascii_art) | [Shiny Akash](https://github.com/Shiny-Akash)
57 | [Merge Pdf Files](https://github.com/Python-World/python-mini-projects/tree/master/projects/Merge_pdfs) | [ShivSt](https://github.com/ShivSt)
58 | [Fetch Open Port](https://github.com/Python-World/python-mini-projects/tree/master/projects/Fetch_open_ports) | [Kushal Agrawal](https://github.com/kushal98)
59 | [Convert Numbers To Words](https://github.com/Python-World/python-mini-projects/tree/master/projects/Convert_numbers_to_word) | [Niraj Shrestha](https://github.com/CrestNiraj12)
60 | [Restart and Shutdown System](https://github.com/Python-World/python-mini-projects/tree/master/projects/Shutdown_or_restart_your_device) | [Phillibob55](https://github.com/Phillibob55)
61 | [Check website connectivity](https://github.com/Python-World/python-mini-projects/tree/master/projects/Check_website_connectivity) | [Shiv Thakur](https://github.com/ShivSt)
62 | [Digital clock using tkinter](https://github.com/Python-World/python-mini-projects/tree/master/projects/Digital_clock) | [Aditya Jetely](https://github.com/adityaj7)
63 | [Covert Image To Pdf](https://github.com/Python-World/python-mini-projects/tree/master/projects/Convert_a_image_to_pdf) | [Gaodong](https://github.com/xlgd)
64 | [Store emails in csv file](https://github.com/Python-World/python-mini-projects/tree/master/projects/Store_emails_in_csv) | [Shiv Thakur](https://github.com/ShivSt)
65 | [Test Internet Connection](https://github.com/Python-World/python-mini-projects/tree/master/projects/Internet_connection_check) | [Jacob Ogle](https://github.com/Jakeogle94)
66 | [XKCD Comics Downloader](https://github.com/Python-World/python-mini-projects/tree/master/projects/XKCD_downloader)| [Aditya Jetely](https://github.com/AdityaJ7)
67 | [Website Blocker And Unblocker](https://github.com/Python-World/python-mini-projects/tree/master/projects/Website_blocker)| [Phillibob55](https://github.com/Phillibob55)
68 | [Fetch Domain Dns Record](https://github.com/Python-World/python-mini-projects/tree/master/projects/Dns_record)| [Aditya Jetely](https://github.com/AdityaJ7)
69 | [Python-Auto-Draw](https://github.com/Python-World/python-mini-projects/tree/master/projects/Python_auto_draw)| [Tushar Nankani](https://github.com/tusharnankani)
70 | [News Website Scraper](https://github.com/Python-World/python-mini-projects/tree/master/projects/News_website_scraper)| [pratik-choudhari](https://github.com/pratik-choudhari)
71 | [Rock Paper Scissors Game](https://github.com/Python-World/python-mini-projects/tree/master/projects/RockPaperScissors_Game)| [Tushar Nankani](https://github.com/tusharnankani)
72 | [Zip File Extractor](https://github.com/Python-World/python-mini-projects/tree/master/projects/Extract_zip_files)| [Aditya Jetely](https://github.com/AdityaJ7)
73 | [Random Password Generator](https://github.com/Python-World/python-mini-projects/blob/master/projects/Random_password_generator)| [Tushar Nankani](https://github.com/tusharnankani)
74 | [Script to perform Geocoding](https://github.com/Python-World/python-mini-projects/tree/master/projects/Geocoding)| [Aditya Jetely](https://github.com/AdityaJ7)
75 | [Python Carbon Clips](https://github.com/Python-World/python-mini-projects/tree/master/projects/Py_carbon_clips)| [Ravishankar Chavare](https://github.com/chavarera)
76 | [QR Code Generator](https://github.com/Python-World/python-mini-projects/tree/master/projects/Qr_code_generator)| [Shiv Thakur](https://github.com/ShivSt)
77 | [Recursive Password Generator](https://github.com/Python-World/python-mini-projects/tree/master/projects/Recursive_password_generator)| [Erfan Saberi](https://github.com/erfansaberi)
78 | [Tic Tac Toe](https://github.com/Python-World/python-mini-projects/tree/master/projects/Tic_tac_toe)| [Erfan Saberi](https://github.com/erfansaberi)
79 | [Tic Tac Toe with AI](https://github.com/Python-World/python-mini-projects/tree/master/projects/Tic_tac_toe_with_ai)| [Tushar Nankani](https://github.com/tusharnankani)
80 | [Cartoonify an Image](https://github.com/Python-World/python-mini-projects/tree/master/projects/Easy_cartoonify)| [Bartu Yaman](https://github.com/brtymn)
81 | [Quote Scrapper](https://github.com/Python-World/python-mini-projects/tree/master/projects/Scrape_quotes)| [Anandha Krishnan Aji](https://github.com/anandhakrishnanaji)
82 | [Time To Load Website](https://github.com/Python-World/python-mini-projects/tree/master/projects/Time_to_load_website)| [Aditya Jetely](https://github.com/AdityaJ7)
83 | [Customer Loan Repayment Prediction](https://github.com/Python-World/python-mini-projects/tree/master/Notebooks/Customer_loan_repayment_problem)| [ART](https://github.com/Tomyzon1728)
84 | [Generate Wordcloud from Wikipedia Article](https://github.com/Python-World/python-mini-projects/tree/master/projects/Wikipedia_search_wordcloud)| [Naman Shah](https://github.com/namanshah01)
85 | [Number Guessing Game](https://github.com/Python-World/python-mini-projects/tree/master/projects/Number_guessing_game)| [Javokhirbek](https://github.com/leader2one)
86 | [Convert JPEG to PNG](https://github.com/Python-World/python-mini-projects/tree/master/projects/Convert_JPEG_to_PNG)| [AnuragGupta](https://github.com/AnuragGupta806)
87 | [Movie Information Scrapper](https://github.com/Python-World/python-mini-projects/tree/master/projects/Movie%20Information%20Scraper)| [Anandha Krishnan Aji](https://github.com/anandhakrishnanaji)
88 | [Fetch HTTP Status Code](https://github.com/Python-World/python-mini-projects/tree/master/projects/Fetch%20HTTP%20status%20code)| [AkshataJ96](https://github.com/AkshataJ96)
89 | [Check Leap Year](https://github.com/Python-World/python-mini-projects/tree/master/projects/Leap_Year_Checker)| [Hariom Vyas](https://github.com/Hariom1509)
90 | [Scrape Medium Articles](https://github.com/Python-World/python-mini-projects/tree/master/projects/Scraping%20Medium%20Articles)| [Naman Shah](https://github.com/namanshah01)
91 | [HackerNews Scrapper](https://github.com/Python-World/python-mini-projects/tree/master/projects/Scrape_Hacker_News)| [Javokhirbek](https://github.com/leader2one)
92 | [Reduce Image Size](https://github.com/Python-World/python-mini-projects/tree/master/projects/Reduce_image_file_size)| [Vipul Verma](https://github.com/VIPverma01)
93 | [Easy Video Player](https://github.com/Python-World/python-mini-projects/tree/master/projects/EasyVideoPlayer)| [Bartu Yaman](https://github.com/brtymn)
94 | [GeeksforGeeks Article downloader](https://github.com/Python-World/python-mini-projects/tree/master/projects/download%20GeeksForGeeks%20articles)| [Shiv Thakur](https://github.com/ShivSt)
95 | [PDF to Text](https://github.com/Python-World/python-mini-projects/tree/master/projects/convert%20pdf%20to%20text)| [pi1814](https://github.com/pi1814)
96 | [Unstructured Supplemenrary Service Data](https://github.com/Python-World/python-mini-projects/tree/master/projects/Unstructured%20Supplemenrary%20%20Service%20Data)| [ART](https://github.com/Tomyzon1728)
97 | [Duplicate Files remover](https://github.com/Python-World/python-mini-projects/tree/master/projects/Duplicate%20files%20remover)| [Anandha Krishnan Aji](https://github.com/anandhakrishnanaji)
98 | [PNG to ICO converter](https://github.com/Python-World/python-mini-projects/tree/master/projects/convert_png_images_to_ico_format)| [weicheansoo](https://github.com/weicheansoo)
99 | [Find IMDB Ratings](https://github.com/Python-World/python-mini-projects/tree/master/projects/Find_imdb_rating)| [Utkarsh Bajaj](https://github.com/utkarshbajaj)
100 | [Terminal Based Hangman Game](https://github.com/Python-World/python-mini-projects/tree/master/projects/Terminal_Based_Hangman_Game)| [neohboonyee99](https://github.com/neohboonyee99)
101 | [Whatsapp Bot](https://github.com/Python-World/python-mini-projects/tree/master/projects/whatsapp_Bot)| [urmil89](https://github.com/urmil89)
102 | [Zip Bruter](https://github.com/Python-World/python-mini-projects/tree/master/projects/Zip_Bruter) | [Erdoğan YOKSUL](https://www.github.com/eredotpkfr)
103 | [CountDown Timer](https://github.com/Python-World/python-mini-projects/tree/master/projects/Countdown_timer) | [Japneet Kalra](https://github.com/japneetsingh035)
