From 743ad7bbc7f364b67871d29ffaa3b22c5a113c6a Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Fri, 21 Jul 2023 08:37:42 +0000 Subject: [PATCH] style: format code with autopep8 Format code with autopep8 This commit fixes the style issues introduced in 9ba8bac according to the output from Autopep8. Details: https://app.deepsource.com/gh/avinashkranjan/Amazing-Python-Scripts/transform/4d390bc4-407f-470f-8d11-c3519be94a4e/ --- .../9_Types_of_Hash_Cracker.py | 50 +- AI Calculator/main.py | 14 +- AI Chat Bot/main.py | 20 +- AI TicTacToe/src/TicTacToe.py | 2 + Address-Book/addressbook.py | 123 ++- Age-Calculator-GUI/age_calc_gui.py | 2 - Age_Calculator/Age_Calculator.py | 22 +- All_GitHub_Repos/all_github_repos.py | 2 +- Amazon-Price-Tracker/amazonprice.py | 3 +- Amazon-Price-Tracker/tempCodeRunnerFile.py | 2 +- .../Applying Bitwise operations.py | 15 +- .../arbitary_quotes_generator.py | 5 +- Audio Splitting/audio-split.py | 45 +- Audio to Text Convertor/code.py | 15 +- Auto Birthday Wisher/Auto B'Day Wisher.py | 2 +- Automated_scraper.py/script.py | 7 +- Autonomous-Taxi-Agent/Autonomous TaxiAgent.py | 88 +-- Background-Payload-Runner/run-payload.py | 36 +- Bandwidth-Monitor/bandwidth_py3.py | 2 +- Base-N_Calc/script.py | 87 ++- Battery-Notification/Battery-Notification.py | 4 +- Beat-Board/beatBoard.py | 21 +- Binary-Calculator-GUI/script.py | 42 +- Birthday Wisher Bot/main.py | 31 +- .../Blood_Alcohol_Content.py | 29 +- Blur an Image/BlurImage.py | 41 +- Book_Scraper/book.py | 46 +- Bubble Shooter Game/bubbleshooter.py | 40 +- Bubble-Sort-Visualization/bubble_sort.py | 2 +- CPU temperature/temp.py | 23 +- CSV-To-Excel/CSV-To-Excel.py | 26 +- CSVtoJSON script/CSVtoJSON.py | 6 +- .../Changing_Wall_Paper.py | 36 +- Check_External_IP/Check_IP.py | 2 +- Chess-Game/main.py | 66 +- .../License-plate-recognition/CNN.py | 27 +- .../License-plate-recognition/UI.py | 103 ++- .../License-plate-recognition/Unet.py | 35 +- .../License-plate-recognition/core.py | 43 +- .../License-plate-recognition/train.py | 4 +- .../Clean_Up_Photo_Directory.py | 34 +- Codechef Scrapper/codechef.py | 2 +- .../Codeforces_problem_scrapper.py | 30 +- Codes on Turtle Graphics/DrawSpirograph.py | 3 +- Codes on Turtle Graphics/RandomColorWalk.py | 3 +- .../coffee-machine-py-game.py | 3 +- .../connect4withMiniMax.py | 420 +++++----- Connect-4 game/Connect-4.py | 4 +- Cookie_Clicker/main.py | 41 +- Coursera Scraper/courses.py | 75 +- Covid -19-Detection-Using-Chest-X-Ray/test.py | 14 +- Covid-19_Real-time_Notification/Covid.py | 62 +- Crypt_Socket/crypt_socket.py | 3 +- Cryptography/crypto.py | 9 +- .../Currency_convertor_GUI.py | 2 +- Current_City_Weather/Current_City_Weather.py | 6 +- CustomTkinter-GUI/Feedback_GUI/Feedback.py | 18 +- CustomTkinter-GUI/SignUP_page/SignUP.py | 52 +- DNS verifier/main.py | 4 +- DSA-Python/Algorithms/BigO.py | 7 +- DSA-Python/Algorithms/BinarySearch.py | 19 +- DSA-Python/Algorithms/BinarySearchTree.py | 27 +- DSA-Python/Algorithms/BubbleSort.py | 7 +- DSA-Python/Algorithms/InsertionSort.py | 14 +- DSA-Python/Algorithms/MergeSort.py | 16 +- DSA-Python/Algorithms/SelectionSort.py | 4 +- DSA-Python/Algorithms/ShellSort.py | 9 +- DSA-Python/Algorithms/recursion.py | 3 +- DSA-Python/DataStructures/LinkedList.py | 16 +- DSA-Python/DataStructures/dictionary.py | 45 +- DSA-Python/DataStructures/graph.py | 29 +- DSA-Python/DataStructures/hashtable.py | 12 +- DSA-Python/DataStructures/list.py | 70 +- DSA-Python/DataStructures/queue.py | 18 +- DSA-Python/DataStructures/sets.py | 13 +- DSA-Python/DataStructures/stack.py | 10 +- DSA-Python/DataStructures/tree.py | 31 +- DSA-Python/DataStructures/tuple.py | 7 +- .../FunnelChart/FunnelCharts.py | 41 +- Data-Visualization/LineChart/line_chart.py | 2 + .../TernaryPlots/TernaryPlot.py | 16 +- .../WaterfallChart/Waterfall.py | 31 +- Decimal-to-hexa-decimal/decimal_to_hexa.py | 26 +- Dev.to Scraper/scraper.py | 2 +- Dictionary-GUI/dictionary.py | 8 +- Digital Clock/Clock.py | 2 +- Directory Tree Generator/tree.py | 9 +- Discord News Bot With AI/main.py | 29 +- Discord-Bot/main.py | 3 +- Disk Space Analyzer/DiskSpaceAnalyzer.py | 11 +- .../distance_conversion.py | 2 +- Doh-Dig/dog-dig.py | 4 +- Dot_Connect/DotConnect.py | 29 +- Download-page-as-pdf/main.py | 11 +- Drowsiness-Detector/drowsiness detection.py | 132 ++-- Drowsiness-Detector/model.py | 64 +- EazyDiner-Scraper/restaurants.py | 3 +- Email GUI/script.py | 68 +- Email-Validator/email_verification.py | 2 +- Email-With-Files/sendemail.py | 2 +- Excel_File_Merger/Excel_file_merger.py | 2 +- Expense Tracker/script.py | 47 +- Eye Detection/eyes.py | 2 +- .../face_mask_detection_using_cnn.py | 4 +- Face_Detection_using_openCV/script.py | 59 +- Facebook-DP-Downloader/fb_dp_downloader.py | 12 +- Facebook_Video_Downloader/script.py | 55 +- .../Fetch_all_links_from_webpage.py | 12 +- Fibonacci_Sequence_Generator/Fibonacci.py | 3 +- .../travel_destinations_scraper.py | 5 +- File Downloader Script/file_downloader.py | 2 + File Downloader/file_downloader.py | 24 +- File Organizer script/file_organizer.py | 8 +- File-Encrypter/script.py | 83 +- File-Mover/fmover.py | 2 +- File_Separator/file_separator.py | 1 + Finger-Counter/HandTrackingModule.py | 2 +- Finger-Counter/finger_counter.py | 25 +- Finger_count_openCV/main.py | 82 +- FirebaseScripts/CredentialsHelper.py | 5 +- FirebaseScripts/firebase_storage.py | 3 +- Flappy-Bird-Game/main.py | 225 +++--- FlappyBird/Flappy.py | 126 +-- Fleury-Algorithm/Fleury_Algorithm.py | 147 ++-- Flipkart-price-alert/track.py | 4 +- FlipkartScraper/dbConnector.py | 16 +- FlipkartScraper/genricHtmlib.py | 42 +- FlipkartScraper/main.py | 44 +- FlipkartScraper/productList.py | 2 +- FlipkartScraper/useragent.py | 3 +- Flipkart_webscraping/Scrap.py | 63 +- Folder-To-HTML/make_data.py | 33 +- Food Detector/app.py | 46 +- Food Detector/model.py | 33 +- Football-Player-Club-Info/main.py | 2 +- Frame-Extract/framext.py | 6 +- GIF/gifnew.py | 9 +- GST Calculator/script.py | 85 ++- GUI-Password-Generator/generator.py | 126 +-- GUI-Stopwatch/stopwatch.py | 28 +- Galaxy Game/main.py | 36 +- Galaxy Game/transforms.py | 3 +- Galaxy Game/user_actions.py | 1 + Get-Live-Youtube-Video-Stats/main.py | 12 +- Github-User-Scraper/scraper.py | 70 +- Github_User_Info/main.py | 30 +- Google-Image-Scrapper/main.py | 6 +- Google-Image-Scrapper/scrapper.py | 3 +- GridSearchCV/GridsearchCV.py | 12 +- Guessing_Game_GUI/guessing_game_tkinter.py | 2 +- Hand-Written-Digit-Recognition/app.py | 16 +- .../Handwritten_character_recog.py | 88 ++- Hashnode-Scraper/scraper.py | 16 +- HeartRate-Detection-OpenC-py/HeartRate.py | 7 +- IOC_Scripts/script.py | 16 +- ISBN-Number-Validator/ISBN-Number.py | 5 +- Image Classification/image_classification.py | 3 +- .../Image Contrast Adjusting Filter.py | 16 +- .../image_manipulation.py | 4 + Image-Captioning/image-captioning.py | 238 +++--- Image-Resizing/resize.py | 7 +- Image-Scraper/scrape_images.py | 4 +- Image-scrape-download/image.py | 31 +- Image-to-PDF Converter/main.py | 11 +- ImageToSketch/sketchScript.py | 2 +- Image_text_hider/img_text_hider.py | 36 +- India-state-guessing-game/main.py | 20 +- Instagram downloader/downloader.py | 4 +- Internet-Speed-Test/main.py | 35 +- Invisibility_Cloak/Invisibility_Cloak.py | 2 +- JSON-to-CSV/json-to-csv.py | 8 +- Job Scraper/JobScraper.py | 21 +- Lane Detection/laneDetection.py | 51 +- Language Detection/app.py | 14 +- Language Translator/lanaguage_translator.py | 6 +- LeetCode-Scrapper/ques.py | 118 +-- Linear-Search-Visualizer/script.py | 134 ++-- Link Scrapper/script.py | 5 +- ...ven_Code_for_Circular_Doubly_LinkedList.py | 29 +- ...enu_Driven_Code_for_Circular_LinkedList.py | 24 +- .../Menu_Driven_Code_for_Doubly_LinkedList.py | 28 +- ...r_Dynamic_Linear_Queue_using_LinkedList.py | 18 +- ...Code_for_Dynamic_Stack_using_LinkedList.py | 19 +- .../Menu_Driven_Code_for_Linear_LinkedList.py | 34 +- Linkedin_Video_Downloader/script.py | 56 +- .../show_file_in_dir.py | 12 +- Login And Signup GUI/login.py | 24 +- Low_battery_alert/low_battery_alert.py | 14 +- Malaria/model_training.py | 2 +- Markdown-viewer/viewer.py | 2 + Master Script/manual db updater.py | 49 +- Medium-Scraper/scraper.py | 11 +- Memory-game/animal.py | 5 +- Memory-game/app.py | 8 +- .../Mini google assistant.py | 6 +- Morse_Code/morse.py | 51 +- Motion Detect/detect.py | 18 +- Movie-Info-Telegram-Bot/bot.py | 2 +- Multi-Language Translation/main.py | 44 +- Music_Player/music.py | 4 + NATO/main.py | 63 +- NSE Stocks GUI/stocks.py | 41 +- Neon Effect Filter/Code.py | 17 +- .../Noise Reduction Script.py | 71 +- .../Nth_Fibonacci_Generator.py | 34 +- Num-Plate-Detector/number_plate.py | 4 +- Number Plate Detection System/main.py.py | 9 +- Number-To-Words/numToWords.py | 25 +- ORB Algorithm/ORB_Algorithm.py | 35 +- .../PDF-Watermark-Remover.py | 23 +- PDF-rotation-API/api.py | 32 +- PDFToWord/main.py | 25 +- .../YouTube_Donlowder.py | 32 +- Palindrome Checker/main.py | 16 +- Parking Space Detection System/detector.py | 15 +- Parking Space Detection System/set_regions.py | 3 +- Password-Manager-GUI/passwords.py | 2 +- Pdf2Video_Converter/script.py | 6 +- Phone Number Tracker/Number.py | 14 +- Piglatin_Translator/piglatin.py | 37 +- Plagiarism_detector/plagiarism.py | 18 +- .../Playback-speed-calculator.py | 31 +- PlaystoreScraper/display_apps.py | 1 - PlaystoreScraper/fetch_apps.py | 26 +- Pomodoro_GUI/Pomodoro_gui.py | 96 ++- PortScanning/portscanningscript.py | 2 + .../PoseEstimation.py | 11 +- .../price_comparison.py | 4 +- Pwned_or_not_GUI/pwned_passwords_GUI.py | 128 ++-- Pygame-Buttons/ExampleButtons.py | 77 +- Pygame-Buttons/main.py | 179 +++-- QR-Code-Generator/QR-generator.py | 6 +- Queue/Menu_Driven_Code_for_Circular_Queue.py | 22 +- ...r_Dynamic_Linear_Queue_using_LinkedList.py | 18 +- Queue/Menu_Driven_Code_for_Linear_Queue.py | 9 +- Queue/Menu_Driven_Code_for_Priority_Queue.py | 9 +- Quiz_Game/quiz.py | 66 +- Rain Alert Mail Sender/main.py | 36 +- Random Password Generator/script.py | 6 +- Random-Quote-generator/quote.py | 6 +- .../real_estate_webscrapper.py | 81 +- Reddit_Scraper_without_API/display_reddit.py | 1 - Reddit_Scraper_without_API/fetch_reddit.py | 18 +- Regular_Expressions_Match/reg.py | 2 +- .../hindi_POS_tag_removal.py | 2 +- Rescale Image/resize_image.py | 2 + .../Restaurant-Management-System.py | 44 +- Resume_parser/resumeparser.py | 9 +- .../Addtional_features.py | 196 ++--- .../Admin_menu.py | 614 ++++++++------- .../User_menu.py | 325 ++++---- .../Userlogin.py | 78 +- Sales-and-Order-Management-System/main.py | 32 +- .../Scientific_Calculator.py | 55 +- Script to check Sentiment/script.py | 129 ++-- Search_File/searching_specific_files.py | 2 +- .../Binary_Search_Iterative.py | 13 +- .../Binary_Search_Recursive.py | 15 +- Searching Techniques/Sequential_Search.py | 12 +- Select Stocks by volume Increase/script.py | 4 +- Sgpa_To_Cgpa_Convertor/sga_to_cgpa.py | 18 +- Simple-Clock-Gui/clock.py | 23 +- .../FlameDect/SmokeDect/SmokeDect-v0.2.py | 12 +- .../FlameDect/SmokeDect/SmokeDect-v0.3.py | 3 +- Smoke_Detect/FlameDect/SmokeDect/__init__.py | 2 +- .../FlameDect/SmokeDect/smokeDect-v0.py | 9 +- Smoke_Detect/FlameDect/__init__.py | 2 +- Smoke_Detect/FlameDect/flameDect-v.py | 6 +- Smoke_Detect/FlameDect/flameDect-v2.py | 56 +- Smoke_Detect/FlameDect/flameDection.py | 8 +- Smoke_Detect/FlameDect/tools/__init__.py | 2 +- Smoke_Detect/FlameDect/tools/get_hog.py | 3 +- .../FlameDect/tools/reformate_video.py | 3 +- Smoke_Detect/FlameDect/tools/split_images.py | 3 +- Snake-Water-Game/Snake-Water Game.py | 27 +- Sorting Techniques/Bubble_Sort.py | 8 +- Sorting Techniques/Insertion_Sort.py | 8 +- Sorting Techniques/Merge_Sort.py | 40 +- Sorting Techniques/Quick_Sort.py | 20 +- Sorting Techniques/Selection_Sort.py | 8 +- .../sortingAlgoVisualizer.py | 147 ++-- Space News AI Model/Space_News.py | 227 +++--- SpaceInvader-Agent/SpaceInvaders Agent.py | 66 +- Spaceship_Game/main.py | 15 +- Spaceship_Game/utility.py | 15 +- Spacex-Calender/main_gui.py | 4 +- Spacex-Calender/notifly.py | 32 +- Speak-like-Yoda/Speak_Like_yoda.py | 8 +- Spotify Playlist Automation/config.py | 4 +- .../spotify_discover_weekly.py | 87 ++- Stack-overflow-scraper/scraper.py | 96 ++- ...Code_for_Dynamic_Stack_using_LinkedList.py | 19 +- Stack/Menu_Driven_Code_for_Stack.py | 56 +- StackOverflow-Scraper/questions.py | 5 +- Stackoverflow-Tool/script.py | 36 +- Stay Hydrated/main.py | 3 + Steganography/steganography.py | 18 +- Stock-Price-Prediction/stock_app.py | 285 ++++--- Stock-Price-Prediction/stock_pred.py | 102 +-- .../Rock-Paper-Scissors Game.py | 3 +- StonePaperScissor - GUI/StonePaperScissors.py | 2 +- Stopwatch GUI/stopwatch_gui.py | 12 +- Story_Generator/story_generator.py | 12 +- Student-placement-prediction/app.py | 1 - Sudoku_Game/sudoku.py | 65 +- TODO (CLI-VER)/todolist.py | 109 +-- TOI_Scrapper/TOI_Scrapper.py | 15 +- Telegram-Weather-Bot/main.py | 1 + Text-to-Image/dalle.py | 13 +- .../Model.py | 6 +- .../app.py | 9 +- TheSnakeGame/snake.py | 106 +-- TicTacToe-GUI/TicTacToe.py | 14 +- Timezone Converter GUI/Tkinter_time_conv.py | 166 ++-- .../Project-GUI.py | 86 ++- .../object_detection.py | 298 +++++--- Train_pnr_status/script.py | 87 +-- TurtleRace/TurtleRace.py | 2 +- Tweet-Fetcher/display.py | 4 +- Twitter bot/Tweepy.py | 6 +- TwitterTweetSentimentalAnalysis/Model.py | 9 +- TwitterTweetSentimentalAnalysis/app.py | 15 +- .../display_hashtags.py | 1 - Twitter_Scraper_without_API/fetch_hashtags.py | 1 - Twitter_Video_Downloader/script.py | 17 +- URL_Short/Shortener/serializers.py | 4 +- URL_Short/Shortener/services/madwire.py | 4 +- URL_Short/Shortener/services/rebrandly.py | 6 +- URL_Short/Shortener/tests.py | 1 + URL_Short/Shortener/views.py | 10 +- URL_Short/UrlShortener/settings.py | 4 +- URL_Short/setup.py | 2 +- Vector_Calc/script.py | 113 ++- Video to PDF/script.py | 46 +- Voice-Assistant/test.py | 2 +- Voice_Recorder/main.py | 3 +- Weather-App/weatherapp.py | 8 +- WhatsAppSpammerBot/main.py | 6 +- Wiki_Infobox_Scraper/main.py | 37 +- Wiki_Scrapper/wiki_Scraper.py | 25 +- Wishing Bot/WishingBot.py | 5 +- YouTube-Video-Downloader/youtube_vid_dl.py | 31 +- Zomato Data Scraper/main.py | 48 +- chat_bot/_Project.py | 463 +++++++----- checksum_Script/Checksum_Script.py | 31 +- cipher_buster/cipher_buster.py | 27 +- face_detection/face_detect.py | 58 +- hangman/hangman.py | 28 +- hangman/hangman_visual.py | 20 +- hangman/words.py | 3 +- imageWatermarker/main.py | 2 + mp3 Downloader/music.py | 31 +- pong-pygame/pong.py | 89 +-- .../PYTHON PROJECT(FINAL).py | 715 +++++++++--------- script_updater.py | 4 +- sticky notes/main.py | 4 +- text_encryption/encryption_method.py | 40 +- 357 files changed, 7203 insertions(+), 5941 deletions(-) diff --git a/9_Typesof_Hash_Craker/9_Types_of_Hash_Cracker.py b/9_Typesof_Hash_Craker/9_Types_of_Hash_Cracker.py index 43fa2715dc..660232b204 100644 --- a/9_Typesof_Hash_Craker/9_Types_of_Hash_Cracker.py +++ b/9_Typesof_Hash_Craker/9_Types_of_Hash_Cracker.py @@ -15,17 +15,24 @@ class Cracker(object): ALPHA_MIXED = (string.ascii_lowercase, string.ascii_uppercase) PUNCTUATION = (string.punctuation,) NUMERIC = (''.join(map(str, range(0, 10))),) - ALPHA_LOWER_NUMERIC = (string.ascii_lowercase, ''.join(map(str, range(0, 10)))) - ALPHA_UPPER_NUMERIC = (string.ascii_uppercase, ''.join(map(str, range(0, 10)))) - ALPHA_MIXED_NUMERIC = (string.ascii_lowercase, string.ascii_uppercase, ''.join(map(str, range(0, 10)))) + ALPHA_LOWER_NUMERIC = (string.ascii_lowercase, + ''.join(map(str, range(0, 10)))) + ALPHA_UPPER_NUMERIC = (string.ascii_uppercase, + ''.join(map(str, range(0, 10)))) + ALPHA_MIXED_NUMERIC = ( + string.ascii_lowercase, string.ascii_uppercase, ''.join(map(str, range(0, 10)))) ALPHA_LOWER_PUNCTUATION = (string.ascii_lowercase, string.punctuation) ALPHA_UPPER_PUNCTUATION = (string.ascii_uppercase, string.punctuation) - ALPHA_MIXED_PUNCTUATION = (string.ascii_lowercase, string.ascii_uppercase, string.punctuation) + ALPHA_MIXED_PUNCTUATION = ( + string.ascii_lowercase, string.ascii_uppercase, string.punctuation) NUMERIC_PUNCTUATION = (''.join(map(str, range(0, 10))), string.punctuation) - ALPHA_LOWER_NUMERIC_PUNCTUATION = (string.ascii_lowercase, ''.join(map(str, range(0, 10))), string.punctuation) - ALPHA_UPPER_NUMERIC_PUNCTUATION = (string.ascii_uppercase, ''.join(map(str, range(0, 10))), string.punctuation) + ALPHA_LOWER_NUMERIC_PUNCTUATION = (string.ascii_lowercase, ''.join( + map(str, range(0, 10))), string.punctuation) + ALPHA_UPPER_NUMERIC_PUNCTUATION = (string.ascii_uppercase, ''.join( + map(str, range(0, 10))), string.punctuation) ALPHA_MIXED_NUMERIC_PUNCTUATION = ( - string.ascii_lowercase, string.ascii_uppercase, ''.join(map(str, range(0, 10))), string.punctuation + string.ascii_lowercase, string.ascii_uppercase, ''.join( + map(str, range(0, 10))), string.punctuation ) def __init__(self, hash_type, hash, charset, progress_interval): @@ -90,7 +97,8 @@ def __attack(self, q, max_length): hasher.update(hash_fn(value)) if self.__hash == hasher.hexdigest(): q.put("FOUND") - q.put("{}Match found! Password is {}{}".format(os.linesep, value, os.linesep)) + q.put("{}Match found! Password is {}{}".format( + os.linesep, value, os.linesep)) self.stop_reporting_progress() return @@ -110,7 +118,8 @@ def work(work_q, done_q, max_length): obj.__attack(done_q, max_length) def start_reporting_progress(self): - self.__progress_timer = threading.Timer(self.__progress_interval, self.start_reporting_progress) + self.__progress_timer = threading.Timer( + self.__progress_interval, self.start_reporting_progress) self.__progress_timer.start() print( f"Character set: {self.__charset}, iteration: {self.__curr_iter}, trying: {self.__curr_val}, hashes/sec: {self.__curr_iter - self.__prev_iter}", @@ -119,7 +128,8 @@ def start_reporting_progress(self): def stop_reporting_progress(self): self.__progress_timer.cancel() - print(f"Finished character set {self.__charset} after {self.__curr_iter} iterations", flush=True) + print( + f"Finished character set {self.__charset} after {self.__curr_iter} iterations", flush=True) if __name__ == "__main__": @@ -153,7 +163,8 @@ def stop_reporting_progress(self): "09": "SHA512" } - prompt = "Specify the character set to use:{}{}".format(os.linesep, os.linesep) + prompt = "Specify the character set to use:{}{}".format( + os.linesep, os.linesep) for key, value in sorted(character_sets.items()): prompt += "{}. {}{}".format(key, ''.join(value), os.linesep) @@ -162,12 +173,14 @@ def stop_reporting_progress(self): charset = input(prompt).zfill(2) selected_charset = character_sets[charset] except KeyError: - print("{}Please select a valid character set{}".format(os.linesep, os.linesep)) + print("{}Please select a valid character set{}".format( + os.linesep, os.linesep)) continue else: break - prompt = "{}Specify the maximum possible length of the password: ".format(os.linesep) + prompt = "{}Specify the maximum possible length of the password: ".format( + os.linesep) while True: try: @@ -197,7 +210,8 @@ def stop_reporting_progress(self): try: user_hash = input(prompt) except ValueError: - print("{}Something is wrong with the format of the hash. Please enter a valid hash".format(os.linesep)) + print("{}Something is wrong with the format of the hash. Please enter a valid hash".format( + os.linesep)) continue else: break @@ -207,7 +221,8 @@ def stop_reporting_progress(self): work_queue = multiprocessing.Queue() done_queue = multiprocessing.Queue() progress_interval = 3 - cracker = Cracker(hash_type.lower(), user_hash.lower(), ''.join(selected_charset), progress_interval) + cracker = Cracker(hash_type.lower(), user_hash.lower(), + ''.join(selected_charset), progress_interval) start_time = time.time() p = multiprocessing.Process(target=Cracker.work, args=(work_queue, done_queue, password_length)) @@ -218,7 +233,8 @@ def stop_reporting_progress(self): if len(selected_charset) > 1: for i in range(len(selected_charset)): progress_interval += .2 - cracker = Cracker(hash_type.lower(), user_hash.lower(), selected_charset[i], progress_interval) + cracker = Cracker(hash_type.lower(), user_hash.lower(), + selected_charset[i], progress_interval) p = multiprocessing.Process(target=Cracker.work, args=(work_queue, done_queue, password_length)) processes.append(p) @@ -241,4 +257,4 @@ def stop_reporting_progress(self): print("{}No matches found{}".format(os.linesep, os.linesep)) break - print("Took {} seconds".format(time.time() - start_time)) \ No newline at end of file + print("Took {} seconds".format(time.time() - start_time)) diff --git a/AI Calculator/main.py b/AI Calculator/main.py index c45ec61da2..206ccbac54 100644 --- a/AI Calculator/main.py +++ b/AI Calculator/main.py @@ -3,11 +3,11 @@ # naming the ChatBot calculator # using mathematical evaluation logic # the calculator AI will not learn with the user input -Bot = ChatBot(name = 'Calculator', - read_only = True, - logic_adapters = ["chatterbot.logic.MathematicalEvaluation"], - storage_adapter = "chatterbot.storage.SQLStorageAdapter") - +Bot = ChatBot(name='Calculator', + read_only=True, + logic_adapters=["chatterbot.logic.MathematicalEvaluation"], + storage_adapter="chatterbot.storage.SQLStorageAdapter") + # clear the screen and start the calculator print('\033c') @@ -15,8 +15,8 @@ while (True): # take the input from the user user_input = input("me: ") - - # check if the user has typed quit to exit the prgram + + # check if the user has typed quit to exit the prgram if user_input.lower() == 'quit': print("Exiting") break diff --git a/AI Chat Bot/main.py b/AI Chat Bot/main.py index 72813ee3bc..279d3143d7 100644 --- a/AI Chat Bot/main.py +++ b/AI Chat Bot/main.py @@ -9,11 +9,12 @@ headers = { - "content-type": "application/json", - "X-RapidAPI-Key": "OUR API KEY", - "X-RapidAPI-Host": "simple-chatgpt-api.p.rapidapi.com" + "content-type": "application/json", + "X-RapidAPI-Key": "OUR API KEY", + "X-RapidAPI-Host": "simple-chatgpt-api.p.rapidapi.com" } + def animate(): for c in itertools.cycle(['|', '/', '-', '\\']): if done: @@ -21,16 +22,18 @@ def animate(): sys.stdout.write('\r' + c) sys.stdout.flush() time.sleep(0.1) - + # Clear the console output sys.stdout.write('\r') sys.stdout.flush() + def ask(question): - payload = { "question": question } + payload = {"question": question} response = requests.post(url, json=payload, headers=headers) return response.json().get("answer") + if __name__ == "__main__": print(pyfiglet.figlet_format("AI Chat BOT")) print("Enter the question to ask:") @@ -38,18 +41,17 @@ def ask(question): while True: # print("/>> ", end="") question = str(input(">> ")) - if(question == 'q'): + if (question == 'q'): print(">> Bye! Thanks for Using...") break # loading done = False - #here is the animation + # here is the animation t = threading.Thread(target=animate) t.start() answer = ask(question) time.sleep(5) done = True t.join() - print(">> ",answer) + print(">> ", answer) print() - \ No newline at end of file diff --git a/AI TicTacToe/src/TicTacToe.py b/AI TicTacToe/src/TicTacToe.py index 900747e8c8..36f8487a8c 100644 --- a/AI TicTacToe/src/TicTacToe.py +++ b/AI TicTacToe/src/TicTacToe.py @@ -1,5 +1,6 @@ import random + def display_board(board): print('-------------') print('| ' + board[7] + ' | ' + board[8] + ' | ' + board[9] + ' |') @@ -110,5 +111,6 @@ def play_tic_tac_toe(): print('Thank you for playing.') break + # Start the game play_tic_tac_toe() diff --git a/Address-Book/addressbook.py b/Address-Book/addressbook.py index 76ca9e2e69..ce05b37019 100644 --- a/Address-Book/addressbook.py +++ b/Address-Book/addressbook.py @@ -7,7 +7,7 @@ import tkinter.messagebox root = Tk() root.geometry('600x370') -list_of_names=[] +list_of_names = [] root.title('AddressBook') Name = StringVar() Number = StringVar() @@ -16,11 +16,13 @@ specified by db_file return: Connection object or None """ + + def create_connection(db_file): conn = None try: conn = sqlite3.connect(db_file) - r_set=conn.execute('''SELECT * from tasks'''); + r_set = conn.execute('''SELECT * from tasks''') for student in r_set: list_of_names.append(student[1]) return conn @@ -28,10 +30,13 @@ def create_connection(db_file): print(e) return conn + """ create a table from the create_table_sql statement conn: Connection object create_table_sql: a CREATE TABLE statement """ + + def create_table(conn, create_table_sql): try: c = conn.cursor() @@ -40,28 +45,35 @@ def create_table(conn, create_table_sql): print(e) return + ''' displaying added/deleted message ''' + + def onClickAdded(): - tkinter.messagebox.showinfo(" ",Name.get()+" got added") + tkinter.messagebox.showinfo(" ", Name.get()+" got added") + def onClickDeleted(): - tkinter.messagebox.showinfo(" ",Name.get()+" got deleted") + tkinter.messagebox.showinfo(" ", Name.get()+" got deleted") + """ Create a new task (ie creating new row) for the given Name taking care of all conditions such as Name,phone no cannot be empty ,phone no should be 10 digits and also if Name already exist,then it cannot be inerted """ + + def create_task(): sql = ''' INSERT INTO tasks(name,status_id) VALUES(?,?) ''' - if(Name.get() not in list_of_names): - - if((Name.get()=='') | (Number.get()=='') | (len(Number.get())!=10)): + if (Name.get() not in list_of_names): + + if ((Name.get() == '') | (Number.get() == '') | (len(Number.get()) != 10)): top = Toplevel(root) top.geometry('180x100') - if((Number.get()=='') | (len(Number.get())!=10)): - myLabel = Label(top, text="Phone no should be 10 digits\n") + if ((Number.get() == '') | (len(Number.get()) != 10)): + myLabel = Label(top, text="Phone no should be 10 digits\n") else: myLabel = Label(top, text="NAME IS EMPTY\n") myLabel.pack() @@ -70,15 +82,15 @@ def create_task(): return onClickAdded() cur = conn.cursor() - cur.execute(sql, (Name.get(),Number.get())) + cur.execute(sql, (Name.get(), Number.get())) conn.commit() return cur.lastrowid else: top = Toplevel(root) top.geometry('180x100') - if(Name.get()==''): + if (Name.get() == ''): myLabel = Label(top, text="NAME IS EMPTY\n") - elif((Number.get()=='') | (len(Number.get())!=10)): + elif ((Number.get() == '') | (len(Number.get()) != 10)): myLabel = Label(top, text="Phone no should be 10 digits\n") else: myLabel = Label(top, text=Name.get()+" Already Exist\n") @@ -86,22 +98,28 @@ def create_task(): mySubmitButton = Button(top, text=' Back ', command=top.destroy) mySubmitButton.pack() + """ Query tasks by Name, if name not found then it gives a warning saying "NOT Found" -""" +""" + + def select_task_by_name(): cur = conn.cursor() cur.execute("SELECT * FROM tasks WHERE name=?", (Name.get(),)) rows = cur.fetchall() - if(len(rows)==0): + if (len(rows) == 0): inputDialog = MyDialog(root) root.wait_window(inputDialog.top) else: Number.set(rows[0][2]) - + + """ Editing phone no, if name not found then it gives a warning saying "NOT Found" """ + + def update_task(): """ update priority, begin_date, and end date of a task @@ -112,19 +130,22 @@ def update_task(): sql = ''' UPDATE tasks SET status_id = ? WHERE name = ?''' - if((Name.get() not in list_of_names) | (Name.get()=='')): + if ((Name.get() not in list_of_names) | (Name.get() == '')): inputDialog = MyDialog(root) root.wait_window(inputDialog.top) return cur = conn.cursor() - cur.execute(sql, (Number.get(),Name.get())) + cur.execute(sql, (Number.get(), Name.get())) conn.commit() + """ Delete a task by name.if not found ,gives a warning!!! """ + + def delete_task(): - if((Name.get() not in list_of_names) | (Name.get()=='')): + if ((Name.get() not in list_of_names) | (Name.get() == '')): inputDialog = MyDialog(root) root.wait_window(inputDialog.top) return @@ -134,26 +155,30 @@ def delete_task(): cur.execute(sql, (Name.get(),)) conn.commit() + """ Get all rows in the tasks table """ + + def select_all_tasks(): - r_set=conn.execute('''SELECT * from tasks'''); - i=0 - j=0 + r_set = conn.execute('''SELECT * from tasks''') + i = 0 + j = 0 top = Toplevel(root) for student in r_set: list_of_names.append(student[1]) for j in range(len(student)): - e = Entry(top, width=11, fg='Gray20') - e.grid(row=i, column=j) + e = Entry(top, width=11, fg='Gray20') + e.grid(row=i, column=j) e.insert(END, student[j]) - i=i+1 - okButton= Button(top, text=' ok ', command=top.destroy) - if(j==0): - j=1 - okButton.grid(row=i+3, column=j-1) - + i = i+1 + okButton = Button(top, text=' ok ', command=top.destroy) + if (j == 0): + j = 1 + okButton.grid(row=i+3, column=j-1) + + ''' Getting the path of database and defining the table to be created ''' @@ -172,11 +197,13 @@ def select_all_tasks(): if conn is not None: create_table(conn, sql_create_tasks_table) else: - print("Error! cannot create the database connection.") + print("Error! cannot create the database connection.") ''' creating dialog box for warnings! ''' + + class MyDialog: def __init__(self, parent): top = self.top = Toplevel(parent) @@ -188,31 +215,45 @@ def __init__(self, parent): def send(self): self.top.destroy() + ''' Exiting from the application ''' + + def EXIT(): root.destroy() + ''' Resetting Name and phone no field ''' + + def RESET(): Name.set('') Number.set('') + ''' Creating UI for whole application ''' -Label(root, text = 'NAME', font='Times 15 bold').place(x= 130, y=20) -Entry(root, textvariable = Name,width=42).place(x= 200, y=25) -Label(root, text = 'PHONE NO ', font='Times 15 bold').place(x= 130, y=70) -Entry(root, textvariable = Number,width=35).place(x= 242, y=73) -Button(root,text=" ADD", font='Times 14 bold',bg='dark gray', command = create_task,width=8).place(x= 130, y=110) -Button(root,text="EDIT", font='Times 14 bold',bg='dark gray',command = update_task,width=8).place(x= 260, y=108) -Button(root,text="DELETE", font='Times 14 bold',bg='dark gray',command = delete_task,width=8).place(x= 390, y=107.5) -Button(root,text="VIEW ALL", font='Times 14 bold',bg='dark gray', command = select_all_tasks,width=12).place(x= 160, y=191) -Button(root,text="VIEW BY NAME", font='Times 14 bold',bg='dark gray', command = select_task_by_name,width=13).place(x= 330, y=190) -Button(root,text="EXIT", font='Times 14 bold',bg='dark gray', command = EXIT,width=8).place(x= 200, y=280) -Button(root,text="RESET", font='Times 14 bold',bg='dark gray', command = RESET,width=8).place(x= 320, y=280) +Label(root, text='NAME', font='Times 15 bold').place(x=130, y=20) +Entry(root, textvariable=Name, width=42).place(x=200, y=25) +Label(root, text='PHONE NO ', font='Times 15 bold').place(x=130, y=70) +Entry(root, textvariable=Number, width=35).place(x=242, y=73) +Button(root, text=" ADD", font='Times 14 bold', bg='dark gray', + command=create_task, width=8).place(x=130, y=110) +Button(root, text="EDIT", font='Times 14 bold', bg='dark gray', + command=update_task, width=8).place(x=260, y=108) +Button(root, text="DELETE", font='Times 14 bold', bg='dark gray', + command=delete_task, width=8).place(x=390, y=107.5) +Button(root, text="VIEW ALL", font='Times 14 bold', bg='dark gray', + command=select_all_tasks, width=12).place(x=160, y=191) +Button(root, text="VIEW BY NAME", font='Times 14 bold', bg='dark gray', + command=select_task_by_name, width=13).place(x=330, y=190) +Button(root, text="EXIT", font='Times 14 bold', bg='dark gray', + command=EXIT, width=8).place(x=200, y=280) +Button(root, text="RESET", font='Times 14 bold', bg='dark gray', + command=RESET, width=8).place(x=320, y=280) root.mainloop() diff --git a/Age-Calculator-GUI/age_calc_gui.py b/Age-Calculator-GUI/age_calc_gui.py index 778c1d8a4e..8be7d4c0b4 100644 --- a/Age-Calculator-GUI/age_calc_gui.py +++ b/Age-Calculator-GUI/age_calc_gui.py @@ -127,8 +127,6 @@ def check_day(): self.statement = tk.Label( text=f"{nameValue.get()}'s birth month\n cannot parse to int.", font="courier 10", bg="lightblue") - - self.statement.grid(row=6, column=1, pady=15) return False diff --git a/Age_Calculator/Age_Calculator.py b/Age_Calculator/Age_Calculator.py index ce29deda08..b1591987eb 100644 --- a/Age_Calculator/Age_Calculator.py +++ b/Age_Calculator/Age_Calculator.py @@ -19,14 +19,14 @@ def calculate_age(birthday): if __name__ == "__main__": - print(" Age Calculator By Python") - - try: - birthYear = int(input("Enter the birth year: ")) - birthMonth = int(input("Enter the birth month: ")) - birthDay = int(input("Enter the birth day: ")) - dateOfBirth = date(birthYear, birthMonth, birthDay) - age = calculate_age(dateOfBirth) - print(age) - except ValueError: - print("Invalid input. Please enter valid integers for the year, month, and day.") + print(" Age Calculator By Python") + + try: + birthYear = int(input("Enter the birth year: ")) + birthMonth = int(input("Enter the birth month: ")) + birthDay = int(input("Enter the birth day: ")) + dateOfBirth = date(birthYear, birthMonth, birthDay) + age = calculate_age(dateOfBirth) + print(age) + except ValueError: + print("Invalid input. Please enter valid integers for the year, month, and day.") diff --git a/All_GitHub_Repos/all_github_repos.py b/All_GitHub_Repos/all_github_repos.py index 49c7b482bd..70fe6c0746 100644 --- a/All_GitHub_Repos/all_github_repos.py +++ b/All_GitHub_Repos/all_github_repos.py @@ -58,4 +58,4 @@ def repository_details(user): print(title, ":", description) print( "\n-------------------------------------------------------------------------------------------------------------------\n" - ) \ No newline at end of file + ) diff --git a/Amazon-Price-Tracker/amazonprice.py b/Amazon-Price-Tracker/amazonprice.py index fd90ea180a..8d5ea76214 100644 --- a/Amazon-Price-Tracker/amazonprice.py +++ b/Amazon-Price-Tracker/amazonprice.py @@ -26,11 +26,12 @@ # print(soup) -def message_sending(phone_number,title): +def message_sending(phone_number, title): now = datetime.datetime.now() message = f"Price of {title} is fallen below the threshold amount. Click on the link below to buy the product!!!\n\n" pywhatkit.sendwhatmsg(phone_number, message, now.hour, now.minute + 1) + def mail_sending(mail_id, title, password): server_mail = "smtp.gmail.com" port = 587 diff --git a/Amazon-Price-Tracker/tempCodeRunnerFile.py b/Amazon-Price-Tracker/tempCodeRunnerFile.py index 61ba2757a6..f6617cb73d 100644 --- a/Amazon-Price-Tracker/tempCodeRunnerFile.py +++ b/Amazon-Price-Tracker/tempCodeRunnerFile.py @@ -1 +1 @@ -https://www.amazon.in/Apple-Original-MMTN2ZM-Lightning-Connector/dp/B01M1EEPOB/ref=sr_1_1?crid=XFITOYOGI999&keywords=airpods+apple&qid=1685422019&s=electronics&sprefix=airpods+appl%2Celectronics%2C458&sr=1-1 \ No newline at end of file +https: // www.amazon. in /Apple-Original-MMTN2ZM-Lightning-Connector/dp/B01M1EEPOB/ref = sr_1_1?crid = XFITOYOGI999 & keywords = airpods+apple & qid = 1685422019 & s = electronics & sprefix = airpods+appl % 2Celectronics % 2C458 & sr = 1-1 diff --git a/Applying Bitwise Operations/Applying Bitwise operations.py b/Applying Bitwise Operations/Applying Bitwise operations.py index 91797bde48..4346a621b7 100644 --- a/Applying Bitwise Operations/Applying Bitwise operations.py +++ b/Applying Bitwise Operations/Applying Bitwise operations.py @@ -1,6 +1,7 @@ import cv2 import argparse + def perform_bitwise_operations(image1_path, image2_path): src1 = cv2.imread(image1_path) src2 = cv2.imread(image2_path) @@ -19,6 +20,7 @@ def perform_bitwise_operations(image1_path, image2_path): return and_op, or_op, xor_op + def save_images(image1, image2, image3): cv2.imshow('Bitwise AND', image1) cv2.imshow('Bitwise OR', image2) @@ -26,18 +28,23 @@ def save_images(image1, image2, image3): cv2.waitKey(0) cv2.destroyAllWindows() + if __name__ == '__main__': # Creating command-line arguments parser - parser = argparse.ArgumentParser(description='Perform bitwise operations on two images.') - parser.add_argument('image1', type=str, help='Path to the first image file.') - parser.add_argument('image2', type=str, help='Path to the second image file.') + parser = argparse.ArgumentParser( + description='Perform bitwise operations on two images.') + parser.add_argument('image1', type=str, + help='Path to the first image file.') + parser.add_argument('image2', type=str, + help='Path to the second image file.') args = parser.parse_args() image1_path = args.image1 image2_path = args.image2 # Performing bitwise operations - result1, result2, result3 = perform_bitwise_operations(image1_path, image2_path) + result1, result2, result3 = perform_bitwise_operations( + image1_path, image2_path) # Displaying and saving the resulting images save_images(result1, result2, result3) diff --git a/Arbitary Quotes Generator/arbitary_quotes_generator.py b/Arbitary Quotes Generator/arbitary_quotes_generator.py index 011a12bc0a..7d6c9c0245 100644 --- a/Arbitary Quotes Generator/arbitary_quotes_generator.py +++ b/Arbitary Quotes Generator/arbitary_quotes_generator.py @@ -1,6 +1,7 @@ import random import quote + def generate_quotes(): print("1. Inspirational") print("2. Motivational") @@ -24,7 +25,7 @@ def generate_quotes(): quotes = quote.quote(search_term) num = int(input("Enter the No. of quotes to generate: ")) for i in range(num): - print(i+1 ,".", random.choice(quotes)['quote']) - + print(i+1, ".", random.choice(quotes)['quote']) + generate_quotes() diff --git a/Audio Splitting/audio-split.py b/Audio Splitting/audio-split.py index 09165d6307..bdd14f4962 100644 --- a/Audio Splitting/audio-split.py +++ b/Audio Splitting/audio-split.py @@ -8,6 +8,7 @@ import os import webrtcvad + def read_wave(path): with contextlib.closing(wave.open(path, 'rb')) as wf: @@ -63,7 +64,6 @@ def vad_collector(sample_rate, frame_duration_ms, for frame in frames: is_speech = vad.is_speech(frame.bytes, sample_rate) - if not triggered: ring_buffer.append((frame, is_speech)) num_voiced = len([f for f, speech in ring_buffer if speech]) @@ -71,7 +71,6 @@ def vad_collector(sample_rate, frame_duration_ms, if num_voiced > 0.9 * ring_buffer.maxlen: triggered = True - for f, s in ring_buffer: voiced_frames.append(f) ring_buffer.clear() @@ -93,13 +92,15 @@ def vad_collector(sample_rate, frame_duration_ms, if voiced_frames: yield b''.join([f.bytes for f in voiced_frames]) + path = "./frontend/speech-transcription-app/public/Original data" if not os.path.exists(path): - os.makedirs(path) - print("Output folder created") + os.makedirs(path) + print("Output folder created") else: - print("Output folder already present") - sys.exit() + print("Output folder already present") + sys.exit() + def folder(path): if not os.path.exists(path): @@ -108,6 +109,7 @@ def folder(path): else: print("Output folder already present") + path = "./frontend/speech-transcription-app/public/Original data" folder(path) path = "./main/save" @@ -115,19 +117,18 @@ def folder(path): path = "./main/discard" folder(path) -file_name= "./main/mod_1.wav" -op_path= "./frontend/speech-transcription-app/public/Original data/audio_chunks" +file_name = "./main/mod_1.wav" +op_path = "./frontend/speech-transcription-app/public/Original data/audio_chunks" - -def main(file_name,op_path): +def main(file_name, op_path): if os.path.isdir(op_path): print("Output folder already present") else: os.mkdir(op_path) - print("Output folder created") - + print("Output folder created") + audio, sample_rate = read_wave(file_name) vad = webrtcvad.Vad(2) frames = frame_generator(30, audio, sample_rate) @@ -135,25 +136,15 @@ def main(file_name,op_path): for i, segment in enumerate(segments): path = op_path+'/'+'chunk%004d.wav' % (i+1,) - print(' Writing %s' %(path,)) - write_wave(path, segment, sample_rate ) - + print(' Writing %s' % (path,)) + write_wave(path, segment, sample_rate) # sys.argv[1] # sys.argv[2] -file_name= "./main/mod_1.wav" -op_path= "./frontend/speech-transcription-app/public/Original data/audio_chunks" -main(file_name,op_path) +file_name = "./main/mod_1.wav" +op_path = "./frontend/speech-transcription-app/public/Original data/audio_chunks" +main(file_name, op_path) print("Audio Splitting Done") - - - - - - - - - diff --git a/Audio to Text Convertor/code.py b/Audio to Text Convertor/code.py index c67235125e..4c92ea2c6e 100644 --- a/Audio to Text Convertor/code.py +++ b/Audio to Text Convertor/code.py @@ -1,5 +1,6 @@ import speech_recognition as sr + def convert_audio_to_text(): # Initialize the recognizer r = sr.Recognizer() @@ -11,15 +12,20 @@ def convert_audio_to_text(): try: # Use the recognizer to convert audio to text - text = r.recognize_google(audio) # Convert audio to text using Google Speech Recognition service + # Convert audio to text using Google Speech Recognition service + text = r.recognize_google(audio) return text except sr.UnknownValueError: - print("Unable to recognize speech.") # Handle the case when speech cannot be recognized + # Handle the case when speech cannot be recognized + print("Unable to recognize speech.") except sr.RequestError as e: - print("Error: {0}".format(e)) # Handle any errors that occur during speech recognition + # Handle any errors that occur during speech recognition + print("Error: {0}".format(e)) + # Example usage -audio_text = convert_audio_to_text() # Call the function to convert audio to text +# Call the function to convert audio to text +audio_text = convert_audio_to_text() if audio_text: print("You said:", audio_text) # Print the converted text @@ -34,4 +40,3 @@ def convert_audio_to_text(): print("Words:", words) # Perform other operations on the text as needed - diff --git a/Auto Birthday Wisher/Auto B'Day Wisher.py b/Auto Birthday Wisher/Auto B'Day Wisher.py index 2f2d7f5adb..572a7e5d29 100755 --- a/Auto Birthday Wisher/Auto B'Day Wisher.py +++ b/Auto Birthday Wisher/Auto B'Day Wisher.py @@ -40,7 +40,7 @@ def sendEmail(to, sub, msg): bday = item['Birthday'] bday = datetime.datetime.strptime(bday, "%d-%m-%Y") bday = bday.strftime("%d-%m") - if(today == bday) and yearNow not in str(item['LastWishedYear']): + if (today == bday) and yearNow not in str(item['LastWishedYear']): # calling the sendmail function sendEmail(item['Email'], "Happy Birthday", item['Dialogue']) writeInd.append(index) diff --git a/Automated_scraper.py/script.py b/Automated_scraper.py/script.py index 27c58d2d72..abde80a7dc 100644 --- a/Automated_scraper.py/script.py +++ b/Automated_scraper.py/script.py @@ -3,11 +3,12 @@ from bs4 import BeautifulSoup import time + def display_content(url, selector): try: # Send a GET request to the URL response = requests.get(url) - + # Check if the request was successful if response.status_code == 200: # Create a BeautifulSoup object with the page content @@ -23,10 +24,12 @@ def display_content(url, selector): except Exception as e: print("An error occurred:", e) + if __name__ == "__main__": # Check if URL, selector, and interval are provided as arguments if len(sys.argv) < 4: - print("Usage: python script.py [URL] [CSS selector] [Interval in minutes]") + print( + "Usage: python script.py [URL] [CSS selector] [Interval in minutes]") sys.exit(1) # Get the URL, selector, and interval from command-line arguments diff --git a/Autonomous-Taxi-Agent/Autonomous TaxiAgent.py b/Autonomous-Taxi-Agent/Autonomous TaxiAgent.py index 21938baabd..e724717170 100644 --- a/Autonomous-Taxi-Agent/Autonomous TaxiAgent.py +++ b/Autonomous-Taxi-Agent/Autonomous TaxiAgent.py @@ -5,6 +5,8 @@ @author: Ayush """ +import time +import random import gym import numpy as np from IPython.display import clear_output @@ -12,97 +14,98 @@ env = gym.make('Taxi-v3') episodes = 10 -for episode in range(1,episodes): +for episode in range(1, episodes): state = env.reset() - done= False - score=0 - + done = False + score = 0 + while not done: env.render() - state,reward,done,info = env.step(env.action_space.sample()) + state, reward, done, info = env.step(env.action_space.sample()) score += reward clear_output(wait=True) print('Episode: {}\nScore: {}'.format(episode, score)) env.close() -#Creating Q-Table +# Creating Q-Table actions = env.action_space.n state = env.observation_space.n -q_table = np.zeros((state,actions)) +q_table = np.zeros((state, actions)) -#q_table.shape -#q_table +# q_table.shape +# q_table -#Parameters for Q-Learning +# Parameters for Q-Learning num_episodes = 10000 -max_steps_per_episode =1000 -learning_rate=0.01 +max_steps_per_episode = 1000 +learning_rate = 0.01 discount_rate = 0.99 -exploration_rate=1 +exploration_rate = 1 max_exploration_rate = 1 min_exploration_rate = 0.01 -exploration_decay_rate= 0.01 +exploration_decay_rate = 0.01 rewards_all_episodes = [] -#Q-Learning Algorithm -import random +# Q-Learning Algorithm for episode in range(num_episodes): state = env.reset() done = False reward_current_episode = 0 - + for step in range(max_steps_per_episode): - #Exploration vs Exploitation trade-off - exploration_threshold = random.uniform(0,1) + # Exploration vs Exploitation trade-off + exploration_threshold = random.uniform(0, 1) if exploration_threshold > exploration_rate: - action = np.argmax(q_table[state,:]) + action = np.argmax(q_table[state, :]) else: action = env.action_space.sample() - new_state,reward,done,info = env.step(action) - - #Update Q-Table - q_table[state,action] = q_table[state,action]*(1-learning_rate)+ learning_rate*(reward + discount_rate * np.max(q_table[new_state, :])) - state=new_state + new_state, reward, done, info = env.step(action) + + # Update Q-Table + q_table[state, action] = q_table[state, action]*(1-learning_rate) + learning_rate*( + reward + discount_rate * np.max(q_table[new_state, :])) + state = new_state reward_current_episode += reward - - if done== True: + + if done == True: break exploration_rate = min_exploration_rate + \ - (max_exploration_rate- min_exploration_rate) * np.exp(-exploration_decay_rate * episode) + (max_exploration_rate - min_exploration_rate) * \ + np.exp(-exploration_decay_rate * episode) rewards_all_episodes.append(reward_current_episode) print("***** Training Finished *****") q_table -#Calculate and print average reward per thousand episodes -rewards_per_thousand_episodes = np.split(np.array(rewards_all_episodes), num_episodes/1000) +# Calculate and print average reward per thousand episodes +rewards_per_thousand_episodes = np.split( + np.array(rewards_all_episodes), num_episodes/1000) count = 1000 print("Average per thousand episodes") for r in rewards_per_thousand_episodes: print(count, ":", str(sum(r/1000))) - count+=1000 - + count += 1000 + # Visualize Agent -import time for episode in range(3): status = env.reset() done = False - print("Episode is: "+ str(episode)) + print("Episode is: " + str(episode)) time.sleep(1) - + for step in range(max_steps_per_episode): clear_output(wait=True) env.render() time.sleep(.4) - - action = np.argmax(q_table[state,:]) - + + action = np.argmax(q_table[state, :]) + new_state, reward, done, info = env.step(action) - + if done: clear_output(wait=True) env.render() @@ -114,10 +117,7 @@ print("****Failed****") time.sleep(2) clear_output(wait=True) - + break - state=new_state + state = new_state env.close() - - - diff --git a/Background-Payload-Runner/run-payload.py b/Background-Payload-Runner/run-payload.py index 9686cf7bf8..91a103c765 100644 --- a/Background-Payload-Runner/run-payload.py +++ b/Background-Payload-Runner/run-payload.py @@ -2,32 +2,34 @@ import background import os -##select which command line you want to run the payload on -##commandline="cmd /c " -commandline="powershell " +# select which command line you want to run the payload on +# commandline="cmd /c " +commandline = "powershell " -time_delay=0 ##in seconds +time_delay = 0 # in seconds -##CUSTOM PAYLOAD -payload="Start-process chrome.exe https://www.youtube.com/watch?v=dQw4w9WgXcQ" ##rickroll payload +# CUSTOM PAYLOAD +# rickroll payload +payload = "Start-process chrome.exe https://www.youtube.com/watch?v=dQw4w9WgXcQ" -##other payloads (example) -##payload="shutdown" -## --shuts down the machine without any confirmation +# other payloads (example) +# payload="shutdown" +# --shuts down the machine without any confirmation -##payload="shutdown -force -restart" -## --restarts the machine without any confirmation -##payload="netsh wlan disconnect" -## --disconnects the wifi of the machine - -##THESE ARE JUST A FEW. The possibilities are endless +# payload="shutdown -force -restart" +# --restarts the machine without any confirmation +# payload="netsh wlan disconnect" +# --disconnects the wifi of the machine +# THESE ARE JUST A FEW. The possibilities are endless @background.task def work(): - if(time_delay!=0): + if (time_delay != 0): time.sleep(time_delay) os.system(commandline+payload) -work() \ No newline at end of file + + +work() diff --git a/Bandwidth-Monitor/bandwidth_py3.py b/Bandwidth-Monitor/bandwidth_py3.py index b063b82e71..0611dbbc9a 100644 --- a/Bandwidth-Monitor/bandwidth_py3.py +++ b/Bandwidth-Monitor/bandwidth_py3.py @@ -51,7 +51,7 @@ def main(): else: limit = float(sys.argv[1]) unit = str(sys.argv[2]) - #callMonitor(limit, unit) + # callMonitor(limit, unit) monitor(limit, unit) diff --git a/Base-N_Calc/script.py b/Base-N_Calc/script.py index 1a1581dd50..a512c818f9 100644 --- a/Base-N_Calc/script.py +++ b/Base-N_Calc/script.py @@ -1,5 +1,6 @@ from tkinter import * + def SetStatusError(): """ Sets Status bar label to error message """ Status["text"] = "Wronge Input(s)... :\ " @@ -8,21 +9,27 @@ def SetStatusError(): def Con_Base_X_to_Dec(num, base_x): # Converting the integeral part - integeral_part = str(int(num))[::-1] # Extract integerals in reverse order - i=0 + # Extract integerals in reverse order + integeral_part = str(int(num))[::-1] + i = 0 res = 0 for number in integeral_part: - element = int(number) * (base_x**i) # Convert each number to decimal - res += element # Add element to result - i+=1 + # Convert each number to decimal + element = int(number) * (base_x**i) + # Add element to result + res += element + i += 1 # Converting the decimal part decimal_part = str(num) - decimal_part = decimal_part[decimal_part.index(".")+1:] # Extract decimal part using string manipulation + # Extract decimal part using string manipulation + decimal_part = decimal_part[decimal_part.index(".")+1:] i = -1 for decimal in decimal_part: - element = int(decimal) * (base_x**i) # Convert each number to decimal - res += element # Add element to result + # Convert each number to decimal + element = int(decimal) * (base_x**i) + # Add element to result + res += element i += -1 # Return total result @@ -35,22 +42,29 @@ def Con_Dec_to_Base_Y(num, base_y): res_int = [] while int(integeral_part) != 0: integeral_part = integeral_part / base_y # Divide number by base - element = (integeral_part - int(integeral_part)) * base_y # Get the remainder - res_int.append(str(int(element))) # Append element - res_int = res_int[::-1] # Numbers are organised from LCM to HCM + element = (integeral_part - int(integeral_part)) * \ + base_y # Get the remainder + # Append element + res_int.append(str(int(element))) + # Numbers are organised from LCM to HCM + res_int = res_int[::-1] # Converting the decimal part decimal_part = num - int(num) res_dec = [] while (decimal_part != 0): - decimal_part = (decimal_part - int(decimal_part)) * base_y # Multiply decimal part by base - if str(int(decimal_part)) in res_dec: # Check if not duplicated, for no infinite loops + decimal_part = (decimal_part - int(decimal_part)) * \ + base_y # Multiply decimal part by base + # Check if not duplicated, for no infinite loops + if str(int(decimal_part)) in res_dec: break - res_dec.append(str(int(decimal_part))) # Append element + # Append element + res_dec.append(str(int(decimal_part))) # Organize result if len(res_dec) == 0: - res = res_int # If result has decimal numbers + # If result has decimal numbers + res = res_int else: res = res_int + ["."] + res_dec # If not @@ -86,7 +100,7 @@ def Main(): SetStatusError() return # If same bases are entered - if base_x == base_y or base_x<2 or base_y<2: + if base_x == base_y or base_x < 2 or base_y < 2: Status["text"] = "Huh?! -_- " Status["fg"] = "orange" return @@ -112,46 +126,53 @@ def Main(): main_window.geometry("420x250") -# <----- Elements for number that is going to be converted -----> -Num_Label = Label(main_window, text="Enter Number :", anchor=E, font=("Calibri", 9)) -Num_Label.place(x=30,y=30) +# <----- Elements for number that is going to be converted -----> +Num_Label = Label(main_window, text="Enter Number :", + anchor=E, font=("Calibri", 9)) +Num_Label.place(x=30, y=30) Num_Val = StringVar() Num = Entry(main_window, textvariable=Num_Val, font=("Calibri", 9)) -Num.place(x=120,y=32) +Num.place(x=120, y=32) # <----- Elements for Base-X -----> -Base_X_Label = Label(main_window, text="Base-X :", anchor=E, font=("Calibri", 9)) -Base_X_Label.place(x=250,y=30) +Base_X_Label = Label(main_window, text="Base-X :", + anchor=E, font=("Calibri", 9)) +Base_X_Label.place(x=250, y=30) Base_X_Val = StringVar() Base_X = Entry(main_window, textvariable=Base_X_Val, font=("Calibri", 9)) -Base_X.place(x=305,y=32,width=30) +Base_X.place(x=305, y=32, width=30) # <----- Elements for Base-Y -----> -Base_Y_Label = Label(main_window, text="Base-Y :", anchor=E, font=("Calibri", 9)) -Base_Y_Label.place(x=250,y=50) +Base_Y_Label = Label(main_window, text="Base-Y :", + anchor=E, font=("Calibri", 9)) +Base_Y_Label.place(x=250, y=50) Base_Y_Val = StringVar() Base_Y = Entry(main_window, textvariable=Base_Y_Val, font=("Calibri", 9)) -Base_Y.place(x=305,y=52,width=30) +Base_Y.place(x=305, y=52, width=30) # <----- Elements for calculate button -----> -Calculate_Button = Button(main_window, text="Convert", font=("Calibri", 9), command=Main) -Calculate_Button.place(x=180,y=75,width=80) +Calculate_Button = Button(main_window, text="Convert", + font=("Calibri", 9), command=Main) +Calculate_Button.place(x=180, y=75, width=80) # <----- Elements for Result -----> -Result_Label = Label(main_window, text="Result :", anchor=E, font=("Calibri", 9)) -Result_Label.place(x=100,y=130) +Result_Label = Label(main_window, text="Result :", + anchor=E, font=("Calibri", 9)) +Result_Label.place(x=100, y=130) Result_Entry_Val = StringVar() -Result_Entry = Entry(main_window, textvariable=Result_Entry_Val, font=("Calibri", 9)) +Result_Entry = Entry( + main_window, textvariable=Result_Entry_Val, font=("Calibri", 9)) Result_Entry.configure(state='readonly') -Result_Entry.place(x=150,y=130) +Result_Entry.place(x=150, y=130) # <----- Elements for Status Bar -----> -Status = Label(main_window, text="Hello!! :D", fg="green", font=("Calibri", 9), bd=1, relief=SUNKEN, anchor=W, padx=3) +Status = Label(main_window, text="Hello!! :D", fg="green", font=( + "Calibri", 9), bd=1, relief=SUNKEN, anchor=W, padx=3) Status.pack(side=BOTTOM, fill=X) diff --git a/Battery-Notification/Battery-Notification.py b/Battery-Notification/Battery-Notification.py index c7ea7c630a..1db16c6920 100644 --- a/Battery-Notification/Battery-Notification.py +++ b/Battery-Notification/Battery-Notification.py @@ -7,13 +7,13 @@ battery = psutil.sensors_battery() percent = battery.percent -while(True): +while (True): battery = psutil.sensors_battery() 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 - if(diff >= threshold): + if (diff >= threshold): notification.notify( title="Battery Percentage", message=str(cur_per) + "% Battery Remaining", diff --git a/Beat-Board/beatBoard.py b/Beat-Board/beatBoard.py index 6da0c34c06..d666275260 100644 --- a/Beat-Board/beatBoard.py +++ b/Beat-Board/beatBoard.py @@ -10,24 +10,24 @@ def __init__(self, soundLocation): def given_sound(self): playsound(self.soundLocation) - def play_sound(self,event): + def play_sound(self, event): sound = Thread(target=self.given_sound) sound.start() # All the locations of the sounds -kickLocation = './Beat-Board/Sounds/Kick.wav' +kickLocation = './Beat-Board/Sounds/Kick.wav' hiHatLocation = './Beat-Board/Sounds/hiHat.wav' snareLocation = './Beat-Board/Sounds/snare.wav' -pad1Location = './Beat-Board/Sounds/Pad1.wav' -pad2Location = './Beat-Board/Sounds/Pad2.wav' -pad3Location = './Beat-Board/Sounds/Pad3.wav' -pad4Location = './Beat-Board/Sounds/Pad4.wav' -pad5Location = './Beat-Board/Sounds/Pad5.wav' -pad6Location = './Beat-Board/Sounds/Pad6.wav' +pad1Location = './Beat-Board/Sounds/Pad1.wav' +pad2Location = './Beat-Board/Sounds/Pad2.wav' +pad3Location = './Beat-Board/Sounds/Pad3.wav' +pad4Location = './Beat-Board/Sounds/Pad4.wav' +pad5Location = './Beat-Board/Sounds/Pad5.wav' +pad6Location = './Beat-Board/Sounds/Pad6.wav' # Create drum objects -kickDrum = padSound(kickLocation) +kickDrum = padSound(kickLocation) hiHatDrum = padSound(hiHatLocation) snareDrum = padSound(snareLocation) @@ -39,6 +39,7 @@ def play_sound(self,event): pad5 = padSound(pad5Location) pad6 = padSound(pad6Location) + def create_layout(): # Creates the Frame @@ -111,7 +112,7 @@ def create_layout(): main_window = Tk() -main_window.resizable(False,False) +main_window.resizable(False, False) main_window.title('Beat Board') create_layout() main_window.mainloop() diff --git a/Binary-Calculator-GUI/script.py b/Binary-Calculator-GUI/script.py index 15abfd47d2..215b8cb45d 100644 --- a/Binary-Calculator-GUI/script.py +++ b/Binary-Calculator-GUI/script.py @@ -5,21 +5,29 @@ window.resizable(0, 0) # Function to clear the entry field + + def f1(): s = e1_val.get() e1.delete(first=0, last=len(s)) # Function to add "1" to the entry field + + def f2(): s = e1_val.get() e1.insert(END, "1") # Function to add "0" to the entry field + + def f3(): s = e1_val.get() e1.insert(END, "0") # Function to evaluate the expression and display the result + + def f4(): s = e1_val.get() result = evaluate_expression(s) @@ -27,22 +35,32 @@ def f4(): e1.insert(END, result) # Function to add "+" operator to the entry field + + def f5(): e1.insert(END, "+") # Function to add "-" operator to the entry field + + def f6(): e1.insert(END, "-") # Function to add "/" operator to the entry field + + def f7(): e1.insert(END, "/") # Function to add "X" operator to the entry field + + def f8(): e1.insert(END, "X") # Function to negate the sign of the number in the entry field + + def negate(): s = e1_val.get() if s.startswith("-"): @@ -51,11 +69,15 @@ def negate(): e1_val.set("-" + s) # Function to delete the last character in the entry field + + def backspace(): s = e1_val.get() e1_val.set(s[:-1]) # Function to convert binary to decimal + + def binary_to_decimal(n): num = n dec_value = 0 @@ -69,6 +91,8 @@ def binary_to_decimal(n): return dec_value # Function to convert decimal to binary + + def decimal_to_binary(n): if n == 0: return '0' @@ -79,6 +103,8 @@ def decimal_to_binary(n): return binary # Function to evaluate the expression + + def evaluate_expression(expression): x = 0 s = expression @@ -101,6 +127,8 @@ def evaluate_expression(expression): return "" # Function to perform binary addition + + def add(x, y): a = binary_to_decimal(x) b = binary_to_decimal(y) @@ -109,6 +137,8 @@ def add(x, y): return d # Function to perform binary subtraction + + def sub(x, y): a = binary_to_decimal(x) b = binary_to_decimal(y) @@ -116,6 +146,7 @@ def sub(x, y): d = decimal_to_binary(c) return d + # Creating a StringVar to store the value of the entry field e1_val = StringVar() @@ -158,22 +189,29 @@ def sub(x, y): bbackspace = Button(window, text="⌫", width=8, height=2, command=backspace) bbackspace.grid(row=3, column=1) -bbinary = Button(window, text="Bin to Dec", width=12, height=2, command=on_binary) +bbinary = Button(window, text="Bin to Dec", width=12, + height=2, command=on_binary) bbinary.grid(row=3, column=2) -bdecimal = Button(window, text="Dec to Bin", width=12, height=2, command=on_decimal) +bdecimal = Button(window, text="Dec to Bin", width=12, + height=2, command=on_decimal) bdecimal.grid(row=3, column=3) # Function to convert binary to decimal and update entry field + + def on_binary(): s = e1_val.get() decimal = binary_to_decimal(s) e1_val.set(decimal_to_binary(decimal)) # Function to convert decimal to binary and update entry field + + def on_decimal(): s = e1_val.get() binary = decimal_to_binary(int(s)) e1_val.set(binary) + window.mainloop() diff --git a/Birthday Wisher Bot/main.py b/Birthday Wisher Bot/main.py index 64556efc96..0bd8314e75 100644 --- a/Birthday Wisher Bot/main.py +++ b/Birthday Wisher Bot/main.py @@ -2,21 +2,22 @@ from datetime import datetime as dt import random import pandas as pd -my_mail="your email" -password="your application password" +my_mail = "your email" +password = "your application password" -file=pd.read_csv("./birthday.csv") -data=pd.DataFrame(file).set_index("name") -date=dt.now() -today=f"{date.month}-{date.day}" -for index,row in data.iterrows(): - birth_day=(f"{row.month}-{row.day}") - if(today==today): - with open(f"./letter_{random.randint(1,3)}.txt",mode="r") as wish_file: - contents=wish_file.read() - output=contents.replace('[NAME]',row.name) - with smtplib.SMTP("smtp.gmail.com",port=587) as connection: +file = pd.read_csv("./birthday.csv") +data = pd.DataFrame(file).set_index("name") +date = dt.now() +today = f"{date.month}-{date.day}" +for index, row in data.iterrows(): + birth_day = (f"{row.month}-{row.day}") + if (today == today): + with open(f"./letter_{random.randint(1,3)}.txt", mode="r") as wish_file: + contents = wish_file.read() + output = contents.replace('[NAME]', row.name) + with smtplib.SMTP("smtp.gmail.com", port=587) as connection: connection.starttls() - connection.login(user=my_mail,password=password) - connection.sendmail(from_addr=my_mail,to_addrs=row.email,msg=f"Subject:Happy Birthday\n\n{output}") + connection.login(user=my_mail, password=password) + connection.sendmail( + from_addr=my_mail, to_addrs=row.email, msg=f"Subject:Happy Birthday\n\n{output}") connection.close() diff --git a/Blood Alcohol Content/Blood_Alcohol_Content.py b/Blood Alcohol Content/Blood_Alcohol_Content.py index 2900fe3f4a..d9209a967f 100644 --- a/Blood Alcohol Content/Blood_Alcohol_Content.py +++ b/Blood Alcohol Content/Blood_Alcohol_Content.py @@ -1,34 +1,41 @@ class BAC(object): - def __init__(self,weight, time, vol, amount, gender): + def __init__(self, weight, time, vol, amount, gender): self.weight = weight - self.time = time + self.time = time self.vol = vol self.amount = amount - self.gender = gender - self.std = 0.0068 + self.gender = gender + self.std = 0.0068 + def standard_drink(self): return round((self.std * self.vol) * self.amount, 2) + def promille_man(self): return round((self.standard_drink() * 12) / ((self.weight*1.7) - (0.15*self.time)), 2) + def promille_woman(self): return round((self.standard_drink() * 12) / ((self.weight*1.6) - (0.15*self.time)), 2) - def result(self): if self.gender == 'woman': - print(f'\nAs a woman who have had {self.amount} cl. of {self.vol}% vol, {self.time} hour ago.') - print(f'You`ve had {self.standard_drink()} drinks,which gives you a {self.promille_woman()}% BAC\n') + print( + f'\nAs a woman who have had {self.amount} cl. of {self.vol}% vol, {self.time} hour ago.') + print( + f'You`ve had {self.standard_drink()} drinks,which gives you a {self.promille_woman()}% BAC\n') elif self.gender == 'man': - print(f'\nAs a man who have had {self.amount} cl. of {self.vol}% vol, {self.time} hour ago.') - print(f'You`ve had {self.standard_drink()} drinks,which gives you a {self.promille_man()}% BAC\n') + print( + f'\nAs a man who have had {self.amount} cl. of {self.vol}% vol, {self.time} hour ago.') + print( + f'You`ve had {self.standard_drink()} drinks,which gives you a {self.promille_man()}% BAC\n') else: print("Fault.") + if __name__ == "__main__": weight = int(input("Weight of the patient in kg: ")) time = int(input("Enter the time of drink (in hour only): ")) - vol = float(input("Volume percent of alcohol in the drink:")) + vol = float(input("Volume percent of alcohol in the drink:")) amount = int(input("Enter the amount the you drank: ")) gender = str(input("You are man or woman: ")) - BAC(weight,time,vol,amount,gender).result() + BAC(weight, time, vol, amount, gender).result() diff --git a/Blur an Image/BlurImage.py b/Blur an Image/BlurImage.py index b9a55b15d3..5e5d56ebf1 100644 --- a/Blur an Image/BlurImage.py +++ b/Blur an Image/BlurImage.py @@ -4,15 +4,16 @@ import tkinter as tk import cv2 -window=tk.Tk() +window = tk.Tk() window.title("Image Blur") window.geometry('350x200') -label = tk.Label(window, text="Choose an option").grid(row=0,column=1) +label = tk.Label(window, text="Choose an option").grid(row=0, column=1) + def blur1(): photo = askopenfilename() img = cv2.imread(photo) - avgblur = cv2.blur(img,(5,5)) + avgblur = cv2.blur(img, (5, 5)) cv2.imshow("Image", img) cv2.imshow("Average blur", avgblur) @@ -20,24 +21,27 @@ def blur1(): cv2.waitKey(0) cv2.destroyAllWindows() + def fx(x): - return + return + def blur2(): photo = askopenfilename() img = cv2.imread(photo) - - cv2.namedWindow("Gaussian Blur",cv2.WINDOW_NORMAL) - cv2.createTrackbar("kernelSize",'Gaussian Blur',1,7,fx) # we want trackbar to not call any function + cv2.namedWindow("Gaussian Blur", cv2.WINDOW_NORMAL) + + # we want trackbar to not call any function + cv2.createTrackbar("kernelSize", 'Gaussian Blur', 1, 7, fx) # thus calling an empty function - g = cv2.getTrackbarPos("kernelSize",'Gaussian Blur') + g = cv2.getTrackbarPos("kernelSize", 'Gaussian Blur') - if g==3 or g==5 or g==7: # kernel size must be positive odd values - gaussblur = cv2.GaussianBlur(img,(g,g),0) + if g == 3 or g == 5 or g == 7: # kernel size must be positive odd values + gaussblur = cv2.GaussianBlur(img, (g, g), 0) else: - gaussblur = cv2.GaussianBlur(img,(3,3),0) + gaussblur = cv2.GaussianBlur(img, (3, 3), 0) cv2.imshow("Image", img) cv2.imshow("Gaussian Blur", gaussblur) @@ -45,10 +49,11 @@ def blur2(): cv2.waitKey(0) cv2.destroyAllWindows() + def blur3(): photo = askopenfilename() img = cv2.imread(photo) - medianblur = cv2.medianBlur(img,5) + medianblur = cv2.medianBlur(img, 5) cv2.imshow("Image", img) cv2.imshow("Median blur", medianblur) @@ -57,12 +62,12 @@ def blur3(): cv2.destroyAllWindows() -rad1 = tk.Radiobutton(window,text='average blur', value=1, command=blur1) -rad2 = tk.Radiobutton(window,text='gaussian blur', value=2, command=blur2) -rad3 = tk.Radiobutton(window,text='median blur', value=3, command=blur3) +rad1 = tk.Radiobutton(window, text='average blur', value=1, command=blur1) +rad2 = tk.Radiobutton(window, text='gaussian blur', value=2, command=blur2) +rad3 = tk.Radiobutton(window, text='median blur', value=3, command=blur3) -rad1.grid(row=1,column=0) -rad2.grid(row=1,column=1) -rad3.grid(row=1,column=2) +rad1.grid(row=1, column=0) +rad2.grid(row=1, column=1) +rad3.grid(row=1, column=2) window.mainloop() diff --git a/Book_Scraper/book.py b/Book_Scraper/book.py index 5243de93ee..aa09ff5801 100644 --- a/Book_Scraper/book.py +++ b/Book_Scraper/book.py @@ -10,24 +10,25 @@ import sys - def is_emoji(text): """This function returns True if there is an emoji in the given string else False""" return bool(emoji.get_emoji_regexp().search(text)) + def link_to_get(link): """This function will get the url of the image & book download direct link using the given link for book download""" response = requests.get(link) - th_html = bs(response.text , "html.parser") - td_all = th_html.find_all("td" ,id ="info") + th_html = bs(response.text, "html.parser") + td_all = th_html.find_all("td", id="info") td_all = td_all[0] td_a = td_all.find_all("a") link_href = td_a[1].get("href") - img_link_td = td_all.find("img" ,alt="cover") + img_link_td = td_all.find("img", alt="cover") img_link_src = img_link_td.get("src") img_link = f"http://library.lol{img_link_src}" return [link_href, img_link] + def book_get(name, mainres=100, results=5): """This function returns the list of books for the given name @@ -36,7 +37,7 @@ def book_get(name, mainres=100, results=5): 2. isbn of book 3. author of book 4. publisher of book - + mainres : 1. 25 2. 50 @@ -60,11 +61,11 @@ def book_get(name, mainres=100, results=5): url = f"http://libgen.is/search.php?req={name}&lg_topic=libgen&open=0&view=simple&res={mainres}&phrase=1&column=def" # print(url) response = requests.get(url) - bs_html = bs(response.text , "html.parser") + bs_html = bs(response.text, "html.parser") if "Search string must contain minimum 3 characters.." in bs_html.body: return "Error: Title Too Short" - + # scraping the site for response table = bs_html.find_all("table") table = table[2] @@ -72,9 +73,9 @@ def book_get(name, mainres=100, results=5): a = len(table_rows) table_rows.pop(0) # print(url, "\n\n") - if a > 1 : + if a > 1: counter = 1 - for i in table_rows : + for i in table_rows: if counter <= results: # make book list book_lst = [] @@ -86,7 +87,7 @@ def book_get(name, mainres=100, results=5): author = table_datas[1].get_text() # getting link to book link_row = table_datas[9] - a = link_row.find("a" , href = True) + a = link_row.find("a", href=True) link = a.get("href") # getting image url & direct book download link link_all = link_to_get(link) @@ -111,10 +112,10 @@ def book_get(name, mainres=100, results=5): book_lst.append(language) Books.append(book_lst) # print(f"\n\n\n{book_lst}\n\n\n") - counter+=1 - if len(Books) >=1 : + counter += 1 + if len(Books) >= 1: return Books - else : + else: return "Error: no results found" else: return "Error: no results found" @@ -124,6 +125,7 @@ def book_get(name, mainres=100, results=5): # for i in a : # print(f"\n\nName : {i[0]}\nAuthor : {i[1]}\nSize : {i[2]}\nFormat : {i[3]}\nLink : {i[4]}\nImage : {i[5]}\n\n") + def animate(): for c in itertools.cycle(['|', '/', '-', '\\']): if done: @@ -132,32 +134,34 @@ def animate(): sys.stdout.flush() time.sleep(0.1) + if __name__ == "__main__": print(pyfiglet.figlet_format("Book Scraper")) print("---------------------------------------------------------------") print("---------------------------------------------------------------") - while(True): + while (True): print("\nEnter your Choice: \n1 - Search Book\n2 - Exit") entry = int(input()) - if(entry == 1): + if (entry == 1): print("Enter name of book : ") book_name = input() # loading done = False - #here is the animation + # here is the animation t = threading.Thread(target=animate) t.start() books = book_get(book_name, 25, 5) done = True try: - for i in books : - print(f"\n\nName : {i[0]}\nAuthor : {i[1]}\nSize : {i[2]}\nFormat : {i[3]}\nLink : {i[4]}\nImage : {i[5]}\n") + for i in books: + print( + f"\n\nName : {i[0]}\nAuthor : {i[1]}\nSize : {i[2]}\nFormat : {i[3]}\nLink : {i[4]}\nImage : {i[5]}\n") except: - if(book_get == "Error: no results found"): + if (book_get == "Error: no results found"): print("Book not Found/n") - elif(book_get == "Error: Title Too Short"): + elif (book_get == "Error: Title Too Short"): print("Title too short/n") - elif(entry == 2): + elif (entry == 2): print(pyfiglet.figlet_format("Thank You for Using")) print("---------------------------------------------------------------") print("---------------------------------------------------------------") diff --git a/Bubble Shooter Game/bubbleshooter.py b/Bubble Shooter Game/bubbleshooter.py index 729c032a9d..08fb2573d2 100644 --- a/Bubble Shooter Game/bubbleshooter.py +++ b/Bubble Shooter Game/bubbleshooter.py @@ -363,12 +363,12 @@ def popflotrs(bbarr, cpyofbrd, col, row=0): 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 - 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) @@ -437,12 +437,12 @@ def stbb(bbarr, newbb, launchbb, score): 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): + 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): newRow = row - 1 newcol = col - if(bbarr[newRow][newcol] != blank): + if (bbarr[newRow][newcol] != blank): newRow = newRow + 1 bbarr[newRow][newcol] = copy.copy(newbb) bbarr[newRow][newcol].row = newRow @@ -457,10 +457,10 @@ def stbb(bbarr, newbb, launchbb, score): bbarr[newRow][newcol].col = newcol elif newbb.rect.centerx <= bbarr[row][col].rect.centerx: - if(row == 0 or row % 2 == 0): + if (row == 0 or row % 2 == 0): newRow = row - 1 newcol = col - 1 - if(bbarr[newRow][newcol] != blank): + if (bbarr[newRow][newcol] != blank): newRow = newRow + 1 bbarr[newRow][newcol] = copy.copy(newbb) bbarr[newRow][newcol].row = newRow @@ -469,7 +469,7 @@ def stbb(bbarr, newbb, launchbb, score): else: newRow = row - 1 newcol = col - if(bbarr[newRow][newcol] != blank): + if (bbarr[newRow][newcol] != blank): newRow = newRow + 1 bbarr[newRow][newcol] = copy.copy(newbb) bbarr[newRow][newcol].row = newRow @@ -477,7 +477,7 @@ def stbb(bbarr, newbb, launchbb, score): popbb(bbarr, newRow, newcol, newbb.color, dellst) - if(len(dellst) >= 3): + if (len(dellst) >= 3): for pos in dellst: popSound.play() row = pos[0] @@ -508,22 +508,22 @@ def addbbtotop(bbarr, bubble): def popbb(bbarr, row, col, color, dellst): - if(row < 0 or col < 0 or row > (len(bbarr)-1) or col > (len(bbarr[0])-1)): + if (row < 0 or col < 0 or row > (len(bbarr)-1) or col > (len(bbarr[0])-1)): return elif (bbarr[row][col] == blank): return - elif(bbarr[row][col].color != color): + elif (bbarr[row][col].color != color): return for bubble in dellst: - if(bbarr[bubble[0]][bubble[1]] == bbarr[row][col]): + if (bbarr[bubble[0]][bubble[1]] == bbarr[row][col]): return dellst.append((row, col)) - if(row == 0): + 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) - elif(row % 2 == 0): + 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) @@ -543,7 +543,7 @@ def popbb(bbarr, row, col, color, dellst): def drawbbary(array): for row in range(aryhgt): for col in range(len(array[row])): - if(array[row][col] != blank): + if (array[row][col] != blank): array[row][col].draw() @@ -582,12 +582,12 @@ def endScreen(score, winorlose): while True: for event in pygame.event.get(): - if(event.type == QUIT): + if (event.type == QUIT): terminate() - elif(event.type == KEYUP): - if(event.key == K_RETURN): + elif (event.type == KEYUP): + if (event.key == K_RETURN): return - elif(event.key == K_ESCAPE): + elif (event.key == K_ESCAPE): terminate() diff --git a/Bubble-Sort-Visualization/bubble_sort.py b/Bubble-Sort-Visualization/bubble_sort.py index e260b074e4..2a98eaff79 100644 --- a/Bubble-Sort-Visualization/bubble_sort.py +++ b/Bubble-Sort-Visualization/bubble_sort.py @@ -53,7 +53,7 @@ def generate_array(): size_val = int(size_value.get()) max_val = int(max_value.get()) - if(min_val > max_val): + if (min_val > max_val): messagebox.showwarning( message="Max. value should not be less than Min. value") min_val, max_val = max_val, min_val diff --git a/CPU temperature/temp.py b/CPU temperature/temp.py index 77dd4256bf..5d7b139dce 100644 --- a/CPU temperature/temp.py +++ b/CPU temperature/temp.py @@ -1,6 +1,8 @@ import psutil # Function to retrieve CPU temperature + + def get_cpu_temperature() -> float | str: """A function which returns the temperature of the CPU @@ -16,6 +18,7 @@ def get_cpu_temperature() -> float | str: # Handle cases where temperature information is not available return "NA" + def get_ram_and_cpu_util() -> list: """Get the utilization of system RAM and CPU @@ -24,26 +27,28 @@ def get_ram_and_cpu_util() -> list: """ memory_stats = psutil.virtual_memory() return [ - memory_stats[0]//(1024*1024), #Total memory available in the system (MB) - memory_stats[2], #Percentage of memory utilized - psutil.cpu_percent(interval=4, percpu=True) #Percentage of CPU utilized - ] + # Total memory available in the system (MB) + memory_stats[0]//(1024*1024), + memory_stats[2], # Percentage of memory utilized + # Percentage of CPU utilized + psutil.cpu_percent(interval=4, percpu=True) + ] # Call the get_cpu_temperature() function to get the CPU temperature cpu_temperature = get_cpu_temperature() -#Call the get_ram_and_cpu_util() function to get data on system resource utilization +# Call the get_ram_and_cpu_util() function to get data on system resource utilization system_utils = get_ram_and_cpu_util() # Print the system info -if(type(system_utils[2]) == list): +if (type(system_utils[2]) == list): cpu_percentage = "" for i in system_utils[2]: cpu_percentage += "{}%, ".format(i) else: - cpu_percentage = '{}%'.format(system_utils[2]) + cpu_percentage = '{}%'.format(system_utils[2]) -print(f"Current CPU Temperature in Celsius is {cpu_temperature}°C, with percentage utilized being at {cpu_percentage}") +print( + f"Current CPU Temperature in Celsius is {cpu_temperature}°C, with percentage utilized being at {cpu_percentage}") print(f"Current RAM utilization is {system_utils[1]}% of {system_utils[0]} MB") - diff --git a/CSV-To-Excel/CSV-To-Excel.py b/CSV-To-Excel/CSV-To-Excel.py index 46260edde4..38aea98c85 100644 --- a/CSV-To-Excel/CSV-To-Excel.py +++ b/CSV-To-Excel/CSV-To-Excel.py @@ -4,7 +4,7 @@ import openpyxl import sys -#inputs +# inputs print("This programme writes the data in any Comma-separated value file (such as: .csv or .data) to a Excel file.") print("The input and output files must be in the same directory of the python file for the programme to work.\n") @@ -13,37 +13,37 @@ excel_name = input("Name of the excel file for output (with the extension): ") sheet_name = input("Name of the excel sheet for output: ") -#opening the files +# opening the files try: wb = openpyxl.load_workbook(excel_name) sheet = wb.get_sheet_by_name(sheet_name) - file = open(csv_name,"r",encoding = "utf-8") + file = open(csv_name, "r", encoding="utf-8") except: print("File Error!") sys.exit() -#rows and columns +# rows and columns row = 1 column = 1 -#for each line in the file +# for each line in the file for line in file: - #remove the \n from the line and make it a list with the separator + # remove the \n from the line and make it a list with the separator line = line[:-1] line = line.split(sep) - #for each data in the line + # for each data in the line for data in line: - #write the data to the cell - sheet.cell(row,column).value = data - #after each data column number increases by 1 + # write the data to the cell + sheet.cell(row, column).value = data + # after each data column number increases by 1 column += 1 - #to write the next line column number is set to 1 and row number is increased by 1 + # to write the next line column number is set to 1 and row number is increased by 1 column = 1 row += 1 -#saving the excel file and closing the csv file +# saving the excel file and closing the csv file wb.save(excel_name) -file.close() \ No newline at end of file +file.close() diff --git a/CSVtoJSON script/CSVtoJSON.py b/CSVtoJSON script/CSVtoJSON.py index 11dcc7c352..f9e8148ebc 100644 --- a/CSVtoJSON script/CSVtoJSON.py +++ b/CSVtoJSON script/CSVtoJSON.py @@ -1,19 +1,21 @@ import csv import json + def csv_to_json(csv_file, json_file): # Open the CSV file with open(csv_file, 'r') as file: # Read the CSV data csv_data = csv.DictReader(file) - + # Convert CSV to JSON json_data = json.dumps(list(csv_data), indent=4) - + # Write the JSON data to a file with open(json_file, 'w') as json_file: json_file.write(json_data) + # Specify the CSV and JSON file paths csv_file = 'input.csv' json_file = 'output.json' diff --git a/Changing_Wall_Paper_using_python/Changing_Wall_Paper.py b/Changing_Wall_Paper_using_python/Changing_Wall_Paper.py index 0b0a0224e1..7b4d8ac53e 100644 --- a/Changing_Wall_Paper_using_python/Changing_Wall_Paper.py +++ b/Changing_Wall_Paper_using_python/Changing_Wall_Paper.py @@ -4,28 +4,30 @@ from wallpaper import set_wallpaper # user define function + + def change_wall(): - # set your photo - try: - set_wallpaper(str(path.get())) - check = "success" + # set your photo + try: + set_wallpaper(str(path.get())) + check = "success" - except: + except: - check = "Wallpaper not found !" - result.set(check) + check = "Wallpaper not found !" + result.set(check) def browseFiles(): - filename = filedialog.askopenfilename(initialdir="/", - title="Select a File", - filetypes=(("jpeg files", "*.jpg"), ("all files", "*.*"))) - path.set(filename) - - # Change label contents - label_file_explorer.configure(text="File Opened: "+filename) - return filename + filename = filedialog.askopenfilename(initialdir="/", + title="Select a File", + filetypes=(("jpeg files", "*.jpg"), ("all files", "*.*"))) + path.set(filename) + + # Change label contents + label_file_explorer.configure(text="File Opened: "+filename) + return filename # object of tkinter @@ -39,7 +41,7 @@ def browseFiles(): label_file_explorer = Label( - master, text="Select a image", width=100, fg="blue") + master, text="Select a image", width=100, fg="blue") # Creating label for each information @@ -51,7 +53,7 @@ def browseFiles(): # Creating label for class variable # name using widget Entry Label(master, text="", textvariable=result, - bg="light grey").grid(row=3, column=1, sticky=W) + bg="light grey").grid(row=3, column=1, sticky=W) # creating a button using the widget # Button that will call the submit function diff --git a/Check_External_IP/Check_IP.py b/Check_External_IP/Check_IP.py index ab454e2ddb..8c09e729ce 100644 --- a/Check_External_IP/Check_IP.py +++ b/Check_External_IP/Check_IP.py @@ -9,4 +9,4 @@ _result = request.text.split(': ', 1)[1] your_ip = _result.split('', 1)[0] -print(your_ip) \ No newline at end of file +print(your_ip) diff --git a/Chess-Game/main.py b/Chess-Game/main.py index b6595b23a7..3ac967aecf 100644 --- a/Chess-Game/main.py +++ b/Chess-Game/main.py @@ -78,11 +78,13 @@ white_pawn = pygame.transform.scale(white_pawn, (65, 65)) white_pawn_small = pygame.transform.scale(white_pawn, (45, 45)) -white_images = [white_pawn, white_queen, white_king, white_knight, white_rook, white_bishop] +white_images = [white_pawn, white_queen, white_king, + white_knight, white_rook, white_bishop] small_white_images = [white_pawn_small, white_queen_small, white_king_small, white_knight_small, white_rook_small, white_bishop_small] -black_images = [black_pawn, black_queen, black_king, black_knight, black_rook, black_bishop] +black_images = [black_pawn, black_queen, black_king, + black_knight, black_rook, black_bishop] small_black_images = [black_pawn_small, black_queen_small, black_king_small, black_knight_small, black_rook_small, black_bishop_small] @@ -100,15 +102,18 @@ def draw_board(): column = i % 4 row = i // 4 if row % 2 == 0: - pygame.draw.rect(screen, 'light gray', [600 - (column * 200), row * 100, 100, 100]) + pygame.draw.rect(screen, 'light gray', [ + 600 - (column * 200), row * 100, 100, 100]) else: - pygame.draw.rect(screen, 'light gray', [700 - (column * 200), row * 100, 100, 100]) + pygame.draw.rect(screen, 'light gray', [ + 700 - (column * 200), row * 100, 100, 100]) pygame.draw.rect(screen, 'gray', [0, 800, WIDTH, 100]) pygame.draw.rect(screen, 'gold', [0, 800, WIDTH, 100], 5) pygame.draw.rect(screen, 'gold', [800, 0, 200, HEIGHT], 5) status_text = ['White: Select a Piece to Move!', 'White: Select a Destination!', 'Black: Select a Piece to Move!', 'Black: Select a Destination!'] - screen.blit(big_font.render(status_text[turn_step], True, 'black'), (20, 820)) + screen.blit(big_font.render( + status_text[turn_step], True, 'black'), (20, 820)) for i in range(9): pygame.draw.line(screen, 'black', (0, 100 * i), (800, 100 * i), 2) pygame.draw.line(screen, 'black', (100 * i, 0), (100 * i, 800), 2) @@ -120,9 +125,11 @@ def draw_pieces(): for i in range(len(white_pieces)): index = piece_list.index(white_pieces[i]) if white_pieces[i] == 'pawn': - screen.blit(white_pawn, (white_locations[i][0] * 100 + 22, white_locations[i][1] * 100 + 30)) + screen.blit( + white_pawn, (white_locations[i][0] * 100 + 22, white_locations[i][1] * 100 + 30)) else: - screen.blit(white_images[index], (white_locations[i][0] * 100 + 10, white_locations[i][1] * 100 + 10)) + screen.blit(white_images[index], (white_locations[i] + [0] * 100 + 10, white_locations[i][1] * 100 + 10)) if turn_step < 2: if selection == i: pygame.draw.rect(screen, 'red', [white_locations[i][0] * 100 + 1, white_locations[i][1] * 100 + 1, @@ -131,9 +138,11 @@ def draw_pieces(): for i in range(len(black_pieces)): index = piece_list.index(black_pieces[i]) if black_pieces[i] == 'pawn': - screen.blit(black_pawn, (black_locations[i][0] * 100 + 22, black_locations[i][1] * 100 + 30)) + screen.blit( + black_pawn, (black_locations[i][0] * 100 + 22, black_locations[i][1] * 100 + 30)) else: - screen.blit(black_images[index], (black_locations[i][0] * 100 + 10, black_locations[i][1] * 100 + 10)) + screen.blit(black_images[index], (black_locations[i] + [0] * 100 + 10, black_locations[i][1] * 100 + 10)) if turn_step >= 2: if selection == i: pygame.draw.rect(screen, 'blue', [black_locations[i][0] * 100 + 1, black_locations[i][1] * 100 + 1, @@ -173,7 +182,8 @@ def check_king(position, color): friends_list = black_locations enemies_list = white_locations # 8 squares to check for kings, they can go one square any direction - targets = [(1, 0), (1, 1), (1, -1), (-1, 0), (-1, 1), (-1, -1), (0, 1), (0, -1)] + targets = [(1, 0), (1, 1), (1, -1), (-1, 0), + (-1, 1), (-1, -1), (0, 1), (0, -1)] for i in range(8): target = (position[0] + targets[i][0], position[1] + targets[i][1]) if target not in friends_list and 0 <= target[0] <= 7 and 0 <= target[1] <= 7: @@ -217,7 +227,8 @@ def check_bishop(position, color): while path: if (position[0] + (chain * x), position[1] + (chain * y)) not in friends_list and \ 0 <= position[0] + (chain * x) <= 7 and 0 <= position[1] + (chain * y) <= 7: - moves_list.append((position[0] + (chain * x), position[1] + (chain * y))) + moves_list.append( + (position[0] + (chain * x), position[1] + (chain * y))) if (position[0] + (chain * x), position[1] + (chain * y)) in enemies_list: path = False chain += 1 @@ -253,7 +264,8 @@ def check_rook(position, color): while path: if (position[0] + (chain * x), position[1] + (chain * y)) not in friends_list and \ 0 <= position[0] + (chain * x) <= 7 and 0 <= position[1] + (chain * y) <= 7: - moves_list.append((position[0] + (chain * x), position[1] + (chain * y))) + moves_list.append( + (position[0] + (chain * x), position[1] + (chain * y))) if (position[0] + (chain * x), position[1] + (chain * y)) in enemies_list: path = False chain += 1 @@ -300,7 +312,8 @@ def check_knight(position, color): friends_list = black_locations enemies_list = white_locations # 8 squares to check for knights, they can go two squares in one direction and one in another - targets = [(1, 2), (1, -2), (2, 1), (2, -1), (-1, 2), (-1, -2), (-2, 1), (-2, -1)] + targets = [(1, 2), (1, -2), (2, 1), (2, -1), + (-1, 2), (-1, -2), (-2, 1), (-2, -1)] for i in range(8): target = (position[0] + targets[i][0], position[1] + targets[i][1]) if target not in friends_list and 0 <= target[0] <= 7 and 0 <= target[1] <= 7: @@ -325,7 +338,8 @@ def draw_valid(moves): else: color = 'blue' for i in range(len(moves)): - pygame.draw.circle(screen, color, (moves[i][0] * 100 + 50, moves[i][1] * 100 + 50), 5) + pygame.draw.circle( + screen, color, (moves[i][0] * 100 + 50, moves[i][1] * 100 + 50), 5) # draw captured pieces on side of screen @@ -364,8 +378,10 @@ def draw_check(): def draw_game_over(): pygame.draw.rect(screen, 'black', [200, 200, 400, 70]) - screen.blit(font.render(f'{winner} won the game!', True, 'white'), (210, 210)) - screen.blit(font.render(f'Press ENTER to Restart!', True, 'white'), (210, 240)) + screen.blit(font.render( + f'{winner} won the game!', True, 'white'), (210, 210)) + screen.blit(font.render(f'Press ENTER to Restart!', + True, 'white'), (210, 240)) # main game loop @@ -410,8 +426,10 @@ def draw_game_over(): winner = 'white' black_pieces.pop(black_piece) black_locations.pop(black_piece) - black_options = check_options(black_pieces, black_locations, 'black') - white_options = check_options(white_pieces, white_locations, 'white') + black_options = check_options( + black_pieces, black_locations, 'black') + white_options = check_options( + white_pieces, white_locations, 'white') turn_step = 2 selection = 100 valid_moves = [] @@ -431,8 +449,10 @@ def draw_game_over(): winner = 'black' white_pieces.pop(white_piece) white_locations.pop(white_piece) - black_options = check_options(black_pieces, black_locations, 'black') - white_options = check_options(white_pieces, white_locations, 'white') + black_options = check_options( + black_pieces, black_locations, 'black') + white_options = check_options( + white_pieces, white_locations, 'white') turn_step = 0 selection = 100 valid_moves = [] @@ -453,8 +473,10 @@ def draw_game_over(): turn_step = 0 selection = 100 valid_moves = [] - black_options = check_options(black_pieces, black_locations, 'black') - white_options = check_options(white_pieces, white_locations, 'white') + black_options = check_options( + black_pieces, black_locations, 'black') + white_options = check_options( + white_pieces, white_locations, 'white') if winner != '': game_over = True diff --git a/Chinese_plate_scan/License-plate-recognition/CNN.py b/Chinese_plate_scan/License-plate-recognition/CNN.py index f53268057e..8820b9642e 100644 --- a/Chinese_plate_scan/License-plate-recognition/CNN.py +++ b/Chinese_plate_scan/License-plate-recognition/CNN.py @@ -22,30 +22,37 @@ def cnn_train(): X_train, y_train = [], [] for i in range(n): print("正在读取第%d张图片" % i) - img = cv2.imdecode(np.fromfile(path + pic_name[i], dtype=np.uint8), -1) # cv2.imshow无法读取中文路径图片,改用此方式 + # cv2.imshow无法读取中文路径图片,改用此方式 + img = cv2.imdecode(np.fromfile(path + pic_name[i], dtype=np.uint8), -1) label = [char_dict[name] for name in pic_name[i][0:7]] # 图片名前7位为车牌标签 X_train.append(img) y_train.append(label) X_train = np.array(X_train) - y_train = [np.array(y_train)[:, i] for i in range(7)] # y_train是长度为7的列表,其中每个都是shape为(n,)的ndarray,分别对应n张图片的第一个字符,第二个字符....第七个字符 + # y_train是长度为7的列表,其中每个都是shape为(n,)的ndarray,分别对应n张图片的第一个字符,第二个字符....第七个字符 + y_train = [np.array(y_train)[:, i] for i in range(7)] # cnn模型 Input = layers.Input((80, 240, 3)) # 车牌图片shape(80,240,3) x = Input - x = layers.Conv2D(filters=16, kernel_size=(3, 3), strides=1, padding='same', activation='relu')(x) + x = layers.Conv2D(filters=16, kernel_size=( + 3, 3), strides=1, padding='same', activation='relu')(x) x = layers.MaxPool2D(pool_size=(2, 2), padding='same', strides=2)(x) for i in range(3): - x = layers.Conv2D(filters=32 * 2 ** i, kernel_size=(3, 3), padding='valid', activation='relu')(x) - x = layers.Conv2D(filters=32 * 2 ** i, kernel_size=(3, 3), padding='valid', activation='relu')(x) + x = layers.Conv2D(filters=32 * 2 ** i, kernel_size=(3, 3), + padding='valid', activation='relu')(x) + x = layers.Conv2D(filters=32 * 2 ** i, kernel_size=(3, 3), + padding='valid', activation='relu')(x) x = layers.MaxPool2D(pool_size=(2, 2), padding='same', strides=2)(x) x = layers.Dropout(0.5)(x) x = layers.Flatten()(x) x = layers.Dropout(0.3)(x) - Output = [layers.Dense(65, activation='softmax', name='c%d' % (i + 1))(x) for i in range(7)] # 7个输出分别对应车牌7个字符,每个输出都为65个类别类概率 + Output = [layers.Dense(65, activation='softmax', name='c%d' % ( + i + 1))(x) for i in range(7)] # 7个输出分别对应车牌7个字符,每个输出都为65个类别类概率 model = models.Model(inputs=Input, outputs=Output) model.summary() model.compile(optimizer='adam', - loss='sparse_categorical_crossentropy', # y_train未进行one-hot编码,所以loss选择sparse_categorical_crossentropy + # y_train未进行one-hot编码,所以loss选择sparse_categorical_crossentropy + loss='sparse_categorical_crossentropy', metrics=['accuracy']) # 模型训练 @@ -62,9 +69,11 @@ def cnn_predict(cnn, Lic_img): "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] Lic_pred = [] for lic in Lic_img: - lic_pred = cnn.predict(lic.reshape(1, 80, 240, 3)) # 预测形状应为(1,80,240,3) + lic_pred = cnn.predict(lic.reshape( + 1, 80, 240, 3)) # 预测形状应为(1,80,240,3) lic_pred = np.array(lic_pred).reshape(7, 65) # 列表转为ndarray,形状为(7,65) - if len(lic_pred[lic_pred >= 0.8]) >= 4: # 统计其中预测概率值大于80%以上的个数,大于等于4个以上认为识别率高,识别成功 + # 统计其中预测概率值大于80%以上的个数,大于等于4个以上认为识别率高,识别成功 + if len(lic_pred[lic_pred >= 0.8]) >= 4: chars = '' for arg in np.argmax(lic_pred, axis=1): # 取每行中概率值最大的arg,将其转为字符 chars += characters[arg] diff --git a/Chinese_plate_scan/License-plate-recognition/UI.py b/Chinese_plate_scan/License-plate-recognition/UI.py index 95a0e97361..d842a38f52 100644 --- a/Chinese_plate_scan/License-plate-recognition/UI.py +++ b/Chinese_plate_scan/License-plate-recognition/UI.py @@ -20,34 +20,51 @@ def __init__(self, win, ww, wh): self.win.title("车牌定位,矫正和识别软件---by DuanshengLiu") self.img_src_path = None - self.label_src = Label(self.win, text='原图:', font=('微软雅黑', 13)).place(x=0, y=0) - self.label_lic1 = Label(self.win, text='车牌区域1:', font=('微软雅黑', 13)).place(x=615, y=0) - self.label_pred1 = Label(self.win, text='识别结果1:', font=('微软雅黑', 13)).place(x=615, y=85) - self.label_lic2 = Label(self.win, text='车牌区域2:', font=('微软雅黑', 13)).place(x=615, y=180) - self.label_pred2 = Label(self.win, text='识别结果2:', font=('微软雅黑', 13)).place(x=615, y=265) - self.label_lic3 = Label(self.win, text='车牌区域3:', font=('微软雅黑', 13)).place(x=615, y=360) - self.label_pred3 = Label(self.win, text='识别结果3:', font=('微软雅黑', 13)).place(x=615, y=445) + self.label_src = Label(self.win, text='原图:', + font=('微软雅黑', 13)).place(x=0, y=0) + self.label_lic1 = Label(self.win, text='车牌区域1:', + font=('微软雅黑', 13)).place(x=615, y=0) + self.label_pred1 = Label( + self.win, text='识别结果1:', font=('微软雅黑', 13)).place(x=615, y=85) + self.label_lic2 = Label(self.win, text='车牌区域2:', + font=('微软雅黑', 13)).place(x=615, y=180) + self.label_pred2 = Label(self.win, text='识别结果2:', font=( + '微软雅黑', 13)).place(x=615, y=265) + self.label_lic3 = Label(self.win, text='车牌区域3:', + font=('微软雅黑', 13)).place(x=615, y=360) + self.label_pred3 = Label(self.win, text='识别结果3:', font=( + '微软雅黑', 13)).place(x=615, y=445) - self.can_src = Canvas(self.win, width=512, height=512, bg='white', relief='solid', borderwidth=1) # 原图画布 + self.can_src = Canvas(self.win, width=512, height=512, + bg='white', relief='solid', borderwidth=1) # 原图画布 self.can_src.place(x=50, y=0) - self.can_lic1 = Canvas(self.win, width=245, height=85, bg='white', relief='solid', borderwidth=1) # 车牌区域1画布 + self.can_lic1 = Canvas(self.win, width=245, height=85, + bg='white', relief='solid', borderwidth=1) # 车牌区域1画布 self.can_lic1.place(x=710, y=0) - self.can_pred1 = Canvas(self.win, width=245, height=65, bg='white', relief='solid', borderwidth=1) # 车牌识别1画布 + self.can_pred1 = Canvas(self.win, width=245, height=65, + bg='white', relief='solid', borderwidth=1) # 车牌识别1画布 self.can_pred1.place(x=710, y=90) - self.can_lic2 = Canvas(self.win, width=245, height=85, bg='white', relief='solid', borderwidth=1) # 车牌区域2画布 + self.can_lic2 = Canvas(self.win, width=245, height=85, + bg='white', relief='solid', borderwidth=1) # 车牌区域2画布 self.can_lic2.place(x=710, y=175) - self.can_pred2 = Canvas(self.win, width=245, height=65, bg='white', relief='solid', borderwidth=1) # 车牌识别2画布 + self.can_pred2 = Canvas(self.win, width=245, height=65, + bg='white', relief='solid', borderwidth=1) # 车牌识别2画布 self.can_pred2.place(x=710, y=265) - self.can_lic3 = Canvas(self.win, width=245, height=85, bg='white', relief='solid', borderwidth=1) # 车牌区域3画布 + self.can_lic3 = Canvas(self.win, width=245, height=85, + bg='white', relief='solid', borderwidth=1) # 车牌区域3画布 self.can_lic3.place(x=710, y=350) - self.can_pred3 = Canvas(self.win, width=245, height=65, bg='white', relief='solid', borderwidth=1) # 车牌识别3画布 + self.can_pred3 = Canvas(self.win, width=245, height=65, + bg='white', relief='solid', borderwidth=1) # 车牌识别3画布 self.can_pred3.place(x=710, y=440) - self.button1 = Button(self.win, text='选择文件', width=10, height=1, command=self.load_show_img) # 选择文件按钮 + self.button1 = Button(self.win, text='选择文件', width=10, + height=1, command=self.load_show_img) # 选择文件按钮 self.button1.place(x=680, y=wh - 30) - self.button2 = Button(self.win, text='识别车牌', width=10, height=1, command=self.display) # 识别车牌按钮 + self.button2 = Button(self.win, text='识别车牌', width=10, + height=1, command=self.display) # 识别车牌按钮 self.button2.place(x=780, y=wh - 30) - self.button3 = Button(self.win, text='清空所有', width=10, height=1, command=self.clear) # 清空所有按钮 + self.button3 = Button(self.win, text='清空所有', + width=10, height=1, command=self.clear) # 清空所有按钮 self.button3.place(x=880, y=wh - 30) self.unet = keras.models.load_model('unet.h5') self.cnn = keras.models.load_model('cnn.h5') @@ -55,12 +72,12 @@ def __init__(self, win, ww, wh): cnn_predict(self.cnn, [np.zeros((80, 240, 3))]) print("已启动,开始识别吧!") - def load_show_img(self): self.clear() sv = StringVar() sv.set(askopenfilename()) - self.img_src_path = Entry(self.win, state='readonly', text=sv).get() # 获取到所打开的图片 + self.img_src_path = Entry( + self.win, state='readonly', text=sv).get() # 获取到所打开的图片 img_open = Image.open(self.img_src_path) if img_open.size[0] * img_open.size[1] > 240 * 80: img_open = img_open.resize((512, 512), Image.ANTIALIAS) @@ -69,40 +86,56 @@ def load_show_img(self): def display(self): if self.img_src_path == None: # 还没选择图片就进行预测 - self.can_pred1.create_text(32, 15, text='请选择图片', anchor='nw', font=('黑体', 28)) + self.can_pred1.create_text( + 32, 15, text='请选择图片', anchor='nw', font=('黑体', 28)) else: - img_src = cv2.imdecode(np.fromfile(self.img_src_path, dtype=np.uint8), -1) # 从中文路径读取时用 + img_src = cv2.imdecode(np.fromfile( + self.img_src_path, dtype=np.uint8), -1) # 从中文路径读取时用 h, w = img_src.shape[0], img_src.shape[1] if h * w <= 240 * 80 and 2 <= w / h <= 5: # 满足该条件说明可能整个图片就是一张车牌,无需定位,直接识别即可 - lic = cv2.resize(img_src, dsize=(240, 80), interpolation=cv2.INTER_AREA)[:, :, :3] # 直接resize为(240,80) + lic = cv2.resize(img_src, dsize=(240, 80), interpolation=cv2.INTER_AREA)[ + :, :, :3] # 直接resize为(240,80) img_src_copy, Lic_img = img_src, [lic] else: # 否则就需通过unet对img_src原图预测,得到img_mask,实现车牌定位,然后进行识别 img_src, img_mask = unet_predict(self.unet, self.img_src_path) - img_src_copy, Lic_img = locate_and_correct(img_src, img_mask) # 利用core.py中的locate_and_correct函数进行车牌定位和矫正 + # 利用core.py中的locate_and_correct函数进行车牌定位和矫正 + img_src_copy, Lic_img = locate_and_correct(img_src, img_mask) - Lic_pred = cnn_predict(self.cnn, Lic_img) # 利用cnn进行车牌的识别预测,Lic_pred中存的是元祖(车牌图片,识别结果) + # 利用cnn进行车牌的识别预测,Lic_pred中存的是元祖(车牌图片,识别结果) + Lic_pred = cnn_predict(self.cnn, Lic_img) if Lic_pred: - img = Image.fromarray(img_src_copy[:, :, ::-1]) # img_src_copy[:, :, ::-1]将BGR转为RGB + # img_src_copy[:, :, ::-1]将BGR转为RGB + img = Image.fromarray(img_src_copy[:, :, ::-1]) self.img_Tk = ImageTk.PhotoImage(img) self.can_src.delete('all') # 显示前,先清空画板 self.can_src.create_image(258, 258, image=self.img_Tk, anchor='center') # img_src_copy上绘制出了定位的车牌轮廓,将其显示在画板上 for i, lic_pred in enumerate(Lic_pred): if i == 0: - self.lic_Tk1 = ImageTk.PhotoImage(Image.fromarray(lic_pred[0][:, :, ::-1])) - self.can_lic1.create_image(5, 5, image=self.lic_Tk1, anchor='nw') - self.can_pred1.create_text(35, 15, text=lic_pred[1], anchor='nw', font=('黑体', 28)) + self.lic_Tk1 = ImageTk.PhotoImage( + Image.fromarray(lic_pred[0][:, :, ::-1])) + self.can_lic1.create_image( + 5, 5, image=self.lic_Tk1, anchor='nw') + self.can_pred1.create_text( + 35, 15, text=lic_pred[1], anchor='nw', font=('黑体', 28)) elif i == 1: - self.lic_Tk2 = ImageTk.PhotoImage(Image.fromarray(lic_pred[0][:, :, ::-1])) - self.can_lic2.create_image(5, 5, image=self.lic_Tk2, anchor='nw') - self.can_pred2.create_text(40, 15, text=lic_pred[1], anchor='nw', font=('黑体', 28)) + self.lic_Tk2 = ImageTk.PhotoImage( + Image.fromarray(lic_pred[0][:, :, ::-1])) + self.can_lic2.create_image( + 5, 5, image=self.lic_Tk2, anchor='nw') + self.can_pred2.create_text( + 40, 15, text=lic_pred[1], anchor='nw', font=('黑体', 28)) elif i == 2: - self.lic_Tk3 = ImageTk.PhotoImage(Image.fromarray(lic_pred[0][:, :, ::-1])) - self.can_lic3.create_image(5, 5, image=self.lic_Tk3, anchor='nw') - self.can_pred3.create_text(40, 15, text=lic_pred[1], anchor='nw', font=('黑体', 28)) + self.lic_Tk3 = ImageTk.PhotoImage( + Image.fromarray(lic_pred[0][:, :, ::-1])) + self.can_lic3.create_image( + 5, 5, image=self.lic_Tk3, anchor='nw') + self.can_pred3.create_text( + 40, 15, text=lic_pred[1], anchor='nw', font=('黑体', 28)) else: # Lic_pred为空说明未能识别 - self.can_pred1.create_text(47, 15, text='未能识别', anchor='nw', font=('黑体', 27)) + self.can_pred1.create_text( + 47, 15, text='未能识别', anchor='nw', font=('黑体', 27)) def clear(self): self.can_src.delete('all') diff --git a/Chinese_plate_scan/License-plate-recognition/Unet.py b/Chinese_plate_scan/License-plate-recognition/Unet.py index 9ad53dae3d..c7c7a54954 100644 --- a/Chinese_plate_scan/License-plate-recognition/Unet.py +++ b/Chinese_plate_scan/License-plate-recognition/Unet.py @@ -22,15 +22,16 @@ def unet_train(): X_train = np.array(X_train) y_train = np.array(y_train) - def Conv2d_BN(x, nb_filter, kernel_size, strides=(1, 1), padding='same'): - x = layers.Conv2D(nb_filter, kernel_size, strides=strides, padding=padding)(x) + x = layers.Conv2D(nb_filter, kernel_size, + strides=strides, padding=padding)(x) x = layers.BatchNormalization(axis=3)(x) x = layers.LeakyReLU(alpha=0.1)(x) return x def Conv2dT_BN(x, filters, kernel_size, strides=(2, 2), padding='same'): - x = layers.Conv2DTranspose(filters, kernel_size, strides=strides, padding=padding)(x) + x = layers.Conv2DTranspose( + filters, kernel_size, strides=strides, padding=padding)(x) x = layers.BatchNormalization(axis=3)(x) x = layers.LeakyReLU(alpha=0.1)(x) return x @@ -38,19 +39,23 @@ def Conv2dT_BN(x, filters, kernel_size, strides=(2, 2), padding='same'): inpt = layers.Input(shape=(height, width, 3)) conv1 = Conv2d_BN(inpt, 8, (3, 3)) conv1 = Conv2d_BN(conv1, 8, (3, 3)) - pool1 = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same')(conv1) + pool1 = layers.MaxPooling2D(pool_size=( + 2, 2), strides=(2, 2), padding='same')(conv1) conv2 = Conv2d_BN(pool1, 16, (3, 3)) conv2 = Conv2d_BN(conv2, 16, (3, 3)) - pool2 = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same')(conv2) + pool2 = layers.MaxPooling2D(pool_size=( + 2, 2), strides=(2, 2), padding='same')(conv2) conv3 = Conv2d_BN(pool2, 32, (3, 3)) conv3 = Conv2d_BN(conv3, 32, (3, 3)) - pool3 = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same')(conv3) + pool3 = layers.MaxPooling2D(pool_size=( + 2, 2), strides=(2, 2), padding='same')(conv3) conv4 = Conv2d_BN(pool3, 64, (3, 3)) conv4 = Conv2d_BN(conv4, 64, (3, 3)) - pool4 = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same')(conv4) + pool4 = layers.MaxPooling2D(pool_size=( + 2, 2), strides=(2, 2), padding='same')(conv4) conv5 = Conv2d_BN(pool4, 128, (3, 3)) conv5 = layers.Dropout(0.5)(conv5) @@ -81,7 +86,8 @@ def Conv2dT_BN(x, filters, kernel_size, strides=(2, 2), padding='same'): conv9 = Conv2d_BN(concat4, 8, (3, 3)) conv9 = Conv2d_BN(conv9, 8, (3, 3)) conv9 = layers.Dropout(0.5)(conv9) - outpt = layers.Conv2D(filters=3, kernel_size=(1, 1), strides=(1, 1), padding='same', activation='relu')(conv9) + outpt = layers.Conv2D(filters=3, kernel_size=(1, 1), strides=( + 1, 1), padding='same', activation='relu')(conv9) model = models.Model(inpt, outpt) model.compile(optimizer='adam', @@ -96,15 +102,16 @@ def Conv2dT_BN(x, filters, kernel_size, strides=(2, 2), padding='same'): def unet_predict(unet, img_src_path): - img_src = cv2.imdecode(np.fromfile(img_src_path, dtype=np.uint8), -1) + img_src = cv2.imdecode(np.fromfile(img_src_path, dtype=np.uint8), -1) if img_src.shape != (512, 512, 3): - img_src = cv2.resize(img_src, dsize=(512, 512), interpolation=cv2.INTER_AREA)[:, :, :3] + img_src = cv2.resize(img_src, dsize=(512, 512), + interpolation=cv2.INTER_AREA)[:, :, :3] img_src = img_src.reshape(1, 512, 512, 3) - img_mask = unet.predict(img_src) - img_src = img_src.reshape(512, 512, 3) + img_mask = unet.predict(img_src) + img_src = img_src.reshape(512, 512, 3) img_mask = img_mask.reshape(512, 512, 3) - img_mask = img_mask / np.max(img_mask) * 255 - img_mask[:, :, 2] = img_mask[:, :, 1] = img_mask[:, :, 0] + img_mask = img_mask / np.max(img_mask) * 255 + img_mask[:, :, 2] = img_mask[:, :, 1] = img_mask[:, :, 0] img_mask = img_mask.astype(np.uint8) return img_src, img_mask diff --git a/Chinese_plate_scan/License-plate-recognition/core.py b/Chinese_plate_scan/License-plate-recognition/core.py index 8751f14d0e..1ee0acd10b 100644 --- a/Chinese_plate_scan/License-plate-recognition/core.py +++ b/Chinese_plate_scan/License-plate-recognition/core.py @@ -18,9 +18,11 @@ def locate_and_correct(img_src, img_mask): # cv2.imshow('thresh',thresh) # cv2.waitKey(0) try: - contours, hierarchy = cv2.findContours(img_mask[:, :, 0], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + contours, hierarchy = cv2.findContours( + img_mask[:, :, 0], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) except: # 防止opencv版本不一致报错 - ret, contours, hierarchy = cv2.findContours(img_mask[:, :, 0], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + ret, contours, hierarchy = cv2.findContours( + img_mask[:, :, 0], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if not len(contours): # contours1长度为0说明未检测到车牌 # print("未检测到车牌") return [], [] @@ -36,7 +38,8 @@ def locate_and_correct(img_src, img_mask): # contours中除了车牌区域可能会有宽或高都是1或者2这样的小噪点, # 而待选车牌区域的均值应较高,且宽和高不会非常小,因此通过以下条件进行筛选 if np.mean(img_cut_mask) >= 75 and w > 15 and h > 15: - rect = cv2.minAreaRect(cont) # 针对坐标点获取带方向角的最小外接矩形,中心点坐标,宽高,旋转角度 + # 针对坐标点获取带方向角的最小外接矩形,中心点坐标,宽高,旋转角度 + rect = cv2.minAreaRect(cont) box = cv2.boxPoints(rect).astype(np.int32) # 获取最小外接矩形四个顶点坐标 # cv2.drawContours(img_mask, contours, -1, (0, 0, 255), 2) # cv2.drawContours(img_mask, [box], 0, (0, 255, 0), 2) @@ -44,13 +47,18 @@ def locate_and_correct(img_src, img_mask): # cv2.waitKey(0) cont = cont.reshape(-1, 2).tolist() # 由于转换矩阵的两组坐标位置需要一一对应,因此需要将最小外接矩形的坐标进行排序,最终排序为[左上,左下,右上,右下] - box = sorted(box, key=lambda xy: xy[0]) # 先按照左右进行排序,分为左侧的坐标和右侧的坐标 - box_left, box_right = box[:2], box[2:] # 此时box的前2个是左侧的坐标,后2个是右侧的坐标 - box_left = sorted(box_left, key=lambda x: x[1]) # 再按照上下即y进行排序,此时box_left中为左上和左下两个端点坐标 - box_right = sorted(box_right, key=lambda x: x[1]) # 此时box_right中为右上和右下两个端点坐标 + # 先按照左右进行排序,分为左侧的坐标和右侧的坐标 + box = sorted(box, key=lambda xy: xy[0]) + # 此时box的前2个是左侧的坐标,后2个是右侧的坐标 + box_left, box_right = box[:2], box[2:] + # 再按照上下即y进行排序,此时box_left中为左上和左下两个端点坐标 + box_left = sorted(box_left, key=lambda x: x[1]) + # 此时box_right中为右上和右下两个端点坐标 + box_right = sorted(box_right, key=lambda x: x[1]) box = np.array(box_left + box_right) # [左上,左下,右上,右下] # print(box) - x0, y0 = box[0][0], box[0][1] # 这里的4个坐标即为最小外接矩形的四个坐标,接下来需获取平行(或不规则)四边形的坐标 + # 这里的4个坐标即为最小外接矩形的四个坐标,接下来需获取平行(或不规则)四边形的坐标 + x0, y0 = box[0][0], box[0][1] x1, y1 = box[1][0], box[1][1] x2, y2 = box[2][0], box[2][1] x3, y3 = box[3][0], box[3][1] @@ -58,12 +66,14 @@ def locate_and_correct(img_src, img_mask): def point_to_line_distance(X, Y): if x2 - x0: k_up = (y2 - y0) / (x2 - x0) # 斜率不为无穷大 - d_up = abs(k_up * X - Y + y2 - k_up * x2) / (k_up ** 2 + 1) ** 0.5 + d_up = abs(k_up * X - Y + y2 - k_up * x2) / \ + (k_up ** 2 + 1) ** 0.5 else: # 斜率无穷大 d_up = abs(X - x2) if x1 - x3: k_down = (y1 - y3) / (x1 - x3) # 斜率不为无穷大 - d_down = abs(k_down * X - Y + y1 - k_down * x1) / (k_down ** 2 + 1) ** 0.5 + d_down = abs(k_down * X - Y + y1 - k_down * + x1) / (k_down ** 2 + 1) ** 0.5 else: # 斜率无穷大 d_down = abs(X - x1) return d_up, d_down @@ -96,12 +106,17 @@ def point_to_line_distance(X, Y): # cv2.circle(img=img_mask, color=(0, 255, 255), center=tuple(l), thickness=2, radius=2) # cv2.imshow('img_mask',img_mask) # cv2.waitKey(0) - p0 = np.float32([l0, l1, l2, l3]) # 左上角,左下角,右上角,右下角,p0和p1中的坐标顺序对应,以进行转换矩阵的形成 - p1 = np.float32([(0, 0), (0, 80), (240, 0), (240, 80)]) # 我们所需的长方形 + # 左上角,左下角,右上角,右下角,p0和p1中的坐标顺序对应,以进行转换矩阵的形成 + p0 = np.float32([l0, l1, l2, l3]) + p1 = np.float32( + [(0, 0), (0, 80), (240, 0), (240, 80)]) # 我们所需的长方形 transform_mat = cv2.getPerspectiveTransform(p0, p1) # 构成转换矩阵 - lic = cv2.warpPerspective(img_src, transform_mat, (240, 80)) # 进行车牌矫正 + lic = cv2.warpPerspective( + img_src, transform_mat, (240, 80)) # 进行车牌矫正 # cv2.imshow('lic',lic) # cv2.waitKey(0) Lic_img.append(lic) - cv2.drawContours(img_src_copy, [np.array([l0, l1, l3, l2])], -1, (0, 255, 0), 2) # 在img_src_copy上绘制出定位的车牌轮廓,(0, 255, 0)表示绘制线条为绿色 + # 在img_src_copy上绘制出定位的车牌轮廓,(0, 255, 0)表示绘制线条为绿色 + cv2.drawContours(img_src_copy, [np.array( + [l0, l1, l3, l2])], -1, (0, 255, 0), 2) return img_src_copy, Lic_img diff --git a/Chinese_plate_scan/License-plate-recognition/train.py b/Chinese_plate_scan/License-plate-recognition/train.py index 65889bfb3c..195c6ca1e0 100644 --- a/Chinese_plate_scan/License-plate-recognition/train.py +++ b/Chinese_plate_scan/License-plate-recognition/train.py @@ -3,5 +3,5 @@ from Unet import unet_train from CNN import cnn_train -unet_train()#训练后得到unet.h5,用于车牌定位 -cnn_train()#训练后得到cnn.h5,用于车牌识别 +unet_train() # 训练后得到unet.h5,用于车牌定位 +cnn_train() # 训练后得到cnn.h5,用于车牌识别 diff --git a/Clean_Up_Photo_Directory/Clean_Up_Photo_Directory.py b/Clean_Up_Photo_Directory/Clean_Up_Photo_Directory.py index 79b030f8d8..510c7819b2 100644 --- a/Clean_Up_Photo_Directory/Clean_Up_Photo_Directory.py +++ b/Clean_Up_Photo_Directory/Clean_Up_Photo_Directory.py @@ -1,20 +1,20 @@ import os from os.path import join for (dirname, dirs, files) in os.walk('.'): - for filename in files: - if filename.endswith('.txt') : - thefile = os.path.join(dirname,filename) - size = os.path.getsize(thefile) - if size == 2578 or size == 2565: - print 'T-Mobile:',thefile - #os.remove(thefile) Add this when you are sure to delete the file - continue - fhand = open(thefile,'r') - lines = list() - for line in fhand: - lines.append(line) - fhand.close() - if len(lines) == 3 and lines[2].startswith('Sent from my iPhone'): - print 'iPhone:', thefile - #os.remove(thefile) Add this when you are sure to delete the file - continue \ No newline at end of file + for filename in files: + if filename.endswith('.txt'): + thefile = os.path.join(dirname, filename) + size = os.path.getsize(thefile) + if size == 2578 or size == 2565: + print 'T-Mobile:', thefile + # os.remove(thefile) Add this when you are sure to delete the file + continue + fhand = open(thefile, 'r') + lines = list() + for line in fhand: + lines.append(line) + fhand.close() + if len(lines) == 3 and lines[2].startswith('Sent from my iPhone'): + print 'iPhone:', thefile + # os.remove(thefile) Add this when you are sure to delete the file + continue diff --git a/Codechef Scrapper/codechef.py b/Codechef Scrapper/codechef.py index 22660ff25e..fc5ceca106 100644 --- a/Codechef Scrapper/codechef.py +++ b/Codechef Scrapper/codechef.py @@ -114,7 +114,7 @@ def main(): 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): + if (problem is not None): convert_to_pdf(problem) else: pass diff --git a/Coderforces_Problem_Scrapper/Codeforces_problem_scrapper.py b/Coderforces_Problem_Scrapper/Codeforces_problem_scrapper.py index 2f2bb074a4..a35f6dc289 100644 --- a/Coderforces_Problem_Scrapper/Codeforces_problem_scrapper.py +++ b/Coderforces_Problem_Scrapper/Codeforces_problem_scrapper.py @@ -33,7 +33,8 @@ def extracting_problem_links(diff_level): options.headless = True driver = webdriver.Chrome(DRIVER_PATH, options=options) print("\nRequesting URL ...") - driver.get(f"https://codeforces.com/problemset/?tags={diff_level[0]}-{diff_level[1]}") + driver.get( + f"https://codeforces.com/problemset/?tags={diff_level[0]}-{diff_level[1]}") # ===================Getting no. of Pages to Scrape============================= @@ -54,7 +55,8 @@ def extracting_problem_links(diff_level): # ***************************** SCRAPING PAGE 1 ************************************* print(f"\nScraping Page {page}") - elements = driver.find_elements_by_css_selector("td.id.dark.left a" and "td.id.left a") + elements = driver.find_elements_by_css_selector( + "td.id.dark.left a" and "td.id.left a") for element in elements: # Saving the link in pblms_links pblms_links.append(element.get_attribute("href")) @@ -63,7 +65,8 @@ def extracting_problem_links(diff_level): # If we scraped required no. of questions then return if pblms_link_scraped == no_of_questions: print(f"URLs of Question Scraped till now: {pblms_link_scraped}") - print(f"\nURLs Scrapped Successfully {pblms_link_scraped} out of {no_of_questions}") + print( + f"\nURLs Scrapped Successfully {pblms_link_scraped} out of {no_of_questions}") return pblms_links page += 1 print(f"URLs of Question Scraped till now: {pblms_link_scraped}") @@ -75,7 +78,8 @@ def extracting_problem_links(diff_level): # Going to next Page driver.get(link) - elements = driver.find_elements_by_css_selector("td.id.dark.left a" and "td.id.left a") + elements = driver.find_elements_by_css_selector( + "td.id.dark.left a" and "td.id.left a") for element in elements: # Saving the link in pblms_links pblms_links.append(element.get_attribute("href")) @@ -83,8 +87,10 @@ def extracting_problem_links(diff_level): # If we scraped required no. of questions then return if pblms_link_scraped == no_of_questions: - print(f"URLs of Question Scraped till now: {pblms_link_scraped}") - print(f"\nURLs Scrapped Successfully {pblms_link_scraped} out of {no_of_questions}") + print( + f"URLs of Question Scraped till now: {pblms_link_scraped}") + print( + f"\nURLs Scrapped Successfully {pblms_link_scraped} out of {no_of_questions}") return pblms_links print(f"URLs of Question Scraped till now: {pblms_link_scraped}") @@ -92,7 +98,8 @@ def extracting_problem_links(diff_level): # ---------------------------------------------------------------------------------------------- # scraped all the available questions but still the count is less - print(f"\n{pblms_link_scraped} out of {no_of_questions} URLs able to scrapped !!!") + print( + f"\n{pblms_link_scraped} out of {no_of_questions} URLs able to scrapped !!!") return pblms_links @@ -140,14 +147,17 @@ def getproblem(URLs): pdf.add_page() # Adding new page to the pdf pdf.image(path, MARGIN, MARGIN) - pdf.output(os.path.join(target_folder, filename), "F") # saving the pdf with the specified filename - print(f'File saved in your directory ./problems_pdf/{filename} ({file_counter}/{len(URLs)}) !') + # saving the pdf with the specified filename + pdf.output(os.path.join(target_folder, filename), "F") + print( + f'File saved in your directory ./problems_pdf/{filename} ({file_counter}/{len(URLs)}) !') file_counter += 1 if __name__ == "__main__": DRIVER_PATH = input("Enter DRIVER PATH location: ") diff = select_difficulty() # Accepting difficulty level from user - problems_link = extracting_problem_links(diff) # scraping the required the no. of links + # scraping the required the no. of links + problems_link = extracting_problem_links(diff) getproblem(problems_link) # saving the Questions in PDF file. os.remove('image.png') diff --git a/Codes on Turtle Graphics/DrawSpirograph.py b/Codes on Turtle Graphics/DrawSpirograph.py index 9f96124910..e6cec630b4 100644 --- a/Codes on Turtle Graphics/DrawSpirograph.py +++ b/Codes on Turtle Graphics/DrawSpirograph.py @@ -6,7 +6,8 @@ tim.speed("fastest") # Detecting the total number of circles for i in range(int(360 / 5)): - tim.color((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) + tim.color((random.randint(0, 255), random.randint( + 0, 255), random.randint(0, 255))) tim.circle(100) tim.setheading(tim.heading() + 5) scr = t.Screen() diff --git a/Codes on Turtle Graphics/RandomColorWalk.py b/Codes on Turtle Graphics/RandomColorWalk.py index 10e0cef8b7..fcc07633c5 100644 --- a/Codes on Turtle Graphics/RandomColorWalk.py +++ b/Codes on Turtle Graphics/RandomColorWalk.py @@ -9,7 +9,8 @@ for i in range(300): tim.forward(30) # Choosing a random combination of colors - tim.color((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) + tim.color((random.randint(0, 255), random.randint( + 0, 255), random.randint(0, 255))) tim.setheading(random.choice([0, 90, 180, 270])) scr = t.Screen() scr.exitonclick() diff --git a/Coffee-Machine-py-game/coffee-machine-py-game.py b/Coffee-Machine-py-game/coffee-machine-py-game.py index db0cd557bd..a8f09a405d 100644 --- a/Coffee-Machine-py-game/coffee-machine-py-game.py +++ b/Coffee-Machine-py-game/coffee-machine-py-game.py @@ -51,7 +51,8 @@ def buy_coffee(self, choice): return message # Check if there are enough resources to make the selected coffee - message = self.check_resources(water_needed, milk_needed, coffee_beans_needed, cups_needed) + message = self.check_resources( + water_needed, milk_needed, coffee_beans_needed, cups_needed) if message == "Enough resources. Enjoy your coffee!": # Prompt for inserting coins and calculate the total amount print(f"Please insert coins for {coffee_type} (${price}):") diff --git a/Connect 4 with Minimax Algorithm/connect4withMiniMax.py b/Connect 4 with Minimax Algorithm/connect4withMiniMax.py index 057f1f8856..7d70733949 100644 --- a/Connect 4 with Minimax Algorithm/connect4withMiniMax.py +++ b/Connect 4 with Minimax Algorithm/connect4withMiniMax.py @@ -4,10 +4,10 @@ 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 @@ -18,186 +18,204 @@ PLAYER_PIECE = 1 AI_PIECE = 2 + def createBoard(): - board = np.zeros((ROW_COUNT,COLUMN_COUNT)) - return board + board = np.zeros((ROW_COUNT, COLUMN_COUNT)) + return board + def dropPiece(board, row, col, piece): - board[row][col] = piece + board[row][col] = piece + def isPlaceValid(board, col): - return board[ROW_COUNT-1][col] == 0 + return board[ROW_COUNT-1][col] == 0 + def GetNextRow(board, col): - for r in range(ROW_COUNT): - if board[r][col] == 0: - return r + for r in range(ROW_COUNT): + if board[r][col] == 0: + return r + def printBoard(board): - print(np.flip(board, 0)) + print(np.flip(board, 0)) + def winningMove(board, piece): - # Check horizontal locations for 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: - return True - - # Check vertical locations for 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: - return True - - # Check positively sloped diaganols - 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: - return True - - # Check negatively sloped diaganols - 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: - return True + # Check horizontal locations for 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: + return True + + # Check vertical locations for 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: + return True + + # Check positively sloped diaganols + 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: + return True + + # Check negatively sloped diaganols + 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: + return True + def scoringScorePosition(selectedGroup, piece): - score = 0 - opp_piece = PLAYER_PIECE - if piece == PLAYER_PIECE: - opp_piece = AI_PIECE + score = 0 + opp_piece = PLAYER_PIECE + if piece == PLAYER_PIECE: + opp_piece = AI_PIECE + + if selectedGroup.count(piece) == 4: + score += 100 + elif selectedGroup.count(piece) == 3 and selectedGroup.count(0) == 1: + score += 5 + elif selectedGroup.count(piece) == 2 and selectedGroup.count(0) == 2: + score += 2 - if selectedGroup.count(piece) == 4: - score += 100 - elif selectedGroup.count(piece) == 3 and selectedGroup.count(0) == 1: - score += 5 - elif selectedGroup.count(piece) == 2 and selectedGroup.count(0) == 2: - score += 2 + if selectedGroup.count(opp_piece) == 3 and selectedGroup.count(0) == 1: + score -= 4 - if selectedGroup.count(opp_piece) == 3 and selectedGroup.count(0) == 1: - score -= 4 + return score - return score def scorePosition(board, piece): - score = 0 - - ## Score center column - center_array = [int(i) for i in list(board[:, COLUMN_COUNT//2])] - center_count = center_array.count(piece) - score += center_count * 3 - - ## Score Horizontal - for r in range(ROW_COUNT): - row_array = [int(i) for i in list(board[r,:])] - for c in range(COLUMN_COUNT-3): - selectedGroup = row_array[c:c+4] - score += scoringScorePosition(selectedGroup, piece) - - ## Score Vertical - for c in range(COLUMN_COUNT): - col_array = [int(i) for i in list(board[:,c])] - for r in range(ROW_COUNT-3): - selectedGroup = col_array[r:r+4] - score += scoringScorePosition(selectedGroup, piece) - - ## Score posiive sloped diagonal - for r in range(ROW_COUNT-3): - for c in range(COLUMN_COUNT-3): - selectedGroup = [board[r+i][c+i] for i in range(4)] - score += scoringScorePosition(selectedGroup, piece) - - for r in range(ROW_COUNT-3): - for c in range(COLUMN_COUNT-3): - selectedGroup = [board[r+3-i][c+i] for i in range(4)] - score += scoringScorePosition(selectedGroup, piece) - - return score + score = 0 + + # Score center column + center_array = [int(i) for i in list(board[:, COLUMN_COUNT//2])] + center_count = center_array.count(piece) + score += center_count * 3 + + # Score Horizontal + for r in range(ROW_COUNT): + row_array = [int(i) for i in list(board[r, :])] + for c in range(COLUMN_COUNT-3): + selectedGroup = row_array[c:c+4] + score += scoringScorePosition(selectedGroup, piece) + + # Score Vertical + for c in range(COLUMN_COUNT): + col_array = [int(i) for i in list(board[:, c])] + for r in range(ROW_COUNT-3): + selectedGroup = col_array[r:r+4] + score += scoringScorePosition(selectedGroup, piece) + + # Score posiive sloped diagonal + for r in range(ROW_COUNT-3): + for c in range(COLUMN_COUNT-3): + selectedGroup = [board[r+i][c+i] for i in range(4)] + score += scoringScorePosition(selectedGroup, piece) + + for r in range(ROW_COUNT-3): + for c in range(COLUMN_COUNT-3): + selectedGroup = [board[r+3-i][c+i] for i in range(4)] + score += scoringScorePosition(selectedGroup, piece) + + return score + def isTerminalNode(board): - return winningMove(board, PLAYER_PIECE) or winningMove(board, AI_PIECE) or len(getValidLocations(board)) == 0 + return winningMove(board, PLAYER_PIECE) or winningMove(board, AI_PIECE) or len(getValidLocations(board)) == 0 + def minimax(board, depth, alpha, beta, maximizingPlayer): - validLocations = getValidLocations(board) - isTerminal = isTerminalNode(board) - if depth == 0 or isTerminal: - if isTerminal: - if winningMove(board, AI_PIECE): - return (None, 100000000000000) - elif winningMove(board, PLAYER_PIECE): - return (None, -10000000000000) - else: # Game is over, no more valid moves - return (None, 0) - else: # Depth is zero - return (None, scorePosition(board, AI_PIECE)) - if maximizingPlayer: - value = -math.inf - column = random.choice(validLocations) - for col in validLocations: - row = GetNextRow(board, col) - b_copy = board.copy() - dropPiece(b_copy, row, col, AI_PIECE) - new_score = minimax(b_copy, depth-1, alpha, beta, False)[1] - if new_score > value: - value = new_score - column = col - alpha = max(alpha, value) - if alpha >= beta: - break - return column, value - - else: # Minimizing player - value = math.inf - column = random.choice(validLocations) - for col in validLocations: - row = GetNextRow(board, col) - b_copy = board.copy() - dropPiece(b_copy, row, col, PLAYER_PIECE) - new_score = minimax(b_copy, depth-1, alpha, beta, True)[1] - if new_score < value: - value = new_score - column = col - beta = min(beta, value) - if alpha >= beta: - break - return column, value + validLocations = getValidLocations(board) + isTerminal = isTerminalNode(board) + if depth == 0 or isTerminal: + if isTerminal: + if winningMove(board, AI_PIECE): + return (None, 100000000000000) + elif winningMove(board, PLAYER_PIECE): + return (None, -10000000000000) + else: # Game is over, no more valid moves + return (None, 0) + else: # Depth is zero + return (None, scorePosition(board, AI_PIECE)) + if maximizingPlayer: + value = -math.inf + column = random.choice(validLocations) + for col in validLocations: + row = GetNextRow(board, col) + b_copy = board.copy() + dropPiece(b_copy, row, col, AI_PIECE) + new_score = minimax(b_copy, depth-1, alpha, beta, False)[1] + if new_score > value: + value = new_score + column = col + alpha = max(alpha, value) + if alpha >= beta: + break + return column, value + + else: # Minimizing player + value = math.inf + column = random.choice(validLocations) + for col in validLocations: + row = GetNextRow(board, col) + b_copy = board.copy() + dropPiece(b_copy, row, col, PLAYER_PIECE) + new_score = minimax(b_copy, depth-1, alpha, beta, True)[1] + if new_score < value: + value = new_score + column = col + beta = min(beta, value) + if alpha >= beta: + break + return column, value + def getValidLocations(board): - validLocations = [] - for col in range(COLUMN_COUNT): - if isPlaceValid(board, col): - validLocations.append(col) - return validLocations + validLocations = [] + for col in range(COLUMN_COUNT): + if isPlaceValid(board, col): + validLocations.append(col) + return validLocations + def bestMoveForAI(board, piece): - validLocations = getValidLocations(board) - bestScore = -10000 - bestMove = random.choice(validLocations) - for col in validLocations: - row = GetNextRow(board, col) - temp_board = board.copy() - dropPiece(temp_board, row, col, piece) - score = scorePosition(temp_board, piece) - if score > bestScore: - bestScore = score - bestMove = col + validLocations = getValidLocations(board) + bestScore = -10000 + bestMove = random.choice(validLocations) + for col in validLocations: + row = GetNextRow(board, col) + temp_board = board.copy() + dropPiece(temp_board, row, col, piece) + score = scorePosition(temp_board, piece) + if score > bestScore: + bestScore = score + bestMove = col + + return bestMove - return bestMove def drawBoard(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) - - for c in range(COLUMN_COUNT): - for r in range(ROW_COUNT): - if board[r][c] == PLAYER_PIECE: - pygame.draw.circle(screen, RED, (int(c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS) - elif board[r][c] == AI_PIECE: - pygame.draw.circle(screen, YELLOW, (int(c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS) - pygame.display.update() + 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) + + for c in range(COLUMN_COUNT): + for r in range(ROW_COUNT): + if board[r][c] == PLAYER_PIECE: + pygame.draw.circle(screen, RED, (int( + c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS) + elif board[r][c] == AI_PIECE: + pygame.draw.circle(screen, YELLOW, (int( + c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS) + pygame.display.update() + board = createBoard() printBoard(board) @@ -224,64 +242,64 @@ def drawBoard(board): while not isGameOver: - for event in pygame.event.get(): - 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 == PLAYER: - pygame.draw.circle(screen, RED, (posx, int(SQUARESIZE/2)), RADIUS) + for event in pygame.event.get(): + if event.type == pygame.QUIT: + sys.exit() - pygame.display.update() + if event.type == pygame.MOUSEMOTION: + pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARESIZE)) + posx = event.pos[0] + if turn == PLAYER: + pygame.draw.circle( + screen, RED, (posx, int(SQUARESIZE/2)), RADIUS) - if event.type == pygame.MOUSEBUTTONDOWN: - pygame.draw.rect(screen, BLACK, (0,0, width, SQUARESIZE)) - #print(event.pos) - # Ask for Player 1 Input - if turn == PLAYER: - posx = event.pos[0] - col = int(math.floor(posx/SQUARESIZE)) + pygame.display.update() - if isPlaceValid(board, col): - row = GetNextRow(board, col) - dropPiece(board, row, col, PLAYER_PIECE) + if event.type == pygame.MOUSEBUTTONDOWN: + pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARESIZE)) + # print(event.pos) + # Ask for Player 1 Input + if turn == PLAYER: + posx = event.pos[0] + col = int(math.floor(posx/SQUARESIZE)) - if winningMove(board, PLAYER_PIECE): - label = myfont.render("Player 1 win!!", 1, RED) - screen.blit(label, (40,10)) - isGameOver = True + if isPlaceValid(board, col): + row = GetNextRow(board, col) + dropPiece(board, row, col, PLAYER_PIECE) - turn += 1 - turn = turn % 2 + if winningMove(board, PLAYER_PIECE): + label = myfont.render("Player 1 win!!", 1, RED) + screen.blit(label, (40, 10)) + isGameOver = True - printBoard(board) - drawBoard(board) + turn += 1 + turn = turn % 2 + printBoard(board) + drawBoard(board) - # # Ask for Player 2 Input - if turn == AI and not isGameOver: + # # Ask for Player 2 Input + if turn == AI and not isGameOver: - #col = random.randint(0, COLUMN_COUNT-1) - #col = bestMoveForAI(board, AI_PIECE) - col, minimax_score = minimax(board, 5, -math.inf, math.inf, True) + # col = random.randint(0, COLUMN_COUNT-1) + # col = bestMoveForAI(board, AI_PIECE) + col, minimax_score = minimax(board, 5, -math.inf, math.inf, True) - if isPlaceValid(board, col): - #pygame.time.wait(500) - row = GetNextRow(board, col) - dropPiece(board, row, col, AI_PIECE) + if isPlaceValid(board, col): + # pygame.time.wait(500) + row = GetNextRow(board, col) + dropPiece(board, row, col, AI_PIECE) - if winningMove(board, AI_PIECE): - label = myfont.render("Player 2 wins!!", 1, YELLOW) - screen.blit(label, (40,10)) - isGameOver = True + if winningMove(board, AI_PIECE): + label = myfont.render("Player 2 wins!!", 1, YELLOW) + screen.blit(label, (40, 10)) + isGameOver = True - printBoard(board) - drawBoard(board) + printBoard(board) + drawBoard(board) - turn += 1 - turn = turn % 2 + turn += 1 + turn = turn % 2 - if isGameOver: - pygame.time.wait(5000) \ No newline at end of file + if isGameOver: + pygame.time.wait(5000) diff --git a/Connect-4 game/Connect-4.py b/Connect-4 game/Connect-4.py index 6eee2fe83c..203bdb81ec 100644 --- a/Connect-4 game/Connect-4.py +++ b/Connect-4 game/Connect-4.py @@ -133,7 +133,7 @@ def draw_board(board): drop_piece(board, row, col, 1) if winning_move(board, 1): - #print("Player 1 wins CONGRATULATIONS!!") + # print("Player 1 wins CONGRATULATIONS!!") label = myfont.render("Player 1 wins!!", 1, RED) screen.blit(label, (40, 10)) game_over = True @@ -147,7 +147,7 @@ def draw_board(board): drop_piece(board, row, col, 2) if winning_move(board, 2): - #print("Player 2 wins CONGRATULATIONS!!") + # print("Player 2 wins CONGRATULATIONS!!") label = myfont.render("Player 2 wins!!", 1, YELLOW) screen.blit(label, (40, 10)) game_over = True diff --git a/Cookie_Clicker/main.py b/Cookie_Clicker/main.py index fb95e490a4..abaa9ce677 100644 --- a/Cookie_Clicker/main.py +++ b/Cookie_Clicker/main.py @@ -1,41 +1,46 @@ from selenium import webdriver from selenium.webdriver.common.by import By import time -cookies_per_sec=0 +cookies_per_sec = 0 + def cookie_click(): - buy_time=time.time()+5.0 - while (time.time()last_item_price: + last_item_price = int(driver.find_element( + By.CSS_SELECTOR, f"#productPrice{len(purchase_list)-1}").text) + if int(current_money) > last_item_price: purchase_list[-1].click() - current_money-=last_item_price + current_money -= last_item_price -chrome_driver_path="C:/Development/chromedriver.exe" -driver=webdriver.Chrome(executable_path=chrome_driver_path) + +chrome_driver_path = "C:/Development/chromedriver.exe" +driver = webdriver.Chrome(executable_path=chrome_driver_path) driver.get("https://orteil.dashnet.org/cookieclicker/") time.sleep(7) -language_click=driver.find_element(By.CSS_SELECTOR,"#langSelect-EN") +language_click = driver.find_element(By.CSS_SELECTOR, "#langSelect-EN") language_click.click() time.sleep(7) -end_time=time.time()+300.0 -while (time.time()li'))) + courses = wait.until(EC.visibility_of_all_elements_located( + (By.CSS_SELECTOR, 'main ul>li'))) for course in courses: - title = driver.execute_script('return arguments[0].querySelector("h3")?.innerText',course) - description = driver.execute_script('return arguments[0].querySelector("p>span")?.innerText', course) - review = driver.execute_script('return arguments[0].querySelector("div:has(>svg)")?.innerText.replace("\\n\\n","⭐")', course) - url = driver.execute_script('return String(arguments[0].querySelector("a")?.href)', course) - data = {"id":j,"title":title,"description":description,"review":review,"url":url} + title = driver.execute_script( + 'return arguments[0].querySelector("h3")?.innerText', course) + description = driver.execute_script( + 'return arguments[0].querySelector("p>span")?.innerText', course) + review = driver.execute_script( + 'return arguments[0].querySelector("div:has(>svg)")?.innerText.replace("\\n\\n","⭐")', course) + url = driver.execute_script( + 'return String(arguments[0].querySelector("a")?.href)', course) + data = {"id": j, "title": title, + "description": description, "review": review, "url": url} courses_data += [data] - j+=1 - next_btn = driver.find_element(By.CSS_SELECTOR, 'button[aria-label="Next Page"]') + j += 1 + next_btn = driver.find_element( + By.CSS_SELECTOR, 'button[aria-label="Next Page"]') if 'disabled' in next_btn.get_attribute('class'): print('There are no more pages') break @@ -53,14 +64,18 @@ def scrape_all(self): "data": None, "message": f"No courses found for {self.keyword}" } + def course_titles(self): wait, driver = self.__scrape_page() titles = [] try: for i in range(self.page_count): - courses = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, 'main ul>li'))) - titles.extend([driver.execute_script('return arguments[0].querySelector("h3")?.innerText', course) for course in courses]) - next_btn = driver.find_element(By.CSS_SELECTOR, 'button[aria-label="Next Page"]') + courses = wait.until(EC.visibility_of_all_elements_located( + (By.CSS_SELECTOR, 'main ul>li'))) + titles.extend([driver.execute_script( + 'return arguments[0].querySelector("h3")?.innerText', course) for course in courses]) + next_btn = driver.find_element( + By.CSS_SELECTOR, 'button[aria-label="Next Page"]') if 'disabled' in next_btn.get_attribute('class'): print('There are no more pages') break @@ -75,14 +90,18 @@ def course_titles(self): "data": None, "message": f"No courses found for {self.keyword}" } + def course_description(self): wait, driver = self.__scrape_page() descriptions = [] try: for i in range(self.page_count): - courses = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, 'main ul>li'))) - descriptions.extend([driver.execute_script('return arguments[0].querySelector("p>span")?.innerText', course) for course in courses]) - next_btn = driver.find_element(By.CSS_SELECTOR, 'button[aria-label="Next Page"]') + courses = wait.until(EC.visibility_of_all_elements_located( + (By.CSS_SELECTOR, 'main ul>li'))) + descriptions.extend([driver.execute_script( + 'return arguments[0].querySelector("p>span")?.innerText', course) for course in courses]) + next_btn = driver.find_element( + By.CSS_SELECTOR, 'button[aria-label="Next Page"]') if 'disabled' in next_btn.get_attribute('class'): print('There are no more pages') break @@ -97,14 +116,18 @@ def course_description(self): "data": None, "message": f"No courses found for {self.keyword}" } + def course_reviews(self): wait, driver = self.__scrape_page() reviews = [] try: for i in range(self.page_count): - courses = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, 'main ul>li'))) - reviews.extend([driver.execute_script('return arguments[0].querySelector("div:has(>svg)")?.innerText.replace("\\n\\n","⭐")', course) for course in courses]) - next_btn = driver.find_element(By.CSS_SELECTOR, 'button[aria-label="Next Page"]') + courses = wait.until(EC.visibility_of_all_elements_located( + (By.CSS_SELECTOR, 'main ul>li'))) + reviews.extend([driver.execute_script( + 'return arguments[0].querySelector("div:has(>svg)")?.innerText.replace("\\n\\n","⭐")', course) for course in courses]) + next_btn = driver.find_element( + By.CSS_SELECTOR, 'button[aria-label="Next Page"]') if 'disabled' in next_btn.get_attribute('class'): print('There are no more pages') break @@ -119,14 +142,18 @@ def course_reviews(self): "data": None, "message": f"No courses found for {self.keyword}" } + def course_urls(self): wait, driver = self.__scrape_page() urls = [] try: for i in range(self.page_count): - courses = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, 'main ul>li'))) - urls.extend([driver.execute_script('return String(arguments[0].querySelector("a")?.href)', course) for course in courses]) - next_btn = driver.find_element(By.CSS_SELECTOR, 'button[aria-label="Next Page"]') + courses = wait.until(EC.visibility_of_all_elements_located( + (By.CSS_SELECTOR, 'main ul>li'))) + urls.extend([driver.execute_script( + 'return String(arguments[0].querySelector("a")?.href)', course) for course in courses]) + next_btn = driver.find_element( + By.CSS_SELECTOR, 'button[aria-label="Next Page"]') if 'disabled' in next_btn.get_attribute('class'): print('There are no more pages') break @@ -141,5 +168,7 @@ def course_urls(self): "data": None, "message": f"No courses found for {self.keyword}" } -python_scraper = Courses("python",5) -print(python_scraper.scrape_all()) \ No newline at end of file + + +python_scraper = Courses("python", 5) +print(python_scraper.scrape_all()) diff --git a/Covid -19-Detection-Using-Chest-X-Ray/test.py b/Covid -19-Detection-Using-Chest-X-Ray/test.py index ba23f64299..cd3c200065 100644 --- a/Covid -19-Detection-Using-Chest-X-Ray/test.py +++ b/Covid -19-Detection-Using-Chest-X-Ray/test.py @@ -1,8 +1,8 @@ import numpy as np import matplotlib.pyplot as plt import tensorflow.keras as keras -#from keras.layers import * -#from keras.models import * +# from keras.layers import * +# from keras.models import * from tensorflow.keras.preprocessing import image from tensorflow.keras.preprocessing.image import load_img from tensorflow.keras.preprocessing.image import img_to_array @@ -20,7 +20,7 @@ window.configure(background='yellow') -#window.attributes('-fullscreen', True) +# window.attributes('-fullscreen', True) window.grid_rowconfigure(0, weight=1) window.grid_columnconfigure(0, weight=1) @@ -34,8 +34,8 @@ font=('times', 30, 'italic bold underline')) message.place(x=200, y=20) -#txt = tk.Entry(window,width=20 ,bg="blue" ,fg="red",font=('times', 15, ' bold ')) -#txt.place(x=700, y=215) +# txt = tk.Entry(window,width=20 ,bg="blue" ,fg="red",font=('times', 15, ' bold ')) +# txt.place(x=700, y=215) lbl3 = tk.Label(window, text="Status of a Person : ", @@ -96,8 +96,8 @@ def run_example(): message.configure(text=res) -#clearButton = tk.Button(window, text="Clear", command=clear ,fg="red" ,bg="green" ,width=20 ,height=2 ,activebackground = "Red" ,font=('times', 15, ' bold ')) -#clearButton.place(x=950, y=200) +# clearButton = tk.Button(window, text="Clear", command=clear ,fg="red" ,bg="green" ,width=20 ,height=2 ,activebackground = "Red" ,font=('times', 15, ' bold ')) +# clearButton.place(x=950, y=200) takeImg = tk.Button(window, text="Click to load X-ray Images ", diff --git a/Covid-19_Real-time_Notification/Covid.py b/Covid-19_Real-time_Notification/Covid.py index c2332f533b..c2dbff6b51 100644 --- a/Covid-19_Real-time_Notification/Covid.py +++ b/Covid-19_Real-time_Notification/Covid.py @@ -4,41 +4,43 @@ import time from englisttohindi.englisttohindi import EngtoHindi + def notify_user(title, message): notification.notify( - title = title, - message = message, - app_icon = "./Covid-19_Real-time_Notification/Notify_icon.ico" , - timeout = 5) - + title=title, + message=message, + app_icon="./Covid-19_Real-time_Notification/Notify_icon.ico", + timeout=5) + + def getInfo(url): r = requests.get(url) return r.text if __name__ == '__main__': - t = int(input("Enter interval in secs: ")) - li = list(map(str, input("Enter name of states: ").split(","))) - states = [] - for i in li: - states.append(i + " ( " + str(((EngtoHindi(i)).convert)) + " )") - - while True: - HtmlData = getInfo('https://www.medtalks.in/live-corona-counter-india') - soup = BeautifulSoup(HtmlData, 'html.parser') - - myData = "" - for tr in soup.find('tbody').find_all('tr'): - myData += tr.get_text() - myData = myData[1:] - - itemList = myData.split("\n\n") - for item in itemList[:-2]: - dataList = item.split('\n') - - if dataList[0] in states: - nTitle = 'Cases of Covid-19' - nText = f"State: {dataList[0]}: Total: {dataList[1]}\n Active: {dataList[2]}\n Death: {dataList[3]}" - notify_user(nTitle, nText) - time.sleep(2) - time.sleep(t) \ No newline at end of file + t = int(input("Enter interval in secs: ")) + li = list(map(str, input("Enter name of states: ").split(","))) + states = [] + for i in li: + states.append(i + " ( " + str(((EngtoHindi(i)).convert)) + " )") + + while True: + HtmlData = getInfo('https://www.medtalks.in/live-corona-counter-india') + soup = BeautifulSoup(HtmlData, 'html.parser') + + myData = "" + for tr in soup.find('tbody').find_all('tr'): + myData += tr.get_text() + myData = myData[1:] + + itemList = myData.split("\n\n") + for item in itemList[:-2]: + dataList = item.split('\n') + + if dataList[0] in states: + nTitle = 'Cases of Covid-19' + nText = f"State: {dataList[0]}: Total: {dataList[1]}\n Active: {dataList[2]}\n Death: {dataList[3]}" + notify_user(nTitle, nText) + time.sleep(2) + time.sleep(t) diff --git a/Crypt_Socket/crypt_socket.py b/Crypt_Socket/crypt_socket.py index 8350bfdd68..064076f152 100644 --- a/Crypt_Socket/crypt_socket.py +++ b/Crypt_Socket/crypt_socket.py @@ -18,7 +18,8 @@ print('Connected to:', client_address) # Wrap the socket with SSL/TLS encryption -ssl_socket = ssl.wrap_socket(client_socket, server_side=True, ssl_version=ssl.PROTOCOL_TLS) +ssl_socket = ssl.wrap_socket( + client_socket, server_side=True, ssl_version=ssl.PROTOCOL_TLS) while True: # Receive data from the client diff --git a/Cryptography/crypto.py b/Cryptography/crypto.py index 0383740e56..74414986fb 100644 --- a/Cryptography/crypto.py +++ b/Cryptography/crypto.py @@ -16,7 +16,8 @@ # label Label(root, text='ENCODE DECODE', font='arial 20 bold').pack() -Label(root, text='By Anushka Chitranshi', font='arial 20 bold').pack(side=BOTTOM) +Label(root, text='By Anushka Chitranshi', + font='arial 20 bold').pack(side=BOTTOM) # define variables Text = StringVar() @@ -83,7 +84,7 @@ def Reset(): # key Label(root, font='arial 12 bold', text='KEY').place(x=60, y=90) Entry( - root, font='arial 10', textvariable=private_key , bg='ghost white' + root, font='arial 10', textvariable=private_key, bg='ghost white' ).place(x=290, y=90) # mode @@ -91,12 +92,12 @@ def Reset(): root, font='arial 12 bold', text='MODE(e-encode, d-decode)' ).place(x=60, y=120) Entry( - root, font='arial 10', textvariable=mode , bg='ghost white' + root, font='arial 10', textvariable=mode, bg='ghost white' ).place(x=290, y=120) # result Entry( - root, font='arial 10 bold', textvariable=Result, bg='ghost white' + root, font='arial 10 bold', textvariable=Result, bg='ghost white' ).place(x=290, y=150) # result button diff --git a/Currency Convertor - GUI based/Currency_convertor_GUI.py b/Currency Convertor - GUI based/Currency_convertor_GUI.py index e08421b31d..5a782f4ed8 100644 --- a/Currency Convertor - GUI based/Currency_convertor_GUI.py +++ b/Currency Convertor - GUI based/Currency_convertor_GUI.py @@ -80,7 +80,7 @@ def calculate_conversion(): to_currency_menu.place(x=303, y=110) answer = tk.Label(screen, anchor="center", bg='#282828', - fg='red', width=50, font=("Lato", 12),text="") + fg='red', width=50, font=("Lato", 12), text="") answer.place(x=50, y=220) # Convert button and placing diff --git a/Current_City_Weather/Current_City_Weather.py b/Current_City_Weather/Current_City_Weather.py index 447c57e71d..29d0743745 100644 --- a/Current_City_Weather/Current_City_Weather.py +++ b/Current_City_Weather/Current_City_Weather.py @@ -5,16 +5,17 @@ def get_temperature(json_data): temp_in_celcius = json_data['main']['temp'] return temp_in_celcius + def get_weather_type(json_data): weather_type = json_data['weather'][0]['description'] return weather_type + def get_wind_speed(json_data): wind_speed = json_data['wind']['speed'] return wind_speed - def get_weather_data(json_data, city): description_of_weather = json_data['weather'][0]['description'] weather_type = get_weather_type(json_data) @@ -35,5 +36,4 @@ def main(): print(weather_details) - -main() \ No newline at end of file +main() diff --git a/CustomTkinter-GUI/Feedback_GUI/Feedback.py b/CustomTkinter-GUI/Feedback_GUI/Feedback.py index a9efbc62d7..77ffbffa75 100644 --- a/CustomTkinter-GUI/Feedback_GUI/Feedback.py +++ b/CustomTkinter-GUI/Feedback_GUI/Feedback.py @@ -23,6 +23,7 @@ class FeedBack(customtkinter.CTk): __init__(): Initializes the FeedBack class. button_callback(): Callback function for the button click event. """ + def __init__(self): super().__init__() @@ -34,18 +35,21 @@ def __init__(self): self.grid_columnconfigure(0, weight=1) self.textbox = customtkinter.CTkTextbox(master=self) - self.textbox.grid(row=0, column=0, padx=10, pady=(10, 0), sticky="nsew") + self.textbox.grid(row=0, column=0, padx=10, + pady=(10, 0), sticky="nsew") text = ( - " Please enter your valuable Feedback \n" - " We are sorry you have to delete your account \n" - " Help us to improve\n" + " Please enter your valuable Feedback \n" + " We are sorry you have to delete your account \n" + " Help us to improve\n" ) self.textbox.insert("1.0", text) - self.feedback = customtkinter.CTkEntry(master=self, placeholder_text="FeedBack") + self.feedback = customtkinter.CTkEntry( + master=self, placeholder_text="FeedBack") self.feedback.grid(row=1, column=0, padx=10, pady=5, sticky='ew') - self.button = customtkinter.CTkButton(master=self, command=self.button_callback,text="Done") + self.button = customtkinter.CTkButton( + master=self, command=self.button_callback, text="Done") self.button.grid(row=2, column=0, padx=10, pady=(0, 20), sticky="ew") def button_callback(self): @@ -57,7 +61,7 @@ def button_callback(self): """ def writing_feedback(): fdbck = self.feedback.get() - with open('CustomTkinter-GUI/Feedback_GUI/FeedbackGUI','w',encoding="utf-8") as feedbck: + with open('CustomTkinter-GUI/Feedback_GUI/FeedbackGUI', 'w', encoding="utf-8") as feedbck: feedbck.write(str(fdbck)) writing_feedback() self.destroy() diff --git a/CustomTkinter-GUI/SignUP_page/SignUP.py b/CustomTkinter-GUI/SignUP_page/SignUP.py index cbde155aa7..9a7ecc83e3 100644 --- a/CustomTkinter-GUI/SignUP_page/SignUP.py +++ b/CustomTkinter-GUI/SignUP_page/SignUP.py @@ -8,6 +8,7 @@ customtkinter.set_appearance_mode("dark") + def check_credentials(username, password): # Read the stored usernames and passwords from text files with open('File Path Where username is stored', 'r') as f_username, open('File Path where password is stored', 'r') as f_password: @@ -23,8 +24,9 @@ def check_credentials(username, password): class Login(customtkinter.CTk): - width = 1240 #helps in image width - height = 1080 #helps in image height + width = 1240 # helps in image width + height = 1080 # helps in image height + def __init__(self): super().__init__() @@ -40,41 +42,49 @@ def __init__(self): # TEXT : "Welcome!\nUnified Travelling & Transport System" self.login_frame = customtkinter.CTkFrame(self, corner_radius=15) self.login_frame.grid(row=0, column=0, sticky="ns") - self.login_label = customtkinter.CTkLabel(self.login_frame, text="Welcome!\nTo lOIGN pAGE",font=customtkinter.CTkFont(size=24, weight="bold", slant="roman", family="Helvetica")) + self.login_label = customtkinter.CTkLabel(self.login_frame, text="Welcome!\nTo lOIGN pAGE", font=customtkinter.CTkFont( + size=24, weight="bold", slant="roman", family="Helvetica")) self.login_label.grid(row=0, column=0, padx=30, pady=(150, 15)) - #TEXT : LOGIN PAGE - self.login_label_2 = customtkinter.CTkLabel(self.login_frame, text="Login Page",font=customtkinter.CTkFont(size=40, weight="bold")) + # TEXT : LOGIN PAGE + self.login_label_2 = customtkinter.CTkLabel( + self.login_frame, text="Login Page", font=customtkinter.CTkFont(size=40, weight="bold")) self.login_label_2.grid(row=1, column=0, padx=30, pady=(50, 15)) - - #TEXT : USERNAME - self.username_entry = customtkinter.CTkEntry(self.login_frame, width=300, placeholder_text="Username") + + # TEXT : USERNAME + self.username_entry = customtkinter.CTkEntry( + self.login_frame, width=300, placeholder_text="Username") self.username_entry.grid(row=2, column=0, padx=30, pady=(15, 15)) - - #TEXT : PASSWORD - self.password_entry = customtkinter.CTkEntry(self.login_frame, width=300, show="*", placeholder_text="Password") + + # TEXT : PASSWORD + self.password_entry = customtkinter.CTkEntry( + self.login_frame, width=300, show="*", placeholder_text="Password") self.password_entry.grid(row=3, column=0, padx=30, pady=(0, 15)) - - #TEXT : LOGIN BUTTON TEXT - self.login_button = customtkinter.CTkButton(self.login_frame, text="Login", command=self.login_event, width=200) + + # TEXT : LOGIN BUTTON TEXT + self.login_button = customtkinter.CTkButton( + self.login_frame, text="Login", command=self.login_event, width=200) self.login_button.grid(row=4, column=0, padx=30, pady=(15, 15)) def login_event(self): - + entered_username = self.username_entry.get() entered_password = self.password_entry.get() - QueryCheckForPassword=sql.Query_LoginCheck(entered_username, entered_password) + QueryCheckForPassword = sql.Query_LoginCheck( + entered_username, entered_password) if QueryCheckForPassword: - self.destroy() + self.destroy() else: print("error") - return messagebox.showerror('Error','Incorrect Username or Password') - - print("Login pressed - username:", entered_username, "password:",entered_password) + return messagebox.showerror('Error', 'Incorrect Username or Password') + + print("Login pressed - username:", entered_username, + "password:", entered_password) + if __name__ == "__main__": app9 = Login() - app9.mainloop() \ No newline at end of file + app9.mainloop() diff --git a/DNS verifier/main.py b/DNS verifier/main.py index 251c528b4b..03b2c4a8b0 100644 --- a/DNS verifier/main.py +++ b/DNS verifier/main.py @@ -33,7 +33,7 @@ def checker(dns_val=None) -> OrderedDict: dns_val = None option = None print("Enter the DNS:") - dns_val=input() + dns_val = input() try: response = checker(dns_val=dns_val) except Exception as err: @@ -41,4 +41,4 @@ def checker(dns_val=None) -> OrderedDict: sys.exit(1) print(json.dumps(response, indent=4)) - sys.exit(0) \ No newline at end of file + sys.exit(0) diff --git a/DSA-Python/Algorithms/BigO.py b/DSA-Python/Algorithms/BigO.py index e04ab4e49c..f997d9f2ef 100644 --- a/DSA-Python/Algorithms/BigO.py +++ b/DSA-Python/Algorithms/BigO.py @@ -92,6 +92,8 @@ def foo(arr): """ Time Complexity """ # Linear Time Complexity O(n) + + def squareNum(numbers): """ Time Complexity: O(n) :: loop will iterate n time linearly @@ -126,6 +128,8 @@ def duplicateInArray(numbers): """ Space Complexity """ + + def Search(numbers): """ Search for 10 in list @@ -136,8 +140,6 @@ def Search(numbers): print(i) - - if __name__ == '__main__': # O(n) numbers = [2, 5, 7, 9] @@ -155,4 +157,3 @@ def Search(numbers): numbers = [1, 6, 8, 10, 4, 5] Search(numbers) - diff --git a/DSA-Python/Algorithms/BinarySearch.py b/DSA-Python/Algorithms/BinarySearch.py index 43261a7789..758048bc1d 100644 --- a/DSA-Python/Algorithms/BinarySearch.py +++ b/DSA-Python/Algorithms/BinarySearch.py @@ -38,19 +38,22 @@ Binary Search 3 iterations log(n) """ + def LinearSearch(numList, key): - for index, element in enumerate(numList): # return index as well as element + # return index as well as element + for index, element in enumerate(numList): if element == key: return index # if key is found in list, return index of key return -1 + def BinarySearch(numList, key): left = 0 # index of elements at left of the mid value right = len(numList) - 1 # index of elements at right of the mid value mid_index = 0 # index of mid value while left <= right: # while index[left] <= index[right] - mid_index = (left + right) // 2 # '//2' returns integer value + mid_index = (left + right) // 2 # '//2' returns integer value mid_num = numList[mid_index] if mid_num == key: # middle number is equal to key @@ -64,7 +67,10 @@ def BinarySearch(numList, key): """Binary Search using Recursion""" -def BinarySearchRecursion(numList, key, leftIndex, rightIndex): # will search within left and right + + +# will search within left and right +def BinarySearchRecursion(numList, key, leftIndex, rightIndex): if rightIndex < leftIndex: # won't iterate in reverse order return -1 @@ -84,10 +90,6 @@ def BinarySearchRecursion(numList, key, leftIndex, rightIndex): # will search w return BinarySearchRecursion(numList, key, leftIndex, rightIndex) - - - - if __name__ == '__main__': numList = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] key = 18 @@ -100,6 +102,3 @@ def BinarySearchRecursion(numList, key, leftIndex, rightIndex): # will search w # Binary Search using Recursion index = BinarySearchRecursion(numList, key, 0, len(numList)) print(f"Binary Search Recursion: Number found at index {index}") - - - diff --git a/DSA-Python/Algorithms/BinarySearchTree.py b/DSA-Python/Algorithms/BinarySearchTree.py index c5985d1b85..b0accae4f0 100644 --- a/DSA-Python/Algorithms/BinarySearchTree.py +++ b/DSA-Python/Algorithms/BinarySearchTree.py @@ -58,7 +58,6 @@ def __init__(self, data): self.left = None self.right = None - def add_child(self, data): """Insert data as child in Tree""" @@ -73,17 +72,19 @@ def add_child(self, data): if self.left is None: # and if no element is present at left of node self.left = Node(data) # insert data at left else: - self.left.add_child(data) # consider node(left) {current node} as node(root) + # consider node(left) {current node} as node(root) + self.left.add_child(data) elif data > self.data: # if data is greater than root node if self.right is None: # and if no data(right) is None - self.right = Node(data) # insert data at right of node(parent) + # insert data at right of node(parent) + self.right = Node(data) else: # if data is already present at right of node - self.right.add_child(data) # consider node(right) {current node} as node(root) + # consider node(right) {current node} as node(root) + self.right.add_child(data) else: self.data = data # if tree is empty; treat incoming data as root of the tree - def InOrderTraversal(self): elements = [] # list to be filled with all elements of BST in specific order @@ -98,7 +99,6 @@ def InOrderTraversal(self): return elements # return list[elements] - def PreOrderTraversal(self): elements = [] @@ -149,11 +149,10 @@ def search(self, val): return False def max(self): - '''Maximum element of tree: keep searching on right sub-tree to find maximum element ''' - if self.right is None: # leaf node - return self.data - return self.right.max() - + '''Maximum element of tree: keep searching on right sub-tree to find maximum element ''' + if self.right is None: # leaf node + return self.data + return self.right.max() def min(self): ''' Minimum element of tree: keep searching on left sub-tree to find minimum element ''' @@ -161,7 +160,6 @@ def min(self): return self.data return self.left.min() - def delete(self, val): if val < self.data: # search for element in left sub-tree if self.left: # check if there is any left sub-tree @@ -183,7 +181,6 @@ def delete(self, val): return self - def display(self): """ Display tree """ if self.left: @@ -218,7 +215,8 @@ def build_tree(elements): if __name__ == '__main__': # Numeric BST - num_list = [20, 18, 37, 15, 7, 5, 9, 18, 24, 0] # repeated elements are removed + # repeated elements are removed + num_list = [20, 18, 37, 15, 7, 5, 9, 18, 24, 0] list_tree = build_tree(num_list) print(list_tree.InOrderTraversal()) # return list in sorted order print(list_tree.PreOrderTraversal()) # return list in sorted order @@ -235,4 +233,3 @@ def build_tree(elements): print(country_tree.InOrderTraversal()) # return list in sorted order print(country_tree.search("UK")) # False print(country_tree.search("Japan")) # True - diff --git a/DSA-Python/Algorithms/BubbleSort.py b/DSA-Python/Algorithms/BubbleSort.py index 2a3a4b52ad..2f9489d1ca 100644 --- a/DSA-Python/Algorithms/BubbleSort.py +++ b/DSA-Python/Algorithms/BubbleSort.py @@ -6,6 +6,7 @@ Space Complexity: O(1) """ + def BubbleSort(elements): size = len(elements) # get size of list for iteration purpose @@ -13,7 +14,8 @@ def BubbleSort(elements): # If list is already swapped, loop would run only once swapped = False # list is not swapped yet # swaps greatest element each time - for j in range(size-1-i): # no element after last element to compare with: that's why size-1 + # no element after last element to compare with: that's why size-1 + for j in range(size-1-i): # size-1-i: if last 2 elements of list are already sorted, run loop for previous elements only if elements[j] > elements[j+1]: # if element[left] > element[right] # Swapping Variables in traditional way @@ -26,7 +28,6 @@ def BubbleSort(elements): break - if __name__ == '__main__': elements = [10, 9, 7, 8, 6, 28, 2, 3, 1] BubbleSort(elements) @@ -34,4 +35,4 @@ def BubbleSort(elements): # sorting alphabets using bubble sort elements = ['c', 'e', 'a', 'b', 'd', 'python'] BubbleSort(elements) - print(elements) \ No newline at end of file + print(elements) diff --git a/DSA-Python/Algorithms/InsertionSort.py b/DSA-Python/Algorithms/InsertionSort.py index cb7205252a..4e61e8fcf5 100644 --- a/DSA-Python/Algorithms/InsertionSort.py +++ b/DSA-Python/Algorithms/InsertionSort.py @@ -39,16 +39,20 @@ def InsertionSort(elements): - for i in range(1, len(elements)): # starting with the 2nd element {index[1]} + # starting with the 2nd element {index[1]} + for i in range(1, len(elements)): pointer = elements[i] # current element named as pointer - j = i - 1 # left element of pointer {index[current] - 1 = elements[left]} + # left element of pointer {index[current] - 1 = elements[left]} + j = i - 1 # compare current element (pointer) to sorted array (j) # iterate between j to index[0] and continue until elements of j > pointer while j >= 0 and pointer < elements[j]: - elements[j + 1] = elements[j] # swapped left element to right element + # swapped left element to right element + elements[j + 1] = elements[j] j = j - 1 # same as j-- # when loop is terminated, pointer will be assigned to next element - elements[j + 1] = pointer # increase pointer value and repeat until array is sorted + # increase pointer value and repeat until array is sorted + elements[j + 1] = pointer if __name__ == '__main__': @@ -66,4 +70,4 @@ def InsertionSort(elements): for elements in tests: InsertionSort(elements) - print(f"Sorted array: {elements}") \ No newline at end of file + print(f"Sorted array: {elements}") diff --git a/DSA-Python/Algorithms/MergeSort.py b/DSA-Python/Algorithms/MergeSort.py index 6317a4c222..50f071c6c5 100644 --- a/DSA-Python/Algorithms/MergeSort.py +++ b/DSA-Python/Algorithms/MergeSort.py @@ -23,6 +23,7 @@ """ + def Merge2SortedList(arr1, arr2): """Input: 2 sorted lists""" sortedList = [] # created an empty sorted list @@ -33,13 +34,13 @@ def Merge2SortedList(arr1, arr2): while i < len_arr1 and j < len_arr2: if arr1[i] <= arr2[j]: # compare elements between both the lists sortedList.append(arr1[i]) # append to sorted list - i+=1 # i pointer is increased by 1 and j pointer is static + i += 1 # i pointer is increased by 1 and j pointer is static else: sortedList.append(arr2[j]) - j+=1 + j += 1 while i < len_arr1: sortedList.append(arr1[i]) - i+=1 + i += 1 while j < len_arr2: sortedList.append(arr2[j]) j += 1 @@ -50,12 +51,15 @@ def MergeSort(arr): # if list is empty or contains 1 element only: return list if len(arr) <= 1: return arr - mid = len(arr) // 2 # get middle index of array to divide it into 2 parts: left and right + # get middle index of array to divide it into 2 parts: left and right + mid = len(arr) // 2 left = arr[:mid] # dividing list into 2 parts: left and right right = arr[mid:] # dividing list into 2 parts: left and right - left = MergeSort(left) # recursively call MergeSort function to sort left array - right = MergeSort(right) # recursively call MergeSort function to sort right array + # recursively call MergeSort function to sort left array + left = MergeSort(left) + # recursively call MergeSort function to sort right array + right = MergeSort(right) # MergeSort(left) # recursively call MergeSort function to sort left array # MergeSort(right) # recursively call MergeSort function to sort right array diff --git a/DSA-Python/Algorithms/SelectionSort.py b/DSA-Python/Algorithms/SelectionSort.py index 6a12802960..1cf302e248 100644 --- a/DSA-Python/Algorithms/SelectionSort.py +++ b/DSA-Python/Algorithms/SelectionSort.py @@ -4,6 +4,7 @@ Time Complexity: O(n^2) """ + def FindMin(arr): """finds minimum element from the list""" min = 100000 # let list contain +ve numbers only: so minimum number is -1 @@ -24,6 +25,7 @@ def SelectionSort(arr): if i != minIndex: arr[i], arr[minIndex] = arr[minIndex], arr[i] + if __name__ == '__main__': elements = [100, 19, 28, 14, 6, 1, 99] print(FindMin(elements)) # prints minimum element from the list @@ -42,4 +44,4 @@ def SelectionSort(arr): # print("Tests case testing...") for elements in tests: SelectionSort(elements) - print(elements) \ No newline at end of file + print(elements) diff --git a/DSA-Python/Algorithms/ShellSort.py b/DSA-Python/Algorithms/ShellSort.py index a51822b11e..8c05b2ad51 100644 --- a/DSA-Python/Algorithms/ShellSort.py +++ b/DSA-Python/Algorithms/ShellSort.py @@ -21,19 +21,22 @@ """ + def ShellSort(arr): # gap = 3 # initialised gap to 3 size = len(arr) gap = size // 2 # initialised gap to half of size of array while gap > 0: for i in range(gap, size): - pointer = arr[i] # pointer initialised to array such that gap is maintained + # pointer initialised to array such that gap is maintained + pointer = arr[i] j = i # get element which is at gap 3 and compare with current pointer element AND j>=gap else (j-gap) would be negative while j >= gap and arr[j - gap] > pointer: arr[j] = arr[j-gap] # swapped elements j -= gap # In each while loop iteration, reduce by gap for comparison with previous elements - arr[j] = pointer # after while loop ends, all elements have been swapped + # after while loop ends, all elements have been swapped + arr[j] = pointer # after function end, all heavy values are at right side and light values at left of partially-sorted array gap = gap // 2 # gap reduced by half @@ -55,4 +58,4 @@ def ShellSort(arr): for elements in tests: ShellSort(elements) - print(elements) \ No newline at end of file + print(elements) diff --git a/DSA-Python/Algorithms/recursion.py b/DSA-Python/Algorithms/recursion.py index 631b52c51c..7152c85dd7 100644 --- a/DSA-Python/Algorithms/recursion.py +++ b/DSA-Python/Algorithms/recursion.py @@ -7,7 +7,7 @@ def sumIteration(n): sum = 0 for i in range(1, n+1): - sum+=i + sum += i return sum @@ -28,7 +28,6 @@ def fibonacci(n): return fibonacci(n-1) + fibonacci(n-2) - if __name__ == '__main__': print(f"Sum using Iteration: {sumIteration(15)}") print(f"Sum using Recursion: {sumRecursion(15)}") diff --git a/DSA-Python/DataStructures/LinkedList.py b/DSA-Python/DataStructures/LinkedList.py index 9dbe99c747..7222229a58 100644 --- a/DSA-Python/DataStructures/LinkedList.py +++ b/DSA-Python/DataStructures/LinkedList.py @@ -20,21 +20,24 @@ Accessing Elements by Value -----> O(n) """ + class Node: ''' Working of Class Node: whenever this class is called, a data will be passed which will get saved in LinkedList as a node which has 2 parts: data & next ''' + def __init__(self, data=None, next=None): # initialised data to None self.data = data self.next = next + class LinkedList(): def __init__(self): self.head = Node() # Head is starting point of a Linked List and points to no other value # def accept_data(self, data): - def accept_data(self, *data): # args to get data at single go + def accept_data(self, *data): # args to get data at single go new_node = Node(data) # created a new node to add data cur = self.head # pointer set for the next data while cur.next != None: @@ -44,8 +47,8 @@ def accept_data(self, *data): # args to get data at single go cur = cur.next cur.next = new_node # pointer set to the new node - # method to print each element of Linked List + def display(self): disp = [] cur = self.head @@ -53,7 +56,8 @@ def display(self): while cur.next != None: # will iterate until next val of current pointer gets None cur = cur.next # accessing next element of the node - disp.append(cur.data) # appended the data of current element to the list disp[] + # appended the data of current element to the list disp[] + disp.append(cur.data) print(disp) # Method to get length of elements in Linked List @@ -85,7 +89,6 @@ def removeAtIndex(self, index): itr = itr.next count += 1 - def insertAtIndex(self, index, data): # check if index is valid if index < 0 or index >= self.getLength(): @@ -102,8 +105,7 @@ def insertAtIndex(self, index, data): node = Node(data, itr.next) itr.next = node itr = itr.next - count+=1 - + count += 1 l = LinkedList() # created an object 'l' to call class LinkedList @@ -141,4 +143,4 @@ def insertAtIndex(self, index, data): # l.accept_data(3) # l.accept_data(4) # l.accept_data(5) -# l.display() \ No newline at end of file +# l.display() diff --git a/DSA-Python/DataStructures/dictionary.py b/DSA-Python/DataStructures/dictionary.py index cc8fc0da15..22114284ed 100644 --- a/DSA-Python/DataStructures/dictionary.py +++ b/DSA-Python/DataStructures/dictionary.py @@ -3,14 +3,14 @@ Dictionaries are used to store key-value pairs which are mutable, or changeable, and ordered. ''' -#empty dictionary -dict = {} +# empty dictionary +dict = {} print("This is an empty Dictionary ", dict, end="\n\n") -#dictionary with elements +# dictionary with elements dict = { 1: 'Python', 'Two': 'Java', 3: 'Swift', - } +} print("Elements of dictionary are \n", dict, end="\n\n") @@ -18,12 +18,12 @@ print("**********Adding Elements**********") -#changing element -dict[3] = 'C++' +# changing element +dict[3] = 'C++' print(f"Changed 3rd element \n {dict}", end="\n\n") -#adding key-value pair -dict['Fourth'] = 'Swift' +# adding key-value pair +dict['Fourth'] = 'Swift' print("Added element \n", dict, end="\n\n") @@ -31,33 +31,32 @@ print("**********Accessing Elements**********") -#access elements using keys -print("First element is ", dict[1], end="\n\n") +# access elements using keys +print("First element is ", dict[1], end="\n\n") print("Fourth Element is ", dict.get('Fourth'), end="\n\n") -#get keys -print(f"Keys of the dictionary are \n{dict.keys()}", end="\n\n") +# get keys +print(f"Keys of the dictionary are \n{dict.keys()}", end="\n\n") -#get values -print(f"Values of the dictionary are \n{dict.values()}", end="\n\n") +# get values +print(f"Values of the dictionary are \n{dict.values()}", end="\n\n") -#get key-value pairs -print(f"Dictionary is \n{dict.items()}", end="\n\n") +# get key-value pairs +print(f"Dictionary is \n{dict.items()}", end="\n\n") ''' Deleting Elements ''' print("**********Deleting Elements**********") -#pop element -a = dict.pop('Fourth') +# pop element +a = dict.pop('Fourth') print(f"Deleted {a} \nNew dictionary {dict}", end="\n\n") -#pop the key-value pair -b = dict.popitem() +# pop the key-value pair +b = dict.popitem() print(f"Popped {b} \nNew dictionary {dict}", end="\n\n") -#empty dictionary -dict.clear() +# empty dictionary +dict.clear() print(f"Cleared dictionary {dict}", end="\n\n") - diff --git a/DSA-Python/DataStructures/graph.py b/DSA-Python/DataStructures/graph.py index eb6300a565..7e9db14fb8 100644 --- a/DSA-Python/DataStructures/graph.py +++ b/DSA-Python/DataStructures/graph.py @@ -33,6 +33,7 @@ """ + class Graph: def __init__(self, edges): self.edges = edges @@ -40,9 +41,11 @@ def __init__(self, edges): self.graph_dict = {} # blank dictionary for start, end in self.edges: if start in self.graph_dict: # element1 is already in dictionary - self.graph_dict[start].append(end) # add another element associated to element1 in graph_dictionary + # add another element associated to element1 in graph_dictionary + self.graph_dict[start].append(end) else: - self.graph_dict[start] = [end] # if element1 is not present, add it to graph_dictionary + # if element1 is not present, add it to graph_dictionary + self.graph_dict[start] = [end] print("Graph dictionary: ", self.graph_dict) # print route dictionary # get paths between start-point and end-point @@ -89,17 +92,15 @@ def getShortestPath(self, start, end, path=[]): return shortest_path - - if __name__ == '__main__': routes = [ - ("Mumbai","Pune"), + ("Mumbai", "Pune"), ("Mumbai", "Surat"), ("Surat", "Bangaluru"), - ("Pune","Hyderabad"), - ("Pune","Mysuru"), - ("Hyderabad","Bangaluru"), + ("Pune", "Hyderabad"), + ("Pune", "Mysuru"), + ("Hyderabad", "Bangaluru"), ("Hyderabad", "Chennai"), ("Mysuru", "Bangaluru"), ("Chennai", "Bangaluru") @@ -129,11 +130,15 @@ def getShortestPath(self, start, end, path=[]): start = "Mumbai" end = "New York" - print(f"All paths between: {start} and {end}: ",route_graph.getpath(start,end)) - print(f"Shortest path between {start} and {end}: ", route_graph.getShortestPath(start,end)) + print(f"All paths between: {start} and {end}: ", + route_graph.getpath(start, end)) + print(f"Shortest path between {start} and {end}: ", + route_graph.getShortestPath(start, end)) start = "Dubai" end = "New York" - print(f"All paths between: {start} and {end}: ",route_graph.getpath(start,end)) - print(f"Shortest path between {start} and {end}: ", route_graph.getShortestPath(start,end)) \ No newline at end of file + print(f"All paths between: {start} and {end}: ", + route_graph.getpath(start, end)) + print(f"Shortest path between {start} and {end}: ", + route_graph.getShortestPath(start, end)) diff --git a/DSA-Python/DataStructures/hashtable.py b/DSA-Python/DataStructures/hashtable.py index 51f9c87fd1..1970859f4a 100644 --- a/DSA-Python/DataStructures/hashtable.py +++ b/DSA-Python/DataStructures/hashtable.py @@ -9,24 +9,25 @@ C++ :: std::map """ + class HashTable(): """ In class hashTable, an array of size '100' is created which is initialised using list_comprehension; val in each element is None """ + def __init__(self): self.MAX = 100 # size of array = 100 self.arr = [None for i in range(self.MAX)] # list-comprehension - def get_hash(self, key): h = 0 for char in key: - h += ord(char) # returns ASCII val of char - return h%self.MAX # hash: Sum(ASCII_Values(key)) % size(array) + h += ord(char) # returns ASCII val of char + return h % self.MAX # hash: Sum(ASCII_Values(key)) % size(array) def add(self, key, val): - h = self.get_hash(key) # retrieving hash function + h = self.get_hash(key) # retrieving hash function self.arr[h] = val def get(self, key): @@ -38,8 +39,6 @@ def delete(self, key): self.arr[h] = None - - t = HashTable() # object of class HashTable q = t.add('Google', 120) r = t.get('Google') @@ -54,4 +53,3 @@ def delete(self, key): s = t.add('Google', 121) z = t.get('Google') print(z) - diff --git a/DSA-Python/DataStructures/list.py b/DSA-Python/DataStructures/list.py index 0737af250b..274bb38c15 100644 --- a/DSA-Python/DataStructures/list.py +++ b/DSA-Python/DataStructures/list.py @@ -25,37 +25,37 @@ print("**********Adding Elements**********", end="\n\n") -#add as a single element -list.append(["B", 4]) +# add as a single element +list.append(["B", 4]) print("Appended List ", list, end="\n\n") -#add as different elements -list.extend([5, 'E']) +# add as different elements +list.extend([5, 'E']) print("Entended List ", list, end="\n\n") -#add element at 1st Index -list.insert(0, 0) -list.insert(5, "F") +# add element at 1st Index +list.insert(0, 0) +list.insert(5, "F") print("Inserted Element ", list, end="\n\n") ''' Deleting Elements ''' print("**********Deleting Elements**********", end="\n\n") -#delete element at index 5 -del list[5] +# delete element at index 5 +del list[5] print("Deleted element ", list, end="\n\n") -#remove element with value '' -list.remove('E') +# remove element with value '' +list.remove('E') print("Removed element ", list, end="\n\n") -#pop element from list at i^th index -a = list.pop(1) +# pop element from list at i^th index +a = list.pop(1) print('Popped Element: ', a, ' List remaining: ', list, end="\n\n") -#empty the list -list.clear() +# empty the list +list.clear() print("Empty List ", list, end="\n\n") @@ -66,23 +66,23 @@ list = [1, 2, 3.5, "A", True] print("This is new list ", list, end="\n\n") -#access elements one by one +# access elements one by one print("Accessing all Elements one by one\n") -for element in list: +for element in list: print(element, end="\n") -#access all elements +# access all elements print("\nAccessing all elements\n") -print(list, end="\n\n") +print(list, end="\n\n") -#access index i element -print("Element at index=2 is", list[2], end="\n\n") +# access index i element +print("Element at index=2 is", list[2], end="\n\n") -#access elements from 0 to 1 and exclude 2 -print("Elements from index(0 to 1) are ", list[0:2], end="\n\n") +# access elements from 0 to 1 and exclude 2 +print("Elements from index(0 to 1) are ", list[0:2], end="\n\n") -#access elements in reverse -print("Elements in reverse order ", list[::-1], end="\n\n") +# access elements in reverse +print("Elements in reverse order ", list[::-1], end="\n\n") ''' @@ -98,18 +98,18 @@ list = [1, 2, 3, 10, 20, 50] -#find length of list -print("No of elements in the list ", len(list), end="\n\n") +# find length of list +print("No of elements in the list ", len(list), end="\n\n") -#find index of element that occurs first -print("Index of element 20 is ", list.index(20), end="\n\n") +# find index of element that occurs first +print("Index of element 20 is ", list.index(20), end="\n\n") -#find count of the element +# find count of the element print(f"Elements has been repeated {list.count(10)} time", end="\n\n") -#print sorted list but not change original -print("Sorted list is [AESC] ", sorted(list), end="\n\n") +# print sorted list but not change original +print("Sorted list is [AESC] ", sorted(list), end="\n\n") -#sort original list -list.sort(reverse=True) -print("Sorted list is [DESC]", list, end="\n\n") \ No newline at end of file +# sort original list +list.sort(reverse=True) +print("Sorted list is [DESC]", list, end="\n\n") diff --git a/DSA-Python/DataStructures/queue.py b/DSA-Python/DataStructures/queue.py index 5c13b14d3f..d9f60a51aa 100644 --- a/DSA-Python/DataStructures/queue.py +++ b/DSA-Python/DataStructures/queue.py @@ -49,13 +49,13 @@ # insert(), index(), remove(), count() -print (f"Index of 2 between index 0&3 is {queue.index(3,1,4)}", end="\n\n") # index(ele, begi, endi) : return First repetitive_index of element - -queue.insert(3,1) # insert(index,val) -print (f"Queue after inserting 1 at index3 {queue}", end="\n\n") - -print (f"1 has been repeated {queue.count(1)} times", end="\n\n") - -queue.remove(3) -print (f"Deleting first occurrence of 3 is{queue}", end="\n\n") +# index(ele, begi, endi) : return First repetitive_index of element +print(f"Index of 2 between index 0&3 is {queue.index(3,1,4)}", end="\n\n") + +queue.insert(3, 1) # insert(index,val) +print(f"Queue after inserting 1 at index3 {queue}", end="\n\n") +print(f"1 has been repeated {queue.count(1)} times", end="\n\n") + +queue.remove(3) +print(f"Deleting first occurrence of 3 is{queue}", end="\n\n") diff --git a/DSA-Python/DataStructures/sets.py b/DSA-Python/DataStructures/sets.py index b0840d8941..532e0c18e6 100644 --- a/DSA-Python/DataStructures/sets.py +++ b/DSA-Python/DataStructures/sets.py @@ -2,7 +2,7 @@ Sets are a collection of unordered elements that are unique. ''' -set = {1, 2, 1, 4, 'A' ,'B', 'A', 5} +set = {1, 2, 1, 4, 'A', 'B', 'A', 5} print(f"All the Unique elements of Set are {set}", end="\n\n") @@ -30,14 +30,15 @@ print("UNION ", set.union(set_2), '----------', set | set_2, end="\n\n") -print("INTERSECTION ", set.intersection(set_2), '----------', set & set_2, end="\n\n") +print("INTERSECTION ", set.intersection(set_2), + '----------', set & set_2, end="\n\n") -print("DIFFERENCE ", set.difference(set_2), '----------', set - set_2, end="\n\n") +print("DIFFERENCE ", set.difference(set_2), + '----------', set - set_2, end="\n\n") -print("SYMMETRIC-DIFFERENCE ",set.symmetric_difference(set_2), '----------', set ^ set_2, end="\n\n") +print("SYMMETRIC-DIFFERENCE ", set.symmetric_difference(set_2), + '----------', set ^ set_2, end="\n\n") set.clear() print(f"Deleted all elements of set {set}", end="\n\n") - - diff --git a/DSA-Python/DataStructures/stack.py b/DSA-Python/DataStructures/stack.py index 9318e2e756..57a4348d31 100644 --- a/DSA-Python/DataStructures/stack.py +++ b/DSA-Python/DataStructures/stack.py @@ -24,6 +24,8 @@ ''' ''' CLASS STACK() ''' + + class Stack(): def __init__(self): self.stack = list() @@ -43,7 +45,9 @@ def peek(self): def __str__(self): return str(self.stack) -''' CLASS STACK() END ''' + + +''' CLASS STACK() END ''' stack = list() # .append method to append items to the stack @@ -68,6 +72,4 @@ def __str__(self): print(f"Seek is at {stack.peek()}") - -#TODO: Stack continue ( https://youtu.be/kQDxmjfkIKY?t=3077 ) - +# TODO: Stack continue ( https://youtu.be/kQDxmjfkIKY?t=3077 ) diff --git a/DSA-Python/DataStructures/tree.py b/DSA-Python/DataStructures/tree.py index ec9ec151e2..a1d5e9b8bf 100644 --- a/DSA-Python/DataStructures/tree.py +++ b/DSA-Python/DataStructures/tree.py @@ -27,6 +27,7 @@ class TreeNode: """ Class TreeNode """ + def __init__(self, data): self.data = data self.children = [] @@ -34,34 +35,31 @@ def __init__(self, data): def add_child(self, child): """ Adds children elements to Tree """ - child.parent = self # child is an instance of class(node) + child.parent = self # child is an instance of class(node) # adding a child node to tree self.children.append(child) - def get_level(self): """ Gets the level of Tree by counting ancestors: if a node has no ancestor, it is root node """ - level = 0 # initialised level to 0 + level = 0 # initialised level to 0 p = self.parent while p: """keep on going through parents and increasing levels""" - level += 1 # increase level by 1 + level += 1 # increase level by 1 p = p.parent return level - def print_tree(self): """Display Tree in hierarchical format""" - spaces = ' ' * self.get_level() * 3 # printing 3 spaces for each level + spaces = ' ' * self.get_level() * 3 # printing 3 spaces for each level prefix = spaces + "|__" if self.parent else "" - print(prefix + self.data) # prints prefix(probably spaces) based on level + # prints prefix(probably spaces) based on level + print(prefix + self.data) # At leaf nodes, self.children will be an empty array... so we create a check if self.children() is an empty array or not - if self.children: # checks if len(self.children > 0) + if self.children: # checks if len(self.children > 0) for child in self.children: - child.print_tree() # It will recursively call this fn and print the sub-trees - - + child.print_tree() # It will recursively call this fn and print the sub-trees def electronic_product(): @@ -81,7 +79,6 @@ def electronic_product(): tv.add_child(TreeNode("Samsung")) tv.add_child(TreeNode("MI")) - root.add_child(laptop) root.add_child(cellphones) root.add_child(tv) @@ -93,17 +90,9 @@ def electronic_product(): return root - - - # main method if __name__ == '__main__': root = electronic_product() - root.print_tree() # prints tree in hierarchical format + root.print_tree() # prints tree in hierarchical format # print(root.get_level()) # 0 // get level of root node - - - - - diff --git a/DSA-Python/DataStructures/tuple.py b/DSA-Python/DataStructures/tuple.py index 3f55ccc2d1..c10e363549 100644 --- a/DSA-Python/DataStructures/tuple.py +++ b/DSA-Python/DataStructures/tuple.py @@ -6,8 +6,8 @@ print("**********Adding Elements**********", end="\n\n") -tuple = (1, 2, 3, 'Alphabet') -print(f"Tuple is {tuple}", end="\n\n") +tuple = (1, 2, 3, 'Alphabet') +print(f"Tuple is {tuple}", end="\n\n") ''' Accessing Elements ''' @@ -33,7 +33,7 @@ print("**********Appending Elements**********", end="\n\n") -tuple = tuple + (4, 5, ['B', 'C']) #add elements +tuple = tuple + (4, 5, ['B', 'C']) # add elements print(f"Tuple after appending elements is {tuple}", end="\n\n") # (1, 2, 3, 'Alphabet', 4, 5, ['B','C']) @@ -48,4 +48,3 @@ print(f"2 has been repeated {tuple.count(2)} time", end="\n\n") print(f"Index of ['K','C'] is {tuple.index(['K', 'C'])}", end="\n\n") - diff --git a/Data-Visualization/FunnelChart/FunnelCharts.py b/Data-Visualization/FunnelChart/FunnelCharts.py index 9db9d2a3c8..ac9ad3a938 100644 --- a/Data-Visualization/FunnelChart/FunnelCharts.py +++ b/Data-Visualization/FunnelChart/FunnelCharts.py @@ -3,31 +3,32 @@ fig = go.Figure() fig.add_trace(go.Funnel( - name = 'India', - y = ["McDonalds", "Dominoz", "PizzaHut", "Subway" , "MadOverDonuts" , "Keventers"], - x = [150, 140, 40, 50, 40 , 20], - textposition = "inside", - textinfo = "value+percent initial")) + name='India', + y=["McDonalds", "Dominoz", "PizzaHut", + "Subway", "MadOverDonuts", "Keventers"], + x=[150, 140, 40, 50, 40, 20], + textposition="inside", + textinfo="value+percent initial")) fig.add_trace(go.Funnel( - name = 'Bangladesh', - orientation = "h", - y = ["McDonalds", "Dominoz", "PizzaHut", "Subway"], - x = [50, 60, 40, 30], - textposition = "inside", - textinfo = "value+percent previous")) + name='Bangladesh', + orientation="h", + y=["McDonalds", "Dominoz", "PizzaHut", "Subway"], + x=[50, 60, 40, 30], + textposition="inside", + textinfo="value+percent previous")) fig.add_trace(go.Funnel( - name = 'SriLanka', - orientation = "h", - y = ["McDonalds", "Dominoz", "PizzaHut", "Subway" ,"MadOverDonuts" ], - x = [90, 70, 50, 30, 10], - textposition = "outside", - textinfo = "value+percent total")) + name='SriLanka', + orientation="h", + y=["McDonalds", "Dominoz", "PizzaHut", "Subway", "MadOverDonuts"], + x=[90, 70, 50, 30, 10], + textposition="outside", + textinfo="value+percent total")) fig.update_layout( - title = "Funnel Chart for Food Sales in Asian Countries", - showlegend = True + title="Funnel Chart for Food Sales in Asian Countries", + showlegend=True ) fig.layout.template = 'plotly_dark' -fig.show() \ No newline at end of file +fig.show() diff --git a/Data-Visualization/LineChart/line_chart.py b/Data-Visualization/LineChart/line_chart.py index 27791a7843..43588ffff4 100644 --- a/Data-Visualization/LineChart/line_chart.py +++ b/Data-Visualization/LineChart/line_chart.py @@ -1,6 +1,7 @@ import plotly.graph_objects as go import numpy as np + def create_line_chart(x_data, y_data): fig = go.Figure(data=go.Scatter(x=x_data, y=y_data)) @@ -18,6 +19,7 @@ def create_line_chart(x_data, y_data): ) fig.show() + if __name__ == "__main__": np.random.seed(42) diff --git a/Data-Visualization/TernaryPlots/TernaryPlot.py b/Data-Visualization/TernaryPlots/TernaryPlot.py index 0ece5038f9..6e7057807b 100644 --- a/Data-Visualization/TernaryPlots/TernaryPlot.py +++ b/Data-Visualization/TernaryPlots/TernaryPlot.py @@ -11,20 +11,20 @@ 'marker': { 'color': 'green', 'size': 14, - } , - + }, + })) fig.update_layout({ 'title': 'Ternary Scatter Plot', 'ternary': { - 'sum':1, - 'aaxis':{'title': 'Joly', 'min': 0.01, 'linewidth':2, 'ticks':'outside' }, - 'baxis':{'title': 'Coderre', 'min': 0.01, 'linewidth':2, 'ticks':'outside' }, - 'caxis':{'title': 'Bergeron', 'min': 0.01, 'linewidth':2, 'ticks':'outside' } - }, + 'sum': 1, + 'aaxis': {'title': 'Joly', 'min': 0.01, 'linewidth': 2, 'ticks': 'outside'}, + 'baxis': {'title': 'Coderre', 'min': 0.01, 'linewidth': 2, 'ticks': 'outside'}, + 'caxis': {'title': 'Bergeron', 'min': 0.01, 'linewidth': 2, 'ticks': 'outside'} + }, 'showlegend': False }) fig.layout.template = 'plotly_dark' -fig.show() \ No newline at end of file +fig.show() diff --git a/Data-Visualization/WaterfallChart/Waterfall.py b/Data-Visualization/WaterfallChart/Waterfall.py index f94ec9aa18..e95b63cea5 100644 --- a/Data-Visualization/WaterfallChart/Waterfall.py +++ b/Data-Visualization/WaterfallChart/Waterfall.py @@ -2,23 +2,24 @@ import plotly.graph_objects as go fig = go.Figure(go.Waterfall( - name = "20", - orientation = "v", - measure = ["relative", "relative", "relative", "relative", "relative", "total"], - x = ["Exp1", "Exp2", "Exp3", "Exp4", "Exp5", "Exp6"], - textposition = "outside", - text = ["100", "50", "130", "200", "40", "Total"], - y = [100, +50, 130, 200, 40, 0 ], - connector = {"line":{"color":"rgb(63, 63, 63)"}}, - increasing = {"marker":{"color":"green"}}, - totals = {"marker":{"color":"blue"}} + name="20", + orientation="v", + measure=["relative", "relative", "relative", + "relative", "relative", "total"], + x=["Exp1", "Exp2", "Exp3", "Exp4", "Exp5", "Exp6"], + textposition="outside", + text=["100", "50", "130", "200", "40", "Total"], + y=[100, +50, 130, 200, 40, 0], + connector={"line": {"color": "rgb(63, 63, 63)"}}, + increasing={"marker": {"color": "green"}}, + totals={"marker": {"color": "blue"}} )) fig.update_layout( - title = "Waterfall Chart", - showlegend = True , - xaxis_title='X Axis Title', - yaxis_title='Y Axis Title', + title="Waterfall Chart", + showlegend=True, + xaxis_title='X Axis Title', + yaxis_title='Y Axis Title', ) fig.layout.template = 'plotly_dark' -fig.show() \ No newline at end of file +fig.show() diff --git a/Decimal-to-hexa-decimal/decimal_to_hexa.py b/Decimal-to-hexa-decimal/decimal_to_hexa.py index 5e46d15135..3f96912fe7 100644 --- a/Decimal-to-hexa-decimal/decimal_to_hexa.py +++ b/Decimal-to-hexa-decimal/decimal_to_hexa.py @@ -1,17 +1,17 @@ # decimal to hexa decimal converter if __name__ == "__main__": - print('decimal to hexa-decimal converter using python') - def decimal_to_hexadecimal(): - try: - decimal_input = int(input("Enter a decimal number: ")) - hexadecimal_output = hex(decimal_input) - return hexadecimal_output - except ValueError: - raise ValueError("Invalid input. Please enter a valid decimal number.") + print('decimal to hexa-decimal converter using python') + + def decimal_to_hexadecimal(): + try: + decimal_input = int(input("Enter a decimal number: ")) + hexadecimal_output = hex(decimal_input) + return hexadecimal_output + except ValueError: + raise ValueError( + "Invalid input. Please enter a valid decimal number.") try: - hexadecimal_number = decimal_to_hexadecimal() - print(hexadecimal_number) + hexadecimal_number = decimal_to_hexadecimal() + print(hexadecimal_number) except ValueError as e: - print(str(e)) - - + print(str(e)) diff --git a/Dev.to Scraper/scraper.py b/Dev.to Scraper/scraper.py index ab9abf0d0b..deb49d45ca 100644 --- a/Dev.to Scraper/scraper.py +++ b/Dev.to Scraper/scraper.py @@ -85,7 +85,7 @@ pdf.output("{}.pdf".format(pdf_title)) count = count + 1 - if(count == number_articles): + if (count == number_articles): break driver.close() # closing the webdriver diff --git a/Dictionary-GUI/dictionary.py b/Dictionary-GUI/dictionary.py index aa21189e17..e21bdd255a 100644 --- a/Dictionary-GUI/dictionary.py +++ b/Dictionary-GUI/dictionary.py @@ -13,12 +13,12 @@ def getMeaning(): response = dictionary.meaning(word.get()) - if(response): - if('Noun' in response): + if (response): + if ('Noun' in response): meaning = response['Noun'][0] - elif('Verb' in response): + elif ('Verb' in response): meaning = response['Verb'][0] - elif('Adjective' in response): + elif ('Adjective' in response): meaning = response['Adjective'][0] else: meaning = "Invalid word" diff --git a/Digital Clock/Clock.py b/Digital Clock/Clock.py index f0df75d16f..d3a29806b6 100644 --- a/Digital Clock/Clock.py +++ b/Digital Clock/Clock.py @@ -18,4 +18,4 @@ def time(): label.pack(anchor='center') time() -mainloop() \ No newline at end of file +mainloop() diff --git a/Directory Tree Generator/tree.py b/Directory Tree Generator/tree.py index d24ea71ac0..c5c32acea4 100644 --- a/Directory Tree Generator/tree.py +++ b/Directory Tree Generator/tree.py @@ -20,7 +20,8 @@ def get_file_info(path, root=None): path = os.path.join(root, path) size = os.path.getsize(path) modified = os.path.getmtime(path) - modified_time = datetime.fromtimestamp(modified).strftime('%Y-%m-%d %H:%M:%S') + modified_time = datetime.fromtimestamp( + modified).strftime('%Y-%m-%d %H:%M:%S') return f'{realname(path, root=root)} (Size: {size} bytes, Modified: {modified_time})' @@ -51,8 +52,10 @@ def ptree(startpath, depth=-1): print("\nDirectory tree\n") parser = argparse.ArgumentParser(description='Prints directory tree.') - parser.add_argument('startpath', type=str, help='Path to starting directory') - parser.add_argument('-d', '--depth', type=int, default=-1, help='Depth of the directory tree') + parser.add_argument('startpath', type=str, + help='Path to starting directory') + parser.add_argument('-d', '--depth', type=int, default=- + 1, help='Depth of the directory tree') args = parser.parse_args() ptree(args.startpath, args.depth) diff --git a/Discord News Bot With AI/main.py b/Discord News Bot With AI/main.py index ca2d7b6fce..e14785b572 100644 --- a/Discord News Bot With AI/main.py +++ b/Discord News Bot With AI/main.py @@ -10,7 +10,6 @@ # Get a key at https://platform.openai.com/docs/api-reference - CLIENT_TOKEN = 'YOUR_DISCORD_TOKEN' # Get a token at the discord developer portal https://discord.com/developers/docs/intro @@ -25,7 +24,6 @@ } - intents = discord.Intents.default() intents.members = True @@ -34,8 +32,6 @@ latest_url = "" - - def get_latest_article(): global latest_article response = requests.get(url, params=params) @@ -53,18 +49,18 @@ async def send_article(): await channel.send(message) latest_url = latest_article['url'] response_text = f'\n {message}' - + # Feel free to add your own prompts prompt = "Come up with a sarcastic response to this news article " + response_text response = openai.Completion.create( - model="text-davinci-003", - prompt=prompt, - temperature=0.7, - max_tokens=60, - top_p=1, - frequency_penalty=0, - presence_penalty=0 - ) + model="text-davinci-003", + prompt=prompt, + temperature=0.7, + max_tokens=60, + top_p=1, + frequency_penalty=0, + presence_penalty=0 + ) sarcastic_response = response.choices[0].text.strip() if sarcastic_response: await channel.send(sarcastic_response) @@ -79,9 +75,8 @@ async def on_ready(): while True: await send_article() - await asyncio.sleep(10*60) # wait for 10 minutes before sending the next article to avoid using to many resources - - + # wait for 10 minutes before sending the next article to avoid using to many resources + await asyncio.sleep(10*60) -client.run(CLIENT_TOKEN) \ No newline at end of file +client.run(CLIENT_TOKEN) diff --git a/Discord-Bot/main.py b/Discord-Bot/main.py index c86d9639bb..0ee6c868a2 100644 --- a/Discord-Bot/main.py +++ b/Discord-Bot/main.py @@ -20,7 +20,8 @@ async def on_ready(): @bot.event async def on_member_join(member): - welcome_channel = discord.utils.get(member.guild.channels, name=WELCOME_CHANNEL) + welcome_channel = discord.utils.get( + member.guild.channels, name=WELCOME_CHANNEL) # Feel free to change this message! await welcome_channel.send(f"Welcome {member.mention}! Please read our rules and have a great time!") diff --git a/Disk Space Analyzer/DiskSpaceAnalyzer.py b/Disk Space Analyzer/DiskSpaceAnalyzer.py index 34ec875a66..f16845c9d1 100644 --- a/Disk Space Analyzer/DiskSpaceAnalyzer.py +++ b/Disk Space Analyzer/DiskSpaceAnalyzer.py @@ -1,5 +1,6 @@ import os + def get_size(path): total_size = 0 if os.path.isfile(path): @@ -11,6 +12,7 @@ def get_size(path): total_size += os.path.getsize(fp) return total_size + def analyze_disk_space(directory): files = [] folders = [] @@ -21,22 +23,23 @@ def analyze_disk_space(directory): elif entry.is_dir(): size = get_size(entry.path) folders.append((entry.name, size)) - + sorted_files = sorted(files, key=lambda x: x[1], reverse=True) sorted_folders = sorted(folders, key=lambda x: x[1], reverse=True) - + print("Files:") for file in sorted_files: name, size = file print(f"{name}: {size} bytes") - + print("\nFolders:") for folder in sorted_folders: name, size = folder print(f"{name}: {size} bytes") + # Specify the directory to analyze -directory = r"C:\Users\python" #insert your directory path here +directory = r"C:\Users\python" # insert your directory path here # Analyze the disk space analyze_disk_space(directory) diff --git a/Distance Conversion GUI/distance_conversion.py b/Distance Conversion GUI/distance_conversion.py index 4911f5b82c..d6a8543cf3 100644 --- a/Distance Conversion GUI/distance_conversion.py +++ b/Distance Conversion GUI/distance_conversion.py @@ -32,7 +32,7 @@ def convert(): 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): + if (ip_unit == op_unit): messagebox.showwarning("Warning", "Select different units") # else perform conversion else: diff --git a/Doh-Dig/dog-dig.py b/Doh-Dig/dog-dig.py index 89d5bdf0e4..3619a50230 100644 --- a/Doh-Dig/dog-dig.py +++ b/Doh-Dig/dog-dig.py @@ -1,7 +1,9 @@ import os import requests -DOH_SERVER = os.environ.get("DOH_SERVER", "https://cloudflare-dns.com/dns-query") +DOH_SERVER = os.environ.get( + "DOH_SERVER", "https://cloudflare-dns.com/dns-query") + def doh_dns_lookup(domain, record_type): url = f"{DOH_SERVER}?name={domain}&type={record_type}" diff --git a/Dot_Connect/DotConnect.py b/Dot_Connect/DotConnect.py index 8bf3acfa0b..bc6bb7e95e 100644 --- a/Dot_Connect/DotConnect.py +++ b/Dot_Connect/DotConnect.py @@ -11,6 +11,8 @@ GAME_WIDTH = 400 # Player Class + + class Player: def __init__(self, name, color="#00BFFF"): # Blue color self.score = 0 @@ -28,27 +30,34 @@ def __init__(self, master): Frame.__init__(self, master) # Fonts - self.title_font = font.Font(self, name="TitleFont", family="Arial", weight="bold", size=36) + self.title_font = font.Font( + self, name="TitleFont", family="Arial", weight="bold", size=36) # Info Frame self.info_frame = Frame(self, bg="#333333") # Dark gray background - self.players = [Player("Player A", "#00BFFF"), Player("Player B", "#00FF00")] # Blue and Green colors - self.info_frame.players = [Label(self.info_frame, textvariable=i.text_var, bg="#FFFFFF", fg="#333333", font="Arial 20 bold") for i in self.players] # White text on dark gray background + self.players = [Player("Player A", "#00BFFF"), Player( + "Player B", "#00FF00")] # Blue and Green colors + self.info_frame.players = [Label(self.info_frame, textvariable=i.text_var, bg="#FFFFFF", fg="#333333", + font="Arial 20 bold") for i in self.players] # White text on dark gray background for i in self.info_frame.players: i.grid() self.info_frame.grid(row=0, column=0, columnspan=2, pady=10) # Canvas - self.canvas = Canvas(self, height=GAME_HEIGHT, width=GAME_WIDTH, bg="#333333") # Dark gray background + # Dark gray background + self.canvas = Canvas(self, height=GAME_HEIGHT, + width=GAME_WIDTH, bg="#333333") self.canvas.bind("", lambda e: self.click(e)) self.canvas.grid(row=1, column=0, padx=10) # Dots - self.dots = [[self.canvas.create_oval(CELL_SIZE*i+OFFSET, CELL_SIZE*j+OFFSET, CELL_SIZE*i+OFFSET+2*CIRCLE_RADIUS, CELL_SIZE*j+OFFSET+2*CIRCLE_RADIUS, fill="#000000") for j in range(10)] for i in range(10)] # Black dots + self.dots = [[self.canvas.create_oval(CELL_SIZE*i+OFFSET, CELL_SIZE*j+OFFSET, CELL_SIZE*i+OFFSET+2*CIRCLE_RADIUS, + CELL_SIZE*j+OFFSET+2*CIRCLE_RADIUS, fill="#000000") for j in range(10)] for i in range(10)] # Black dots self.lines = [] # Reset Game Button - self.reset_button = Button(self, text="Reset Game", command=self.reset_game, font="Arial 14 bold", bg="#FF0000", fg="#000000") # Red button with white text + self.reset_button = Button(self, text="Reset Game", command=self.reset_game, + font="Arial 14 bold", bg="#FF0000", fg="#000000") # Red button with white text self.reset_button.grid(row=2, column=0, pady=10) self.turn = self.players[0] @@ -122,12 +131,14 @@ def find_lines(self, coords): if y < 0 or y > GAME_WIDTH: return [] - lines = [x for x in self.canvas.find_enclosed(x - CELL_SIZE, y - CELL_SIZE, x + CELL_SIZE, y + CELL_SIZE) if x in self.lines] + lines = [x for x in self.canvas.find_enclosed( + x - CELL_SIZE, y - CELL_SIZE, x + CELL_SIZE, y + CELL_SIZE) if x in self.lines] return lines def fill_box(self, coords): x, y = coords - self.canvas.create_text(x, y, text=self.turn.name, fill=self.turn.color, font="Arial 5 bold") + self.canvas.create_text(x, y, text=self.turn.name, + fill=self.turn.color, font="Arial 5 bold") def check_proximity(self, x, y): x -= OFFSET @@ -174,6 +185,6 @@ def reset_game(self): # Main Tkinter Window main_window = Tk() main_window.title("Dot Connect") -main_window.config(bg="#000000") +main_window.config(bg="#000000") main_window.frame = DotConnectFrame(main_window) main_window.mainloop() diff --git a/Download-page-as-pdf/main.py b/Download-page-as-pdf/main.py index 5e26c87767..e40e33548b 100644 --- a/Download-page-as-pdf/main.py +++ b/Download-page-as-pdf/main.py @@ -8,11 +8,11 @@ def main(): - parser = argparse.ArgumentParser(description = 'Page Downloader as PDF') - parser.add_argument('--link', '-l', action = 'store', dest = 'link', - required = True, help = 'Inform the link to download.') - parser.add_argument('--name', '-n', action = 'store', dest = 'name', - required = False, help = 'Inform the name to save.') + parser = argparse.ArgumentParser(description='Page Downloader as PDF') + parser.add_argument('--link', '-l', action='store', dest='link', + required=True, help='Inform the link to download.') + parser.add_argument('--name', '-n', action='store', dest='name', + required=False, help='Inform the name to save.') arguments = parser.parse_args() @@ -38,5 +38,6 @@ def main(): except NetworkError: print('No access to the network.') + if __name__ == '__main__': main() diff --git a/Drowsiness-Detector/drowsiness detection.py b/Drowsiness-Detector/drowsiness detection.py index 36f1f2209a..1ef3559f10 100644 --- a/Drowsiness-Detector/drowsiness detection.py +++ b/Drowsiness-Detector/drowsiness detection.py @@ -9,97 +9,103 @@ mixer.init() sound = mixer.Sound('alarm.wav') -face = cv2.CascadeClassifier('haar cascade files\haarcascade_frontalface_alt.xml') -leye = cv2.CascadeClassifier('haar cascade files\haarcascade_lefteye_2splits.xml') -reye = cv2.CascadeClassifier('haar cascade files\haarcascade_righteye_2splits.xml') +face = cv2.CascadeClassifier( + 'haar cascade files\haarcascade_frontalface_alt.xml') +leye = cv2.CascadeClassifier( + 'haar cascade files\haarcascade_lefteye_2splits.xml') +reye = cv2.CascadeClassifier( + 'haar cascade files\haarcascade_righteye_2splits.xml') - -lbl=['Close','Open'] +lbl = ['Close', 'Open'] model = load_model('models/cnncat2.h5') path = os.getcwd() cap = cv2.VideoCapture(0) font = cv2.FONT_HERSHEY_COMPLEX_SMALL -count=0 -score=0 -thicc=2 -rpred=[99] -lpred=[99] +count = 0 +score = 0 +thicc = 2 +rpred = [99] +lpred = [99] -while(True): +while (True): ret, frame = cap.read() - height,width = frame.shape[:2] + height, width = frame.shape[:2] gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) - - faces = face.detectMultiScale(gray,minNeighbors=5,scaleFactor=1.1,minSize=(25,25)) + + faces = face.detectMultiScale( + gray, minNeighbors=5, scaleFactor=1.1, minSize=(25, 25)) left_eye = leye.detectMultiScale(gray) - right_eye = reye.detectMultiScale(gray) + right_eye = reye.detectMultiScale(gray) - cv2.rectangle(frame, (0,height-50) , (200,height) , (0,0,0) , thickness=cv2.FILLED ) + cv2.rectangle(frame, (0, height-50), (200, height), + (0, 0, 0), thickness=cv2.FILLED) - for (x,y,w,h) in faces: - cv2.rectangle(frame, (x,y) , (x+w,y+h) , (100,100,100) , 1 ) + for (x, y, w, h) in faces: + cv2.rectangle(frame, (x, y), (x+w, y+h), (100, 100, 100), 1) - for (x,y,w,h) in right_eye: - r_eye=frame[y:y+h,x:x+w] - count=count+1 - r_eye = cv2.cvtColor(r_eye,cv2.COLOR_BGR2GRAY) - r_eye = cv2.resize(r_eye,(24,24)) - r_eye= r_eye/255 - r_eye= r_eye.reshape(24,24,-1) - r_eye = np.expand_dims(r_eye,axis=0) + for (x, y, w, h) in right_eye: + r_eye = frame[y:y+h, x:x+w] + count = count+1 + r_eye = cv2.cvtColor(r_eye, cv2.COLOR_BGR2GRAY) + r_eye = cv2.resize(r_eye, (24, 24)) + r_eye = r_eye/255 + r_eye = r_eye.reshape(24, 24, -1) + r_eye = np.expand_dims(r_eye, axis=0) rpred = model.predict_classes(r_eye) - if(rpred[0]==1): - lbl='Open' - if(rpred[0]==0): - lbl='Closed' + if (rpred[0] == 1): + lbl = 'Open' + if (rpred[0] == 0): + lbl = 'Closed' break - for (x,y,w,h) in left_eye: - l_eye=frame[y:y+h,x:x+w] - count=count+1 - l_eye = cv2.cvtColor(l_eye,cv2.COLOR_BGR2GRAY) - l_eye = cv2.resize(l_eye,(24,24)) - l_eye= l_eye/255 - l_eye=l_eye.reshape(24,24,-1) - l_eye = np.expand_dims(l_eye,axis=0) + for (x, y, w, h) in left_eye: + l_eye = frame[y:y+h, x:x+w] + count = count+1 + l_eye = cv2.cvtColor(l_eye, cv2.COLOR_BGR2GRAY) + l_eye = cv2.resize(l_eye, (24, 24)) + l_eye = l_eye/255 + l_eye = l_eye.reshape(24, 24, -1) + l_eye = np.expand_dims(l_eye, axis=0) lpred = model.predict_classes(l_eye) - if(lpred[0]==1): - lbl='Open' - if(lpred[0]==0): - lbl='Closed' + if (lpred[0] == 1): + lbl = 'Open' + if (lpred[0] == 0): + lbl = 'Closed' break - if(rpred[0]==0 and lpred[0]==0): - score=score+1 - cv2.putText(frame,"Closed",(10,height-20), font, 1,(255,255,255),1,cv2.LINE_AA) + if (rpred[0] == 0 and lpred[0] == 0): + score = score+1 + cv2.putText(frame, "Closed", (10, height-20), font, + 1, (255, 255, 255), 1, cv2.LINE_AA) # if(rpred[0]==1 or lpred[0]==1): else: - score=score-1 - cv2.putText(frame,"Open",(10,height-20), font, 1,(255,255,255),1,cv2.LINE_AA) - - - if(score<0): - score=0 - cv2.putText(frame,'Score:'+str(score),(100,height-20), font, 1,(255,255,255),1,cv2.LINE_AA) - if(score>15): - #person is feeling sleepy so we beep the alarm - cv2.imwrite(os.path.join(path,'image.jpg'),frame) + score = score-1 + cv2.putText(frame, "Open", (10, height-20), font, + 1, (255, 255, 255), 1, cv2.LINE_AA) + + if (score < 0): + score = 0 + cv2.putText(frame, 'Score:'+str(score), (100, height-20), + font, 1, (255, 255, 255), 1, cv2.LINE_AA) + if (score > 15): + # person is feeling sleepy so we beep the alarm + cv2.imwrite(os.path.join(path, 'image.jpg'), frame) try: sound.play() - + except: # isplaying = False pass - if(thicc<16): - thicc= thicc+2 + if (thicc < 16): + thicc = thicc+2 else: - thicc=thicc-2 - if(thicc<2): - thicc=2 - cv2.rectangle(frame,(0,0),(width,height),(0,0,255),thicc) - cv2.imshow('frame',frame) + thicc = thicc-2 + if (thicc < 2): + thicc = 2 + cv2.rectangle(frame, (0, 0), (width, height), (0, 0, 255), thicc) + cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() diff --git a/Drowsiness-Detector/model.py b/Drowsiness-Detector/model.py index 614cec4d63..fc9facb8fb 100644 --- a/Drowsiness-Detector/model.py +++ b/Drowsiness-Detector/model.py @@ -1,57 +1,63 @@ import os from keras.preprocessing import image -import matplotlib.pyplot as plt +import matplotlib.pyplot as plt import numpy as np from keras.utils.np_utils import to_categorical -import random,shutil +import random +import shutil from keras.models import Sequential -from keras.layers import Dropout,Conv2D,Flatten,Dense, MaxPooling2D, BatchNormalization +from keras.layers import Dropout, Conv2D, Flatten, Dense, MaxPooling2D, BatchNormalization from keras.models import load_model -def generator(dir, gen=image.ImageDataGenerator(rescale=1./255), shuffle=True,batch_size=1,target_size=(24,24),class_mode='categorical' ): +def generator(dir, gen=image.ImageDataGenerator(rescale=1./255), shuffle=True, batch_size=1, target_size=(24, 24), class_mode='categorical'): - return gen.flow_from_directory(dir,batch_size=batch_size,shuffle=shuffle,color_mode='grayscale',class_mode=class_mode,target_size=target_size) + return gen.flow_from_directory(dir, batch_size=batch_size, shuffle=shuffle, color_mode='grayscale', class_mode=class_mode, target_size=target_size) -BS= 32 -TS=(24,24) -train_batch= generator('data/train',shuffle=True, batch_size=BS,target_size=TS) -valid_batch= generator('data/valid',shuffle=True, batch_size=BS,target_size=TS) -SPE= len(train_batch.classes)//BS + +BS = 32 +TS = (24, 24) +train_batch = generator('data/train', shuffle=True, + batch_size=BS, target_size=TS) +valid_batch = generator('data/valid', shuffle=True, + batch_size=BS, target_size=TS) +SPE = len(train_batch.classes)//BS VS = len(valid_batch.classes)//BS -print(SPE,VS) +print(SPE, VS) # img,labels= next(train_batch) # print(img.shape) model = Sequential([ - Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(24,24,1)), - MaxPooling2D(pool_size=(1,1)), - Conv2D(32,(3,3),activation='relu'), - MaxPooling2D(pool_size=(1,1)), -#32 convolution filters used each of size 3x3 -#again + Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(24, 24, 1)), + MaxPooling2D(pool_size=(1, 1)), + Conv2D(32, (3, 3), activation='relu'), + MaxPooling2D(pool_size=(1, 1)), + # 32 convolution filters used each of size 3x3 + # again Conv2D(64, (3, 3), activation='relu'), - MaxPooling2D(pool_size=(1,1)), + MaxPooling2D(pool_size=(1, 1)), + + # 64 convolution filters used each of size 3x3 + # choose the best features via pooling -#64 convolution filters used each of size 3x3 -#choose the best features via pooling - -#randomly turn neurons on and off to improve convergence + # randomly turn neurons on and off to improve convergence Dropout(0.25), -#flatten since too many dimensions, we only want a classification output + # flatten since too many dimensions, we only want a classification output Flatten(), -#fully connected to get all relevant data + # fully connected to get all relevant data Dense(128, activation='relu'), -#one more dropout for convergence' sake :) + # one more dropout for convergence' sake :) Dropout(0.5), -#output a softmax to squash the matrix into output probabilities + # output a softmax to squash the matrix into output probabilities Dense(2, activation='softmax') ]) -model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy']) +model.compile(optimizer='adam', loss='categorical_crossentropy', + metrics=['accuracy']) -model.fit_generator(train_batch, validation_data=valid_batch,epochs=15,steps_per_epoch=SPE ,validation_steps=VS) +model.fit_generator(train_batch, validation_data=valid_batch, + epochs=15, steps_per_epoch=SPE, validation_steps=VS) -model.save('models/cnnCat2.h5', overwrite=True) \ No newline at end of file +model.save('models/cnnCat2.h5', overwrite=True) diff --git a/EazyDiner-Scraper/restaurants.py b/EazyDiner-Scraper/restaurants.py index b23a06a009..2d609d5cf1 100644 --- a/EazyDiner-Scraper/restaurants.py +++ b/EazyDiner-Scraper/restaurants.py @@ -50,7 +50,8 @@ def getRestaurants(self): location = r.find("h3", class_="res_loc").getText().strip() rating = r.find("span", class_="critic").getText().strip() cuisine = ( - r.find("div", class_="res_cuisine").getText().replace(",", ", ") + r.find("div", class_="res_cuisine").getText().replace( + ",", ", ") ) price = ( r.find("span", class_="cost_for_two") diff --git a/Email GUI/script.py b/Email GUI/script.py index c9e41a5bc9..756beccf6f 100644 --- a/Email GUI/script.py +++ b/Email GUI/script.py @@ -3,32 +3,32 @@ def send_message(): - + address_info = address.get() - + email_body_info = email_body.get() sender_info = sender_address.get() password_info = password.get() - - server = smtplib.SMTP('smtp.gmail.com',587) - + + server = smtplib.SMTP('smtp.gmail.com', 587) + server.starttls() - - server.login(sender_info,password_info) - + + server.login(sender_info, password_info) + print("Login successful") - - server.sendmail(sender_info,address_info,email_body_info) - + + server.sendmail(sender_info, address_info, email_body_info) + print("Message sent") - - address_entry.delete(0,END) - email_body_entry.delete(0,END) - password_entry.delete(0,END) - sender_address_entry.delete(0,END) - + + address_entry.delete(0, END) + email_body_entry.delete(0, END) + password_entry.delete(0, END) + sender_address_entry.delete(0, END) + gui = Tk() @@ -36,41 +36,43 @@ def send_message(): gui.title("Email Sender App") -heading = Label(text="Email Sender App",bg="yellow",fg="black",font="10",width="500",height="3") +heading = Label(text="Email Sender App", bg="yellow", + fg="black", font="10", width="500", height="3") heading.pack() -gui.configure(background = "light blue") +gui.configure(background="light blue") sender_address_field = Label(text="Sender's Email :") -sender_address_field.place(x=15,y=70) +sender_address_field.place(x=15, y=70) sender_address = StringVar() -sender_address_entry = Entry(textvariable=sender_address,width="30") -sender_address_entry.place(x=15,y=100) +sender_address_entry = Entry(textvariable=sender_address, width="30") +sender_address_entry.place(x=15, y=100) sender_password_field = Label(text="Sender's Password :") -sender_password_field.place(x=15,y=140) +sender_password_field.place(x=15, y=140) password = StringVar() -password_entry = Entry(textvariable=password,width="30") -password_entry.place(x=15,y=170) +password_entry = Entry(textvariable=password, width="30") +password_entry.place(x=15, y=170) address_field = Label(text="Recipient Email :") -address_field.place(x=15,y=210) +address_field.place(x=15, y=210) address = StringVar() -address_entry = Entry(textvariable=address,width="30") -address_entry.place(x=15,y=240) +address_entry = Entry(textvariable=address, width="30") +address_entry.place(x=15, y=240) email_body_field = Label(text="Message :") -email_body_field.place(x=15,y=280) +email_body_field.place(x=15, y=280) email_body = StringVar() -email_body_entry = Entry(textvariable=email_body,width="30") -email_body_entry.place(x=15,y=320,height="30") +email_body_entry = Entry(textvariable=email_body, width="30") +email_body_entry.place(x=15, y=320, height="30") -button = Button(gui,text="Send Message",command=send_message,width="30",height="2",bg="grey") +button = Button(gui, text="Send Message", command=send_message, + width="30", height="2", bg="grey") -button.place(x=15,y=400) +button.place(x=15, y=400) mainloop() diff --git a/Email-Validator/email_verification.py b/Email-Validator/email_verification.py index 4138fa6e32..91a27a64c0 100644 --- a/Email-Validator/email_verification.py +++ b/Email-Validator/email_verification.py @@ -8,7 +8,7 @@ def check_syntax(email): regex = r'^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' - if(re.search(regex, email)): + if (re.search(regex, email)): print("Check 1 (Syntax) Passed") else: print("Check 1 FAILED! Bad Syntax, Invalid Email!") diff --git a/Email-With-Files/sendemail.py b/Email-With-Files/sendemail.py index b6261040ee..f391db428f 100644 --- a/Email-With-Files/sendemail.py +++ b/Email-With-Files/sendemail.py @@ -47,4 +47,4 @@ def send_mail(send_from, send_to, subject, message, files=[], smtp.starttls() smtp.login(username, password) smtp.sendmail(send_from, send_to, msg.as_string()) - smtp.quit() \ No newline at end of file + smtp.quit() diff --git a/Excel_File_Merger/Excel_file_merger.py b/Excel_File_Merger/Excel_file_merger.py index 84daa24707..689fa4e564 100644 --- a/Excel_File_Merger/Excel_file_merger.py +++ b/Excel_File_Merger/Excel_file_merger.py @@ -32,4 +32,4 @@ def reader(file): rows = reader(file) for row in rows: sheet.append(row) - book.save(filename=workbook_name) \ No newline at end of file + book.save(filename=workbook_name) diff --git a/Expense Tracker/script.py b/Expense Tracker/script.py index f2fb2ac74e..f25b6f5072 100644 --- a/Expense Tracker/script.py +++ b/Expense Tracker/script.py @@ -10,24 +10,25 @@ def Addexpense(): x = Edate.get() y = Item.get() z = Eexpense.get() - data = [x,y,z] - + data = [x, y, z] + with db: c = db.cursor() - c.execute("INSERT INTO expense(Dates, Items, Expense) VALUES(?,?,?)",(x,y,z)) - + c.execute( + "INSERT INTO expense(Dates, Items, Expense) VALUES(?,?,?)", (x, y, z)) def show(): x = Edate.get() y = Item.get() z = Eexpense.get() - data = [x,y,z] - connt=sqlite3.connect('./Expense Tracker/expense.db') - cursor=connt.cursor() + data = [x, y, z] + connt = sqlite3.connect('./Expense Tracker/expense.db') + cursor = connt.cursor() cursor.execute("SELECT * FROM expense") for row in cursor.fetchall(): - TVExpense.insert('','end',values=row) + TVExpense.insert('', 'end', values=row) + def delete(): with db: @@ -37,6 +38,7 @@ def delete(): db.commit() show() + db = sqlite3.connect('./Expense Tracker/expense.db') c = db.cursor() @@ -60,46 +62,47 @@ def delete(): Tab.pack(fill=BOTH, expand=1) -ldate = ttk.Label(F1, text="Date", font=(None,18)) +ldate = ttk.Label(F1, text="Date", font=(None, 18)) ldate.grid(row=0, column=0, padx=5, pady=5, sticky='w') -Edate = DateEntry(F1, width=19, background = 'blue', foreground='white', font=(None,18)) -Edate.grid(row=0, column=1, padx=5,pady=5, sticky='w') +Edate = DateEntry(F1, width=19, background='blue', + foreground='white', font=(None, 18)) +Edate.grid(row=0, column=1, padx=5, pady=5, sticky='w') -ltitle = ttk.Label(F1, text="Items",font=(None,18)) +ltitle = ttk.Label(F1, text="Items", font=(None, 18)) ltitle.grid(row=1, column=0, padx=5, pady=5, sticky='w') Item = StringVar() -Etitle = ttk.Entry(F1, textvariable=Item,font=(None,18)) +Etitle = ttk.Entry(F1, textvariable=Item, font=(None, 18)) Etitle.grid(row=1, column=1, padx=5, pady=5, sticky='w') -lexpense = ttk.Label(F1, text="Expense",font=(None,18)) +lexpense = ttk.Label(F1, text="Expense", font=(None, 18)) lexpense.grid(row=2, column=0, padx=5, pady=5, sticky='w') Expense = StringVar() -Eexpense = ttk.Entry(F1, textvariable=Expense,font=(None,18)) +Eexpense = ttk.Entry(F1, textvariable=Expense, font=(None, 18)) Eexpense.grid(row=2, column=1, padx=5, pady=5, sticky='w') -btn = ttk.Button(F1,text='Add', command=Addexpense) +btn = ttk.Button(F1, text='Add', command=Addexpense) btn.grid(row=3, column=1, padx=5, pady=5, sticky='w', ipadx=10, ipady=10) -Ldel = ttk.Label(F1, text='Delete',font=(None,18)) +Ldel = ttk.Label(F1, text='Delete', font=(None, 18)) Ldel.grid(row=4, column=0, padx=5, pady=5, sticky='w') Delete = StringVar() -dell = ttk.Entry(F1, textvariable=Delete,font=(None,18)) +dell = ttk.Entry(F1, textvariable=Delete, font=(None, 18)) dell.grid(row=4, column=1, padx=5, pady=5, sticky='w') -btn2 = ttk.Button(F1,text='Delete', command=delete) +btn2 = ttk.Button(F1, text='Delete', command=delete) btn2.grid(row=5, column=1, padx=5, pady=5, sticky='w', ipadx=10, ipady=10) -btn1 = ttk.Button(F1,text='Show', command=show) +btn1 = ttk.Button(F1, text='Show', command=show) btn1.grid(row=3, column=2, padx=5, pady=5, sticky='w', ipadx=10, ipady=10) -TVList = ['Date','Item','Expense'] +TVList = ['Date', 'Item', 'Expense'] TVExpense = ttk.Treeview(F1, column=TVList, show='headings', height=5) for i in TVList: @@ -108,4 +111,4 @@ def delete(): TVExpense.grid(row=6, column=0, padx=5, pady=5, sticky='w', columnspan=3) gui.mainloop() -db.close() \ No newline at end of file +db.close() diff --git a/Eye Detection/eyes.py b/Eye Detection/eyes.py index c1c0ec714d..179f5364ff 100644 --- a/Eye Detection/eyes.py +++ b/Eye Detection/eyes.py @@ -6,7 +6,7 @@ if (capture.isOpened() == False): print("Sorry") -while(capture.isOpened()): +while (capture.isOpened()): # Load trained cascade classifier ret, color_image = capture.read() diff --git a/Face-Mask-Detection/face_mask_detection_using_cnn.py b/Face-Mask-Detection/face_mask_detection_using_cnn.py index 85fe7d9757..a0d1c45c1a 100644 --- a/Face-Mask-Detection/face_mask_detection_using_cnn.py +++ b/Face-Mask-Detection/face_mask_detection_using_cnn.py @@ -37,7 +37,7 @@ def data_set(dir_data): ymin = int(df1['ymin'][i]) xmax = int(df1['xmax'][i]) ymax = int(df1['ymax'][i]) - #image=image[ymin:ymax, xmin:xmax] + # image=image[ymin:ymax, xmin:xmax] try: # resizing to (70 x 70) image = cv2.resize(image, (70, 70)) @@ -45,7 +45,7 @@ def data_set(dir_data): skipped += 1 print(E) continue - if(df1['class'][i] == 'mask'): + if (df1['class'][i] == 'mask'): without_mask = 'with_mask' image = img_to_array(image) data.append(image) diff --git a/Face_Detection_using_openCV/script.py b/Face_Detection_using_openCV/script.py index 2601f49f6a..08fac5042a 100644 --- a/Face_Detection_using_openCV/script.py +++ b/Face_Detection_using_openCV/script.py @@ -5,53 +5,52 @@ import cv2 import pandas -video=cv2.VideoCapture(0) -first_frame=None -status_list=[None,None] -time=[] -df=pandas.DataFrame(columns=["Start","End"]) -cnts= [[0,0], [255,0], [255,255], [0,255]] +video = cv2.VideoCapture(0) +first_frame = None +status_list = [None, None] +time = [] +df = pandas.DataFrame(columns=["Start", "End"]) +cnts = [[0, 0], [255, 0], [255, 255], [0, 255]] while True: check, frame = video.read() - status=0 - gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) - gray=cv2.GaussianBlur(gray,(21,21),0) + status = 0 + gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) + gray = cv2.GaussianBlur(gray, (21, 21), 0) if first_frame is None: - first_frame=gray + first_frame = gray continue - delta_frame=cv2.absdiff(first_frame,gray) - thresh_data=cv2.threshold(delta_frame,30,255,cv2.THRESH_BINARY)[1] - thresh_delta=cv2.dilate(thresh_data,None,iterations=5) - (cnts,_) =cv2.findContours(thresh_data.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) + delta_frame = cv2.absdiff(first_frame, gray) + thresh_data = cv2.threshold(delta_frame, 30, 255, cv2.THRESH_BINARY)[1] + thresh_delta = cv2.dilate(thresh_data, None, iterations=5) + (cnts, _) = cv2.findContours(thresh_data.copy(), + cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in cnts: - if cv2.contourArea(contour)<10000: + if cv2.contourArea(contour) < 10000: continue - status=1 - (x,y,w,h)=cv2.boundingRect(contour) - cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),3) + status = 1 + (x, y, w, h) = cv2.boundingRect(contour) + cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 3) status_list.append(status) - if status_list[-1]==1 and status_list[-2]==0: + if status_list[-1] == 1 and status_list[-2] == 0: time.append(datetime.now()) - if status_list[-1]==0 and status_list[-2]==1: + if status_list[-1] == 0 and status_list[-2] == 1: time.append(datetime.now()) cv2.imshow("Capturing", gray) - cv2.imshow("Delta Frame",delta_frame) - cv2.imshow("Threshold Frame",thresh_data) - cv2.imshow("Colour Frame",frame) + cv2.imshow("Delta Frame", delta_frame) + cv2.imshow("Threshold Frame", thresh_data) + cv2.imshow("Colour Frame", frame) - - key=cv2.waitKey(1) - if key==ord('q'): - if status==1: + key = cv2.waitKey(1) + if key == ord('q'): + if status == 1: time.append(datetime.now()) break print(time) -for i in range(0,len(time),2): - df=df.append({"Start":time[i],"End":time[i+1]},ignore_index=True) +for i in range(0, len(time), 2): + df = df.append({"Start": time[i], "End": time[i+1]}, ignore_index=True) df.to_csv("Times.csv") video.release() cv2.destroyAllWindows - diff --git a/Facebook-DP-Downloader/fb_dp_downloader.py b/Facebook-DP-Downloader/fb_dp_downloader.py index b052957ecd..046f46d3f9 100644 --- a/Facebook-DP-Downloader/fb_dp_downloader.py +++ b/Facebook-DP-Downloader/fb_dp_downloader.py @@ -8,7 +8,7 @@ import os import requests -url="https://graph.facebook.com/{}/picture?type=large" +url = "https://graph.facebook.com/{}/picture?type=large" """ This url is the url provided by the Facebook graph api which helps to get to the profile picture of the corresponding Facebook id @@ -27,13 +27,13 @@ If it does not exist, then it gets created """ -fbid=int(input("Enter the Facebook-id to download it's profile picture: ")) -# the number should be a valid Facebook user id +fbid = int(input("Enter the Facebook-id to download it's profile picture: ")) +# the number should be a valid Facebook user id try: - result=requests.get(url.format(fbid)) - with open("fb_dps/{}_img.jpg".format(fbid),"wb") as file: + result = requests.get(url.format(fbid)) + with open("fb_dps/{}_img.jpg".format(fbid), "wb") as file: file.write(result.content) except: - print("There was some error") + print("There was some error") diff --git a/Facebook_Video_Downloader/script.py b/Facebook_Video_Downloader/script.py index 24e6aad413..1b889947c2 100644 --- a/Facebook_Video_Downloader/script.py +++ b/Facebook_Video_Downloader/script.py @@ -9,11 +9,13 @@ import queue from queue import Empty + def Invalid_Url(): """ Sets Status bar label to error message """ Status["text"] = "Invalid URL..." Status["fg"] = "red" + def get_downloadlink(url): url = url.replace("www", "mbasic") @@ -32,16 +34,14 @@ def get_downloadlink(url): exit(1) - def Download_vid(): # Validates Link and download Video global Url_Val - url=Url_Val.get() - - Status["text"]="Downloading" - Status["fg"]="green" + url = Url_Val.get() + Status["text"] = "Downloading" + Status["fg"] = "green" # Validating Input @@ -49,28 +49,26 @@ def Download_vid(): Invalid_Url() return - link=get_downloadlink(url) + link = get_downloadlink(url) start_downloading() - download_thread=VideoDownload(link) + download_thread = VideoDownload(link) download_thread.start() monitor(download_thread) - -def monitor( download_thread): +def monitor(download_thread): """ Monitor the download thread """ if download_thread.is_alive(): try: - bar["value"]=queue.get(0) + bar["value"] = queue.get(0) ld_window.after(10, lambda: monitor(download_thread)) except Empty: pass - class VideoDownload(Thread): def __init__(self, url): @@ -87,15 +85,15 @@ def run(self): total_size = int(r.headers.get("content-length")) with open('video.mp4', 'wb') as file: - totaldata=0; + totaldata = 0 for data in r.iter_content(block_size): - totaldata+=len(data) - per_downloaded=totaldata*100/total_size + totaldata += len(data) + per_downloaded = totaldata*100/total_size queue.put(per_downloaded) bar['value'] = per_downloaded file.write(data) time.sleep(0.01) - file.close() + file.close() print("Download Finished") print("Download Complete !!!") @@ -103,37 +101,40 @@ def run(self): Status["fg"] = "green" - -#start download +# start download def start_downloading(): - bar["value"]=0; + bar["value"] = 0 # GUI -ld_window=tk.Tk() + +ld_window = tk.Tk() ld_window.title("Facebook Video Downloader") ld_window.geometry("400x300") # Label for URL Input -input_label= tk.Label(ld_window,text="Enter Facebook Video URL:") +input_label = tk.Label(ld_window, text="Enter Facebook Video URL:") input_label.pack() # Input of URL Url_Val = tk.StringVar() Url_Input = tk.Entry(ld_window, textvariable=Url_Val, font=("Calibri", 9)) -Url_Input.place( x=25,y=50, width=350) +Url_Input.place(x=25, y=50, width=350) # Button for Download -Download_button = tk.Button(ld_window, text="Download", font=("Calibri", 9), command=Download_vid) +Download_button = tk.Button(ld_window, text="Download", font=( + "Calibri", 9), command=Download_vid) Download_button.place(x=100, y=100, width=200) # Progress Bar -bar = Progressbar(ld_window, length=350, style='grey.Horizontal.TProgressbar',mode='determinate') -bar.place(y=200,width=350,x=25) +bar = Progressbar(ld_window, length=350, + style='grey.Horizontal.TProgressbar', mode='determinate') +bar.place(y=200, width=350, x=25) -queue=queue.Queue() +queue = queue.Queue() # Text for Status of Downloading -Status = tk.Label(ld_window, text="Hello!! :D", fg="blue", font=("Calibri", 9), bd=1, relief=tk.SUNKEN, anchor=tk.W, padx=3) +Status = tk.Label(ld_window, text="Hello!! :D", fg="blue", font=( + "Calibri", 9), bd=1, relief=tk.SUNKEN, anchor=tk.W, padx=3) Status.pack(side=tk.BOTTOM, fill=tk.X) -ld_window.mainloop() \ No newline at end of file +ld_window.mainloop() diff --git a/Fetch All links in given webpage/Fetch_all_links_from_webpage.py b/Fetch All links in given webpage/Fetch_all_links_from_webpage.py index 4a3b1e8410..432dfa26b4 100644 --- a/Fetch All links in given webpage/Fetch_all_links_from_webpage.py +++ b/Fetch All links in given webpage/Fetch_all_links_from_webpage.py @@ -1,20 +1,20 @@ -# import requests module first +# import requests module first import requests as rq from bs4 import BeautifulSoup -url = input("Enter Link: ")### input link by user +url = input("Enter Link: ") # input link by user if ("https" or "http") in url: - data = rq.get(url) + data = rq.get(url) else: - data = rq.get("https://" + url) + data = rq.get("https://" + url) soup = BeautifulSoup(data.text, "html.parser") links = [] for link in soup.find_all("a"): - links.append(link.get("href")) + links.append(link.get("href")) with open("myLinks.txt", 'w') as saved: - print(links[:20], file=saved) + print(links[:20], file=saved) diff --git a/Fibonacci_Sequence_Generator/Fibonacci.py b/Fibonacci_Sequence_Generator/Fibonacci.py index acf7576c54..3124ba493f 100644 --- a/Fibonacci_Sequence_Generator/Fibonacci.py +++ b/Fibonacci_Sequence_Generator/Fibonacci.py @@ -11,9 +11,10 @@ def fibo(n): sequence.append(sequence[i-1] + sequence[i-2]) return sequence + n = 0 while n <= 0: n = int(input("Enter how many terms you need in your Fibonacci Sequence: ")) fib_sequence = fibo(n) -print(", ".join(map(str, fib_sequence))) \ No newline at end of file +print(", ".join(map(str, fib_sequence))) diff --git a/File Downloader Script/Travel Destination Scraper/travel_destinations_scraper.py b/File Downloader Script/Travel Destination Scraper/travel_destinations_scraper.py index 7ab99d7cac..729692f286 100644 --- a/File Downloader Script/Travel Destination Scraper/travel_destinations_scraper.py +++ b/File Downloader Script/Travel Destination Scraper/travel_destinations_scraper.py @@ -3,7 +3,8 @@ def scrape_travel_destinations(): - url = "https://www.example.com/destinations" # Replace with the actual URL of the travel destinations page + # Replace with the actual URL of the travel destinations page + url = "https://www.example.com/destinations" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") @@ -39,4 +40,4 @@ def scrape_travel_destinations(): print("Destination: ", destination["name"]) print("Description: ", destination["description"]) print("Image URL: ", destination["image_url"]) - print("------------------------") \ No newline at end of file + print("------------------------") diff --git a/File Downloader Script/file_downloader.py b/File Downloader Script/file_downloader.py index 6a0562b609..64bc3c3b24 100644 --- a/File Downloader Script/file_downloader.py +++ b/File Downloader Script/file_downloader.py @@ -1,5 +1,6 @@ import requests + def download_file(url, destination): response = requests.get(url, stream=True) if response.status_code == 200: @@ -10,6 +11,7 @@ def download_file(url, destination): else: print("Failed to download file.") + # Example usage: Download a file from a URL file_url = 'https://example.com/path/to/file.txt' save_as = 'downloaded_file.txt' diff --git a/File Downloader/file_downloader.py b/File Downloader/file_downloader.py index 40940f0db7..07c12b2bf8 100644 --- a/File Downloader/file_downloader.py +++ b/File Downloader/file_downloader.py @@ -10,31 +10,31 @@ import math import time -url=input("Enter the url of the file you want to download: ") +url = input("Enter the url of the file you want to download: ") -r=requests.get(url) -#receives data from the url +r = requests.get(url) +# receives data from the url -file_size=int(r.headers['Content-Length']) -chunk_size=256 +file_size = int(r.headers['Content-Length']) +chunk_size = 256 """Chunk size is the number of bytes downloaded at a time """ -r=requests.get(url,stream=True) +r = requests.get(url, stream=True) """streams=True ensures that will not get data at once, but will get data one by one """ -extension=(os.path.splitext(url))[-1] -file="file"+extension +extension = (os.path.splitext(url))[-1] +file = "file"+extension -iterations=math.ceil(file_size/chunk_size) +iterations = math.ceil(file_size/chunk_size) with open(file, "wb") as file: - for chunk in tqdm(r.iter_content(chunk_size=chunk_size),total=iterations): - time.sleep(0.5) - file.write(chunk) + for chunk in tqdm(r.iter_content(chunk_size=chunk_size), total=iterations): + time.sleep(0.5) + file.write(chunk) diff --git a/File Organizer script/file_organizer.py b/File Organizer script/file_organizer.py index 90b3783653..fafae545aa 100644 --- a/File Organizer script/file_organizer.py +++ b/File Organizer script/file_organizer.py @@ -1,20 +1,22 @@ import os import shutil + def organize_files(source_directory, destination_directory): for root, dirs, files in os.walk(source_directory): for file in files: source_path = os.path.join(root, file) destination_path = os.path.join(destination_directory, file) - + # Create destination directory if it doesn't exist os.makedirs(destination_directory, exist_ok=True) - + # Move the file to the destination directory shutil.move(source_path, destination_path) - + print(f"Moved {file} to {destination_directory}") + # Example usage: Organize files from source directory to destination directory source_directory = '/path/to/source_directory' destination_directory = '/path/to/destination_directory' diff --git a/File-Encrypter/script.py b/File-Encrypter/script.py index 8581b8ccd6..2909faab90 100644 --- a/File-Encrypter/script.py +++ b/File-Encrypter/script.py @@ -3,49 +3,58 @@ import sys import argparse + def generate_key(): - return Fernet.generate_key() + return Fernet.generate_key() + def save_key(key, file_path): - # save encryption key to a file - with open(file_path,'wb') as f: - f.write(key) + # save encryption key to a file + with open(file_path, 'wb') as f: + f.write(key) + def load_key(file_path): - with open(file_path,'rb') as f: - return f.read() - -def encrypt_file(key,file_path): - f=Fernet(key) - with open(file_path,'rb') as f_input: - data = f_input.read() - encrypted_data = f.encrypt(data) - with open(file_path.split(".")[0]+'.encrypted','wb') as f_output: - f_output.write(encrypted_data) - os.remove(file_path) + with open(file_path, 'rb') as f: + return f.read() + + +def encrypt_file(key, file_path): + f = Fernet(key) + with open(file_path, 'rb') as f_input: + data = f_input.read() + encrypted_data = f.encrypt(data) + with open(file_path.split(".")[0]+'.encrypted', 'wb') as f_output: + f_output.write(encrypted_data) + os.remove(file_path) + def decrypt_file(key, file_path): - f=Fernet(key) - with open (file_path,'rb') as f_enc: - data = f_enc.read() - dec_data = f.decrypt(data) - with open(file_path.split(".")[0]+".txt",'wb') as f_dec: - f_dec.write(dec_data) - os.remove(file_path) + f = Fernet(key) + with open(file_path, 'rb') as f_enc: + data = f_enc.read() + dec_data = f.decrypt(data) + with open(file_path.split(".")[0]+".txt", 'wb') as f_dec: + f_dec.write(dec_data) + os.remove(file_path) + if __name__ == "__main__": - parser = argparse.ArgumentParser(description = "[*]Encrypt youre files and password protect them") - parser.add_argument('file_path', help="Add the name of the file to be encrypted") - parser.add_argument('mode',choices=['encrypt','decrypt'],help="Choose either encrypt or decrypt") - args = parser.parse_args() - - if args.mode == "encrypt": - key = generate_key() - save_key(key,"secret.key") - encrypt_file(key,args.file_path) - print("Encrypted") - else: - key = load_key("secret.key") - - decrypt_file(key, args.file_path ) - print("Decrypted") + parser = argparse.ArgumentParser( + description="[*]Encrypt youre files and password protect them") + parser.add_argument( + 'file_path', help="Add the name of the file to be encrypted") + parser.add_argument('mode', choices=[ + 'encrypt', 'decrypt'], help="Choose either encrypt or decrypt") + args = parser.parse_args() + + if args.mode == "encrypt": + key = generate_key() + save_key(key, "secret.key") + encrypt_file(key, args.file_path) + print("Encrypted") + else: + key = load_key("secret.key") + + decrypt_file(key, args.file_path) + print("Decrypted") diff --git a/File-Mover/fmover.py b/File-Mover/fmover.py index e473a0adcf..b229ef4de4 100644 --- a/File-Mover/fmover.py +++ b/File-Mover/fmover.py @@ -167,7 +167,7 @@ def filemover(self, operation, sortby): raise SystemExit() elif sortby is None: for file in os.listdir(get_path('src')): - #file_ending = get_file_type() + # file_ending = get_file_type() is_file_in_curr_dir = os.path.isfile( get_path('dst') + "/" + file) for value in file_type: diff --git a/File_Separator/file_separator.py b/File_Separator/file_separator.py index 9f69a21252..7ee5c93665 100644 --- a/File_Separator/file_separator.py +++ b/File_Separator/file_separator.py @@ -1,6 +1,7 @@ import os import shutil + def separate_files(): source_folder = os.getcwd() # Current working directory as the source folder destination_folder = os.path.join(source_folder, "separated_files") diff --git a/Finger-Counter/HandTrackingModule.py b/Finger-Counter/HandTrackingModule.py index 2ec8efde6e..2864ac9254 100644 --- a/Finger-Counter/HandTrackingModule.py +++ b/Finger-Counter/HandTrackingModule.py @@ -67,4 +67,4 @@ def main(): if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/Finger-Counter/finger_counter.py b/Finger-Counter/finger_counter.py index 33dfc2dd80..4030c54ffd 100644 --- a/Finger-Counter/finger_counter.py +++ b/Finger-Counter/finger_counter.py @@ -3,13 +3,14 @@ import os import HandTrackingModule as htm + class fingerCounter(): def __init__(self): self.wCam = 640 self.hCam = 480 self.folderPath = "./Finger-Counter/FingerImages" self.previousTime = 0 - #self.currentTime = time.time() + # self.currentTime = time.time() # 4 for thumb, 8 for index, 12 for middle, 16 for ring, 20 for pinky finger self.tipIds = [4, 8, 12, 16, 20] self.overlayList = [] @@ -33,7 +34,7 @@ def process(self, tipIds, overlayList): while True: success, img = cap.read() img = detector.findHands(img) - lmList = detector.findPosition(img, draw = False) + lmList = detector.findPosition(img, draw=False) print(lmList) if len(lmList) != 0: @@ -45,7 +46,7 @@ def process(self, tipIds, overlayList): else: fingers.append(0) # Four fingers - for id in range(1,5): + for id in range(1, 5): if lmList[self.tipIds[id]][2] < lmList[self.tipIds[id] - 2][2]: fingers.append(1) else: @@ -56,20 +57,24 @@ def process(self, tipIds, overlayList): h, w, c = self.overlayList[totalFingers - 1].shape img[0:h, 0:w] = self.overlayList[totalFingers - 1] - cv2.rectangle(img, (20, 225), (170, 425), (0, 255, 0), cv2.FILLED) - cv2.putText(img, str(totalFingers), (45, 375), cv2.FONT_HERSHEY_PLAIN, 10, (255, 0, 0), 25) - + cv2.rectangle(img, (20, 225), (170, 425), + (0, 255, 0), cv2.FILLED) + cv2.putText(img, str(totalFingers), (45, 375), + cv2.FONT_HERSHEY_PLAIN, 10, (255, 0, 0), 25) + self.currentTime = time.time() fps = 1/(self.currentTime - self.previousTime) self.previousTime = self.currentTime - cv2.putText(img, f'FPS: {int(fps)}', (400,70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3) + cv2.putText(img, f'FPS: {int(fps)}', (400, 70), + cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3) cv2.imshow("Image", img) - - if cv2.waitKey(1) == ord('q') : + + if cv2.waitKey(1) == ord('q'): break - + + cv2.destroyAllWindows() if __name__ == "__main__": diff --git a/Finger_count_openCV/main.py b/Finger_count_openCV/main.py index 9c0117ad29..f61409956f 100644 --- a/Finger_count_openCV/main.py +++ b/Finger_count_openCV/main.py @@ -6,68 +6,66 @@ capture = cv2.VideoCapture(0) while True: - success,img = capture.read() - - + success, img = capture.read() + # Frame Cropping - cv2.rectangle(img,(20,20),(400,300),(0,255,0),0) - crop_image= img[20:300,20:400] - + cv2.rectangle(img, (20, 20), (400, 300), (0, 255, 0), 0) + crop_image = img[20:300, 20:400] + # TODO: Grey Filter (pass crop_image) # grey = your code - grey = cv2.cvtColor(crop_image,cv2.COLOR_BGR2GRAY) - + grey = cv2.cvtColor(crop_image, cv2.COLOR_BGR2GRAY) + # TODO: Gaussian Blur to smoothen the image (pass grey) # blur = your code - blur = cv2.GaussianBlur(grey,(35,35),0) - + blur = cv2.GaussianBlur(grey, (35, 35), 0) # TODO: thresholding the image using Binary inversion + OTSU # ret,thresh= your code - ret,thresh= cv2.threshold(blur,127,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) - + ret, thresh = cv2.threshold( + blur, 127, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) # show threshold - cv2.imshow("Threshold",thresh) - - contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) + cv2.imshow("Threshold", thresh) + + contours, hierarchy = cv2.findContours( + thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) try: # TODO: contour with maximum area # contour = your code contour = max(contours, key=lambda x: cv2.contourArea(x)) - + # bounding rectangle for the contour x, y, w, h = cv2.boundingRect(contour) cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 0) # TODO: create hull - #hull = your code (important: do not use returnPoints argument) + # hull = your code (important: do not use returnPoints argument) hull = cv2.convexHull(contour) drawing = np.zeros(img.shape, np.uint8) cv2.drawContours(drawing, [contour], -1, (0, 255, 0), 0) - cv2.drawContours(drawing,[hull],-1,(0,0,255),0) + cv2.drawContours(drawing, [hull], -1, (0, 0, 255), 0) - #TODO: finding convex hull - #hull = your code (important: use returnPoints argument as False) + # TODO: finding convex hull + # hull = your code (important: use returnPoints argument as False) hull = cv2.convexHull(contour, returnPoints=False) - + # TODO: finding convexity defects # defects = your code defects = cv2.convexityDefects(contour, hull) - - count_defects = 0 - #TODO: refer to the math for calculating the angle part of README + # TODO: refer to the math for calculating the angle part of README for i in range(defects.shape[0]): - s,e,f,d = defects[i,0] + s, e, f, d = defects[i, 0] start = tuple(contour[s][0]) end = tuple(contour[e][0]) far = tuple(contour[f][0]) a = math.sqrt((start[0] - end[0]) ** 2 + (start[1] - end[1]) ** 2) - b = math.sqrt((-start[0] + far[0]) ** 2 + (-start[1] + far[1]) ** 2) + b = math.sqrt((-start[0] + far[0]) ** 2 + + (-start[1] + far[1]) ** 2) c = math.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2) angle = (math.acos((b**2 + c**2 - a**2) / (2*b*c)))*57 @@ -75,48 +73,36 @@ count_defects += 1 cv2.circle(crop_image, far, 1, [0, 0, 255], -1) cv2.line(crop_image, start, end, [0, 255, 0], 2) - + # output # TODO: Complete the logic if count_defects == 0: - cv2.putText(img, "ONE",(50,50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2) + cv2.putText(img, "ONE", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2) # elif count_defects == 1: elif count_defects == 1: - cv2.putText(img, "TWO",(50,50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2) + cv2.putText(img, "TWO", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2) elif count_defects == 2: - cv2.putText(img, "THREE",(50,50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2) + cv2.putText(img, "THREE", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2) elif count_defects == 3: - cv2.putText(img, "FOUR",(50,50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2) + cv2.putText(img, "FOUR", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2) elif count_defects == 4: - cv2.putText(img, "FIVE",(50,50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2) - - + cv2.putText(img, "FIVE", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2) else: pass - except: pass - cv2.imshow("Gesture",img) - all_image = np.hstack((drawing,img)) + cv2.imshow("Gesture", img) + all_image = np.hstack((drawing, img)) - cv2.imshow('contours',all_image) + cv2.imshow('contours', all_image) - if cv2.waitKey(1)==ord('q'): + if cv2.waitKey(1) == ord('q'): break capture.release() cv2.destroyAllWindows() - - - - - - - - - diff --git a/FirebaseScripts/CredentialsHelper.py b/FirebaseScripts/CredentialsHelper.py index 720b8c6137..e35e1d27f5 100644 --- a/FirebaseScripts/CredentialsHelper.py +++ b/FirebaseScripts/CredentialsHelper.py @@ -32,7 +32,7 @@ def get_fireBase_credentials(): measurementId = os.getenv('measurementId') credentials = [apiKey, authDomain, databaseURL, projectId, storageBucket, messagingSenderId, appId, measurementId] - if any(not(credential) for credential in credentials): + if any(not (credential) for credential in credentials): raise ValueError("Value cannot be None ") else: firebaseConfig["apiKey"] = apiKey @@ -50,4 +50,5 @@ def get_fireBase_credentials(): return firebaseConfig -get_fireBase_credentials() \ No newline at end of file + +get_fireBase_credentials() diff --git a/FirebaseScripts/firebase_storage.py b/FirebaseScripts/firebase_storage.py index 39742d480a..a40d5ba75b 100644 --- a/FirebaseScripts/firebase_storage.py +++ b/FirebaseScripts/firebase_storage.py @@ -20,7 +20,8 @@ def delete_file(firebase_path, name_of_file_to_delete): def download_file(firebase_path, file_name): - response = storage.child(firebase_path).download(path="./", filename=file_name) + response = storage.child(firebase_path).download( + path="./", filename=file_name) print(response) return response diff --git a/Flappy-Bird-Game/main.py b/Flappy-Bird-Game/main.py index e8568b50d0..1cad5774cd 100644 --- a/Flappy-Bird-Game/main.py +++ b/Flappy-Bird-Game/main.py @@ -1,112 +1,114 @@ import random -import sys # we use sys.exit to exit the program +import sys # we use sys.exit to exit the program import pygame from pygame.locals import * -#Global variables for the games -FPS =32 -SCREENWIDTH=289 -SCREENHEIGHT=511 -SCREEN= pygame.display.set_mode((SCREENWIDTH,SCREENHEIGHT)) -GROUNDY=SCREENHEIGHT*0.8 -GAME_SPRITES={} -GAME_SOUNDS={} -PLAYER='assets/sprites/redbird-midflap.png' -BACKGROUND='assets/sprites/background-day.png' -PIPE='assets/sprites/pipe-green.png' +# Global variables for the games +FPS = 32 +SCREENWIDTH = 289 +SCREENHEIGHT = 511 +SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) +GROUNDY = SCREENHEIGHT*0.8 +GAME_SPRITES = {} +GAME_SOUNDS = {} +PLAYER = 'assets/sprites/redbird-midflap.png' +BACKGROUND = 'assets/sprites/background-day.png' +PIPE = 'assets/sprites/pipe-green.png' + +'''(0,0) co-ordinates mean that we want the top-left point of our image placed at this co-ord''' -'''(0,0) co-ordinates mean that we want the top-left point of our image placed at this co-ord''' def welcomeScreen(): '''Shows welcome images on the screen''' - playerx=int(SCREENWIDTH/5) - playery=int((SCREENHEIGHT-GAME_SPRITES['player'].get_height())/2) - messagex=int((SCREENWIDTH-GAME_SPRITES['message'].get_width())/2) - messagey=int(SCREENHEIGHT*0.13) - basex=0 + playerx = int(SCREENWIDTH/5) + playery = int((SCREENHEIGHT-GAME_SPRITES['player'].get_height())/2) + messagex = int((SCREENWIDTH-GAME_SPRITES['message'].get_width())/2) + messagey = int(SCREENHEIGHT*0.13) + basex = 0 while True: for event in pygame.event.get(): - #if user clicks on cross button close the game - if event.type==QUIT or (event.type==KEYDOWN and event.key==K_ESCAPE): + # if user clicks on cross button close the game + if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() - #if user presses 'space' or 'up' key, start the game for them - elif event.type==KEYDOWN and (event.key==K_SPACE or event.key==K_UP): + # if user presses 'space' or 'up' key, start the game for them + elif event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): return else: - SCREEN.blit(GAME_SPRITES['background'], (0,0)) - SCREEN.blit(GAME_SPRITES['player'], (playerx,playery)) - SCREEN.blit(GAME_SPRITES['message'], (messagex,messagey)) - SCREEN.blit(GAME_SPRITES['base'], (basex,GROUNDY)) - pygame.display.update() #it updates the entire Surface area - FPSCLOCK.tick(FPS) + SCREEN.blit(GAME_SPRITES['background'], (0, 0)) + SCREEN.blit(GAME_SPRITES['player'], (playerx, playery)) + SCREEN.blit(GAME_SPRITES['message'], (messagex, messagey)) + SCREEN.blit(GAME_SPRITES['base'], (basex, GROUNDY)) + pygame.display.update() # it updates the entire Surface area + FPSCLOCK.tick(FPS) + def mainGame(): - score=0 - playerx=int(SCREENWIDTH/5) - playery=int(SCREENHEIGHT/2) - basex=0 - #creating 2 pipes for blitting on the screen - newPipe1=getRandomPipe() - newPipe2=getRandomPipe() + score = 0 + playerx = int(SCREENWIDTH/5) + playery = int(SCREENHEIGHT/2) + basex = 0 + # creating 2 pipes for blitting on the screen + newPipe1 = getRandomPipe() + newPipe2 = getRandomPipe() # list of upper pipes upperPipes = [ - {'x': SCREENWIDTH+200, 'y':newPipe1[0]['y']}, - {'x': SCREENWIDTH+200+(SCREENWIDTH/2), 'y':newPipe2[0]['y']}, + {'x': SCREENWIDTH+200, 'y': newPipe1[0]['y']}, + {'x': SCREENWIDTH+200+(SCREENWIDTH/2), 'y': newPipe2[0]['y']}, ] # my List of lower pipes lowerPipes = [ - {'x': SCREENWIDTH+200, 'y':newPipe1[1]['y']}, - {'x': SCREENWIDTH+200+(SCREENWIDTH/2), 'y':newPipe2[1]['y']}, + {'x': SCREENWIDTH+200, 'y': newPipe1[1]['y']}, + {'x': SCREENWIDTH+200+(SCREENWIDTH/2), 'y': newPipe2[1]['y']}, ] - pipeVelX=-4 - playerVelY=-9 - playerMaxVelY=10 - playerMinVelY=-8 - playerAccY=1 - playerFlapAccv=-8 #velocity while flapping - playerFlapped=False #true only when the bird is flapping + pipeVelX = -4 + playerVelY = -9 + playerMaxVelY = 10 + playerMinVelY = -8 + playerAccY = 1 + playerFlapAccv = -8 # velocity while flapping + playerFlapped = False # true only when the bird is flapping while True: for event in pygame.event.get(): - if event.type==QUIT or (event.type==KEYDOWN and event.key==K_ESCAPE): + if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() - if event.type==KEYDOWN and (event.key==K_SPACE or event.key==K_UP): - if playery>0: - playerVelY=playerFlapAccv - playerFlapped =True + if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): + if playery > 0: + playerVelY = playerFlapAccv + playerFlapped = True GAME_SOUNDS['wing'].play() - crashTest=isCollide(playerx,playery, upperPipes, lowerPipes)# returns true if player crashed + # returns true if player crashed + crashTest = isCollide(playerx, playery, upperPipes, lowerPipes) if crashTest: return - #check for score + # check for score playerMidPos = playerx + GAME_SPRITES['player'].get_width()/2 for pipe in upperPipes: pipeMidPos = pipe['x'] + GAME_SPRITES['pipe'][0].get_width()/2 - if pipeMidPos<= playerMidPos < pipeMidPos +4: - score +=1 - print(f"Your score is {score}") + if pipeMidPos <= playerMidPos < pipeMidPos + 4: + score += 1 + print(f"Your score is {score}") GAME_SOUNDS['point'].play() - - if playerVelY GROUNDY - 25 or playery<0: + if playery > GROUNDY - 25 or playery < 0: GAME_SOUNDS['hit'].play() return True - + for pipe in upperPipes: pipeHeight = GAME_SPRITES['pipe'][0].get_height() - if(playery < pipeHeight + pipe['y'] and abs(playerx - pipe['x']) < GAME_SPRITES['pipe'][0].get_width()): + if (playery < pipeHeight + pipe['y'] and abs(playerx - pipe['x']) < GAME_SPRITES['pipe'][0].get_width()): GAME_SOUNDS['hit'].play() return True @@ -152,61 +158,64 @@ def isCollide(playerx, playery, upperPipes, lowerPipes): GAME_SOUNDS['hit'].play() return True - return False - - + return False def getRandomPipe(): '''Generate position of the two pipes(one straight(bottom pipe), one rotated (top pipe)) for blitting on the screen''' - pipeHeight=GAME_SPRITES['pipe'][0].get_height() - offset=SCREENHEIGHT/3 - y2= offset+ random.randrange(0,int(SCREENHEIGHT-GAME_SPRITES['base'].get_height()-1.2*offset)) - pipeX=SCREENWIDTH+10 - y1=pipeHeight-y2+offset - pipe=[ - {"x":pipeX,"y":-y1}, #upper pipe - {"x":pipeX,"y":y2} #lower pipe + pipeHeight = GAME_SPRITES['pipe'][0].get_height() + offset = SCREENHEIGHT/3 + y2 = offset + \ + random.randrange( + 0, int(SCREENHEIGHT-GAME_SPRITES['base'].get_height()-1.2*offset)) + pipeX = SCREENWIDTH+10 + y1 = pipeHeight-y2+offset + pipe = [ + {"x": pipeX, "y": -y1}, # upper pipe + {"x": pipeX, "y": y2} # lower pipe ] return pipe -if __name__=="__main__": - #this will be the main point from where our game will stop - #initialize all pygame modules +if __name__ == "__main__": + # this will be the main point from where our game will stop + # initialize all pygame modules pygame.init() - FPSCLOCK=pygame.time.Clock() + FPSCLOCK = pygame.time.Clock() pygame.display.set_caption("Simple Flappy Bird") pygame_icon = pygame.image.load('assets/sprites/redbird-upflap.png') pygame.display.set_icon(pygame_icon) - GAME_SPRITES['numbers']=( - pygame.image.load('assets/sprites/0.png').convert_alpha(), #fast image processing on screen - pygame.image.load('assets/sprites/1.png').convert_alpha(), - pygame.image.load('assets/sprites/2.png').convert_alpha(), - pygame.image.load('assets/sprites/3.png').convert_alpha(), - pygame.image.load('assets/sprites/4.png').convert_alpha(), - pygame.image.load('assets/sprites/5.png').convert_alpha(), - pygame.image.load('assets/sprites/6.png').convert_alpha(), - pygame.image.load('assets/sprites/7.png').convert_alpha(), - pygame.image.load('assets/sprites/8.png').convert_alpha(), - pygame.image.load('assets/sprites/9.png').convert_alpha(), + GAME_SPRITES['numbers'] = ( + # fast image processing on screen + pygame.image.load('assets/sprites/0.png').convert_alpha(), + pygame.image.load('assets/sprites/1.png').convert_alpha(), + pygame.image.load('assets/sprites/2.png').convert_alpha(), + pygame.image.load('assets/sprites/3.png').convert_alpha(), + pygame.image.load('assets/sprites/4.png').convert_alpha(), + pygame.image.load('assets/sprites/5.png').convert_alpha(), + pygame.image.load('assets/sprites/6.png').convert_alpha(), + pygame.image.load('assets/sprites/7.png').convert_alpha(), + pygame.image.load('assets/sprites/8.png').convert_alpha(), + pygame.image.load('assets/sprites/9.png').convert_alpha(), ) - GAME_SPRITES['message']=pygame.image.load('assets/sprites/message.png').convert_alpha() - GAME_SPRITES['base']=pygame.image.load('assets/sprites/base.png').convert_alpha() - GAME_SPRITES['pipe']=( - pygame.transform.rotate(pygame.image.load(PIPE).convert_alpha(),180), + GAME_SPRITES['message'] = pygame.image.load( + 'assets/sprites/message.png').convert_alpha() + GAME_SPRITES['base'] = pygame.image.load( + 'assets/sprites/base.png').convert_alpha() + GAME_SPRITES['pipe'] = ( + pygame.transform.rotate(pygame.image.load(PIPE).convert_alpha(), 180), pygame.image.load(PIPE).convert_alpha(), ) - #Game sounds - GAME_SOUNDS['die']=pygame.mixer.Sound('assets/audio/die.wav') - GAME_SOUNDS['hit']=pygame.mixer.Sound('assets/audio/hit.wav') - GAME_SOUNDS['point']=pygame.mixer.Sound('assets/audio/point.wav') - GAME_SOUNDS['swoosh']=pygame.mixer.Sound('assets/audio/swoosh.wav') - GAME_SOUNDS['wing']=pygame.mixer.Sound('assets/audio/wing.wav') - GAME_SPRITES['background']=pygame.image.load(BACKGROUND).convert() - GAME_SPRITES['player']=pygame.image.load(PLAYER).convert_alpha() + # Game sounds + GAME_SOUNDS['die'] = pygame.mixer.Sound('assets/audio/die.wav') + GAME_SOUNDS['hit'] = pygame.mixer.Sound('assets/audio/hit.wav') + GAME_SOUNDS['point'] = pygame.mixer.Sound('assets/audio/point.wav') + GAME_SOUNDS['swoosh'] = pygame.mixer.Sound('assets/audio/swoosh.wav') + GAME_SOUNDS['wing'] = pygame.mixer.Sound('assets/audio/wing.wav') + GAME_SPRITES['background'] = pygame.image.load(BACKGROUND).convert() + GAME_SPRITES['player'] = pygame.image.load(PLAYER).convert_alpha() while True: - welcomeScreen() #shows welcome screen untill user presses a key - mainGame() # main game function + welcomeScreen() # shows welcome screen untill user presses a key + mainGame() # main game function diff --git a/FlappyBird/Flappy.py b/FlappyBird/Flappy.py index 145757f062..bd0ae96370 100644 --- a/FlappyBird/Flappy.py +++ b/FlappyBird/Flappy.py @@ -5,7 +5,7 @@ @author: Ayush """ -#Import Dependencies +# Import Dependencies import random import numpy as np import flappy_bird_gym @@ -16,19 +16,23 @@ # Neural Network for Agent -def NeuralNetwork(input_shape,output_shape): + +def NeuralNetwork(input_shape, output_shape): model = Sequential() model.add(Input(input_shape)) - model.add(Dense(512, input_shape = input_shape, activation ='relu',kernel_initializer='he_uniform')) - model.add(Dense(256, activation ='relu',kernel_initializer='he_uniform')) - model.add(Dense(64, activation ='relu',kernel_initializer='he_uniform')) - model.add(Dense(output_shape, activation ='linear',kernel_initializer='he_uniform')) - model.compile(loss='mse',optimizer=RMSprop(lr=0.0001,rho=0.95, epsilon=0.01),metrics=['accuracy']) + model.add(Dense(512, input_shape=input_shape, + activation='relu', kernel_initializer='he_uniform')) + model.add(Dense(256, activation='relu', kernel_initializer='he_uniform')) + model.add(Dense(64, activation='relu', kernel_initializer='he_uniform')) + model.add(Dense(output_shape, activation='linear', + kernel_initializer='he_uniform')) + model.compile(loss='mse', optimizer=RMSprop( + lr=0.0001, rho=0.95, epsilon=0.01), metrics=['accuracy']) model.summary() return model -#Brain of Agent || BluePrint of Agent +# Brain of Agent || BluePrint of Agent class DQNAgent: def __init__(self): @@ -37,113 +41,115 @@ def __init__(self): self.state_space = self.env.observation_space.shape[0] self.action_space = self.env.action_space.n self.memory = deque(maxlen=2000) - - #Hyperparameters + + # Hyperparameters self.gamma = 0.95 - self.epsilon=1 + self.epsilon = 1 self.epsilon_decay = 0.9999 self.epsilon_min = 0.01 - self.batch_number = 64 #16, 32, 128, 256 - + self.batch_number = 64 # 16, 32, 128, 256 + self.train_start = 1000 self.jump_prob = 0.01 - self.model= NeuralNetwork(input_shape=(self.state_space,), output_shape=self.action_space) - - def act(self,state): + self.model = NeuralNetwork(input_shape=( + self.state_space,), output_shape=self.action_space) + + def act(self, state): if np.random.random() > self.epsilon: return np.argmax(self.model.predict(state)) return 1 if np.random.random() < self.jump_prob else 0 - + def learn(self): - #Make sure we have enough data + # Make sure we have enough data if len(self.memory) < self.train_start: return - - #Create minibatch - minibatch = random.sample(self.memory, min(len(self.memory), self.batch_number)) - #Variables to store minibatch info - state = np.zeros((self.batch_number,self.state_space)) - next_state = np.zeros((self.batch_number,self.state_space)) - + + # Create minibatch + minibatch = random.sample(self.memory, min( + len(self.memory), self.batch_number)) + # Variables to store minibatch info + state = np.zeros((self.batch_number, self.state_space)) + next_state = np.zeros((self.batch_number, self.state_space)) + action, reward, done = [], [], [] - - - #Store data in variables + + # Store data in variables for i in range(self.batch_number): state[i] = minibatch[i][0] action.append(minibatch[i][1]) reward.append(minibatch[i][2]) next_state[i] = minibatch[i][3] done.append(minibatch[i][4]) - - #Predict y label + + # Predict y label target = self.model.predict(state) target_next = self.model.predict(next_state) - + for i in range(self.batch_number): if done[i]: target[i][action[i]] = reward[i] else: - target[i][action[i]] = reward[i] + self.gamma *(np.argmax(target_next[i])) + target[i][action[i]] = reward[i] + \ + self.gamma * (np.argmax(target_next[i])) print('training') self.model.fit(state, target, batch_size=self.batch_number, verbose=0) - + def train(self): - #n episode Iterartions for training + # n episode Iterartions for training for i in range(self.episodes): # Environment variables for training state = self.env.reset() - state = np.reshape(state,[1, self.state_space]) - done= False - score=0 - self.epsilon =self.epsilon * self.epsilon_decay if self.epsilon * self.epsilon_decay > self.epsilon_min else self.epsilon_min - + state = np.reshape(state, [1, self.state_space]) + done = False + score = 0 + self.epsilon = self.epsilon * self.epsilon_decay if self.epsilon * \ + self.epsilon_decay > self.epsilon_min else self.epsilon_min + while not done: self.env.render() action = self.act(state) next_state, reward, done, info = self.env.step(action) - - #reshape nextstate - next_state = np.reshape(next_state,[1,self.state_space]) - score +=1 + + # reshape nextstate + next_state = np.reshape(next_state, [1, self.state_space]) + score += 1 if done: reward -= 100 - + self.memory.append((state, action, reward, next_state, done)) state = next_state - + if done: - print("Episode: {}\nScore: {}\nEpsilon: {:.2}".format(i,score,self.epsilon)) - #Save model + print("Episode: {}\nScore: {}\nEpsilon: {:.2}".format( + i, score, self.epsilon)) + # Save model if score >= 1000: self.model.save_model('flappybrain.h5') self.learn() - + def perform(self): self.model = load_model('flappybrain.h5') while 1: state = self.env.reset() - state = np.reshape(state,[1,self.state_space]) + state = np.reshape(state, [1, self.state_space]) done = False - score=0 - + score = 0 + while not done: self.env.render() action = np.argmax(self.model.predict(state)) next_state, reward, done, info = self.env.step(action) - state = np.reshape(next_state,[1,self.state_space]) - score +=1 - + state = np.reshape(next_state, [1, self.state_space]) + score += 1 + print("Current Score: {}".format(score)) - + if done: print('DEAD') break - - - + + if __name__ == '__main__': agent = DQNAgent() agent.train() - #agent.perform() - \ No newline at end of file + # agent.perform() diff --git a/Fleury-Algorithm/Fleury_Algorithm.py b/Fleury-Algorithm/Fleury_Algorithm.py index f77f5d9cf5..d33092310c 100644 --- a/Fleury-Algorithm/Fleury_Algorithm.py +++ b/Fleury-Algorithm/Fleury_Algorithm.py @@ -20,88 +20,91 @@ # Program Starts from collections import defaultdict + class Graph: - def __init__(self,vertices): - self.V= vertices #No. of vertices - self.graph = defaultdict(list) - self.Time = 0 - - # function to add an edge to graph - def addEdge(self,source,destination): - self.graph[source].append(destination) - self.graph[destination].append(source) - - # This function removes edge source-destination from graph - def removeEdge(self, source, destination): - for index, key in enumerate(self.graph[source]): - if key == destination: - self.graph[source].pop(index) - for index, key in enumerate(self.graph[destination]): - if key == source: - self.graph[destination].pop(index) - - # A DFS based function to count reachable vertices from destination - def DFSCount(self, destination, visited): - count = 1 - visited[destination] = True - for i in self.graph[destination]: - if visited[i] == False: - count = count + self.DFSCount(i, visited) - return count - - # The function to check if edge source-destination can be considered as next edge in Euler Trail - def isValidNextEdge(self, source, destination): - # The edge source-destination is valid in one of the following two cases: - - # 1) If destination is the only adjacent vertex of source - if len(self.graph[source]) == 1: - return True - else: - ''' - 2) If there are multiple adjacents, then source-destination is not a bridge - Do following steps to check if source-destination is a bridge - - 2.a) count of vertices reachable from source''' - visited =[False]*(self.V) - count1 = self.DFSCount(source, visited) - - '''2.b) Remove edge (source, destination) and after removing the edge, count + def __init__(self, vertices): + self.V = vertices # No. of vertices + self.graph = defaultdict(list) + self.Time = 0 + + # function to add an edge to graph + def addEdge(self, source, destination): + self.graph[source].append(destination) + self.graph[destination].append(source) + + # This function removes edge source-destination from graph + def removeEdge(self, source, destination): + for index, key in enumerate(self.graph[source]): + if key == destination: + self.graph[source].pop(index) + for index, key in enumerate(self.graph[destination]): + if key == source: + self.graph[destination].pop(index) + + # A DFS based function to count reachable vertices from destination + def DFSCount(self, destination, visited): + count = 1 + visited[destination] = True + for i in self.graph[destination]: + if visited[i] == False: + count = count + self.DFSCount(i, visited) + return count + + # The function to check if edge source-destination can be considered as next edge in Euler Trail + def isValidNextEdge(self, source, destination): + # The edge source-destination is valid in one of the following two cases: + + # 1) If destination is the only adjacent vertex of source + if len(self.graph[source]) == 1: + return True + else: + ''' + 2) If there are multiple adjacents, then source-destination is not a bridge + Do following steps to check if source-destination is a bridge + + 2.a) count of vertices reachable from source''' + visited = [False]*(self.V) + count1 = self.DFSCount(source, visited) + + '''2.b) Remove edge (source, destination) and after removing the edge, count vertices reachable from source''' - self.removeEdge(source, destination) - visited =[False]*(self.V) - count2 = self.DFSCount(source, visited) + self.removeEdge(source, destination) + visited = [False]*(self.V) + count2 = self.DFSCount(source, visited) - #2.c) Add the edge back to the graph - self.addEdge(source,destination) + # 2.c) Add the edge back to the graph + self.addEdge(source, destination) - # 2.d) If count1 is greater, then edge (source, destination) is a bridge - return False if count1 > count2 else True + # 2.d) If count1 is greater, then edge (source, destination) is a bridge + return False if count1 > count2 else True + # Print Euler Trail starting from vertex source - # Print Euler Trail starting from vertex source - def printEulerUtil(self, source): - #Recur for all the vertices adjacent to this vertex - for destination in self.graph[source]: - #If edge source-destination is not removed and it's a a valid next edge - if self.isValidNextEdge(source, destination): - print("%d-%d " %(source,destination)), - self.removeEdge(source, destination) - self.printEulerUtil(destination) + def printEulerUtil(self, source): + # Recur for all the vertices adjacent to this vertex + for destination in self.graph[source]: + # If edge source-destination is not removed and it's a a valid next edge + if self.isValidNextEdge(source, destination): + print("%d-%d " % (source, destination)), + self.removeEdge(source, destination) + self.printEulerUtil(destination) - '''The main function that print Eulerian Trail. It first finds an odd + '''The main function that print Eulerian Trail. It first finds an odd degree vertex (if there is any) and then calls printEulerUtil() to print the path ''' - def printEulerTrail(self): - #Find a vertex with odd degree - source = 0 - for i in range(self.V): - if len(self.graph[i]) %2 != 0 : - source = i - break - # Print Trail starting from odd vertex - print ("\n") - self.printEulerUtil(source) + + def printEulerTrail(self): + # Find a vertex with odd degree + source = 0 + for i in range(self.V): + if len(self.graph[i]) % 2 != 0: + source = i + break + # Print Trail starting from odd vertex + print("\n") + self.printEulerUtil(source) + # Driver program V = int(input("\nEnter the number of vertices in the graph: ")) diff --git a/Flipkart-price-alert/track.py b/Flipkart-price-alert/track.py index cea0a826ab..d6207db4c1 100644 --- a/Flipkart-price-alert/track.py +++ b/Flipkart-price-alert/track.py @@ -36,7 +36,7 @@ def priceCheck(): print(price) print(THRESHHOLD) # If the price falls below threshold, send an email - if(price < THRESHHOLD): + if (price < THRESHHOLD): sendMail(title) @@ -50,6 +50,6 @@ def priceCheck(): if (PRODUCT_URL == '' or MY_APP_PASSWORD == '' or MY_EMAIL == '' or RECEIVER_EMAIL == ''): print('VALUES MISSING! TRY AGAIN') exit() -while(True): +while (True): priceCheck() time.sleep(CHECK_AGAIN*60) diff --git a/FlipkartScraper/dbConnector.py b/FlipkartScraper/dbConnector.py index 749233b27f..e4fc14ebe4 100644 --- a/FlipkartScraper/dbConnector.py +++ b/FlipkartScraper/dbConnector.py @@ -1,12 +1,14 @@ import sqlite3 import os + class FlipkartDatabaseConnector: def __init__(self, stamp): self.dbPath = "flipkart.db" self.conn = sqlite3.connect(self.dbPath) self.cur = self.conn.cursor() - self.welcomeMessage = "Welcome to Flipkart Scraper. This is the database for the Flipkart Scraper. This database was created on {}.".format(stamp) + self.welcomeMessage = "Welcome to Flipkart Scraper. This is the database for the Flipkart Scraper. This database was created on {}.".format( + stamp) def schemaMaker(self): # creating tables @@ -24,9 +26,10 @@ def schemaMaker(self): self.conn.commit() self.cur.execute("CREATE TABLE product_matches (id INTEGER PRIMARY KEY AUTOINCREMENT, product_id INTEGER NOT NULL, product_sku INTEGER NOT NULL, match_id INTEGER NOT NULL, match_sku INTEGER NOT NULL);") self.conn.commit() - + def insertProduct(self, productDetails): - self.cur.execute("INSERT INTO products (sku, name, description, image_path, category, timestamp, URL, price) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (productDetails["sku"], productDetails["name"], productDetails["description"], productDetails["image_path"], productDetails["category"], productDetails["timestamp"], productDetails["URL"], productDetails["price"])) + self.cur.execute("INSERT INTO products (sku, name, description, image_path, category, timestamp, URL, price) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", ( + productDetails["sku"], productDetails["name"], productDetails["description"], productDetails["image_path"], productDetails["category"], productDetails["timestamp"], productDetails["URL"], productDetails["price"])) self.conn.commit() def fetchAllProducts(self): @@ -38,7 +41,8 @@ def clearDatabase(self): self.conn.commit() self.cur.execute("DELETE FROM product_matches") self.conn.commit() - + def removeDuplicates(self): - self.cur.execute("DELETE FROM products WHERE rowid NOT IN (SELECT MIN(rowid) FROM products GROUP BY sku)") - self.conn.commit() \ No newline at end of file + self.cur.execute( + "DELETE FROM products WHERE rowid NOT IN (SELECT MIN(rowid) FROM products GROUP BY sku)") + self.conn.commit() diff --git a/FlipkartScraper/genricHtmlib.py b/FlipkartScraper/genricHtmlib.py index d20884a1f0..a8cd153e3c 100644 --- a/FlipkartScraper/genricHtmlib.py +++ b/FlipkartScraper/genricHtmlib.py @@ -10,6 +10,7 @@ import requests warnings.filterwarnings("ignore") + class SeleniumScraper: def __init__(self, timeout=10): self.timeout = timeout @@ -32,7 +33,7 @@ def __init__(self, timeout=10): 'sec-fetch-dest': 'document', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', } - + def fetch_request_normal(self, url, params=None): try: headers = { @@ -42,26 +43,27 @@ def fetch_request_normal(self, url, params=None): if response.status_code == 200: return response.text - + if response.status_code == 301: # retry with redirect response = requests.get(response.headers['Location']) response.raise_for_status() if response.status_code == 200: return response.text - + if response.status_code == 503: - #print("Request Failed Response status code for url: {} and status code: {}".format(url, 503)) + # print("Request Failed Response status code for url: {} and status code: {}".format(url, 503)) return None - + except Exception as e: print( - "Exception occurred for url: {} and exception: {}".format(url, e) + "Exception occurred for url: {} and exception: {}".format( + url, e) ) print("Exception occurred for url: {} and exception: {}".format(url, e)) pass return None - + def get_xpath_link(self, doc, xpath, website): try: name = doc.xpath("".join(xpath)) @@ -77,7 +79,7 @@ def get_xpath_link(self, doc, xpath, website): pass return None pass - + def get_selenium_driver(self): chrome_options = Options() chrome_options.add_argument("--headless") @@ -104,7 +106,8 @@ def fetch_request_selenium(self, url, waiting_time=1): except Exception as e: print( - "Exception occurred for url: {} and exception: {}".format(url, e) + "Exception occurred for url: {} and exception: {}".format( + url, e) ) pass @@ -117,9 +120,10 @@ def get_xpath_data(self, doc, xpath): print("Error in getting {}: {}".format(name, e)) pass return None - + def slow_page_scroll(self, driver, speed): - current_scroll_position = driver.execute_script("return window.pageYOffset;") + current_scroll_position = driver.execute_script( + "return window.pageYOffset;") while current_scroll_position < driver.execute_script( "return document.body.scrollHeight;" ): @@ -134,20 +138,18 @@ def data_storage(self, df_list, unique_id, name, storageFormat, storagePath=None df_combined.drop_duplicates(subset=unique_id, inplace=True) if storageFormat == "csv": df_combined.to_csv( - self.storagePath +"/{}_{}.csv".format(name, self.stamp), - index=False, - ) + self.storagePath + "/{}_{}.csv".format(name, self.stamp), + index=False, + ) elif storageFormat == "json": df_combined.to_json( - self.storagePath + "/{}_{}.json".format(name, self.stamp), - orient="records", - ) - + self.storagePath + "/{}_{}.json".format(name, self.stamp), + orient="records", + ) + def cleanData(self, array): array = [x.strip() for x in array] array = list(filter(None, array)) array = [x.encode("ascii", "ignore").decode() for x in array] array = [x.replace("\n", "") for x in array] return array - - \ No newline at end of file diff --git a/FlipkartScraper/main.py b/FlipkartScraper/main.py index e18808646e..a8388cdcd5 100644 --- a/FlipkartScraper/main.py +++ b/FlipkartScraper/main.py @@ -9,14 +9,15 @@ SeleniumScraper = SeleniumScraper() + class Scraper: def __init__(self): self.brand: str = "flipkart" self.website = "https://www.flipkart.com/search?q=" self.websiteName = "https://www.flipkart.com" - self.stamp: str = datetime.now().strftime("%Y-%ma-%d_%H-%M-%S") + self.stamp: str = datetime.now().strftime("%Y-%ma-%d_%H-%M-%S") self.storagePath: str = os.getcwd() - + self.productLinksXpath = '//*[@rel="noopener noreferrer"]//@href' self.skuXpath = '//tr[contains(@class, "row")]//td[contains(text(), "Model Number")]/following-sibling::td[1]/ul/li/text()' self.nameXpath = '//*[@class="B_NuCI"]//text()' @@ -24,7 +25,7 @@ def __init__(self): self.image = '//*[@class="_396cs4 _2amPTt _3qGmMb"]//@src' self.category = '//*[@class="_3GIHBu"]//text()' self.price = '//*[@class="_30jeq3 _16Jk6d"]//text()' - + def getProductList(self, keyword): try: productLinks = [] @@ -34,8 +35,9 @@ def getProductList(self, keyword): doc = SeleniumScraper.fetch_request_selenium(url) else: doc = html.fromstring(response) - - Links = SeleniumScraper.get_xpath_link(doc, self.productLinksXpath, self.websiteName) + + Links = SeleniumScraper.get_xpath_link( + doc, self.productLinksXpath, self.websiteName) productLinks.extend(Links) for page in range(2, 20): @@ -46,13 +48,14 @@ def getProductList(self, keyword): doc = SeleniumScraper.fetch_request_selenium(url) else: doc = html.fromstring(response) - - Links = SeleniumScraper.get_xpath_link(doc, self.productLinksXpath, self.websiteName) + + Links = SeleniumScraper.get_xpath_link( + doc, self.productLinksXpath, self.websiteName) productLinks.extend(Links) print(f'Total products for {keyword} is {len(productLinks)}') return productLinks - + except Exception as e: print(e) @@ -67,13 +70,13 @@ def getProductDetails(self, productLink): productDetails = {} try: - sku = SeleniumScraper.get_xpath_data(doc ,self.skuXpath) + sku = SeleniumScraper.get_xpath_data(doc, self.skuXpath) sku = sku[0] except: sku = "None" try: - name = SeleniumScraper.get_xpath_data(doc ,self.nameXpath) + name = SeleniumScraper.get_xpath_data(doc, self.nameXpath) name = name[0] except: name = "None" @@ -85,7 +88,8 @@ def getProductDetails(self, productLink): description = "None" try: - image_path = SeleniumScraper.get_xpath_link(doc, self.image, self.websiteName) + image_path = SeleniumScraper.get_xpath_link( + doc, self.image, self.websiteName) image_path = image_path[0] except: image_path = "None" @@ -101,7 +105,7 @@ def getProductDetails(self, productLink): price = SeleniumScraper.cleanData(price) price = price[0] except: - price = "None" + price = "None" productDetails["sku"] = str(sku) productDetails["name"] = str(name) @@ -124,19 +128,19 @@ def start(self): # make db amazon.db if it doesn't exist if not os.path.exists(self.storagePath + "/" + self.brand + ".db"): - print(f'Creating {self.brand}.db at {self.storagePath+self.brand+".db"}') + print( + f'Creating {self.brand}.db at {self.storagePath+self.brand+".db"}') db = FlipkartDatabaseConnector(self.stamp) db.schemaMaker() print(db.welcomeMessage) self.db = FlipkartDatabaseConnector(self.stamp) print(self.db.welcomeMessage) - + with concurrent.futures.ThreadPoolExecutor(max_workers=number_of_threads) as executor: - productUrls = executor.map(self.getProductList, product_categories) - productList.extend(productUrls) + productUrls = executor.map(self.getProductList, product_categories) + productList.extend(productUrls) - # flatten the list productList productList = [item for sublist in productList for item in sublist] print(f'Total products for {self.brand} is {len(productList)}') @@ -149,8 +153,8 @@ def start(self): self.db.insertProduct(result) self.db.removeDuplicates() - - + + if __name__ == '__main__': scraper = Scraper() - scraper.start() \ No newline at end of file + scraper.start() diff --git a/FlipkartScraper/productList.py b/FlipkartScraper/productList.py index a9c65659a4..cbf5d91e45 100644 --- a/FlipkartScraper/productList.py +++ b/FlipkartScraper/productList.py @@ -1,3 +1,3 @@ product_categories = [ 'mobiles', -] \ No newline at end of file +] diff --git a/FlipkartScraper/useragent.py b/FlipkartScraper/useragent.py index f4a7712e1f..d3e6575bf5 100644 --- a/FlipkartScraper/useragent.py +++ b/FlipkartScraper/useragent.py @@ -19,6 +19,7 @@ "Mozilla/5.0 (Linux; Android 10; LM-Q710(FGN)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.5195.77 Mobile Safari/537.36", ] + def get_ua(): return choice(UserAgents) @@ -27,4 +28,4 @@ def get_ua(): # create a function that returns a random user agent from the list # return the user agent -# user agents are used to identify the browser, operating system, device, and/or application that is making a request to a website \ No newline at end of file +# user agents are used to identify the browser, operating system, device, and/or application that is making a request to a website diff --git a/Flipkart_webscraping/Scrap.py b/Flipkart_webscraping/Scrap.py index 7a45028df8..b313da6da2 100644 --- a/Flipkart_webscraping/Scrap.py +++ b/Flipkart_webscraping/Scrap.py @@ -2,50 +2,49 @@ import requests from bs4 import BeautifulSoup -Product_name=[] -Prices=[] -Description=[] -Reviews=[] +Product_name = [] +Prices = [] +Description = [] +Reviews = [] -for i in range(2,43): - #url="https://www.flipkart.com" - url="https://www.flipkart.com/search?q=MOBILE+PHONE+UNDER+50000&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off&page="+str(2) +for i in range(2, 43): + # url="https://www.flipkart.com" + url = "https://www.flipkart.com/search?q=MOBILE+PHONE+UNDER+50000&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off&page=" + \ + str(2) - r=requests.get(url) - soup=BeautifulSoup(r.text,"lxml") + r = requests.get(url) + soup = BeautifulSoup(r.text, "lxml") - box=soup.find("div",class_="_1YokD2 _3Mn1Gg") - names=box.find_all("div",class_="_4rR01T") + box = soup.find("div", class_="_1YokD2 _3Mn1Gg") + names = box.find_all("div", class_="_4rR01T") - #scraping data 1.product name + # scraping data 1.product name for i in names: - name=i.text + name = i.text Product_name.append(name) - - #2.prices - prices=box.find_all("div",class_="_30jeq3 _1_WHN1") + + # 2.prices + prices = box.find_all("div", class_="_30jeq3 _1_WHN1") for i in prices: - name=i.text + name = i.text Prices.append(name) - - #3.description - desc=box.find_all("ul",class_="_1xgFaf") + + # 3.description + desc = box.find_all("ul", class_="_1xgFaf") for i in desc: - name=i.text + name = i.text Description.append(name) - #4.reviews - revi=box.find_all("div",class_="_3LWZlK") + # 4.reviews + revi = box.find_all("div", class_="_3LWZlK") for i in revi: - name=i.text + name = i.text Reviews.append(name) - - #data frame - df=pd.DataFrame({"Product Name":Product_name,"Prices":Prices,"Description":Description,"Reviews":Reviews}) - #print(df) -#DF TO CSV -df.to_csv("filpkart-Scraping-under-50k.csv") - - + # data frame + df = pd.DataFrame({"Product Name": Product_name, "Prices": Prices, + "Description": Description, "Reviews": Reviews}) + # print(df) +# DF TO CSV +df.to_csv("filpkart-Scraping-under-50k.csv") diff --git a/Folder-To-HTML/make_data.py b/Folder-To-HTML/make_data.py index ed136b6b04..927128885f 100644 --- a/Folder-To-HTML/make_data.py +++ b/Folder-To-HTML/make_data.py @@ -5,6 +5,7 @@ html_file = 'data_view.html' data_dir_path = os.path.dirname(os.path.abspath(__file__)) + class DataView(): def __init__(self, data_folder, html_file): @@ -19,7 +20,7 @@ def __init__(self, data_folder, html_file): 'other': [] } - self.allowed_data_types = ['.mp4','.mp3','.pdf'] + self.allowed_data_types = ['.mp4', '.mp3', '.pdf'] self.data_types = { '.mp4': """