From 63b7450215519447dd4847ff7a4f4283e93eb226 Mon Sep 17 00:00:00 2001
From: "deepsource-autofix[bot]"
<62050782+deepsource-autofix[bot]@users.noreply.github.com>
Date: Tue, 20 Apr 2021 20:07:39 +0000
Subject: [PATCH] Format code with autopep8
This commit fixes the style issues introduced in 5bfb399 according to the output
from autopep8.
Details: https://deepsource.io/gh/avinashkranjan/Amazing-Python-Scripts/transform/cde918ce-12ee-455a-a397-6e343a1a9f1b/
---
.../awsLambda.py | 3 +-
.../ec2.py | 5 +-
.../rds.py | 12 +-
Age-Calculator-GUI/age_calc_gui.py | 16 +-
Air pollution prediction/CodeAP.py | 36 +-
.../Applying Bitwise operations.py | 32 +-
Attachment_Downloader/attachment.py | 26 +-
Auto Birthday Wisher/Auto B'Day Wisher.py | 33 +-
Automate Facebook bot/script.py | 47 +-
Bag of words model/bow.py | 48 +-
Battery-Notification/Battery-Notification.py | 12 +-
BitCoin Mining/BitCoin_Mining.py | 22 +-
Blackjack/blackjack.py | 15 +-
Body Detection/detection.py | 32 +-
Brick Breaker game/brick_breaker.py | 414 ++--
Bubble Shooter Game/bubbleshooter.py | 311 +--
Bubble-Sort-Visualization/bubble_sort.py | 106 +-
CPU temperature/temp.py | 4 +-
Caesar-Cipher/caesar_cipher.py | 43 +-
Calendar GUI/Calendar_gui.py | 64 +-
Cartooning Image/cartooneffect.py | 11 +-
.../censor_word_detection.py | 4 +-
Codechef Scrapper/codechef.py | 127 +-
Codes on Turtle Graphics/Animated_Robot.py | 78 +-
Codes on Turtle Graphics/Kaleido-spiral.py | 11 +-
Color_detection/Color_detection.py | 30 +-
Connect-4 game/Connect-4.py | 148 +-
Contour-Detection/live_contour_det.py | 102 +-
Covid India Stats App/app.py | 12 +-
.../Currency_convertor_GUI.py | 80 +-
Data-Visualization/BarChart/bar_chart.py | 41 +-
.../BubbleChart/bubble_chart.py | 30 +-
Data-Visualization/HeatMap/heat_maps.py | 25 +-
Data-Visualization/HistogramPlot/histogram.py | 22 +-
Data-Visualization/LineChart/line_chart.py | 20 +-
Data-Visualization/PieChart/pie_chart.py | 21 +-
.../ScatterPlot/scatter_plot.py | 22 +-
Desktop News Notifier/script.py | 17 +-
Desktop-Voice-assistant/voice_assistant.py | 97 +-
Desktop-drinkWater-Notification/main.py | 6 +-
Dev.to Scraper/scraper.py | 78 +-
Dice-Roll-Simulator/dice_roll_simulator.py | 18 +-
Dictionary-GUI/dictionary.py | 20 +-
Digital Clock/Clock.py | 7 +-
Directory Tree Generator/tree.py | 36 +-
.../distance_conversion.py | 75 +-
DownTube-Youtube-Downloader/DownTube.py | 102 +-
Edge Detection/Edge_Detection.py | 26 +-
Email-Validator/email_verification.py | 38 +-
Eye Detection/eyes.py | 38 +-
Face-Detection/v2/face_detectv2.py | 25 +-
Face-Detection/v3/face_detectv3.py | 18 +-
.../face_mask_detection_using_cnn.py | 125 +-
Facial-Expression-Recognition/face_crop.py | 42 +-
Facial-Expression-Recognition/label.py | 30 +-
Facial-Expression-Recognition/label_image.py | 206 +-
Facial-Expression-Recognition/retrain.py | 2114 +++++++++--------
.../Fast_Algorithm.py | 44 +-
File-Mover/fmover.py | 12 +-
Flipkart-price-alert/track.py | 6 +-
Ghost filter/Ghost filter code.py | 16 +-
Github_Bomb_Issues/bomb-issues.py | 3 +-
Gmplot-Track the Route/main.py | 54 +-
Google-Meet-Scheduler/script.py | 27 +-
Guess the Countries/main.py | 49 +-
Guessing_Game_GUI/guessing_game_tkinter.py | 161 +-
Hangman-Game/main.py | 189 +-
Health_Log_Book/database.py | 1 +
Health_Log_Book/main.py | 15 +-
IPL Statistics GUI/ipl.py | 12 +-
Image Processing/ImageCompressing.py | 10 +-
Image Processing/ImageTransposing.py | 14 +-
Image Processing/ImgEnhancing.py | 24 +-
.../Image_editing_script.py | 1 -
Image_Background_Subtractor/BG_Subtractor.py | 3 +-
Image_Viewing_GUI/script.py | 48 +-
Imagetospeech/image_to_speech.py | 11 +-
Insta-Bot-Follow-SendMsg/instabot.py | 12 +-
Instagram Liker Bot/Instagram_Liker_Bot.py | 40 +-
Instagram downloader/downloader.py | 464 ++--
Invisibility_Cloak/Invisibility_Cloak.py | 53 +-
Linkedin_Connections_Scrapper/script.py | 75 +-
Matrix-rain-code/matrix-rain.py | 50 +-
Message_Spam_Detection/Dataset_Cleaning.py | 102 +-
.../Message_Spam_Detection.py | 103 +-
MineSweeper/minesweeper.py | 225 +-
.../Mini google assistant.py | 15 +-
.../Morse_Code_Translator.py | 58 +-
Movie-Info-Telegram-Bot/bot.py | 102 +-
News_Scrapper/scrapper.py | 22 +-
Num-Plate-Detector/number_plate.py | 48 +-
PDF-Tools/main.py | 6 +-
PDF2Text/script.py | 7 +-
Pagespeed-API/pagespeed.py | 1 +
Pagespeed-API/responses.py | 1 +
Paint Application/paint.py | 523 ++--
Password-Manager-GUI/passwords.py | 25 +-
Photo To Ascii/photo_to_ascii.py | 47 +-
Plagiarism-Checker/plagiarism.py | 32 +-
.../price_comparison.py | 176 +-
QR-code-Genrator/main.py | 122 +-
Quiz-GUI/quiztime.py | 115 +-
Random Password Generator/script.py | 123 +-
.../Realtime Text Extraction.py | 49 +-
Reddit-Meme-Scraper/script.py | 2 +
.../hindi_POS_tag_removal.py | 43 +-
SMS Automation/script.py | 13 +-
Salary Predictor/model.py | 38 +-
Salary Predictor/script.py | 55 +-
Select Stocks by volume Increase/script.py | 79 +-
.../Shortest Path Finder.py | 35 +-
Simple Python IDE using Tkinter/script.py | 4 +-
.../slideshare_downloader.py | 3 +-
Smart calcy/Smart_calcy.py | 114 +-
Spreadsheet_Automation/script.py | 12 +-
Steganography/steganography.py | 44 +-
StonePaperScissor - GUI/StonePaperScissors.py | 128 +-
Stopwatch GUI/stopwatch_gui.py | 95 +-
Tarot Reader/tarot_card_reader.py | 11 +-
Telegram-Bot/TelegramBot.py | 3 +-
Terminal Hangman/T_hangman.py | 9 +-
Text-To-Speech/text-to-speech.py | 30 +-
TicTacToe-GUI/TicTacToe.py | 273 ++-
Translator Script/Translation.py | 4 +-
Translator-GUI/translator.py | 3 +
Tweet-Fetcher/display.py | 18 +-
Tweet-Fetcher/fetcher.py | 46 +-
Typing-Speed-Test/speed_test.py | 86 +-
Udemy Scraper/display.py | 37 +-
Udemy Scraper/fetcher.py | 57 +-
Unzip file/script.py | 1 -
Video-Audio-Converter-GUI/converter.py | 46 +-
Video-To-Audio(CLI-Ver)/video_to_audio.py | 4 +-
Virtual Paint/virtual_paint.py | 8 +-
Watermark Maker(On Image)/Watermark_maker.py | 90 +-
Weight-Converter-GUI/weight_con_gui.py | 97 +-
Wikipedia-Summary-GUI/summary.py | 94 +-
YouTube-Video-Downloader/youtube_vid_dl.py | 22 +-
.../scrap_reader.py | 13 +-
.../youtube_scrapper.py | 47 +-
corona cases forecasting/main.py | 208 +-
.../emails-from-website.py | 15 +-
script_updater.py | 28 +-
sticky notes/main.py | 47 +-
144 files changed, 5576 insertions(+), 4865 deletions(-)
diff --git a/AWS Management Scripts/AWS Automation Script for AWS endorsement management/awsLambda.py b/AWS Management Scripts/AWS Automation Script for AWS endorsement management/awsLambda.py
index 319354f032..a609f72a4d 100644
--- a/AWS Management Scripts/AWS Automation Script for AWS endorsement management/awsLambda.py
+++ b/AWS Management Scripts/AWS Automation Script for AWS endorsement management/awsLambda.py
@@ -8,7 +8,8 @@ def lambda_handler(event, context):
instances = Ec2Instances(region_name)
deleted_counts = instances.delete_snapshots(1)
instances.delete_available_volumes()
- print("deleted_counts for region " + str(region_name) + " is " + str(deleted_counts))
+ print("deleted_counts for region " +
+ str(region_name) + " is " + str(deleted_counts))
instances.shutdown()
print("For RDS")
rds = Rds(region_name)
diff --git a/AWS Management Scripts/AWS Automation Script for AWS endorsement management/ec2.py b/AWS Management Scripts/AWS Automation Script for AWS endorsement management/ec2.py
index 7e439e41e4..581684ac89 100644
--- a/AWS Management Scripts/AWS Automation Script for AWS endorsement management/ec2.py
+++ b/AWS Management Scripts/AWS Automation Script for AWS endorsement management/ec2.py
@@ -5,14 +5,15 @@
def get_delete_data(older_days):
delete_time = datetime.now(tz=timezone.utc) - timedelta(days=older_days)
- return delete_time;
+ return delete_time
def is_ignore_shutdown(tags):
for tag in tags:
print("K " + str(tag['Key']) + " is " + str(tag['Value']))
if str(tag['Key']) == 'excludepower' and str(tag['Value']) == 'true':
- print("Not stopping K " + str(tag['Key']) + " is " + str(tag['Value']))
+ print("Not stopping K " +
+ str(tag['Key']) + " is " + str(tag['Value']))
return True
return False
diff --git a/AWS Management Scripts/AWS Automation Script for AWS endorsement management/rds.py b/AWS Management Scripts/AWS Automation Script for AWS endorsement management/rds.py
index f967e6da7c..c41f154f58 100644
--- a/AWS Management Scripts/AWS Automation Script for AWS endorsement management/rds.py
+++ b/AWS Management Scripts/AWS Automation Script for AWS endorsement management/rds.py
@@ -36,7 +36,8 @@ def _delete_instance_snapshot(self, identifier):
self.rds.delete_db_snapshot(DBSnapshotIdentifier=identifier)
def _delete_cluster_snapshot(self, identifier):
- self.rds.delete_db_cluster_snapshot(DBClusterSnapshotIdentifier=identifier)
+ self.rds.delete_db_cluster_snapshot(
+ DBClusterSnapshotIdentifier=identifier)
@staticmethod
def _can_delete_instance(tags):
@@ -88,7 +89,8 @@ def _cleanup_snapshots_clusters(self):
if self._can_delete_snapshot(tags) and self._is_older_snapshot(
str(snapshot['SnapshotCreateTime']).split(" ")):
try:
- self._delete_cluster_snapshot(snapshot['DBClusterSnapshotIdentifier'])
+ self._delete_cluster_snapshot(
+ snapshot['DBClusterSnapshotIdentifier'])
except Exception as e:
print(str(e))
@@ -99,14 +101,16 @@ def _cleanup_snapshot_instance(self):
if self._can_delete_snapshot(tags) and self._is_older_snapshot(
str(snapshot['SnapshotCreateTime']).split(" ")):
try:
- self._delete_instance_snapshot(snapshot['DBSnapshotIdentifier'])
+ self._delete_instance_snapshot(
+ snapshot['DBSnapshotIdentifier'])
except Exception as e:
print(str(e))
@staticmethod
def _is_older_snapshot(snapshot_datetime):
snapshot_date = snapshot_datetime[0].split("-")
- snapshot_date = datetime.date(int(snapshot_date[0]), int(snapshot_date[1]), int(snapshot_date[2]))
+ snapshot_date = datetime.date(int(snapshot_date[0]), int(
+ snapshot_date[1]), int(snapshot_date[2]))
today = datetime.date.today()
if abs(today - snapshot_date).days > 2:
return True
diff --git a/Age-Calculator-GUI/age_calc_gui.py b/Age-Calculator-GUI/age_calc_gui.py
index d92ce73e67..1ee3b6da75 100644
--- a/Age-Calculator-GUI/age_calc_gui.py
+++ b/Age-Calculator-GUI/age_calc_gui.py
@@ -5,24 +5,28 @@
# initialized window
root = Tk()
root.geometry('280x300')
-root.resizable(0,0)
+root.resizable(0, 0)
root.title('Age Calculator')
statement = Label(root)
# defining the function for calculating age
+
+
def ageCalc():
global statement
statement.destroy()
today = date.today()
- birthDate = date(int(yearEntry.get()), int(monthEntry.get()), int(dayEntry.get()))
+ birthDate = date(int(yearEntry.get()), int(
+ monthEntry.get()), int(dayEntry.get()))
age = today.year - birthDate.year
if today.month < birthDate.month or today.month == birthDate.month and today.day < birthDate.day:
age -= 1
statement = Label(text=f"{nameValue.get()}'s age is {age}.")
statement.grid(row=6, column=1, pady=15)
+
# creating a label for person's name to display
-l1 = Label(text = "Name: ")
+l1 = Label(text="Name: ")
l1.grid(row=1, column=0)
nameValue = StringVar()
@@ -31,21 +35,21 @@ def ageCalc():
nameEntry.grid(row=1, column=1, padx=10, pady=10)
# label for year in which user was born
-l2 = Label(text = "Year: ")
+l2 = Label(text="Year: ")
l2.grid(row=2, column=0)
yearValue = StringVar()
yearEntry = Entry(root, textvariable=yearValue)
yearEntry.grid(row=2, column=1, padx=10, pady=10)
# label for month in which user was born
-l3 = Label(text = "Month: ")
+l3 = Label(text="Month: ")
l3.grid(row=3, column=0)
monthValue = StringVar()
monthEntry = Entry(root, textvariable=monthValue)
monthEntry.grid(row=3, column=1, padx=10, pady=10)
# label for day/date on which user was born
-l4 = Label(text = "Day: ")
+l4 = Label(text="Day: ")
l4.grid(row=4, column=0)
dayValue = StringVar()
dayEntry = Entry(root, textvariable=dayValue)
diff --git a/Air pollution prediction/CodeAP.py b/Air pollution prediction/CodeAP.py
index c2c03de832..f8633707ff 100644
--- a/Air pollution prediction/CodeAP.py
+++ b/Air pollution prediction/CodeAP.py
@@ -11,24 +11,23 @@
iaqi = data['iaqi']
-
for i in iaqi.items():
- print(i[0],':',i[1]['v'])
-dew = iaqi.get('dew','Nil')
-no2 = iaqi.get('no2','Nil')
-o3 = iaqi.get('o3','Nil')
-so2 = iaqi.get('so2','Nil')
-pm10 = iaqi.get('pm10','Nil')
-pm25 = iaqi.get('pm25','Nil')
-
-print(f'{city} AQI :',aqi,'\n')
+ print(i[0], ':', i[1]['v'])
+dew = iaqi.get('dew', 'Nil')
+no2 = iaqi.get('no2', 'Nil')
+o3 = iaqi.get('o3', 'Nil')
+so2 = iaqi.get('so2', 'Nil')
+pm10 = iaqi.get('pm10', 'Nil')
+pm25 = iaqi.get('pm25', 'Nil')
+
+print(f'{city} AQI :', aqi, '\n')
print('Individual Air quality')
-print('Dew :',dew)
-print('no2 :',no2)
-print('Ozone :',o3)
-print('sulphur :',so2)
-print('pm10 :',so2)
-print('pm25 :',pm25)
+print('Dew :', dew)
+print('no2 :', no2)
+print('Ozone :', o3)
+print('sulphur :', so2)
+print('pm10 :', so2)
+print('pm25 :', pm25)
pollutants = [i for i in iaqi]
values = [i['v'] for i in iaqi.values()]
@@ -39,8 +38,9 @@
explode[mx] = 0.1
# Plot a pie chart
-plt.figure(figsize=(8,6))
-plt.pie(values, labels=pollutants,explode=explode,autopct='%1.1f%%', shadow=True)
+plt.figure(figsize=(8, 6))
+plt.pie(values, labels=pollutants, explode=explode,
+ autopct='%1.1f%%', shadow=True)
plt.title('Air pollutants and their probable amount in atmosphere [kanpur]')
diff --git a/Applying Bitwise Operations/Applying Bitwise operations.py b/Applying Bitwise Operations/Applying Bitwise operations.py
index d189580fbc..951d94c0ec 100644
--- a/Applying Bitwise Operations/Applying Bitwise operations.py
+++ b/Applying Bitwise Operations/Applying Bitwise operations.py
@@ -1,22 +1,26 @@
import cv2
-src1= input("Enter the path of the image 1\n") #getting the path for first image
-src1 = cv2.imread(src1)
-#src1 = cv2.resize(src1,(540,540)) #resizing the image
-src2 = input("Enter the path of the image 2\n") #getting the path for second image
+# getting the path for first image
+src1 = input("Enter the path of the image 1\n")
+src1 = cv2.imread(src1)
+# src1 = cv2.resize(src1,(540,540)) #resizing the image
+# getting the path for second image
+src2 = input("Enter the path of the image 2\n")
src2 = cv2.imread(src2)
-src2 = cv2.resize(src2, src1.shape[1::-1]) #Resizing the image so that both images have same dimensions
-andop= cv2.bitwise_and(src1, src2,mask=None) #Applying Bitwise AND operation
-andop=cv2.resize(andop,(640,640))
-cv2.imshow('Bitwise AND',andop)
+# Resizing the image so that both images have same dimensions
+src2 = cv2.resize(src2, src1.shape[1::-1])
+# Applying Bitwise AND operation
+andop = cv2.bitwise_and(src1, src2, mask=None)
+andop = cv2.resize(andop, (640, 640))
+cv2.imshow('Bitwise AND', andop)
-orop= cv2.bitwise_or(src1, src2,mask=None) #Applying Bitwise OR operation
-orop=cv2.resize(orop,(640,640))
-cv2.imshow('Bitwise OR',orop)
+orop = cv2.bitwise_or(src1, src2, mask=None) # Applying Bitwise OR operation
+orop = cv2.resize(orop, (640, 640))
+cv2.imshow('Bitwise OR', orop)
-xorop = cv2.bitwise_xor(src1,src2,mask=None) #Applying Bitwise OR operation
-xorop=cv2.resize(xorop,(640,640))
-cv2.imshow('Bitwise XOR',xorop)
+xorop = cv2.bitwise_xor(src1, src2, mask=None) # Applying Bitwise OR operation
+xorop = cv2.resize(xorop, (640, 640))
+cv2.imshow('Bitwise XOR', xorop)
cv2.waitKey(0)
cv2.destroyAllWindows()
diff --git a/Attachment_Downloader/attachment.py b/Attachment_Downloader/attachment.py
index e9784da9fc..80e865cf84 100644
--- a/Attachment_Downloader/attachment.py
+++ b/Attachment_Downloader/attachment.py
@@ -1,5 +1,6 @@
import ezgmail
+
def attachmentdownload(resulthreads):
# Two Objects used in code are GmailThread and GmailMessage
# 1. GmailThread - Represents conversation threads
@@ -7,12 +8,14 @@ def attachmentdownload(resulthreads):
countofresults = len(resulthreads)
try:
for i in range(countofresults):
- if len(resulthreads[i].messages) > 1: # checks whether the count of messages in threads is greater than 1
+ # checks whether the count of messages in threads is greater than 1
+ if len(resulthreads[i].messages) > 1:
for j in range(len(resulthreads[i].messages)):
resulthreads[i].messages[
j].downloadAllAttachments() # downloads attachment(s) for individual messages
else:
- resulthreads[i].messages[0].downloadAllAttachments() # downloads attachment(s) for single message
+ # downloads attachment(s) for single message
+ resulthreads[i].messages[0].downloadAllAttachments()
print("Download compelete. Please check your root directory.")
except:
raise Exception("Error occured while downloading attachment(s).")
@@ -20,25 +23,26 @@ def attachmentdownload(resulthreads):
if __name__ == '__main__':
query = input("Enter search query: ")
- newquery = query + " + has:attachment" # appending to make sure the result threads always has an attachment
- resulthreads = ezgmail.search(newquery) # search functions accepts all the operators described at https://support.google.com/mail/answer/7190?hl=en
+ # appending to make sure the result threads always has an attachment
+ newquery = query + " + has:attachment"
+ # search functions accepts all the operators described at https://support.google.com/mail/answer/7190?hl=en
+ resulthreads = ezgmail.search(newquery)
if len(resulthreads) == 0:
- print("Result has no attachments:") # Executed if results don't have attachment
+ # Executed if results don't have attachment
+ print("Result has no attachments:")
else:
print("Result(s) with attachments:")
for threads in resulthreads:
- print(f"Email Subject: {threads.messages[0].subject}") # prints the subject line of email thread in results
+ # prints the subject line of email thread in results
+ print(f"Email Subject: {threads.messages[0].subject}")
try:
ask = input(
"Do you want to download attachment(s) in result(s) (Yes/No)? ") # Allows user to decide whether they want to download attachment(s) or not
if ask == "Yes":
- attachmentdownload(resulthreads) # calls the function that downloads attachment(s)
+ # calls the function that downloads attachment(s)
+ attachmentdownload(resulthreads)
else:
print("Program exited")
except:
print("Something went wrong")
-
-
-
-
diff --git a/Auto Birthday Wisher/Auto B'Day Wisher.py b/Auto Birthday Wisher/Auto B'Day Wisher.py
index 9d714081b2..2f2d7f5adb 100755
--- a/Auto Birthday Wisher/Auto B'Day Wisher.py
+++ b/Auto Birthday Wisher/Auto B'Day Wisher.py
@@ -1,27 +1,37 @@
-import pandas as pd # Pandas library is used for importing and reading the data
-import datetime # datetime module is used for fetching the dates
+# Pandas library is used for importing and reading the data
+import pandas as pd
+# datetime module is used for fetching the dates
+import datetime
import smtplib # smtp library used for sending mail
import os
current_path = os.getcwd()
print(current_path)
-os.chdir(current_path) # Changing the Path of the directory in which you are currently working
+# Changing the Path of the directory in which you are currently working
+os.chdir(current_path)
-GMAIL_ID = input("Enter your email: ") # Give your mail here from which you want to send the wishes
-GMAIL_PSWD = input("Enter password for your email mentioned above: ") # Give your mail password
+# Give your mail here from which you want to send the wishes
+GMAIL_ID = input("Enter your email: ")
+# Give your mail password
+GMAIL_PSWD = input("Enter password for your email mentioned above: ")
def sendEmail(to, sub, msg):
print(f"Email to {to} sent: \nSubject: {sub} ,\nMessage: {msg}")
- s = smtplib.SMTP('smtp.gmail.com', 587) # creating server to send mail
- s.starttls() # start a TLS session
- s.login(GMAIL_ID, GMAIL_PSWD) # the function will login with your Gmail credentials
- s.sendmail(GMAIL_ID, to, f"Subject: {sub} \n\n {msg}") # sending the mail
+ # creating server to send mail
+ s = smtplib.SMTP('smtp.gmail.com', 587)
+ # start a TLS session
+ s.starttls()
+ # the function will login with your Gmail credentials
+ s.login(GMAIL_ID, GMAIL_PSWD)
+ # sending the mail
+ s.sendmail(GMAIL_ID, to, f"Subject: {sub} \n\n {msg}")
s.quit()
if __name__ == "__main__":
- df = pd.read_excel("data.xlsx") # the datasheet where the data of the friends is stored
+ # the datasheet where the data of the friends is stored
+ df = pd.read_excel("data.xlsx")
today = datetime.datetime.now().strftime("%d-%m")
yearNow = datetime.datetime.now().strftime("%Y")
@@ -31,7 +41,8 @@ def sendEmail(to, sub, msg):
bday = datetime.datetime.strptime(bday, "%d-%m-%Y")
bday = bday.strftime("%d-%m")
if(today == bday) and yearNow not in str(item['LastWishedYear']):
- sendEmail(item['Email'], "Happy Birthday", item['Dialogue']) # calling the sendmail function
+ # calling the sendmail function
+ sendEmail(item['Email'], "Happy Birthday", item['Dialogue'])
writeInd.append(index)
if writeInd != None:
diff --git a/Automate Facebook bot/script.py b/Automate Facebook bot/script.py
index b241209a66..15771915af 100644
--- a/Automate Facebook bot/script.py
+++ b/Automate Facebook bot/script.py
@@ -8,15 +8,16 @@
LOGIN_URL = 'https://www.facebook.com/login.php'
-num = str (input ("Enter group ids separated by commas: "))
-lists = num.split (",")
+num = str(input("Enter group ids separated by commas: "))
+lists = num.split(",")
groupid = []
for i in lists:
- groupid.append(i)
+ groupid.append(i)
+
+
+message = input("Enter your message: ")
-message=input("Enter your message: ")
-
class FacebookLogin():
def __init__(self, email, password, browser='Chrome'):
# Store credentials for login
@@ -24,45 +25,45 @@ def __init__(self, email, password, browser='Chrome'):
self.password = password
if browser == 'Chrome':
# Use chrome
- self.driver = webdriver.Chrome(executable_path=ChromeDriverManager().install())
+ self.driver = webdriver.Chrome(
+ executable_path=ChromeDriverManager().install())
self.driver.get(LOGIN_URL)
- time.sleep(1) # Wait for some time to load
+ time.sleep(1) # Wait for some time to load
-
def login(self):
email_element = self.driver.find_element_by_id('email')
- email_element.send_keys(self.email) # Give keyboard input
-
+ email_element.send_keys(self.email) # Give keyboard input
+
password_element = self.driver.find_element_by_id('pass')
- password_element.send_keys(self.password) # Give password as input too
-
+ password_element.send_keys(self.password) # Give password as input too
+
login_button = self.driver.find_element_by_id('loginbutton')
- login_button.click() # Send mouse click
-
- time.sleep(2) # Wait for 2 seconds for the page to show up
+ login_button.click() # Send mouse click
+
+ time.sleep(2) # Wait for 2 seconds for the page to show up
for i in range(len(groupid)):
link = 'https://facebook.com/groups/'+groupid[i]
self.driver.get(link)
print("Waiting for few seconds .......")
time.sleep(45)
- self.driver.find_element_by_class_name('a8c37x1j ni8dbmo4 stjgntxs l9j0dhe7').click()
+ self.driver.find_element_by_class_name(
+ 'a8c37x1j ni8dbmo4 stjgntxs l9j0dhe7').click()
time.sleep(7)
self.driver.switch_to.active_element.send_keys("message")
time.sleep(7)
- self.driver.find_element_by_class_name('a8c37x1j ni8dbmo4 stjgntxs l9j0dhe7 ltmttdrg g0qnabr5').click()
+ self.driver.find_element_by_class_name(
+ 'a8c37x1j ni8dbmo4 stjgntxs l9j0dhe7 ltmttdrg g0qnabr5').click()
time.sleep(7)
-
+
if __name__ == '__main__':
# Enter your login credentials here
- usr=input('Enter Email Id:')
- pwd= getpass('Enter Password:')
+ usr = input('Enter Email Id:')
+ pwd = getpass('Enter Password:')
fb_login = FacebookLogin(email=usr, password=pwd, browser='Chrome')
fb_login.login()
-#time.sleep(5)
-
-
+# time.sleep(5)
diff --git a/Bag of words model/bow.py b/Bag of words model/bow.py
index eb42c553aa..bd8e397ce1 100644
--- a/Bag of words model/bow.py
+++ b/Bag of words model/bow.py
@@ -1,33 +1,35 @@
from sklearn.feature_extraction.text import CountVectorizer
import nltk
-import pandas as pd #pandas is a library where your data can be stored, analyzed and processed in row and column representation
+import pandas as pd # pandas is a library where your data can be stored, analyzed and processed in row and column representation
from openpyxl import Workbook
-sentences=input("Enter your sentences: ")
-#eg. My name is sanya. I am caring and loving. I am generous.
-#converting to lower case (normalization)
-sentences=sentences.lower()
-#sentence tokenized
-tokenized_sentences=nltk.tokenize.sent_tokenize(sentences)
+sentences = input("Enter your sentences: ")
+# eg. My name is sanya. I am caring and loving. I am generous.
+# converting to lower case (normalization)
+sentences = sentences.lower()
+# sentence tokenized
+tokenized_sentences = nltk.tokenize.sent_tokenize(sentences)
print(tokenized_sentences)
-tokenized_sentences1=[]
+tokenized_sentences1 = []
for x in tokenized_sentences:
- x=x.replace(".","") #removed .
+ x = x.replace(".", "") # removed .
tokenized_sentences1.append(x)
-print(tokenized_sentences1) #list of word can be converted to set to get unique words
-#instantiating CountVectorizer()
-countVectorizer=CountVectorizer() #BOW
-#transforming text from to vectors where each word and its count is a feature
-tmpbow=countVectorizer.fit_transform(tokenized_sentences1)#pass list of sentences as arguments
-print("tmpbow \n",tmpbow) #bag of word model is ready
+# list of word can be converted to set to get unique words
+print(tokenized_sentences1)
+# instantiating CountVectorizer()
+countVectorizer = CountVectorizer() # BOW
+# transforming text from to vectors where each word and its count is a feature
+# pass list of sentences as arguments
+tmpbow = countVectorizer.fit_transform(tokenized_sentences1)
+print("tmpbow \n", tmpbow) # bag of word model is ready
-bow=tmpbow.toarray()
-print("Vocabulary = ",countVectorizer.vocabulary_)
-print("Features = ",countVectorizer.get_feature_names())
-#Features in machine learning are nothing but names of the columns
-print("BOW ",bow)
+bow = tmpbow.toarray()
+print("Vocabulary = ", countVectorizer.vocabulary_)
+print("Features = ", countVectorizer.get_feature_names())
+# Features in machine learning are nothing but names of the columns
+print("BOW ", bow)
-#create dataframe #DataFrame is an analogy to excel-spreadsheet
-cv_dataframe=pd.DataFrame(bow,columns=countVectorizer.get_feature_names())
+# create dataframe #DataFrame is an analogy to excel-spreadsheet
+cv_dataframe = pd.DataFrame(bow, columns=countVectorizer.get_feature_names())
-print("cv_dataframe is below\n",cv_dataframe)
+print("cv_dataframe is below\n", cv_dataframe)
cv_dataframe.to_excel('./Bag of words model/bowp.xlsx', sheet_name='data')
diff --git a/Battery-Notification/Battery-Notification.py b/Battery-Notification/Battery-Notification.py
index a7c04044aa..c7ea7c630a 100644
--- a/Battery-Notification/Battery-Notification.py
+++ b/Battery-Notification/Battery-Notification.py
@@ -1,7 +1,7 @@
import psutil
from plyer import notification
import time
-#From psutil we import sensors battery class which gives us battery percentage
+# From psutil we import sensors battery class which gives us battery percentage
threshold = int(input('Enter the threshold: '))
battery = psutil.sensors_battery()
@@ -12,12 +12,12 @@
cur_per = battery.percent
change = cur_per - percent
diff = abs(change)
- #We calculate the change in the battery and show notification if battery level increases or decreases
+ # We calculate the change in the battery and show notification if battery level increases or decreases
if(diff >= threshold):
notification.notify(
- title = "Battery Percentage",
- message = str(cur_per) + "% Battery Remaining",
- timeout = 5
+ title="Battery Percentage",
+ message=str(cur_per) + "% Battery Remaining",
+ timeout=5
)
- percent = cur_per
+ percent = cur_per
continue
diff --git a/BitCoin Mining/BitCoin_Mining.py b/BitCoin Mining/BitCoin_Mining.py
index 61fbbbe1eb..3ec620c11c 100644
--- a/BitCoin Mining/BitCoin_Mining.py
+++ b/BitCoin Mining/BitCoin_Mining.py
@@ -8,7 +8,7 @@
# Import the sha256 function
from hashlib import sha256
-# Nonce value
+# Nonce value
MAX_NONCE = 10000
@@ -23,7 +23,7 @@ def mine(block_number, transactions, previous_hash, prefix_zeros):
# string with difficulty zeroes
prefix_str = '0'*prefix_zeros
- # nonce is the value we want
+ # nonce is the value we want
for nonce in range(MAX_NONCE):
# concatinating the string and encoding it
@@ -36,28 +36,28 @@ def mine(block_number, transactions, previous_hash, prefix_zeros):
return new_hash
# might raise exception due to hardware issues etc
- raise BaseException(f"Couldn't find correct has after trying {MAX_NONCE} times")
+ raise BaseException(
+ f"Couldn't find correct has after trying {MAX_NONCE} times")
# Driver Code
-if __name__=='__main__':
-
+if __name__ == '__main__':
+
# Transactions string
- transactions=input('Enter Transactions : ')
-
+ transactions = input('Enter Transactions : ')
+
# Number of prefix zeroes
- difficulty=int(input('Enter Difficulty level : '))
+ difficulty = int(input('Enter Difficulty level : '))
# For knowing time taken for mining
import time
start = time.time()
print("start mining")
- previous_hash=input('Enter Previous has value : ')
-
+ previous_hash = input('Enter Previous has value : ')
# Calling mine function with all required parameters
- new_hash = mine(5,transactions,previous_hash, difficulty)
+ new_hash = mine(5, transactions, previous_hash, difficulty)
# total time for refrence
total_time = str((time.time() - start))
diff --git a/Blackjack/blackjack.py b/Blackjack/blackjack.py
index 93a2221fa7..33679434d6 100644
--- a/Blackjack/blackjack.py
+++ b/Blackjack/blackjack.py
@@ -18,10 +18,11 @@ def __str__(self):
class Deck: # creates a deck of cards
-
+
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
- ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
-
+ ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven',
+ 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
+
def __init__(self):
self.deck = [] # haven't created a deck yet
for suit in Deck.suits:
@@ -43,9 +44,9 @@ def deal(self): # pick out a card from the deck
class Hand: # show all the cards that the dealer and player have
-
+
values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8,
- 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11}
+ 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11}
def __init__(self):
self.cards = []
@@ -102,7 +103,8 @@ def hit_or_stand(deck, hand): # hit or stand
global playing
while True:
- ask = input("\nWould you like to hit or stand? Please enter 'h' or 's': ")
+ ask = input(
+ "\nWould you like to hit or stand? Please enter 'h' or 's': ")
if ask[0].lower() == 'h':
hit(deck, hand)
@@ -218,4 +220,3 @@ def push(player, dealer):
else:
print("\nThanks for playing!")
break
-
diff --git a/Body Detection/detection.py b/Body Detection/detection.py
index 1697c007d0..14a99e109c 100644
--- a/Body Detection/detection.py
+++ b/Body Detection/detection.py
@@ -1,35 +1,35 @@
import cv2
-
+
# Load the Cascade Classifier
body_cascade = cv2.CascadeClassifier("haarcascade_fullbody.xml")
-videopath=input("Enter the video Path : ")
-#Capture the video
+videopath = input("Enter the video Path : ")
+# Capture the video
cap = cv2.VideoCapture(videopath)
-
+
while True:
-
- #read image from video
- response,frame = cap.read()
-
+
+ # read image from video
+ response, frame = cap.read()
+
if response == False:
break
-
+
# Convert to grayscale
gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
-
+
# Detect the full body
faces = body_cascade.detectMultiScale(gray_img, 1.1, 1)
-
- #display rectangle
+
+ # display rectangle
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
-
+
# display video
cv2.imshow('img', frame)
-
- if cv2.waitKey(1) & 0xFF == ord('q'):# Enter q to quit
+
+ if cv2.waitKey(1) & 0xFF == ord('q'): # Enter q to quit
break
-
+
# Release the VideoCapture object
cap.release()
cv2.destroyAllWindows()
diff --git a/Brick Breaker game/brick_breaker.py b/Brick Breaker game/brick_breaker.py
index b6615f239a..9ab47b4e61 100644
--- a/Brick Breaker game/brick_breaker.py
+++ b/Brick Breaker game/brick_breaker.py
@@ -35,195 +35,186 @@
class Ball():
- '''
- Creating ball for the game
'''
+Creating ball for the game
+'''
- def __init__(self, x, y):
-
- self.radius = 10
- self.x = x - self.radius
- self.y = y - 50
- self.rect = Rect(self.x, self.y, self.radius * 2, self.radius * 2)
- self.x_speed = 4
- self.y_speed = -4
- self.max_speed = 5
- self.game_over = 0
-
- def motion(self):
- collision_threshold = 5
- block_object = Block.bricks
- brick_destroyed = 1
- count_row = 0
- for row in block_object:
- count_item = 0
- for item in row:
- # check collision with gaming window
- if self.rect.colliderect(item[0]):
- if abs(self.rect.bottom - item[0].top) < collision_threshold and self.y_speed > 0:
- self.y_speed *= -1
-
- if abs(self.rect.top - item[0].bottom) < collision_threshold and self.y_speed < 0:
- self.y_speed *= -1
- if abs(self.rect.right -item[0].left) < collision_threshold and self.x_speed > 0:
- self.x_speed *= -1
- if abs(self.rect.left - item[0].right) < collision_threshold and self.x_speed < 0:
- self.x_speed *= -1
-
- if block_object[count_row][count_item][1] > 1:
- block_object[count_row][count_item][1] -= 1
- else:
- block_object[count_row][count_item][0] = (0, 0, 0, 0)
-
- if block_object[count_row][count_item][0] != (0, 0, 0, 0):
- brick_destroyed = 0
- count_item += 1
- count_row += 1
-
- if brick_destroyed == 1:
- self.game_over = 1
-
-
- # check for collision with bricks
- if self.rect.left < 0 or self.rect.right > Window_width:
- self.x_speed *= -1
-
- if self.rect.top < 0:
- self.y_speed *= -1
- if self.rect.bottom > Window_height:
- self.game_over = -1
-
-
- # check for collission with base
- if self.rect.colliderect(user_basepad):
- if abs(self.rect.bottom - user_basepad.rect.top) < collision_threshold and self.y_speed > 0:
- self.y_speed *= -1
- self.x_speed += user_basepad.direction
- if self.x_speed > self.max_speed:
- self.x_speed = self.max_speed
- elif self.x_speed < 0 and self.x_speed < -self.max_speed:
- self.x_speed = -self.max_speed
- else:
- self.x_speed *= -1
-
- self.rect.x += self.x_speed
- self.rect.y += self.y_speed
-
- return self.game_over
-
-
- def draw(self):
- pygame.draw.circle(window, (0, 0, 255), (self.rect.x + self.radius, self.rect.y + self.radius), self.radius)
- pygame.draw.circle(window, (255, 255, 255), (self.rect.x + self.radius, self.rect.y + self.radius), self.radius, 1)
-
-
-
- def reset(self, x, y):
-
- self.radius = 10
- self.x = x - self.radius
- self.y = y - 50
- self.rect = Rect(self.x, self.y, self.radius * 2, self.radius * 2)
- self.x_speed = 4
- self.y_speed = -4
- self.max_speed = 5
- self.game_over = 0
-
+ def __init__(self, x, y):
+
+ self.radius = 10
+ self.x = x - self.radius
+ self.y = y - 50
+ self.rect = Rect(self.x, self.y, self.radius * 2, self.radius * 2)
+ self.x_speed = 4
+ self.y_speed = -4
+ self.max_speed = 5
+ self.game_over = 0
+
+ def motion(self):
+ collision_threshold = 5
+ block_object = Block.bricks
+ brick_destroyed = 1
+ count_row = 0
+ for row in block_object:
+ count_item = 0
+ for item in row:
+ # check collision with gaming window
+ if self.rect.colliderect(item[0]):
+ if abs(self.rect.bottom - item[0].top) < collision_threshold and self.y_speed > 0:
+ self.y_speed *= -1
+
+ if abs(self.rect.top - item[0].bottom) < collision_threshold and self.y_speed < 0:
+ self.y_speed *= -1
+ if abs(self.rect.right - item[0].left) < collision_threshold and self.x_speed > 0:
+ self.x_speed *= -1
+ if abs(self.rect.left - item[0].right) < collision_threshold and self.x_speed < 0:
+ self.x_speed *= -1
+
+ if block_object[count_row][count_item][1] > 1:
+ block_object[count_row][count_item][1] -= 1
+ else:
+ block_object[count_row][count_item][0] = (0, 0, 0, 0)
+
+ if block_object[count_row][count_item][0] != (0, 0, 0, 0):
+ brick_destroyed = 0
+ count_item += 1
+ count_row += 1
+
+ if brick_destroyed == 1:
+ self.game_over = 1
+
+ # check for collision with bricks
+ if self.rect.left < 0 or self.rect.right > Window_width:
+ self.x_speed *= -1
+
+ if self.rect.top < 0:
+ self.y_speed *= -1
+ if self.rect.bottom > Window_height:
+ self.game_over = -1
+
+ # check for collission with base
+ if self.rect.colliderect(user_basepad):
+ if abs(self.rect.bottom - user_basepad.rect.top) < collision_threshold and self.y_speed > 0:
+ self.y_speed *= -1
+ self.x_speed += user_basepad.direction
+ if self.x_speed > self.max_speed:
+ self.x_speed = self.max_speed
+ elif self.x_speed < 0 and self.x_speed < -self.max_speed:
+ self.x_speed = -self.max_speed
+ else:
+ self.x_speed *= -1
+
+ self.rect.x += self.x_speed
+ self.rect.y += self.y_speed
+
+ return self.game_over
+
+ def draw(self):
+ pygame.draw.circle(window, (0, 0, 255), (self.rect.x +
+ self.radius, self.rect.y + self.radius), self.radius)
+ pygame.draw.circle(window, (255, 255, 255), (self.rect.x +
+ self.radius, self.rect.y + self.radius), self.radius, 1)
+
+ def reset(self, x, y):
+
+ self.radius = 10
+ self.x = x - self.radius
+ self.y = y - 50
+ self.rect = Rect(self.x, self.y, self.radius * 2, self.radius * 2)
+ self.x_speed = 4
+ self.y_speed = -4
+ self.max_speed = 5
+ self.game_over = 0
class Block():
- '''
- This class will help me create Blocks/bricks of the game
'''
- def __init__(self):
- self.width = Window_width // game_coloumns
- self.height = 40
-
- def make_brick(self):
- self.bricks = []
- single_brick = []
- for row in range(game_rows):
-
- brick_row = []
-
- for coloumn in range(game_coloumns):
-
- x_brick = coloumn * self.width
- y_brick = row * self.height
- rect = pygame.Rect(x_brick, y_brick, self.width, self.height)
- # assign power to the bricks based on row
- if row < 2:
- power = 3
- elif row < 4:
- power = 2
- elif row < 6:
- power = 1
-
- single_brick = [rect, power]
-
- brick_row.append(single_brick)
-
- self.bricks.append(brick_row)
-
-
- def draw_brick(self):
- for row in self.bricks:
- for brick in row:
-
- if brick[1] == 3:
- brick_colour = O_brick
- elif brick[1] == 2:
- brick_colour = w_brick
- elif brick[1] == 1:
- brick_colour = g_brick
- pygame.draw.rect(window, brick_colour, brick[0])
- pygame.draw.rect(window, black, (brick[0]), 1)
+This class will help me create Blocks/bricks of the game
+'''
+
+ def __init__(self):
+ self.width = Window_width // game_coloumns
+ self.height = 40
+
+ def make_brick(self):
+ self.bricks = []
+ single_brick = []
+ for row in range(game_rows):
+
+ brick_row = []
+
+ for coloumn in range(game_coloumns):
+
+ x_brick = coloumn * self.width
+ y_brick = row * self.height
+ rect = pygame.Rect(x_brick, y_brick, self.width, self.height)
+ # assign power to the bricks based on row
+ if row < 2:
+ power = 3
+ elif row < 4:
+ power = 2
+ elif row < 6:
+ power = 1
+
+ single_brick = [rect, power]
+
+ brick_row.append(single_brick)
+ self.bricks.append(brick_row)
+ def draw_brick(self):
+ for row in self.bricks:
+ for brick in row:
+ if brick[1] == 3:
+ brick_colour = O_brick
+ elif brick[1] == 2:
+ brick_colour = w_brick
+ elif brick[1] == 1:
+ brick_colour = g_brick
+ pygame.draw.rect(window, brick_colour, brick[0])
+ pygame.draw.rect(window, black, (brick[0]), 1)
class base():
- '''
- This class is to create the base pad of the game
'''
- def __init__(self):
-
- self.height = 20
- self.width = int(Window_width / game_coloumns)
- self.x = int((Window_width / 2) - (self.width / 2))
- self.y = Window_height - (self.height * 2)
- self.speed = 8
- self.rect = Rect(self.x, self.y, self.width, self.height)
- self.direction = 0
+This class is to create the base pad of the game
+'''
+ def __init__(self):
- def slide(self):
-
- self.direction = 0
- key = pygame.key.get_pressed()
- if key[pygame.K_LEFT] and self.rect.left > 0:
- self.rect.x -= self.speed
- self.direction = -1
- if key[pygame.K_RIGHT] and self.rect.right < Window_width:
- self.rect.x += self.speed
- self.direction = 1
+ self.height = 20
+ self.width = int(Window_width / game_coloumns)
+ self.x = int((Window_width / 2) - (self.width / 2))
+ self.y = Window_height - (self.height * 2)
+ self.speed = 8
+ self.rect = Rect(self.x, self.y, self.width, self.height)
+ self.direction = 0
- def draw(self):
- pygame.draw.rect(window,(0, 0, 255), self.rect)
- pygame.draw.rect(window, (255, 255, 255), self.rect, 1)
+ def slide(self):
+ self.direction = 0
+ key = pygame.key.get_pressed()
+ if key[pygame.K_LEFT] and self.rect.left > 0:
+ self.rect.x -= self.speed
+ self.direction = -1
+ if key[pygame.K_RIGHT] and self.rect.right < Window_width:
+ self.rect.x += self.speed
+ self.direction = 1
- def reset(self):
+ def draw(self):
+ pygame.draw.rect(window, (0, 0, 255), self.rect)
+ pygame.draw.rect(window, (255, 255, 255), self.rect, 1)
- self.height = 20
- self.width = int(Window_width / game_coloumns)
- self.x = int((Window_width / 2) - (self.width / 2))
- self.y = Window_height - (self.height * 2)
- self.speed = 8
- self.rect = Rect(self.x, self.y, self.width, self.height)
- self.direction = 0
+ def reset(self):
+ self.height = 20
+ self.width = int(Window_width / game_coloumns)
+ self.x = int((Window_width / 2) - (self.width / 2))
+ self.y = Window_height - (self.height * 2)
+ self.speed = 8
+ self.rect = Rect(self.x, self.y, self.width, self.height)
+ self.direction = 0
def draw_text(text, font, w_brick, x, y):
@@ -234,51 +225,54 @@ def draw_text(text, font, w_brick, x, y):
window.blit(image, (x, y))
-
Block = Block()
-Block.make_brick() # Creating Brick
-user_basepad = base() # Defining base pad
-ball = Ball(user_basepad.x + (user_basepad.width // 2), user_basepad.y - user_basepad.height) # Defining ball
+# Creating Brick
+Block.make_brick()
+# Defining base pad
+user_basepad = base()
+ball = Ball(user_basepad.x + (user_basepad.width // 2),
+ user_basepad.y - user_basepad.height) # Defining ball
game = True
while game:
- clock.tick(frame_rate)
- window.fill(black) # Gaming window Background
- Block.draw_brick() # Drawing bricks
- user_basepad.draw() # Drawing user basepad
- ball.draw() # Drawing gaming ball
-
- if my_ball:
- user_basepad.slide()
- game_over = ball.motion()
- if game_over != 0:
- my_ball = False
-
-
- # Game Info on the gaming window
- if not my_ball:
- if game_over == 0:
- draw_text('CLICK ANYWHERE TO START', font, w_brick, 90, Window_height // 2 + 100)
- elif game_over == 1:
- draw_text('YOU WON!', font, w_brick, 180, Window_height // 2 + 50)
- draw_text('CLICK ANYWHERE TO RESTART', font, w_brick, 90, Window_height // 2 + 100)
- elif game_over == -1:
- draw_text('GAME OVER!', font, w_brick, 180, Window_height // 2 + 50)
- draw_text('CLICK ANYWHERE TO RESTART', font, w_brick, 90, Window_height // 2 + 100)
-
-
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- game = False
- if event.type == pygame.MOUSEBUTTONDOWN and my_ball == False:
- my_ball = True
- ball.reset(user_basepad.x + (user_basepad.width // 2), user_basepad.y - user_basepad.height)
- user_basepad.reset()
- Block.make_brick()
-
-
-
- pygame.display.update()
+ clock.tick(frame_rate)
+ window.fill(black) # Gaming window Background
+ Block.draw_brick() # Drawing bricks
+ user_basepad.draw() # Drawing user basepad
+ ball.draw() # Drawing gaming ball
+
+ if my_ball:
+ user_basepad.slide()
+ game_over = ball.motion()
+ if game_over != 0:
+ my_ball = False
+
+ # Game Info on the gaming window
+ if not my_ball:
+ if game_over == 0:
+ draw_text('CLICK ANYWHERE TO START', font,
+ w_brick, 90, Window_height // 2 + 100)
+ elif game_over == 1:
+ draw_text('YOU WON!', font, w_brick, 180, Window_height // 2 + 50)
+ draw_text('CLICK ANYWHERE TO RESTART', font,
+ w_brick, 90, Window_height // 2 + 100)
+ elif game_over == -1:
+ draw_text('GAME OVER!', font, w_brick,
+ 180, Window_height // 2 + 50)
+ draw_text('CLICK ANYWHERE TO RESTART', font,
+ w_brick, 90, Window_height // 2 + 100)
+
+ for event in pygame.event.get():
+ if event.type == pygame.QUIT:
+ game = False
+ if event.type == pygame.MOUSEBUTTONDOWN and my_ball == False:
+ my_ball = True
+ ball.reset(user_basepad.x + (user_basepad.width // 2),
+ user_basepad.y - user_basepad.height)
+ user_basepad.reset()
+ Block.make_brick()
+
+ pygame.display.update()
pygame.quit()
diff --git a/Bubble Shooter Game/bubbleshooter.py b/Bubble Shooter Game/bubbleshooter.py
index 71dad0b459..729c032a9d 100644
--- a/Bubble Shooter Game/bubbleshooter.py
+++ b/Bubble Shooter Game/bubbleshooter.py
@@ -1,50 +1,58 @@
-import math,pygame,copy,time,sys,os,random
+import math
+import pygame
+import copy
+import time
+import sys
+import os
+import random
import pygame.gfxdraw
from pygame.locals import *
-FPS=120
-winwdth=940
-winhgt=740
-txthgt=20
-bubblerad =20
-bubblewdth=bubblerad * 2
-bubblelyrs =5
-bubadjst =5
-strx =winwdth /2
-strY =winhgt - 26
-arywdth =25
-aryhgt =20
-
-RIGHT='right'
-LEFT='left'
-blank='.'
-
-vblue=(51,255,255)
-black=(0,0,0)
-white=(255,255,255)
-grey=(100,100,100)
-blue=(0,0,205)
-red=(255,0,0)
-white=(255,255,255)
-pink=(255,192,203)
-lightpink=(255,182,193)
-hotpink=(255,105,180)
-deeppink=(255,20,147)
-cyan=(0,255,255)
-peacockblue=(0,164,180)
-grapecolor=(128,49,167)
-amber=(255,198,0)
-comic=(0,174,239)
-lytgray=(217,217,214)
-peach=(255,229,180)
-green=(0, 255,0)
-GRAY=(100,100,100)
-white=(255,255,255)
-cyan=(0,255,255)
-black=(0,0,0)
-
-bgcolor =vblue
-clrlist =[grey,blue,red,white,pink,peach,hotpink,green,deeppink,peacockblue,grapecolor,amber,comic,lytgray]
+FPS = 120
+winwdth = 940
+winhgt = 740
+txthgt = 20
+bubblerad = 20
+bubblewdth = bubblerad * 2
+bubblelyrs = 5
+bubadjst = 5
+strx = winwdth / 2
+strY = winhgt - 26
+arywdth = 25
+aryhgt = 20
+
+RIGHT = 'right'
+LEFT = 'left'
+blank = '.'
+
+vblue = (51, 255, 255)
+black = (0, 0, 0)
+white = (255, 255, 255)
+grey = (100, 100, 100)
+blue = (0, 0, 205)
+red = (255, 0, 0)
+white = (255, 255, 255)
+pink = (255, 192, 203)
+lightpink = (255, 182, 193)
+hotpink = (255, 105, 180)
+deeppink = (255, 20, 147)
+cyan = (0, 255, 255)
+peacockblue = (0, 164, 180)
+grapecolor = (128, 49, 167)
+amber = (255, 198, 0)
+comic = (0, 174, 239)
+lytgray = (217, 217, 214)
+peach = (255, 229, 180)
+green = (0, 255, 0)
+GRAY = (100, 100, 100)
+white = (255, 255, 255)
+cyan = (0, 255, 255)
+black = (0, 0, 0)
+
+bgcolor = vblue
+clrlist = [grey, blue, red, white, pink, peach, hotpink, green,
+ deeppink, peacockblue, grapecolor, amber, comic, lytgray]
+
class Bubble(pygame.sprite.Sprite):
def __init__(self, color, row=0, col=0):
@@ -59,7 +67,7 @@ def __init__(self, color, row=0, col=0):
self.angle = 0
self.row = row
self.col = col
-
+
def update(self):
if self.angle == 90:
@@ -71,26 +79,29 @@ def update(self):
elif self.angle > 90:
xmove = self.xcalc(180 - self.angle) * -1
ymove = self.ycalc(180 - self.angle)
-
self.rect.x += int(xmove)
self.rect.y += int(ymove)
+
def draw(self):
- pygame.gfxdraw.filled_circle(dispsurf, self.rect.centerx, self.rect.centery, self.radius, self.color)
- pygame.gfxdraw.aacircle(dispsurf, self.rect.centerx, self.rect.centery, self.radius, GRAY)
-
+ pygame.gfxdraw.filled_circle(
+ dispsurf, self.rect.centerx, self.rect.centery, self.radius, self.color)
+ pygame.gfxdraw.aacircle(
+ dispsurf, self.rect.centerx, self.rect.centery, self.radius, GRAY)
+
def xcalc(self, angle):
radians = math.radians(angle)
-
+
xmove = math.cos(radians)*(self.speed)
return xmove
- def ycalc(self,angle):
+ def ycalc(self, angle):
radians = math.radians(angle)
-
+
ymove = math.sin(radians)*(self.speed) * -1
return ymove
+
class Ary(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
@@ -98,61 +109,66 @@ def __init__(self):
self.angle = 90
arrimg = pygame.image.load('Arrow.png')
arrimg.convert_alpha()
-
+
arrowRect = arrimg.get_rect()
self.image = arrimg
self.transformImage = self.image
self.rect = arrowRect
- self.rect.centerx = int(strx)
+ self.rect.centerx = int(strx)
self.rect.centery = strY
-
+
def update(self, dir):
-
+
if (dir == LEFT and self.angle < 180):
self.angle += 2
- elif (dir == RIGHT and self.angle > 0):
+ elif (dir == RIGHT and self.angle > 0):
self.angle -= 2
self.transformImage = pygame.transform.rotate(self.image, self.angle)
self.rect = self.transformImage.get_rect()
- self.rect.centerx = int(strx)
+ self.rect.centerx = int(strx)
self.rect.centery = strY
-
+
def draw(self):
dispsurf.blit(self.transformImage, self.rect)
-
+
+
class Score(object):
def __init__(self):
self.total = 0
self.font = pygame.font.SysFont('merlin', 35)
- self.render = self.font.render('Score: ' + str(self.total), True, black, white)
+ self.render = self.font.render(
+ 'Score: ' + str(self.total), True, black, white)
self.rect = self.render.get_rect()
self.rect.left = 5
self.rect.bottom = winhgt - 5
-
+
def update(self, dellst):
self.total += ((len(dellst)) * 10)
- self.render = self.font.render('Score: ' + str(self.total), True, black, white)
+ self.render = self.font.render(
+ 'Score: ' + str(self.total), True, black, white)
def draw(self):
dispsurf.blit(self.render, self.rect)
-
+
+
def main():
-
+
global fpsclock, dispsurf, disprect, mainfont
pygame.init()
-
+
fpsclock = pygame.time.Clock()
pygame.display.set_caption('Bubble Shooter')
mainfont = pygame.font.SysFont('Comic Sans MS', txthgt)
dispsurf, disprect = makeDisplay()
-
+
while True:
score, winorlose = rngame()
endScreen(score, winorlose)
-
+
+
def rngame():
- musclist =['Whatever_It _Takes_OGG.ogg','bgmusic.ogg','Goofy_Theme.ogg']
+ musclist = ['Whatever_It _Takes_OGG.ogg', 'bgmusic.ogg', 'Goofy_Theme.ogg']
pygame.mixer.music.load(musclist[0])
pygame.mixer.music.play()
track = 0
@@ -160,30 +176,30 @@ def rngame():
dir = None
launchbb = False
newbb = None
-
+
arrow = Ary()
bbarr = mkeblkbrd()
setbb(bbarr, gameclrlist)
-
+
nxtbb = Bubble(gameclrlist[0])
nxtbb.rect.right = winwdth - 5
nxtbb.rect.bottom = winhgt - 5
score = Score()
-
+
while True:
dispsurf.fill(bgcolor)
-
+
for event in pygame.event.get():
if event.type == QUIT:
terminate()
-
+
elif event.type == KEYDOWN:
if (event.key == K_LEFT):
dir = LEFT
elif (event.key == K_RIGHT):
dir = RIGHT
-
+
elif event.type == KEYUP:
dir = None
if event.key == K_SPACE:
@@ -195,10 +211,10 @@ def rngame():
if newbb == None:
newbb = Bubble(nxtbb.color)
newbb.angle = arrow.angle
-
+
newbb.update()
newbb.draw()
-
+
if newbb.rect.right >= winwdth - 5:
newbb.angle = 180 - newbb.angle
elif newbb.rect.left <= 5:
@@ -212,24 +228,24 @@ def rngame():
fbblist.append(bbarr[row][col])
if bbarr[row][col].rect.bottom > (winhgt - arrow.rect.height - 10):
return score.total, 'lose'
-
+
if len(fbblist) < 1:
return score.total, 'win'
gameclrlist = updtclrlist(bbarr)
- random.shuffle(gameclrlist)
+ random.shuffle(gameclrlist)
if launchbb == False:
-
+
nxtbb = Bubble(gameclrlist[0])
nxtbb.rect.right = winwdth - 5
- nxtbb.rect.bottom = winhgt - 5
-
+ nxtbb.rect.bottom = winhgt - 5
+
nxtbb.draw()
if launchbb == True:
covnxtbb()
-
+
arrow.update(dir)
arrow.draw()
-
+
setarrpos(bbarr)
drawbbary(bbarr)
@@ -243,13 +259,14 @@ def rngame():
pygame.mixer.music.load(musclist[track])
pygame.mixer.music.play()
-
+
pygame.display.update()
fpsclock.tick(FPS)
+
def mkeblkbrd():
array = []
-
+
for row in range(aryhgt):
col = []
for i in range(arywdth):
@@ -258,15 +275,17 @@ def mkeblkbrd():
return array
+
def setbb(array, gameclrlist):
for row in range(bubblelyrs):
for col in range(len(array[row])):
random.shuffle(gameclrlist)
newbb = Bubble(gameclrlist[0], row, col)
- array[row][col] = newbb
-
+ array[row][col] = newbb
+
setarrpos(array)
+
def setarrpos(array):
for row in range(aryhgt):
for col in range(len(array[row])):
@@ -278,14 +297,15 @@ def setarrpos(array):
for col in range(len(array[row])):
if array[row][col] != blank:
array[row][col].rect.x += bubblerad
-
+
for row in range(1, aryhgt):
for col in range(len(array[row])):
if array[row][col] != blank:
array[row][col].rect.y -= (bubadjst * row)
delextrbb(array)
-
+
+
def delextrbb(array):
for row in range(aryhgt):
for col in range(len(array[row])):
@@ -293,6 +313,7 @@ def delextrbb(array):
if array[row][col].rect.right > winwdth:
array[row][col] = blank
+
def updtclrlist(bbarr):
newColorList = []
for row in range(len(bbarr)):
@@ -309,10 +330,11 @@ def updtclrlist(bbarr):
else:
return list(colorSet)
-
+
+
def chkfflotrs(bbarr):
bubbleList = [col for col in range(len(bbarr[0]))
- if bbarr[0][col] != blank]
+ if bbarr[0][col] != blank]
newbbList = []
@@ -331,47 +353,49 @@ def chkfflotrs(bbarr):
for col in newbbList:
popflotrs(bbarr, cpyofbrd, col)
+
def popflotrs(bbarr, cpyofbrd, col, row=0):
if (row < 0 or row > (len(bbarr)-1)
- or col < 0 or col > (len(bbarr[0])-1)):
+ or col < 0 or col > (len(bbarr[0])-1)):
return
elif cpyofbrd[row][col] == blank:
return
elif bbarr[row][col] == cpyofbrd[row][col]:
return
bbarr[row][col] = cpyofbrd[row][col]
- if(row==0):
+ if(row == 0):
popflotrs(bbarr, cpyofbrd, col + 1, row)
popflotrs(bbarr, cpyofbrd, col - 1, row)
- popflotrs(bbarr, cpyofbrd, col,row + 1)
+ popflotrs(bbarr, cpyofbrd, col, row + 1)
popflotrs(bbarr, cpyofbrd, col - 1, row + 1)
- elif(row%2==0):
+ elif(row % 2 == 0):
popflotrs(bbarr, cpyofbrd, col + 1, row)
popflotrs(bbarr, cpyofbrd, col - 1, row)
- popflotrs(bbarr, cpyofbrd, col,row + 1)
+ popflotrs(bbarr, cpyofbrd, col, row + 1)
popflotrs(bbarr, cpyofbrd, col - 1, row + 1)
- popflotrs(bbarr, cpyofbrd, col,row - 1)
+ popflotrs(bbarr, cpyofbrd, col, row - 1)
popflotrs(bbarr, cpyofbrd, col - 1, row - 1)
else:
popflotrs(bbarr, cpyofbrd, col + 1, row)
popflotrs(bbarr, cpyofbrd, col - 1, row)
- popflotrs(bbarr, cpyofbrd, col,row + 1)
+ popflotrs(bbarr, cpyofbrd, col, row + 1)
popflotrs(bbarr, cpyofbrd, col + 1, row + 1)
- popflotrs(bbarr, cpyofbrd, col,row - 1)
+ popflotrs(bbarr, cpyofbrd, col, row - 1)
popflotrs(bbarr, cpyofbrd, col + 1, row - 1)
-
+
+
def stbb(bbarr, newbb, launchbb, score):
dellst = []
popSound = pygame.mixer.Sound('popcork.ogg')
-
+
for row in range(len(bbarr)):
for col in range(len(bbarr[row])):
-
+
if (bbarr[row][col] != blank and newbb != None):
if (pygame.sprite.collide_rect(newbb, bbarr[row][col])) or newbb.rect.top < 0:
if newbb.rect.top < 0:
newRow, newcol = addbbtotop(bbarr, newbb)
-
+
elif newbb.rect.centery >= bbarr[row][col].rect.centery:
if newbb.rect.centerx >= bbarr[row][col].rect.centerx:
@@ -383,7 +407,7 @@ def stbb(bbarr, newbb, launchbb, score):
bbarr[newRow][newcol] = copy.copy(newbb)
bbarr[newRow][newcol].row = newRow
bbarr[newRow][newcol].col = newcol
-
+
else:
newRow = row + 1
newcol = col + 1
@@ -392,7 +416,7 @@ def stbb(bbarr, newbb, launchbb, score):
bbarr[newRow][newcol] = copy.copy(newbb)
bbarr[newRow][newcol].row = newRow
bbarr[newRow][newcol].col = newcol
-
+
elif newbb.rect.centerx < bbarr[row][col].rect.centerx:
if row == 0 or row % 2 == 0:
newRow = row + 1
@@ -412,7 +436,7 @@ def stbb(bbarr, newbb, launchbb, score):
bbarr[newRow][newcol] = copy.copy(newbb)
bbarr[newRow][newcol].row = newRow
bbarr[newRow][newcol].col = newcol
-
+
elif(newbb.rect.centery < bbarr[row][col].rect.centery):
if(newbb.rect.centerx >= bbarr[row][col].rect.centerx):
if(row == 0 or row % 2 == 0):
@@ -431,7 +455,7 @@ def stbb(bbarr, newbb, launchbb, score):
bbarr[newRow][newcol] = copy.copy(newbb)
bbarr[newRow][newcol].row = newRow
bbarr[newRow][newcol].col = newcol
-
+
elif newbb.rect.centerx <= bbarr[row][col].rect.centerx:
if(row == 0 or row % 2 == 0):
newRow = row - 1
@@ -441,7 +465,7 @@ def stbb(bbarr, newbb, launchbb, score):
bbarr[newRow][newcol] = copy.copy(newbb)
bbarr[newRow][newcol].row = newRow
bbarr[newRow][newcol].col = newcol
-
+
else:
newRow = row - 1
newcol = col
@@ -452,7 +476,7 @@ def stbb(bbarr, newbb, launchbb, score):
bbarr[newRow][newcol].col = newcol
popbb(bbarr, newRow, newcol, newbb.color, dellst)
-
+
if(len(dellst) >= 3):
for pos in dellst:
popSound.play()
@@ -460,27 +484,29 @@ def stbb(bbarr, newbb, launchbb, score):
col = pos[1]
bbarr[row][col] = blank
chkfflotrs(bbarr)
-
+
score.update(dellst)
launchbb = False
newbb = None
return launchbb, newbb, score
-
-def addbbtotop(bbarr,bubble):
- posx=bubble.rect.centerx
- leftSidex =posx-bubblerad
+
+
+def addbbtotop(bbarr, bubble):
+ posx = bubble.rect.centerx
+ leftSidex = posx-bubblerad
coldiv = math.modf(float(leftSidex)/float(bubblewdth))
col = int(coldiv[1])
if (coldiv[0] < 0.5):
- bbarr[0][col]=copy.copy(bubble)
+ bbarr[0][col] = copy.copy(bubble)
else:
col += 1
- bbarr[0][col]= copy.copy(bubble)
+ bbarr[0][col] = copy.copy(bubble)
row = 0
return row, col
-
+
+
def popbb(bbarr, row, col, color, dellst):
if(row < 0 or col < 0 or row > (len(bbarr)-1) or col > (len(bbarr[0])-1)):
return
@@ -493,30 +519,34 @@ def popbb(bbarr, row, col, color, dellst):
return
dellst.append((row, col))
if(row == 0):
- popbb(bbarr,row,col-1,color,dellst)
- popbb(bbarr,row,col+1,color,dellst)
- popbb(bbarr,row+1,col,color,dellst)
- popbb(bbarr,row+1,col-1,color,dellst)
+ popbb(bbarr, row, col-1, color, dellst)
+ popbb(bbarr, row, col+1, color, dellst)
+ popbb(bbarr, row+1, col, color, dellst)
+ popbb(bbarr, row+1, col-1, color, dellst)
elif(row % 2 == 0):
- popbb(bbarr,row +1,col,color,dellst)
- popbb(bbarr,row +1,col-1,color,dellst)
- popbb(bbarr,row -1,col,color,dellst)
- popbb(bbarr,row -1,col -1,color,dellst)
- popbb(bbarr,row,col+1,color,dellst)
- popbb(bbarr,row,col-1,color,dellst)
+ popbb(bbarr, row + 1, col, color, dellst)
+ popbb(bbarr, row + 1, col-1, color, dellst)
+ popbb(bbarr, row - 1, col, color, dellst)
+ popbb(bbarr, row - 1, col - 1, color, dellst)
+ popbb(bbarr, row, col+1, color, dellst)
+ popbb(bbarr, row, col-1, color, dellst)
else:
- popbb(bbarr,row - 1,col,color,dellst)
- popbb(bbarr,row - 1,col + 1,color,dellst)
- popbb(bbarr,row + 1,col,color,dellst)
- popbb(bbarr,row + 1,col + 1, color, dellst)
- popbb(bbarr,row,col + 1,color,dellst)
- popbb(bbarr,row,col - 1,color,dellst)
+ popbb(bbarr, row - 1, col, color, dellst)
+ popbb(bbarr, row - 1, col + 1, color, dellst)
+ popbb(bbarr, row + 1, col, color, dellst)
+ popbb(bbarr, row + 1, col + 1, color, dellst)
+ popbb(bbarr, row, col + 1, color, dellst)
+ popbb(bbarr, row, col - 1, color, dellst)
+
+
def drawbbary(array):
for row in range(aryhgt):
for col in range(len(array[row])):
if(array[row][col] != blank):
array[row][col].draw()
+
+
def makeDisplay():
dispsurf = pygame.display.set_mode((winwdth, winhgt))
disprect = dispsurf.get_rect()
@@ -525,20 +555,24 @@ def makeDisplay():
pygame.display.update()
return dispsurf, disprect
-
+
+
def terminate():
pygame.quit()
sys.exit()
+
def covnxtbb():
whiteRect = pygame.Rect(0, 0, bubblewdth, bubblewdth)
whiteRect.bottom = winhgt
whiteRect.right = winwdth
pygame.draw.rect(dispsurf, bgcolor, whiteRect)
+
def endScreen(score, winorlose):
endFont = pygame.font.SysFont('merlin', 50)
- endMessage1 = endFont.render('You ' + winorlose + '! Hey Your Scored ' + str(score) + '. Press Enter to Play Again.', True, black, bgcolor)
+ endMessage1 = endFont.render('You ' + winorlose + '! Hey Your Scored ' + str(
+ score) + '. Press Enter to Play Again.', True, black, bgcolor)
endMessage1Rect = endMessage1.get_rect()
endMessage1Rect.center = disprect.center
@@ -555,8 +589,7 @@ def endScreen(score, winorlose):
return
elif(event.key == K_ESCAPE):
terminate()
-
+
+
if __name__ == '__main__':
main()
-
-
diff --git a/Bubble-Sort-Visualization/bubble_sort.py b/Bubble-Sort-Visualization/bubble_sort.py
index 113a191504..5c7938440f 100644
--- a/Bubble-Sort-Visualization/bubble_sort.py
+++ b/Bubble-Sort-Visualization/bubble_sort.py
@@ -5,14 +5,15 @@
unsorted_data = data = []
+
def draw_data(data, colors):
""""
Function that is used to draw the array of data
-
+
Inputs:
data => array of the data to be drawn
colors => array carrying the corresponding color of each value in the array
-
+
"""
canvas.delete("all")
canvas_height = 500
@@ -20,129 +21,138 @@ def draw_data(data, colors):
x_width = canvas_width / (len(data) + 1)
offset = 20
spacing = 10
-
+
# Normalizing the heights of the bars
normalize_data = [i / max(data) for i in data]
-
+
for i, rec_height in enumerate(normalize_data):
x_initial = i * x_width + offset + spacing
y_initial = canvas_height - rec_height * 460
-
+
x_final = (i+1) * x_width + offset
y_final = canvas_height
-
- canvas.create_rectangle(x_initial, y_initial, x_final, y_final, fill=colors[i])
- canvas.create_text(x_initial + 2, y_initial, anchor=SW, text=str(data[i]))
-
+
+ canvas.create_rectangle(x_initial, y_initial,
+ x_final, y_final, fill=colors[i])
+ canvas.create_text(x_initial + 2, y_initial,
+ anchor=SW, text=str(data[i]))
+
# Updating the canvas after sleep
- main_prog.update_idletasks();
+ main_prog.update_idletasks()
def generate_array():
""""
Function that is used to generate an array of data on clicking on the generate button in the UI_frame
-
+
"""
global data, unsorted_data
-
+
# Reading user inputs
min_val = int(min_value.get())
size_val = int(size_value.get())
- max_val = int(max_value.get())
-
+ max_val = int(max_value.get())
+
if(min_val > max_val):
- messagebox.showwarning(message="Max. value should not be less than Min. value")
+ messagebox.showwarning(
+ message="Max. value should not be less than Min. value")
min_val, max_val = max_val, min_val
-
+
data = []
-
+
for i in range(size_val):
data.append(random.randrange(min_val, max_val + 1))
-
- unsorted_data = data.copy()
- draw_data(data, [ "red" for x in range(len(data)) ])
+ unsorted_data = data.copy()
+ draw_data(data, ["red" for x in range(len(data))])
def reset_array():
"""
Function that resets the current sorted array
-
+
"""
global data
- data = unsorted_data.copy();
- draw_data(data, [ "red" for x in range(len(data)) ])
-
+ data = unsorted_data.copy()
+ draw_data(data, ["red" for x in range(len(data))])
def bubble_sort(data, speed):
"""
Function that performs bubble sort on the passed array
-
+
Inputs:
data => array to be sorted
speed => speed of the simulation
"""
-
+
for i in range(len(data)-1):
- for j in range(len(data)- i - 1):
+ for j in range(len(data) - i - 1):
if data[j] > data[j+1]:
data[j], data[j+1] = data[j+1], data[j]
- draw_data(data, ["yellow" if x == j or x == j+1 else "red" for x in range(len(data))])
+ draw_data(data, ["yellow" if x == j or x == j +
+ 1 else "red" for x in range(len(data))])
time.sleep(speed)
-
+
draw_data(data, ["green" for x in range(len(data))])
-
+
def run_sort():
"""
Function that runs the simulation on user click
-
+
"""
global data
bubble_sort(data, speed_scale.get())
-## Intialzing main program
+
+# Intialzing main program
main_prog = Tk()
main_prog.title("Bubble Sort Visualization")
main_prog.maxsize(800, 800)
main_prog.config(bg="grey")
-## Creating user interface frame
+# Creating user interface frame
UI_frame = Frame(main_prog, width=800, height=300, bg="grey")
UI_frame.grid(row=0, column=0)
-Label(UI_frame, text="Let's learn Bubble Sort", bg="grey").grid(row=0, column=0, padx=5, pady=5, sticky=W)
-Button(UI_frame, text="Start", command=run_sort, bg="green").grid(row=0, column=1, padx=5, pady=5)
+Label(UI_frame, text="Let's learn Bubble Sort", bg="grey").grid(
+ row=0, column=0, padx=5, pady=5, sticky=W)
+Button(UI_frame, text="Start", command=run_sort,
+ bg="green").grid(row=0, column=1, padx=5, pady=5)
-speed_scale = Scale(UI_frame, from_=0.1, to=2.0, length=200, digits=2, resolution=0.2, orient=HORIZONTAL, label="Select Speed", bg="ivory")
+speed_scale = Scale(UI_frame, from_=0.1, to=2.0, length=200, digits=2,
+ resolution=0.2, orient=HORIZONTAL, label="Select Speed", bg="ivory")
speed_scale.grid(row=0, column=2, padx=5, pady=5)
-## Creating scale for array size
-size_value = Scale(UI_frame, from_=0, to=30, resolution=1, orient=HORIZONTAL, label="Select Size", bg="ivory")
+# Creating scale for array size
+size_value = Scale(UI_frame, from_=0, to=30, resolution=1,
+ orient=HORIZONTAL, label="Select Size", bg="ivory")
size_value.grid(row=1, column=0, padx=5, pady=5, sticky=W)
-## Creating scale for min. value of generated values
-min_value = Scale(UI_frame, from_=0, to=100, resolution=10, orient=HORIZONTAL, label="Select Min. value", bg="ivory")
+# Creating scale for min. value of generated values
+min_value = Scale(UI_frame, from_=0, to=100, resolution=10,
+ orient=HORIZONTAL, label="Select Min. value", bg="ivory")
min_value.grid(row=1, column=1, padx=5, pady=5, sticky=W)
-## Creating scale for max. value of generated values
-max_value = Scale(UI_frame, from_=0, to=500, resolution=10, orient=HORIZONTAL, label="Select Max. value", bg="ivory")
+# Creating scale for max. value of generated values
+max_value = Scale(UI_frame, from_=0, to=500, resolution=10,
+ orient=HORIZONTAL, label="Select Max. value", bg="ivory")
max_value.grid(row=1, column=2, padx=5, pady=5, sticky=W)
# Generate random array button
-Button(UI_frame, text="Generate",command=generate_array, bg="blue").grid(row=2, column=2, padx=5, pady=5)
+Button(UI_frame, text="Generate", command=generate_array,
+ bg="blue").grid(row=2, column=2, padx=5, pady=5)
# Reset the current array button
-Button(UI_frame, text="Reset",command=reset_array, bg="blue").grid(row=2, column=1, padx=5, pady=5)
+Button(UI_frame, text="Reset", command=reset_array,
+ bg="blue").grid(row=2, column=1, padx=5, pady=5)
-## Creating canvas for visualization
+# Creating canvas for visualization
canvas = Canvas(main_prog, width=800, height=500, bg="white")
canvas.grid(row=1, column=0)
-
-## Running main program
+# Running main program
main_prog.mainloop()
-
diff --git a/CPU temperature/temp.py b/CPU temperature/temp.py
index 19cdfdf5db..ddb0560ece 100644
--- a/CPU temperature/temp.py
+++ b/CPU temperature/temp.py
@@ -1,7 +1,7 @@
# importing the psutil library
import psutil
-# Note: It is not for windows user
+# Note: It is not for windows user
data = psutil.sensors_temperatures()
-print("Current Temperature of CPU (celcius): ",data['coretemp'][0][1])
+print("Current Temperature of CPU (celcius): ", data['coretemp'][0][1])
diff --git a/Caesar-Cipher/caesar_cipher.py b/Caesar-Cipher/caesar_cipher.py
index 8d29483de2..0a53388778 100644
--- a/Caesar-Cipher/caesar_cipher.py
+++ b/Caesar-Cipher/caesar_cipher.py
@@ -1,31 +1,32 @@
import string as st
-letter_list=st.ascii_lowercase
-alphabet=[letter for letter in letter_list]*2
+letter_list = st.ascii_lowercase
+alphabet = [letter for letter in letter_list]*2
+
def caesar(text1, shift1, direction1):
- end_text = ''
- if direction=='decode':
- shift1 *= -1
+ end_text = ''
+ if direction == 'decode':
+ shift1 *= -1
- for char in text1:
- if char in alphabet:
- position = alphabet.index(char)
- new_position = position + shift1
- end_text += alphabet[new_position]
- else:
- end_text += char
- print(f'The {direction1}d text is: {end_text}.')
+ for char in text1:
+ if char in alphabet:
+ position = alphabet.index(char)
+ new_position = position + shift1
+ end_text += alphabet[new_position]
+ else:
+ end_text += char
+ print(f'The {direction1}d text is: {end_text}.')
should_continue = True
while should_continue:
- direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
- text = input("Type your message:\n").lower()
- shift = int(input("Type the shift number:\n"))
- shift = shift % 25
+ direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
+ text = input("Type your message:\n").lower()
+ shift = int(input("Type the shift number:\n"))
+ shift = shift % 25
- caesar(text, shift, direction)
- choice=input("Type 'yes' to continue otherwise type 'no'.\n")
- if choice == 'no':
- should_continue=False
+ caesar(text, shift, direction)
+ choice = input("Type 'yes' to continue otherwise type 'no'.\n")
+ if choice == 'no':
+ should_continue = False
diff --git a/Calendar GUI/Calendar_gui.py b/Calendar GUI/Calendar_gui.py
index 59d70c3a35..4573121aa8 100644
--- a/Calendar GUI/Calendar_gui.py
+++ b/Calendar GUI/Calendar_gui.py
@@ -3,70 +3,60 @@
import calendar
-def showCal() :
+def showCal():
-
- box= Tk()
-
-
+ box = Tk()
box.title("Calendar For The Year")
-
+
box.geometry("550x600")
-
+
find_year = int(year_field.get())
-
- first_label = Label(box,text = 'CALENDAR',bg = 'dark grey' , font = ("times",28,'bold'))
- first_label.grid(row=1,column =1)
-
- box.config(background = "white")
-
- cal_data = calendar.calendar(find_year)
- cal_year = Label(box, text = cal_data, font = "consolas 10 bold",justify=LEFT)
- cal_year.grid(row = 2, column = 1, padx = 20,)
+ first_label = Label(box, text='CALENDAR', bg='dark grey',
+ font=("times", 28, 'bold'))
+ first_label.grid(row=1, column=1)
-
- box.mainloop()
+ box.config(background="white")
+ cal_data = calendar.calendar(find_year)
+ cal_year = Label(box, text=cal_data, font="consolas 10 bold", justify=LEFT)
+ cal_year.grid(row=2, column=1, padx=20,)
+
+ box.mainloop()
-if __name__ == "__main__" :
+if __name__ == "__main__":
-
gui = Tk()
-
- gui.config(background = "misty rose")
+ gui.config(background="misty rose")
gui.title("CALENDAR")
gui.geometry("250x250")
-
- cal = Label(gui, text = "CALENDAR",bg="lavender",font = ("Helvetica", 28, 'bold','underline'))
+ cal = Label(gui, text="CALENDAR", bg="lavender",
+ font=("Helvetica", 28, 'bold', 'underline'))
-
- year = Label(gui, text = "Enter Year", bg = "peach puff" , padx=10, pady=10 )
+ year = Label(gui, text="Enter Year", bg="peach puff", padx=10, pady=10)
year_field = Entry(gui)
+ Show = Button(gui, text="Show Calendar", fg="Black",
+ bg="lavender", command=showCal)
- Show = Button(gui, text = "Show Calendar", fg = "Black",
- bg = "lavender", command = showCal)
-
- Exit = Button(gui, text = "CLOSE", bg = "peach puff", command = exit)
+ Exit = Button(gui, text="CLOSE", bg="peach puff", command=exit)
-
- cal.grid(row = 1, column = 1)
+ cal.grid(row=1, column=1)
- year.grid(row = 3, column = 1)
+ year.grid(row=3, column=1)
- year_field.grid(row = 4, column = 1)
+ year_field.grid(row=4, column=1)
- Show.grid(row = 5, column = 1)
+ Show.grid(row=5, column=1)
- Exit.grid(row = 7, column = 1)
+ Exit.grid(row=7, column=1)
- gui.mainloop()
\ No newline at end of file
+ gui.mainloop()
diff --git a/Cartooning Image/cartooneffect.py b/Cartooning Image/cartooneffect.py
index 054fb79656..8909eaead9 100644
--- a/Cartooning Image/cartooneffect.py
+++ b/Cartooning Image/cartooneffect.py
@@ -1,4 +1,4 @@
-
+
import cv2
import numpy as np
from tkinter.filedialog import *
@@ -8,16 +8,17 @@
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
grey = cv2.medianBlur(grey, 5)
-edges = cv2.adaptiveThreshold(grey, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9)
+edges = cv2.adaptiveThreshold(
+ grey, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9)
-#cartoonize
+# cartoonize
color = cv2.bilateralFilter(img, 9, 250, 250)
-cartoon = cv2.bitwise_and(color, color, mask = edges)
+cartoon = cv2.bitwise_and(color, color, mask=edges)
cv2.imshow("Image", img)
cv2.imshow("Cartoon", cartoon)
-#save
+# save
cv2.imwrite("cartoon.jpg", cartoon)
cv2.waitKey(0)
cv2.destroyAllWindows()
diff --git a/Censor word detection/censor_word_detection.py b/Censor word detection/censor_word_detection.py
index a0663c6052..359aa84022 100644
--- a/Censor word detection/censor_word_detection.py
+++ b/Censor word detection/censor_word_detection.py
@@ -1,12 +1,14 @@
from better_profanity import profanity
+
def detect(data):
try:
- output=profanity.censor(data,'#')
+ output = profanity.censor(data, '#')
print(output)
except Exception as e:
print(e)
+
profanity.load_censor_words()
data = input("enter your msg:")
detect(data)
diff --git a/Codechef Scrapper/codechef.py b/Codechef Scrapper/codechef.py
index 37220ca3f7..22660ff25e 100644
--- a/Codechef Scrapper/codechef.py
+++ b/Codechef Scrapper/codechef.py
@@ -1,116 +1,125 @@
+from fpdf import FPDF
+from selenium.common.exceptions import TimeoutException
+from selenium.common.exceptions import NoSuchElementException
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support import expected_conditions as EC
+from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium import webdriver
import os
options = webdriver.ChromeOptions()
options.add_argument("--headless")
-from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
-from selenium.webdriver.support.ui import WebDriverWait
-from selenium.webdriver.support import expected_conditions as EC
-from selenium.webdriver.common.by import By
-from selenium.common.exceptions import NoSuchElementException
-from selenium.common.exceptions import TimeoutException
-from fpdf import FPDF
capa = DesiredCapabilities.CHROME
capa["pageLoadStrategy"] = "none"
-driver = webdriver.Chrome(desired_capabilities=capa,options=options)
-baseurl="https://www.codechef.com/problems"
+driver = webdriver.Chrome(desired_capabilities=capa, options=options)
+baseurl = "https://www.codechef.com/problems"
wait = WebDriverWait(driver, 15)
# map to get url from its problem difficulty
-problem_difficulty = {"Beginner": "school", "Easy": "easy", "Medium": "medium", "Hard": "hard", "Challenge": "challenge"}
+problem_difficulty = {"Beginner": "school", "Easy": "easy",
+ "Medium": "medium", "Hard": "hard", "Challenge": "challenge"}
# get_problems returns the name and links of the problems
+
+
def get_problems(category, no_of_problems):
-# A map to store problem name and problem url
+ # A map to store problem name and problem url
problem_info = {}
try:
driver.get(baseurl + '/' + category)
# wait till the first element is loaded
- wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id='primary-content']/div/div[2]/div/div[2]/table/tbody/tr[1]/td[1]/div/a/b")))
+ wait.until(EC.element_to_be_clickable(
+ (By.XPATH, "//*[@id='primary-content']/div/div[2]/div/div[2]/table/tbody/tr[1]/td[1]/div/a/b")))
except TimeoutException as exception:
print("Couldn't fetch problem. Network issue or page slow to render. Try again")
os._exit(-1)
-
-
for problem_index in range(1, no_of_problems + 1):
- problem_name = driver.find_element_by_xpath("//*[@id='primary-content']/div/div[2]/div/div[2]/table/tbody/tr[{}]/td[1]/div/a/b".format(problem_index)).text
- problem_url = driver.find_element_by_xpath("//*[@id='primary-content']/div/div[2]/div/div[2]/table/tbody/tr[{}]/td[1]/div/a".format(problem_index)).get_attribute('href')
- print(problem_name," ",problem_url)
+ problem_name = driver.find_element_by_xpath(
+ "//*[@id='primary-content']/div/div[2]/div/div[2]/table/tbody/tr[{}]/td[1]/div/a/b".format(problem_index)).text
+ problem_url = driver.find_element_by_xpath(
+ "//*[@id='primary-content']/div/div[2]/div/div[2]/table/tbody/tr[{}]/td[1]/div/a".format(problem_index)).get_attribute('href')
+ print(problem_name, " ", problem_url)
problem_info[problem_name] = problem_url
return problem_info
-
+
# get_problem_desciption returns content of the problem
-def get_problem_description(problem_url,problem_name):
+
+
+def get_problem_description(problem_url, problem_name):
try:
driver.get(problem_url)
- wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id='problem-statement']/p[1]")))
- problem_title= problem_name
- problem_statement = driver.find_element_by_xpath("//*[@id='problem-statement']/p[1]").text
- problem_test_cases = driver.find_element_by_xpath("//*[@id='problem-statement']/pre[1]").text
+ wait.until(EC.element_to_be_clickable(
+ (By.XPATH, "//*[@id='problem-statement']/p[1]")))
+ problem_title = problem_name
+ problem_statement = driver.find_element_by_xpath(
+ "//*[@id='problem-statement']/p[1]").text
+ problem_test_cases = driver.find_element_by_xpath(
+ "//*[@id='problem-statement']/pre[1]").text
-
if (problem_test_cases.find("Output") == -1):
problem_test_cases = "Input\n" + problem_test_cases
- problem_test_cases+="\nOutput\n"
- problem_test_cases += driver.find_element_by_xpath("//*[@id='problem-statement']/pre[2]").text
-
-
+ problem_test_cases += "\nOutput\n"
+ problem_test_cases += driver.find_element_by_xpath(
+ "//*[@id='problem-statement']/pre[2]").text
+
else:
-
-
+
driver.execute_script("window.stop();")
- problem={'title':problem_title,'statement':problem_statement,'test_case':problem_test_cases,'url':problem_url}
+ problem = {'title': problem_title, 'statement': problem_statement,
+ 'test_case': problem_test_cases, 'url': problem_url}
return problem
-
- #Handling exceptions
+
+ # Handling exceptions
except NoSuchElementException as e:
print("Couldn't scrap the element, Unable to locate it")
- problem=None
+ problem = None
except TimeoutException as exception:
print("Couldn't scrap the element, Unable to locate it")
- problem=None
-
-
+ problem = None
-
-#storing the information in the pdf
+# storing the information in the pdf
def convert_to_pdf(problem):
pdf = FPDF()
pdf.add_page()
- pdf.set_font("Arial", size = 15)
+ pdf.set_font("Arial", size=15)
# Replace character that aren't in latin-1 character set
- title=problem["title"].encode('latin-1', 'replace').decode('latin-1')
- statement=problem["statement"].encode('latin-1', 'replace').decode('latin-1')
- test_case=problem["test_case"].encode('latin-1', 'replace').decode('latin-1')
- url=problem["url"]
+ title = problem["title"].encode('latin-1', 'replace').decode('latin-1')
+ statement = problem["statement"].encode(
+ 'latin-1', 'replace').decode('latin-1')
+ test_case = problem["test_case"].encode(
+ 'latin-1', 'replace').decode('latin-1')
+ url = problem["url"]
# add sections to pdf
- pdf.cell(200, 10, txt =title, ln = 1, align = 'C')
- pdf.multi_cell(200, 10, txt =statement, align = 'L')
- pdf.multi_cell(200, 10, txt =test_case, align = 'L')
+ pdf.cell(200, 10, txt=title, ln=1, align='C')
+ pdf.multi_cell(200, 10, txt=statement, align='L')
+ pdf.multi_cell(200, 10, txt=test_case, align='L')
pdf.write(5, 'Problem_Link: ')
- pdf.write(5,url,url)
+ pdf.write(5, url, url)
+
+ pdf.output(title+".pdf")
-
- pdf.output(title+".pdf")
-
-
-#main function
+
+# main function
def main():
- category=input("Enter the difficulty level from the following \n Beginner \n Easy \n Medium \n Hard \n Challenge \n\n")
- no_of_problems=int(input("\n Enter the number of problems to be scrapped: \n"))
- info = get_problems(problem_difficulty[category],no_of_problems)
+ category = input(
+ "Enter the difficulty level from the following \n Beginner \n Easy \n Medium \n Hard \n Challenge \n\n")
+ no_of_problems = int(
+ input("\n Enter the number of problems to be scrapped: \n"))
+ info = get_problems(problem_difficulty[category], no_of_problems)
for name, url in info.items():
- problem=get_problem_description(url,name)
- if(problem is not None ):
+ problem = get_problem_description(url, name)
+ if(problem is not None):
convert_to_pdf(problem)
else:
pass
-
+
+
if __name__ == '__main__':
main()
diff --git a/Codes on Turtle Graphics/Animated_Robot.py b/Codes on Turtle Graphics/Animated_Robot.py
index 9e34d2a428..5d342636d2 100644
--- a/Codes on Turtle Graphics/Animated_Robot.py
+++ b/Codes on Turtle Graphics/Animated_Robot.py
@@ -1,57 +1,59 @@
import turtle as t
import time as ti
-def rectangle(hor,ver,col):
+
+def rectangle(hor, ver, col):
t.pendown() # to create a canvas for drawing
t.pensize(1) # size of pen
t.color(col)
t.begin_fill()
- for counter in range(1,3):
+ for counter in range(1, 3):
t.forward(hor)
- t.right(90) #move 90 degree right
+ t.right(90) # move 90 degree right
t.forward(ver)
- t.right(90)
+ t.right(90)
t.end_fill()
t.penup()
+
t.penup()
t.speed('slow')
t.bgcolor('Dodger blue') # give background color
-t.goto(-100,-150) # move the turtle to given coordinates
-rectangle(50,20,'blue') # create a rectangle of given size
-t.goto(-30,-150)
-rectangle(50,20,'blue')
-
-t.goto(-25,-50)
-rectangle(15,100,'grey')
-t.goto(-55,-50)
-rectangle(-15,100,'grey')
-
-t.goto(-90,100)
-rectangle(100,150,'skyblue')
-
-t.goto(-150,70)
-rectangle(60,15,'grey')
-t.goto(-150,110)
-rectangle(15,40,'grey')
-t.goto(10,70)
-rectangle(60,15,'grey')
-t.goto(55,110)
-rectangle(15,40,'grey')
-
-t.goto(-50,120)
-rectangle(15,20,'grey')
-t.goto(-85,170)
-rectangle(80,50,'red')
-t.goto(-60,160)
-rectangle(30,10,'white')
-t.goto(-55,155)
-rectangle(5,5,'black')
-t.goto(-40,155)
-rectangle(5,5,'black')
-t.goto(-65,138)
-rectangle(40,5,'black')
+t.goto(-100, -150) # move the turtle to given coordinates
+rectangle(50, 20, 'blue') # create a rectangle of given size
+t.goto(-30, -150)
+rectangle(50, 20, 'blue')
+
+t.goto(-25, -50)
+rectangle(15, 100, 'grey')
+t.goto(-55, -50)
+rectangle(-15, 100, 'grey')
+
+t.goto(-90, 100)
+rectangle(100, 150, 'skyblue')
+
+t.goto(-150, 70)
+rectangle(60, 15, 'grey')
+t.goto(-150, 110)
+rectangle(15, 40, 'grey')
+t.goto(10, 70)
+rectangle(60, 15, 'grey')
+t.goto(55, 110)
+rectangle(15, 40, 'grey')
+
+t.goto(-50, 120)
+rectangle(15, 20, 'grey')
+t.goto(-85, 170)
+rectangle(80, 50, 'red')
+t.goto(-60, 160)
+rectangle(30, 10, 'white')
+t.goto(-55, 155)
+rectangle(5, 5, 'black')
+t.goto(-40, 155)
+rectangle(5, 5, 'black')
+t.goto(-65, 138)
+rectangle(40, 5, 'black')
ti.sleep(10)
diff --git a/Codes on Turtle Graphics/Kaleido-spiral.py b/Codes on Turtle Graphics/Kaleido-spiral.py
index 75a04b4244..6ec056bdf6 100644
--- a/Codes on Turtle Graphics/Kaleido-spiral.py
+++ b/Codes on Turtle Graphics/Kaleido-spiral.py
@@ -2,9 +2,11 @@
import time as ti
from itertools import cycle
-colors = cycle(['red','orange','yellow','blue','green','purple']) # create circles and squares of different colors
+# create circles and squares of different colors
+colors = cycle(['red', 'orange', 'yellow', 'blue', 'green', 'purple'])
-def draw_circle(size,angle,shift,shape):
+
+def draw_circle(size, angle, shift, shape):
t.pencolor(next(colors))
next_shape = ''
if shape == 'circle':
@@ -17,13 +19,14 @@ def draw_circle(size,angle,shift,shape):
next_shape = 'circle'
t.right(angle)
t.forward(shift)
- draw_circle(size + 5,angle+1,shift+1,next_shape)
+ draw_circle(size + 5, angle+1, shift+1, next_shape)
+
t.bgcolor('black')
t.speed('fast') # to create the figure fastly
t.pensize(4)
-draw_circle(5,0,1,'circle')
+draw_circle(5, 0, 1, 'circle')
ti.sleep(3)
t.hideturtle()
diff --git a/Color_detection/Color_detection.py b/Color_detection/Color_detection.py
index e4d1efff4b..8407d385a0 100644
--- a/Color_detection/Color_detection.py
+++ b/Color_detection/Color_detection.py
@@ -4,30 +4,35 @@
img_path = './Color_detection/colorpic.jpg'
csv_path = './Color_detection/colors.csv'
-#Reading csv file with pandas and giving names to each column
+# Reading csv file with pandas and giving names to each column
index = ['color', 'color_name', 'hex', 'R', 'G', 'B']
df = pd.read_csv(csv_path, names=index, header=None)
-#Reading the image with opencv
+# Reading the image with opencv
img = cv2.imread(img_path)
img = cv2.resize(img, (800, 600))
-#declaring global variables
+# declaring global variables
clicked = False
r = g = b = xpos = ypos = 0
-#function to calculate minimum distance from all colors and get the most matching color
-def get_color_name(R,G,B):
+# function to calculate minimum distance from all colors and get the most matching color
+
+
+def get_color_name(R, G, B):
minimum = 10000
for i in range(len(df)):
- d = abs(R - int(df.loc[i, 'R'])) + abs(G - int(df.loc[i, 'G'])) + abs(B - int(df.loc[i, 'B']))
+ d = abs(R - int(df.loc[i, 'R'])) + abs(G -
+ int(df.loc[i, 'G'])) + abs(B - int(df.loc[i, 'B']))
if d <= minimum:
minimum = d
cname = df.loc[i, 'color_name']
return cname
-#function to get x,y coordinates of mouse double click
+# function to get x,y coordinates of mouse double click
+
+
def draw_function(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDBLCLK:
global clicked, r, g, b, xpos, ypos
@@ -39,6 +44,7 @@ def draw_function(event, x, y, flags, param):
g = int(g)
r = int(r)
+
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw_function)
@@ -49,13 +55,15 @@ def draw_function(event, x, y, flags, param):
cv2.rectangle(img, (20, 20), (600, 60), (b, g, r), -1)
# Creating text string to display( Color name and RGB values )
- text = get_color_name(r, g, b) + ' R=' + str(r) + 'G=' + str(g) + ' B=' + str(b)
+ text = get_color_name(r, g, b) + ' R=' + str(r) + \
+ 'G=' + str(g) + ' B=' + str(b)
# cv2.putText(img,text,start,font(0-7),fontScale,color,thickness,lineType )
- cv2.putText(img, text, (50,50), 2, 0.8, (255, 255, 255), 2, cv2.LINE_AA)
+ cv2.putText(img, text, (50, 50), 2, 0.8,
+ (255, 255, 255), 2, cv2.LINE_AA)
# For very light colours we will display text in black colour
- if (r+ g+ b>= 600):
+ if (r + g + b >= 600):
cv2.putText(img, text, (50, 50), 2, 0.8, (0, 0, 0), 2, cv2.LINE_AA)
clicked = False
@@ -64,4 +72,4 @@ def draw_function(event, x, y, flags, param):
break
-cv2.destroyAllWindows()
\ No newline at end of file
+cv2.destroyAllWindows()
diff --git a/Connect-4 game/Connect-4.py b/Connect-4 game/Connect-4.py
index b0aeadafb2..6eee2fe83c 100644
--- a/Connect-4 game/Connect-4.py
+++ b/Connect-4 game/Connect-4.py
@@ -3,148 +3,160 @@
import sys
import math
-BLUE = (0,0,255)
-BLACK = (0,0,0)
-RED = (255,0,0)
-YELLOW = (255,255,0)
+BLUE = (0, 0, 255)
+BLACK = (0, 0, 0)
+RED = (255, 0, 0)
+YELLOW = (255, 255, 0)
ROW_COUNT = 6
COLUMN_COUNT = 7
+
def create_board():
- board = np.zeros((ROW_COUNT,COLUMN_COUNT))
+ board = np.zeros((ROW_COUNT, COLUMN_COUNT))
return board
-def drop_piece(board,row,col,piece):
- board[row][col]=piece
-def is_valid_location(board,col):
- return board[ROW_COUNT-1][col]==0
+def drop_piece(board, row, col, piece):
+ board[row][col] = piece
+
+
+def is_valid_location(board, col):
+ return board[ROW_COUNT-1][col] == 0
+
-def get_next_open_row(board,col):
+def get_next_open_row(board, col):
for r in range(ROW_COUNT):
- if board[r][col]==0:
+ if board[r][col] == 0:
return r
+
def print_board(board):
print(np.flip(board, 0))
+
def winning_move(board, piece):
- #check horizontal locations to win
+ # check horizontal locations to win
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT):
- if board[r][c]==piece and board[r][c+1] == piece and board[r][c+2] ==piece and board[r][c+3]==piece:
+ if board[r][c] == piece and board[r][c+1] == piece and board[r][c+2] == piece and board[r][c+3] == piece:
return True
- #check vertical locations to win
+ # check vertical locations to win
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT-3):
- if board[r][c]==piece and board[r+1][c]==piece and board[r+2][c] ==piece and board[r+3][c]==piece:
+ if board[r][c] == piece and board[r+1][c] == piece and board[r+2][c] == piece and board[r+3][c] == piece:
return True
- #CHECK POSITIVE SLOPE DIAGONALS
+ # CHECK POSITIVE SLOPE DIAGONALS
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT-3):
- if board[r][c]==piece and board[r+1][c+1]==piece and board[r+2][c+2]==piece and board[r+3][c+3]==piece:
+ if board[r][c] == piece and board[r+1][c+1] == piece and board[r+2][c+2] == piece and board[r+3][c+3] == piece:
return True
- #CHECK NEGATIVE DIAGONALS
+ # CHECK NEGATIVE DIAGONALS
for c in range(COLUMN_COUNT-3):
- for r in range(3,ROW_COUNT):
- if board[r][c]==piece and board[r-1][c+1]==piece and board[r-2][c+2] ==piece and board[r-3][c+3]==piece:
+ for r in range(3, ROW_COUNT):
+ if board[r][c] == piece and board[r-1][c+1] == piece and board[r-2][c+2] == piece and board[r-3][c+3] == piece:
return True
+
def draw_board(board):
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
- pygame.draw.rect(screen,BLUE,(c*SQUARESIZE,r*SQUARESIZE+SQUARESIZE,SQUARESIZE,SQUARESIZE))
- pygame.draw.circle(screen,BLACK,(int(c*SQUARESIZE+SQUARESIZE/2),int(r*SQUARESIZE+SQUARESIZE+SQUARESIZE/2)),RADIUS)
+ pygame.draw.rect(screen, BLUE, (c*SQUARESIZE, r *
+ SQUARESIZE+SQUARESIZE, SQUARESIZE, SQUARESIZE))
+ pygame.draw.circle(screen, BLACK, (int(
+ c*SQUARESIZE+SQUARESIZE/2), int(r*SQUARESIZE+SQUARESIZE+SQUARESIZE/2)), RADIUS)
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
- if board[r][c]==1:
- pygame.draw.circle(screen,RED,(int(c*SQUARESIZE+SQUARESIZE/2),height-int(r*SQUARESIZE+SQUARESIZE/2)),RADIUS)
+ if board[r][c] == 1:
+ pygame.draw.circle(screen, RED, (int(
+ c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS)
- elif board[r][c]==2:
- pygame.draw.circle(screen,YELLOW,(int(c*SQUARESIZE+SQUARESIZE/2),height-int(r*SQUARESIZE+SQUARESIZE/2)),RADIUS)
+ elif board[r][c] == 2:
+ pygame.draw.circle(screen, YELLOW, (int(
+ c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS)
pygame.display.update()
-board=create_board()
+board = create_board()
print_board(board)
-game_over=False
-turn=0
+game_over = False
+turn = 0
pygame.init()
-SQUARESIZE=100
+SQUARESIZE = 100
-width=COLUMN_COUNT*SQUARESIZE
-height=(ROW_COUNT+1)*SQUARESIZE
+width = COLUMN_COUNT*SQUARESIZE
+height = (ROW_COUNT+1)*SQUARESIZE
-size=(width,height)
+size = (width, height)
-RADIUS=int(SQUARESIZE/2 -5)
+RADIUS = int(SQUARESIZE/2 - 5)
pygame.display.set_caption("CONNECT FOUR GAME")
-screen=pygame.display.set_mode(size)
+screen = pygame.display.set_mode(size)
draw_board(board)
pygame.display.update()
-myfont=pygame.font.SysFont("monosoace",75)
+myfont = pygame.font.SysFont("monosoace", 75)
while not game_over:
for event in pygame.event.get():
- if event.type==pygame.QUIT:
+ if event.type == pygame.QUIT:
sys.exit()
- if event.type==pygame.MOUSEMOTION:
- pygame.draw.rect(screen,BLACK,(0,0,width,SQUARESIZE))
- posx=event.pos[0]
- if turn==0:
- pygame.draw.circle(screen,RED,(posx,int(SQUARESIZE/2)),RADIUS)
+ if event.type == pygame.MOUSEMOTION:
+ pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARESIZE))
+ posx = event.pos[0]
+ if turn == 0:
+ pygame.draw.circle(
+ screen, RED, (posx, int(SQUARESIZE/2)), RADIUS)
else:
- pygame.draw.circle(screen,YELLOW,(posx,int(SQUARESIZE/2)),RADIUS)
+ pygame.draw.circle(
+ screen, YELLOW, (posx, int(SQUARESIZE/2)), RADIUS)
pygame.display.update()
- if event.type==pygame.MOUSEBUTTONDOWN:
- #print(event.pos)
- pygame.draw.rect(screen,BLACK,(0,0,width,SQUARESIZE))
-
- if turn==0:
- posx=event.pos[0]
- col=int(math.floor(posx/SQUARESIZE))
+ if event.type == pygame.MOUSEBUTTONDOWN:
+ # print(event.pos)
+ pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARESIZE))
- if is_valid_location(board,col):
- row=get_next_open_row(board,col)
- drop_piece(board,row,col,1)
+ if turn == 0:
+ posx = event.pos[0]
+ col = int(math.floor(posx/SQUARESIZE))
+ if is_valid_location(board, col):
+ row = get_next_open_row(board, col)
+ drop_piece(board, row, col, 1)
- if winning_move(board,1):
+ if winning_move(board, 1):
#print("Player 1 wins CONGRATULATIONS!!")
- label=myfont.render("Player 1 wins!!",1,RED)
- screen.blit(label,(40,10))
- game_over=True
+ label = myfont.render("Player 1 wins!!", 1, RED)
+ screen.blit(label, (40, 10))
+ game_over = True
else:
- posx=event.pos[0]
- col=int(math.floor(posx/SQUARESIZE))
+ posx = event.pos[0]
+ col = int(math.floor(posx/SQUARESIZE))
- if is_valid_location(board,col):
- row=get_next_open_row(board,col)
- drop_piece(board,row,col,2)
+ if is_valid_location(board, col):
+ row = get_next_open_row(board, col)
+ drop_piece(board, row, col, 2)
- if winning_move(board,2):
+ if winning_move(board, 2):
#print("Player 2 wins CONGRATULATIONS!!")
- label=myfont.render("Player 2 wins!!",1,YELLOW)
- screen.blit(label,(40,10))
- game_over=True
+ label = myfont.render("Player 2 wins!!", 1, YELLOW)
+ screen.blit(label, (40, 10))
+ game_over = True
print_board(board)
draw_board(board)
- turn+=1
- turn=turn%2
+ turn += 1
+ turn = turn % 2
if game_over:
pygame.time.wait(3000)
diff --git a/Contour-Detection/live_contour_det.py b/Contour-Detection/live_contour_det.py
index f6de177c92..a354ab9842 100644
--- a/Contour-Detection/live_contour_det.py
+++ b/Contour-Detection/live_contour_det.py
@@ -9,35 +9,43 @@
cap.set(3, frameWidth)
cap.set(4, frameHeight)
+
def empty(a):
pass
+
# name of the window
cv2.namedWindow("Parameters")
# resize the window
-cv2.resizeWindow("Parameters",640,240)
+cv2.resizeWindow("Parameters", 640, 240)
-#creating trackbars
-cv2.createTrackbar("Threshold1","Parameters",23,255,empty)
-cv2.createTrackbar("Threshold2","Parameters",20,255,empty)
-cv2.createTrackbar("Area","Parameters",5000,30000,empty)
+# creating trackbars
+cv2.createTrackbar("Threshold1", "Parameters", 23, 255, empty)
+cv2.createTrackbar("Threshold2", "Parameters", 20, 255, empty)
+cv2.createTrackbar("Area", "Parameters", 5000, 30000, empty)
# function for stacking images together
-def stackImages(scale,imgArray):
+
+
+def stackImages(scale, imgArray):
rows = len(imgArray)
cols = len(imgArray[0])
rowsAvailable = isinstance(imgArray[0], list)
width = imgArray[0][0].shape[1]
height = imgArray[0][0].shape[0]
if rowsAvailable:
- for x in range ( 0, rows):
+ for x in range(0, rows):
for y in range(0, cols):
- if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:
- imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)
+ if imgArray[x][y].shape[:2] == imgArray[0][0].shape[:2]:
+ imgArray[x][y] = cv2.resize(
+ imgArray[x][y], (0, 0), None, scale, scale)
else:
- imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)
- if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)
+ imgArray[x][y] = cv2.resize(
+ imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)
+ if len(imgArray[x][y].shape) == 2:
+ imgArray[x][y] = cv2.cvtColor(
+ imgArray[x][y], cv2.COLOR_GRAY2BGR)
imageBlank = np.zeros((height, width, 3), np.uint8)
hor = [imageBlank]*rows
hor_con = [imageBlank]*rows
@@ -47,72 +55,80 @@ def stackImages(scale,imgArray):
else:
for x in range(0, rows):
if imgArray[x].shape[:2] == imgArray[0].shape[:2]:
- imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)
+ imgArray[x] = cv2.resize(
+ imgArray[x], (0, 0), None, scale, scale)
else:
- imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)
- if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
- hor= np.hstack(imgArray)
+ imgArray[x] = cv2.resize(
+ imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None, scale, scale)
+ if len(imgArray[x].shape) == 2:
+ imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
+ hor = np.hstack(imgArray)
ver = hor
return ver
-def getContours(img,imgContour):
- contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
-
+
+def getContours(img, imgContour):
+ contours, hierarchy = cv2.findContours(
+ img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
+
# detect the area of each contour and based on the area we can remove all the contours that we are not interested in
- # so in order to do that we will need a for loop
+ # so in order to do that we will need a for loop
for cnt in contours:
area = cv2.contourArea(cnt)
areaMin = cv2.getTrackbarPos("Area", "Parameters")
if area > areaMin:
cv2.drawContours(imgContour, cnt, -1, (255, 0, 255), 7)
-
+
# find the corner points, so in order to do that we need to first find the length of contours
# true basically means that the contour is closed
peri = cv2.arcLength(cnt, True)
-
- # to approximate what type of shape this is, we will use the approximation of poly method
- # we will input the contour, will give it a resolution and then we will define again that this is a closed contour
+
+ # to approximate what type of shape this is, we will use the approximation of poly method
+ # we will input the contour, will give it a resolution and then we will define again that this is a closed contour
approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
print(len(approx))
-
- # create a bounding box because we need to highlight the area of where the object is
- x , y , w, h = cv2.boundingRect(approx)
- cv2.rectangle(imgContour, (x , y ), (x + w , y + h ), (0, 255, 0), 5)
+
+ # create a bounding box because we need to highlight the area of where the object is
+ x, y, w, h = cv2.boundingRect(approx)
+ cv2.rectangle(imgContour, (x, y), (x + w, y + h), (0, 255, 0), 5)
# to display values so that we can easily see the number of points and the area detected
- cv2.putText(imgContour, "Points: " + str(len(approx)), (x + w + 20, y + 20), cv2.FONT_HERSHEY_COMPLEX, .7, (0, 255, 0), 2)
- cv2.putText(imgContour, "Area: " + str(int(area)), (x + w + 20, y + 45), cv2.FONT_HERSHEY_COMPLEX, 0.7, (0, 255, 0), 2)
+ cv2.putText(imgContour, "Points: " + str(len(approx)), (x +
+ w + 20, y + 20), cv2.FONT_HERSHEY_COMPLEX, .7, (0, 255, 0), 2)
+ cv2.putText(imgContour, "Area: " + str(int(area)), (x + w +
+ 20, y + 45), cv2.FONT_HERSHEY_COMPLEX, 0.7, (0, 255, 0), 2)
+
# reading each frame
while True:
success, img = cap.read()
imgContour = img.copy()
-
+
# converting img into blur version
imgBlur = cv2.GaussianBlur(img, (7, 7), 1)
-
+
# converting it into gray scale
imgGray = cv2.cvtColor(imgBlur, cv2.COLOR_BGR2GRAY)
-
+
# define trackbar positions
threshold1 = cv2.getTrackbarPos("Threshold1", "Parameters")
threshold2 = cv2.getTrackbarPos("Threshold2", "Parameters")
-
+
# canny edge detector
- imgCanny = cv2.Canny(imgGray,threshold1,threshold2)
-
+ imgCanny = cv2.Canny(imgGray, threshold1, threshold2)
+
# define kernel for dilation
kernel = np.ones((5, 5))
-
+
# to overcome the overlaps and noise, we use dilation function
imgDil = cv2.dilate(imgCanny, kernel, iterations=1)
- getContours(imgDil,imgContour)
-
- # stacking images together as we want images side by side instead of different window
- imgStack = stackImages(0.8,([img,imgCanny],
- [imgDil,imgContour]))
-
- # displaying it
+ getContours(imgDil, imgContour)
+
+ # stacking images together as we want images side by side instead of different window
+ imgStack = stackImages(0.8, ([img, imgCanny],
+ [imgDil, imgContour]))
+
+ # displaying it
cv2.imshow("Result", imgStack)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
diff --git a/Covid India Stats App/app.py b/Covid India Stats App/app.py
index 9e91d1394d..ae2421a704 100644
--- a/Covid India Stats App/app.py
+++ b/Covid India Stats App/app.py
@@ -30,13 +30,15 @@ def webhook_handle():
if event.get("message"): # somebody typed a message
process_message(event)
- elif event.get("postback"): # user clicked/tapped "postback" button in earlier message
+ # user clicked/tapped "postback" button in earlier message
+ elif event.get("postback"):
process_postback(event)
return 'ok'
def process_message(event):
- sender_id = event["sender"]["id"] # the facebook ID of the person sending you the message
+ # the facebook ID of the person sending you the message
+ sender_id = event["sender"]["id"]
# could receive text or attachment but not both
if "text" in event["message"]:
@@ -141,7 +143,8 @@ def create_state_list(index):
def get_stats_send(sender_id, state):
- response = json.loads(requests.get("https://api.covid19india.org/data.json").text)
+ response = json.loads(requests.get(
+ "https://api.covid19india.org/data.json").text)
list_state = response['statewise']
for i in list_state:
if i['state'] == state:
@@ -179,7 +182,8 @@ def call_send_api(message_data):
"Content-Type": "application/json"
}
- r = requests.post("https://graph.facebook.com/v5.0/me/messages", params=params, headers=headers, data=message_data)
+ r = requests.post("https://graph.facebook.com/v5.0/me/messages",
+ params=params, headers=headers, data=message_data)
if __name__ == "__main__":
diff --git a/Currency Convertor - GUI based/Currency_convertor_GUI.py b/Currency Convertor - GUI based/Currency_convertor_GUI.py
index 4bee92542d..f73b14df60 100644
--- a/Currency Convertor - GUI based/Currency_convertor_GUI.py
+++ b/Currency Convertor - GUI based/Currency_convertor_GUI.py
@@ -2,78 +2,82 @@
import tkinter as tk
from tkinter import ttk
+
def calculate_conversion():
- #URL of respective API
+ # URL of respective API
url = "https://api.exchangerate-api.com/v4/latest/INR"
-
- #Receive Data from API
+
+ # Receive Data from API
data = requests.get(url).json()
currency_rates = data['rates']
-
- #get From amount from GUI
+
+ # get From amount from GUI
amount = float(from_amount.get())
-
- #Get country code from GUI
+
+ # Get country code from GUI
fc = from_currency_code.get()
tc = to_currency_code.get()
- #Logic to convert amount to INR (if county code is not INR)
+ # Logic to convert amount to INR (if county code is not INR)
if fc != 'INR':
amount = amount/currency_rates[fc]
-
- #INR to To_country code
+
+ # INR to To_country code
amount = amount * currency_rates[tc]
- amount = round(amount,2)
+ amount = round(amount, 2)
- #Set amount to Label in GUI
- to_amount.config(text = str(amount))
+ # Set amount to Label in GUI
+ to_amount.config(text=str(amount))
if __name__ == '__main__':
- #url and data extraction
+ # url and data extraction
url = "https://api.exchangerate-api.com/v4/latest/INR"
data = requests.get(url).json()
currency_rates = data['rates']
- #Building of GUI
+ # Building of GUI
screen = tk.Tk()
screen.title("Currency convertor")
screen.geometry("500x300")
- screen.config(bg = "#282828")
+ screen.config(bg="#282828")
- #Introduction Label
- main_label = tk.Label(screen,text=" Welcome to Currency Convertor ")
- main_label.config(font = ("Lato",15,"bold"), anchor = "center" , bg = '#3500D3' , fg = 'white')
- main_label.place(x = 70,y = 10)
+ # Introduction Label
+ main_label = tk.Label(screen, text=" Welcome to Currency Convertor ")
+ main_label.config(font=("Lato", 15, "bold"),
+ anchor="center", bg='#3500D3', fg='white')
+ main_label.place(x=70, y=10)
- #from_amount input field and placing
- from_amount = tk.Entry(screen , justify = tk.CENTER)
- from_amount.place(x=58,y = 180)
+ # from_amount input field and placing
+ from_amount = tk.Entry(screen, justify=tk.CENTER)
+ from_amount.place(x=58, y=180)
- #Converted amount label and it's placing
- to_amount = tk.Label(screen, anchor = "center" , bg = 'white' , fg = 'black', width = 16, font = ("Lato",12))
- to_amount.place(x=300,y = 180)
+ # Converted amount label and it's placing
+ to_amount = tk.Label(screen, anchor="center", bg='white',
+ fg='black', width=16, font=("Lato", 12))
+ to_amount.place(x=300, y=180)
- #Variable declation for dropdown menu and set default values
+ # Variable declation for dropdown menu and set default values
from_currency_code = tk.StringVar(screen)
from_currency_code.set("INR")
to_currency_code = tk.StringVar(screen)
to_currency_code.set("INR")
- #dropdown menu for from_currency and it's placing
- from_currency_menu = ttk.Combobox(screen,textvariable = from_currency_code,values = list(currency_rates.keys()),font = ("Lato",12),state = 'readonly', width = 14, justify = tk.CENTER)
- from_currency_menu.place(x = 61,y = 110)
+ # dropdown menu for from_currency and it's placing
+ from_currency_menu = ttk.Combobox(screen, textvariable=from_currency_code, values=list(
+ currency_rates.keys()), font=("Lato", 12), state='readonly', width=14, justify=tk.CENTER)
+ from_currency_menu.place(x=61, y=110)
- #dropdown menu for to_currency and it's placing
- to_currency_menu = ttk.Combobox(screen,textvariable = to_currency_code,values = list(currency_rates.keys()),font = ("Lato",12),state = 'readonly', width = 14, justify = tk.CENTER)
- to_currency_menu.place(x = 303,y = 110)
+ # dropdown menu for to_currency and it's placing
+ to_currency_menu = ttk.Combobox(screen, textvariable=to_currency_code, values=list(
+ currency_rates.keys()), font=("Lato", 12), state='readonly', width=14, justify=tk.CENTER)
+ to_currency_menu.place(x=303, y=110)
- #Convert button and placing
- convert_btn = tk.Button(screen, text = "Convert" , fg = 'white' , bg = "#3500D3", command = calculate_conversion)
- convert_btn.place(x = 230,y = 240)
+ # Convert button and placing
+ convert_btn = tk.Button(
+ screen, text="Convert", fg='white', bg="#3500D3", command=calculate_conversion)
+ convert_btn.place(x=230, y=240)
screen.mainloop()
-
-
diff --git a/Data-Visualization/BarChart/bar_chart.py b/Data-Visualization/BarChart/bar_chart.py
index f5aa3738e2..27928fe88e 100644
--- a/Data-Visualization/BarChart/bar_chart.py
+++ b/Data-Visualization/BarChart/bar_chart.py
@@ -7,35 +7,34 @@
size = 7
x = [f'Product {i}' for i in range(size)]
-y = np.random.randint(low = 0, high = 100, size=size)
+y = np.random.randint(low=0, high=100, size=size)
# creating the Bar Chart
-fig = go.Figure(go.Bar(
- x = x,
- y = y,
- text = y,
- textposition='outside',
- marker_color='indianred',
- hovertemplate = "%{x} : %{y} ",
- showlegend = False,
- ))
+fig = go.Figure(go.Bar(
+ x=x,
+ y=y,
+ text=y,
+ textposition='outside',
+ marker_color='indianred',
+ hovertemplate="%{x} : %{y} ",
+ showlegend=False,
+))
# Modifying the tickangle of the xaxis, and adjusting width and height of the image
fig.layout.template = 'plotly_dark'
-#Hiding y-axis labels
+# Hiding y-axis labels
layout_yaxis_visible = False
layout_yaxis_showticklabels = False
fig.update_layout(
- xaxis_title = 'X Axis Title',
- yaxis_title = 'Y Axis Title',
- xaxis_tickangle = -45,
- autosize=False,
- width=600,
- height=600,
- margin=dict(l=50, r=50, b=100, t=100, pad=4)
- )
+ xaxis_title='X Axis Title',
+ yaxis_title='Y Axis Title',
+ xaxis_tickangle=-45,
+ autosize=False,
+ width=600,
+ height=600,
+ margin=dict(l=50, r=50, b=100, t=100, pad=4)
+)
# Removing the background grid and the Y-axis labels
-fig.update_yaxes(showgrid = False, showticklabels = False)
+fig.update_yaxes(showgrid=False, showticklabels=False)
fig.show()
-
diff --git a/Data-Visualization/BubbleChart/bubble_chart.py b/Data-Visualization/BubbleChart/bubble_chart.py
index 70d9d5a969..f025283e61 100644
--- a/Data-Visualization/BubbleChart/bubble_chart.py
+++ b/Data-Visualization/BubbleChart/bubble_chart.py
@@ -5,14 +5,14 @@
# declaring size of arr
size = 10
-size_arr = np.random.randint(low = 50, high = 600, size=size)
+size_arr = np.random.randint(low=50, high=600, size=size)
-x = np.random.randint(low = 0, high = 30, size=size)
-y = np.random.randint(low = 0, high = 20, size=size)
+x = np.random.randint(low=0, high=30, size=size)
+y = np.random.randint(low=0, high=20, size=size)
fig = go.Figure(data=[go.Scatter(
- x = x,
- y = y,
+ x=x,
+ y=y,
mode='markers',
marker=dict(
size=size_arr,
@@ -20,20 +20,20 @@
sizeref=2.*max(size_arr)/(40.**2),
sizemin=4
),
- hovertemplate = " x : %{x}
y : %{y}
"
+ hovertemplate=" x : %{x}
y : %{y}
"
)])
# Adjusting width and height of the image
fig.layout.template = 'plotly_dark'
fig.update_layout(
- title = 'Bubble Chart',
- xaxis_title = 'X Axis Title',
- yaxis_title = 'Y Axis Title',
- autosize=False,
- width=600,
- height=600,
- margin=dict(l=50, r=50, b=100, t=100, pad=4)
- )
+ title='Bubble Chart',
+ xaxis_title='X Axis Title',
+ yaxis_title='Y Axis Title',
+ autosize=False,
+ width=600,
+ height=600,
+ margin=dict(l=50, r=50, b=100, t=100, pad=4)
+)
-fig.show()
\ No newline at end of file
+fig.show()
diff --git a/Data-Visualization/HeatMap/heat_maps.py b/Data-Visualization/HeatMap/heat_maps.py
index dd83aa80ff..4e739ce017 100644
--- a/Data-Visualization/HeatMap/heat_maps.py
+++ b/Data-Visualization/HeatMap/heat_maps.py
@@ -7,23 +7,24 @@
rows = 5
columns = 3
-data = np.random.randint(low = 0, high = 50, size=(columns, rows))
+data = np.random.randint(low=0, high=50, size=(columns, rows))
fig = px.imshow(data,
- labels=dict(x="X Axis Title", y="Y Axis Title", color="Productivity"),
+ labels=dict(x="X Axis Title", y="Y Axis Title",
+ color="Productivity"),
x=[f'Product {i}' for i in range(rows)],
- y=[f'Type {i}' for i in range(columns)],
- )
+ y=[f'Type {i}' for i in range(columns)],
+ )
# Modifying the tickangle of the xaxis, and adjusting width and height of the image
fig.layout.template = 'plotly_dark'
fig.update_xaxes(side="top")
fig.update_layout(
- title = 'Heat Map ',
- xaxis_tickangle = -45,
- autosize=False,
- width=600,
- height=600,
- margin=dict(l=50, r=50, b=100, t=100, pad=4)
- )
-fig.show()
\ No newline at end of file
+ title='Heat Map ',
+ xaxis_tickangle=-45,
+ autosize=False,
+ width=600,
+ height=600,
+ margin=dict(l=50, r=50, b=100, t=100, pad=4)
+)
+fig.show()
diff --git a/Data-Visualization/HistogramPlot/histogram.py b/Data-Visualization/HistogramPlot/histogram.py
index 2c001506aa..8d4a2a29af 100644
--- a/Data-Visualization/HistogramPlot/histogram.py
+++ b/Data-Visualization/HistogramPlot/histogram.py
@@ -6,18 +6,18 @@
# declaring size of arr
size = 50
-data = np.random.randint(low = 0, high = 150, size=size)
+data = np.random.randint(low=0, high=150, size=size)
# create the bins
-fig = px.histogram(x = data, labels={'x': 'data', 'y':'count'})
+fig = px.histogram(x=data, labels={'x': 'data', 'y': 'count'})
fig.layout.template = 'plotly_dark'
fig.update_layout(
- title = 'Histogram',
- xaxis_title = 'X Axis Title',
- yaxis_title = 'Y Axis Title',
- autosize=False,
- width=600,
- height=600,
- margin=dict(l=50, r=50, b=100, t=100, pad=4)
- )
-fig.show()
\ No newline at end of file
+ title='Histogram',
+ xaxis_title='X Axis Title',
+ yaxis_title='Y Axis Title',
+ autosize=False,
+ width=600,
+ height=600,
+ margin=dict(l=50, r=50, b=100, t=100, pad=4)
+)
+fig.show()
diff --git a/Data-Visualization/LineChart/line_chart.py b/Data-Visualization/LineChart/line_chart.py
index 438e33f399..1b6020d682 100644
--- a/Data-Visualization/LineChart/line_chart.py
+++ b/Data-Visualization/LineChart/line_chart.py
@@ -14,13 +14,13 @@
# Modifying the tickangle of the xaxis, and adjusting width and height of the image
fig.layout.template = 'plotly_dark'
fig.update_layout(
- title = 'Line Chart',
- xaxis_title = 'X Axis Title',
- yaxis_title = 'Y Axis Title',
- xaxis_tickangle = -45,
- autosize=False,
- width=600,
- height=600,
- margin=dict(l=50, r=50, b=100, t=100, pad=4)
- )
-fig.show()
\ No newline at end of file
+ title='Line Chart',
+ xaxis_title='X Axis Title',
+ yaxis_title='Y Axis Title',
+ xaxis_tickangle=-45,
+ autosize=False,
+ width=600,
+ height=600,
+ margin=dict(l=50, r=50, b=100, t=100, pad=4)
+)
+fig.show()
diff --git a/Data-Visualization/PieChart/pie_chart.py b/Data-Visualization/PieChart/pie_chart.py
index f61fd949e3..42f226fa2d 100644
--- a/Data-Visualization/PieChart/pie_chart.py
+++ b/Data-Visualization/PieChart/pie_chart.py
@@ -7,7 +7,7 @@
size = 7
x = [f'Product {i}' for i in range(size)]
-y = np.random.randint(low = 0, high = 100, size=size)
+y = np.random.randint(low=0, high=100, size=size)
# creating a Pie Chart
fig = go.Figure(data=[go.Pie(labels=x, values=y)])
@@ -15,15 +15,14 @@
# Adjusting width and height of the image
fig.layout.template = 'plotly_dark'
# To display labels with the percentage
-fig.update_traces(textposition = 'inside', textinfo = 'percent+label')
+fig.update_traces(textposition='inside', textinfo='percent+label')
fig.update_layout(
- title = 'Pie Chart',
- xaxis_title = 'X Axis Title',
- yaxis_title = 'Y Axis Title',
- autosize=False,
- width=600,
- height=600,
- margin=dict(l=50, r=50, b=100, t=100, pad=4)
- )
+ title='Pie Chart',
+ xaxis_title='X Axis Title',
+ yaxis_title='Y Axis Title',
+ autosize=False,
+ width=600,
+ height=600,
+ margin=dict(l=50, r=50, b=100, t=100, pad=4)
+)
fig.show()
-
diff --git a/Data-Visualization/ScatterPlot/scatter_plot.py b/Data-Visualization/ScatterPlot/scatter_plot.py
index 7de06f71c2..c504653ddf 100644
--- a/Data-Visualization/ScatterPlot/scatter_plot.py
+++ b/Data-Visualization/ScatterPlot/scatter_plot.py
@@ -6,20 +6,20 @@
# declaring size of arr
size = 100
-x = np.random.randint(low = 0, high = 100, size=size)
-y = np.random.randint(low = 0, high = 100, size=size)
+x = np.random.randint(low=0, high=100, size=size)
+y = np.random.randint(low=0, high=100, size=size)
fig = px.scatter(x=x, y=y)
# Adjusting width and height of the image
fig.layout.template = 'plotly_dark'
fig.update_layout(
- title = 'Scatter Plot',
- xaxis_title = 'X Axis Title',
- yaxis_title = 'Y Axis Title',
- autosize=False,
- width=600,
- height=600,
- margin=dict(l=50, r=50, b=100, t=100, pad=4)
- )
-fig.show()
\ No newline at end of file
+ title='Scatter Plot',
+ xaxis_title='X Axis Title',
+ yaxis_title='Y Axis Title',
+ autosize=False,
+ width=600,
+ height=600,
+ margin=dict(l=50, r=50, b=100, t=100, pad=4)
+)
+fig.show()
diff --git a/Desktop News Notifier/script.py b/Desktop News Notifier/script.py
index 2cd1c8a443..a485b4d081 100644
--- a/Desktop News Notifier/script.py
+++ b/Desktop News Notifier/script.py
@@ -6,19 +6,16 @@
country_code = input("Enter the country code for the news: ")
api_key = input("Enter the api key: ")
-news = requests.get(f'https://newsapi.org/v2/top-headlines?country={country_code}&apiKey={api_key}')
+news = requests.get(
+ f'https://newsapi.org/v2/top-headlines?country={country_code}&apiKey={api_key}')
data = json.loads(news.content)
for i in range(10):
notification.notify(
- title = data['articles'][i]['title'][:20],
- message= data['articles'][i]['description'][:44] ,
- # displaying time
- timeout=5 ,
- toast=False)
-
-
-
-
+ title=data['articles'][i]['title'][:20],
+ message=data['articles'][i]['description'][:44],
+ # displaying time
+ timeout=5,
+ toast=False)
diff --git a/Desktop-Voice-assistant/voice_assistant.py b/Desktop-Voice-assistant/voice_assistant.py
index 736596bc6d..7d18ce4e01 100644
--- a/Desktop-Voice-assistant/voice_assistant.py
+++ b/Desktop-Voice-assistant/voice_assistant.py
@@ -13,68 +13,75 @@
print("Your Assistant is starting......")
engine = pyttsx3.init('sapi5')
-voices= engine.getProperty('voices')
+voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
engine.setProperty('rate', 190)
-Master=input("Enter your name: ") # when you start using the assistant enter your name here
+# when you start using the assistant enter your name here
+Master = input("Enter your name: ")
+
def speak(audio):
engine.say(audio)
engine.runAndWait()
-
+
+
def wish_user():
- hour= int(datetime.datetime.now().hour)
- if hour>=0 and hour<12:
+ hour = int(datetime.datetime.now().hour)
+ if hour >= 0 and hour < 12:
speak("Good Morning!" + Master)
-
- elif hour>=12 and hour<16:
+
+ elif hour >= 12 and hour < 16:
speak("Good Afternoon!" + Master)
-
+
else:
speak("Good Evening" + Master)
-
+
speak("I am your Desktop-Assistant! How may I help you?")
-
+
+
def user_command():
# takes microphone command and converts to string
-
- r= sr.Recognizer()
+
+ r = sr.Recognizer()
with sr.Microphone() as source:
print("I am listening....")
- r.pause_threshold=1
- audio=r.listen(source)
-
+ r.pause_threshold = 1
+ audio = r.listen(source)
+
try:
print("Recognising.....")
- query=r.recognize_google(audio,language='en-in')
+ query = r.recognize_google(audio, language='en-in')
print(f"User said: {query}\n")
-
+
except Exception as e:
print("I am sorry I don't understand, Say that again please...")
return "None"
return query
+
def mailSent(to, content):
- server=smtplib.SMTP('smtp.gmail.com', 587)
+ server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
- server.login('your email', 'your app password') # when you start working with the assistant, save this on your device
- #check READme.md for creating an app password
- server.sendmail('Your email',to,content)
-
+ # when you start working with the assistant, save this on your device
+ server.login('your email', 'your app password')
+ # check READme.md for creating an app password
+ server.sendmail('Your email', to, content)
+
server.close()
-
-if __name__=='__main__':
+
+
+if __name__ == '__main__':
wish_user()
while True:
- query= user_command().lower()
+ query = user_command().lower()
if 'wikipedia' in query:
speak('Give me sometime I am looking into Wikipedia')
- query= query.replace("wikipedia","")
- results= wikipedia.summary(query, sentences=5)
+ query = query.replace("wikipedia", "")
+ results = wikipedia.summary(query, sentences=5)
speak("This is what I found!")
speak(results)
@@ -89,50 +96,48 @@ def mailSent(to, content):
# you can use API as well, with the help of spotipy module
elif 'time' in query:
- time= datetime.datetime.now().strftime("%H:%M")
+ time = datetime.datetime.now().strftime("%H:%M")
speak(f"Its {time} now")
elif 'date today' in query:
- date=datetime.datetime.today()
+ date = datetime.datetime.today()
speak(f"Today is {date}")
elif 'send email' in query:
try:
speak("please tell me the content of the email")
- content=user_command()
+ content = user_command()
speak(content)
- to=input()
+ to = input()
speak(to)
mailSent(to, content)
speak(f"successfully sent the email to {to}")
except Exception as e:
print(e)
speak("sorry! i was unable to send the mail")
-
- elif 'send whatsapp message' in query: #you should be logged in into whatsapp web for this
+
+ elif 'send whatsapp message' in query: # you should be logged in into whatsapp web for this
speak("To whom should I send the message?")
- number=int(input())
+ number = int(input())
speak("Tell me the message please")
- message=user_command()
+ message = user_command()
speak("At what time should I send?")
speak("At what time? (24 hours system)")
- hr=int(input("Hours: "))
- mins=int(input("Minutes: "))
- kit.sendwhatmsg(number,message,hr,mins)
- # this should be in the format ("+91xxxxxxxxxx","This is message", 15, 20)
-
+ hr = int(input("Hours: "))
+ mins = int(input("Minutes: "))
+ kit.sendwhatmsg(number, message, hr, mins)
+ # this should be in the format ("+91xxxxxxxxxx","This is message", 15, 20)
+
elif 'open facebook' in query:
webbrowser.open("facebook.com")
-
+
elif 'make me laugh' in query:
- joke=pyjokes.get_joke()
+ joke = pyjokes.get_joke()
speak(joke)
-
+
elif 'no thanks' in query:
speak("thanks for using me! Have a good day")
sys.exit()
-
+
time.sleep(5)
speak("do you have any other work?")
-
-
diff --git a/Desktop-drinkWater-Notification/main.py b/Desktop-drinkWater-Notification/main.py
index 875e89a556..4e0ffa4e2c 100644
--- a/Desktop-drinkWater-Notification/main.py
+++ b/Desktop-drinkWater-Notification/main.py
@@ -6,7 +6,7 @@
notification.notify(
title="Please Drink Water",
message="The U.S. National Academies of Sciences, Engineering, and Medicine determined that an adequate daily fluid intake is: About 15.5 cups (3.7 liters) of fluids a day for men. About 11.5 cups (2.7 liters) of fluids a day for women.",
- app_icon = "./Desktop-drinkWater-Notification/icon.ico",
- timeout = 12
+ app_icon="./Desktop-drinkWater-Notification/icon.ico",
+ timeout=12
)
- time.sleep(1800)
\ No newline at end of file
+ time.sleep(1800)
diff --git a/Dev.to Scraper/scraper.py b/Dev.to Scraper/scraper.py
index a8316f4069..ab9abf0d0b 100644
--- a/Dev.to Scraper/scraper.py
+++ b/Dev.to Scraper/scraper.py
@@ -4,7 +4,7 @@
from selenium.webdriver.common.keys import Keys
import time
from fpdf import FPDF
-
+
# Get input for category and number of articles
category = input("Enter category: ")
number_articles = int(input("Enter number of articles: "))
@@ -13,71 +13,79 @@
url = 'https://dev.to/search?q={}'.format(category)
# initiating the webdriver. Parameter includes the path of the webdriver.
-driver = webdriver.Chrome(driver_path)
-driver.get(url)
-
+driver = webdriver.Chrome(driver_path)
+driver.get(url)
+
# this is just to ensure that the page is loaded
-time.sleep(5)
+time.sleep(5)
html = driver.page_source
# Now apply bs4 to html variable
soup = BeautifulSoup(html, "html.parser")
-results_div = soup.find('div', {'id' : 'substories'})
+results_div = soup.find('div', {'id': 'substories'})
articles = results_div.find_all('article')
-
+
# Getting articles from dev.to
count = 0
-for article in articles :
- article_data=article.find('a',class_='crayons-story__hidden-navigation-link')['href']
+for article in articles:
+ article_data = article.find(
+ 'a', class_='crayons-story__hidden-navigation-link')['href']
- post_url="https://dev.to{}".format(article_data)
- driver.get(post_url)
+ post_url = "https://dev.to{}".format(article_data)
+ driver.get(post_url)
time.sleep(5)
- post_html=driver.page_source
+ post_html = driver.page_source
soup = BeautifulSoup(post_html, "html.parser")
- article_div = soup.find('div', {'class' : 'article-wrapper'})
- article_content=article_div.find('article', {'id' : 'article-show-container'})
+ article_div = soup.find('div', {'class': 'article-wrapper'})
+ article_content = article_div.find(
+ 'article', {'id': 'article-show-container'})
# Title of post found
- header_tag = article_content.find('header',class_='crayons-article__header')
- title_div = header_tag.find('div',class_='crayons-article__header__meta')
+ header_tag = article_content.find(
+ 'header', class_='crayons-article__header')
+ title_div = header_tag.find('div', class_='crayons-article__header__meta')
title_content = title_div.find('h1')
-
+
# Author of post found
- author_tag = title_div.find('div',class_='crayons-article__subheader')
- author_name = author_tag.find('a',class_='crayons-link')
+ author_tag = title_div.find('div', class_='crayons-article__subheader')
+ author_name = author_tag.find('a', class_='crayons-link')
# Post content found
- article_content_div = article_content.find('div',class_='crayons-article__main')
- article_content_body = article_content_div.find('div',class_='crayons-article__body')
- p_tags = article_content_body.find_all('p')
+ article_content_div = article_content.find(
+ 'div', class_='crayons-article__main')
+ article_content_body = article_content_div.find(
+ 'div', class_='crayons-article__body')
+ p_tags = article_content_body.find_all('p')
- title_string = (title_content.text.strip()).encode('latin-1', 'replace').decode('latin-1')
- author_string = ("By - {}".format(author_name.text.strip())).encode('latin-1', 'replace').decode('latin-1')
+ title_string = (title_content.text.strip()).encode(
+ 'latin-1', 'replace').decode('latin-1')
+ author_string = ("By - {}".format(author_name.text.strip())
+ ).encode('latin-1', 'replace').decode('latin-1')
# Add a page
pdf = FPDF()
pdf.add_page()
- # set style and size of font
- pdf.set_font("Arial", size = 12)
-
+ # set style and size of font
+ pdf.set_font("Arial", size=12)
+
# Title cell
- pdf.cell(200, 5, txt = title_string,ln = 1, align = 'C')
+ pdf.cell(200, 5, txt=title_string, ln=1, align='C')
# Author cell
- pdf.cell(200, 10, txt = author_string,ln = 2, align = 'C')
+ pdf.cell(200, 10, txt=author_string, ln=2, align='C')
for p_tag in p_tags:
- article_part = (p_tag.text.strip()).encode('latin-1', 'replace').decode('latin-1')
+ article_part = (p_tag.text.strip()).encode(
+ 'latin-1', 'replace').decode('latin-1')
# Add part of article to pdf
- pdf.multi_cell(0, 5, txt = article_part, align = 'L')
-
+ pdf.multi_cell(0, 5, txt=article_part, align='L')
+
# save the pdf with name .pdf
pdf_title = ''.join(e for e in title_string if e.isalnum())
pdf.output("{}.pdf".format(pdf_title))
count = count + 1
- if(count == number_articles) :
+ if(count == number_articles):
break
-
-driver.close() # closing the webdriver
\ No newline at end of file
+
+driver.close() # closing the webdriver
diff --git a/Dice-Roll-Simulator/dice_roll_simulator.py b/Dice-Roll-Simulator/dice_roll_simulator.py
index b44c2f68de..3d6e3528e5 100644
--- a/Dice-Roll-Simulator/dice_roll_simulator.py
+++ b/Dice-Roll-Simulator/dice_roll_simulator.py
@@ -12,13 +12,14 @@
l0.pack()
# adding label with different font and formatting
-l1 = tkinter.Label(root, text="Dice Rolling Simulator", fg = "white",
- bg = "black",
- font = "Helvetica 16 bold italic")
+l1 = tkinter.Label(root, text="Dice Rolling Simulator", fg="white",
+ bg="black",
+ font="Helvetica 16 bold italic")
l1.pack()
# images
-dice = ['./Dice-Roll-Simulator/imgs/die1.png', './Dice-Roll-Simulator/imgs/die2.png', './Dice-Roll-Simulator/imgs/die3.png', './Dice-Roll-Simulator/imgs/die4.png', './Dice-Roll-Simulator/imgs/die5.png', './Dice-Roll-Simulator/imgs/die6.png']
+dice = ['./Dice-Roll-Simulator/imgs/die1.png', './Dice-Roll-Simulator/imgs/die2.png', './Dice-Roll-Simulator/imgs/die3.png',
+ './Dice-Roll-Simulator/imgs/die4.png', './Dice-Roll-Simulator/imgs/die5.png', './Dice-Roll-Simulator/imgs/die6.png']
# simulating the dice with random numbers between 0 to 6 and generating image
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
@@ -27,9 +28,11 @@
label1.image = image1
# packing a widget in the parent widget
-label1.pack( expand=True)
+label1.pack(expand=True)
# function activated by button
+
+
def rolling_dice():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
# update image
@@ -39,10 +42,11 @@ def rolling_dice():
# adding button, and command will use rolling_dice function
-button = tkinter.Button(root, text='Click here to Roll the Dice', fg='blue', command=rolling_dice)
+button = tkinter.Button(
+ root, text='Click here to Roll the Dice', fg='blue', command=rolling_dice)
# pack a widget in the parent widget
-button.pack( expand=True)
+button.pack(expand=True)
# call the mainloop of Tk
# keeps window open
diff --git a/Dictionary-GUI/dictionary.py b/Dictionary-GUI/dictionary.py
index dbd49d8657..aa21189e17 100644
--- a/Dictionary-GUI/dictionary.py
+++ b/Dictionary-GUI/dictionary.py
@@ -10,25 +10,28 @@
# Initialize dictionary objecy
dictionary = PyDictionary()
+
def getMeaning():
- response=dictionary.meaning(word.get())
+ response = dictionary.meaning(word.get())
if(response):
if('Noun' in response):
- meaning=response['Noun'][0]
+ meaning = response['Noun'][0]
elif('Verb' in response):
- meaning=response['Verb'][0]
+ meaning = response['Verb'][0]
elif('Adjective' in response):
- meaning=response['Adjective'][0]
+ meaning = response['Adjective'][0]
else:
- meaning="Invalid word"
+ meaning = "Invalid word"
else:
- messagebox.showinfo("Error","Please add a Noun, Pronoun, verb or a valid word.")
+ messagebox.showinfo(
+ "Error", "Please add a Noun, Pronoun, verb or a valid word.")
# Show meaning in frame
meaning_label.config(text=meaning)
# Heading Label
-heading_label = Label(root, text = "DICTIONARY", font=("Helvetica 35 bold"),foreground='Blue')
+heading_label = Label(root, text="DICTIONARY", font=(
+ "Helvetica 35 bold"), foreground='Blue')
heading_label.config(anchor=CENTER)
heading_label.pack(pady=10)
@@ -39,7 +42,8 @@ def getMeaning():
word.pack(padx=10)
frame.pack()
-search_button=Button(root, text="Search Word",font=("Helvetica 15 bold"),relief=RIDGE,borderwidth=3,cursor="hand2",foreground='Green', command=getMeaning)
+search_button = Button(root, text="Search Word", font=("Helvetica 15 bold"), relief=RIDGE,
+ borderwidth=3, cursor="hand2", foreground='Green', command=getMeaning)
search_button.config(anchor=CENTER)
search_button.pack(pady=10)
diff --git a/Digital Clock/Clock.py b/Digital Clock/Clock.py
index da49a7d978..d3a29806b6 100644
--- a/Digital Clock/Clock.py
+++ b/Digital Clock/Clock.py
@@ -6,12 +6,15 @@
root = Tk()
root.title = ("Clock")
+
def time():
string = strftime('%I:%M:%S %p')
label.config(text=string)
- label.after(1000,time)
+ label.after(1000, time)
+
-label = Label(root, font=("ds-digital", 80), background = "black", foreground = "cyan" )
+label = Label(root, font=("ds-digital", 80),
+ background="black", foreground="cyan")
label.pack(anchor='center')
time()
diff --git a/Directory Tree Generator/tree.py b/Directory Tree Generator/tree.py
index f5bcbfbd8f..bfcae6e86c 100644
--- a/Directory Tree Generator/tree.py
+++ b/Directory Tree Generator/tree.py
@@ -1,40 +1,44 @@
-#Directory Tree Generator
+# Directory Tree Generator
import os
import argparse
+
def realname(path, root=None):
if root is not None:
- path=os.path.join(root, path)
- result=os.path.basename(path)
+ path = os.path.join(root, path)
+ result = os.path.basename(path)
if os.path.islink(path):
- realpath=os.readlink(path)
- result= '%s -> %s' % (os.path.basename(path), realpath)
+ realpath = os.readlink(path)
+ result = '%s -> %s' % (os.path.basename(path), realpath)
return result
+
def ptree(startpath, depth=-1):
- prefix=0
- assert os.path.isdir(startpath),"Directory not valid"
+ prefix = 0
+ assert os.path.isdir(startpath), "Directory not valid"
if startpath != '/':
- if startpath.endswith('/'): startpath=startpath[:-1]
- prefix=len(startpath)
+ if startpath.endswith('/'):
+ startpath = startpath[:-1]
+ prefix = len(startpath)
for root, dirs, files in os.walk(startpath):
level = root[prefix:].count(os.sep)
- if depth >-1 and level > depth: continue
- indent=subindent =''
+ if depth > -1 and level > depth:
+ continue
+ indent = subindent = ''
if level > 0:
indent = '| ' * (level-1) + '|-- '
subindent = '| ' * (level) + '|-- '
print('{}{}/'.format(indent, realname(root)))
-
+
for d in dirs:
if os.path.islink(os.path.join(root, d)):
print('{}{}'.format(subindent, realname(d, root=root)))
for f in files:
print('{}{}'.format(subindent, realname(f, root=root)))
+
if __name__ == '__main__':
-
print("\nDirectory tree \n")
@@ -42,7 +46,7 @@ def ptree(startpath, depth=-1):
parser.add_argument('startpath', type=str,
help='path to stating directory')
args = parser.parse_args()
- argsd=vars(args)
+ argsd = vars(args)
ptree(**argsd)
-
- input("\n\nPress enter to exit")
\ No newline at end of file
+
+ input("\n\nPress enter to exit")
diff --git a/Distance Conversion GUI/distance_conversion.py b/Distance Conversion GUI/distance_conversion.py
index 4f65d1fe20..4911f5b82c 100644
--- a/Distance Conversion GUI/distance_conversion.py
+++ b/Distance Conversion GUI/distance_conversion.py
@@ -2,21 +2,21 @@
from tkinter import *
from tkinter import messagebox
-#main window
+# main window
root = tk.Tk()
-#window size (width x height)
+# window size (width x height)
root.geometry("600x350")
-#title of window
+# title of window
root.title("Distance Unit Converter")
-#disabling resizing of window
+# disabling resizing of window
root.resizable(0, 0)
-#background colour of window
+# background colour of window
root['bg'] = 'skyblue'
-#conversion factors
+# conversion factors
conv_factors = {
- "cm" : 0.01,
- "m" : 1.0,
+ "cm": 0.01,
+ "m": 1.0,
"km": 1000.0,
"feet": 0.3048,
"miles": 1609.344,
@@ -24,54 +24,61 @@
"yards": 0.9144
}
-#function to convert from one unit to other
+# function to convert from one unit to other
+
+
def convert():
ip = float(input.get())
ip_unit = ip_opt.get()
op_unit = op_opt.get()
- #if user chooses same input & output unit then display warning
- if(ip_unit==op_unit):
- messagebox.showwarning("Warning","Select different units")
- #else perform conversion
+ # if user chooses same input & output unit then display warning
+ if(ip_unit == op_unit):
+ messagebox.showwarning("Warning", "Select different units")
+ # else perform conversion
else:
output.delete(0, END)
ans = ip*(conv_factors[ip_unit]/conv_factors[op_unit])
output.insert(0, round(ans, 4))
-#menu default text
+
+# menu default text
ip_opt = StringVar()
ip_opt.set("Select Unit")
op_opt = StringVar()
op_opt.set("Select Unit")
-#Adding Widgets
-greeting = Label(text="Welcome to Distance Unit Converter !!", bg="lavender", width=40, height=2, bd=2, relief="ridge", font = ("Lucida Console", 10, "italic"))
-greeting.grid(row = 0, column = 1, pady=20, padx=12)
+# Adding Widgets
+greeting = Label(text="Welcome to Distance Unit Converter !!", bg="lavender",
+ width=40, height=2, bd=2, relief="ridge", font=("Lucida Console", 10, "italic"))
+greeting.grid(row=0, column=1, pady=20, padx=12)
-#---input row---
-fromlabel = Label(root, text="From", width=10, height = 2)
-fromlabel.grid(row = 2, column = 0, padx = 20, pady=20)
+# ---input row---
+fromlabel = Label(root, text="From", width=10, height=2)
+fromlabel.grid(row=2, column=0, padx=20, pady=20)
input = Entry(root, justify="center")
-input.grid(row =2, column = 1, ipady=8)
-input.config(font = 8)
+input.grid(row=2, column=1, ipady=8)
+input.config(font=8)
-ipmenu = OptionMenu(root, ip_opt, "cm", "m", "km", "feet", "miles", "inches", "yards")
-ipmenu.grid(row = 2, column = 2)
+ipmenu = OptionMenu(root, ip_opt, "cm", "m", "km",
+ "feet", "miles", "inches", "yards")
+ipmenu.grid(row=2, column=2)
-#---output row---
-tolabel = Label(root, text="To", width=10, height = 2)
-tolabel.grid(row = 4, column = 0, padx = 20, pady=20)
+# ---output row---
+tolabel = Label(root, text="To", width=10, height=2)
+tolabel.grid(row=4, column=0, padx=20, pady=20)
output = Entry(root, justify="center")
-output.grid(row =4, column = 1, ipady=8)
-output.config(font = 8)
+output.grid(row=4, column=1, ipady=8)
+output.config(font=8)
-opmenu = OptionMenu(root, op_opt, "cm", "m", "km", "feet", "miles", "inches", "yards")
-opmenu.grid(row = 4, column = 2)
+opmenu = OptionMenu(root, op_opt, "cm", "m", "km",
+ "feet", "miles", "inches", "yards")
+opmenu.grid(row=4, column=2)
-#---convert Button---
-convertbtn = Button(root, text="Convert", justify="center", width=10, height = 2, command = convert, bg="lavender", font=("bold", 12))
-convertbtn.grid(row = 6, column = 1)
+# ---convert Button---
+convertbtn = Button(root, text="Convert", justify="center", width=10,
+ height=2, command=convert, bg="lavender", font=("bold", 12))
+convertbtn.grid(row=6, column=1)
root.mainloop()
diff --git a/DownTube-Youtube-Downloader/DownTube.py b/DownTube-Youtube-Downloader/DownTube.py
index dd11ecdb58..c398d4d50c 100644
--- a/DownTube-Youtube-Downloader/DownTube.py
+++ b/DownTube-Youtube-Downloader/DownTube.py
@@ -1,6 +1,6 @@
-#DownTube is a Youtube Video/Audio downloader script written by XZANATOL
-#https://www.github.com/XZANATOL
-#source code can be found on https://github.com/avinashkranjan/Amazing-Python-Scripts
+# DownTube is a Youtube Video/Audio downloader script written by XZANATOL
+# https://www.github.com/XZANATOL
+# source code can be found on https://github.com/avinashkranjan/Amazing-Python-Scripts
from pytube.cli import on_progress
from pytube import YouTube, Playlist
from optparse import OptionParser
@@ -8,7 +8,7 @@
import os
import re
-#Help menu
+# Help menu
usage = """